__init__.py 75 KB

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