models.py 93 KB

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