__init__.py 70 KB

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