models.py 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736
  1. from __future__ import unicode_literals
  2. from collections import OrderedDict
  3. from itertools import count, groupby
  4. from django.conf import settings
  5. from django.contrib.auth.models import User
  6. from django.contrib.contenttypes.fields import GenericRelation
  7. from django.contrib.postgres.fields import ArrayField
  8. from django.core.exceptions import ValidationError
  9. from django.core.validators import MaxValueValidator, MinValueValidator
  10. from django.db import models
  11. from django.db.models import Count, Q, ObjectDoesNotExist
  12. from django.urls import reverse
  13. from django.utils.encoding import python_2_unicode_compatible
  14. from mptt.models import MPTTModel, TreeForeignKey
  15. from timezone_field import TimeZoneField
  16. from circuits.models import Circuit
  17. from extras.models import CustomFieldModel, CustomFieldValue, ImageAttachment
  18. from extras.rpc import RPC_CLIENTS
  19. from tenancy.models import Tenant
  20. from utilities.fields import ColorField, NullableCharField
  21. from utilities.managers import NaturalOrderByManager
  22. from utilities.models import CreatedUpdatedModel
  23. from .constants import *
  24. from .fields import ASNField, MACAddressField
  25. from .querysets import InterfaceQuerySet
  26. #
  27. # Regions
  28. #
  29. @python_2_unicode_compatible
  30. class Region(MPTTModel):
  31. """
  32. Sites can be grouped within geographic Regions.
  33. """
  34. parent = TreeForeignKey(
  35. 'self', null=True, blank=True, related_name='children', db_index=True, on_delete=models.CASCADE
  36. )
  37. name = models.CharField(max_length=50, unique=True)
  38. slug = models.SlugField(unique=True)
  39. csv_headers = ['name', 'slug', 'parent']
  40. class MPTTMeta:
  41. order_insertion_by = ['name']
  42. def __str__(self):
  43. return self.name
  44. def get_absolute_url(self):
  45. return "{}?region={}".format(reverse('dcim:site_list'), self.slug)
  46. def to_csv(self):
  47. return (
  48. self.name,
  49. self.slug,
  50. self.parent.name if self.parent else None,
  51. )
  52. #
  53. # Facilities
  54. #
  55. class FacilityManager(NaturalOrderByManager):
  56. def get_queryset(self):
  57. return self.natural_order_by('name')
  58. @python_2_unicode_compatible
  59. class Facility(CreatedUpdatedModel, CustomFieldModel):
  60. """
  61. A Facility represents a building, typically a datacenter, that can host Sites from several tenants.
  62. """
  63. name = models.CharField(max_length=50, unique=True)
  64. slug = models.SlugField(unique=True)
  65. tenant = models.ForeignKey(Tenant, related_name='facilities', blank=True, null=True, on_delete=models.PROTECT)
  66. description = models.CharField(max_length=100, blank=True)
  67. peeringdb_id = models.PositiveIntegerField(blank=True, null=True, verbose_name='Facility ID in PeeringDB')
  68. city = models.CharField(max_length=100, blank=True)
  69. latitude = models.FloatField(blank=True, null=True)
  70. longitude = models.FloatField(blank=True, null=True)
  71. physical_address = models.CharField(max_length=200, blank=True)
  72. shipping_address = models.CharField(max_length=200, blank=True)
  73. contact_name = models.CharField(max_length=50, blank=True)
  74. contact_phone = models.CharField(max_length=20, blank=True)
  75. contact_email = models.EmailField(blank=True, verbose_name="Contact E-mail")
  76. comments = models.TextField(blank=True)
  77. custom_field_values = GenericRelation(CustomFieldValue, content_type_field='obj_type', object_id_field='obj_id')
  78. objects = FacilityManager()
  79. csv_headers = [
  80. 'name', 'slug', 'tenant', 'description', 'peeringdb_id', 'city', 'latitude', 'longitude',
  81. 'physical_address', 'shipping_address', 'contact_name', 'contact_phone', 'contact_email', 'comments',
  82. ]
  83. class Meta:
  84. ordering = ['name']
  85. verbose_name_plural = 'facilities'
  86. def __str__(self):
  87. return self.name
  88. def get_absolute_url(self):
  89. return reverse('dcim:facility', args=[self.slug])
  90. def to_csv(self):
  91. return (
  92. self.name,
  93. self.slug,
  94. self.tenant.name if self.tenant else None,
  95. self.description,
  96. self.peeringdb_id,
  97. self.city,
  98. self.latitude,
  99. self.longitude,
  100. self.physical_address,
  101. self.shipping_address,
  102. self.contact_name,
  103. self.contact_phone,
  104. self.contact_email,
  105. self.comments,
  106. )
  107. @property
  108. def count_sites(self):
  109. return self.sites.count()
  110. #
  111. # Sites
  112. #
  113. class SiteManager(NaturalOrderByManager):
  114. def get_queryset(self):
  115. return self.natural_order_by('name')
  116. @python_2_unicode_compatible
  117. class Site(CreatedUpdatedModel, CustomFieldModel):
  118. """
  119. A Site represents a geographic location within a network; typically a building or campus.
  120. """
  121. name = models.CharField(max_length=50, unique=True)
  122. slug = models.SlugField(unique=True)
  123. status = models.PositiveSmallIntegerField(choices=SITE_STATUS_CHOICES, default=SITE_STATUS_ACTIVE)
  124. region = models.ForeignKey('Region', related_name='sites', blank=True, null=True, on_delete=models.SET_NULL)
  125. tenant = models.ForeignKey(Tenant, related_name='sites', blank=True, null=True, on_delete=models.PROTECT)
  126. facility = models.ForeignKey('Facility', related_name='sites', blank=True, null=True, on_delete=models.SET_NULL)
  127. asn = ASNField(blank=True, null=True, verbose_name='ASN')
  128. time_zone = TimeZoneField(blank=True)
  129. description = models.CharField(max_length=100, blank=True)
  130. comments = models.TextField(blank=True)
  131. custom_field_values = GenericRelation(CustomFieldValue, content_type_field='obj_type', object_id_field='obj_id')
  132. images = GenericRelation(ImageAttachment)
  133. objects = SiteManager()
  134. csv_headers = [
  135. 'name', 'slug', 'status', 'region', 'tenant', 'facility', 'asn', 'time_zone', 'description', 'comments',
  136. ]
  137. class Meta:
  138. ordering = ['name']
  139. def __str__(self):
  140. return self.name
  141. def get_absolute_url(self):
  142. return reverse('dcim:site', args=[self.slug])
  143. def to_csv(self):
  144. return (
  145. self.name,
  146. self.slug,
  147. self.get_status_display(),
  148. self.region.name if self.region else None,
  149. self.tenant.name if self.tenant else None,
  150. self.facility.name if self.facility else None,
  151. self.asn,
  152. self.time_zone,
  153. self.description,
  154. self.comments,
  155. )
  156. def get_status_class(self):
  157. return STATUS_CLASSES[self.status]
  158. @property
  159. def count_prefixes(self):
  160. return self.prefixes.count()
  161. @property
  162. def count_vlans(self):
  163. return self.vlans.count()
  164. @property
  165. def count_racks(self):
  166. return Rack.objects.filter(site=self).count()
  167. @property
  168. def count_devices(self):
  169. return Device.objects.filter(site=self).count()
  170. @property
  171. def count_circuits(self):
  172. return Circuit.objects.filter(terminations__site=self).count()
  173. @property
  174. def count_vms(self):
  175. from virtualization.models import VirtualMachine
  176. return VirtualMachine.objects.filter(cluster__site=self).count()
  177. #
  178. # Racks
  179. #
  180. @python_2_unicode_compatible
  181. class RackGroup(models.Model):
  182. """
  183. Racks can be grouped as subsets within a Site. The scope of a group will depend on how Sites are defined. For
  184. example, if a Site spans a corporate campus, a RackGroup might be defined to represent each building within that
  185. campus. If a Site instead represents a single building, a RackGroup might represent a single room or floor.
  186. """
  187. name = models.CharField(max_length=50)
  188. slug = models.SlugField()
  189. site = models.ForeignKey('Site', related_name='rack_groups', on_delete=models.CASCADE)
  190. csv_headers = ['site', 'name', 'slug']
  191. class Meta:
  192. ordering = ['site', 'name']
  193. unique_together = [
  194. ['site', 'name'],
  195. ['site', 'slug'],
  196. ]
  197. def __str__(self):
  198. return self.name
  199. def get_absolute_url(self):
  200. return "{}?group_id={}".format(reverse('dcim:rack_list'), self.pk)
  201. def to_csv(self):
  202. return (
  203. self.site,
  204. self.name,
  205. self.slug,
  206. )
  207. @python_2_unicode_compatible
  208. class RackRole(models.Model):
  209. """
  210. Racks can be organized by functional role, similar to Devices.
  211. """
  212. name = models.CharField(max_length=50, unique=True)
  213. slug = models.SlugField(unique=True)
  214. color = ColorField()
  215. csv_headers = ['name', 'slug', 'color']
  216. class Meta:
  217. ordering = ['name']
  218. def __str__(self):
  219. return self.name
  220. def get_absolute_url(self):
  221. return "{}?role={}".format(reverse('dcim:rack_list'), self.slug)
  222. def to_csv(self):
  223. return (
  224. self.name,
  225. self.slug,
  226. self.color,
  227. )
  228. class RackManager(NaturalOrderByManager):
  229. def get_queryset(self):
  230. return self.natural_order_by('site__name', 'name')
  231. @python_2_unicode_compatible
  232. class Rack(CreatedUpdatedModel, CustomFieldModel):
  233. """
  234. Devices are housed within Racks. Each rack has a defined height measured in rack units, and a front and rear face.
  235. Each Rack is assigned to a Site and (optionally) a RackGroup.
  236. """
  237. name = models.CharField(max_length=50)
  238. facility_id = NullableCharField(max_length=50, blank=True, null=True, verbose_name='Facility ID')
  239. site = models.ForeignKey('Site', related_name='racks', on_delete=models.PROTECT)
  240. group = models.ForeignKey('RackGroup', related_name='racks', blank=True, null=True, on_delete=models.SET_NULL)
  241. tenant = models.ForeignKey(Tenant, blank=True, null=True, related_name='racks', on_delete=models.PROTECT)
  242. role = models.ForeignKey('RackRole', related_name='racks', blank=True, null=True, on_delete=models.PROTECT)
  243. serial = models.CharField(max_length=50, blank=True, verbose_name='Serial number')
  244. type = models.PositiveSmallIntegerField(choices=RACK_TYPE_CHOICES, blank=True, null=True, verbose_name='Type')
  245. width = models.PositiveSmallIntegerField(choices=RACK_WIDTH_CHOICES, default=RACK_WIDTH_19IN, verbose_name='Width',
  246. help_text='Rail-to-rail width')
  247. u_height = models.PositiveSmallIntegerField(default=42, verbose_name='Height (U)',
  248. validators=[MinValueValidator(1), MaxValueValidator(100)])
  249. desc_units = models.BooleanField(default=False, verbose_name='Descending units',
  250. help_text='Units are numbered top-to-bottom')
  251. comments = models.TextField(blank=True)
  252. custom_field_values = GenericRelation(CustomFieldValue, content_type_field='obj_type', object_id_field='obj_id')
  253. images = GenericRelation(ImageAttachment)
  254. objects = RackManager()
  255. csv_headers = [
  256. 'site', 'group_name', 'name', 'facility_id', 'tenant', 'role', 'type', 'serial', 'width', 'u_height',
  257. 'desc_units', 'comments',
  258. ]
  259. class Meta:
  260. ordering = ['site', 'name']
  261. unique_together = [
  262. ['site', 'name'],
  263. ['site', 'facility_id'],
  264. ]
  265. def __str__(self):
  266. return self.display_name or super(Rack, self).__str__()
  267. def get_absolute_url(self):
  268. return reverse('dcim:rack', args=[self.pk])
  269. def clean(self):
  270. if self.pk:
  271. # Validate that Rack is tall enough to house the installed Devices
  272. top_device = Device.objects.filter(rack=self).exclude(position__isnull=True).order_by('-position').first()
  273. if top_device:
  274. min_height = top_device.position + top_device.device_type.u_height - 1
  275. if self.u_height < min_height:
  276. raise ValidationError({
  277. 'u_height': "Rack must be at least {}U tall to house currently installed devices.".format(
  278. min_height
  279. )
  280. })
  281. # Validate that Rack was assigned a group of its same site, if applicable
  282. if self.group:
  283. if self.group.site != self.site:
  284. raise ValidationError({
  285. 'group': "Rack group must be from the same site, {}.".format(self.site)
  286. })
  287. def save(self, *args, **kwargs):
  288. # Record the original site assignment for this rack.
  289. _site_id = None
  290. if self.pk:
  291. _site_id = Rack.objects.get(pk=self.pk).site_id
  292. super(Rack, self).save(*args, **kwargs)
  293. # Update racked devices if the assigned Site has been changed.
  294. if _site_id is not None and self.site_id != _site_id:
  295. Device.objects.filter(rack=self).update(site_id=self.site.pk)
  296. def to_csv(self):
  297. return (
  298. self.site.name,
  299. self.group.name if self.group else None,
  300. self.name,
  301. self.facility_id,
  302. self.tenant.name if self.tenant else None,
  303. self.role.name if self.role else None,
  304. self.get_type_display() if self.type else None,
  305. self.serial,
  306. self.width,
  307. self.u_height,
  308. self.desc_units,
  309. self.comments,
  310. )
  311. @property
  312. def units(self):
  313. if self.desc_units:
  314. return range(1, self.u_height + 1)
  315. else:
  316. return reversed(range(1, self.u_height + 1))
  317. @property
  318. def display_name(self):
  319. if self.facility_id:
  320. return "{} ({})".format(self.name, self.facility_id)
  321. elif self.name:
  322. return self.name
  323. return ""
  324. def get_rack_units(self, face=RACK_FACE_FRONT, exclude=None, remove_redundant=False):
  325. """
  326. Return a list of rack units as dictionaries. Example: {'device': None, 'face': 0, 'id': 48, 'name': 'U48'}
  327. Each key 'device' is either a Device or None. By default, multi-U devices are repeated for each U they occupy.
  328. :param face: Rack face (front or rear)
  329. :param exclude: PK of a Device to exclude (optional); helpful when relocating a Device within a Rack
  330. :param remove_redundant: If True, rack units occupied by a device already listed will be omitted
  331. """
  332. elevation = OrderedDict()
  333. for u in self.units:
  334. elevation[u] = {'id': u, 'name': 'U{}'.format(u), 'face': face, 'device': None}
  335. # Add devices to rack units list
  336. if self.pk:
  337. for device in Device.objects.select_related('device_type__manufacturer', 'device_role')\
  338. .annotate(devicebay_count=Count('device_bays'))\
  339. .exclude(pk=exclude)\
  340. .filter(rack=self, position__gt=0)\
  341. .filter(Q(face=face) | Q(device_type__is_full_depth=True)):
  342. if remove_redundant:
  343. elevation[device.position]['device'] = device
  344. for u in range(device.position + 1, device.position + device.device_type.u_height):
  345. elevation.pop(u, None)
  346. else:
  347. for u in range(device.position, device.position + device.device_type.u_height):
  348. elevation[u]['device'] = device
  349. return [u for u in elevation.values()]
  350. def get_front_elevation(self):
  351. return self.get_rack_units(face=RACK_FACE_FRONT, remove_redundant=True)
  352. def get_rear_elevation(self):
  353. return self.get_rack_units(face=RACK_FACE_REAR, remove_redundant=True)
  354. def get_available_units(self, u_height=1, rack_face=None, exclude=list()):
  355. """
  356. Return a list of units within the rack available to accommodate a device of a given U height (default 1).
  357. Optionally exclude one or more devices when calculating empty units (needed when moving a device from one
  358. position to another within a rack).
  359. :param u_height: Minimum number of contiguous free units required
  360. :param rack_face: The face of the rack (front or rear) required; 'None' if device is full depth
  361. :param exclude: List of devices IDs to exclude (useful when moving a device within a rack)
  362. """
  363. # Gather all devices which consume U space within the rack
  364. devices = self.devices.select_related('device_type').filter(position__gte=1).exclude(pk__in=exclude)
  365. # Initialize the rack unit skeleton
  366. units = list(range(1, self.u_height + 1))
  367. # Remove units consumed by installed devices
  368. for d in devices:
  369. if rack_face is None or d.face == rack_face or d.device_type.is_full_depth:
  370. for u in range(d.position, d.position + d.device_type.u_height):
  371. try:
  372. units.remove(u)
  373. except ValueError:
  374. # Found overlapping devices in the rack!
  375. pass
  376. # Remove units without enough space above them to accommodate a device of the specified height
  377. available_units = []
  378. for u in units:
  379. if set(range(u, u + u_height)).issubset(units):
  380. available_units.append(u)
  381. return list(reversed(available_units))
  382. def get_reserved_units(self):
  383. """
  384. Return a dictionary mapping all reserved units within the rack to their reservation.
  385. """
  386. reserved_units = {}
  387. for r in self.reservations.all():
  388. for u in r.units:
  389. reserved_units[u] = r
  390. return reserved_units
  391. def get_0u_devices(self):
  392. return self.devices.filter(position=0)
  393. def get_utilization(self):
  394. """
  395. Determine the utilization rate of the rack and return it as a percentage.
  396. """
  397. u_available = len(self.get_available_units())
  398. return int(float(self.u_height - u_available) / self.u_height * 100)
  399. @python_2_unicode_compatible
  400. class RackReservation(models.Model):
  401. """
  402. One or more reserved units within a Rack.
  403. """
  404. rack = models.ForeignKey('Rack', related_name='reservations', on_delete=models.CASCADE)
  405. units = ArrayField(models.PositiveSmallIntegerField())
  406. created = models.DateTimeField(auto_now_add=True)
  407. tenant = models.ForeignKey(Tenant, blank=True, null=True, related_name='rackreservations', on_delete=models.PROTECT)
  408. user = models.ForeignKey(User, on_delete=models.PROTECT)
  409. description = models.CharField(max_length=100)
  410. class Meta:
  411. ordering = ['created']
  412. def __str__(self):
  413. return "Reservation for rack {}".format(self.rack)
  414. def clean(self):
  415. if self.units:
  416. # Validate that all specified units exist in the Rack.
  417. invalid_units = [u for u in self.units if u not in self.rack.units]
  418. if invalid_units:
  419. raise ValidationError({
  420. 'units': "Invalid unit(s) for {}U rack: {}".format(
  421. self.rack.u_height,
  422. ', '.join([str(u) for u in invalid_units]),
  423. ),
  424. })
  425. # Check that none of the units has already been reserved for this Rack.
  426. reserved_units = []
  427. for resv in self.rack.reservations.exclude(pk=self.pk):
  428. reserved_units += resv.units
  429. conflicting_units = [u for u in self.units if u in reserved_units]
  430. if conflicting_units:
  431. raise ValidationError({
  432. 'units': 'The following units have already been reserved: {}'.format(
  433. ', '.join([str(u) for u in conflicting_units]),
  434. )
  435. })
  436. @property
  437. def unit_list(self):
  438. """
  439. Express the assigned units as a string of summarized ranges. For example:
  440. [0, 1, 2, 10, 14, 15, 16] => "0-2, 10, 14-16"
  441. """
  442. group = (list(x) for _, x in groupby(sorted(self.units), lambda x, c=count(): next(c) - x))
  443. return ', '.join('-'.join(map(str, (g[0], g[-1])[:len(g)])) for g in group)
  444. #
  445. # Device Types
  446. #
  447. @python_2_unicode_compatible
  448. class Manufacturer(models.Model):
  449. """
  450. A Manufacturer represents a company which produces hardware devices; for example, Juniper or Dell.
  451. """
  452. name = models.CharField(max_length=50, unique=True)
  453. slug = models.SlugField(unique=True)
  454. csv_headers = ['name', 'slug']
  455. class Meta:
  456. ordering = ['name']
  457. def __str__(self):
  458. return self.name
  459. def get_absolute_url(self):
  460. return "{}?manufacturer={}".format(reverse('dcim:devicetype_list'), self.slug)
  461. def to_csv(self):
  462. return (
  463. self.name,
  464. self.slug,
  465. )
  466. @python_2_unicode_compatible
  467. class DeviceType(models.Model, CustomFieldModel):
  468. """
  469. A DeviceType represents a particular make (Manufacturer) and model of device. It specifies rack height and depth, as
  470. well as high-level functional role(s).
  471. Each DeviceType can have an arbitrary number of component templates assigned to it, which define console, power, and
  472. interface objects. For example, a Juniper EX4300-48T DeviceType would have:
  473. * 1 ConsolePortTemplate
  474. * 2 PowerPortTemplates
  475. * 48 InterfaceTemplates
  476. When a new Device of this type is created, the appropriate console, power, and interface objects (as defined by the
  477. DeviceType) are automatically created as well.
  478. """
  479. manufacturer = models.ForeignKey('Manufacturer', related_name='device_types', on_delete=models.PROTECT)
  480. model = models.CharField(max_length=50)
  481. slug = models.SlugField()
  482. part_number = models.CharField(max_length=50, blank=True, help_text="Discrete part number (optional)")
  483. u_height = models.PositiveSmallIntegerField(verbose_name='Height (U)', default=1)
  484. is_full_depth = models.BooleanField(default=True, verbose_name="Is full depth",
  485. help_text="Device consumes both front and rear rack faces")
  486. interface_ordering = models.PositiveSmallIntegerField(choices=IFACE_ORDERING_CHOICES,
  487. default=IFACE_ORDERING_POSITION)
  488. is_console_server = models.BooleanField(default=False, verbose_name='Is a console server',
  489. help_text="This type of device has console server ports")
  490. is_pdu = models.BooleanField(default=False, verbose_name='Is a PDU',
  491. help_text="This type of device has power outlets")
  492. is_network_device = models.BooleanField(default=True, verbose_name='Is a network device',
  493. help_text="This type of device has network interfaces")
  494. subdevice_role = models.NullBooleanField(default=None, verbose_name='Parent/child status',
  495. choices=SUBDEVICE_ROLE_CHOICES,
  496. help_text="Parent devices house child devices in device bays. Select "
  497. "\"None\" if this device type is neither a parent nor a child.")
  498. comments = models.TextField(blank=True)
  499. custom_field_values = GenericRelation(CustomFieldValue, content_type_field='obj_type', object_id_field='obj_id')
  500. csv_headers = [
  501. 'manufacturer', 'model', 'slug', 'part_number', 'u_height', 'is_full_depth', 'is_console_server',
  502. 'is_pdu', 'is_network_device', 'subdevice_role', 'interface_ordering', 'comments',
  503. ]
  504. class Meta:
  505. ordering = ['manufacturer', 'model']
  506. unique_together = [
  507. ['manufacturer', 'model'],
  508. ['manufacturer', 'slug'],
  509. ]
  510. def __str__(self):
  511. return self.model
  512. def __init__(self, *args, **kwargs):
  513. super(DeviceType, self).__init__(*args, **kwargs)
  514. # Save a copy of u_height for validation in clean()
  515. self._original_u_height = self.u_height
  516. def get_absolute_url(self):
  517. return reverse('dcim:devicetype', args=[self.pk])
  518. def to_csv(self):
  519. return (
  520. self.manufacturer.name,
  521. self.model,
  522. self.slug,
  523. self.part_number,
  524. self.u_height,
  525. self.is_full_depth,
  526. self.is_console_server,
  527. self.is_pdu,
  528. self.is_network_device,
  529. self.get_subdevice_role_display() if self.subdevice_role else None,
  530. self.get_interface_ordering_display(),
  531. self.comments,
  532. )
  533. def clean(self):
  534. # If editing an existing DeviceType to have a larger u_height, first validate that *all* instances of it have
  535. # room to expand within their racks. This validation will impose a very high performance penalty when there are
  536. # many instances to check, but increasing the u_height of a DeviceType should be a very rare occurrence.
  537. if self.pk is not None and self.u_height > self._original_u_height:
  538. for d in Device.objects.filter(device_type=self, position__isnull=False):
  539. face_required = None if self.is_full_depth else d.face
  540. u_available = d.rack.get_available_units(u_height=self.u_height, rack_face=face_required,
  541. exclude=[d.pk])
  542. if d.position not in u_available:
  543. raise ValidationError({
  544. 'u_height': "Device {} in rack {} does not have sufficient space to accommodate a height of "
  545. "{}U".format(d, d.rack, self.u_height)
  546. })
  547. if not self.is_console_server and self.cs_port_templates.count():
  548. raise ValidationError({
  549. 'is_console_server': "Must delete all console server port templates associated with this device before "
  550. "declassifying it as a console server."
  551. })
  552. if not self.is_pdu and self.power_outlet_templates.count():
  553. raise ValidationError({
  554. 'is_pdu': "Must delete all power outlet templates associated with this device before declassifying it "
  555. "as a PDU."
  556. })
  557. if not self.is_network_device and self.interface_templates.filter(mgmt_only=False).count():
  558. raise ValidationError({
  559. 'is_network_device': "Must delete all non-management-only interface templates associated with this "
  560. "device before declassifying it as a network device."
  561. })
  562. if self.subdevice_role != SUBDEVICE_ROLE_PARENT and self.device_bay_templates.count():
  563. raise ValidationError({
  564. 'subdevice_role': "Must delete all device bay templates associated with this device before "
  565. "declassifying it as a parent device."
  566. })
  567. if self.u_height and self.subdevice_role == SUBDEVICE_ROLE_CHILD:
  568. raise ValidationError({
  569. 'u_height': "Child device types must be 0U."
  570. })
  571. @property
  572. def full_name(self):
  573. return '{} {}'.format(self.manufacturer.name, self.model)
  574. @property
  575. def is_parent_device(self):
  576. return bool(self.subdevice_role)
  577. @property
  578. def is_child_device(self):
  579. return bool(self.subdevice_role is False)
  580. @python_2_unicode_compatible
  581. class ConsolePortTemplate(models.Model):
  582. """
  583. A template for a ConsolePort to be created for a new Device.
  584. """
  585. device_type = models.ForeignKey('DeviceType', related_name='console_port_templates', on_delete=models.CASCADE)
  586. name = models.CharField(max_length=50)
  587. class Meta:
  588. ordering = ['device_type', 'name']
  589. unique_together = ['device_type', 'name']
  590. def __str__(self):
  591. return self.name
  592. @python_2_unicode_compatible
  593. class ConsoleServerPortTemplate(models.Model):
  594. """
  595. A template for a ConsoleServerPort to be created for a new Device.
  596. """
  597. device_type = models.ForeignKey('DeviceType', related_name='cs_port_templates', on_delete=models.CASCADE)
  598. name = models.CharField(max_length=50)
  599. class Meta:
  600. ordering = ['device_type', 'name']
  601. unique_together = ['device_type', 'name']
  602. def __str__(self):
  603. return self.name
  604. @python_2_unicode_compatible
  605. class PowerPortTemplate(models.Model):
  606. """
  607. A template for a PowerPort to be created for a new Device.
  608. """
  609. device_type = models.ForeignKey('DeviceType', related_name='power_port_templates', on_delete=models.CASCADE)
  610. name = models.CharField(max_length=50)
  611. class Meta:
  612. ordering = ['device_type', 'name']
  613. unique_together = ['device_type', 'name']
  614. def __str__(self):
  615. return self.name
  616. @python_2_unicode_compatible
  617. class PowerOutletTemplate(models.Model):
  618. """
  619. A template for a PowerOutlet to be created for a new Device.
  620. """
  621. device_type = models.ForeignKey('DeviceType', related_name='power_outlet_templates', on_delete=models.CASCADE)
  622. name = models.CharField(max_length=50)
  623. class Meta:
  624. ordering = ['device_type', 'name']
  625. unique_together = ['device_type', 'name']
  626. def __str__(self):
  627. return self.name
  628. @python_2_unicode_compatible
  629. class InterfaceTemplate(models.Model):
  630. """
  631. A template for a physical data interface on a new Device.
  632. """
  633. device_type = models.ForeignKey('DeviceType', related_name='interface_templates', on_delete=models.CASCADE)
  634. name = models.CharField(max_length=64)
  635. form_factor = models.PositiveSmallIntegerField(choices=IFACE_FF_CHOICES, default=IFACE_FF_10GE_SFP_PLUS)
  636. mgmt_only = models.BooleanField(default=False, verbose_name='Management only')
  637. objects = InterfaceQuerySet.as_manager()
  638. class Meta:
  639. ordering = ['device_type', 'name']
  640. unique_together = ['device_type', 'name']
  641. def __str__(self):
  642. return self.name
  643. @python_2_unicode_compatible
  644. class DeviceBayTemplate(models.Model):
  645. """
  646. A template for a DeviceBay to be created for a new parent Device.
  647. """
  648. device_type = models.ForeignKey('DeviceType', related_name='device_bay_templates', on_delete=models.CASCADE)
  649. name = models.CharField(max_length=50)
  650. class Meta:
  651. ordering = ['device_type', 'name']
  652. unique_together = ['device_type', 'name']
  653. def __str__(self):
  654. return self.name
  655. #
  656. # Devices
  657. #
  658. @python_2_unicode_compatible
  659. class DeviceRole(models.Model):
  660. """
  661. Devices are organized by functional role; for example, "Core Switch" or "File Server". Each DeviceRole is assigned a
  662. color to be used when displaying rack elevations. The vm_role field determines whether the role is applicable to
  663. virtual machines as well.
  664. """
  665. name = models.CharField(max_length=50, unique=True)
  666. slug = models.SlugField(unique=True)
  667. color = ColorField()
  668. vm_role = models.BooleanField(
  669. default=True,
  670. verbose_name="VM Role",
  671. help_text="Virtual machines may be assigned to this role"
  672. )
  673. csv_headers = ['name', 'slug', 'color', 'vm_role']
  674. class Meta:
  675. ordering = ['name']
  676. def __str__(self):
  677. return self.name
  678. def get_absolute_url(self):
  679. return "{}?role={}".format(reverse('dcim:device_list'), self.slug)
  680. def to_csv(self):
  681. return (
  682. self.name,
  683. self.slug,
  684. self.color,
  685. self.vm_role,
  686. )
  687. @python_2_unicode_compatible
  688. class Platform(models.Model):
  689. """
  690. Platform refers to the software or firmware running on a Device. For example, "Cisco IOS-XR" or "Juniper Junos".
  691. NetBox uses Platforms to determine how to interact with devices when pulling inventory data or other information by
  692. specifying a NAPALM driver.
  693. """
  694. name = models.CharField(max_length=50, unique=True)
  695. slug = models.SlugField(unique=True)
  696. manufacturer = models.ForeignKey(
  697. to='Manufacturer',
  698. related_name='platforms',
  699. blank=True,
  700. null=True,
  701. help_text="Optionally limit this platform to devices of a certain manufacturer"
  702. )
  703. napalm_driver = models.CharField(
  704. max_length=50,
  705. blank=True,
  706. verbose_name='NAPALM driver',
  707. help_text="The name of the NAPALM driver to use when interacting with devices"
  708. )
  709. rpc_client = models.CharField(
  710. max_length=30,
  711. choices=RPC_CLIENT_CHOICES,
  712. blank=True,
  713. verbose_name="Legacy RPC client"
  714. )
  715. csv_headers = ['name', 'slug', 'manufacturer', 'napalm_driver']
  716. class Meta:
  717. ordering = ['name']
  718. def __str__(self):
  719. return self.name
  720. def get_absolute_url(self):
  721. return "{}?platform={}".format(reverse('dcim:device_list'), self.slug)
  722. def to_csv(self):
  723. return (
  724. self.name,
  725. self.slug,
  726. self.manufacturer.name if self.manufacturer else None,
  727. self.napalm_driver,
  728. )
  729. class DeviceManager(NaturalOrderByManager):
  730. def get_queryset(self):
  731. return self.natural_order_by('name')
  732. @python_2_unicode_compatible
  733. class Device(CreatedUpdatedModel, CustomFieldModel):
  734. """
  735. A Device represents a piece of physical hardware mounted within a Rack. Each Device is assigned a DeviceType,
  736. DeviceRole, and (optionally) a Platform. Device names are not required, however if one is set it must be unique.
  737. Each Device must be assigned to a site, and optionally to a rack within that site. Associating a device with a
  738. particular rack face or unit is optional (for example, vertically mounted PDUs do not consume rack units).
  739. When a new Device is created, console/power/interface/device bay components are created along with it as dictated
  740. by the component templates assigned to its DeviceType. Components can also be added, modified, or deleted after the
  741. creation of a Device.
  742. """
  743. device_type = models.ForeignKey('DeviceType', related_name='instances', on_delete=models.PROTECT)
  744. device_role = models.ForeignKey('DeviceRole', related_name='devices', on_delete=models.PROTECT)
  745. tenant = models.ForeignKey(Tenant, blank=True, null=True, related_name='devices', on_delete=models.PROTECT)
  746. platform = models.ForeignKey('Platform', related_name='devices', blank=True, null=True, on_delete=models.SET_NULL)
  747. name = NullableCharField(max_length=64, blank=True, null=True, unique=True)
  748. serial = models.CharField(max_length=50, blank=True, verbose_name='Serial number')
  749. asset_tag = NullableCharField(
  750. max_length=50, blank=True, null=True, unique=True, verbose_name='Asset tag',
  751. help_text='A unique tag used to identify this device'
  752. )
  753. site = models.ForeignKey('Site', related_name='devices', on_delete=models.PROTECT)
  754. rack = models.ForeignKey('Rack', related_name='devices', blank=True, null=True, on_delete=models.PROTECT)
  755. position = models.PositiveSmallIntegerField(
  756. blank=True, null=True, validators=[MinValueValidator(1)], verbose_name='Position (U)',
  757. help_text='The lowest-numbered unit occupied by the device'
  758. )
  759. face = models.PositiveSmallIntegerField(blank=True, null=True, choices=RACK_FACE_CHOICES, verbose_name='Rack face')
  760. status = models.PositiveSmallIntegerField(choices=DEVICE_STATUS_CHOICES, default=DEVICE_STATUS_ACTIVE, verbose_name='Status')
  761. primary_ip4 = models.OneToOneField(
  762. 'ipam.IPAddress', related_name='primary_ip4_for', on_delete=models.SET_NULL, blank=True, null=True,
  763. verbose_name='Primary IPv4'
  764. )
  765. primary_ip6 = models.OneToOneField(
  766. 'ipam.IPAddress', related_name='primary_ip6_for', on_delete=models.SET_NULL, blank=True, null=True,
  767. verbose_name='Primary IPv6'
  768. )
  769. cluster = models.ForeignKey(
  770. to='virtualization.Cluster',
  771. on_delete=models.SET_NULL,
  772. related_name='devices',
  773. blank=True,
  774. null=True
  775. )
  776. virtual_chassis = models.ForeignKey(
  777. to='VirtualChassis',
  778. on_delete=models.SET_NULL,
  779. related_name='members',
  780. blank=True,
  781. null=True
  782. )
  783. vc_position = models.PositiveSmallIntegerField(
  784. blank=True,
  785. null=True,
  786. validators=[MaxValueValidator(255)]
  787. )
  788. vc_priority = models.PositiveSmallIntegerField(
  789. blank=True,
  790. null=True,
  791. validators=[MaxValueValidator(255)]
  792. )
  793. comments = models.TextField(blank=True)
  794. custom_field_values = GenericRelation(CustomFieldValue, content_type_field='obj_type', object_id_field='obj_id')
  795. images = GenericRelation(ImageAttachment)
  796. objects = DeviceManager()
  797. csv_headers = [
  798. 'name', 'device_role', 'tenant', 'manufacturer', 'model_name', 'platform', 'serial', 'asset_tag', 'status',
  799. 'site', 'rack_group', 'rack_name', 'position', 'face', 'comments',
  800. ]
  801. class Meta:
  802. ordering = ['name']
  803. unique_together = [
  804. ['rack', 'position', 'face'],
  805. ['virtual_chassis', 'vc_position'],
  806. ]
  807. permissions = (
  808. ('napalm_read', 'Read-only access to devices via NAPALM'),
  809. ('napalm_write', 'Read/write access to devices via NAPALM'),
  810. )
  811. def __str__(self):
  812. return self.display_name or super(Device, self).__str__()
  813. def get_absolute_url(self):
  814. return reverse('dcim:device', args=[self.pk])
  815. def clean(self):
  816. # Validate site/rack combination
  817. if self.rack and self.site != self.rack.site:
  818. raise ValidationError({
  819. 'rack': "Rack {} does not belong to site {}.".format(self.rack, self.site),
  820. })
  821. if self.rack is None:
  822. if self.face is not None:
  823. raise ValidationError({
  824. 'face': "Cannot select a rack face without assigning a rack.",
  825. })
  826. if self.position:
  827. raise ValidationError({
  828. 'face': "Cannot select a rack position without assigning a rack.",
  829. })
  830. # Validate position/face combination
  831. if self.position and self.face is None:
  832. raise ValidationError({
  833. 'face': "Must specify rack face when defining rack position.",
  834. })
  835. if self.rack:
  836. try:
  837. # Child devices cannot be assigned to a rack face/unit
  838. if self.device_type.is_child_device and self.face is not None:
  839. raise ValidationError({
  840. 'face': "Child device types cannot be assigned to a rack face. This is an attribute of the "
  841. "parent device."
  842. })
  843. if self.device_type.is_child_device and self.position:
  844. raise ValidationError({
  845. 'position': "Child device types cannot be assigned to a rack position. This is an attribute of "
  846. "the parent device."
  847. })
  848. # Validate rack space
  849. rack_face = self.face if not self.device_type.is_full_depth else None
  850. exclude_list = [self.pk] if self.pk else []
  851. try:
  852. available_units = self.rack.get_available_units(
  853. u_height=self.device_type.u_height, rack_face=rack_face, exclude=exclude_list
  854. )
  855. if self.position and self.position not in available_units:
  856. raise ValidationError({
  857. 'position': "U{} is already occupied or does not have sufficient space to accommodate a(n) "
  858. "{} ({}U).".format(self.position, self.device_type, self.device_type.u_height)
  859. })
  860. except Rack.DoesNotExist:
  861. pass
  862. except DeviceType.DoesNotExist:
  863. pass
  864. # Validate primary IP addresses
  865. vc_interfaces = self.vc_interfaces.all()
  866. if self.primary_ip4:
  867. if self.primary_ip4.interface in vc_interfaces:
  868. pass
  869. elif self.primary_ip4.nat_inside is not None and self.primary_ip4.nat_inside.interface in vc_interfaces:
  870. pass
  871. else:
  872. raise ValidationError({
  873. 'primary_ip4': "The specified IP address ({}) is not assigned to this device.".format(
  874. self.primary_ip4),
  875. })
  876. if self.primary_ip6:
  877. if self.primary_ip6.interface in vc_interfaces:
  878. pass
  879. elif self.primary_ip6.nat_inside is not None and self.primary_ip6.nat_inside.interface in vc_interfaces:
  880. pass
  881. else:
  882. raise ValidationError({
  883. 'primary_ip6': "The specified IP address ({}) is not assigned to this device.".format(
  884. self.primary_ip6),
  885. })
  886. # Validate manufacturer/platform
  887. if self.device_type and self.platform:
  888. if self.platform.manufacturer and self.platform.manufacturer != self.device_type.manufacturer:
  889. raise ValidationError({
  890. 'platform': "The assigned platform is limited to {} device types, but this device's type belongs "
  891. "to {}.".format(self.platform.manufacturer, self.device_type.manufacturer)
  892. })
  893. # A Device can only be assigned to a Cluster in the same Site (or no Site)
  894. if self.cluster and self.cluster.site is not None and self.cluster.site != self.site:
  895. raise ValidationError({
  896. 'cluster': "The assigned cluster belongs to a different site ({})".format(self.cluster.site)
  897. })
  898. # Validate virtual chassis assignment
  899. if self.virtual_chassis and self.vc_position is None:
  900. raise ValidationError({
  901. 'vc_position': "A device assigned to a virtual chassis must have its position defined."
  902. })
  903. def save(self, *args, **kwargs):
  904. is_new = not bool(self.pk)
  905. super(Device, self).save(*args, **kwargs)
  906. # If this is a new Device, instantiate all of the related components per the DeviceType definition
  907. if is_new:
  908. ConsolePort.objects.bulk_create(
  909. [ConsolePort(device=self, name=template.name) for template in
  910. self.device_type.console_port_templates.all()]
  911. )
  912. ConsoleServerPort.objects.bulk_create(
  913. [ConsoleServerPort(device=self, name=template.name) for template in
  914. self.device_type.cs_port_templates.all()]
  915. )
  916. PowerPort.objects.bulk_create(
  917. [PowerPort(device=self, name=template.name) for template in
  918. self.device_type.power_port_templates.all()]
  919. )
  920. PowerOutlet.objects.bulk_create(
  921. [PowerOutlet(device=self, name=template.name) for template in
  922. self.device_type.power_outlet_templates.all()]
  923. )
  924. Interface.objects.bulk_create(
  925. [Interface(device=self, name=template.name, form_factor=template.form_factor,
  926. mgmt_only=template.mgmt_only) for template in self.device_type.interface_templates.all()]
  927. )
  928. DeviceBay.objects.bulk_create(
  929. [DeviceBay(device=self, name=template.name) for template in
  930. self.device_type.device_bay_templates.all()]
  931. )
  932. # Update Site and Rack assignment for any child Devices
  933. Device.objects.filter(parent_bay__device=self).update(site=self.site, rack=self.rack)
  934. def to_csv(self):
  935. return (
  936. self.name or '',
  937. self.device_role.name,
  938. self.tenant.name if self.tenant else None,
  939. self.device_type.manufacturer.name,
  940. self.device_type.model,
  941. self.platform.name if self.platform else None,
  942. self.serial,
  943. self.asset_tag,
  944. self.get_status_display(),
  945. self.site.name,
  946. self.rack.group.name if self.rack and self.rack.group else None,
  947. self.rack.name if self.rack else None,
  948. self.position,
  949. self.get_face_display(),
  950. self.comments,
  951. )
  952. @property
  953. def display_name(self):
  954. if self.name:
  955. return self.name
  956. elif self.virtual_chassis and self.virtual_chassis.master.name:
  957. return "{}:{}".format(self.virtual_chassis.master, self.vc_position)
  958. elif hasattr(self, 'device_type'):
  959. return "{}".format(self.device_type)
  960. return ""
  961. @property
  962. def identifier(self):
  963. """
  964. Return the device name if set; otherwise return the Device's primary key as {pk}
  965. """
  966. if self.name is not None:
  967. return self.name
  968. return '{{{}}}'.format(self.pk)
  969. @property
  970. def primary_ip(self):
  971. if settings.PREFER_IPV4 and self.primary_ip4:
  972. return self.primary_ip4
  973. elif self.primary_ip6:
  974. return self.primary_ip6
  975. elif self.primary_ip4:
  976. return self.primary_ip4
  977. else:
  978. return None
  979. def get_vc_master(self):
  980. """
  981. If this Device is a VirtualChassis member, return the VC master. Otherwise, return None.
  982. """
  983. return self.virtual_chassis.master if self.virtual_chassis else None
  984. @property
  985. def vc_interfaces(self):
  986. """
  987. Return a QuerySet matching all Interfaces assigned to this Device or, if this Device is a VC master, to another
  988. Device belonging to the same VirtualChassis.
  989. """
  990. filter = Q(device=self)
  991. if self.virtual_chassis and self.virtual_chassis.master == self:
  992. filter |= Q(device__virtual_chassis=self.virtual_chassis, mgmt_only=False)
  993. return Interface.objects.filter(filter)
  994. def get_children(self):
  995. """
  996. Return the set of child Devices installed in DeviceBays within this Device.
  997. """
  998. return Device.objects.filter(parent_bay__device=self.pk)
  999. def get_status_class(self):
  1000. return STATUS_CLASSES[self.status]
  1001. def get_rpc_client(self):
  1002. """
  1003. Return the appropriate RPC (e.g. NETCONF, ssh, etc.) client for this device's platform, if one is defined.
  1004. """
  1005. if not self.platform:
  1006. return None
  1007. return RPC_CLIENTS.get(self.platform.rpc_client)
  1008. #
  1009. # Console ports
  1010. #
  1011. @python_2_unicode_compatible
  1012. class ConsolePort(models.Model):
  1013. """
  1014. A physical console port within a Device. ConsolePorts connect to ConsoleServerPorts.
  1015. """
  1016. device = models.ForeignKey('Device', related_name='console_ports', on_delete=models.CASCADE)
  1017. name = models.CharField(max_length=50)
  1018. cs_port = models.OneToOneField('ConsoleServerPort', related_name='connected_console', on_delete=models.SET_NULL,
  1019. verbose_name='Console server port', blank=True, null=True)
  1020. connection_status = models.NullBooleanField(choices=CONNECTION_STATUS_CHOICES, default=CONNECTION_STATUS_CONNECTED)
  1021. csv_headers = ['console_server', 'cs_port', 'device', 'console_port', 'connection_status']
  1022. class Meta:
  1023. ordering = ['device', 'name']
  1024. unique_together = ['device', 'name']
  1025. def __str__(self):
  1026. return self.name
  1027. def get_absolute_url(self):
  1028. return self.device.get_absolute_url()
  1029. def to_csv(self):
  1030. return (
  1031. self.cs_port.device.identifier if self.cs_port else None,
  1032. self.cs_port.name if self.cs_port else None,
  1033. self.device.identifier,
  1034. self.name,
  1035. self.get_connection_status_display(),
  1036. )
  1037. #
  1038. # Console server ports
  1039. #
  1040. class ConsoleServerPortManager(models.Manager):
  1041. def get_queryset(self):
  1042. # Pad any trailing digits to effect natural sorting
  1043. return super(ConsoleServerPortManager, self).get_queryset().extra(select={
  1044. 'name_padded': "CONCAT(REGEXP_REPLACE(dcim_consoleserverport.name, '\d+$', ''), "
  1045. "LPAD(SUBSTRING(dcim_consoleserverport.name FROM '\d+$'), 8, '0'))",
  1046. }).order_by('device', 'name_padded')
  1047. @python_2_unicode_compatible
  1048. class ConsoleServerPort(models.Model):
  1049. """
  1050. A physical port within a Device (typically a designated console server) which provides access to ConsolePorts.
  1051. """
  1052. device = models.ForeignKey('Device', related_name='cs_ports', on_delete=models.CASCADE)
  1053. name = models.CharField(max_length=50)
  1054. objects = ConsoleServerPortManager()
  1055. class Meta:
  1056. unique_together = ['device', 'name']
  1057. def __str__(self):
  1058. return self.name
  1059. def get_absolute_url(self):
  1060. return self.device.get_absolute_url()
  1061. def clean(self):
  1062. # Check that the parent device's DeviceType is a console server
  1063. if self.device is None:
  1064. raise ValidationError("Console server ports must be assigned to devices.")
  1065. device_type = self.device.device_type
  1066. if not device_type.is_console_server:
  1067. raise ValidationError("The {} {} device type not support assignment of console server ports.".format(
  1068. device_type.manufacturer, device_type
  1069. ))
  1070. #
  1071. # Power ports
  1072. #
  1073. @python_2_unicode_compatible
  1074. class PowerPort(models.Model):
  1075. """
  1076. A physical power supply (intake) port within a Device. PowerPorts connect to PowerOutlets.
  1077. """
  1078. device = models.ForeignKey('Device', related_name='power_ports', on_delete=models.CASCADE)
  1079. name = models.CharField(max_length=50)
  1080. power_outlet = models.OneToOneField('PowerOutlet', related_name='connected_port', on_delete=models.SET_NULL,
  1081. blank=True, null=True)
  1082. connection_status = models.NullBooleanField(choices=CONNECTION_STATUS_CHOICES, default=CONNECTION_STATUS_CONNECTED)
  1083. csv_headers = ['pdu', 'power_outlet', 'device', 'power_port', 'connection_status']
  1084. class Meta:
  1085. ordering = ['device', 'name']
  1086. unique_together = ['device', 'name']
  1087. def __str__(self):
  1088. return self.name
  1089. def get_absolute_url(self):
  1090. return self.device.get_absolute_url()
  1091. def to_csv(self):
  1092. return (
  1093. self.power_outlet.device.identifier if self.power_outlet else None,
  1094. self.power_outlet.name if self.power_outlet else None,
  1095. self.device.identifier,
  1096. self.name,
  1097. self.get_connection_status_display(),
  1098. )
  1099. #
  1100. # Power outlets
  1101. #
  1102. class PowerOutletManager(models.Manager):
  1103. def get_queryset(self):
  1104. # Pad any trailing digits to effect natural sorting
  1105. return super(PowerOutletManager, self).get_queryset().extra(select={
  1106. 'name_padded': "CONCAT(REGEXP_REPLACE(dcim_poweroutlet.name, '\d+$', ''), "
  1107. "LPAD(SUBSTRING(dcim_poweroutlet.name FROM '\d+$'), 8, '0'))",
  1108. }).order_by('device', 'name_padded')
  1109. @python_2_unicode_compatible
  1110. class PowerOutlet(models.Model):
  1111. """
  1112. A physical power outlet (output) within a Device which provides power to a PowerPort.
  1113. """
  1114. device = models.ForeignKey('Device', related_name='power_outlets', on_delete=models.CASCADE)
  1115. name = models.CharField(max_length=50)
  1116. objects = PowerOutletManager()
  1117. class Meta:
  1118. unique_together = ['device', 'name']
  1119. def __str__(self):
  1120. return self.name
  1121. def get_absolute_url(self):
  1122. return self.device.get_absolute_url()
  1123. def clean(self):
  1124. # Check that the parent device's DeviceType is a PDU
  1125. if self.device is None:
  1126. raise ValidationError("Power outlets must be assigned to devices.")
  1127. device_type = self.device.device_type
  1128. if not device_type.is_pdu:
  1129. raise ValidationError("The {} {} device type not support assignment of power outlets.".format(
  1130. device_type.manufacturer, device_type
  1131. ))
  1132. #
  1133. # Interfaces
  1134. #
  1135. @python_2_unicode_compatible
  1136. class Interface(models.Model):
  1137. """
  1138. A network interface within a Device or VirtualMachine. A physical Interface can connect to exactly one other
  1139. Interface via the creation of an InterfaceConnection.
  1140. """
  1141. device = models.ForeignKey(
  1142. to='Device',
  1143. on_delete=models.CASCADE,
  1144. related_name='interfaces',
  1145. null=True,
  1146. blank=True
  1147. )
  1148. virtual_machine = models.ForeignKey(
  1149. to='virtualization.VirtualMachine',
  1150. on_delete=models.CASCADE,
  1151. related_name='interfaces',
  1152. null=True,
  1153. blank=True
  1154. )
  1155. lag = models.ForeignKey(
  1156. to='self',
  1157. on_delete=models.SET_NULL,
  1158. related_name='member_interfaces',
  1159. null=True,
  1160. blank=True,
  1161. verbose_name='Parent LAG'
  1162. )
  1163. name = models.CharField(max_length=64)
  1164. form_factor = models.PositiveSmallIntegerField(choices=IFACE_FF_CHOICES, default=IFACE_FF_10GE_SFP_PLUS)
  1165. enabled = models.BooleanField(default=True)
  1166. mac_address = MACAddressField(null=True, blank=True, verbose_name='MAC Address')
  1167. mtu = models.PositiveSmallIntegerField(blank=True, null=True, verbose_name='MTU')
  1168. mgmt_only = models.BooleanField(
  1169. default=False,
  1170. verbose_name='OOB Management',
  1171. help_text="This interface is used only for out-of-band management"
  1172. )
  1173. description = models.CharField(max_length=100, blank=True)
  1174. mode = models.PositiveSmallIntegerField(
  1175. choices=IFACE_MODE_CHOICES,
  1176. blank=True,
  1177. null=True
  1178. )
  1179. untagged_vlan = models.ForeignKey(
  1180. to='ipam.VLAN',
  1181. null=True,
  1182. blank=True,
  1183. verbose_name='Untagged VLAN',
  1184. related_name='interfaces_as_untagged'
  1185. )
  1186. tagged_vlans = models.ManyToManyField(
  1187. to='ipam.VLAN',
  1188. blank=True,
  1189. verbose_name='Tagged VLANs',
  1190. related_name='interfaces_as_tagged'
  1191. )
  1192. objects = InterfaceQuerySet.as_manager()
  1193. class Meta:
  1194. ordering = ['device', 'name']
  1195. unique_together = ['device', 'name']
  1196. def __str__(self):
  1197. return self.name
  1198. def get_absolute_url(self):
  1199. return self.parent.get_absolute_url()
  1200. def clean(self):
  1201. # Check that the parent device's DeviceType is a network device
  1202. if self.device is not None:
  1203. device_type = self.device.device_type
  1204. if not device_type.is_network_device:
  1205. raise ValidationError("The {} {} device type not support assignment of network interfaces.".format(
  1206. device_type.manufacturer, device_type
  1207. ))
  1208. # An Interface must belong to a Device *or* to a VirtualMachine
  1209. if self.device and self.virtual_machine:
  1210. raise ValidationError("An interface cannot belong to both a device and a virtual machine.")
  1211. if not self.device and not self.virtual_machine:
  1212. raise ValidationError("An interface must belong to either a device or a virtual machine.")
  1213. # VM interfaces must be virtual
  1214. if self.virtual_machine and self.form_factor is not IFACE_FF_VIRTUAL:
  1215. raise ValidationError({
  1216. 'form_factor': "Virtual machines can only have virtual interfaces."
  1217. })
  1218. # Virtual interfaces cannot be connected
  1219. if self.form_factor in NONCONNECTABLE_IFACE_TYPES and self.is_connected:
  1220. raise ValidationError({
  1221. 'form_factor': "Virtual and wireless interfaces cannot be connected to another interface or circuit. "
  1222. "Disconnect the interface or choose a suitable form factor."
  1223. })
  1224. # An interface's LAG must belong to the same device (or VC master)
  1225. if self.lag and self.lag.device not in [self.device, self.device.get_vc_master()]:
  1226. raise ValidationError({
  1227. 'lag': "The selected LAG interface ({}) belongs to a different device ({}).".format(
  1228. self.lag.name, self.lag.device.name
  1229. )
  1230. })
  1231. # A virtual interface cannot have a parent LAG
  1232. if self.form_factor in NONCONNECTABLE_IFACE_TYPES and self.lag is not None:
  1233. raise ValidationError({
  1234. 'lag': "{} interfaces cannot have a parent LAG interface.".format(self.get_form_factor_display())
  1235. })
  1236. # Only a LAG can have LAG members
  1237. if self.form_factor != IFACE_FF_LAG and self.member_interfaces.exists():
  1238. raise ValidationError({
  1239. 'form_factor': "Cannot change interface form factor; it has LAG members ({}).".format(
  1240. ", ".join([iface.name for iface in self.member_interfaces.all()])
  1241. )
  1242. })
  1243. # Validate untagged VLAN
  1244. if self.untagged_vlan and self.untagged_vlan.site not in [self.parent.site, None]:
  1245. raise ValidationError({
  1246. 'untagged_vlan': "The untagged VLAN ({}) must belong to the same site as the interface's parent "
  1247. "device/VM, or it must be global".format(self.untagged_vlan)
  1248. })
  1249. def save(self, *args, **kwargs):
  1250. # Remove untagged VLAN assignment for non-802.1Q interfaces
  1251. if self.mode is None:
  1252. self.untagged_vlan = None
  1253. # Only "tagged" interfaces may have tagged VLANs assigned. ("tagged all" implies all VLANs are assigned.)
  1254. if self.pk and self.mode is not IFACE_MODE_TAGGED:
  1255. self.tagged_vlans.clear()
  1256. return super(Interface, self).save(*args, **kwargs)
  1257. @property
  1258. def parent(self):
  1259. return self.device or self.virtual_machine
  1260. @property
  1261. def is_virtual(self):
  1262. return self.form_factor in VIRTUAL_IFACE_TYPES
  1263. @property
  1264. def is_wireless(self):
  1265. return self.form_factor in WIRELESS_IFACE_TYPES
  1266. @property
  1267. def is_lag(self):
  1268. return self.form_factor == IFACE_FF_LAG
  1269. @property
  1270. def is_connected(self):
  1271. try:
  1272. return bool(self.circuit_termination)
  1273. except ObjectDoesNotExist:
  1274. pass
  1275. return bool(self.connection)
  1276. @property
  1277. def connection(self):
  1278. try:
  1279. return self.connected_as_a
  1280. except ObjectDoesNotExist:
  1281. pass
  1282. try:
  1283. return self.connected_as_b
  1284. except ObjectDoesNotExist:
  1285. pass
  1286. return None
  1287. @property
  1288. def connected_interface(self):
  1289. try:
  1290. if self.connected_as_a:
  1291. return self.connected_as_a.interface_b
  1292. except ObjectDoesNotExist:
  1293. pass
  1294. try:
  1295. if self.connected_as_b:
  1296. return self.connected_as_b.interface_a
  1297. except ObjectDoesNotExist:
  1298. pass
  1299. return None
  1300. class InterfaceConnection(models.Model):
  1301. """
  1302. An InterfaceConnection represents a symmetrical, one-to-one connection between two Interfaces. There is no
  1303. significant difference between the interface_a and interface_b fields.
  1304. """
  1305. interface_a = models.OneToOneField('Interface', related_name='connected_as_a', on_delete=models.CASCADE)
  1306. interface_b = models.OneToOneField('Interface', related_name='connected_as_b', on_delete=models.CASCADE)
  1307. connection_status = models.BooleanField(choices=CONNECTION_STATUS_CHOICES, default=CONNECTION_STATUS_CONNECTED,
  1308. verbose_name='Status')
  1309. csv_headers = ['device_a', 'interface_a', 'device_b', 'interface_b', 'connection_status']
  1310. def clean(self):
  1311. try:
  1312. if self.interface_a == self.interface_b:
  1313. raise ValidationError({
  1314. 'interface_b': "Cannot connect an interface to itself."
  1315. })
  1316. except ObjectDoesNotExist:
  1317. pass
  1318. def to_csv(self):
  1319. return (
  1320. self.interface_a.device.identifier,
  1321. self.interface_a.name,
  1322. self.interface_b.device.identifier,
  1323. self.interface_b.name,
  1324. self.get_connection_status_display(),
  1325. )
  1326. #
  1327. # Device bays
  1328. #
  1329. @python_2_unicode_compatible
  1330. class DeviceBay(models.Model):
  1331. """
  1332. An empty space within a Device which can house a child device
  1333. """
  1334. device = models.ForeignKey('Device', related_name='device_bays', on_delete=models.CASCADE)
  1335. name = models.CharField(max_length=50, verbose_name='Name')
  1336. installed_device = models.OneToOneField('Device', related_name='parent_bay', on_delete=models.SET_NULL, blank=True,
  1337. null=True)
  1338. class Meta:
  1339. ordering = ['device', 'name']
  1340. unique_together = ['device', 'name']
  1341. def __str__(self):
  1342. return '{} - {}'.format(self.device.name, self.name)
  1343. def get_absolute_url(self):
  1344. return self.device.get_absolute_url()
  1345. def clean(self):
  1346. # Validate that the parent Device can have DeviceBays
  1347. if not self.device.device_type.is_parent_device:
  1348. raise ValidationError("This type of device ({}) does not support device bays.".format(
  1349. self.device.device_type
  1350. ))
  1351. # Cannot install a device into itself, obviously
  1352. if self.device == self.installed_device:
  1353. raise ValidationError("Cannot install a device into itself.")
  1354. #
  1355. # Inventory items
  1356. #
  1357. @python_2_unicode_compatible
  1358. class InventoryItem(models.Model):
  1359. """
  1360. An InventoryItem represents a serialized piece of hardware within a Device, such as a line card or power supply.
  1361. InventoryItems are used only for inventory purposes.
  1362. """
  1363. device = models.ForeignKey('Device', related_name='inventory_items', on_delete=models.CASCADE)
  1364. parent = models.ForeignKey('self', related_name='child_items', blank=True, null=True, on_delete=models.CASCADE)
  1365. name = models.CharField(max_length=50, verbose_name='Name')
  1366. manufacturer = models.ForeignKey(
  1367. 'Manufacturer', models.PROTECT, related_name='inventory_items', blank=True, null=True
  1368. )
  1369. part_id = models.CharField(max_length=50, verbose_name='Part ID', blank=True)
  1370. serial = models.CharField(max_length=50, verbose_name='Serial number', blank=True)
  1371. asset_tag = NullableCharField(
  1372. max_length=50, blank=True, null=True, unique=True, verbose_name='Asset tag',
  1373. help_text='A unique tag used to identify this item'
  1374. )
  1375. discovered = models.BooleanField(default=False, verbose_name='Discovered')
  1376. description = models.CharField(max_length=100, blank=True)
  1377. csv_headers = [
  1378. 'device', 'name', 'manufacturer', 'part_id', 'serial', 'asset_tag', 'discovered', 'description',
  1379. ]
  1380. class Meta:
  1381. ordering = ['device__id', 'parent__id', 'name']
  1382. unique_together = ['device', 'parent', 'name']
  1383. def __str__(self):
  1384. return self.name
  1385. def get_absolute_url(self):
  1386. return self.device.get_absolute_url()
  1387. def to_csv(self):
  1388. return (
  1389. self.device.name or '{' + self.device.pk + '}',
  1390. self.name,
  1391. self.manufacturer.name if self.manufacturer else None,
  1392. self.part_id,
  1393. self.serial,
  1394. self.asset_tag,
  1395. self.discovered,
  1396. self.description,
  1397. )
  1398. #
  1399. # Virtual chassis
  1400. #
  1401. @python_2_unicode_compatible
  1402. class VirtualChassis(models.Model):
  1403. """
  1404. A collection of Devices which operate with a shared control plane (e.g. a switch stack).
  1405. """
  1406. master = models.OneToOneField(
  1407. to='Device',
  1408. on_delete=models.PROTECT,
  1409. related_name='vc_master_for'
  1410. )
  1411. domain = models.CharField(
  1412. max_length=30,
  1413. blank=True
  1414. )
  1415. class Meta:
  1416. ordering = ['master']
  1417. verbose_name_plural = 'virtual chassis'
  1418. def __str__(self):
  1419. return str(self.master) if hasattr(self, 'master') else 'New Virtual Chassis'
  1420. def get_absolute_url(self):
  1421. return self.master.get_absolute_url()
  1422. def clean(self):
  1423. # Verify that the selected master device has been assigned to this VirtualChassis. (Skip when creating a new
  1424. # VirtualChassis.)
  1425. if self.pk and self.master not in self.members.all():
  1426. raise ValidationError({
  1427. 'master': "The selected master is not assigned to this virtual chassis."
  1428. })