__init__.py 72 KB

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