__init__.py 73 KB

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