models.py 80 KB

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