__init__.py 76 KB

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