models.py 100 KB

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