models.py 53 KB

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