models.py 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650
  1. from collections import OrderedDict
  2. from itertools import count, groupby
  3. from django.conf import settings
  4. from django.contrib.auth.models import User
  5. from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
  6. from django.contrib.contenttypes.models import ContentType
  7. from django.contrib.postgres.fields import ArrayField, JSONField
  8. from django.core.exceptions import ObjectDoesNotExist, ValidationError
  9. from django.core.validators import MaxValueValidator, MinValueValidator
  10. from django.db import models
  11. from django.db.models import Count, Q
  12. from django.urls import reverse
  13. from mptt.models import MPTTModel, TreeForeignKey
  14. from taggit.managers import TaggableManager
  15. from timezone_field import TimeZoneField
  16. from extras.models import ConfigContextModel, CustomFieldModel, ObjectChange
  17. from utilities.fields import ColorField, NullableCharField
  18. from utilities.managers import NaturalOrderingManager
  19. from utilities.models import ChangeLoggedModel
  20. from utilities.utils import serialize_object, to_meters
  21. from .constants import *
  22. from .exceptions import LoopDetected
  23. from .fields import ASNField, MACAddressField
  24. from .managers import DeviceComponentManager, InterfaceManager
  25. class ComponentTemplateModel(models.Model):
  26. class Meta:
  27. abstract = True
  28. def log_change(self, user, request_id, action):
  29. """
  30. Log an ObjectChange including the parent DeviceType.
  31. """
  32. ObjectChange(
  33. user=user,
  34. request_id=request_id,
  35. changed_object=self,
  36. related_object=self.device_type,
  37. action=action,
  38. object_data=serialize_object(self)
  39. ).save()
  40. class ComponentModel(models.Model):
  41. class Meta:
  42. abstract = True
  43. def log_change(self, user, request_id, action):
  44. """
  45. Log an ObjectChange including the parent Device/VM.
  46. """
  47. parent = self.device if self.device is not None else getattr(self, 'virtual_machine', None)
  48. ObjectChange(
  49. user=user,
  50. request_id=request_id,
  51. changed_object=self,
  52. related_object=parent,
  53. action=action,
  54. object_data=serialize_object(self)
  55. ).save()
  56. class CableTermination(models.Model):
  57. cable = models.ForeignKey(
  58. to='dcim.Cable',
  59. on_delete=models.SET_NULL,
  60. related_name='+',
  61. blank=True,
  62. null=True
  63. )
  64. # Generic relations to Cable. These ensure that an attached Cable is deleted if the terminated object is deleted.
  65. _cabled_as_a = GenericRelation(
  66. to='dcim.Cable',
  67. content_type_field='termination_a_type',
  68. object_id_field='termination_a_id'
  69. )
  70. _cabled_as_b = GenericRelation(
  71. to='dcim.Cable',
  72. content_type_field='termination_b_type',
  73. object_id_field='termination_b_id'
  74. )
  75. class Meta:
  76. abstract = True
  77. def trace(self, position=1, follow_circuits=False, cable_history=None):
  78. """
  79. Return a list representing a complete cable path, with each individual segment represented as a three-tuple:
  80. [
  81. (termination A, cable, termination B),
  82. (termination C, cable, termination D),
  83. (termination E, cable, termination F)
  84. ]
  85. """
  86. def get_peer_port(termination, position=1, follow_circuits=False):
  87. from circuits.models import CircuitTermination
  88. # Map a front port to its corresponding rear port
  89. if isinstance(termination, FrontPort):
  90. return termination.rear_port, termination.rear_port_position
  91. # Map a rear port/position to its corresponding front port
  92. elif isinstance(termination, RearPort):
  93. if position not in range(1, termination.positions + 1):
  94. raise Exception("Invalid position for {} ({} positions): {})".format(
  95. termination, termination.positions, position
  96. ))
  97. try:
  98. peer_port = FrontPort.objects.get(
  99. rear_port=termination,
  100. rear_port_position=position,
  101. )
  102. return peer_port, 1
  103. except ObjectDoesNotExist:
  104. return None, None
  105. # Follow a circuit to its other termination
  106. elif isinstance(termination, CircuitTermination) and follow_circuits:
  107. peer_termination = termination.get_peer_termination()
  108. if peer_termination is None:
  109. return None, None
  110. return peer_termination, position
  111. # Termination is not a pass-through port
  112. else:
  113. return None, None
  114. if not self.cable:
  115. return [(self, None, None)]
  116. # Record cable history to detect loops
  117. if cable_history is None:
  118. cable_history = []
  119. elif self.cable in cable_history:
  120. raise LoopDetected()
  121. cable_history.append(self.cable)
  122. far_end = self.cable.termination_b if self.cable.termination_a == self else self.cable.termination_a
  123. path = [(self, self.cable, far_end)]
  124. peer_port, position = get_peer_port(far_end, position, follow_circuits)
  125. if peer_port is None:
  126. return path
  127. try:
  128. next_segment = peer_port.trace(position, follow_circuits, cable_history)
  129. except LoopDetected:
  130. return path
  131. if next_segment is None:
  132. return path + [(peer_port, None, None)]
  133. return path + next_segment
  134. #
  135. # Regions
  136. #
  137. class Region(MPTTModel, ChangeLoggedModel):
  138. """
  139. Sites can be grouped within geographic Regions.
  140. """
  141. parent = TreeForeignKey(
  142. to='self',
  143. on_delete=models.CASCADE,
  144. related_name='children',
  145. blank=True,
  146. null=True,
  147. db_index=True
  148. )
  149. name = models.CharField(
  150. max_length=50,
  151. unique=True
  152. )
  153. slug = models.SlugField(
  154. unique=True
  155. )
  156. csv_headers = ['name', 'slug', 'parent']
  157. class MPTTMeta:
  158. order_insertion_by = ['name']
  159. def __str__(self):
  160. return self.name
  161. def get_absolute_url(self):
  162. return "{}?region={}".format(reverse('dcim:site_list'), self.slug)
  163. def to_csv(self):
  164. return (
  165. self.name,
  166. self.slug,
  167. self.parent.name if self.parent else None,
  168. )
  169. #
  170. # Sites
  171. #
  172. class Site(ChangeLoggedModel, CustomFieldModel):
  173. """
  174. A Site represents a geographic location within a network; typically a building or campus. The optional facility
  175. field can be used to include an external designation, such as a data center name (e.g. Equinix SV6).
  176. """
  177. name = models.CharField(
  178. max_length=50,
  179. unique=True
  180. )
  181. slug = models.SlugField(
  182. unique=True
  183. )
  184. status = models.PositiveSmallIntegerField(
  185. choices=SITE_STATUS_CHOICES,
  186. default=SITE_STATUS_ACTIVE
  187. )
  188. region = models.ForeignKey(
  189. to='dcim.Region',
  190. on_delete=models.SET_NULL,
  191. related_name='sites',
  192. blank=True,
  193. null=True
  194. )
  195. tenant = models.ForeignKey(
  196. to='tenancy.Tenant',
  197. on_delete=models.PROTECT,
  198. related_name='sites',
  199. blank=True,
  200. null=True
  201. )
  202. facility = models.CharField(
  203. max_length=50,
  204. blank=True
  205. )
  206. asn = ASNField(
  207. blank=True,
  208. null=True,
  209. verbose_name='ASN'
  210. )
  211. time_zone = TimeZoneField(
  212. blank=True
  213. )
  214. description = models.CharField(
  215. max_length=100,
  216. blank=True
  217. )
  218. physical_address = models.CharField(
  219. max_length=200,
  220. blank=True
  221. )
  222. shipping_address = models.CharField(
  223. max_length=200,
  224. blank=True
  225. )
  226. latitude = models.DecimalField(
  227. max_digits=8,
  228. decimal_places=6,
  229. blank=True,
  230. null=True
  231. )
  232. longitude = models.DecimalField(
  233. max_digits=9,
  234. decimal_places=6,
  235. blank=True,
  236. null=True
  237. )
  238. contact_name = models.CharField(
  239. max_length=50,
  240. blank=True
  241. )
  242. contact_phone = models.CharField(
  243. max_length=20,
  244. blank=True
  245. )
  246. contact_email = models.EmailField(
  247. blank=True,
  248. verbose_name='Contact E-mail'
  249. )
  250. comments = models.TextField(
  251. blank=True
  252. )
  253. custom_field_values = GenericRelation(
  254. to='extras.CustomFieldValue',
  255. content_type_field='obj_type',
  256. object_id_field='obj_id'
  257. )
  258. images = GenericRelation(
  259. to='extras.ImageAttachment'
  260. )
  261. objects = NaturalOrderingManager()
  262. tags = TaggableManager()
  263. csv_headers = [
  264. 'name', 'slug', 'status', 'region', 'tenant', 'facility', 'asn', 'time_zone', 'description', 'physical_address',
  265. 'shipping_address', 'latitude', 'longitude', 'contact_name', 'contact_phone', 'contact_email', 'comments',
  266. ]
  267. class Meta:
  268. ordering = ['name']
  269. def __str__(self):
  270. return self.name
  271. def get_absolute_url(self):
  272. return reverse('dcim:site', args=[self.slug])
  273. def to_csv(self):
  274. return (
  275. self.name,
  276. self.slug,
  277. self.get_status_display(),
  278. self.region.name if self.region else None,
  279. self.tenant.name if self.tenant else None,
  280. self.facility,
  281. self.asn,
  282. self.time_zone,
  283. self.description,
  284. self.physical_address,
  285. self.shipping_address,
  286. self.latitude,
  287. self.longitude,
  288. self.contact_name,
  289. self.contact_phone,
  290. self.contact_email,
  291. self.comments,
  292. )
  293. def get_status_class(self):
  294. return STATUS_CLASSES[self.status]
  295. @property
  296. def count_prefixes(self):
  297. return self.prefixes.count()
  298. @property
  299. def count_vlans(self):
  300. return self.vlans.count()
  301. @property
  302. def count_racks(self):
  303. return Rack.objects.filter(site=self).count()
  304. @property
  305. def count_devices(self):
  306. return Device.objects.filter(site=self).count()
  307. @property
  308. def count_circuits(self):
  309. from circuits.models import Circuit
  310. return Circuit.objects.filter(terminations__site=self).count()
  311. @property
  312. def count_vms(self):
  313. from virtualization.models import VirtualMachine
  314. return VirtualMachine.objects.filter(cluster__site=self).count()
  315. #
  316. # Racks
  317. #
  318. class RackGroup(ChangeLoggedModel):
  319. """
  320. Racks can be grouped as subsets within a Site. The scope of a group will depend on how Sites are defined. For
  321. example, if a Site spans a corporate campus, a RackGroup might be defined to represent each building within that
  322. campus. If a Site instead represents a single building, a RackGroup might represent a single room or floor.
  323. """
  324. name = models.CharField(
  325. max_length=50
  326. )
  327. slug = models.SlugField()
  328. site = models.ForeignKey(
  329. to='dcim.Site',
  330. on_delete=models.CASCADE,
  331. related_name='rack_groups'
  332. )
  333. csv_headers = ['site', 'name', 'slug']
  334. class Meta:
  335. ordering = ['site', 'name']
  336. unique_together = [
  337. ['site', 'name'],
  338. ['site', 'slug'],
  339. ]
  340. def __str__(self):
  341. return self.name
  342. def get_absolute_url(self):
  343. return "{}?group_id={}".format(reverse('dcim:rack_list'), self.pk)
  344. def to_csv(self):
  345. return (
  346. self.site,
  347. self.name,
  348. self.slug,
  349. )
  350. class RackRole(ChangeLoggedModel):
  351. """
  352. Racks can be organized by functional role, similar to Devices.
  353. """
  354. name = models.CharField(
  355. max_length=50,
  356. unique=True
  357. )
  358. slug = models.SlugField(
  359. unique=True
  360. )
  361. color = ColorField()
  362. csv_headers = ['name', 'slug', 'color']
  363. class Meta:
  364. ordering = ['name']
  365. def __str__(self):
  366. return self.name
  367. def get_absolute_url(self):
  368. return "{}?role={}".format(reverse('dcim:rack_list'), self.slug)
  369. def to_csv(self):
  370. return (
  371. self.name,
  372. self.slug,
  373. self.color,
  374. )
  375. class Rack(ChangeLoggedModel, CustomFieldModel):
  376. """
  377. Devices are housed within Racks. Each rack has a defined height measured in rack units, and a front and rear face.
  378. Each Rack is assigned to a Site and (optionally) a RackGroup.
  379. """
  380. name = models.CharField(
  381. max_length=50
  382. )
  383. facility_id = NullableCharField(
  384. max_length=50,
  385. blank=True,
  386. null=True,
  387. verbose_name='Facility ID'
  388. )
  389. site = models.ForeignKey(
  390. to='dcim.Site',
  391. on_delete=models.PROTECT,
  392. related_name='racks'
  393. )
  394. group = models.ForeignKey(
  395. to='dcim.RackGroup',
  396. on_delete=models.SET_NULL,
  397. related_name='racks',
  398. blank=True,
  399. null=True
  400. )
  401. tenant = models.ForeignKey(
  402. to='tenancy.Tenant',
  403. on_delete=models.PROTECT,
  404. related_name='racks',
  405. blank=True,
  406. null=True
  407. )
  408. status = models.PositiveSmallIntegerField(
  409. choices=RACK_STATUS_CHOICES,
  410. default=RACK_STATUS_ACTIVE
  411. )
  412. role = models.ForeignKey(
  413. to='dcim.RackRole',
  414. on_delete=models.PROTECT,
  415. related_name='racks',
  416. blank=True,
  417. null=True
  418. )
  419. serial = models.CharField(
  420. max_length=50,
  421. blank=True,
  422. verbose_name='Serial number'
  423. )
  424. asset_tag = NullableCharField(
  425. max_length=50,
  426. blank=True,
  427. null=True,
  428. unique=True,
  429. verbose_name='Asset tag',
  430. help_text='A unique tag used to identify this rack'
  431. )
  432. type = models.PositiveSmallIntegerField(
  433. choices=RACK_TYPE_CHOICES,
  434. blank=True,
  435. null=True,
  436. verbose_name='Type'
  437. )
  438. width = models.PositiveSmallIntegerField(
  439. choices=RACK_WIDTH_CHOICES,
  440. default=RACK_WIDTH_19IN,
  441. verbose_name='Width',
  442. help_text='Rail-to-rail width'
  443. )
  444. u_height = models.PositiveSmallIntegerField(
  445. default=42,
  446. verbose_name='Height (U)',
  447. validators=[MinValueValidator(1), MaxValueValidator(100)]
  448. )
  449. desc_units = models.BooleanField(
  450. default=False,
  451. verbose_name='Descending units',
  452. help_text='Units are numbered top-to-bottom'
  453. )
  454. outer_width = models.PositiveSmallIntegerField(
  455. blank=True,
  456. null=True
  457. )
  458. outer_depth = models.PositiveSmallIntegerField(
  459. blank=True,
  460. null=True
  461. )
  462. outer_unit = models.PositiveSmallIntegerField(
  463. choices=RACK_DIMENSION_UNIT_CHOICES,
  464. blank=True,
  465. null=True
  466. )
  467. comments = models.TextField(
  468. blank=True
  469. )
  470. custom_field_values = GenericRelation(
  471. to='extras.CustomFieldValue',
  472. content_type_field='obj_type',
  473. object_id_field='obj_id'
  474. )
  475. images = GenericRelation(
  476. to='extras.ImageAttachment'
  477. )
  478. objects = NaturalOrderingManager()
  479. tags = TaggableManager()
  480. csv_headers = [
  481. 'site', 'group_name', 'name', 'facility_id', 'tenant', 'status', 'role', 'type', 'serial', 'asset_tag', 'width',
  482. 'u_height', 'desc_units', 'outer_width', 'outer_depth', 'outer_unit', 'comments',
  483. ]
  484. class Meta:
  485. ordering = ['site', 'group', 'name']
  486. unique_together = [
  487. ['group', 'name'],
  488. ['group', 'facility_id'],
  489. ]
  490. def __str__(self):
  491. return self.display_name or super().__str__()
  492. def get_absolute_url(self):
  493. return reverse('dcim:rack', args=[self.pk])
  494. def clean(self):
  495. # Validate outer dimensions and unit
  496. if (self.outer_width is not None or self.outer_depth is not None) and self.outer_unit is None:
  497. raise ValidationError("Must specify a unit when setting an outer width/depth")
  498. elif self.outer_width is None and self.outer_depth is None:
  499. self.outer_unit = None
  500. if self.pk:
  501. # Validate that Rack is tall enough to house the installed Devices
  502. top_device = Device.objects.filter(rack=self).exclude(position__isnull=True).order_by('-position').first()
  503. if top_device:
  504. min_height = top_device.position + top_device.device_type.u_height - 1
  505. if self.u_height < min_height:
  506. raise ValidationError({
  507. 'u_height': "Rack must be at least {}U tall to house currently installed devices.".format(
  508. min_height
  509. )
  510. })
  511. # Validate that Rack was assigned a group of its same site, if applicable
  512. if self.group:
  513. if self.group.site != self.site:
  514. raise ValidationError({
  515. 'group': "Rack group must be from the same site, {}.".format(self.site)
  516. })
  517. def save(self, *args, **kwargs):
  518. # Record the original site assignment for this rack.
  519. _site_id = None
  520. if self.pk:
  521. _site_id = Rack.objects.get(pk=self.pk).site_id
  522. super().save(*args, **kwargs)
  523. # Update racked devices if the assigned Site has been changed.
  524. if _site_id is not None and self.site_id != _site_id:
  525. Device.objects.filter(rack=self).update(site_id=self.site.pk)
  526. def to_csv(self):
  527. return (
  528. self.site.name,
  529. self.group.name if self.group else None,
  530. self.name,
  531. self.facility_id,
  532. self.tenant.name if self.tenant else None,
  533. self.get_status_display(),
  534. self.role.name if self.role else None,
  535. self.get_type_display() if self.type else None,
  536. self.serial,
  537. self.asset_tag,
  538. self.width,
  539. self.u_height,
  540. self.desc_units,
  541. self.outer_width,
  542. self.outer_depth,
  543. self.outer_unit,
  544. self.comments,
  545. )
  546. @property
  547. def units(self):
  548. if self.desc_units:
  549. return range(1, self.u_height + 1)
  550. else:
  551. return reversed(range(1, self.u_height + 1))
  552. @property
  553. def display_name(self):
  554. if self.facility_id:
  555. return "{} ({})".format(self.name, self.facility_id)
  556. elif self.name:
  557. return self.name
  558. return ""
  559. def get_status_class(self):
  560. return STATUS_CLASSES[self.status]
  561. def get_rack_units(self, face=RACK_FACE_FRONT, exclude=None, remove_redundant=False):
  562. """
  563. Return a list of rack units as dictionaries. Example: {'device': None, 'face': 0, 'id': 48, 'name': 'U48'}
  564. Each key 'device' is either a Device or None. By default, multi-U devices are repeated for each U they occupy.
  565. :param face: Rack face (front or rear)
  566. :param exclude: PK of a Device to exclude (optional); helpful when relocating a Device within a Rack
  567. :param remove_redundant: If True, rack units occupied by a device already listed will be omitted
  568. """
  569. elevation = OrderedDict()
  570. for u in self.units:
  571. elevation[u] = {'id': u, 'name': 'U{}'.format(u), 'face': face, 'device': None}
  572. # Add devices to rack units list
  573. if self.pk:
  574. for device in Device.objects.select_related('device_type__manufacturer', 'device_role')\
  575. .annotate(devicebay_count=Count('device_bays'))\
  576. .exclude(pk=exclude)\
  577. .filter(rack=self, position__gt=0)\
  578. .filter(Q(face=face) | Q(device_type__is_full_depth=True)):
  579. if remove_redundant:
  580. elevation[device.position]['device'] = device
  581. for u in range(device.position + 1, device.position + device.device_type.u_height):
  582. elevation.pop(u, None)
  583. else:
  584. for u in range(device.position, device.position + device.device_type.u_height):
  585. elevation[u]['device'] = device
  586. return [u for u in elevation.values()]
  587. def get_front_elevation(self):
  588. return self.get_rack_units(face=RACK_FACE_FRONT, remove_redundant=True)
  589. def get_rear_elevation(self):
  590. return self.get_rack_units(face=RACK_FACE_REAR, remove_redundant=True)
  591. def get_available_units(self, u_height=1, rack_face=None, exclude=list()):
  592. """
  593. Return a list of units within the rack available to accommodate a device of a given U height (default 1).
  594. Optionally exclude one or more devices when calculating empty units (needed when moving a device from one
  595. position to another within a rack).
  596. :param u_height: Minimum number of contiguous free units required
  597. :param rack_face: The face of the rack (front or rear) required; 'None' if device is full depth
  598. :param exclude: List of devices IDs to exclude (useful when moving a device within a rack)
  599. """
  600. # Gather all devices which consume U space within the rack
  601. devices = self.devices.select_related('device_type').filter(position__gte=1).exclude(pk__in=exclude)
  602. # Initialize the rack unit skeleton
  603. units = list(range(1, self.u_height + 1))
  604. # Remove units consumed by installed devices
  605. for d in devices:
  606. if rack_face is None or d.face == rack_face or d.device_type.is_full_depth:
  607. for u in range(d.position, d.position + d.device_type.u_height):
  608. try:
  609. units.remove(u)
  610. except ValueError:
  611. # Found overlapping devices in the rack!
  612. pass
  613. # Remove units without enough space above them to accommodate a device of the specified height
  614. available_units = []
  615. for u in units:
  616. if set(range(u, u + u_height)).issubset(units):
  617. available_units.append(u)
  618. return list(reversed(available_units))
  619. def get_reserved_units(self):
  620. """
  621. Return a dictionary mapping all reserved units within the rack to their reservation.
  622. """
  623. reserved_units = {}
  624. for r in self.reservations.all():
  625. for u in r.units:
  626. reserved_units[u] = r
  627. return reserved_units
  628. def get_0u_devices(self):
  629. return self.devices.filter(position=0)
  630. def get_utilization(self):
  631. """
  632. Determine the utilization rate of the rack and return it as a percentage.
  633. """
  634. u_available = len(self.get_available_units())
  635. return int(float(self.u_height - u_available) / self.u_height * 100)
  636. class RackReservation(ChangeLoggedModel):
  637. """
  638. One or more reserved units within a Rack.
  639. """
  640. rack = models.ForeignKey(
  641. to='dcim.Rack',
  642. on_delete=models.CASCADE,
  643. related_name='reservations'
  644. )
  645. units = ArrayField(
  646. base_field=models.PositiveSmallIntegerField()
  647. )
  648. tenant = models.ForeignKey(
  649. to='tenancy.Tenant',
  650. on_delete=models.PROTECT,
  651. related_name='rackreservations',
  652. blank=True,
  653. null=True
  654. )
  655. user = models.ForeignKey(
  656. to=User,
  657. on_delete=models.PROTECT
  658. )
  659. description = models.CharField(
  660. max_length=100
  661. )
  662. class Meta:
  663. ordering = ['created']
  664. def __str__(self):
  665. return "Reservation for rack {}".format(self.rack)
  666. def clean(self):
  667. if self.units:
  668. # Validate that all specified units exist in the Rack.
  669. invalid_units = [u for u in self.units if u not in self.rack.units]
  670. if invalid_units:
  671. raise ValidationError({
  672. 'units': "Invalid unit(s) for {}U rack: {}".format(
  673. self.rack.u_height,
  674. ', '.join([str(u) for u in invalid_units]),
  675. ),
  676. })
  677. # Check that none of the units has already been reserved for this Rack.
  678. reserved_units = []
  679. for resv in self.rack.reservations.exclude(pk=self.pk):
  680. reserved_units += resv.units
  681. conflicting_units = [u for u in self.units if u in reserved_units]
  682. if conflicting_units:
  683. raise ValidationError({
  684. 'units': 'The following units have already been reserved: {}'.format(
  685. ', '.join([str(u) for u in conflicting_units]),
  686. )
  687. })
  688. @property
  689. def unit_list(self):
  690. """
  691. Express the assigned units as a string of summarized ranges. For example:
  692. [0, 1, 2, 10, 14, 15, 16] => "0-2, 10, 14-16"
  693. """
  694. group = (list(x) for _, x in groupby(sorted(self.units), lambda x, c=count(): next(c) - x))
  695. return ', '.join('-'.join(map(str, (g[0], g[-1])[:len(g)])) for g in group)
  696. #
  697. # Device Types
  698. #
  699. class Manufacturer(ChangeLoggedModel):
  700. """
  701. A Manufacturer represents a company which produces hardware devices; for example, Juniper or Dell.
  702. """
  703. name = models.CharField(
  704. max_length=50,
  705. unique=True
  706. )
  707. slug = models.SlugField(
  708. unique=True
  709. )
  710. csv_headers = ['name', 'slug']
  711. class Meta:
  712. ordering = ['name']
  713. def __str__(self):
  714. return self.name
  715. def get_absolute_url(self):
  716. return "{}?manufacturer={}".format(reverse('dcim:devicetype_list'), self.slug)
  717. def to_csv(self):
  718. return (
  719. self.name,
  720. self.slug,
  721. )
  722. class DeviceType(ChangeLoggedModel, CustomFieldModel):
  723. """
  724. A DeviceType represents a particular make (Manufacturer) and model of device. It specifies rack height and depth, as
  725. well as high-level functional role(s).
  726. Each DeviceType can have an arbitrary number of component templates assigned to it, which define console, power, and
  727. interface objects. For example, a Juniper EX4300-48T DeviceType would have:
  728. * 1 ConsolePortTemplate
  729. * 2 PowerPortTemplates
  730. * 48 InterfaceTemplates
  731. When a new Device of this type is created, the appropriate console, power, and interface objects (as defined by the
  732. DeviceType) are automatically created as well.
  733. """
  734. manufacturer = models.ForeignKey(
  735. to='dcim.Manufacturer',
  736. on_delete=models.PROTECT,
  737. related_name='device_types'
  738. )
  739. model = models.CharField(
  740. max_length=50
  741. )
  742. slug = models.SlugField()
  743. part_number = models.CharField(
  744. max_length=50,
  745. blank=True,
  746. help_text='Discrete part number (optional)'
  747. )
  748. u_height = models.PositiveSmallIntegerField(
  749. default=1,
  750. verbose_name='Height (U)'
  751. )
  752. is_full_depth = models.BooleanField(
  753. default=True,
  754. verbose_name='Is full depth',
  755. help_text='Device consumes both front and rear rack faces'
  756. )
  757. subdevice_role = models.NullBooleanField(
  758. default=None,
  759. verbose_name='Parent/child status',
  760. choices=SUBDEVICE_ROLE_CHOICES,
  761. help_text='Parent devices house child devices in device bays. Select '
  762. '"None" if this device type is neither a parent nor a child.'
  763. )
  764. comments = models.TextField(
  765. blank=True
  766. )
  767. custom_field_values = GenericRelation(
  768. to='extras.CustomFieldValue',
  769. content_type_field='obj_type',
  770. object_id_field='obj_id'
  771. )
  772. tags = TaggableManager()
  773. csv_headers = [
  774. 'manufacturer', 'model', 'slug', 'part_number', 'u_height', 'is_full_depth', 'subdevice_role', 'comments',
  775. ]
  776. class Meta:
  777. ordering = ['manufacturer', 'model']
  778. unique_together = [
  779. ['manufacturer', 'model'],
  780. ['manufacturer', 'slug'],
  781. ]
  782. def __str__(self):
  783. return self.model
  784. def __init__(self, *args, **kwargs):
  785. super().__init__(*args, **kwargs)
  786. # Save a copy of u_height for validation in clean()
  787. self._original_u_height = self.u_height
  788. def get_absolute_url(self):
  789. return reverse('dcim:devicetype', args=[self.pk])
  790. def to_csv(self):
  791. return (
  792. self.manufacturer.name,
  793. self.model,
  794. self.slug,
  795. self.part_number,
  796. self.u_height,
  797. self.is_full_depth,
  798. self.get_subdevice_role_display() if self.subdevice_role else None,
  799. self.comments,
  800. )
  801. def clean(self):
  802. # If editing an existing DeviceType to have a larger u_height, first validate that *all* instances of it have
  803. # room to expand within their racks. This validation will impose a very high performance penalty when there are
  804. # many instances to check, but increasing the u_height of a DeviceType should be a very rare occurrence.
  805. if self.pk is not None and self.u_height > self._original_u_height:
  806. for d in Device.objects.filter(device_type=self, position__isnull=False):
  807. face_required = None if self.is_full_depth else d.face
  808. u_available = d.rack.get_available_units(u_height=self.u_height, rack_face=face_required,
  809. exclude=[d.pk])
  810. if d.position not in u_available:
  811. raise ValidationError({
  812. 'u_height': "Device {} in rack {} does not have sufficient space to accommodate a height of "
  813. "{}U".format(d, d.rack, self.u_height)
  814. })
  815. if self.subdevice_role != SUBDEVICE_ROLE_PARENT and self.device_bay_templates.count():
  816. raise ValidationError({
  817. 'subdevice_role': "Must delete all device bay templates associated with this device before "
  818. "declassifying it as a parent device."
  819. })
  820. if self.u_height and self.subdevice_role == SUBDEVICE_ROLE_CHILD:
  821. raise ValidationError({
  822. 'u_height': "Child device types must be 0U."
  823. })
  824. @property
  825. def full_name(self):
  826. return '{} {}'.format(self.manufacturer.name, self.model)
  827. @property
  828. def is_parent_device(self):
  829. return bool(self.subdevice_role)
  830. @property
  831. def is_child_device(self):
  832. return bool(self.subdevice_role is False)
  833. class ConsolePortTemplate(ComponentTemplateModel):
  834. """
  835. A template for a ConsolePort to be created for a new Device.
  836. """
  837. device_type = models.ForeignKey(
  838. to='dcim.DeviceType',
  839. on_delete=models.CASCADE,
  840. related_name='consoleport_templates'
  841. )
  842. name = models.CharField(
  843. max_length=50
  844. )
  845. objects = DeviceComponentManager()
  846. class Meta:
  847. ordering = ['device_type', 'name']
  848. unique_together = ['device_type', 'name']
  849. def __str__(self):
  850. return self.name
  851. class ConsoleServerPortTemplate(ComponentTemplateModel):
  852. """
  853. A template for a ConsoleServerPort to be created for a new Device.
  854. """
  855. device_type = models.ForeignKey(
  856. to='dcim.DeviceType',
  857. on_delete=models.CASCADE,
  858. related_name='consoleserverport_templates'
  859. )
  860. name = models.CharField(
  861. max_length=50
  862. )
  863. objects = DeviceComponentManager()
  864. class Meta:
  865. ordering = ['device_type', 'name']
  866. unique_together = ['device_type', 'name']
  867. def __str__(self):
  868. return self.name
  869. class PowerPortTemplate(ComponentTemplateModel):
  870. """
  871. A template for a PowerPort to be created for a new Device.
  872. """
  873. device_type = models.ForeignKey(
  874. to='dcim.DeviceType',
  875. on_delete=models.CASCADE,
  876. related_name='powerport_templates'
  877. )
  878. name = models.CharField(
  879. max_length=50
  880. )
  881. objects = DeviceComponentManager()
  882. class Meta:
  883. ordering = ['device_type', 'name']
  884. unique_together = ['device_type', 'name']
  885. def __str__(self):
  886. return self.name
  887. class PowerOutletTemplate(ComponentTemplateModel):
  888. """
  889. A template for a PowerOutlet to be created for a new Device.
  890. """
  891. device_type = models.ForeignKey(
  892. to='dcim.DeviceType',
  893. on_delete=models.CASCADE,
  894. related_name='poweroutlet_templates'
  895. )
  896. name = models.CharField(
  897. max_length=50
  898. )
  899. objects = DeviceComponentManager()
  900. class Meta:
  901. ordering = ['device_type', 'name']
  902. unique_together = ['device_type', 'name']
  903. def __str__(self):
  904. return self.name
  905. class InterfaceTemplate(ComponentTemplateModel):
  906. """
  907. A template for a physical data interface on a new Device.
  908. """
  909. device_type = models.ForeignKey(
  910. to='dcim.DeviceType',
  911. on_delete=models.CASCADE,
  912. related_name='interface_templates'
  913. )
  914. name = models.CharField(
  915. max_length=64
  916. )
  917. form_factor = models.PositiveSmallIntegerField(
  918. choices=IFACE_FF_CHOICES,
  919. default=IFACE_FF_10GE_SFP_PLUS
  920. )
  921. mgmt_only = models.BooleanField(
  922. default=False,
  923. verbose_name='Management only'
  924. )
  925. objects = InterfaceManager()
  926. class Meta:
  927. ordering = ['device_type', 'name']
  928. unique_together = ['device_type', 'name']
  929. def __str__(self):
  930. return self.name
  931. class FrontPortTemplate(ComponentTemplateModel):
  932. """
  933. Template for a pass-through port on the front of a new Device.
  934. """
  935. device_type = models.ForeignKey(
  936. to='dcim.DeviceType',
  937. on_delete=models.CASCADE,
  938. related_name='frontport_templates'
  939. )
  940. name = models.CharField(
  941. max_length=64
  942. )
  943. type = models.PositiveSmallIntegerField(
  944. choices=PORT_TYPE_CHOICES
  945. )
  946. rear_port = models.ForeignKey(
  947. to='dcim.RearPortTemplate',
  948. on_delete=models.CASCADE,
  949. related_name='frontport_templates'
  950. )
  951. rear_port_position = models.PositiveSmallIntegerField(
  952. default=1,
  953. validators=[MinValueValidator(1), MaxValueValidator(64)]
  954. )
  955. objects = DeviceComponentManager()
  956. class Meta:
  957. ordering = ['device_type', 'name']
  958. unique_together = [
  959. ['device_type', 'name'],
  960. ['rear_port', 'rear_port_position'],
  961. ]
  962. def __str__(self):
  963. return self.name
  964. def clean(self):
  965. # Validate rear port assignment
  966. if self.rear_port.device_type != self.device_type:
  967. raise ValidationError(
  968. "Rear port ({}) must belong to the same device type".format(self.rear_port)
  969. )
  970. # Validate rear port position assignment
  971. if self.rear_port_position > self.rear_port.positions:
  972. raise ValidationError(
  973. "Invalid rear port position ({}); rear port {} has only {} positions".format(
  974. self.rear_port_position, self.rear_port.name, self.rear_port.positions
  975. )
  976. )
  977. class RearPortTemplate(ComponentTemplateModel):
  978. """
  979. Template for a pass-through port on the rear of a new Device.
  980. """
  981. device_type = models.ForeignKey(
  982. to='dcim.DeviceType',
  983. on_delete=models.CASCADE,
  984. related_name='rearport_templates'
  985. )
  986. name = models.CharField(
  987. max_length=64
  988. )
  989. type = models.PositiveSmallIntegerField(
  990. choices=PORT_TYPE_CHOICES
  991. )
  992. positions = models.PositiveSmallIntegerField(
  993. default=1,
  994. validators=[MinValueValidator(1), MaxValueValidator(64)]
  995. )
  996. objects = DeviceComponentManager()
  997. class Meta:
  998. ordering = ['device_type', 'name']
  999. unique_together = ['device_type', 'name']
  1000. def __str__(self):
  1001. return self.name
  1002. class DeviceBayTemplate(ComponentTemplateModel):
  1003. """
  1004. A template for a DeviceBay to be created for a new parent Device.
  1005. """
  1006. device_type = models.ForeignKey(
  1007. to='dcim.DeviceType',
  1008. on_delete=models.CASCADE,
  1009. related_name='device_bay_templates'
  1010. )
  1011. name = models.CharField(
  1012. max_length=50
  1013. )
  1014. objects = DeviceComponentManager()
  1015. class Meta:
  1016. ordering = ['device_type', 'name']
  1017. unique_together = ['device_type', 'name']
  1018. def __str__(self):
  1019. return self.name
  1020. #
  1021. # Devices
  1022. #
  1023. class DeviceRole(ChangeLoggedModel):
  1024. """
  1025. Devices are organized by functional role; for example, "Core Switch" or "File Server". Each DeviceRole is assigned a
  1026. color to be used when displaying rack elevations. The vm_role field determines whether the role is applicable to
  1027. virtual machines as well.
  1028. """
  1029. name = models.CharField(
  1030. max_length=50,
  1031. unique=True
  1032. )
  1033. slug = models.SlugField(
  1034. unique=True
  1035. )
  1036. color = ColorField()
  1037. vm_role = models.BooleanField(
  1038. default=True,
  1039. verbose_name='VM Role',
  1040. help_text='Virtual machines may be assigned to this role'
  1041. )
  1042. csv_headers = ['name', 'slug', 'color', 'vm_role']
  1043. class Meta:
  1044. ordering = ['name']
  1045. def __str__(self):
  1046. return self.name
  1047. def to_csv(self):
  1048. return (
  1049. self.name,
  1050. self.slug,
  1051. self.color,
  1052. self.vm_role,
  1053. )
  1054. class Platform(ChangeLoggedModel):
  1055. """
  1056. Platform refers to the software or firmware running on a Device. For example, "Cisco IOS-XR" or "Juniper Junos".
  1057. NetBox uses Platforms to determine how to interact with devices when pulling inventory data or other information by
  1058. specifying a NAPALM driver.
  1059. """
  1060. name = models.CharField(
  1061. max_length=50,
  1062. unique=True
  1063. )
  1064. slug = models.SlugField(
  1065. unique=True
  1066. )
  1067. manufacturer = models.ForeignKey(
  1068. to='dcim.Manufacturer',
  1069. on_delete=models.PROTECT,
  1070. related_name='platforms',
  1071. blank=True,
  1072. null=True,
  1073. help_text='Optionally limit this platform to devices of a certain manufacturer'
  1074. )
  1075. napalm_driver = models.CharField(
  1076. max_length=50,
  1077. blank=True,
  1078. verbose_name='NAPALM driver',
  1079. help_text='The name of the NAPALM driver to use when interacting with devices'
  1080. )
  1081. napalm_args = JSONField(
  1082. blank=True,
  1083. null=True,
  1084. verbose_name='NAPALM arguments',
  1085. help_text='Additional arguments to pass when initiating the NAPALM driver (JSON format)'
  1086. )
  1087. csv_headers = ['name', 'slug', 'manufacturer', 'napalm_driver', 'napalm_args']
  1088. class Meta:
  1089. ordering = ['name']
  1090. def __str__(self):
  1091. return self.name
  1092. def get_absolute_url(self):
  1093. return "{}?platform={}".format(reverse('dcim:device_list'), self.slug)
  1094. def to_csv(self):
  1095. return (
  1096. self.name,
  1097. self.slug,
  1098. self.manufacturer.name if self.manufacturer else None,
  1099. self.napalm_driver,
  1100. self.napalm_args,
  1101. )
  1102. class Device(ChangeLoggedModel, ConfigContextModel, CustomFieldModel):
  1103. """
  1104. A Device represents a piece of physical hardware mounted within a Rack. Each Device is assigned a DeviceType,
  1105. DeviceRole, and (optionally) a Platform. Device names are not required, however if one is set it must be unique.
  1106. Each Device must be assigned to a site, and optionally to a rack within that site. Associating a device with a
  1107. particular rack face or unit is optional (for example, vertically mounted PDUs do not consume rack units).
  1108. When a new Device is created, console/power/interface/device bay components are created along with it as dictated
  1109. by the component templates assigned to its DeviceType. Components can also be added, modified, or deleted after the
  1110. creation of a Device.
  1111. """
  1112. device_type = models.ForeignKey(
  1113. to='dcim.DeviceType',
  1114. on_delete=models.PROTECT,
  1115. related_name='instances'
  1116. )
  1117. device_role = models.ForeignKey(
  1118. to='dcim.DeviceRole',
  1119. on_delete=models.PROTECT,
  1120. related_name='devices'
  1121. )
  1122. tenant = models.ForeignKey(
  1123. to='tenancy.Tenant',
  1124. on_delete=models.PROTECT,
  1125. related_name='devices',
  1126. blank=True,
  1127. null=True
  1128. )
  1129. platform = models.ForeignKey(
  1130. to='dcim.Platform',
  1131. on_delete=models.SET_NULL,
  1132. related_name='devices',
  1133. blank=True,
  1134. null=True
  1135. )
  1136. name = NullableCharField(
  1137. max_length=64,
  1138. blank=True,
  1139. null=True,
  1140. unique=True
  1141. )
  1142. serial = models.CharField(
  1143. max_length=50,
  1144. blank=True,
  1145. verbose_name='Serial number'
  1146. )
  1147. asset_tag = NullableCharField(
  1148. max_length=50,
  1149. blank=True,
  1150. null=True,
  1151. unique=True,
  1152. verbose_name='Asset tag',
  1153. help_text='A unique tag used to identify this device'
  1154. )
  1155. site = models.ForeignKey(
  1156. to='dcim.Site',
  1157. on_delete=models.PROTECT,
  1158. related_name='devices'
  1159. )
  1160. rack = models.ForeignKey(
  1161. to='dcim.Rack',
  1162. on_delete=models.PROTECT,
  1163. related_name='devices',
  1164. blank=True,
  1165. null=True
  1166. )
  1167. position = models.PositiveSmallIntegerField(
  1168. blank=True,
  1169. null=True,
  1170. validators=[MinValueValidator(1)],
  1171. verbose_name='Position (U)',
  1172. help_text='The lowest-numbered unit occupied by the device'
  1173. )
  1174. face = models.PositiveSmallIntegerField(
  1175. blank=True,
  1176. null=True,
  1177. choices=RACK_FACE_CHOICES,
  1178. verbose_name='Rack face'
  1179. )
  1180. status = models.PositiveSmallIntegerField(
  1181. choices=DEVICE_STATUS_CHOICES,
  1182. default=DEVICE_STATUS_ACTIVE,
  1183. verbose_name='Status'
  1184. )
  1185. primary_ip4 = models.OneToOneField(
  1186. to='ipam.IPAddress',
  1187. on_delete=models.SET_NULL,
  1188. related_name='primary_ip4_for',
  1189. blank=True,
  1190. null=True,
  1191. verbose_name='Primary IPv4'
  1192. )
  1193. primary_ip6 = models.OneToOneField(
  1194. to='ipam.IPAddress',
  1195. on_delete=models.SET_NULL,
  1196. related_name='primary_ip6_for',
  1197. blank=True,
  1198. null=True,
  1199. verbose_name='Primary IPv6'
  1200. )
  1201. cluster = models.ForeignKey(
  1202. to='virtualization.Cluster',
  1203. on_delete=models.SET_NULL,
  1204. related_name='devices',
  1205. blank=True,
  1206. null=True
  1207. )
  1208. virtual_chassis = models.ForeignKey(
  1209. to='VirtualChassis',
  1210. on_delete=models.SET_NULL,
  1211. related_name='members',
  1212. blank=True,
  1213. null=True
  1214. )
  1215. vc_position = models.PositiveSmallIntegerField(
  1216. blank=True,
  1217. null=True,
  1218. validators=[MaxValueValidator(255)]
  1219. )
  1220. vc_priority = models.PositiveSmallIntegerField(
  1221. blank=True,
  1222. null=True,
  1223. validators=[MaxValueValidator(255)]
  1224. )
  1225. comments = models.TextField(
  1226. blank=True
  1227. )
  1228. custom_field_values = GenericRelation(
  1229. to='extras.CustomFieldValue',
  1230. content_type_field='obj_type',
  1231. object_id_field='obj_id'
  1232. )
  1233. images = GenericRelation(
  1234. to='extras.ImageAttachment'
  1235. )
  1236. objects = NaturalOrderingManager()
  1237. tags = TaggableManager()
  1238. csv_headers = [
  1239. 'name', 'device_role', 'tenant', 'manufacturer', 'model_name', 'platform', 'serial', 'asset_tag', 'status',
  1240. 'site', 'rack_group', 'rack_name', 'position', 'face', 'comments',
  1241. ]
  1242. class Meta:
  1243. ordering = ['name']
  1244. unique_together = [
  1245. ['rack', 'position', 'face'],
  1246. ['virtual_chassis', 'vc_position'],
  1247. ]
  1248. permissions = (
  1249. ('napalm_read', 'Read-only access to devices via NAPALM'),
  1250. ('napalm_write', 'Read/write access to devices via NAPALM'),
  1251. )
  1252. def __str__(self):
  1253. return self.display_name or super().__str__()
  1254. def get_absolute_url(self):
  1255. return reverse('dcim:device', args=[self.pk])
  1256. def clean(self):
  1257. # Validate site/rack combination
  1258. if self.rack and self.site != self.rack.site:
  1259. raise ValidationError({
  1260. 'rack': "Rack {} does not belong to site {}.".format(self.rack, self.site),
  1261. })
  1262. if self.rack is None:
  1263. if self.face is not None:
  1264. raise ValidationError({
  1265. 'face': "Cannot select a rack face without assigning a rack.",
  1266. })
  1267. if self.position:
  1268. raise ValidationError({
  1269. 'face': "Cannot select a rack position without assigning a rack.",
  1270. })
  1271. # Validate position/face combination
  1272. if self.position and self.face is None:
  1273. raise ValidationError({
  1274. 'face': "Must specify rack face when defining rack position.",
  1275. })
  1276. # Prevent 0U devices from being assigned to a specific position
  1277. if self.position and self.device_type.u_height == 0:
  1278. raise ValidationError({
  1279. 'position': "A U0 device type ({}) cannot be assigned to a rack position.".format(self.device_type)
  1280. })
  1281. if self.rack:
  1282. try:
  1283. # Child devices cannot be assigned to a rack face/unit
  1284. if self.device_type.is_child_device and self.face is not None:
  1285. raise ValidationError({
  1286. 'face': "Child device types cannot be assigned to a rack face. This is an attribute of the "
  1287. "parent device."
  1288. })
  1289. if self.device_type.is_child_device and self.position:
  1290. raise ValidationError({
  1291. 'position': "Child device types cannot be assigned to a rack position. This is an attribute of "
  1292. "the parent device."
  1293. })
  1294. # Validate rack space
  1295. rack_face = self.face if not self.device_type.is_full_depth else None
  1296. exclude_list = [self.pk] if self.pk else []
  1297. try:
  1298. available_units = self.rack.get_available_units(
  1299. u_height=self.device_type.u_height, rack_face=rack_face, exclude=exclude_list
  1300. )
  1301. if self.position and self.position not in available_units:
  1302. raise ValidationError({
  1303. 'position': "U{} is already occupied or does not have sufficient space to accommodate a(n) "
  1304. "{} ({}U).".format(self.position, self.device_type, self.device_type.u_height)
  1305. })
  1306. except Rack.DoesNotExist:
  1307. pass
  1308. except DeviceType.DoesNotExist:
  1309. pass
  1310. # Validate primary IP addresses
  1311. vc_interfaces = self.vc_interfaces.all()
  1312. if self.primary_ip4:
  1313. if self.primary_ip4.interface in vc_interfaces:
  1314. pass
  1315. elif self.primary_ip4.nat_inside is not None and self.primary_ip4.nat_inside.interface in vc_interfaces:
  1316. pass
  1317. else:
  1318. raise ValidationError({
  1319. 'primary_ip4': "The specified IP address ({}) is not assigned to this device.".format(
  1320. self.primary_ip4),
  1321. })
  1322. if self.primary_ip6:
  1323. if self.primary_ip6.interface in vc_interfaces:
  1324. pass
  1325. elif self.primary_ip6.nat_inside is not None and self.primary_ip6.nat_inside.interface in vc_interfaces:
  1326. pass
  1327. else:
  1328. raise ValidationError({
  1329. 'primary_ip6': "The specified IP address ({}) is not assigned to this device.".format(
  1330. self.primary_ip6),
  1331. })
  1332. # Validate manufacturer/platform
  1333. if hasattr(self, 'device_type') and self.platform:
  1334. if self.platform.manufacturer and self.platform.manufacturer != self.device_type.manufacturer:
  1335. raise ValidationError({
  1336. 'platform': "The assigned platform is limited to {} device types, but this device's type belongs "
  1337. "to {}.".format(self.platform.manufacturer, self.device_type.manufacturer)
  1338. })
  1339. # A Device can only be assigned to a Cluster in the same Site (or no Site)
  1340. if self.cluster and self.cluster.site is not None and self.cluster.site != self.site:
  1341. raise ValidationError({
  1342. 'cluster': "The assigned cluster belongs to a different site ({})".format(self.cluster.site)
  1343. })
  1344. # Validate virtual chassis assignment
  1345. if self.virtual_chassis and self.vc_position is None:
  1346. raise ValidationError({
  1347. 'vc_position': "A device assigned to a virtual chassis must have its position defined."
  1348. })
  1349. def save(self, *args, **kwargs):
  1350. is_new = not bool(self.pk)
  1351. super().save(*args, **kwargs)
  1352. # If this is a new Device, instantiate all of the related components per the DeviceType definition
  1353. if is_new:
  1354. ConsolePort.objects.bulk_create(
  1355. [ConsolePort(device=self, name=template.name) for template in
  1356. self.device_type.consoleport_templates.all()]
  1357. )
  1358. ConsoleServerPort.objects.bulk_create(
  1359. [ConsoleServerPort(device=self, name=template.name) for template in
  1360. self.device_type.consoleserverport_templates.all()]
  1361. )
  1362. PowerPort.objects.bulk_create(
  1363. [PowerPort(device=self, name=template.name) for template in
  1364. self.device_type.powerport_templates.all()]
  1365. )
  1366. PowerOutlet.objects.bulk_create(
  1367. [PowerOutlet(device=self, name=template.name) for template in
  1368. self.device_type.poweroutlet_templates.all()]
  1369. )
  1370. Interface.objects.bulk_create(
  1371. [Interface(device=self, name=template.name, form_factor=template.form_factor,
  1372. mgmt_only=template.mgmt_only) for template in self.device_type.interface_templates.all()]
  1373. )
  1374. RearPort.objects.bulk_create([
  1375. RearPort(
  1376. device=self,
  1377. name=template.name,
  1378. type=template.type,
  1379. positions=template.positions
  1380. ) for template in self.device_type.rearport_templates.all()
  1381. ])
  1382. FrontPort.objects.bulk_create([
  1383. FrontPort(
  1384. device=self,
  1385. name=template.name,
  1386. type=template.type,
  1387. rear_port=RearPort.objects.get(device=self, name=template.rear_port.name),
  1388. rear_port_position=template.rear_port_position,
  1389. ) for template in self.device_type.frontport_templates.all()
  1390. ])
  1391. DeviceBay.objects.bulk_create(
  1392. [DeviceBay(device=self, name=template.name) for template in
  1393. self.device_type.device_bay_templates.all()]
  1394. )
  1395. # Update Site and Rack assignment for any child Devices
  1396. Device.objects.filter(parent_bay__device=self).update(site=self.site, rack=self.rack)
  1397. def to_csv(self):
  1398. return (
  1399. self.name or '',
  1400. self.device_role.name,
  1401. self.tenant.name if self.tenant else None,
  1402. self.device_type.manufacturer.name,
  1403. self.device_type.model,
  1404. self.platform.name if self.platform else None,
  1405. self.serial,
  1406. self.asset_tag,
  1407. self.get_status_display(),
  1408. self.site.name,
  1409. self.rack.group.name if self.rack and self.rack.group else None,
  1410. self.rack.name if self.rack else None,
  1411. self.position,
  1412. self.get_face_display(),
  1413. self.comments,
  1414. )
  1415. @property
  1416. def display_name(self):
  1417. if self.name:
  1418. return self.name
  1419. elif self.virtual_chassis and self.virtual_chassis.master.name:
  1420. return "{}:{}".format(self.virtual_chassis.master, self.vc_position)
  1421. elif hasattr(self, 'device_type'):
  1422. return "{}".format(self.device_type)
  1423. return ""
  1424. @property
  1425. def identifier(self):
  1426. """
  1427. Return the device name if set; otherwise return the Device's primary key as {pk}
  1428. """
  1429. if self.name is not None:
  1430. return self.name
  1431. return '{{{}}}'.format(self.pk)
  1432. @property
  1433. def primary_ip(self):
  1434. if settings.PREFER_IPV4 and self.primary_ip4:
  1435. return self.primary_ip4
  1436. elif self.primary_ip6:
  1437. return self.primary_ip6
  1438. elif self.primary_ip4:
  1439. return self.primary_ip4
  1440. else:
  1441. return None
  1442. def get_vc_master(self):
  1443. """
  1444. If this Device is a VirtualChassis member, return the VC master. Otherwise, return None.
  1445. """
  1446. return self.virtual_chassis.master if self.virtual_chassis else None
  1447. @property
  1448. def vc_interfaces(self):
  1449. """
  1450. Return a QuerySet matching all Interfaces assigned to this Device or, if this Device is a VC master, to another
  1451. Device belonging to the same VirtualChassis.
  1452. """
  1453. filter = Q(device=self)
  1454. if self.virtual_chassis and self.virtual_chassis.master == self:
  1455. filter |= Q(device__virtual_chassis=self.virtual_chassis, mgmt_only=False)
  1456. return Interface.objects.filter(filter)
  1457. def get_children(self):
  1458. """
  1459. Return the set of child Devices installed in DeviceBays within this Device.
  1460. """
  1461. return Device.objects.filter(parent_bay__device=self.pk)
  1462. def get_status_class(self):
  1463. return STATUS_CLASSES[self.status]
  1464. #
  1465. # Console ports
  1466. #
  1467. class ConsolePort(CableTermination, ComponentModel):
  1468. """
  1469. A physical console port within a Device. ConsolePorts connect to ConsoleServerPorts.
  1470. """
  1471. device = models.ForeignKey(
  1472. to='dcim.Device',
  1473. on_delete=models.CASCADE,
  1474. related_name='consoleports'
  1475. )
  1476. name = models.CharField(
  1477. max_length=50
  1478. )
  1479. connected_endpoint = models.OneToOneField(
  1480. to='dcim.ConsoleServerPort',
  1481. on_delete=models.SET_NULL,
  1482. related_name='connected_endpoint',
  1483. blank=True,
  1484. null=True
  1485. )
  1486. connection_status = models.NullBooleanField(
  1487. choices=CONNECTION_STATUS_CHOICES,
  1488. blank=True
  1489. )
  1490. objects = DeviceComponentManager()
  1491. tags = TaggableManager()
  1492. csv_headers = ['device', 'name']
  1493. class Meta:
  1494. ordering = ['device', 'name']
  1495. unique_together = ['device', 'name']
  1496. def __str__(self):
  1497. return self.name
  1498. def get_absolute_url(self):
  1499. return self.device.get_absolute_url()
  1500. def to_csv(self):
  1501. return (
  1502. self.device.identifier,
  1503. self.name,
  1504. )
  1505. #
  1506. # Console server ports
  1507. #
  1508. class ConsoleServerPort(CableTermination, ComponentModel):
  1509. """
  1510. A physical port within a Device (typically a designated console server) which provides access to ConsolePorts.
  1511. """
  1512. device = models.ForeignKey(
  1513. to='dcim.Device',
  1514. on_delete=models.CASCADE,
  1515. related_name='consoleserverports'
  1516. )
  1517. name = models.CharField(
  1518. max_length=50
  1519. )
  1520. connection_status = models.NullBooleanField(
  1521. choices=CONNECTION_STATUS_CHOICES,
  1522. blank=True
  1523. )
  1524. objects = DeviceComponentManager()
  1525. tags = TaggableManager()
  1526. csv_headers = ['device', 'name']
  1527. class Meta:
  1528. unique_together = ['device', 'name']
  1529. def __str__(self):
  1530. return self.name
  1531. def get_absolute_url(self):
  1532. return self.device.get_absolute_url()
  1533. def to_csv(self):
  1534. return (
  1535. self.device.identifier,
  1536. self.name,
  1537. )
  1538. #
  1539. # Power ports
  1540. #
  1541. class PowerPort(CableTermination, ComponentModel):
  1542. """
  1543. A physical power supply (intake) port within a Device. PowerPorts connect to PowerOutlets.
  1544. """
  1545. device = models.ForeignKey(
  1546. to='dcim.Device',
  1547. on_delete=models.CASCADE,
  1548. related_name='powerports'
  1549. )
  1550. name = models.CharField(
  1551. max_length=50
  1552. )
  1553. connected_endpoint = models.OneToOneField(
  1554. to='dcim.PowerOutlet',
  1555. on_delete=models.SET_NULL,
  1556. related_name='connected_endpoint',
  1557. blank=True,
  1558. null=True
  1559. )
  1560. connection_status = models.NullBooleanField(
  1561. choices=CONNECTION_STATUS_CHOICES,
  1562. blank=True
  1563. )
  1564. objects = DeviceComponentManager()
  1565. tags = TaggableManager()
  1566. csv_headers = ['device', 'name']
  1567. class Meta:
  1568. ordering = ['device', 'name']
  1569. unique_together = ['device', 'name']
  1570. def __str__(self):
  1571. return self.name
  1572. def get_absolute_url(self):
  1573. return self.device.get_absolute_url()
  1574. def to_csv(self):
  1575. return (
  1576. self.device.identifier,
  1577. self.name,
  1578. )
  1579. #
  1580. # Power outlets
  1581. #
  1582. class PowerOutlet(CableTermination, ComponentModel):
  1583. """
  1584. A physical power outlet (output) within a Device which provides power to a PowerPort.
  1585. """
  1586. device = models.ForeignKey(
  1587. to='dcim.Device',
  1588. on_delete=models.CASCADE,
  1589. related_name='poweroutlets'
  1590. )
  1591. name = models.CharField(
  1592. max_length=50
  1593. )
  1594. connection_status = models.NullBooleanField(
  1595. choices=CONNECTION_STATUS_CHOICES,
  1596. blank=True
  1597. )
  1598. objects = DeviceComponentManager()
  1599. tags = TaggableManager()
  1600. csv_headers = ['device', 'name']
  1601. class Meta:
  1602. unique_together = ['device', 'name']
  1603. def __str__(self):
  1604. return self.name
  1605. def get_absolute_url(self):
  1606. return self.device.get_absolute_url()
  1607. def to_csv(self):
  1608. return (
  1609. self.device.identifier,
  1610. self.name,
  1611. )
  1612. #
  1613. # Interfaces
  1614. #
  1615. class Interface(CableTermination, ComponentModel):
  1616. """
  1617. A network interface within a Device or VirtualMachine. A physical Interface can connect to exactly one other
  1618. Interface.
  1619. """
  1620. device = models.ForeignKey(
  1621. to='Device',
  1622. on_delete=models.CASCADE,
  1623. related_name='interfaces',
  1624. null=True,
  1625. blank=True
  1626. )
  1627. virtual_machine = models.ForeignKey(
  1628. to='virtualization.VirtualMachine',
  1629. on_delete=models.CASCADE,
  1630. related_name='interfaces',
  1631. null=True,
  1632. blank=True
  1633. )
  1634. name = models.CharField(
  1635. max_length=64
  1636. )
  1637. _connected_interface = models.OneToOneField(
  1638. to='self',
  1639. on_delete=models.SET_NULL,
  1640. related_name='+',
  1641. blank=True,
  1642. null=True
  1643. )
  1644. _connected_circuittermination = models.OneToOneField(
  1645. to='circuits.CircuitTermination',
  1646. on_delete=models.SET_NULL,
  1647. related_name='+',
  1648. blank=True,
  1649. null=True
  1650. )
  1651. connection_status = models.NullBooleanField(
  1652. choices=CONNECTION_STATUS_CHOICES,
  1653. blank=True
  1654. )
  1655. lag = models.ForeignKey(
  1656. to='self',
  1657. on_delete=models.SET_NULL,
  1658. related_name='member_interfaces',
  1659. null=True,
  1660. blank=True,
  1661. verbose_name='Parent LAG'
  1662. )
  1663. form_factor = models.PositiveSmallIntegerField(
  1664. choices=IFACE_FF_CHOICES,
  1665. default=IFACE_FF_10GE_SFP_PLUS
  1666. )
  1667. enabled = models.BooleanField(
  1668. default=True
  1669. )
  1670. mac_address = MACAddressField(
  1671. null=True,
  1672. blank=True,
  1673. verbose_name='MAC Address'
  1674. )
  1675. mtu = models.PositiveIntegerField(
  1676. blank=True,
  1677. null=True,
  1678. validators=[MinValueValidator(1), MaxValueValidator(65536)],
  1679. verbose_name='MTU'
  1680. )
  1681. mgmt_only = models.BooleanField(
  1682. default=False,
  1683. verbose_name='OOB Management',
  1684. help_text='This interface is used only for out-of-band management'
  1685. )
  1686. description = models.CharField(
  1687. max_length=100,
  1688. blank=True
  1689. )
  1690. mode = models.PositiveSmallIntegerField(
  1691. choices=IFACE_MODE_CHOICES,
  1692. blank=True,
  1693. null=True
  1694. )
  1695. untagged_vlan = models.ForeignKey(
  1696. to='ipam.VLAN',
  1697. on_delete=models.SET_NULL,
  1698. related_name='interfaces_as_untagged',
  1699. null=True,
  1700. blank=True,
  1701. verbose_name='Untagged VLAN'
  1702. )
  1703. tagged_vlans = models.ManyToManyField(
  1704. to='ipam.VLAN',
  1705. related_name='interfaces_as_tagged',
  1706. blank=True,
  1707. verbose_name='Tagged VLANs'
  1708. )
  1709. objects = InterfaceManager()
  1710. tags = TaggableManager()
  1711. csv_headers = [
  1712. 'device', 'virtual_machine', 'name', 'lag', 'form_factor', 'enabled', 'mac_address', 'mtu', 'mgmt_only',
  1713. 'description', 'mode',
  1714. ]
  1715. class Meta:
  1716. ordering = ['device', 'name']
  1717. unique_together = ['device', 'name']
  1718. def __str__(self):
  1719. return self.name
  1720. def get_absolute_url(self):
  1721. return reverse('dcim:interface', kwargs={'pk': self.pk})
  1722. def to_csv(self):
  1723. return (
  1724. self.device.identifier if self.device else None,
  1725. self.virtual_machine.name if self.virtual_machine else None,
  1726. self.name,
  1727. self.lag.name if self.lag else None,
  1728. self.get_form_factor_display(),
  1729. self.enabled,
  1730. self.mac_address,
  1731. self.mtu,
  1732. self.mgmt_only,
  1733. self.description,
  1734. self.get_mode_display(),
  1735. )
  1736. def clean(self):
  1737. # An Interface must belong to a Device *or* to a VirtualMachine
  1738. if self.device and self.virtual_machine:
  1739. raise ValidationError("An interface cannot belong to both a device and a virtual machine.")
  1740. if not self.device and not self.virtual_machine:
  1741. raise ValidationError("An interface must belong to either a device or a virtual machine.")
  1742. # VM interfaces must be virtual
  1743. if self.virtual_machine and self.form_factor is not IFACE_FF_VIRTUAL:
  1744. raise ValidationError({
  1745. 'form_factor': "Virtual machines can only have virtual interfaces."
  1746. })
  1747. # Virtual interfaces cannot be connected
  1748. if self.form_factor in NONCONNECTABLE_IFACE_TYPES and (
  1749. self.cable or getattr(self, 'circuit_termination', False)
  1750. ):
  1751. raise ValidationError({
  1752. 'form_factor': "Virtual and wireless interfaces cannot be connected to another interface or circuit. "
  1753. "Disconnect the interface or choose a suitable form factor."
  1754. })
  1755. # An interface's LAG must belong to the same device (or VC master)
  1756. if self.lag and self.lag.device not in [self.device, self.device.get_vc_master()]:
  1757. raise ValidationError({
  1758. 'lag': "The selected LAG interface ({}) belongs to a different device ({}).".format(
  1759. self.lag.name, self.lag.device.name
  1760. )
  1761. })
  1762. # A virtual interface cannot have a parent LAG
  1763. if self.form_factor in NONCONNECTABLE_IFACE_TYPES and self.lag is not None:
  1764. raise ValidationError({
  1765. 'lag': "{} interfaces cannot have a parent LAG interface.".format(self.get_form_factor_display())
  1766. })
  1767. # Only a LAG can have LAG members
  1768. if self.form_factor != IFACE_FF_LAG and self.member_interfaces.exists():
  1769. raise ValidationError({
  1770. 'form_factor': "Cannot change interface form factor; it has LAG members ({}).".format(
  1771. ", ".join([iface.name for iface in self.member_interfaces.all()])
  1772. )
  1773. })
  1774. # Validate untagged VLAN
  1775. if self.untagged_vlan and self.untagged_vlan.site not in [self.parent.site, None]:
  1776. raise ValidationError({
  1777. 'untagged_vlan': "The untagged VLAN ({}) must belong to the same site as the interface's parent "
  1778. "device/VM, or it must be global".format(self.untagged_vlan)
  1779. })
  1780. def save(self, *args, **kwargs):
  1781. # Remove untagged VLAN assignment for non-802.1Q interfaces
  1782. if self.mode is None:
  1783. self.untagged_vlan = None
  1784. # Only "tagged" interfaces may have tagged VLANs assigned. ("tagged all" implies all VLANs are assigned.)
  1785. if self.pk and self.mode is not IFACE_MODE_TAGGED:
  1786. self.tagged_vlans.clear()
  1787. return super().save(*args, **kwargs)
  1788. def log_change(self, user, request_id, action):
  1789. """
  1790. Include the connected Interface (if any).
  1791. """
  1792. # It's possible that an Interface can be deleted _after_ its parent Device/VM, in which case trying to resolve
  1793. # the component parent will raise DoesNotExist. For more discussion, see
  1794. # https://github.com/digitalocean/netbox/issues/2323
  1795. try:
  1796. parent_obj = self.device or self.virtual_machine
  1797. except ObjectDoesNotExist:
  1798. parent_obj = None
  1799. ObjectChange(
  1800. user=user,
  1801. request_id=request_id,
  1802. changed_object=self,
  1803. related_object=parent_obj,
  1804. action=action,
  1805. object_data=serialize_object(self)
  1806. ).save()
  1807. @property
  1808. def connected_endpoint(self):
  1809. if self._connected_interface:
  1810. return self._connected_interface
  1811. return self._connected_circuittermination
  1812. @connected_endpoint.setter
  1813. def connected_endpoint(self, value):
  1814. from circuits.models import CircuitTermination
  1815. if value is None:
  1816. self._connected_interface = None
  1817. self._connected_circuittermination = None
  1818. elif isinstance(value, Interface):
  1819. self._connected_interface = value
  1820. self._connected_circuittermination = None
  1821. elif isinstance(value, CircuitTermination):
  1822. self._connected_interface = None
  1823. self._connected_circuittermination = value
  1824. else:
  1825. raise ValueError(
  1826. "Connected endpoint must be an Interface or CircuitTermination, not {}.".format(type(value))
  1827. )
  1828. @property
  1829. def parent(self):
  1830. return self.device or self.virtual_machine
  1831. @property
  1832. def is_connectable(self):
  1833. return self.form_factor not in NONCONNECTABLE_IFACE_TYPES
  1834. @property
  1835. def is_virtual(self):
  1836. return self.form_factor in VIRTUAL_IFACE_TYPES
  1837. @property
  1838. def is_wireless(self):
  1839. return self.form_factor in WIRELESS_IFACE_TYPES
  1840. @property
  1841. def is_lag(self):
  1842. return self.form_factor == IFACE_FF_LAG
  1843. @property
  1844. def count_ipaddresses(self):
  1845. return self.ip_addresses.count()
  1846. #
  1847. # Pass-through ports
  1848. #
  1849. class FrontPort(CableTermination, ComponentModel):
  1850. """
  1851. A pass-through port on the front of a Device.
  1852. """
  1853. device = models.ForeignKey(
  1854. to='dcim.Device',
  1855. on_delete=models.CASCADE,
  1856. related_name='frontports'
  1857. )
  1858. name = models.CharField(
  1859. max_length=64
  1860. )
  1861. type = models.PositiveSmallIntegerField(
  1862. choices=PORT_TYPE_CHOICES
  1863. )
  1864. rear_port = models.ForeignKey(
  1865. to='dcim.RearPort',
  1866. on_delete=models.CASCADE,
  1867. related_name='frontports'
  1868. )
  1869. rear_port_position = models.PositiveSmallIntegerField(
  1870. default=1,
  1871. validators=[MinValueValidator(1), MaxValueValidator(64)]
  1872. )
  1873. description = models.CharField(
  1874. max_length=100,
  1875. blank=True
  1876. )
  1877. objects = DeviceComponentManager()
  1878. tags = TaggableManager()
  1879. csv_headers = ['device', 'name', 'type', 'rear_port', 'rear_port_position', 'description']
  1880. class Meta:
  1881. ordering = ['device', 'name']
  1882. unique_together = [
  1883. ['device', 'name'],
  1884. ['rear_port', 'rear_port_position'],
  1885. ]
  1886. def __str__(self):
  1887. return self.name
  1888. def to_csv(self):
  1889. return (
  1890. self.device.identifier,
  1891. self.name,
  1892. self.get_type_display(),
  1893. self.rear_port.name,
  1894. self.rear_port_position,
  1895. self.description,
  1896. )
  1897. def clean(self):
  1898. # Validate rear port assignment
  1899. if self.rear_port.device != self.device:
  1900. raise ValidationError(
  1901. "Rear port ({}) must belong to the same device".format(self.rear_port)
  1902. )
  1903. # Validate rear port position assignment
  1904. if self.rear_port_position > self.rear_port.positions:
  1905. raise ValidationError(
  1906. "Invalid rear port position ({}); rear port {} has only {} positions".format(
  1907. self.rear_port_position, self.rear_port.name, self.rear_port.positions
  1908. )
  1909. )
  1910. class RearPort(CableTermination, ComponentModel):
  1911. """
  1912. A pass-through port on the rear of a Device.
  1913. """
  1914. device = models.ForeignKey(
  1915. to='dcim.Device',
  1916. on_delete=models.CASCADE,
  1917. related_name='rearports'
  1918. )
  1919. name = models.CharField(
  1920. max_length=64
  1921. )
  1922. type = models.PositiveSmallIntegerField(
  1923. choices=PORT_TYPE_CHOICES
  1924. )
  1925. positions = models.PositiveSmallIntegerField(
  1926. default=1,
  1927. validators=[MinValueValidator(1), MaxValueValidator(64)]
  1928. )
  1929. description = models.CharField(
  1930. max_length=100,
  1931. blank=True
  1932. )
  1933. objects = DeviceComponentManager()
  1934. tags = TaggableManager()
  1935. csv_headers = ['device', 'name', 'type', 'positions', 'description']
  1936. class Meta:
  1937. ordering = ['device', 'name']
  1938. unique_together = ['device', 'name']
  1939. def __str__(self):
  1940. return self.name
  1941. def to_csv(self):
  1942. return (
  1943. self.device.identifier,
  1944. self.name,
  1945. self.get_type_display(),
  1946. self.positions,
  1947. self.description,
  1948. )
  1949. #
  1950. # Device bays
  1951. #
  1952. class DeviceBay(ComponentModel):
  1953. """
  1954. An empty space within a Device which can house a child device
  1955. """
  1956. device = models.ForeignKey(
  1957. to='dcim.Device',
  1958. on_delete=models.CASCADE,
  1959. related_name='device_bays'
  1960. )
  1961. name = models.CharField(
  1962. max_length=50,
  1963. verbose_name='Name'
  1964. )
  1965. installed_device = models.OneToOneField(
  1966. to='dcim.Device',
  1967. on_delete=models.SET_NULL,
  1968. related_name='parent_bay',
  1969. blank=True,
  1970. null=True
  1971. )
  1972. objects = DeviceComponentManager()
  1973. tags = TaggableManager()
  1974. csv_headers = ['device', 'name', 'installed_device']
  1975. class Meta:
  1976. ordering = ['device', 'name']
  1977. unique_together = ['device', 'name']
  1978. def __str__(self):
  1979. return '{} - {}'.format(self.device.name, self.name)
  1980. def get_absolute_url(self):
  1981. return self.device.get_absolute_url()
  1982. def to_csv(self):
  1983. return (
  1984. self.device.identifier,
  1985. self.name,
  1986. self.installed_device.identifier if self.installed_device else None,
  1987. )
  1988. def clean(self):
  1989. # Validate that the parent Device can have DeviceBays
  1990. if not self.device.device_type.is_parent_device:
  1991. raise ValidationError("This type of device ({}) does not support device bays.".format(
  1992. self.device.device_type
  1993. ))
  1994. # Cannot install a device into itself, obviously
  1995. if self.device == self.installed_device:
  1996. raise ValidationError("Cannot install a device into itself.")
  1997. #
  1998. # Inventory items
  1999. #
  2000. class InventoryItem(ComponentModel):
  2001. """
  2002. An InventoryItem represents a serialized piece of hardware within a Device, such as a line card or power supply.
  2003. InventoryItems are used only for inventory purposes.
  2004. """
  2005. device = models.ForeignKey(
  2006. to='dcim.Device',
  2007. on_delete=models.CASCADE,
  2008. related_name='inventory_items'
  2009. )
  2010. parent = models.ForeignKey(
  2011. to='self',
  2012. on_delete=models.CASCADE,
  2013. related_name='child_items',
  2014. blank=True,
  2015. null=True
  2016. )
  2017. name = models.CharField(
  2018. max_length=50,
  2019. verbose_name='Name'
  2020. )
  2021. manufacturer = models.ForeignKey(
  2022. to='dcim.Manufacturer',
  2023. on_delete=models.PROTECT,
  2024. related_name='inventory_items',
  2025. blank=True,
  2026. null=True
  2027. )
  2028. part_id = models.CharField(
  2029. max_length=50,
  2030. verbose_name='Part ID',
  2031. blank=True
  2032. )
  2033. serial = models.CharField(
  2034. max_length=50,
  2035. verbose_name='Serial number',
  2036. blank=True
  2037. )
  2038. asset_tag = NullableCharField(
  2039. max_length=50,
  2040. unique=True,
  2041. blank=True,
  2042. null=True,
  2043. verbose_name='Asset tag',
  2044. help_text='A unique tag used to identify this item'
  2045. )
  2046. discovered = models.BooleanField(
  2047. default=False,
  2048. verbose_name='Discovered'
  2049. )
  2050. description = models.CharField(
  2051. max_length=100,
  2052. blank=True
  2053. )
  2054. tags = TaggableManager()
  2055. csv_headers = [
  2056. 'device', 'name', 'manufacturer', 'part_id', 'serial', 'asset_tag', 'discovered', 'description',
  2057. ]
  2058. class Meta:
  2059. ordering = ['device__id', 'parent__id', 'name']
  2060. unique_together = ['device', 'parent', 'name']
  2061. def __str__(self):
  2062. return self.name
  2063. def get_absolute_url(self):
  2064. return self.device.get_absolute_url()
  2065. def to_csv(self):
  2066. return (
  2067. self.device.name or '{' + self.device.pk + '}',
  2068. self.name,
  2069. self.manufacturer.name if self.manufacturer else None,
  2070. self.part_id,
  2071. self.serial,
  2072. self.asset_tag,
  2073. self.discovered,
  2074. self.description,
  2075. )
  2076. #
  2077. # Virtual chassis
  2078. #
  2079. class VirtualChassis(ChangeLoggedModel):
  2080. """
  2081. A collection of Devices which operate with a shared control plane (e.g. a switch stack).
  2082. """
  2083. master = models.OneToOneField(
  2084. to='Device',
  2085. on_delete=models.PROTECT,
  2086. related_name='vc_master_for'
  2087. )
  2088. domain = models.CharField(
  2089. max_length=30,
  2090. blank=True
  2091. )
  2092. tags = TaggableManager()
  2093. csv_headers = ['master', 'domain']
  2094. class Meta:
  2095. ordering = ['master']
  2096. verbose_name_plural = 'virtual chassis'
  2097. def __str__(self):
  2098. return str(self.master) if hasattr(self, 'master') else 'New Virtual Chassis'
  2099. def get_absolute_url(self):
  2100. return self.master.get_absolute_url()
  2101. def clean(self):
  2102. # Verify that the selected master device has been assigned to this VirtualChassis. (Skip when creating a new
  2103. # VirtualChassis.)
  2104. if self.pk and self.master not in self.members.all():
  2105. raise ValidationError({
  2106. 'master': "The selected master is not assigned to this virtual chassis."
  2107. })
  2108. def to_csv(self):
  2109. return (
  2110. self.master,
  2111. self.domain,
  2112. )
  2113. #
  2114. # Cables
  2115. #
  2116. class Cable(ChangeLoggedModel):
  2117. """
  2118. A physical connection between two endpoints.
  2119. """
  2120. termination_a_type = models.ForeignKey(
  2121. to=ContentType,
  2122. limit_choices_to={'model__in': CABLE_TERMINATION_TYPES},
  2123. on_delete=models.PROTECT,
  2124. related_name='+'
  2125. )
  2126. termination_a_id = models.PositiveIntegerField()
  2127. termination_a = GenericForeignKey(
  2128. ct_field='termination_a_type',
  2129. fk_field='termination_a_id'
  2130. )
  2131. termination_b_type = models.ForeignKey(
  2132. to=ContentType,
  2133. limit_choices_to={'model__in': CABLE_TERMINATION_TYPES},
  2134. on_delete=models.PROTECT,
  2135. related_name='+'
  2136. )
  2137. termination_b_id = models.PositiveIntegerField()
  2138. termination_b = GenericForeignKey(
  2139. ct_field='termination_b_type',
  2140. fk_field='termination_b_id'
  2141. )
  2142. type = models.PositiveSmallIntegerField(
  2143. choices=CABLE_TYPE_CHOICES,
  2144. blank=True,
  2145. null=True
  2146. )
  2147. status = models.BooleanField(
  2148. choices=CONNECTION_STATUS_CHOICES,
  2149. default=CONNECTION_STATUS_CONNECTED
  2150. )
  2151. label = models.CharField(
  2152. max_length=100,
  2153. blank=True
  2154. )
  2155. color = ColorField(
  2156. blank=True
  2157. )
  2158. length = models.PositiveSmallIntegerField(
  2159. blank=True,
  2160. null=True
  2161. )
  2162. length_unit = models.PositiveSmallIntegerField(
  2163. choices=CABLE_LENGTH_UNIT_CHOICES,
  2164. blank=True,
  2165. null=True
  2166. )
  2167. # Stores the normalized length (in meters) for database ordering
  2168. _abs_length = models.DecimalField(
  2169. max_digits=10,
  2170. decimal_places=4,
  2171. blank=True,
  2172. null=True
  2173. )
  2174. csv_headers = [
  2175. 'termination_a_type', 'termination_a_id', 'termination_b_type', 'termination_b_id', 'type', 'status', 'label',
  2176. 'color', 'length', 'length_unit',
  2177. ]
  2178. class Meta:
  2179. ordering = ['pk']
  2180. unique_together = (
  2181. ('termination_a_type', 'termination_a_id'),
  2182. ('termination_b_type', 'termination_b_id'),
  2183. )
  2184. def __init__(self, *args, **kwargs):
  2185. super().__init__(*args, **kwargs)
  2186. # Create an ID string for use by __str__(). We have to save a copy of pk since it's nullified after .delete()
  2187. # is called.
  2188. self.id_string = '#{}'.format(self.pk)
  2189. def __str__(self):
  2190. return self.label or self.id_string
  2191. def get_absolute_url(self):
  2192. return reverse('dcim:cable', args=[self.pk])
  2193. def clean(self):
  2194. # Check that termination types are compatible
  2195. type_a = self.termination_a_type.model
  2196. type_b = self.termination_b_type.model
  2197. if type_b not in COMPATIBLE_TERMINATION_TYPES.get(type_a):
  2198. raise ValidationError("Incompatible termination types: {} and {}".format(
  2199. self.termination_a_type, self.termination_b_type
  2200. ))
  2201. # A termination point cannot be connected to itself
  2202. if self.termination_a == self.termination_b:
  2203. raise ValidationError("Cannot connect {} to itself".format(self.termination_a_type))
  2204. # A front port cannot be connected to its corresponding rear port
  2205. if (
  2206. type_a in ['frontport', 'rearport'] and
  2207. type_b in ['frontport', 'rearport'] and
  2208. (
  2209. getattr(self.termination_a, 'rear_port', None) == self.termination_b or
  2210. getattr(self.termination_b, 'rear_port', None) == self.termination_a
  2211. )
  2212. ):
  2213. raise ValidationError("A front port cannot be connected to it corresponding rear port")
  2214. # Check for an existing Cable connected to either termination object
  2215. if self.termination_a.cable not in (None, self):
  2216. raise ValidationError("{} already has a cable attached (#{})".format(
  2217. self.termination_a, self.termination_a.cable_id
  2218. ))
  2219. if self.termination_b.cable not in (None, self):
  2220. raise ValidationError("{} already has a cable attached (#{})".format(
  2221. self.termination_b, self.termination_b.cable_id
  2222. ))
  2223. # Virtual interfaces cannot be connected
  2224. endpoint_a, endpoint_b, _ = self.get_path_endpoints()
  2225. if (
  2226. (
  2227. isinstance(endpoint_a, Interface) and
  2228. endpoint_a.form_factor == IFACE_FF_VIRTUAL
  2229. ) or
  2230. (
  2231. isinstance(endpoint_b, Interface) and
  2232. endpoint_b.form_factor == IFACE_FF_VIRTUAL
  2233. )
  2234. ):
  2235. raise ValidationError("Cannot connect to a virtual interface")
  2236. # Validate length and length_unit
  2237. if self.length is not None and self.length_unit is None:
  2238. raise ValidationError("Must specify a unit when setting a cable length")
  2239. elif self.length is None:
  2240. self.length_unit = None
  2241. def save(self, *args, **kwargs):
  2242. # Store the given length (if any) in meters for use in database ordering
  2243. if self.length and self.length_unit:
  2244. self._abs_length = to_meters(self.length, self.length_unit)
  2245. super().save(*args, **kwargs)
  2246. def to_csv(self):
  2247. return (
  2248. '{}.{}'.format(self.termination_a_type.app_label, self.termination_a_type.model),
  2249. self.termination_a_id,
  2250. '{}.{}'.format(self.termination_b_type.app_label, self.termination_b_type.model),
  2251. self.termination_b_id,
  2252. self.get_type_display(),
  2253. self.get_status_display(),
  2254. self.label,
  2255. self.color,
  2256. self.length,
  2257. self.length_unit,
  2258. )
  2259. def get_path_endpoints(self):
  2260. """
  2261. Traverse both ends of a cable path and return its connected endpoints. Note that one or both endpoints may be
  2262. None.
  2263. """
  2264. a_path = self.termination_b.trace()
  2265. b_path = self.termination_a.trace()
  2266. # Determine overall path status (connected or planned)
  2267. if self.status == CONNECTION_STATUS_PLANNED:
  2268. path_status = CONNECTION_STATUS_PLANNED
  2269. else:
  2270. path_status = CONNECTION_STATUS_CONNECTED
  2271. for segment in a_path[1:] + b_path[1:]:
  2272. if segment[1] is None or segment[1].status == CONNECTION_STATUS_PLANNED:
  2273. path_status = CONNECTION_STATUS_PLANNED
  2274. break
  2275. a_endpoint = a_path[-1][2]
  2276. b_endpoint = b_path[-1][2]
  2277. return a_endpoint, b_endpoint, path_status