models.py 95 KB

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