models.py 80 KB

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