models.py 50 KB

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