__init__.py 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230
  1. from collections import OrderedDict
  2. from itertools import count, groupby
  3. import yaml
  4. from django.conf import settings
  5. from django.contrib.auth.models import User
  6. from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
  7. from django.contrib.contenttypes.models import ContentType
  8. from django.contrib.postgres.fields import ArrayField, JSONField
  9. from django.core.exceptions import ObjectDoesNotExist, ValidationError
  10. from django.core.validators import MaxValueValidator, MinValueValidator
  11. from django.db import models
  12. from django.db.models import Count, F, ProtectedError, Sum
  13. from django.urls import reverse
  14. from mptt.models import MPTTModel, TreeForeignKey
  15. from taggit.managers import TaggableManager
  16. from timezone_field import TimeZoneField
  17. from dcim.choices import *
  18. from dcim.constants import *
  19. from dcim.fields import ASNField
  20. from dcim.elevations import RackElevationSVG
  21. from extras.models import ConfigContextModel, CustomFieldModel, ObjectChange, TaggedItem
  22. from extras.utils import extras_features
  23. from utilities.fields import ColorField, NaturalOrderingField
  24. from utilities.models import ChangeLoggedModel
  25. from utilities.utils import serialize_object, to_meters
  26. from utilities.validators import ExclusionValidator
  27. from .device_component_templates import (
  28. ConsolePortTemplate, ConsoleServerPortTemplate, DeviceBayTemplate, FrontPortTemplate, InterfaceTemplate,
  29. PowerOutletTemplate, PowerPortTemplate, RearPortTemplate,
  30. )
  31. from .device_components import (
  32. CableTermination, ConsolePort, ConsoleServerPort, DeviceBay, FrontPort, Interface, InventoryItem, PowerOutlet,
  33. PowerPort, RearPort,
  34. )
  35. __all__ = (
  36. 'Cable',
  37. 'CableTermination',
  38. 'ConsolePort',
  39. 'ConsolePortTemplate',
  40. 'ConsoleServerPort',
  41. 'ConsoleServerPortTemplate',
  42. 'Device',
  43. 'DeviceBay',
  44. 'DeviceBayTemplate',
  45. 'DeviceRole',
  46. 'DeviceType',
  47. 'FrontPort',
  48. 'FrontPortTemplate',
  49. 'Interface',
  50. 'InterfaceTemplate',
  51. 'InventoryItem',
  52. 'Manufacturer',
  53. 'Platform',
  54. 'PowerFeed',
  55. 'PowerOutlet',
  56. 'PowerOutletTemplate',
  57. 'PowerPanel',
  58. 'PowerPort',
  59. 'PowerPortTemplate',
  60. 'Rack',
  61. 'RackGroup',
  62. 'RackReservation',
  63. 'RackRole',
  64. 'RearPort',
  65. 'RearPortTemplate',
  66. 'Region',
  67. 'Site',
  68. 'VirtualChassis',
  69. )
  70. #
  71. # Regions
  72. #
  73. @extras_features('export_templates', 'webhooks')
  74. class Region(MPTTModel, ChangeLoggedModel):
  75. """
  76. Sites can be grouped within geographic Regions.
  77. """
  78. parent = TreeForeignKey(
  79. to='self',
  80. on_delete=models.CASCADE,
  81. related_name='children',
  82. blank=True,
  83. null=True,
  84. db_index=True
  85. )
  86. name = models.CharField(
  87. max_length=50,
  88. unique=True
  89. )
  90. slug = models.SlugField(
  91. unique=True
  92. )
  93. description = models.CharField(
  94. max_length=200,
  95. blank=True
  96. )
  97. csv_headers = ['name', 'slug', 'parent', 'description']
  98. class MPTTMeta:
  99. order_insertion_by = ['name']
  100. def __str__(self):
  101. return self.name
  102. def get_absolute_url(self):
  103. return "{}?region={}".format(reverse('dcim:site_list'), self.slug)
  104. def to_csv(self):
  105. return (
  106. self.name,
  107. self.slug,
  108. self.parent.name if self.parent else None,
  109. self.description,
  110. )
  111. def get_site_count(self):
  112. return Site.objects.filter(
  113. Q(region=self) |
  114. Q(region__in=self.get_descendants())
  115. ).count()
  116. def to_objectchange(self, action):
  117. # Remove MPTT-internal fields
  118. return ObjectChange(
  119. changed_object=self,
  120. object_repr=str(self),
  121. action=action,
  122. object_data=serialize_object(self, exclude=['level', 'lft', 'rght', 'tree_id'])
  123. )
  124. #
  125. # Sites
  126. #
  127. @extras_features('custom_fields', 'custom_links', 'graphs', 'export_templates', 'webhooks')
  128. class Site(ChangeLoggedModel, CustomFieldModel):
  129. """
  130. A Site represents a geographic location within a network; typically a building or campus. The optional facility
  131. field can be used to include an external designation, such as a data center name (e.g. Equinix SV6).
  132. """
  133. name = models.CharField(
  134. max_length=50,
  135. unique=True
  136. )
  137. _name = NaturalOrderingField(
  138. target_field='name',
  139. max_length=100,
  140. blank=True
  141. )
  142. slug = models.SlugField(
  143. unique=True
  144. )
  145. status = models.CharField(
  146. max_length=50,
  147. choices=SiteStatusChoices,
  148. default=SiteStatusChoices.STATUS_ACTIVE
  149. )
  150. region = models.ForeignKey(
  151. to='dcim.Region',
  152. on_delete=models.SET_NULL,
  153. related_name='sites',
  154. blank=True,
  155. null=True
  156. )
  157. tenant = models.ForeignKey(
  158. to='tenancy.Tenant',
  159. on_delete=models.PROTECT,
  160. related_name='sites',
  161. blank=True,
  162. null=True
  163. )
  164. facility = models.CharField(
  165. max_length=50,
  166. blank=True
  167. )
  168. asn = ASNField(
  169. blank=True,
  170. null=True,
  171. verbose_name='ASN'
  172. )
  173. time_zone = TimeZoneField(
  174. blank=True
  175. )
  176. description = models.CharField(
  177. max_length=200,
  178. blank=True
  179. )
  180. physical_address = models.CharField(
  181. max_length=200,
  182. blank=True
  183. )
  184. shipping_address = models.CharField(
  185. max_length=200,
  186. blank=True
  187. )
  188. latitude = models.DecimalField(
  189. max_digits=8,
  190. decimal_places=6,
  191. blank=True,
  192. null=True
  193. )
  194. longitude = models.DecimalField(
  195. max_digits=9,
  196. decimal_places=6,
  197. blank=True,
  198. null=True
  199. )
  200. contact_name = models.CharField(
  201. max_length=50,
  202. blank=True
  203. )
  204. contact_phone = models.CharField(
  205. max_length=20,
  206. blank=True
  207. )
  208. contact_email = models.EmailField(
  209. blank=True,
  210. verbose_name='Contact E-mail'
  211. )
  212. comments = models.TextField(
  213. blank=True
  214. )
  215. custom_field_values = GenericRelation(
  216. to='extras.CustomFieldValue',
  217. content_type_field='obj_type',
  218. object_id_field='obj_id'
  219. )
  220. images = GenericRelation(
  221. to='extras.ImageAttachment'
  222. )
  223. tags = TaggableManager(through=TaggedItem)
  224. csv_headers = [
  225. 'name', 'slug', 'status', 'region', 'tenant', 'facility', 'asn', 'time_zone', 'description', 'physical_address',
  226. 'shipping_address', 'latitude', 'longitude', 'contact_name', 'contact_phone', 'contact_email', 'comments',
  227. ]
  228. clone_fields = [
  229. 'status', 'region', 'tenant', 'facility', 'asn', 'time_zone', 'description', 'physical_address',
  230. 'shipping_address', 'latitude', 'longitude', 'contact_name', 'contact_phone', 'contact_email',
  231. ]
  232. STATUS_CLASS_MAP = {
  233. SiteStatusChoices.STATUS_ACTIVE: 'success',
  234. SiteStatusChoices.STATUS_PLANNED: 'info',
  235. SiteStatusChoices.STATUS_RETIRED: 'danger',
  236. }
  237. class Meta:
  238. ordering = ('_name',)
  239. def __str__(self):
  240. return self.name
  241. def get_absolute_url(self):
  242. return reverse('dcim:site', args=[self.slug])
  243. def to_csv(self):
  244. return (
  245. self.name,
  246. self.slug,
  247. self.get_status_display(),
  248. self.region.name if self.region else None,
  249. self.tenant.name if self.tenant else None,
  250. self.facility,
  251. self.asn,
  252. self.time_zone,
  253. self.description,
  254. self.physical_address,
  255. self.shipping_address,
  256. self.latitude,
  257. self.longitude,
  258. self.contact_name,
  259. self.contact_phone,
  260. self.contact_email,
  261. self.comments,
  262. )
  263. def get_status_class(self):
  264. return self.STATUS_CLASS_MAP.get(self.status)
  265. #
  266. # Racks
  267. #
  268. @extras_features('export_templates')
  269. class RackGroup(MPTTModel, ChangeLoggedModel):
  270. """
  271. Racks can be grouped as subsets within a Site. The scope of a group will depend on how Sites are defined. For
  272. example, if a Site spans a corporate campus, a RackGroup might be defined to represent each building within that
  273. campus. If a Site instead represents a single building, a RackGroup might represent a single room or floor.
  274. """
  275. name = models.CharField(
  276. max_length=50
  277. )
  278. slug = models.SlugField()
  279. site = models.ForeignKey(
  280. to='dcim.Site',
  281. on_delete=models.CASCADE,
  282. related_name='rack_groups'
  283. )
  284. parent = TreeForeignKey(
  285. to='self',
  286. on_delete=models.CASCADE,
  287. related_name='children',
  288. blank=True,
  289. null=True,
  290. db_index=True
  291. )
  292. description = models.CharField(
  293. max_length=200,
  294. blank=True
  295. )
  296. csv_headers = ['site', 'parent', 'name', 'slug', 'description']
  297. class Meta:
  298. ordering = ['site', 'name']
  299. unique_together = [
  300. ['site', 'name'],
  301. ['site', 'slug'],
  302. ]
  303. class MPTTMeta:
  304. order_insertion_by = ['name']
  305. def __str__(self):
  306. return self.name
  307. def get_absolute_url(self):
  308. return "{}?group_id={}".format(reverse('dcim:rack_list'), self.pk)
  309. def to_csv(self):
  310. return (
  311. self.site,
  312. self.parent.name if self.parent else '',
  313. self.name,
  314. self.slug,
  315. self.description,
  316. )
  317. def to_objectchange(self, action):
  318. # Remove MPTT-internal fields
  319. return ObjectChange(
  320. changed_object=self,
  321. object_repr=str(self),
  322. action=action,
  323. object_data=serialize_object(self, exclude=['level', 'lft', 'rght', 'tree_id'])
  324. )
  325. def clean(self):
  326. # Parent RackGroup (if any) must belong to the same Site
  327. if self.parent and self.parent.site != self.site:
  328. raise ValidationError(f"Parent rack group ({self.parent}) must belong to the same site ({self.site})")
  329. class RackRole(ChangeLoggedModel):
  330. """
  331. Racks can be organized by functional role, similar to Devices.
  332. """
  333. name = models.CharField(
  334. max_length=50,
  335. unique=True
  336. )
  337. slug = models.SlugField(
  338. unique=True
  339. )
  340. color = ColorField()
  341. description = models.CharField(
  342. max_length=200,
  343. blank=True,
  344. )
  345. csv_headers = ['name', 'slug', 'color', 'description']
  346. class Meta:
  347. ordering = ['name']
  348. def __str__(self):
  349. return self.name
  350. def get_absolute_url(self):
  351. return "{}?role={}".format(reverse('dcim:rack_list'), self.slug)
  352. def to_csv(self):
  353. return (
  354. self.name,
  355. self.slug,
  356. self.color,
  357. self.description,
  358. )
  359. @extras_features('custom_fields', 'custom_links', 'export_templates', 'webhooks')
  360. class Rack(ChangeLoggedModel, CustomFieldModel):
  361. """
  362. Devices are housed within Racks. Each rack has a defined height measured in rack units, and a front and rear face.
  363. Each Rack is assigned to a Site and (optionally) a RackGroup.
  364. """
  365. name = models.CharField(
  366. max_length=50
  367. )
  368. _name = NaturalOrderingField(
  369. target_field='name',
  370. max_length=100,
  371. blank=True
  372. )
  373. facility_id = models.CharField(
  374. max_length=50,
  375. blank=True,
  376. null=True,
  377. verbose_name='Facility ID'
  378. )
  379. site = models.ForeignKey(
  380. to='dcim.Site',
  381. on_delete=models.PROTECT,
  382. related_name='racks'
  383. )
  384. group = models.ForeignKey(
  385. to='dcim.RackGroup',
  386. on_delete=models.SET_NULL,
  387. related_name='racks',
  388. blank=True,
  389. null=True
  390. )
  391. tenant = models.ForeignKey(
  392. to='tenancy.Tenant',
  393. on_delete=models.PROTECT,
  394. related_name='racks',
  395. blank=True,
  396. null=True
  397. )
  398. status = models.CharField(
  399. max_length=50,
  400. choices=RackStatusChoices,
  401. default=RackStatusChoices.STATUS_ACTIVE
  402. )
  403. role = models.ForeignKey(
  404. to='dcim.RackRole',
  405. on_delete=models.PROTECT,
  406. related_name='racks',
  407. blank=True,
  408. null=True
  409. )
  410. serial = models.CharField(
  411. max_length=50,
  412. blank=True,
  413. verbose_name='Serial number'
  414. )
  415. asset_tag = models.CharField(
  416. max_length=50,
  417. blank=True,
  418. null=True,
  419. unique=True,
  420. verbose_name='Asset tag',
  421. help_text='A unique tag used to identify this rack'
  422. )
  423. type = models.CharField(
  424. choices=RackTypeChoices,
  425. max_length=50,
  426. blank=True,
  427. verbose_name='Type'
  428. )
  429. width = models.PositiveSmallIntegerField(
  430. choices=RackWidthChoices,
  431. default=RackWidthChoices.WIDTH_19IN,
  432. verbose_name='Width',
  433. help_text='Rail-to-rail width'
  434. )
  435. u_height = models.PositiveSmallIntegerField(
  436. default=RACK_U_HEIGHT_DEFAULT,
  437. verbose_name='Height (U)',
  438. validators=[MinValueValidator(1), MaxValueValidator(100)]
  439. )
  440. desc_units = models.BooleanField(
  441. default=False,
  442. verbose_name='Descending units',
  443. help_text='Units are numbered top-to-bottom'
  444. )
  445. outer_width = models.PositiveSmallIntegerField(
  446. blank=True,
  447. null=True
  448. )
  449. outer_depth = models.PositiveSmallIntegerField(
  450. blank=True,
  451. null=True
  452. )
  453. outer_unit = models.CharField(
  454. max_length=50,
  455. choices=RackDimensionUnitChoices,
  456. blank=True,
  457. )
  458. comments = models.TextField(
  459. blank=True
  460. )
  461. custom_field_values = GenericRelation(
  462. to='extras.CustomFieldValue',
  463. content_type_field='obj_type',
  464. object_id_field='obj_id'
  465. )
  466. images = GenericRelation(
  467. to='extras.ImageAttachment'
  468. )
  469. tags = TaggableManager(through=TaggedItem)
  470. csv_headers = [
  471. 'site', 'group_name', 'name', 'facility_id', 'tenant', 'status', 'role', 'type', 'serial', 'asset_tag', 'width',
  472. 'u_height', 'desc_units', 'outer_width', 'outer_depth', 'outer_unit', 'comments',
  473. ]
  474. clone_fields = [
  475. 'site', 'group', 'tenant', 'status', 'role', 'type', 'width', 'u_height', 'desc_units', 'outer_width',
  476. 'outer_depth', 'outer_unit',
  477. ]
  478. STATUS_CLASS_MAP = {
  479. RackStatusChoices.STATUS_RESERVED: 'warning',
  480. RackStatusChoices.STATUS_AVAILABLE: 'success',
  481. RackStatusChoices.STATUS_PLANNED: 'info',
  482. RackStatusChoices.STATUS_ACTIVE: 'primary',
  483. RackStatusChoices.STATUS_DEPRECATED: 'danger',
  484. }
  485. class Meta:
  486. ordering = ('site', 'group', '_name', 'pk') # (site, group, name) may be non-unique
  487. unique_together = (
  488. # Name and facility_id must be unique *only* within a RackGroup
  489. ('group', 'name'),
  490. ('group', 'facility_id'),
  491. )
  492. def __str__(self):
  493. return self.display_name or super().__str__()
  494. def get_absolute_url(self):
  495. return reverse('dcim:rack', args=[self.pk])
  496. def clean(self):
  497. # Validate outer dimensions and unit
  498. if (self.outer_width is not None or self.outer_depth is not None) and not self.outer_unit:
  499. raise ValidationError("Must specify a unit when setting an outer width/depth")
  500. elif self.outer_width is None and self.outer_depth is None:
  501. self.outer_unit = ''
  502. if self.pk:
  503. # Validate that Rack is tall enough to house the installed Devices
  504. top_device = Device.objects.filter(rack=self).exclude(position__isnull=True).order_by('-position').first()
  505. if top_device:
  506. min_height = top_device.position + top_device.device_type.u_height - 1
  507. if self.u_height < min_height:
  508. raise ValidationError({
  509. 'u_height': "Rack must be at least {}U tall to house currently installed devices.".format(
  510. min_height
  511. )
  512. })
  513. # Validate that Rack was assigned a group of its same site, if applicable
  514. if self.group:
  515. if self.group.site != self.site:
  516. raise ValidationError({
  517. 'group': "Rack group must be from the same site, {}.".format(self.site)
  518. })
  519. def save(self, *args, **kwargs):
  520. # Record the original site assignment for this rack.
  521. _site_id = None
  522. if self.pk:
  523. _site_id = Rack.objects.get(pk=self.pk).site_id
  524. super().save(*args, **kwargs)
  525. # Update racked devices if the assigned Site has been changed.
  526. if _site_id is not None and self.site_id != _site_id:
  527. devices = Device.objects.filter(rack=self)
  528. for device in devices:
  529. device.site = self.site
  530. device.save()
  531. def to_csv(self):
  532. return (
  533. self.site.name,
  534. self.group.name if self.group else None,
  535. self.name,
  536. self.facility_id,
  537. self.tenant.name if self.tenant else None,
  538. self.get_status_display(),
  539. self.role.name if self.role else None,
  540. self.get_type_display() if self.type else None,
  541. self.serial,
  542. self.asset_tag,
  543. self.width,
  544. self.u_height,
  545. self.desc_units,
  546. self.outer_width,
  547. self.outer_depth,
  548. self.outer_unit,
  549. self.comments,
  550. )
  551. @property
  552. def units(self):
  553. if self.desc_units:
  554. return range(1, self.u_height + 1)
  555. else:
  556. return reversed(range(1, self.u_height + 1))
  557. @property
  558. def display_name(self):
  559. if self.facility_id:
  560. return "{} ({})".format(self.name, self.facility_id)
  561. elif self.name:
  562. return self.name
  563. return ""
  564. def get_status_class(self):
  565. return self.STATUS_CLASS_MAP.get(self.status)
  566. def get_rack_units(self, face=DeviceFaceChoices.FACE_FRONT, exclude=None, expand_devices=True):
  567. """
  568. Return a list of rack units as dictionaries. Example: {'device': None, 'face': 0, 'id': 48, 'name': 'U48'}
  569. Each key 'device' is either a Device or None. By default, multi-U devices are repeated for each U they occupy.
  570. :param face: Rack face (front or rear)
  571. :param exclude: PK of a Device to exclude (optional); helpful when relocating a Device within a Rack
  572. :param expand_devices: When True, all units that a device occupies will be listed with each containing a
  573. reference to the device. When False, only the bottom most unit for a device is included and that unit
  574. contains a height attribute for the device
  575. """
  576. elevation = OrderedDict()
  577. for u in self.units:
  578. elevation[u] = {'id': u, 'name': 'U{}'.format(u), 'face': face, 'device': None}
  579. # Add devices to rack units list
  580. if self.pk:
  581. queryset = Device.objects.prefetch_related(
  582. 'device_type',
  583. 'device_type__manufacturer',
  584. 'device_role'
  585. ).annotate(
  586. devicebay_count=Count('device_bays')
  587. ).exclude(
  588. pk=exclude
  589. ).filter(
  590. rack=self,
  591. position__gt=0
  592. ).filter(
  593. Q(face=face) | Q(device_type__is_full_depth=True)
  594. )
  595. for device in queryset:
  596. if expand_devices:
  597. for u in range(device.position, device.position + device.device_type.u_height):
  598. elevation[u]['device'] = device
  599. else:
  600. elevation[device.position]['device'] = device
  601. elevation[device.position]['height'] = device.device_type.u_height
  602. for u in range(device.position + 1, device.position + device.device_type.u_height):
  603. elevation.pop(u, None)
  604. return [u for u in elevation.values()]
  605. def get_available_units(self, u_height=1, rack_face=None, exclude=list()):
  606. """
  607. Return a list of units within the rack available to accommodate a device of a given U height (default 1).
  608. Optionally exclude one or more devices when calculating empty units (needed when moving a device from one
  609. position to another within a rack).
  610. :param u_height: Minimum number of contiguous free units required
  611. :param rack_face: The face of the rack (front or rear) required; 'None' if device is full depth
  612. :param exclude: List of devices IDs to exclude (useful when moving a device within a rack)
  613. """
  614. # Gather all devices which consume U space within the rack
  615. devices = self.devices.prefetch_related('device_type').filter(position__gte=1).exclude(pk__in=exclude)
  616. # Initialize the rack unit skeleton
  617. units = list(range(1, self.u_height + 1))
  618. # Remove units consumed by installed devices
  619. for d in devices:
  620. if rack_face is None or d.face == rack_face or d.device_type.is_full_depth:
  621. for u in range(d.position, d.position + d.device_type.u_height):
  622. try:
  623. units.remove(u)
  624. except ValueError:
  625. # Found overlapping devices in the rack!
  626. pass
  627. # Remove units without enough space above them to accommodate a device of the specified height
  628. available_units = []
  629. for u in units:
  630. if set(range(u, u + u_height)).issubset(units):
  631. available_units.append(u)
  632. return list(reversed(available_units))
  633. def get_reserved_units(self):
  634. """
  635. Return a dictionary mapping all reserved units within the rack to their reservation.
  636. """
  637. reserved_units = {}
  638. for r in self.reservations.all():
  639. for u in r.units:
  640. reserved_units[u] = r
  641. return reserved_units
  642. def get_elevation_svg(
  643. self,
  644. face=DeviceFaceChoices.FACE_FRONT,
  645. unit_width=RACK_ELEVATION_UNIT_WIDTH_DEFAULT,
  646. unit_height=RACK_ELEVATION_UNIT_HEIGHT_DEFAULT,
  647. legend_width=RACK_ELEVATION_LEGEND_WIDTH_DEFAULT,
  648. include_images=True,
  649. base_url=None
  650. ):
  651. """
  652. Return an SVG of the rack elevation
  653. :param face: Enum of [front, rear] representing the desired side of the rack elevation to render
  654. :param unit_width: Width in pixels for the rendered drawing
  655. :param unit_height: Height of each rack unit for the rendered drawing. Note this is not the total
  656. height of the elevation
  657. :param legend_width: Width of the unit legend, in pixels
  658. :param include_images: Embed front/rear device images where available
  659. :param base_url: Base URL for links and images. If none, URLs will be relative.
  660. """
  661. elevation = RackElevationSVG(self, include_images=include_images, base_url=base_url)
  662. return elevation.render(face, unit_width, unit_height, legend_width)
  663. def get_0u_devices(self):
  664. return self.devices.filter(position=0)
  665. def get_utilization(self):
  666. """
  667. Determine the utilization rate of the rack and return it as a percentage. Occupied and reserved units both count
  668. as utilized.
  669. """
  670. # Determine unoccupied units
  671. available_units = self.get_available_units()
  672. # Remove reserved units
  673. for u in self.get_reserved_units():
  674. if u in available_units:
  675. available_units.remove(u)
  676. occupied_unit_count = self.u_height - len(available_units)
  677. percentage = int(float(occupied_unit_count) / self.u_height * 100)
  678. return percentage
  679. def get_power_utilization(self):
  680. """
  681. Determine the utilization rate of power in the rack and return it as a percentage.
  682. """
  683. power_stats = PowerFeed.objects.filter(
  684. rack=self
  685. ).annotate(
  686. allocated_draw_total=Sum('connected_endpoint__poweroutlets__connected_endpoint__allocated_draw'),
  687. ).values(
  688. 'allocated_draw_total',
  689. 'available_power'
  690. )
  691. if power_stats:
  692. allocated_draw_total = sum(x['allocated_draw_total'] for x in power_stats)
  693. available_power_total = sum(x['available_power'] for x in power_stats)
  694. return int(allocated_draw_total / available_power_total * 100) or 0
  695. return 0
  696. @extras_features('custom_links', 'export_templates', 'webhooks')
  697. class RackReservation(ChangeLoggedModel):
  698. """
  699. One or more reserved units within a Rack.
  700. """
  701. rack = models.ForeignKey(
  702. to='dcim.Rack',
  703. on_delete=models.CASCADE,
  704. related_name='reservations'
  705. )
  706. units = ArrayField(
  707. base_field=models.PositiveSmallIntegerField()
  708. )
  709. tenant = models.ForeignKey(
  710. to='tenancy.Tenant',
  711. on_delete=models.PROTECT,
  712. related_name='rackreservations',
  713. blank=True,
  714. null=True
  715. )
  716. user = models.ForeignKey(
  717. to=User,
  718. on_delete=models.PROTECT
  719. )
  720. description = models.CharField(
  721. max_length=200
  722. )
  723. csv_headers = ['site', 'rack_group', 'rack', 'units', 'tenant', 'user', 'description']
  724. class Meta:
  725. ordering = ['created']
  726. def __str__(self):
  727. return "Reservation for rack {}".format(self.rack)
  728. def get_absolute_url(self):
  729. return reverse('dcim:rackreservation', args=[self.pk])
  730. def clean(self):
  731. if self.units:
  732. # Validate that all specified units exist in the Rack.
  733. invalid_units = [u for u in self.units if u not in self.rack.units]
  734. if invalid_units:
  735. raise ValidationError({
  736. 'units': "Invalid unit(s) for {}U rack: {}".format(
  737. self.rack.u_height,
  738. ', '.join([str(u) for u in invalid_units]),
  739. ),
  740. })
  741. # Check that none of the units has already been reserved for this Rack.
  742. reserved_units = []
  743. for resv in self.rack.reservations.exclude(pk=self.pk):
  744. reserved_units += resv.units
  745. conflicting_units = [u for u in self.units if u in reserved_units]
  746. if conflicting_units:
  747. raise ValidationError({
  748. 'units': 'The following units have already been reserved: {}'.format(
  749. ', '.join([str(u) for u in conflicting_units]),
  750. )
  751. })
  752. def to_csv(self):
  753. return (
  754. self.rack.site.name,
  755. self.rack.group if self.rack.group else None,
  756. self.rack.name,
  757. ','.join([str(u) for u in self.units]),
  758. self.tenant.name if self.tenant else None,
  759. self.user.username,
  760. self.description
  761. )
  762. @property
  763. def unit_list(self):
  764. """
  765. Express the assigned units as a string of summarized ranges. For example:
  766. [0, 1, 2, 10, 14, 15, 16] => "0-2, 10, 14-16"
  767. """
  768. group = (list(x) for _, x in groupby(sorted(self.units), lambda x, c=count(): next(c) - x))
  769. return ', '.join('-'.join(map(str, (g[0], g[-1])[:len(g)])) for g in group)
  770. #
  771. # Device Types
  772. #
  773. @extras_features('export_templates', 'webhooks')
  774. class Manufacturer(ChangeLoggedModel):
  775. """
  776. A Manufacturer represents a company which produces hardware devices; for example, Juniper or Dell.
  777. """
  778. name = models.CharField(
  779. max_length=50,
  780. unique=True
  781. )
  782. slug = models.SlugField(
  783. unique=True
  784. )
  785. description = models.CharField(
  786. max_length=200,
  787. blank=True
  788. )
  789. csv_headers = ['name', 'slug', 'description']
  790. class Meta:
  791. ordering = ['name']
  792. def __str__(self):
  793. return self.name
  794. def get_absolute_url(self):
  795. return "{}?manufacturer={}".format(reverse('dcim:devicetype_list'), self.slug)
  796. def to_csv(self):
  797. return (
  798. self.name,
  799. self.slug,
  800. self.description
  801. )
  802. @extras_features('custom_fields', 'custom_links', 'export_templates', 'webhooks')
  803. class DeviceType(ChangeLoggedModel, CustomFieldModel):
  804. """
  805. A DeviceType represents a particular make (Manufacturer) and model of device. It specifies rack height and depth, as
  806. well as high-level functional role(s).
  807. Each DeviceType can have an arbitrary number of component templates assigned to it, which define console, power, and
  808. interface objects. For example, a Juniper EX4300-48T DeviceType would have:
  809. * 1 ConsolePortTemplate
  810. * 2 PowerPortTemplates
  811. * 48 InterfaceTemplates
  812. When a new Device of this type is created, the appropriate console, power, and interface objects (as defined by the
  813. DeviceType) are automatically created as well.
  814. """
  815. manufacturer = models.ForeignKey(
  816. to='dcim.Manufacturer',
  817. on_delete=models.PROTECT,
  818. related_name='device_types'
  819. )
  820. model = models.CharField(
  821. max_length=50
  822. )
  823. slug = models.SlugField()
  824. part_number = models.CharField(
  825. max_length=50,
  826. blank=True,
  827. help_text='Discrete part number (optional)'
  828. )
  829. u_height = models.PositiveSmallIntegerField(
  830. default=1,
  831. verbose_name='Height (U)'
  832. )
  833. is_full_depth = models.BooleanField(
  834. default=True,
  835. verbose_name='Is full depth',
  836. help_text='Device consumes both front and rear rack faces'
  837. )
  838. subdevice_role = models.CharField(
  839. max_length=50,
  840. choices=SubdeviceRoleChoices,
  841. blank=True,
  842. verbose_name='Parent/child status',
  843. help_text='Parent devices house child devices in device bays. Leave blank '
  844. 'if this device type is neither a parent nor a child.'
  845. )
  846. front_image = models.ImageField(
  847. upload_to='devicetype-images',
  848. blank=True
  849. )
  850. rear_image = models.ImageField(
  851. upload_to='devicetype-images',
  852. blank=True
  853. )
  854. comments = models.TextField(
  855. blank=True
  856. )
  857. custom_field_values = GenericRelation(
  858. to='extras.CustomFieldValue',
  859. content_type_field='obj_type',
  860. object_id_field='obj_id'
  861. )
  862. tags = TaggableManager(through=TaggedItem)
  863. clone_fields = [
  864. 'manufacturer', 'u_height', 'is_full_depth', 'subdevice_role',
  865. ]
  866. class Meta:
  867. ordering = ['manufacturer', 'model']
  868. unique_together = [
  869. ['manufacturer', 'model'],
  870. ['manufacturer', 'slug'],
  871. ]
  872. def __str__(self):
  873. return self.model
  874. def __init__(self, *args, **kwargs):
  875. super().__init__(*args, **kwargs)
  876. # Save a copy of u_height for validation in clean()
  877. self._original_u_height = self.u_height
  878. # Save references to the original front/rear images
  879. self._original_front_image = self.front_image
  880. self._original_rear_image = self.rear_image
  881. def get_absolute_url(self):
  882. return reverse('dcim:devicetype', args=[self.pk])
  883. def to_yaml(self):
  884. data = OrderedDict((
  885. ('manufacturer', self.manufacturer.name),
  886. ('model', self.model),
  887. ('slug', self.slug),
  888. ('part_number', self.part_number),
  889. ('u_height', self.u_height),
  890. ('is_full_depth', self.is_full_depth),
  891. ('subdevice_role', self.subdevice_role),
  892. ('comments', self.comments),
  893. ))
  894. # Component templates
  895. if self.consoleport_templates.exists():
  896. data['console-ports'] = [
  897. {
  898. 'name': c.name,
  899. 'type': c.type,
  900. }
  901. for c in self.consoleport_templates.all()
  902. ]
  903. if self.consoleserverport_templates.exists():
  904. data['console-server-ports'] = [
  905. {
  906. 'name': c.name,
  907. 'type': c.type,
  908. }
  909. for c in self.consoleserverport_templates.all()
  910. ]
  911. if self.powerport_templates.exists():
  912. data['power-ports'] = [
  913. {
  914. 'name': c.name,
  915. 'type': c.type,
  916. 'maximum_draw': c.maximum_draw,
  917. 'allocated_draw': c.allocated_draw,
  918. }
  919. for c in self.powerport_templates.all()
  920. ]
  921. if self.poweroutlet_templates.exists():
  922. data['power-outlets'] = [
  923. {
  924. 'name': c.name,
  925. 'type': c.type,
  926. 'power_port': c.power_port.name if c.power_port else None,
  927. 'feed_leg': c.feed_leg,
  928. }
  929. for c in self.poweroutlet_templates.all()
  930. ]
  931. if self.interface_templates.exists():
  932. data['interfaces'] = [
  933. {
  934. 'name': c.name,
  935. 'type': c.type,
  936. 'mgmt_only': c.mgmt_only,
  937. }
  938. for c in self.interface_templates.all()
  939. ]
  940. if self.frontport_templates.exists():
  941. data['front-ports'] = [
  942. {
  943. 'name': c.name,
  944. 'type': c.type,
  945. 'rear_port': c.rear_port.name,
  946. 'rear_port_position': c.rear_port_position,
  947. }
  948. for c in self.frontport_templates.all()
  949. ]
  950. if self.rearport_templates.exists():
  951. data['rear-ports'] = [
  952. {
  953. 'name': c.name,
  954. 'type': c.type,
  955. 'positions': c.positions,
  956. }
  957. for c in self.rearport_templates.all()
  958. ]
  959. if self.device_bay_templates.exists():
  960. data['device-bays'] = [
  961. {
  962. 'name': c.name,
  963. }
  964. for c in self.device_bay_templates.all()
  965. ]
  966. return yaml.dump(dict(data), sort_keys=False)
  967. def clean(self):
  968. # If editing an existing DeviceType to have a larger u_height, first validate that *all* instances of it have
  969. # room to expand within their racks. This validation will impose a very high performance penalty when there are
  970. # many instances to check, but increasing the u_height of a DeviceType should be a very rare occurrence.
  971. if self.pk is not None and self.u_height > self._original_u_height:
  972. for d in Device.objects.filter(device_type=self, position__isnull=False):
  973. face_required = None if self.is_full_depth else d.face
  974. u_available = d.rack.get_available_units(u_height=self.u_height, rack_face=face_required,
  975. exclude=[d.pk])
  976. if d.position not in u_available:
  977. raise ValidationError({
  978. 'u_height': "Device {} in rack {} does not have sufficient space to accommodate a height of "
  979. "{}U".format(d, d.rack, self.u_height)
  980. })
  981. if (
  982. self.subdevice_role != SubdeviceRoleChoices.ROLE_PARENT
  983. ) and self.device_bay_templates.count():
  984. raise ValidationError({
  985. 'subdevice_role': "Must delete all device bay templates associated with this device before "
  986. "declassifying it as a parent device."
  987. })
  988. if self.u_height and self.subdevice_role == SubdeviceRoleChoices.ROLE_CHILD:
  989. raise ValidationError({
  990. 'u_height': "Child device types must be 0U."
  991. })
  992. def save(self, *args, **kwargs):
  993. ret = super().save(*args, **kwargs)
  994. # Delete any previously uploaded image files that are no longer in use
  995. if self.front_image != self._original_front_image:
  996. self._original_front_image.delete(save=False)
  997. if self.rear_image != self._original_rear_image:
  998. self._original_rear_image.delete(save=False)
  999. return ret
  1000. def delete(self, *args, **kwargs):
  1001. super().delete(*args, **kwargs)
  1002. # Delete any uploaded image files
  1003. if self.front_image:
  1004. self.front_image.delete(save=False)
  1005. if self.rear_image:
  1006. self.rear_image.delete(save=False)
  1007. @property
  1008. def display_name(self):
  1009. return '{} {}'.format(self.manufacturer.name, self.model)
  1010. @property
  1011. def is_parent_device(self):
  1012. return self.subdevice_role == SubdeviceRoleChoices.ROLE_PARENT
  1013. @property
  1014. def is_child_device(self):
  1015. return self.subdevice_role == SubdeviceRoleChoices.ROLE_CHILD
  1016. #
  1017. # Devices
  1018. #
  1019. class DeviceRole(ChangeLoggedModel):
  1020. """
  1021. Devices are organized by functional role; for example, "Core Switch" or "File Server". Each DeviceRole is assigned a
  1022. color to be used when displaying rack elevations. The vm_role field determines whether the role is applicable to
  1023. virtual machines as well.
  1024. """
  1025. name = models.CharField(
  1026. max_length=50,
  1027. unique=True
  1028. )
  1029. slug = models.SlugField(
  1030. unique=True
  1031. )
  1032. color = ColorField()
  1033. vm_role = models.BooleanField(
  1034. default=True,
  1035. verbose_name='VM Role',
  1036. help_text='Virtual machines may be assigned to this role'
  1037. )
  1038. description = models.CharField(
  1039. max_length=200,
  1040. blank=True,
  1041. )
  1042. csv_headers = ['name', 'slug', 'color', 'vm_role', 'description']
  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. self.description,
  1054. )
  1055. class Platform(ChangeLoggedModel):
  1056. """
  1057. Platform refers to the software or firmware running on a Device. For example, "Cisco IOS-XR" or "Juniper Junos".
  1058. NetBox uses Platforms to determine how to interact with devices when pulling inventory data or other information by
  1059. specifying a NAPALM driver.
  1060. """
  1061. name = models.CharField(
  1062. max_length=100,
  1063. unique=True
  1064. )
  1065. slug = models.SlugField(
  1066. unique=True,
  1067. max_length=100
  1068. )
  1069. manufacturer = models.ForeignKey(
  1070. to='dcim.Manufacturer',
  1071. on_delete=models.PROTECT,
  1072. related_name='platforms',
  1073. blank=True,
  1074. null=True,
  1075. help_text='Optionally limit this platform to devices of a certain manufacturer'
  1076. )
  1077. napalm_driver = models.CharField(
  1078. max_length=50,
  1079. blank=True,
  1080. verbose_name='NAPALM driver',
  1081. help_text='The name of the NAPALM driver to use when interacting with devices'
  1082. )
  1083. napalm_args = JSONField(
  1084. blank=True,
  1085. null=True,
  1086. verbose_name='NAPALM arguments',
  1087. help_text='Additional arguments to pass when initiating the NAPALM driver (JSON format)'
  1088. )
  1089. description = models.CharField(
  1090. max_length=200,
  1091. blank=True
  1092. )
  1093. csv_headers = ['name', 'slug', 'manufacturer', 'napalm_driver', 'napalm_args', 'description']
  1094. class Meta:
  1095. ordering = ['name']
  1096. def __str__(self):
  1097. return self.name
  1098. def get_absolute_url(self):
  1099. return "{}?platform={}".format(reverse('dcim:device_list'), self.slug)
  1100. def to_csv(self):
  1101. return (
  1102. self.name,
  1103. self.slug,
  1104. self.manufacturer.name if self.manufacturer else None,
  1105. self.napalm_driver,
  1106. self.napalm_args,
  1107. self.description,
  1108. )
  1109. @extras_features('custom_fields', 'custom_links', 'graphs', 'export_templates', 'webhooks')
  1110. class Device(ChangeLoggedModel, ConfigContextModel, CustomFieldModel):
  1111. """
  1112. A Device represents a piece of physical hardware mounted within a Rack. Each Device is assigned a DeviceType,
  1113. DeviceRole, and (optionally) a Platform. Device names are not required, however if one is set it must be unique.
  1114. Each Device must be assigned to a site, and optionally to a rack within that site. Associating a device with a
  1115. particular rack face or unit is optional (for example, vertically mounted PDUs do not consume rack units).
  1116. When a new Device is created, console/power/interface/device bay components are created along with it as dictated
  1117. by the component templates assigned to its DeviceType. Components can also be added, modified, or deleted after the
  1118. creation of a Device.
  1119. """
  1120. device_type = models.ForeignKey(
  1121. to='dcim.DeviceType',
  1122. on_delete=models.PROTECT,
  1123. related_name='instances'
  1124. )
  1125. device_role = models.ForeignKey(
  1126. to='dcim.DeviceRole',
  1127. on_delete=models.PROTECT,
  1128. related_name='devices'
  1129. )
  1130. tenant = models.ForeignKey(
  1131. to='tenancy.Tenant',
  1132. on_delete=models.PROTECT,
  1133. related_name='devices',
  1134. blank=True,
  1135. null=True
  1136. )
  1137. platform = models.ForeignKey(
  1138. to='dcim.Platform',
  1139. on_delete=models.SET_NULL,
  1140. related_name='devices',
  1141. blank=True,
  1142. null=True
  1143. )
  1144. name = models.CharField(
  1145. max_length=64,
  1146. blank=True,
  1147. null=True
  1148. )
  1149. _name = NaturalOrderingField(
  1150. target_field='name',
  1151. max_length=100,
  1152. blank=True,
  1153. null=True
  1154. )
  1155. serial = models.CharField(
  1156. max_length=50,
  1157. blank=True,
  1158. verbose_name='Serial number'
  1159. )
  1160. asset_tag = models.CharField(
  1161. max_length=50,
  1162. blank=True,
  1163. null=True,
  1164. unique=True,
  1165. verbose_name='Asset tag',
  1166. help_text='A unique tag used to identify this device'
  1167. )
  1168. site = models.ForeignKey(
  1169. to='dcim.Site',
  1170. on_delete=models.PROTECT,
  1171. related_name='devices'
  1172. )
  1173. rack = models.ForeignKey(
  1174. to='dcim.Rack',
  1175. on_delete=models.PROTECT,
  1176. related_name='devices',
  1177. blank=True,
  1178. null=True
  1179. )
  1180. position = models.PositiveSmallIntegerField(
  1181. blank=True,
  1182. null=True,
  1183. validators=[MinValueValidator(1)],
  1184. verbose_name='Position (U)',
  1185. help_text='The lowest-numbered unit occupied by the device'
  1186. )
  1187. face = models.CharField(
  1188. max_length=50,
  1189. blank=True,
  1190. choices=DeviceFaceChoices,
  1191. verbose_name='Rack face'
  1192. )
  1193. status = models.CharField(
  1194. max_length=50,
  1195. choices=DeviceStatusChoices,
  1196. default=DeviceStatusChoices.STATUS_ACTIVE
  1197. )
  1198. primary_ip4 = models.OneToOneField(
  1199. to='ipam.IPAddress',
  1200. on_delete=models.SET_NULL,
  1201. related_name='primary_ip4_for',
  1202. blank=True,
  1203. null=True,
  1204. verbose_name='Primary IPv4'
  1205. )
  1206. primary_ip6 = models.OneToOneField(
  1207. to='ipam.IPAddress',
  1208. on_delete=models.SET_NULL,
  1209. related_name='primary_ip6_for',
  1210. blank=True,
  1211. null=True,
  1212. verbose_name='Primary IPv6'
  1213. )
  1214. cluster = models.ForeignKey(
  1215. to='virtualization.Cluster',
  1216. on_delete=models.SET_NULL,
  1217. related_name='devices',
  1218. blank=True,
  1219. null=True
  1220. )
  1221. virtual_chassis = models.ForeignKey(
  1222. to='VirtualChassis',
  1223. on_delete=models.SET_NULL,
  1224. related_name='members',
  1225. blank=True,
  1226. null=True
  1227. )
  1228. vc_position = models.PositiveSmallIntegerField(
  1229. blank=True,
  1230. null=True,
  1231. validators=[MaxValueValidator(255)]
  1232. )
  1233. vc_priority = models.PositiveSmallIntegerField(
  1234. blank=True,
  1235. null=True,
  1236. validators=[MaxValueValidator(255)]
  1237. )
  1238. comments = models.TextField(
  1239. blank=True
  1240. )
  1241. custom_field_values = GenericRelation(
  1242. to='extras.CustomFieldValue',
  1243. content_type_field='obj_type',
  1244. object_id_field='obj_id'
  1245. )
  1246. images = GenericRelation(
  1247. to='extras.ImageAttachment'
  1248. )
  1249. tags = TaggableManager(through=TaggedItem)
  1250. csv_headers = [
  1251. 'name', 'device_role', 'tenant', 'manufacturer', 'model_name', 'platform', 'serial', 'asset_tag', 'status',
  1252. 'site', 'rack_group', 'rack_name', 'position', 'face', 'comments',
  1253. ]
  1254. clone_fields = [
  1255. 'device_type', 'device_role', 'tenant', 'platform', 'site', 'rack', 'status', 'cluster',
  1256. ]
  1257. STATUS_CLASS_MAP = {
  1258. DeviceStatusChoices.STATUS_OFFLINE: 'warning',
  1259. DeviceStatusChoices.STATUS_ACTIVE: 'success',
  1260. DeviceStatusChoices.STATUS_PLANNED: 'info',
  1261. DeviceStatusChoices.STATUS_STAGED: 'primary',
  1262. DeviceStatusChoices.STATUS_FAILED: 'danger',
  1263. DeviceStatusChoices.STATUS_INVENTORY: 'default',
  1264. DeviceStatusChoices.STATUS_DECOMMISSIONING: 'warning',
  1265. }
  1266. class Meta:
  1267. ordering = ('_name', 'pk') # Name may be null
  1268. unique_together = (
  1269. ('site', 'tenant', 'name'), # See validate_unique below
  1270. ('rack', 'position', 'face'),
  1271. ('virtual_chassis', 'vc_position'),
  1272. )
  1273. permissions = (
  1274. ('napalm_read', 'Read-only access to devices via NAPALM'),
  1275. ('napalm_write', 'Read/write access to devices via NAPALM'),
  1276. )
  1277. def __str__(self):
  1278. return self.display_name or super().__str__()
  1279. def get_absolute_url(self):
  1280. return reverse('dcim:device', args=[self.pk])
  1281. def validate_unique(self, exclude=None):
  1282. # Check for a duplicate name on a device assigned to the same Site and no Tenant. This is necessary
  1283. # because Django does not consider two NULL fields to be equal, and thus will not trigger a violation
  1284. # of the uniqueness constraint without manual intervention.
  1285. if self.name and self.tenant is None:
  1286. if Device.objects.exclude(pk=self.pk).filter(name=self.name, site=self.site, tenant__isnull=True):
  1287. raise ValidationError({
  1288. 'name': 'A device with this name already exists.'
  1289. })
  1290. super().validate_unique(exclude)
  1291. def clean(self):
  1292. super().clean()
  1293. # Validate site/rack combination
  1294. if self.rack and self.site != self.rack.site:
  1295. raise ValidationError({
  1296. 'rack': "Rack {} does not belong to site {}.".format(self.rack, self.site),
  1297. })
  1298. if self.rack is None:
  1299. if self.face:
  1300. raise ValidationError({
  1301. 'face': "Cannot select a rack face without assigning a rack.",
  1302. })
  1303. if self.position:
  1304. raise ValidationError({
  1305. 'face': "Cannot select a rack position without assigning a rack.",
  1306. })
  1307. # Validate position/face combination
  1308. if self.position and not self.face:
  1309. raise ValidationError({
  1310. 'face': "Must specify rack face when defining rack position.",
  1311. })
  1312. # Prevent 0U devices from being assigned to a specific position
  1313. if self.position and self.device_type.u_height == 0:
  1314. raise ValidationError({
  1315. 'position': "A U0 device type ({}) cannot be assigned to a rack position.".format(self.device_type)
  1316. })
  1317. if self.rack:
  1318. try:
  1319. # Child devices cannot be assigned to a rack face/unit
  1320. if self.device_type.is_child_device and self.face:
  1321. raise ValidationError({
  1322. 'face': "Child device types cannot be assigned to a rack face. This is an attribute of the "
  1323. "parent device."
  1324. })
  1325. if self.device_type.is_child_device and self.position:
  1326. raise ValidationError({
  1327. 'position': "Child device types cannot be assigned to a rack position. This is an attribute of "
  1328. "the parent device."
  1329. })
  1330. # Validate rack space
  1331. rack_face = self.face if not self.device_type.is_full_depth else None
  1332. exclude_list = [self.pk] if self.pk else []
  1333. try:
  1334. available_units = self.rack.get_available_units(
  1335. u_height=self.device_type.u_height, rack_face=rack_face, exclude=exclude_list
  1336. )
  1337. if self.position and self.position not in available_units:
  1338. raise ValidationError({
  1339. 'position': "U{} is already occupied or does not have sufficient space to accommodate a(n) "
  1340. "{} ({}U).".format(self.position, self.device_type, self.device_type.u_height)
  1341. })
  1342. except Rack.DoesNotExist:
  1343. pass
  1344. except DeviceType.DoesNotExist:
  1345. pass
  1346. # Validate primary IP addresses
  1347. vc_interfaces = self.vc_interfaces.all()
  1348. if self.primary_ip4:
  1349. if self.primary_ip4.interface in vc_interfaces:
  1350. pass
  1351. elif self.primary_ip4.nat_inside is not None and self.primary_ip4.nat_inside.interface in vc_interfaces:
  1352. pass
  1353. else:
  1354. raise ValidationError({
  1355. 'primary_ip4': "The specified IP address ({}) is not assigned to this device.".format(
  1356. self.primary_ip4),
  1357. })
  1358. if self.primary_ip6:
  1359. if self.primary_ip6.interface in vc_interfaces:
  1360. pass
  1361. elif self.primary_ip6.nat_inside is not None and self.primary_ip6.nat_inside.interface in vc_interfaces:
  1362. pass
  1363. else:
  1364. raise ValidationError({
  1365. 'primary_ip6': "The specified IP address ({}) is not assigned to this device.".format(
  1366. self.primary_ip6),
  1367. })
  1368. # Validate manufacturer/platform
  1369. if hasattr(self, 'device_type') and self.platform:
  1370. if self.platform.manufacturer and self.platform.manufacturer != self.device_type.manufacturer:
  1371. raise ValidationError({
  1372. 'platform': "The assigned platform is limited to {} device types, but this device's type belongs "
  1373. "to {}.".format(self.platform.manufacturer, self.device_type.manufacturer)
  1374. })
  1375. # A Device can only be assigned to a Cluster in the same Site (or no Site)
  1376. if self.cluster and self.cluster.site is not None and self.cluster.site != self.site:
  1377. raise ValidationError({
  1378. 'cluster': "The assigned cluster belongs to a different site ({})".format(self.cluster.site)
  1379. })
  1380. # Validate virtual chassis assignment
  1381. if self.virtual_chassis and self.vc_position is None:
  1382. raise ValidationError({
  1383. 'vc_position': "A device assigned to a virtual chassis must have its position defined."
  1384. })
  1385. def save(self, *args, **kwargs):
  1386. is_new = not bool(self.pk)
  1387. super().save(*args, **kwargs)
  1388. # If this is a new Device, instantiate all of the related components per the DeviceType definition
  1389. if is_new:
  1390. ConsolePort.objects.bulk_create(
  1391. [x.instantiate(self) for x in self.device_type.consoleport_templates.all()]
  1392. )
  1393. ConsoleServerPort.objects.bulk_create(
  1394. [x.instantiate(self) for x in self.device_type.consoleserverport_templates.all()]
  1395. )
  1396. PowerPort.objects.bulk_create(
  1397. [x.instantiate(self) for x in self.device_type.powerport_templates.all()]
  1398. )
  1399. PowerOutlet.objects.bulk_create(
  1400. [x.instantiate(self) for x in self.device_type.poweroutlet_templates.all()]
  1401. )
  1402. Interface.objects.bulk_create(
  1403. [x.instantiate(self) for x in self.device_type.interface_templates.all()]
  1404. )
  1405. RearPort.objects.bulk_create(
  1406. [x.instantiate(self) for x in self.device_type.rearport_templates.all()]
  1407. )
  1408. FrontPort.objects.bulk_create(
  1409. [x.instantiate(self) for x in self.device_type.frontport_templates.all()]
  1410. )
  1411. DeviceBay.objects.bulk_create(
  1412. [x.instantiate(self) for x in self.device_type.device_bay_templates.all()]
  1413. )
  1414. # Update Site and Rack assignment for any child Devices
  1415. devices = Device.objects.filter(parent_bay__device=self)
  1416. for device in devices:
  1417. device.site = self.site
  1418. device.rack = self.rack
  1419. device.save()
  1420. def to_csv(self):
  1421. return (
  1422. self.name or '',
  1423. self.device_role.name,
  1424. self.tenant.name if self.tenant else None,
  1425. self.device_type.manufacturer.name,
  1426. self.device_type.model,
  1427. self.platform.name if self.platform else None,
  1428. self.serial,
  1429. self.asset_tag,
  1430. self.get_status_display(),
  1431. self.site.name,
  1432. self.rack.group.name if self.rack and self.rack.group else None,
  1433. self.rack.name if self.rack else None,
  1434. self.position,
  1435. self.get_face_display(),
  1436. self.comments,
  1437. )
  1438. @property
  1439. def display_name(self):
  1440. if self.name:
  1441. return self.name
  1442. elif self.virtual_chassis and self.virtual_chassis.master.name:
  1443. return "{}:{}".format(self.virtual_chassis.master, self.vc_position)
  1444. elif hasattr(self, 'device_type'):
  1445. return "{}".format(self.device_type)
  1446. return ""
  1447. @property
  1448. def identifier(self):
  1449. """
  1450. Return the device name if set; otherwise return the Device's primary key as {pk}
  1451. """
  1452. if self.name is not None:
  1453. return self.name
  1454. return '{{{}}}'.format(self.pk)
  1455. @property
  1456. def primary_ip(self):
  1457. if settings.PREFER_IPV4 and self.primary_ip4:
  1458. return self.primary_ip4
  1459. elif self.primary_ip6:
  1460. return self.primary_ip6
  1461. elif self.primary_ip4:
  1462. return self.primary_ip4
  1463. else:
  1464. return None
  1465. def get_vc_master(self):
  1466. """
  1467. If this Device is a VirtualChassis member, return the VC master. Otherwise, return None.
  1468. """
  1469. return self.virtual_chassis.master if self.virtual_chassis else None
  1470. @property
  1471. def vc_interfaces(self):
  1472. """
  1473. Return a QuerySet matching all Interfaces assigned to this Device or, if this Device is a VC master, to another
  1474. Device belonging to the same VirtualChassis.
  1475. """
  1476. filter = Q(device=self)
  1477. if self.virtual_chassis and self.virtual_chassis.master == self:
  1478. filter |= Q(device__virtual_chassis=self.virtual_chassis, mgmt_only=False)
  1479. return Interface.objects.filter(filter)
  1480. def get_cables(self, pk_list=False):
  1481. """
  1482. Return a QuerySet or PK list matching all Cables connected to a component of this Device.
  1483. """
  1484. cable_pks = []
  1485. for component_model in [
  1486. ConsolePort, ConsoleServerPort, PowerPort, PowerOutlet, Interface, FrontPort, RearPort
  1487. ]:
  1488. cable_pks += component_model.objects.filter(
  1489. device=self, cable__isnull=False
  1490. ).values_list('cable', flat=True)
  1491. if pk_list:
  1492. return cable_pks
  1493. return Cable.objects.filter(pk__in=cable_pks)
  1494. def get_children(self):
  1495. """
  1496. Return the set of child Devices installed in DeviceBays within this Device.
  1497. """
  1498. return Device.objects.filter(parent_bay__device=self.pk)
  1499. def get_status_class(self):
  1500. return self.STATUS_CLASS_MAP.get(self.status)
  1501. #
  1502. # Virtual chassis
  1503. #
  1504. @extras_features('export_templates', 'webhooks')
  1505. class VirtualChassis(ChangeLoggedModel):
  1506. """
  1507. A collection of Devices which operate with a shared control plane (e.g. a switch stack).
  1508. """
  1509. master = models.OneToOneField(
  1510. to='Device',
  1511. on_delete=models.PROTECT,
  1512. related_name='vc_master_for'
  1513. )
  1514. domain = models.CharField(
  1515. max_length=30,
  1516. blank=True
  1517. )
  1518. tags = TaggableManager(through=TaggedItem)
  1519. csv_headers = ['master', 'domain']
  1520. class Meta:
  1521. ordering = ['master']
  1522. verbose_name_plural = 'virtual chassis'
  1523. def __str__(self):
  1524. return str(self.master) if hasattr(self, 'master') else 'New Virtual Chassis'
  1525. def get_absolute_url(self):
  1526. return self.master.get_absolute_url()
  1527. def clean(self):
  1528. # Verify that the selected master device has been assigned to this VirtualChassis. (Skip when creating a new
  1529. # VirtualChassis.)
  1530. if self.pk and self.master not in self.members.all():
  1531. raise ValidationError({
  1532. 'master': "The selected master is not assigned to this virtual chassis."
  1533. })
  1534. def delete(self, *args, **kwargs):
  1535. # Check for LAG interfaces split across member chassis
  1536. interfaces = Interface.objects.filter(
  1537. device__in=self.members.all(),
  1538. lag__isnull=False
  1539. ).exclude(
  1540. lag__device=F('device')
  1541. )
  1542. if interfaces:
  1543. raise ProtectedError(
  1544. "Unable to delete virtual chassis {}. There are member interfaces which form a cross-chassis "
  1545. "LAG".format(self),
  1546. interfaces
  1547. )
  1548. return super().delete(*args, **kwargs)
  1549. def to_csv(self):
  1550. return (
  1551. self.master,
  1552. self.domain,
  1553. )
  1554. #
  1555. # Power
  1556. #
  1557. @extras_features('custom_links', 'export_templates', 'webhooks')
  1558. class PowerPanel(ChangeLoggedModel):
  1559. """
  1560. A distribution point for electrical power; e.g. a data center RPP.
  1561. """
  1562. site = models.ForeignKey(
  1563. to='Site',
  1564. on_delete=models.PROTECT
  1565. )
  1566. rack_group = models.ForeignKey(
  1567. to='RackGroup',
  1568. on_delete=models.PROTECT,
  1569. blank=True,
  1570. null=True
  1571. )
  1572. name = models.CharField(
  1573. max_length=50
  1574. )
  1575. csv_headers = ['site', 'rack_group_name', 'name']
  1576. class Meta:
  1577. ordering = ['site', 'name']
  1578. unique_together = ['site', 'name']
  1579. def __str__(self):
  1580. return self.name
  1581. def get_absolute_url(self):
  1582. return reverse('dcim:powerpanel', args=[self.pk])
  1583. def to_csv(self):
  1584. return (
  1585. self.site.name,
  1586. self.rack_group.name if self.rack_group else None,
  1587. self.name,
  1588. )
  1589. def clean(self):
  1590. # RackGroup must belong to assigned Site
  1591. if self.rack_group and self.rack_group.site != self.site:
  1592. raise ValidationError("Rack group {} ({}) is in a different site than {}".format(
  1593. self.rack_group, self.rack_group.site, self.site
  1594. ))
  1595. @extras_features('custom_fields', 'custom_links', 'export_templates', 'webhooks')
  1596. class PowerFeed(ChangeLoggedModel, CableTermination, CustomFieldModel):
  1597. """
  1598. An electrical circuit delivered from a PowerPanel.
  1599. """
  1600. power_panel = models.ForeignKey(
  1601. to='PowerPanel',
  1602. on_delete=models.PROTECT,
  1603. related_name='powerfeeds'
  1604. )
  1605. rack = models.ForeignKey(
  1606. to='Rack',
  1607. on_delete=models.PROTECT,
  1608. blank=True,
  1609. null=True
  1610. )
  1611. connected_endpoint = models.OneToOneField(
  1612. to='dcim.PowerPort',
  1613. on_delete=models.SET_NULL,
  1614. related_name='+',
  1615. blank=True,
  1616. null=True
  1617. )
  1618. connection_status = models.NullBooleanField(
  1619. choices=CONNECTION_STATUS_CHOICES,
  1620. blank=True
  1621. )
  1622. name = models.CharField(
  1623. max_length=50
  1624. )
  1625. status = models.CharField(
  1626. max_length=50,
  1627. choices=PowerFeedStatusChoices,
  1628. default=PowerFeedStatusChoices.STATUS_ACTIVE
  1629. )
  1630. type = models.CharField(
  1631. max_length=50,
  1632. choices=PowerFeedTypeChoices,
  1633. default=PowerFeedTypeChoices.TYPE_PRIMARY
  1634. )
  1635. supply = models.CharField(
  1636. max_length=50,
  1637. choices=PowerFeedSupplyChoices,
  1638. default=PowerFeedSupplyChoices.SUPPLY_AC
  1639. )
  1640. phase = models.CharField(
  1641. max_length=50,
  1642. choices=PowerFeedPhaseChoices,
  1643. default=PowerFeedPhaseChoices.PHASE_SINGLE
  1644. )
  1645. voltage = models.SmallIntegerField(
  1646. default=POWERFEED_VOLTAGE_DEFAULT,
  1647. validators=[ExclusionValidator([0])]
  1648. )
  1649. amperage = models.PositiveSmallIntegerField(
  1650. validators=[MinValueValidator(1)],
  1651. default=POWERFEED_AMPERAGE_DEFAULT
  1652. )
  1653. max_utilization = models.PositiveSmallIntegerField(
  1654. validators=[MinValueValidator(1), MaxValueValidator(100)],
  1655. default=POWERFEED_MAX_UTILIZATION_DEFAULT,
  1656. help_text="Maximum permissible draw (percentage)"
  1657. )
  1658. available_power = models.PositiveIntegerField(
  1659. default=0,
  1660. editable=False
  1661. )
  1662. comments = models.TextField(
  1663. blank=True
  1664. )
  1665. custom_field_values = GenericRelation(
  1666. to='extras.CustomFieldValue',
  1667. content_type_field='obj_type',
  1668. object_id_field='obj_id'
  1669. )
  1670. tags = TaggableManager(through=TaggedItem)
  1671. csv_headers = [
  1672. 'site', 'panel_name', 'rack_group', 'rack_name', 'name', 'status', 'type', 'supply', 'phase', 'voltage',
  1673. 'amperage', 'max_utilization', 'comments',
  1674. ]
  1675. clone_fields = [
  1676. 'power_panel', 'rack', 'status', 'type', 'supply', 'phase', 'voltage', 'amperage', 'max_utilization',
  1677. 'available_power',
  1678. ]
  1679. STATUS_CLASS_MAP = {
  1680. PowerFeedStatusChoices.STATUS_OFFLINE: 'warning',
  1681. PowerFeedStatusChoices.STATUS_ACTIVE: 'success',
  1682. PowerFeedStatusChoices.STATUS_PLANNED: 'info',
  1683. PowerFeedStatusChoices.STATUS_FAILED: 'danger',
  1684. }
  1685. TYPE_CLASS_MAP = {
  1686. PowerFeedTypeChoices.TYPE_PRIMARY: 'success',
  1687. PowerFeedTypeChoices.TYPE_REDUNDANT: 'info',
  1688. }
  1689. class Meta:
  1690. ordering = ['power_panel', 'name']
  1691. unique_together = ['power_panel', 'name']
  1692. def __str__(self):
  1693. return self.name
  1694. def get_absolute_url(self):
  1695. return reverse('dcim:powerfeed', args=[self.pk])
  1696. def to_csv(self):
  1697. return (
  1698. self.power_panel.site.name,
  1699. self.power_panel.name,
  1700. self.rack.group.name if self.rack and self.rack.group else None,
  1701. self.rack.name if self.rack else None,
  1702. self.name,
  1703. self.get_status_display(),
  1704. self.get_type_display(),
  1705. self.get_supply_display(),
  1706. self.get_phase_display(),
  1707. self.voltage,
  1708. self.amperage,
  1709. self.max_utilization,
  1710. self.comments,
  1711. )
  1712. def clean(self):
  1713. # Rack must belong to same Site as PowerPanel
  1714. if self.rack and self.rack.site != self.power_panel.site:
  1715. raise ValidationError("Rack {} ({}) and power panel {} ({}) are in different sites".format(
  1716. self.rack, self.rack.site, self.power_panel, self.power_panel.site
  1717. ))
  1718. # AC voltage cannot be negative
  1719. if self.voltage < 0 and self.supply == PowerFeedSupplyChoices.SUPPLY_AC:
  1720. raise ValidationError({
  1721. "voltage": "Voltage cannot be negative for AC supply"
  1722. })
  1723. def save(self, *args, **kwargs):
  1724. # Cache the available_power property on the instance
  1725. kva = abs(self.voltage) * self.amperage * (self.max_utilization / 100)
  1726. if self.phase == PowerFeedPhaseChoices.PHASE_3PHASE:
  1727. self.available_power = round(kva * 1.732)
  1728. else:
  1729. self.available_power = round(kva)
  1730. super().save(*args, **kwargs)
  1731. @property
  1732. def parent(self):
  1733. return self.power_panel
  1734. def get_type_class(self):
  1735. return self.TYPE_CLASS_MAP.get(self.type)
  1736. def get_status_class(self):
  1737. return self.STATUS_CLASS_MAP.get(self.status)
  1738. #
  1739. # Cables
  1740. #
  1741. @extras_features('custom_links', 'export_templates', 'webhooks')
  1742. class Cable(ChangeLoggedModel):
  1743. """
  1744. A physical connection between two endpoints.
  1745. """
  1746. termination_a_type = models.ForeignKey(
  1747. to=ContentType,
  1748. limit_choices_to=CABLE_TERMINATION_MODELS,
  1749. on_delete=models.PROTECT,
  1750. related_name='+'
  1751. )
  1752. termination_a_id = models.PositiveIntegerField()
  1753. termination_a = GenericForeignKey(
  1754. ct_field='termination_a_type',
  1755. fk_field='termination_a_id'
  1756. )
  1757. termination_b_type = models.ForeignKey(
  1758. to=ContentType,
  1759. limit_choices_to=CABLE_TERMINATION_MODELS,
  1760. on_delete=models.PROTECT,
  1761. related_name='+'
  1762. )
  1763. termination_b_id = models.PositiveIntegerField()
  1764. termination_b = GenericForeignKey(
  1765. ct_field='termination_b_type',
  1766. fk_field='termination_b_id'
  1767. )
  1768. type = models.CharField(
  1769. max_length=50,
  1770. choices=CableTypeChoices,
  1771. blank=True
  1772. )
  1773. status = models.CharField(
  1774. max_length=50,
  1775. choices=CableStatusChoices,
  1776. default=CableStatusChoices.STATUS_CONNECTED
  1777. )
  1778. label = models.CharField(
  1779. max_length=100,
  1780. blank=True
  1781. )
  1782. color = ColorField(
  1783. blank=True
  1784. )
  1785. length = models.PositiveSmallIntegerField(
  1786. blank=True,
  1787. null=True
  1788. )
  1789. length_unit = models.CharField(
  1790. max_length=50,
  1791. choices=CableLengthUnitChoices,
  1792. blank=True,
  1793. )
  1794. # Stores the normalized length (in meters) for database ordering
  1795. _abs_length = models.DecimalField(
  1796. max_digits=10,
  1797. decimal_places=4,
  1798. blank=True,
  1799. null=True
  1800. )
  1801. # Cache the associated device (where applicable) for the A and B terminations. This enables filtering of Cables by
  1802. # their associated Devices.
  1803. _termination_a_device = models.ForeignKey(
  1804. to=Device,
  1805. on_delete=models.CASCADE,
  1806. related_name='+',
  1807. blank=True,
  1808. null=True
  1809. )
  1810. _termination_b_device = models.ForeignKey(
  1811. to=Device,
  1812. on_delete=models.CASCADE,
  1813. related_name='+',
  1814. blank=True,
  1815. null=True
  1816. )
  1817. csv_headers = [
  1818. 'termination_a_type', 'termination_a_id', 'termination_b_type', 'termination_b_id', 'type', 'status', 'label',
  1819. 'color', 'length', 'length_unit',
  1820. ]
  1821. STATUS_CLASS_MAP = {
  1822. CableStatusChoices.STATUS_CONNECTED: 'success',
  1823. CableStatusChoices.STATUS_PLANNED: 'info',
  1824. CableStatusChoices.STATUS_DECOMMISSIONING: 'warning',
  1825. }
  1826. class Meta:
  1827. ordering = ['pk']
  1828. unique_together = (
  1829. ('termination_a_type', 'termination_a_id'),
  1830. ('termination_b_type', 'termination_b_id'),
  1831. )
  1832. def __init__(self, *args, **kwargs):
  1833. super().__init__(*args, **kwargs)
  1834. # A copy of the PK to be used by __str__ in case the object is deleted
  1835. self._pk = self.pk
  1836. def __str__(self):
  1837. return self.label or '#{}'.format(self._pk)
  1838. def get_absolute_url(self):
  1839. return reverse('dcim:cable', args=[self.pk])
  1840. def clean(self):
  1841. # Validate that termination A exists
  1842. if not hasattr(self, 'termination_a_type'):
  1843. raise ValidationError('Termination A type has not been specified')
  1844. try:
  1845. self.termination_a_type.model_class().objects.get(pk=self.termination_a_id)
  1846. except ObjectDoesNotExist:
  1847. raise ValidationError({
  1848. 'termination_a': 'Invalid ID for type {}'.format(self.termination_a_type)
  1849. })
  1850. # Validate that termination B exists
  1851. if not hasattr(self, 'termination_b_type'):
  1852. raise ValidationError('Termination B type has not been specified')
  1853. try:
  1854. self.termination_b_type.model_class().objects.get(pk=self.termination_b_id)
  1855. except ObjectDoesNotExist:
  1856. raise ValidationError({
  1857. 'termination_b': 'Invalid ID for type {}'.format(self.termination_b_type)
  1858. })
  1859. type_a = self.termination_a_type.model
  1860. type_b = self.termination_b_type.model
  1861. # Validate interface types
  1862. if type_a == 'interface' and self.termination_a.type in NONCONNECTABLE_IFACE_TYPES:
  1863. raise ValidationError({
  1864. 'termination_a_id': 'Cables cannot be terminated to {} interfaces'.format(
  1865. self.termination_a.get_type_display()
  1866. )
  1867. })
  1868. if type_b == 'interface' and self.termination_b.type in NONCONNECTABLE_IFACE_TYPES:
  1869. raise ValidationError({
  1870. 'termination_b_id': 'Cables cannot be terminated to {} interfaces'.format(
  1871. self.termination_b.get_type_display()
  1872. )
  1873. })
  1874. # Check that termination types are compatible
  1875. if type_b not in COMPATIBLE_TERMINATION_TYPES.get(type_a):
  1876. raise ValidationError("Incompatible termination types: {} and {}".format(
  1877. self.termination_a_type, self.termination_b_type
  1878. ))
  1879. # A RearPort with multiple positions must be connected to a component with an equal number of positions
  1880. if isinstance(self.termination_a, RearPort) and isinstance(self.termination_b, RearPort):
  1881. if self.termination_a.positions != self.termination_b.positions:
  1882. raise ValidationError(
  1883. "{} has {} positions and {} has {}. Both terminations must have the same number of positions.".format(
  1884. self.termination_a, self.termination_a.positions,
  1885. self.termination_b, self.termination_b.positions
  1886. )
  1887. )
  1888. # A termination point cannot be connected to itself
  1889. if self.termination_a == self.termination_b:
  1890. raise ValidationError("Cannot connect {} to itself".format(self.termination_a_type))
  1891. # A front port cannot be connected to its corresponding rear port
  1892. if (
  1893. type_a in ['frontport', 'rearport'] and
  1894. type_b in ['frontport', 'rearport'] and
  1895. (
  1896. getattr(self.termination_a, 'rear_port', None) == self.termination_b or
  1897. getattr(self.termination_b, 'rear_port', None) == self.termination_a
  1898. )
  1899. ):
  1900. raise ValidationError("A front port cannot be connected to it corresponding rear port")
  1901. # Check for an existing Cable connected to either termination object
  1902. if self.termination_a.cable not in (None, self):
  1903. raise ValidationError("{} already has a cable attached (#{})".format(
  1904. self.termination_a, self.termination_a.cable_id
  1905. ))
  1906. if self.termination_b.cable not in (None, self):
  1907. raise ValidationError("{} already has a cable attached (#{})".format(
  1908. self.termination_b, self.termination_b.cable_id
  1909. ))
  1910. # Validate length and length_unit
  1911. if self.length is not None and not self.length_unit:
  1912. raise ValidationError("Must specify a unit when setting a cable length")
  1913. elif self.length is None:
  1914. self.length_unit = ''
  1915. def save(self, *args, **kwargs):
  1916. # Store the given length (if any) in meters for use in database ordering
  1917. if self.length and self.length_unit:
  1918. self._abs_length = to_meters(self.length, self.length_unit)
  1919. else:
  1920. self._abs_length = None
  1921. # Store the parent Device for the A and B terminations (if applicable) to enable filtering
  1922. if hasattr(self.termination_a, 'device'):
  1923. self._termination_a_device = self.termination_a.device
  1924. if hasattr(self.termination_b, 'device'):
  1925. self._termination_b_device = self.termination_b.device
  1926. super().save(*args, **kwargs)
  1927. # Update the private pk used in __str__ in case this is a new object (i.e. just got its pk)
  1928. self._pk = self.pk
  1929. def to_csv(self):
  1930. return (
  1931. '{}.{}'.format(self.termination_a_type.app_label, self.termination_a_type.model),
  1932. self.termination_a_id,
  1933. '{}.{}'.format(self.termination_b_type.app_label, self.termination_b_type.model),
  1934. self.termination_b_id,
  1935. self.get_type_display(),
  1936. self.get_status_display(),
  1937. self.label,
  1938. self.color,
  1939. self.length,
  1940. self.length_unit,
  1941. )
  1942. def get_status_class(self):
  1943. return self.STATUS_CLASS_MAP.get(self.status)
  1944. def get_compatible_types(self):
  1945. """
  1946. Return all termination types compatible with termination A.
  1947. """
  1948. if self.termination_a is None:
  1949. return
  1950. return COMPATIBLE_TERMINATION_TYPES[self.termination_a._meta.model_name]
  1951. def get_path_endpoints(self):
  1952. """
  1953. Traverse both ends of a cable path and return its connected endpoints. Note that one or both endpoints may be
  1954. None.
  1955. """
  1956. a_path = self.termination_b.trace()
  1957. b_path = self.termination_a.trace()
  1958. # Determine overall path status (connected or planned)
  1959. if self.status == CableStatusChoices.STATUS_CONNECTED:
  1960. path_status = True
  1961. for segment in a_path[1:] + b_path[1:]:
  1962. if segment[1] is None or segment[1].status != CableStatusChoices.STATUS_CONNECTED:
  1963. path_status = False
  1964. break
  1965. else:
  1966. path_status = False
  1967. a_endpoint = a_path[-1][2]
  1968. b_endpoint = b_path[-1][2]
  1969. return a_endpoint, b_endpoint, path_status