__init__.py 69 KB

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