models.py 74 KB

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