__init__.py 71 KB

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