models.py 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546
  1. from collections import OrderedDict
  2. from itertools import count, groupby
  3. from django.conf import settings
  4. from django.contrib.auth.models import User
  5. from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
  6. from django.contrib.contenttypes.models import ContentType
  7. from django.contrib.postgres.fields import ArrayField, JSONField
  8. from django.core.exceptions import ObjectDoesNotExist, ValidationError
  9. from django.core.validators import MaxValueValidator, MinValueValidator
  10. from django.db import models
  11. from django.db.models import Count, Q
  12. from django.urls import reverse
  13. from mptt.models import MPTTModel, TreeForeignKey
  14. from taggit.managers import TaggableManager
  15. from timezone_field import TimeZoneField
  16. from extras.models import ConfigContextModel, CustomFieldModel, ObjectChange
  17. from utilities.fields import ColorField, NullableCharField
  18. from utilities.managers import NaturalOrderByManager
  19. from utilities.models import ChangeLoggedModel
  20. from utilities.utils import serialize_object, to_meters
  21. from .constants import *
  22. from .fields import ASNField, MACAddressField
  23. from .querysets import InterfaceManager
  24. class ComponentTemplateModel(models.Model):
  25. class Meta:
  26. abstract = True
  27. def log_change(self, user, request_id, action):
  28. """
  29. Log an ObjectChange including the parent DeviceType.
  30. """
  31. ObjectChange(
  32. user=user,
  33. request_id=request_id,
  34. changed_object=self,
  35. related_object=self.device_type,
  36. action=action,
  37. object_data=serialize_object(self)
  38. ).save()
  39. class ComponentModel(models.Model):
  40. class Meta:
  41. abstract = True
  42. def log_change(self, user, request_id, action):
  43. """
  44. Log an ObjectChange including the parent Device/VM.
  45. """
  46. parent = self.device if self.device is not None else getattr(self, 'virtual_machine', None)
  47. ObjectChange(
  48. user=user,
  49. request_id=request_id,
  50. changed_object=self,
  51. related_object=parent,
  52. action=action,
  53. object_data=serialize_object(self)
  54. ).save()
  55. class CableTermination(models.Model):
  56. cable = models.ForeignKey(
  57. to='dcim.Cable',
  58. on_delete=models.SET_NULL,
  59. related_name='+',
  60. blank=True,
  61. null=True
  62. )
  63. class Meta:
  64. abstract = True
  65. def trace(self, position=1):
  66. """
  67. Return a list representing a complete cable path, with each individual segment represented as a three-tuple:
  68. [
  69. (termination A, cable, termination B),
  70. (termination C, cable, termination D),
  71. (termination E, cable, termination F)
  72. ]
  73. """
  74. def get_peer_port(termination, position=1):
  75. from circuits.models import CircuitTermination
  76. # Map a front port to its corresponding rear port
  77. if isinstance(termination, FrontPort):
  78. return termination.rear_port, termination.rear_port_position
  79. # Map a rear port/position to its corresponding front port
  80. elif isinstance(termination, RearPort):
  81. if position not in range(1, termination.positions + 1):
  82. raise Exception("Invalid position for {} ({} positions): {})".format(
  83. termination, termination.positions, position
  84. ))
  85. peer_port = FrontPort.objects.get(
  86. rear_port=termination,
  87. rear_port_position=position,
  88. )
  89. return peer_port, 1
  90. # Follow a circuit to its other termination
  91. elif isinstance(termination, CircuitTermination):
  92. peer_termination = termination.get_peer_termination()
  93. if peer_termination is None:
  94. return None, None
  95. return peer_termination, position
  96. # Termination is not a pass-through port
  97. else:
  98. return None, None
  99. if not self.cable:
  100. return [(self, None, None)]
  101. far_end = self.cable.termination_b if self.cable.termination_a == self else self.cable.termination_a
  102. path = [(self, self.cable, far_end)]
  103. peer_port, position = get_peer_port(far_end, position)
  104. if peer_port is None:
  105. return path
  106. next_segment = peer_port.trace(position)
  107. if next_segment is None:
  108. return path + [(peer_port, None, None)]
  109. return path + next_segment
  110. #
  111. # Regions
  112. #
  113. class Region(MPTTModel, ChangeLoggedModel):
  114. """
  115. Sites can be grouped within geographic Regions.
  116. """
  117. parent = TreeForeignKey(
  118. to='self',
  119. on_delete=models.CASCADE,
  120. related_name='children',
  121. blank=True,
  122. null=True,
  123. db_index=True
  124. )
  125. name = models.CharField(
  126. max_length=50,
  127. unique=True
  128. )
  129. slug = models.SlugField(
  130. unique=True
  131. )
  132. csv_headers = ['name', 'slug', 'parent']
  133. class MPTTMeta:
  134. order_insertion_by = ['name']
  135. def __str__(self):
  136. return self.name
  137. def get_absolute_url(self):
  138. return "{}?region={}".format(reverse('dcim:site_list'), self.slug)
  139. def to_csv(self):
  140. return (
  141. self.name,
  142. self.slug,
  143. self.parent.name if self.parent else None,
  144. )
  145. #
  146. # Sites
  147. #
  148. class SiteManager(NaturalOrderByManager):
  149. natural_order_field = 'name'
  150. class Site(ChangeLoggedModel, CustomFieldModel):
  151. """
  152. A Site represents a geographic location within a network; typically a building or campus. The optional facility
  153. field can be used to include an external designation, such as a data center name (e.g. Equinix SV6).
  154. """
  155. name = models.CharField(
  156. max_length=50,
  157. unique=True
  158. )
  159. slug = models.SlugField(
  160. unique=True
  161. )
  162. status = models.PositiveSmallIntegerField(
  163. choices=SITE_STATUS_CHOICES,
  164. default=SITE_STATUS_ACTIVE
  165. )
  166. region = models.ForeignKey(
  167. to='dcim.Region',
  168. on_delete=models.SET_NULL,
  169. related_name='sites',
  170. blank=True,
  171. null=True
  172. )
  173. tenant = models.ForeignKey(
  174. to='tenancy.Tenant',
  175. on_delete=models.PROTECT,
  176. related_name='sites',
  177. blank=True,
  178. null=True
  179. )
  180. facility = models.CharField(
  181. max_length=50,
  182. blank=True
  183. )
  184. asn = ASNField(
  185. blank=True,
  186. null=True,
  187. verbose_name='ASN'
  188. )
  189. time_zone = TimeZoneField(
  190. blank=True
  191. )
  192. description = models.CharField(
  193. max_length=100,
  194. blank=True
  195. )
  196. physical_address = models.CharField(
  197. max_length=200,
  198. blank=True
  199. )
  200. shipping_address = models.CharField(
  201. max_length=200,
  202. blank=True
  203. )
  204. latitude = models.DecimalField(
  205. max_digits=8,
  206. decimal_places=6,
  207. blank=True,
  208. null=True
  209. )
  210. longitude = models.DecimalField(
  211. max_digits=9,
  212. decimal_places=6,
  213. blank=True,
  214. null=True
  215. )
  216. contact_name = models.CharField(
  217. max_length=50,
  218. blank=True
  219. )
  220. contact_phone = models.CharField(
  221. max_length=20,
  222. blank=True
  223. )
  224. contact_email = models.EmailField(
  225. blank=True,
  226. verbose_name='Contact E-mail'
  227. )
  228. comments = models.TextField(
  229. blank=True
  230. )
  231. custom_field_values = GenericRelation(
  232. to='extras.CustomFieldValue',
  233. content_type_field='obj_type',
  234. object_id_field='obj_id'
  235. )
  236. images = GenericRelation(
  237. to='extras.ImageAttachment'
  238. )
  239. objects = SiteManager()
  240. tags = TaggableManager()
  241. csv_headers = [
  242. 'name', 'slug', 'status', 'region', 'tenant', 'facility', 'asn', 'time_zone', 'description', 'physical_address',
  243. 'shipping_address', 'latitude', 'longitude', 'contact_name', 'contact_phone', 'contact_email', 'comments',
  244. ]
  245. class Meta:
  246. ordering = ['name']
  247. def __str__(self):
  248. return self.name
  249. def get_absolute_url(self):
  250. return reverse('dcim:site', args=[self.slug])
  251. def to_csv(self):
  252. return (
  253. self.name,
  254. self.slug,
  255. self.get_status_display(),
  256. self.region.name if self.region else None,
  257. self.tenant.name if self.tenant else None,
  258. self.facility,
  259. self.asn,
  260. self.time_zone,
  261. self.description,
  262. self.physical_address,
  263. self.shipping_address,
  264. self.latitude,
  265. self.longitude,
  266. self.contact_name,
  267. self.contact_phone,
  268. self.contact_email,
  269. self.comments,
  270. )
  271. def get_status_class(self):
  272. return STATUS_CLASSES[self.status]
  273. @property
  274. def count_prefixes(self):
  275. return self.prefixes.count()
  276. @property
  277. def count_vlans(self):
  278. return self.vlans.count()
  279. @property
  280. def count_racks(self):
  281. return Rack.objects.filter(site=self).count()
  282. @property
  283. def count_devices(self):
  284. return Device.objects.filter(site=self).count()
  285. @property
  286. def count_circuits(self):
  287. from circuits.models import Circuit
  288. return Circuit.objects.filter(terminations__site=self).count()
  289. @property
  290. def count_vms(self):
  291. from virtualization.models import VirtualMachine
  292. return VirtualMachine.objects.filter(cluster__site=self).count()
  293. #
  294. # Racks
  295. #
  296. class RackGroup(ChangeLoggedModel):
  297. """
  298. Racks can be grouped as subsets within a Site. The scope of a group will depend on how Sites are defined. For
  299. example, if a Site spans a corporate campus, a RackGroup might be defined to represent each building within that
  300. campus. If a Site instead represents a single building, a RackGroup might represent a single room or floor.
  301. """
  302. name = models.CharField(
  303. max_length=50
  304. )
  305. slug = models.SlugField()
  306. site = models.ForeignKey(
  307. to='dcim.Site',
  308. on_delete=models.CASCADE,
  309. related_name='rack_groups'
  310. )
  311. csv_headers = ['site', 'name', 'slug']
  312. class Meta:
  313. ordering = ['site', 'name']
  314. unique_together = [
  315. ['site', 'name'],
  316. ['site', 'slug'],
  317. ]
  318. def __str__(self):
  319. return self.name
  320. def get_absolute_url(self):
  321. return "{}?group_id={}".format(reverse('dcim:rack_list'), self.pk)
  322. def to_csv(self):
  323. return (
  324. self.site,
  325. self.name,
  326. self.slug,
  327. )
  328. class RackRole(ChangeLoggedModel):
  329. """
  330. Racks can be organized by functional role, similar to Devices.
  331. """
  332. name = models.CharField(
  333. max_length=50,
  334. unique=True
  335. )
  336. slug = models.SlugField(
  337. unique=True
  338. )
  339. color = ColorField()
  340. csv_headers = ['name', 'slug', 'color']
  341. class Meta:
  342. ordering = ['name']
  343. def __str__(self):
  344. return self.name
  345. def get_absolute_url(self):
  346. return "{}?role={}".format(reverse('dcim:rack_list'), self.slug)
  347. def to_csv(self):
  348. return (
  349. self.name,
  350. self.slug,
  351. self.color,
  352. )
  353. class RackManager(NaturalOrderByManager):
  354. natural_order_field = 'name'
  355. class Rack(ChangeLoggedModel, CustomFieldModel):
  356. """
  357. Devices are housed within Racks. Each rack has a defined height measured in rack units, and a front and rear face.
  358. Each Rack is assigned to a Site and (optionally) a RackGroup.
  359. """
  360. name = models.CharField(
  361. max_length=50
  362. )
  363. facility_id = NullableCharField(
  364. max_length=50,
  365. blank=True,
  366. null=True,
  367. verbose_name='Facility ID'
  368. )
  369. site = models.ForeignKey(
  370. to='dcim.Site',
  371. on_delete=models.PROTECT,
  372. related_name='racks'
  373. )
  374. group = models.ForeignKey(
  375. to='dcim.RackGroup',
  376. on_delete=models.SET_NULL,
  377. related_name='racks',
  378. blank=True,
  379. null=True
  380. )
  381. tenant = models.ForeignKey(
  382. to='tenancy.Tenant',
  383. on_delete=models.PROTECT,
  384. related_name='racks',
  385. blank=True,
  386. null=True
  387. )
  388. status = models.PositiveSmallIntegerField(
  389. choices=RACK_STATUS_CHOICES,
  390. default=RACK_STATUS_ACTIVE
  391. )
  392. role = models.ForeignKey(
  393. to='dcim.RackRole',
  394. on_delete=models.PROTECT,
  395. related_name='racks',
  396. blank=True,
  397. null=True
  398. )
  399. serial = models.CharField(
  400. max_length=50,
  401. blank=True,
  402. verbose_name='Serial number'
  403. )
  404. asset_tag = NullableCharField(
  405. max_length=50,
  406. blank=True,
  407. null=True,
  408. unique=True,
  409. verbose_name='Asset tag',
  410. help_text='A unique tag used to identify this rack'
  411. )
  412. type = models.PositiveSmallIntegerField(
  413. choices=RACK_TYPE_CHOICES,
  414. blank=True,
  415. null=True,
  416. verbose_name='Type'
  417. )
  418. width = models.PositiveSmallIntegerField(
  419. choices=RACK_WIDTH_CHOICES,
  420. default=RACK_WIDTH_19IN,
  421. verbose_name='Width',
  422. help_text='Rail-to-rail width'
  423. )
  424. u_height = models.PositiveSmallIntegerField(
  425. default=42,
  426. verbose_name='Height (U)',
  427. validators=[MinValueValidator(1), MaxValueValidator(100)]
  428. )
  429. desc_units = models.BooleanField(
  430. default=False,
  431. verbose_name='Descending units',
  432. help_text='Units are numbered top-to-bottom'
  433. )
  434. outer_width = models.PositiveSmallIntegerField(
  435. blank=True,
  436. null=True
  437. )
  438. outer_depth = models.PositiveSmallIntegerField(
  439. blank=True,
  440. null=True
  441. )
  442. outer_unit = models.CharField(
  443. choices=RACK_DIMENSION_UNIT_CHOICES,
  444. max_length=2,
  445. blank=True
  446. )
  447. comments = models.TextField(
  448. blank=True
  449. )
  450. custom_field_values = GenericRelation(
  451. to='extras.CustomFieldValue',
  452. content_type_field='obj_type',
  453. object_id_field='obj_id'
  454. )
  455. images = GenericRelation(
  456. to='extras.ImageAttachment'
  457. )
  458. objects = RackManager()
  459. tags = TaggableManager()
  460. csv_headers = [
  461. 'site', 'group_name', 'name', 'facility_id', 'tenant', 'status', 'role', 'type', 'serial', 'asset_tag', 'width',
  462. 'u_height', 'desc_units', 'outer_width', 'outer_depth', 'outer_unit', 'comments',
  463. ]
  464. class Meta:
  465. ordering = ['site', 'group', 'name']
  466. unique_together = [
  467. ['group', 'name'],
  468. ['group', 'facility_id'],
  469. ]
  470. def __str__(self):
  471. return self.display_name or super(Rack, self).__str__()
  472. def get_absolute_url(self):
  473. return reverse('dcim:rack', args=[self.pk])
  474. def clean(self):
  475. # Validate outer dimensions and unit
  476. if self.outer_width and not self.outer_unit:
  477. raise ValidationError("Must specify a unit when setting an outer width")
  478. if self.outer_depth and not self.outer_unit:
  479. raise ValidationError("Must specify a unit when setting an outer depth")
  480. if self.outer_unit and self.outer_width is None and self.outer_depth is None:
  481. self.length_unit = ''
  482. if self.pk:
  483. # Validate that Rack is tall enough to house the installed Devices
  484. top_device = Device.objects.filter(rack=self).exclude(position__isnull=True).order_by('-position').first()
  485. if top_device:
  486. min_height = top_device.position + top_device.device_type.u_height - 1
  487. if self.u_height < min_height:
  488. raise ValidationError({
  489. 'u_height': "Rack must be at least {}U tall to house currently installed devices.".format(
  490. min_height
  491. )
  492. })
  493. # Validate that Rack was assigned a group of its same site, if applicable
  494. if self.group:
  495. if self.group.site != self.site:
  496. raise ValidationError({
  497. 'group': "Rack group must be from the same site, {}.".format(self.site)
  498. })
  499. def save(self, *args, **kwargs):
  500. # Record the original site assignment for this rack.
  501. _site_id = None
  502. if self.pk:
  503. _site_id = Rack.objects.get(pk=self.pk).site_id
  504. super(Rack, self).save(*args, **kwargs)
  505. # Update racked devices if the assigned Site has been changed.
  506. if _site_id is not None and self.site_id != _site_id:
  507. Device.objects.filter(rack=self).update(site_id=self.site.pk)
  508. def to_csv(self):
  509. return (
  510. self.site.name,
  511. self.group.name if self.group else None,
  512. self.name,
  513. self.facility_id,
  514. self.tenant.name if self.tenant else None,
  515. self.get_status_display(),
  516. self.role.name if self.role else None,
  517. self.get_type_display() if self.type else None,
  518. self.serial,
  519. self.asset_tag,
  520. self.width,
  521. self.u_height,
  522. self.desc_units,
  523. self.outer_width,
  524. self.outer_depth,
  525. self.outer_unit,
  526. self.comments,
  527. )
  528. @property
  529. def units(self):
  530. if self.desc_units:
  531. return range(1, self.u_height + 1)
  532. else:
  533. return reversed(range(1, self.u_height + 1))
  534. @property
  535. def display_name(self):
  536. if self.facility_id:
  537. return "{} ({})".format(self.name, self.facility_id)
  538. elif self.name:
  539. return self.name
  540. return ""
  541. def get_status_class(self):
  542. return STATUS_CLASSES[self.status]
  543. def get_rack_units(self, face=RACK_FACE_FRONT, exclude=None, remove_redundant=False):
  544. """
  545. Return a list of rack units as dictionaries. Example: {'device': None, 'face': 0, 'id': 48, 'name': 'U48'}
  546. Each key 'device' is either a Device or None. By default, multi-U devices are repeated for each U they occupy.
  547. :param face: Rack face (front or rear)
  548. :param exclude: PK of a Device to exclude (optional); helpful when relocating a Device within a Rack
  549. :param remove_redundant: If True, rack units occupied by a device already listed will be omitted
  550. """
  551. elevation = OrderedDict()
  552. for u in self.units:
  553. elevation[u] = {'id': u, 'name': 'U{}'.format(u), 'face': face, 'device': None}
  554. # Add devices to rack units list
  555. if self.pk:
  556. for device in Device.objects.select_related('device_type__manufacturer', 'device_role')\
  557. .annotate(devicebay_count=Count('device_bays'))\
  558. .exclude(pk=exclude)\
  559. .filter(rack=self, position__gt=0)\
  560. .filter(Q(face=face) | Q(device_type__is_full_depth=True)):
  561. if remove_redundant:
  562. elevation[device.position]['device'] = device
  563. for u in range(device.position + 1, device.position + device.device_type.u_height):
  564. elevation.pop(u, None)
  565. else:
  566. for u in range(device.position, device.position + device.device_type.u_height):
  567. elevation[u]['device'] = device
  568. return [u for u in elevation.values()]
  569. def get_front_elevation(self):
  570. return self.get_rack_units(face=RACK_FACE_FRONT, remove_redundant=True)
  571. def get_rear_elevation(self):
  572. return self.get_rack_units(face=RACK_FACE_REAR, remove_redundant=True)
  573. def get_available_units(self, u_height=1, rack_face=None, exclude=list()):
  574. """
  575. Return a list of units within the rack available to accommodate a device of a given U height (default 1).
  576. Optionally exclude one or more devices when calculating empty units (needed when moving a device from one
  577. position to another within a rack).
  578. :param u_height: Minimum number of contiguous free units required
  579. :param rack_face: The face of the rack (front or rear) required; 'None' if device is full depth
  580. :param exclude: List of devices IDs to exclude (useful when moving a device within a rack)
  581. """
  582. # Gather all devices which consume U space within the rack
  583. devices = self.devices.select_related('device_type').filter(position__gte=1).exclude(pk__in=exclude)
  584. # Initialize the rack unit skeleton
  585. units = list(range(1, self.u_height + 1))
  586. # Remove units consumed by installed devices
  587. for d in devices:
  588. if rack_face is None or d.face == rack_face or d.device_type.is_full_depth:
  589. for u in range(d.position, d.position + d.device_type.u_height):
  590. try:
  591. units.remove(u)
  592. except ValueError:
  593. # Found overlapping devices in the rack!
  594. pass
  595. # Remove units without enough space above them to accommodate a device of the specified height
  596. available_units = []
  597. for u in units:
  598. if set(range(u, u + u_height)).issubset(units):
  599. available_units.append(u)
  600. return list(reversed(available_units))
  601. def get_reserved_units(self):
  602. """
  603. Return a dictionary mapping all reserved units within the rack to their reservation.
  604. """
  605. reserved_units = {}
  606. for r in self.reservations.all():
  607. for u in r.units:
  608. reserved_units[u] = r
  609. return reserved_units
  610. def get_0u_devices(self):
  611. return self.devices.filter(position=0)
  612. def get_utilization(self):
  613. """
  614. Determine the utilization rate of the rack and return it as a percentage.
  615. """
  616. u_available = len(self.get_available_units())
  617. return int(float(self.u_height - u_available) / self.u_height * 100)
  618. class RackReservation(ChangeLoggedModel):
  619. """
  620. One or more reserved units within a Rack.
  621. """
  622. rack = models.ForeignKey(
  623. to='dcim.Rack',
  624. on_delete=models.CASCADE,
  625. related_name='reservations'
  626. )
  627. units = ArrayField(
  628. base_field=models.PositiveSmallIntegerField()
  629. )
  630. tenant = models.ForeignKey(
  631. to='tenancy.Tenant',
  632. on_delete=models.PROTECT,
  633. related_name='rackreservations',
  634. blank=True,
  635. null=True
  636. )
  637. user = models.ForeignKey(
  638. to=User,
  639. on_delete=models.PROTECT
  640. )
  641. description = models.CharField(
  642. max_length=100
  643. )
  644. class Meta:
  645. ordering = ['created']
  646. def __str__(self):
  647. return "Reservation for rack {}".format(self.rack)
  648. def clean(self):
  649. if self.units:
  650. # Validate that all specified units exist in the Rack.
  651. invalid_units = [u for u in self.units if u not in self.rack.units]
  652. if invalid_units:
  653. raise ValidationError({
  654. 'units': "Invalid unit(s) for {}U rack: {}".format(
  655. self.rack.u_height,
  656. ', '.join([str(u) for u in invalid_units]),
  657. ),
  658. })
  659. # Check that none of the units has already been reserved for this Rack.
  660. reserved_units = []
  661. for resv in self.rack.reservations.exclude(pk=self.pk):
  662. reserved_units += resv.units
  663. conflicting_units = [u for u in self.units if u in reserved_units]
  664. if conflicting_units:
  665. raise ValidationError({
  666. 'units': 'The following units have already been reserved: {}'.format(
  667. ', '.join([str(u) for u in conflicting_units]),
  668. )
  669. })
  670. @property
  671. def unit_list(self):
  672. """
  673. Express the assigned units as a string of summarized ranges. For example:
  674. [0, 1, 2, 10, 14, 15, 16] => "0-2, 10, 14-16"
  675. """
  676. group = (list(x) for _, x in groupby(sorted(self.units), lambda x, c=count(): next(c) - x))
  677. return ', '.join('-'.join(map(str, (g[0], g[-1])[:len(g)])) for g in group)
  678. #
  679. # Device Types
  680. #
  681. class Manufacturer(ChangeLoggedModel):
  682. """
  683. A Manufacturer represents a company which produces hardware devices; for example, Juniper or Dell.
  684. """
  685. name = models.CharField(
  686. max_length=50,
  687. unique=True
  688. )
  689. slug = models.SlugField(
  690. unique=True
  691. )
  692. csv_headers = ['name', 'slug']
  693. class Meta:
  694. ordering = ['name']
  695. def __str__(self):
  696. return self.name
  697. def get_absolute_url(self):
  698. return "{}?manufacturer={}".format(reverse('dcim:devicetype_list'), self.slug)
  699. def to_csv(self):
  700. return (
  701. self.name,
  702. self.slug,
  703. )
  704. class DeviceType(ChangeLoggedModel, CustomFieldModel):
  705. """
  706. A DeviceType represents a particular make (Manufacturer) and model of device. It specifies rack height and depth, as
  707. well as high-level functional role(s).
  708. Each DeviceType can have an arbitrary number of component templates assigned to it, which define console, power, and
  709. interface objects. For example, a Juniper EX4300-48T DeviceType would have:
  710. * 1 ConsolePortTemplate
  711. * 2 PowerPortTemplates
  712. * 48 InterfaceTemplates
  713. When a new Device of this type is created, the appropriate console, power, and interface objects (as defined by the
  714. DeviceType) are automatically created as well.
  715. """
  716. manufacturer = models.ForeignKey(
  717. to='dcim.Manufacturer',
  718. on_delete=models.PROTECT,
  719. related_name='device_types'
  720. )
  721. model = models.CharField(
  722. max_length=50
  723. )
  724. slug = models.SlugField()
  725. part_number = models.CharField(
  726. max_length=50,
  727. blank=True,
  728. help_text='Discrete part number (optional)'
  729. )
  730. u_height = models.PositiveSmallIntegerField(
  731. default=1,
  732. verbose_name='Height (U)'
  733. )
  734. is_full_depth = models.BooleanField(
  735. default=True,
  736. verbose_name='Is full depth',
  737. help_text='Device consumes both front and rear rack faces'
  738. )
  739. subdevice_role = models.NullBooleanField(
  740. default=None,
  741. verbose_name='Parent/child status',
  742. choices=SUBDEVICE_ROLE_CHOICES,
  743. help_text='Parent devices house child devices in device bays. Select '
  744. '"None" if this device type is neither a parent nor a child.'
  745. )
  746. comments = models.TextField(
  747. blank=True
  748. )
  749. custom_field_values = GenericRelation(
  750. to='extras.CustomFieldValue',
  751. content_type_field='obj_type',
  752. object_id_field='obj_id'
  753. )
  754. tags = TaggableManager()
  755. csv_headers = [
  756. 'manufacturer', 'model', 'slug', 'part_number', 'u_height', 'is_full_depth', 'subdevice_role', 'comments',
  757. ]
  758. class Meta:
  759. ordering = ['manufacturer', 'model']
  760. unique_together = [
  761. ['manufacturer', 'model'],
  762. ['manufacturer', 'slug'],
  763. ]
  764. def __str__(self):
  765. return self.model
  766. def __init__(self, *args, **kwargs):
  767. super(DeviceType, self).__init__(*args, **kwargs)
  768. # Save a copy of u_height for validation in clean()
  769. self._original_u_height = self.u_height
  770. def get_absolute_url(self):
  771. return reverse('dcim:devicetype', args=[self.pk])
  772. def to_csv(self):
  773. return (
  774. self.manufacturer.name,
  775. self.model,
  776. self.slug,
  777. self.part_number,
  778. self.u_height,
  779. self.is_full_depth,
  780. self.get_subdevice_role_display() if self.subdevice_role else None,
  781. self.comments,
  782. )
  783. def clean(self):
  784. # If editing an existing DeviceType to have a larger u_height, first validate that *all* instances of it have
  785. # room to expand within their racks. This validation will impose a very high performance penalty when there are
  786. # many instances to check, but increasing the u_height of a DeviceType should be a very rare occurrence.
  787. if self.pk is not None and self.u_height > self._original_u_height:
  788. for d in Device.objects.filter(device_type=self, position__isnull=False):
  789. face_required = None if self.is_full_depth else d.face
  790. u_available = d.rack.get_available_units(u_height=self.u_height, rack_face=face_required,
  791. exclude=[d.pk])
  792. if d.position not in u_available:
  793. raise ValidationError({
  794. 'u_height': "Device {} in rack {} does not have sufficient space to accommodate a height of "
  795. "{}U".format(d, d.rack, self.u_height)
  796. })
  797. if self.subdevice_role != SUBDEVICE_ROLE_PARENT and self.device_bay_templates.count():
  798. raise ValidationError({
  799. 'subdevice_role': "Must delete all device bay templates associated with this device before "
  800. "declassifying it as a parent device."
  801. })
  802. if self.u_height and self.subdevice_role == SUBDEVICE_ROLE_CHILD:
  803. raise ValidationError({
  804. 'u_height': "Child device types must be 0U."
  805. })
  806. @property
  807. def full_name(self):
  808. return '{} {}'.format(self.manufacturer.name, self.model)
  809. @property
  810. def is_parent_device(self):
  811. return bool(self.subdevice_role)
  812. @property
  813. def is_child_device(self):
  814. return bool(self.subdevice_role is False)
  815. class ConsolePortTemplate(ComponentTemplateModel):
  816. """
  817. A template for a ConsolePort to be created for a new Device.
  818. """
  819. device_type = models.ForeignKey(
  820. to='dcim.DeviceType',
  821. on_delete=models.CASCADE,
  822. related_name='consoleport_templates'
  823. )
  824. name = models.CharField(
  825. max_length=50
  826. )
  827. class Meta:
  828. ordering = ['device_type', 'name']
  829. unique_together = ['device_type', 'name']
  830. def __str__(self):
  831. return self.name
  832. class ConsoleServerPortTemplate(ComponentTemplateModel):
  833. """
  834. A template for a ConsoleServerPort to be created for a new Device.
  835. """
  836. device_type = models.ForeignKey(
  837. to='dcim.DeviceType',
  838. on_delete=models.CASCADE,
  839. related_name='consoleserverport_templates'
  840. )
  841. name = models.CharField(
  842. max_length=50
  843. )
  844. class Meta:
  845. ordering = ['device_type', 'name']
  846. unique_together = ['device_type', 'name']
  847. def __str__(self):
  848. return self.name
  849. class PowerPortTemplate(ComponentTemplateModel):
  850. """
  851. A template for a PowerPort to be created for a new Device.
  852. """
  853. device_type = models.ForeignKey(
  854. to='dcim.DeviceType',
  855. on_delete=models.CASCADE,
  856. related_name='powerport_templates'
  857. )
  858. name = models.CharField(
  859. max_length=50
  860. )
  861. class Meta:
  862. ordering = ['device_type', 'name']
  863. unique_together = ['device_type', 'name']
  864. def __str__(self):
  865. return self.name
  866. class PowerOutletTemplate(ComponentTemplateModel):
  867. """
  868. A template for a PowerOutlet to be created for a new Device.
  869. """
  870. device_type = models.ForeignKey(
  871. to='dcim.DeviceType',
  872. on_delete=models.CASCADE,
  873. related_name='poweroutlet_templates'
  874. )
  875. name = models.CharField(
  876. max_length=50
  877. )
  878. class Meta:
  879. ordering = ['device_type', 'name']
  880. unique_together = ['device_type', 'name']
  881. def __str__(self):
  882. return self.name
  883. class InterfaceTemplate(ComponentTemplateModel):
  884. """
  885. A template for a physical data interface on a new Device.
  886. """
  887. device_type = models.ForeignKey(
  888. to='dcim.DeviceType',
  889. on_delete=models.CASCADE,
  890. related_name='interface_templates'
  891. )
  892. name = models.CharField(
  893. max_length=64
  894. )
  895. form_factor = models.PositiveSmallIntegerField(
  896. choices=IFACE_FF_CHOICES,
  897. default=IFACE_FF_10GE_SFP_PLUS
  898. )
  899. mgmt_only = models.BooleanField(
  900. default=False,
  901. verbose_name='Management only'
  902. )
  903. objects = InterfaceManager
  904. class Meta:
  905. ordering = ['device_type', 'name']
  906. unique_together = ['device_type', 'name']
  907. def __str__(self):
  908. return self.name
  909. class FrontPortTemplate(ComponentTemplateModel):
  910. """
  911. Template for a pass-through port on the front of a new Device.
  912. """
  913. device_type = models.ForeignKey(
  914. to='dcim.DeviceType',
  915. on_delete=models.CASCADE,
  916. related_name='frontport_templates'
  917. )
  918. name = models.CharField(
  919. max_length=64
  920. )
  921. type = models.PositiveSmallIntegerField(
  922. choices=PORT_TYPE_CHOICES
  923. )
  924. rear_port = models.ForeignKey(
  925. to='dcim.RearPortTemplate',
  926. on_delete=models.CASCADE,
  927. related_name='frontport_templates'
  928. )
  929. rear_port_position = models.PositiveSmallIntegerField(
  930. default=1,
  931. validators=[MinValueValidator(1), MaxValueValidator(64)]
  932. )
  933. class Meta:
  934. ordering = ['device_type', 'name']
  935. unique_together = [
  936. ['device_type', 'name'],
  937. ['rear_port', 'rear_port_position'],
  938. ]
  939. def __str__(self):
  940. return self.name
  941. def clean(self):
  942. # Validate rear port assignment
  943. if self.rear_port.device_type != self.device_type:
  944. raise ValidationError(
  945. "Rear port ({}) must belong to the same device type".format(self.rear_port)
  946. )
  947. # Validate rear port position assignment
  948. if self.rear_port_position > self.rear_port.positions:
  949. raise ValidationError(
  950. "Invalid rear port position ({}); rear port {} has only {} positions".format(
  951. self.rear_port_position, self.rear_port.name, self.rear_port.positions
  952. )
  953. )
  954. class RearPortTemplate(ComponentTemplateModel):
  955. """
  956. Template for a pass-through port on the rear of a new Device.
  957. """
  958. device_type = models.ForeignKey(
  959. to='dcim.DeviceType',
  960. on_delete=models.CASCADE,
  961. related_name='rearport_templates'
  962. )
  963. name = models.CharField(
  964. max_length=64
  965. )
  966. type = models.PositiveSmallIntegerField(
  967. choices=PORT_TYPE_CHOICES
  968. )
  969. positions = models.PositiveSmallIntegerField(
  970. default=1,
  971. validators=[MinValueValidator(1), MaxValueValidator(64)]
  972. )
  973. class Meta:
  974. ordering = ['device_type', 'name']
  975. unique_together = ['device_type', 'name']
  976. def __str__(self):
  977. return self.name
  978. class DeviceBayTemplate(ComponentTemplateModel):
  979. """
  980. A template for a DeviceBay to be created for a new parent Device.
  981. """
  982. device_type = models.ForeignKey(
  983. to='dcim.DeviceType',
  984. on_delete=models.CASCADE,
  985. related_name='device_bay_templates'
  986. )
  987. name = models.CharField(
  988. max_length=50
  989. )
  990. class Meta:
  991. ordering = ['device_type', 'name']
  992. unique_together = ['device_type', 'name']
  993. def __str__(self):
  994. return self.name
  995. #
  996. # Devices
  997. #
  998. class DeviceRole(ChangeLoggedModel):
  999. """
  1000. Devices are organized by functional role; for example, "Core Switch" or "File Server". Each DeviceRole is assigned a
  1001. color to be used when displaying rack elevations. The vm_role field determines whether the role is applicable to
  1002. virtual machines as well.
  1003. """
  1004. name = models.CharField(
  1005. max_length=50,
  1006. unique=True
  1007. )
  1008. slug = models.SlugField(
  1009. unique=True
  1010. )
  1011. color = ColorField()
  1012. vm_role = models.BooleanField(
  1013. default=True,
  1014. verbose_name='VM Role',
  1015. help_text='Virtual machines may be assigned to this role'
  1016. )
  1017. csv_headers = ['name', 'slug', 'color', 'vm_role']
  1018. class Meta:
  1019. ordering = ['name']
  1020. def __str__(self):
  1021. return self.name
  1022. def to_csv(self):
  1023. return (
  1024. self.name,
  1025. self.slug,
  1026. self.color,
  1027. self.vm_role,
  1028. )
  1029. class Platform(ChangeLoggedModel):
  1030. """
  1031. Platform refers to the software or firmware running on a Device. For example, "Cisco IOS-XR" or "Juniper Junos".
  1032. NetBox uses Platforms to determine how to interact with devices when pulling inventory data or other information by
  1033. specifying a NAPALM driver.
  1034. """
  1035. name = models.CharField(
  1036. max_length=50,
  1037. unique=True
  1038. )
  1039. slug = models.SlugField(
  1040. unique=True
  1041. )
  1042. manufacturer = models.ForeignKey(
  1043. to='dcim.Manufacturer',
  1044. on_delete=models.PROTECT,
  1045. related_name='platforms',
  1046. blank=True,
  1047. null=True,
  1048. help_text='Optionally limit this platform to devices of a certain manufacturer'
  1049. )
  1050. napalm_driver = models.CharField(
  1051. max_length=50,
  1052. blank=True,
  1053. verbose_name='NAPALM driver',
  1054. help_text='The name of the NAPALM driver to use when interacting with devices'
  1055. )
  1056. napalm_args = JSONField(
  1057. blank=True,
  1058. null=True,
  1059. verbose_name='NAPALM arguments',
  1060. help_text='Additional arguments to pass when initiating the NAPALM driver (JSON format)'
  1061. )
  1062. csv_headers = ['name', 'slug', 'manufacturer', 'napalm_driver', 'napalm_args']
  1063. class Meta:
  1064. ordering = ['name']
  1065. def __str__(self):
  1066. return self.name
  1067. def get_absolute_url(self):
  1068. return "{}?platform={}".format(reverse('dcim:device_list'), self.slug)
  1069. def to_csv(self):
  1070. return (
  1071. self.name,
  1072. self.slug,
  1073. self.manufacturer.name if self.manufacturer else None,
  1074. self.napalm_driver,
  1075. self.napalm_args,
  1076. )
  1077. class DeviceManager(NaturalOrderByManager):
  1078. natural_order_field = 'name'
  1079. class Device(ChangeLoggedModel, ConfigContextModel, CustomFieldModel):
  1080. """
  1081. A Device represents a piece of physical hardware mounted within a Rack. Each Device is assigned a DeviceType,
  1082. DeviceRole, and (optionally) a Platform. Device names are not required, however if one is set it must be unique.
  1083. Each Device must be assigned to a site, and optionally to a rack within that site. Associating a device with a
  1084. particular rack face or unit is optional (for example, vertically mounted PDUs do not consume rack units).
  1085. When a new Device is created, console/power/interface/device bay components are created along with it as dictated
  1086. by the component templates assigned to its DeviceType. Components can also be added, modified, or deleted after the
  1087. creation of a Device.
  1088. """
  1089. device_type = models.ForeignKey(
  1090. to='dcim.DeviceType',
  1091. on_delete=models.PROTECT,
  1092. related_name='instances'
  1093. )
  1094. device_role = models.ForeignKey(
  1095. to='dcim.DeviceRole',
  1096. on_delete=models.PROTECT,
  1097. related_name='devices'
  1098. )
  1099. tenant = models.ForeignKey(
  1100. to='tenancy.Tenant',
  1101. on_delete=models.PROTECT,
  1102. related_name='devices',
  1103. blank=True,
  1104. null=True
  1105. )
  1106. platform = models.ForeignKey(
  1107. to='dcim.Platform',
  1108. on_delete=models.SET_NULL,
  1109. related_name='devices',
  1110. blank=True,
  1111. null=True
  1112. )
  1113. name = NullableCharField(
  1114. max_length=64,
  1115. blank=True,
  1116. null=True,
  1117. unique=True
  1118. )
  1119. serial = models.CharField(
  1120. max_length=50,
  1121. blank=True,
  1122. verbose_name='Serial number'
  1123. )
  1124. asset_tag = NullableCharField(
  1125. max_length=50,
  1126. blank=True,
  1127. null=True,
  1128. unique=True,
  1129. verbose_name='Asset tag',
  1130. help_text='A unique tag used to identify this device'
  1131. )
  1132. site = models.ForeignKey(
  1133. to='dcim.Site',
  1134. on_delete=models.PROTECT,
  1135. related_name='devices'
  1136. )
  1137. rack = models.ForeignKey(
  1138. to='dcim.Rack',
  1139. on_delete=models.PROTECT,
  1140. related_name='devices',
  1141. blank=True,
  1142. null=True
  1143. )
  1144. position = models.PositiveSmallIntegerField(
  1145. blank=True,
  1146. null=True,
  1147. validators=[MinValueValidator(1)],
  1148. verbose_name='Position (U)',
  1149. help_text='The lowest-numbered unit occupied by the device'
  1150. )
  1151. face = models.PositiveSmallIntegerField(
  1152. blank=True,
  1153. null=True,
  1154. choices=RACK_FACE_CHOICES,
  1155. verbose_name='Rack face'
  1156. )
  1157. status = models.PositiveSmallIntegerField(
  1158. choices=DEVICE_STATUS_CHOICES,
  1159. default=DEVICE_STATUS_ACTIVE,
  1160. verbose_name='Status'
  1161. )
  1162. primary_ip4 = models.OneToOneField(
  1163. to='ipam.IPAddress',
  1164. on_delete=models.SET_NULL,
  1165. related_name='primary_ip4_for',
  1166. blank=True,
  1167. null=True,
  1168. verbose_name='Primary IPv4'
  1169. )
  1170. primary_ip6 = models.OneToOneField(
  1171. to='ipam.IPAddress',
  1172. on_delete=models.SET_NULL,
  1173. related_name='primary_ip6_for',
  1174. blank=True,
  1175. null=True,
  1176. verbose_name='Primary IPv6'
  1177. )
  1178. cluster = models.ForeignKey(
  1179. to='virtualization.Cluster',
  1180. on_delete=models.SET_NULL,
  1181. related_name='devices',
  1182. blank=True,
  1183. null=True
  1184. )
  1185. virtual_chassis = models.ForeignKey(
  1186. to='VirtualChassis',
  1187. on_delete=models.SET_NULL,
  1188. related_name='members',
  1189. blank=True,
  1190. null=True
  1191. )
  1192. vc_position = models.PositiveSmallIntegerField(
  1193. blank=True,
  1194. null=True,
  1195. validators=[MaxValueValidator(255)]
  1196. )
  1197. vc_priority = models.PositiveSmallIntegerField(
  1198. blank=True,
  1199. null=True,
  1200. validators=[MaxValueValidator(255)]
  1201. )
  1202. comments = models.TextField(
  1203. blank=True
  1204. )
  1205. custom_field_values = GenericRelation(
  1206. to='extras.CustomFieldValue',
  1207. content_type_field='obj_type',
  1208. object_id_field='obj_id'
  1209. )
  1210. images = GenericRelation(
  1211. to='extras.ImageAttachment'
  1212. )
  1213. objects = DeviceManager()
  1214. tags = TaggableManager()
  1215. csv_headers = [
  1216. 'name', 'device_role', 'tenant', 'manufacturer', 'model_name', 'platform', 'serial', 'asset_tag', 'status',
  1217. 'site', 'rack_group', 'rack_name', 'position', 'face', 'comments',
  1218. ]
  1219. class Meta:
  1220. ordering = ['name']
  1221. unique_together = [
  1222. ['rack', 'position', 'face'],
  1223. ['virtual_chassis', 'vc_position'],
  1224. ]
  1225. permissions = (
  1226. ('napalm_read', 'Read-only access to devices via NAPALM'),
  1227. ('napalm_write', 'Read/write access to devices via NAPALM'),
  1228. )
  1229. def __str__(self):
  1230. return self.display_name or super(Device, self).__str__()
  1231. def get_absolute_url(self):
  1232. return reverse('dcim:device', args=[self.pk])
  1233. def clean(self):
  1234. # Validate site/rack combination
  1235. if self.rack and self.site != self.rack.site:
  1236. raise ValidationError({
  1237. 'rack': "Rack {} does not belong to site {}.".format(self.rack, self.site),
  1238. })
  1239. if self.rack is None:
  1240. if self.face is not None:
  1241. raise ValidationError({
  1242. 'face': "Cannot select a rack face without assigning a rack.",
  1243. })
  1244. if self.position:
  1245. raise ValidationError({
  1246. 'face': "Cannot select a rack position without assigning a rack.",
  1247. })
  1248. # Validate position/face combination
  1249. if self.position and self.face is None:
  1250. raise ValidationError({
  1251. 'face': "Must specify rack face when defining rack position.",
  1252. })
  1253. # Prevent 0U devices from being assigned to a specific position
  1254. if self.position and self.device_type.u_height == 0:
  1255. raise ValidationError({
  1256. 'position': "A U0 device type ({}) cannot be assigned to a rack position.".format(self.device_type)
  1257. })
  1258. if self.rack:
  1259. try:
  1260. # Child devices cannot be assigned to a rack face/unit
  1261. if self.device_type.is_child_device and self.face is not None:
  1262. raise ValidationError({
  1263. 'face': "Child device types cannot be assigned to a rack face. This is an attribute of the "
  1264. "parent device."
  1265. })
  1266. if self.device_type.is_child_device and self.position:
  1267. raise ValidationError({
  1268. 'position': "Child device types cannot be assigned to a rack position. This is an attribute of "
  1269. "the parent device."
  1270. })
  1271. # Validate rack space
  1272. rack_face = self.face if not self.device_type.is_full_depth else None
  1273. exclude_list = [self.pk] if self.pk else []
  1274. try:
  1275. available_units = self.rack.get_available_units(
  1276. u_height=self.device_type.u_height, rack_face=rack_face, exclude=exclude_list
  1277. )
  1278. if self.position and self.position not in available_units:
  1279. raise ValidationError({
  1280. 'position': "U{} is already occupied or does not have sufficient space to accommodate a(n) "
  1281. "{} ({}U).".format(self.position, self.device_type, self.device_type.u_height)
  1282. })
  1283. except Rack.DoesNotExist:
  1284. pass
  1285. except DeviceType.DoesNotExist:
  1286. pass
  1287. # Validate primary IP addresses
  1288. vc_interfaces = self.vc_interfaces.all()
  1289. if self.primary_ip4:
  1290. if self.primary_ip4.interface in vc_interfaces:
  1291. pass
  1292. elif self.primary_ip4.nat_inside is not None and self.primary_ip4.nat_inside.interface in vc_interfaces:
  1293. pass
  1294. else:
  1295. raise ValidationError({
  1296. 'primary_ip4': "The specified IP address ({}) is not assigned to this device.".format(
  1297. self.primary_ip4),
  1298. })
  1299. if self.primary_ip6:
  1300. if self.primary_ip6.interface in vc_interfaces:
  1301. pass
  1302. elif self.primary_ip6.nat_inside is not None and self.primary_ip6.nat_inside.interface in vc_interfaces:
  1303. pass
  1304. else:
  1305. raise ValidationError({
  1306. 'primary_ip6': "The specified IP address ({}) is not assigned to this device.".format(
  1307. self.primary_ip6),
  1308. })
  1309. # Validate manufacturer/platform
  1310. if hasattr(self, 'device_type') and self.platform:
  1311. if self.platform.manufacturer and self.platform.manufacturer != self.device_type.manufacturer:
  1312. raise ValidationError({
  1313. 'platform': "The assigned platform is limited to {} device types, but this device's type belongs "
  1314. "to {}.".format(self.platform.manufacturer, self.device_type.manufacturer)
  1315. })
  1316. # A Device can only be assigned to a Cluster in the same Site (or no Site)
  1317. if self.cluster and self.cluster.site is not None and self.cluster.site != self.site:
  1318. raise ValidationError({
  1319. 'cluster': "The assigned cluster belongs to a different site ({})".format(self.cluster.site)
  1320. })
  1321. # Validate virtual chassis assignment
  1322. if self.virtual_chassis and self.vc_position is None:
  1323. raise ValidationError({
  1324. 'vc_position': "A device assigned to a virtual chassis must have its position defined."
  1325. })
  1326. def save(self, *args, **kwargs):
  1327. is_new = not bool(self.pk)
  1328. super(Device, self).save(*args, **kwargs)
  1329. # If this is a new Device, instantiate all of the related components per the DeviceType definition
  1330. if is_new:
  1331. ConsolePort.objects.bulk_create(
  1332. [ConsolePort(device=self, name=template.name) for template in
  1333. self.device_type.consoleport_templates.all()]
  1334. )
  1335. ConsoleServerPort.objects.bulk_create(
  1336. [ConsoleServerPort(device=self, name=template.name) for template in
  1337. self.device_type.consoleserverport_templates.all()]
  1338. )
  1339. PowerPort.objects.bulk_create(
  1340. [PowerPort(device=self, name=template.name) for template in
  1341. self.device_type.powerport_templates.all()]
  1342. )
  1343. PowerOutlet.objects.bulk_create(
  1344. [PowerOutlet(device=self, name=template.name) for template in
  1345. self.device_type.poweroutlet_templates.all()]
  1346. )
  1347. Interface.objects.bulk_create(
  1348. [Interface(device=self, name=template.name, form_factor=template.form_factor,
  1349. mgmt_only=template.mgmt_only) for template in self.device_type.interface_templates.all()]
  1350. )
  1351. RearPort.objects.bulk_create([
  1352. RearPort(
  1353. device=self,
  1354. name=template.name,
  1355. type=template.type,
  1356. positions=template.positions
  1357. ) for template in self.device_type.rearport_templates.all()
  1358. ])
  1359. FrontPort.objects.bulk_create([
  1360. FrontPort(
  1361. device=self,
  1362. name=template.name,
  1363. type=template.type,
  1364. rear_port=RearPort.objects.get(device=self, name=template.rear_port.name),
  1365. rear_port_position=template.rear_port_position,
  1366. ) for template in self.device_type.frontport_templates.all()
  1367. ])
  1368. DeviceBay.objects.bulk_create(
  1369. [DeviceBay(device=self, name=template.name) for template in
  1370. self.device_type.device_bay_templates.all()]
  1371. )
  1372. # Update Site and Rack assignment for any child Devices
  1373. Device.objects.filter(parent_bay__device=self).update(site=self.site, rack=self.rack)
  1374. def to_csv(self):
  1375. return (
  1376. self.name or '',
  1377. self.device_role.name,
  1378. self.tenant.name if self.tenant else None,
  1379. self.device_type.manufacturer.name,
  1380. self.device_type.model,
  1381. self.platform.name if self.platform else None,
  1382. self.serial,
  1383. self.asset_tag,
  1384. self.get_status_display(),
  1385. self.site.name,
  1386. self.rack.group.name if self.rack and self.rack.group else None,
  1387. self.rack.name if self.rack else None,
  1388. self.position,
  1389. self.get_face_display(),
  1390. self.comments,
  1391. )
  1392. @property
  1393. def display_name(self):
  1394. if self.name:
  1395. return self.name
  1396. elif self.virtual_chassis and self.virtual_chassis.master.name:
  1397. return "{}:{}".format(self.virtual_chassis.master, self.vc_position)
  1398. elif hasattr(self, 'device_type'):
  1399. return "{}".format(self.device_type)
  1400. return ""
  1401. @property
  1402. def identifier(self):
  1403. """
  1404. Return the device name if set; otherwise return the Device's primary key as {pk}
  1405. """
  1406. if self.name is not None:
  1407. return self.name
  1408. return '{{{}}}'.format(self.pk)
  1409. @property
  1410. def primary_ip(self):
  1411. if settings.PREFER_IPV4 and self.primary_ip4:
  1412. return self.primary_ip4
  1413. elif self.primary_ip6:
  1414. return self.primary_ip6
  1415. elif self.primary_ip4:
  1416. return self.primary_ip4
  1417. else:
  1418. return None
  1419. def get_vc_master(self):
  1420. """
  1421. If this Device is a VirtualChassis member, return the VC master. Otherwise, return None.
  1422. """
  1423. return self.virtual_chassis.master if self.virtual_chassis else None
  1424. @property
  1425. def vc_interfaces(self):
  1426. """
  1427. Return a QuerySet matching all Interfaces assigned to this Device or, if this Device is a VC master, to another
  1428. Device belonging to the same VirtualChassis.
  1429. """
  1430. filter = Q(device=self)
  1431. if self.virtual_chassis and self.virtual_chassis.master == self:
  1432. filter |= Q(device__virtual_chassis=self.virtual_chassis, mgmt_only=False)
  1433. return Interface.objects.filter(filter)
  1434. def get_children(self):
  1435. """
  1436. Return the set of child Devices installed in DeviceBays within this Device.
  1437. """
  1438. return Device.objects.filter(parent_bay__device=self.pk)
  1439. def get_status_class(self):
  1440. return STATUS_CLASSES[self.status]
  1441. #
  1442. # Console ports
  1443. #
  1444. class ConsolePort(CableTermination, ComponentModel):
  1445. """
  1446. A physical console port within a Device. ConsolePorts connect to ConsoleServerPorts.
  1447. """
  1448. device = models.ForeignKey(
  1449. to='dcim.Device',
  1450. on_delete=models.CASCADE,
  1451. related_name='consoleports'
  1452. )
  1453. name = models.CharField(
  1454. max_length=50
  1455. )
  1456. connected_endpoint = models.OneToOneField(
  1457. to='dcim.ConsoleServerPort',
  1458. on_delete=models.SET_NULL,
  1459. related_name='connected_endpoint',
  1460. blank=True,
  1461. null=True
  1462. )
  1463. connection_status = models.NullBooleanField(
  1464. choices=CONNECTION_STATUS_CHOICES,
  1465. default=CONNECTION_STATUS_CONNECTED
  1466. )
  1467. tags = TaggableManager()
  1468. csv_headers = ['console_server', 'connected_endpoint', 'device', 'console_port', 'connection_status']
  1469. class Meta:
  1470. ordering = ['device', 'name']
  1471. unique_together = ['device', 'name']
  1472. def __str__(self):
  1473. return self.name
  1474. def get_absolute_url(self):
  1475. return self.device.get_absolute_url()
  1476. def to_csv(self):
  1477. return (
  1478. self.connected_endpoint.device.identifier if self.connected_endpoint else None,
  1479. self.connected_endpoint.name if self.connected_endpoint else None,
  1480. self.device.identifier,
  1481. self.name,
  1482. self.get_connection_status_display(),
  1483. )
  1484. #
  1485. # Console server ports
  1486. #
  1487. class ConsoleServerPortManager(models.Manager):
  1488. def get_queryset(self):
  1489. # Pad any trailing digits to effect natural sorting
  1490. return super(ConsoleServerPortManager, self).get_queryset().extra(select={
  1491. 'name_padded': r"CONCAT(REGEXP_REPLACE(dcim_consoleserverport.name, '\d+$', ''), "
  1492. r"LPAD(SUBSTRING(dcim_consoleserverport.name FROM '\d+$'), 8, '0'))",
  1493. }).order_by('device', 'name_padded')
  1494. class ConsoleServerPort(CableTermination, ComponentModel):
  1495. """
  1496. A physical port within a Device (typically a designated console server) which provides access to ConsolePorts.
  1497. """
  1498. device = models.ForeignKey(
  1499. to='dcim.Device',
  1500. on_delete=models.CASCADE,
  1501. related_name='consoleserverports'
  1502. )
  1503. name = models.CharField(
  1504. max_length=50
  1505. )
  1506. objects = ConsoleServerPortManager()
  1507. tags = TaggableManager()
  1508. class Meta:
  1509. unique_together = ['device', 'name']
  1510. def __str__(self):
  1511. return self.name
  1512. def get_absolute_url(self):
  1513. return self.device.get_absolute_url()
  1514. #
  1515. # Power ports
  1516. #
  1517. class PowerPort(CableTermination, ComponentModel):
  1518. """
  1519. A physical power supply (intake) port within a Device. PowerPorts connect to PowerOutlets.
  1520. """
  1521. device = models.ForeignKey(
  1522. to='dcim.Device',
  1523. on_delete=models.CASCADE,
  1524. related_name='powerports'
  1525. )
  1526. name = models.CharField(
  1527. max_length=50
  1528. )
  1529. connected_endpoint = models.OneToOneField(
  1530. to='dcim.PowerOutlet',
  1531. on_delete=models.SET_NULL,
  1532. related_name='connected_endpoint',
  1533. blank=True,
  1534. null=True
  1535. )
  1536. connection_status = models.NullBooleanField(
  1537. choices=CONNECTION_STATUS_CHOICES,
  1538. default=CONNECTION_STATUS_CONNECTED
  1539. )
  1540. tags = TaggableManager()
  1541. csv_headers = ['pdu', 'connected_endpoint', 'device', 'power_port', 'connection_status']
  1542. class Meta:
  1543. ordering = ['device', 'name']
  1544. unique_together = ['device', 'name']
  1545. def __str__(self):
  1546. return self.name
  1547. def get_absolute_url(self):
  1548. return self.device.get_absolute_url()
  1549. def to_csv(self):
  1550. return (
  1551. self.connected_endpoint.device.identifier if self.connected_endpoint else None,
  1552. self.connected_endpoint.name if self.connected_endpoint else None,
  1553. self.device.identifier,
  1554. self.name,
  1555. self.get_connection_status_display(),
  1556. )
  1557. #
  1558. # Power outlets
  1559. #
  1560. class PowerOutletManager(models.Manager):
  1561. def get_queryset(self):
  1562. # Pad any trailing digits to effect natural sorting
  1563. return super(PowerOutletManager, self).get_queryset().extra(select={
  1564. 'name_padded': r"CONCAT(REGEXP_REPLACE(dcim_poweroutlet.name, '\d+$', ''), "
  1565. r"LPAD(SUBSTRING(dcim_poweroutlet.name FROM '\d+$'), 8, '0'))",
  1566. }).order_by('device', 'name_padded')
  1567. class PowerOutlet(CableTermination, ComponentModel):
  1568. """
  1569. A physical power outlet (output) within a Device which provides power to a PowerPort.
  1570. """
  1571. device = models.ForeignKey(
  1572. to='dcim.Device',
  1573. on_delete=models.CASCADE,
  1574. related_name='poweroutlets'
  1575. )
  1576. name = models.CharField(
  1577. max_length=50
  1578. )
  1579. objects = PowerOutletManager()
  1580. tags = TaggableManager()
  1581. class Meta:
  1582. unique_together = ['device', 'name']
  1583. def __str__(self):
  1584. return self.name
  1585. def get_absolute_url(self):
  1586. return self.device.get_absolute_url()
  1587. #
  1588. # Interfaces
  1589. #
  1590. class Interface(CableTermination, ComponentModel):
  1591. """
  1592. A network interface within a Device or VirtualMachine. A physical Interface can connect to exactly one other
  1593. Interface.
  1594. """
  1595. device = models.ForeignKey(
  1596. to='Device',
  1597. on_delete=models.CASCADE,
  1598. related_name='interfaces',
  1599. null=True,
  1600. blank=True
  1601. )
  1602. virtual_machine = models.ForeignKey(
  1603. to='virtualization.VirtualMachine',
  1604. on_delete=models.CASCADE,
  1605. related_name='interfaces',
  1606. null=True,
  1607. blank=True
  1608. )
  1609. name = models.CharField(
  1610. max_length=64
  1611. )
  1612. _connected_interface = models.OneToOneField(
  1613. to='self',
  1614. on_delete=models.SET_NULL,
  1615. related_name='+',
  1616. blank=True,
  1617. null=True
  1618. )
  1619. _connected_circuittermination = models.OneToOneField(
  1620. to='circuits.CircuitTermination',
  1621. on_delete=models.SET_NULL,
  1622. related_name='+',
  1623. blank=True,
  1624. null=True
  1625. )
  1626. connection_status = models.NullBooleanField(
  1627. choices=CONNECTION_STATUS_CHOICES,
  1628. default=CONNECTION_STATUS_CONNECTED
  1629. )
  1630. lag = models.ForeignKey(
  1631. to='self',
  1632. on_delete=models.SET_NULL,
  1633. related_name='member_interfaces',
  1634. null=True,
  1635. blank=True,
  1636. verbose_name='Parent LAG'
  1637. )
  1638. form_factor = models.PositiveSmallIntegerField(
  1639. choices=IFACE_FF_CHOICES,
  1640. default=IFACE_FF_10GE_SFP_PLUS
  1641. )
  1642. enabled = models.BooleanField(
  1643. default=True
  1644. )
  1645. mac_address = MACAddressField(
  1646. null=True,
  1647. blank=True,
  1648. verbose_name='MAC Address'
  1649. )
  1650. mtu = models.PositiveIntegerField(
  1651. blank=True,
  1652. null=True,
  1653. validators=[MinValueValidator(1), MaxValueValidator(65536)],
  1654. verbose_name='MTU'
  1655. )
  1656. mgmt_only = models.BooleanField(
  1657. default=False,
  1658. verbose_name='OOB Management',
  1659. help_text='This interface is used only for out-of-band management'
  1660. )
  1661. description = models.CharField(
  1662. max_length=100,
  1663. blank=True
  1664. )
  1665. mode = models.PositiveSmallIntegerField(
  1666. choices=IFACE_MODE_CHOICES,
  1667. blank=True,
  1668. null=True
  1669. )
  1670. untagged_vlan = models.ForeignKey(
  1671. to='ipam.VLAN',
  1672. on_delete=models.SET_NULL,
  1673. related_name='interfaces_as_untagged',
  1674. null=True,
  1675. blank=True,
  1676. verbose_name='Untagged VLAN'
  1677. )
  1678. tagged_vlans = models.ManyToManyField(
  1679. to='ipam.VLAN',
  1680. related_name='interfaces_as_tagged',
  1681. blank=True,
  1682. verbose_name='Tagged VLANs'
  1683. )
  1684. objects = InterfaceManager()
  1685. tags = TaggableManager()
  1686. class Meta:
  1687. ordering = ['device', 'name']
  1688. unique_together = ['device', 'name']
  1689. def __str__(self):
  1690. return self.name
  1691. def get_absolute_url(self):
  1692. return reverse('dcim:interface', kwargs={'pk': self.pk})
  1693. def clean(self):
  1694. # An Interface must belong to a Device *or* to a VirtualMachine
  1695. if self.device and self.virtual_machine:
  1696. raise ValidationError("An interface cannot belong to both a device and a virtual machine.")
  1697. if not self.device and not self.virtual_machine:
  1698. raise ValidationError("An interface must belong to either a device or a virtual machine.")
  1699. # VM interfaces must be virtual
  1700. if self.virtual_machine and self.form_factor is not IFACE_FF_VIRTUAL:
  1701. raise ValidationError({
  1702. 'form_factor': "Virtual machines can only have virtual interfaces."
  1703. })
  1704. # Virtual interfaces cannot be connected
  1705. if self.form_factor in NONCONNECTABLE_IFACE_TYPES and (
  1706. self.cable or getattr(self, 'circuit_termination', False)
  1707. ):
  1708. raise ValidationError({
  1709. 'form_factor': "Virtual and wireless interfaces cannot be connected to another interface or circuit. "
  1710. "Disconnect the interface or choose a suitable form factor."
  1711. })
  1712. # An interface's LAG must belong to the same device (or VC master)
  1713. if self.lag and self.lag.device not in [self.device, self.device.get_vc_master()]:
  1714. raise ValidationError({
  1715. 'lag': "The selected LAG interface ({}) belongs to a different device ({}).".format(
  1716. self.lag.name, self.lag.device.name
  1717. )
  1718. })
  1719. # A virtual interface cannot have a parent LAG
  1720. if self.form_factor in NONCONNECTABLE_IFACE_TYPES and self.lag is not None:
  1721. raise ValidationError({
  1722. 'lag': "{} interfaces cannot have a parent LAG interface.".format(self.get_form_factor_display())
  1723. })
  1724. # Only a LAG can have LAG members
  1725. if self.form_factor != IFACE_FF_LAG and self.member_interfaces.exists():
  1726. raise ValidationError({
  1727. 'form_factor': "Cannot change interface form factor; it has LAG members ({}).".format(
  1728. ", ".join([iface.name for iface in self.member_interfaces.all()])
  1729. )
  1730. })
  1731. # Validate untagged VLAN
  1732. if self.untagged_vlan and self.untagged_vlan.site not in [self.parent.site, None]:
  1733. raise ValidationError({
  1734. 'untagged_vlan': "The untagged VLAN ({}) must belong to the same site as the interface's parent "
  1735. "device/VM, or it must be global".format(self.untagged_vlan)
  1736. })
  1737. def save(self, *args, **kwargs):
  1738. # Remove untagged VLAN assignment for non-802.1Q interfaces
  1739. if self.mode is None:
  1740. self.untagged_vlan = None
  1741. # Only "tagged" interfaces may have tagged VLANs assigned. ("tagged all" implies all VLANs are assigned.)
  1742. if self.pk and self.mode is not IFACE_MODE_TAGGED:
  1743. self.tagged_vlans.clear()
  1744. return super(Interface, self).save(*args, **kwargs)
  1745. def log_change(self, user, request_id, action):
  1746. """
  1747. Include the connected Interface (if any).
  1748. """
  1749. # It's possible that an Interface can be deleted _after_ its parent Device/VM, in which case trying to resolve
  1750. # the component parent will raise DoesNotExist. For more discussion, see
  1751. # https://github.com/digitalocean/netbox/issues/2323
  1752. try:
  1753. parent_obj = self.device or self.virtual_machine
  1754. except ObjectDoesNotExist:
  1755. parent_obj = None
  1756. ObjectChange(
  1757. user=user,
  1758. request_id=request_id,
  1759. changed_object=self,
  1760. related_object=parent_obj,
  1761. action=action,
  1762. object_data=serialize_object(self)
  1763. ).save()
  1764. @property
  1765. def connected_endpoint(self):
  1766. if self._connected_interface:
  1767. return self._connected_interface
  1768. return self._connected_circuittermination
  1769. @connected_endpoint.setter
  1770. def connected_endpoint(self, value):
  1771. from circuits.models import CircuitTermination
  1772. if value is None:
  1773. self._connected_interface = None
  1774. self._connected_circuittermination = None
  1775. elif isinstance(value, Interface):
  1776. self._connected_interface = value
  1777. self._connected_circuittermination = None
  1778. elif isinstance(value, CircuitTermination):
  1779. self._connected_interface = None
  1780. self._connected_circuittermination = value
  1781. else:
  1782. raise ValueError(
  1783. "Connected endpoint must be an Interface or CircuitTermination, not {}.".format(type(value))
  1784. )
  1785. @property
  1786. def parent(self):
  1787. return self.device or self.virtual_machine
  1788. @property
  1789. def is_connectable(self):
  1790. return self.form_factor not in NONCONNECTABLE_IFACE_TYPES
  1791. @property
  1792. def is_virtual(self):
  1793. return self.form_factor in VIRTUAL_IFACE_TYPES
  1794. @property
  1795. def is_wireless(self):
  1796. return self.form_factor in WIRELESS_IFACE_TYPES
  1797. @property
  1798. def is_lag(self):
  1799. return self.form_factor == IFACE_FF_LAG
  1800. #
  1801. # Pass-through ports
  1802. #
  1803. class FrontPort(CableTermination, ComponentModel):
  1804. """
  1805. A pass-through port on the front of a Device.
  1806. """
  1807. device = models.ForeignKey(
  1808. to='dcim.Device',
  1809. on_delete=models.CASCADE,
  1810. related_name='frontports'
  1811. )
  1812. name = models.CharField(
  1813. max_length=64
  1814. )
  1815. type = models.PositiveSmallIntegerField(
  1816. choices=PORT_TYPE_CHOICES
  1817. )
  1818. rear_port = models.ForeignKey(
  1819. to='dcim.RearPort',
  1820. on_delete=models.CASCADE,
  1821. related_name='frontports'
  1822. )
  1823. rear_port_position = models.PositiveSmallIntegerField(
  1824. default=1,
  1825. validators=[MinValueValidator(1), MaxValueValidator(64)]
  1826. )
  1827. tags = TaggableManager()
  1828. class Meta:
  1829. ordering = ['device', 'name']
  1830. unique_together = [
  1831. ['device', 'name'],
  1832. ['rear_port', 'rear_port_position'],
  1833. ]
  1834. def __str__(self):
  1835. return self.name
  1836. def clean(self):
  1837. # Validate rear port assignment
  1838. if self.rear_port.device != self.device:
  1839. raise ValidationError(
  1840. "Rear port ({}) must belong to the same device".format(self.rear_port)
  1841. )
  1842. # Validate rear port position assignment
  1843. if self.rear_port_position > self.rear_port.positions:
  1844. raise ValidationError(
  1845. "Invalid rear port position ({}); rear port {} has only {} positions".format(
  1846. self.rear_port_position, self.rear_port.name, self.rear_port.positions
  1847. )
  1848. )
  1849. class RearPort(CableTermination, ComponentModel):
  1850. """
  1851. A pass-through port on the rear of a Device.
  1852. """
  1853. device = models.ForeignKey(
  1854. to='dcim.Device',
  1855. on_delete=models.CASCADE,
  1856. related_name='rearports'
  1857. )
  1858. name = models.CharField(
  1859. max_length=64
  1860. )
  1861. type = models.PositiveSmallIntegerField(
  1862. choices=PORT_TYPE_CHOICES
  1863. )
  1864. positions = models.PositiveSmallIntegerField(
  1865. default=1,
  1866. validators=[MinValueValidator(1), MaxValueValidator(64)]
  1867. )
  1868. tags = TaggableManager()
  1869. class Meta:
  1870. ordering = ['device', 'name']
  1871. unique_together = ['device', 'name']
  1872. def __str__(self):
  1873. return self.name
  1874. #
  1875. # Device bays
  1876. #
  1877. class DeviceBay(ComponentModel):
  1878. """
  1879. An empty space within a Device which can house a child device
  1880. """
  1881. device = models.ForeignKey(
  1882. to='dcim.Device',
  1883. on_delete=models.CASCADE,
  1884. related_name='device_bays'
  1885. )
  1886. name = models.CharField(
  1887. max_length=50,
  1888. verbose_name='Name'
  1889. )
  1890. installed_device = models.OneToOneField(
  1891. to='dcim.Device',
  1892. on_delete=models.SET_NULL,
  1893. related_name='parent_bay',
  1894. blank=True,
  1895. null=True
  1896. )
  1897. tags = TaggableManager()
  1898. class Meta:
  1899. ordering = ['device', 'name']
  1900. unique_together = ['device', 'name']
  1901. def __str__(self):
  1902. return '{} - {}'.format(self.device.name, self.name)
  1903. def get_absolute_url(self):
  1904. return self.device.get_absolute_url()
  1905. def clean(self):
  1906. # Validate that the parent Device can have DeviceBays
  1907. if not self.device.device_type.is_parent_device:
  1908. raise ValidationError("This type of device ({}) does not support device bays.".format(
  1909. self.device.device_type
  1910. ))
  1911. # Cannot install a device into itself, obviously
  1912. if self.device == self.installed_device:
  1913. raise ValidationError("Cannot install a device into itself.")
  1914. #
  1915. # Inventory items
  1916. #
  1917. class InventoryItem(ComponentModel):
  1918. """
  1919. An InventoryItem represents a serialized piece of hardware within a Device, such as a line card or power supply.
  1920. InventoryItems are used only for inventory purposes.
  1921. """
  1922. device = models.ForeignKey(
  1923. to='dcim.Device',
  1924. on_delete=models.CASCADE,
  1925. related_name='inventory_items'
  1926. )
  1927. parent = models.ForeignKey(
  1928. to='self',
  1929. on_delete=models.CASCADE,
  1930. related_name='child_items',
  1931. blank=True,
  1932. null=True
  1933. )
  1934. name = models.CharField(
  1935. max_length=50,
  1936. verbose_name='Name'
  1937. )
  1938. manufacturer = models.ForeignKey(
  1939. to='dcim.Manufacturer',
  1940. on_delete=models.PROTECT,
  1941. related_name='inventory_items',
  1942. blank=True,
  1943. null=True
  1944. )
  1945. part_id = models.CharField(
  1946. max_length=50,
  1947. verbose_name='Part ID',
  1948. blank=True
  1949. )
  1950. serial = models.CharField(
  1951. max_length=50,
  1952. verbose_name='Serial number',
  1953. blank=True
  1954. )
  1955. asset_tag = NullableCharField(
  1956. max_length=50,
  1957. unique=True,
  1958. blank=True,
  1959. null=True,
  1960. verbose_name='Asset tag',
  1961. help_text='A unique tag used to identify this item'
  1962. )
  1963. discovered = models.BooleanField(
  1964. default=False,
  1965. verbose_name='Discovered'
  1966. )
  1967. description = models.CharField(
  1968. max_length=100,
  1969. blank=True
  1970. )
  1971. tags = TaggableManager()
  1972. csv_headers = [
  1973. 'device', 'name', 'manufacturer', 'part_id', 'serial', 'asset_tag', 'discovered', 'description',
  1974. ]
  1975. class Meta:
  1976. ordering = ['device__id', 'parent__id', 'name']
  1977. unique_together = ['device', 'parent', 'name']
  1978. def __str__(self):
  1979. return self.name
  1980. def get_absolute_url(self):
  1981. return self.device.get_absolute_url()
  1982. def to_csv(self):
  1983. return (
  1984. self.device.name or '{' + self.device.pk + '}',
  1985. self.name,
  1986. self.manufacturer.name if self.manufacturer else None,
  1987. self.part_id,
  1988. self.serial,
  1989. self.asset_tag,
  1990. self.discovered,
  1991. self.description,
  1992. )
  1993. #
  1994. # Virtual chassis
  1995. #
  1996. class VirtualChassis(ChangeLoggedModel):
  1997. """
  1998. A collection of Devices which operate with a shared control plane (e.g. a switch stack).
  1999. """
  2000. master = models.OneToOneField(
  2001. to='Device',
  2002. on_delete=models.PROTECT,
  2003. related_name='vc_master_for'
  2004. )
  2005. domain = models.CharField(
  2006. max_length=30,
  2007. blank=True
  2008. )
  2009. tags = TaggableManager()
  2010. csv_headers = ['master', 'domain']
  2011. class Meta:
  2012. ordering = ['master']
  2013. verbose_name_plural = 'virtual chassis'
  2014. def __str__(self):
  2015. return str(self.master) if hasattr(self, 'master') else 'New Virtual Chassis'
  2016. def get_absolute_url(self):
  2017. return self.master.get_absolute_url()
  2018. def clean(self):
  2019. # Verify that the selected master device has been assigned to this VirtualChassis. (Skip when creating a new
  2020. # VirtualChassis.)
  2021. if self.pk and self.master not in self.members.all():
  2022. raise ValidationError({
  2023. 'master': "The selected master is not assigned to this virtual chassis."
  2024. })
  2025. def to_csv(self):
  2026. return (
  2027. self.master,
  2028. self.domain,
  2029. )
  2030. #
  2031. # Cables
  2032. #
  2033. class Cable(ChangeLoggedModel):
  2034. """
  2035. A physical connection between two endpoints.
  2036. """
  2037. termination_a_type = models.ForeignKey(
  2038. to=ContentType,
  2039. limit_choices_to={'model__in': CABLE_TERMINATION_TYPES},
  2040. on_delete=models.PROTECT,
  2041. related_name='+'
  2042. )
  2043. termination_a_id = models.PositiveIntegerField()
  2044. termination_a = GenericForeignKey(
  2045. ct_field='termination_a_type',
  2046. fk_field='termination_a_id'
  2047. )
  2048. termination_b_type = models.ForeignKey(
  2049. to=ContentType,
  2050. limit_choices_to={'model__in': CABLE_TERMINATION_TYPES},
  2051. on_delete=models.PROTECT,
  2052. related_name='+'
  2053. )
  2054. termination_b_id = models.PositiveIntegerField()
  2055. termination_b = GenericForeignKey(
  2056. ct_field='termination_b_type',
  2057. fk_field='termination_b_id'
  2058. )
  2059. type = models.PositiveSmallIntegerField(
  2060. choices=CABLE_TYPE_CHOICES,
  2061. blank=True,
  2062. null=True
  2063. )
  2064. status = models.BooleanField(
  2065. choices=CONNECTION_STATUS_CHOICES,
  2066. default=CONNECTION_STATUS_CONNECTED
  2067. )
  2068. label = models.CharField(
  2069. max_length=100,
  2070. blank=True
  2071. )
  2072. color = ColorField(
  2073. blank=True
  2074. )
  2075. length = models.PositiveSmallIntegerField(
  2076. blank=True,
  2077. null=True
  2078. )
  2079. length_unit = models.CharField(
  2080. choices=CABLE_LENGTH_UNIT_CHOICES,
  2081. max_length=2,
  2082. blank=True
  2083. )
  2084. # Stores the normalized length (in meters) for database ordering
  2085. _abs_length = models.DecimalField(
  2086. max_digits=10,
  2087. decimal_places=4,
  2088. blank=True,
  2089. null=True
  2090. )
  2091. csv_headers = [
  2092. 'termination_a_type', 'termination_a_id', 'termination_b_type', 'termination_b_id', 'type', 'status', 'label',
  2093. 'color', 'length', 'length_unit',
  2094. ]
  2095. class Meta:
  2096. ordering = ['pk']
  2097. unique_together = (
  2098. ('termination_a_type', 'termination_a_id'),
  2099. ('termination_b_type', 'termination_b_id'),
  2100. )
  2101. def __init__(self, *args, **kwargs):
  2102. super(Cable, self).__init__(*args, **kwargs)
  2103. # Create an ID string for use by __str__(). We have to save a copy of pk since it's nullified after .delete()
  2104. # is called.
  2105. self.id_string = '#{}'.format(self.pk)
  2106. def __str__(self):
  2107. return self.label or self.id_string
  2108. def get_absolute_url(self):
  2109. return reverse('dcim:cable', args=[self.pk])
  2110. def clean(self):
  2111. # Check that termination types are compatible
  2112. type_a = self.termination_a_type.model
  2113. type_b = self.termination_b_type.model
  2114. if type_b not in COMPATIBLE_TERMINATION_TYPES.get(type_a):
  2115. raise ValidationError("Incompatible termination types: {} and {}".format(
  2116. self.termination_a_type, self.termination_b_type
  2117. ))
  2118. # Check for an existing Cable connected to either termination object
  2119. if self.termination_a.cable not in (None, self):
  2120. raise ValidationError("{} already has a cable attached (#{})".format(
  2121. self.termination_a, self.termination_a.cable_id
  2122. ))
  2123. if self.termination_b.cable not in (None, self):
  2124. raise ValidationError("{} already has a cable attached (#{})".format(
  2125. self.termination_b, self.termination_b.cable_id
  2126. ))
  2127. # Validate length and length_unit
  2128. if self.length and not self.length_unit:
  2129. raise ValidationError("Must specify a unit when setting a cable length")
  2130. if self.length_unit and self.length is None:
  2131. self.length_unit = ''
  2132. def save(self, *args, **kwargs):
  2133. # Store the given length (if any) in meters for use in database ordering
  2134. if self.length and self.length_unit:
  2135. self._abs_length = to_meters(self.length, self.length_unit)
  2136. super(Cable, self).save(*args, **kwargs)
  2137. def to_csv(self):
  2138. return (
  2139. '{}.{}'.format(self.termination_a_type.app_label, self.termination_a_type.model),
  2140. self.termination_a_id,
  2141. '{}.{}'.format(self.termination_b_type.app_label, self.termination_b_type.model),
  2142. self.termination_b_id,
  2143. self.get_type_display(),
  2144. self.get_status_display(),
  2145. self.label,
  2146. self.color,
  2147. self.length,
  2148. self.length_unit,
  2149. )
  2150. def get_path_endpoints(self):
  2151. """
  2152. Traverse both ends of a cable path and return its connected endpoints. Note that one or both endpoints may be
  2153. None.
  2154. """
  2155. def trace_cable(termination, position=1):
  2156. # Given a front port, follow the cable connected to the corresponding rear port/position
  2157. if isinstance(termination, FrontPort):
  2158. peer_port = termination.rear_port
  2159. position = termination.rear_port_position
  2160. # Given a rear port/position, follow the cable connected to the corresponding front port
  2161. elif isinstance(termination, RearPort):
  2162. if position not in range(1, termination.positions + 1):
  2163. raise Exception("Invalid position for {} ({} positions): {})".format(
  2164. termination, termination.positions, position
  2165. ))
  2166. peer_port = FrontPort.objects.get(
  2167. rear_port=termination,
  2168. rear_port_position=position,
  2169. )
  2170. position = 1
  2171. # Termination is not a pass-through port, so we've reached the end of the path
  2172. else:
  2173. return termination
  2174. # Find the cable (if any) attached to the peer port
  2175. next_cable = peer_port.cable
  2176. # If no cable exists, return None
  2177. if next_cable is None:
  2178. return None
  2179. far_end = next_cable.termination_b if next_cable.termination_a == peer_port else next_cable.termination_a
  2180. # Return the far side termination of the cable
  2181. return trace_cable(far_end, position)
  2182. return trace_cable(self.termination_a), trace_cable(self.termination_b)