devices.py 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279
  1. import decimal
  2. import yaml
  3. from functools import cached_property
  4. from django.contrib.contenttypes.fields import GenericForeignKey
  5. from django.core.exceptions import ValidationError
  6. from django.core.files.storage import default_storage
  7. from django.core.validators import MaxValueValidator, MinValueValidator
  8. from django.db import models
  9. from django.db.models import F, ProtectedError
  10. from django.db.models.functions import Lower
  11. from django.db.models.signals import post_save
  12. from django.urls import reverse
  13. from django.utils.safestring import mark_safe
  14. from django.utils.translation import gettext_lazy as _
  15. from core.models import ObjectType
  16. from dcim.choices import *
  17. from dcim.constants import *
  18. from dcim.fields import MACAddressField
  19. from dcim.utils import update_interface_bridges
  20. from extras.models import ConfigContextModel, CustomField
  21. from extras.querysets import ConfigContextModelQuerySet
  22. from netbox.choices import ColorChoices
  23. from netbox.config import ConfigItem
  24. from netbox.models import NestedGroupModel, OrganizationalModel, PrimaryModel
  25. from netbox.models.mixins import WeightMixin
  26. from netbox.models.features import ContactsMixin, ImageAttachmentsMixin
  27. from utilities.fields import ColorField, CounterCacheField
  28. from utilities.tracking import TrackingModelMixin
  29. from .device_components import *
  30. from .mixins import RenderConfigMixin
  31. from .modules import Module
  32. __all__ = (
  33. 'Device',
  34. 'DeviceRole',
  35. 'DeviceType',
  36. 'MACAddress',
  37. 'Manufacturer',
  38. 'Platform',
  39. 'VirtualChassis',
  40. 'VirtualDeviceContext',
  41. )
  42. #
  43. # Device Types
  44. #
  45. class Manufacturer(ContactsMixin, OrganizationalModel):
  46. """
  47. A Manufacturer represents a company which produces hardware devices; for example, Juniper or Dell.
  48. """
  49. class Meta:
  50. ordering = ('name',)
  51. verbose_name = _('manufacturer')
  52. verbose_name_plural = _('manufacturers')
  53. class DeviceType(ImageAttachmentsMixin, PrimaryModel, WeightMixin):
  54. """
  55. A DeviceType represents a particular make (Manufacturer) and model of device. It specifies rack height and depth, as
  56. well as high-level functional role(s).
  57. Each DeviceType can have an arbitrary number of component templates assigned to it, which define console, power, and
  58. interface objects. For example, a Juniper EX4300-48T DeviceType would have:
  59. * 1 ConsolePortTemplate
  60. * 2 PowerPortTemplates
  61. * 48 InterfaceTemplates
  62. When a new Device of this type is created, the appropriate console, power, and interface objects (as defined by the
  63. DeviceType) are automatically created as well.
  64. """
  65. manufacturer = models.ForeignKey(
  66. to='dcim.Manufacturer',
  67. on_delete=models.PROTECT,
  68. related_name='device_types'
  69. )
  70. model = models.CharField(
  71. verbose_name=_('model'),
  72. max_length=100
  73. )
  74. slug = models.SlugField(
  75. verbose_name=_('slug'),
  76. max_length=100
  77. )
  78. default_platform = models.ForeignKey(
  79. to='dcim.Platform',
  80. on_delete=models.SET_NULL,
  81. related_name='+',
  82. blank=True,
  83. null=True,
  84. verbose_name=_('default platform')
  85. )
  86. part_number = models.CharField(
  87. verbose_name=_('part number'),
  88. max_length=50,
  89. blank=True,
  90. help_text=_('Discrete part number (optional)')
  91. )
  92. u_height = models.DecimalField(
  93. max_digits=4,
  94. decimal_places=1,
  95. default=1.0,
  96. verbose_name=_('height (U)')
  97. )
  98. exclude_from_utilization = models.BooleanField(
  99. default=False,
  100. verbose_name=_('exclude from utilization'),
  101. help_text=_('Devices of this type are excluded when calculating rack utilization.')
  102. )
  103. is_full_depth = models.BooleanField(
  104. default=True,
  105. verbose_name=_('is full depth'),
  106. help_text=_('Device consumes both front and rear rack faces.')
  107. )
  108. subdevice_role = models.CharField(
  109. max_length=50,
  110. choices=SubdeviceRoleChoices,
  111. blank=True,
  112. null=True,
  113. verbose_name=_('parent/child status'),
  114. help_text=_('Parent devices house child devices in device bays. Leave blank '
  115. 'if this device type is neither a parent nor a child.')
  116. )
  117. airflow = models.CharField(
  118. verbose_name=_('airflow'),
  119. max_length=50,
  120. choices=DeviceAirflowChoices,
  121. blank=True,
  122. null=True
  123. )
  124. front_image = models.ImageField(
  125. upload_to='devicetype-images',
  126. blank=True
  127. )
  128. rear_image = models.ImageField(
  129. upload_to='devicetype-images',
  130. blank=True
  131. )
  132. # Counter fields
  133. console_port_template_count = CounterCacheField(
  134. to_model='dcim.ConsolePortTemplate',
  135. to_field='device_type'
  136. )
  137. console_server_port_template_count = CounterCacheField(
  138. to_model='dcim.ConsoleServerPortTemplate',
  139. to_field='device_type'
  140. )
  141. power_port_template_count = CounterCacheField(
  142. to_model='dcim.PowerPortTemplate',
  143. to_field='device_type'
  144. )
  145. power_outlet_template_count = CounterCacheField(
  146. to_model='dcim.PowerOutletTemplate',
  147. to_field='device_type'
  148. )
  149. interface_template_count = CounterCacheField(
  150. to_model='dcim.InterfaceTemplate',
  151. to_field='device_type'
  152. )
  153. front_port_template_count = CounterCacheField(
  154. to_model='dcim.FrontPortTemplate',
  155. to_field='device_type'
  156. )
  157. rear_port_template_count = CounterCacheField(
  158. to_model='dcim.RearPortTemplate',
  159. to_field='device_type'
  160. )
  161. device_bay_template_count = CounterCacheField(
  162. to_model='dcim.DeviceBayTemplate',
  163. to_field='device_type'
  164. )
  165. module_bay_template_count = CounterCacheField(
  166. to_model='dcim.ModuleBayTemplate',
  167. to_field='device_type'
  168. )
  169. inventory_item_template_count = CounterCacheField(
  170. to_model='dcim.InventoryItemTemplate',
  171. to_field='device_type'
  172. )
  173. clone_fields = (
  174. 'manufacturer', 'default_platform', 'u_height', 'is_full_depth', 'subdevice_role', 'airflow', 'weight',
  175. 'weight_unit',
  176. )
  177. prerequisite_models = (
  178. 'dcim.Manufacturer',
  179. )
  180. class Meta:
  181. ordering = ['manufacturer', 'model']
  182. constraints = (
  183. models.UniqueConstraint(
  184. fields=('manufacturer', 'model'),
  185. name='%(app_label)s_%(class)s_unique_manufacturer_model'
  186. ),
  187. models.UniqueConstraint(
  188. fields=('manufacturer', 'slug'),
  189. name='%(app_label)s_%(class)s_unique_manufacturer_slug'
  190. ),
  191. )
  192. verbose_name = _('device type')
  193. verbose_name_plural = _('device types')
  194. def __str__(self):
  195. return self.model
  196. def __init__(self, *args, **kwargs):
  197. super().__init__(*args, **kwargs)
  198. # Save a copy of u_height for validation in clean()
  199. self._original_u_height = self.__dict__.get('u_height')
  200. # Save references to the original front/rear images
  201. self._original_front_image = self.__dict__.get('front_image')
  202. self._original_rear_image = self.__dict__.get('rear_image')
  203. @property
  204. def full_name(self):
  205. return f"{self.manufacturer} {self.model}"
  206. def to_yaml(self):
  207. data = {
  208. 'manufacturer': self.manufacturer.name,
  209. 'model': self.model,
  210. 'slug': self.slug,
  211. 'description': self.description,
  212. 'default_platform': self.default_platform.name if self.default_platform else None,
  213. 'part_number': self.part_number,
  214. 'u_height': float(self.u_height),
  215. 'is_full_depth': self.is_full_depth,
  216. 'subdevice_role': self.subdevice_role,
  217. 'airflow': self.airflow,
  218. 'weight': float(self.weight) if self.weight is not None else None,
  219. 'weight_unit': self.weight_unit,
  220. 'comments': self.comments,
  221. }
  222. # Component templates
  223. if self.consoleporttemplates.exists():
  224. data['console-ports'] = [
  225. c.to_yaml() for c in self.consoleporttemplates.all()
  226. ]
  227. if self.consoleserverporttemplates.exists():
  228. data['console-server-ports'] = [
  229. c.to_yaml() for c in self.consoleserverporttemplates.all()
  230. ]
  231. if self.powerporttemplates.exists():
  232. data['power-ports'] = [
  233. c.to_yaml() for c in self.powerporttemplates.all()
  234. ]
  235. if self.poweroutlettemplates.exists():
  236. data['power-outlets'] = [
  237. c.to_yaml() for c in self.poweroutlettemplates.all()
  238. ]
  239. if self.interfacetemplates.exists():
  240. data['interfaces'] = [
  241. c.to_yaml() for c in self.interfacetemplates.all()
  242. ]
  243. if self.frontporttemplates.exists():
  244. data['front-ports'] = [
  245. c.to_yaml() for c in self.frontporttemplates.all()
  246. ]
  247. if self.rearporttemplates.exists():
  248. data['rear-ports'] = [
  249. c.to_yaml() for c in self.rearporttemplates.all()
  250. ]
  251. if self.modulebaytemplates.exists():
  252. data['module-bays'] = [
  253. c.to_yaml() for c in self.modulebaytemplates.all()
  254. ]
  255. if self.devicebaytemplates.exists():
  256. data['device-bays'] = [
  257. c.to_yaml() for c in self.devicebaytemplates.all()
  258. ]
  259. return yaml.dump(dict(data), sort_keys=False)
  260. def clean(self):
  261. super().clean()
  262. # U height must be divisible by 0.5
  263. if decimal.Decimal(self.u_height) % decimal.Decimal(0.5):
  264. raise ValidationError({
  265. 'u_height': _("U height must be in increments of 0.5 rack units.")
  266. })
  267. # If editing an existing DeviceType to have a larger u_height, first validate that *all* instances of it have
  268. # room to expand within their racks. This validation will impose a very high performance penalty when there are
  269. # many instances to check, but increasing the u_height of a DeviceType should be a very rare occurrence.
  270. if not self._state.adding and self.u_height > self._original_u_height:
  271. for d in Device.objects.filter(device_type=self, position__isnull=False):
  272. face_required = None if self.is_full_depth else d.face
  273. u_available = d.rack.get_available_units(
  274. u_height=self.u_height,
  275. rack_face=face_required,
  276. exclude=[d.pk]
  277. )
  278. if d.position not in u_available:
  279. raise ValidationError({
  280. 'u_height': _(
  281. "Device {device} in rack {rack} does not have sufficient space to accommodate a "
  282. "height of {height}U"
  283. ).format(device=d, rack=d.rack, height=self.u_height)
  284. })
  285. # If modifying the height of an existing DeviceType to 0U, check for any instances assigned to a rack position.
  286. elif not self._state.adding and self._original_u_height > 0 and self.u_height == 0:
  287. racked_instance_count = Device.objects.filter(
  288. device_type=self,
  289. position__isnull=False
  290. ).count()
  291. if racked_instance_count:
  292. url = f"{reverse('dcim:device_list')}?manufactuer_id={self.manufacturer_id}&device_type_id={self.pk}"
  293. raise ValidationError({
  294. 'u_height': mark_safe(_(
  295. 'Unable to set 0U height: Found <a href="{url}">{racked_instance_count} instances</a> already '
  296. 'mounted within racks.'
  297. ).format(url=url, racked_instance_count=racked_instance_count))
  298. })
  299. if (
  300. self.subdevice_role != SubdeviceRoleChoices.ROLE_PARENT
  301. ) and self.pk and self.devicebaytemplates.count():
  302. raise ValidationError({
  303. 'subdevice_role': _("Must delete all device bay templates associated with this device before "
  304. "declassifying it as a parent device.")
  305. })
  306. if self.u_height and self.subdevice_role == SubdeviceRoleChoices.ROLE_CHILD:
  307. raise ValidationError({
  308. 'u_height': _("Child device types must be 0U.")
  309. })
  310. def save(self, *args, **kwargs):
  311. ret = super().save(*args, **kwargs)
  312. # Delete any previously uploaded image files that are no longer in use
  313. if self._original_front_image and self.front_image != self._original_front_image:
  314. default_storage.delete(self._original_front_image)
  315. if self._original_rear_image and self.rear_image != self._original_rear_image:
  316. default_storage.delete(self._original_rear_image)
  317. return ret
  318. def delete(self, *args, **kwargs):
  319. super().delete(*args, **kwargs)
  320. # Delete any uploaded image files
  321. if self.front_image:
  322. self.front_image.delete(save=False)
  323. if self.rear_image:
  324. self.rear_image.delete(save=False)
  325. @property
  326. def is_parent_device(self):
  327. return self.subdevice_role == SubdeviceRoleChoices.ROLE_PARENT
  328. @property
  329. def is_child_device(self):
  330. return self.subdevice_role == SubdeviceRoleChoices.ROLE_CHILD
  331. #
  332. # Devices
  333. #
  334. class DeviceRole(NestedGroupModel):
  335. """
  336. Devices are organized by functional role; for example, "Core Switch" or "File Server". Each DeviceRole is assigned a
  337. color to be used when displaying rack elevations. The vm_role field determines whether the role is applicable to
  338. virtual machines as well.
  339. """
  340. color = ColorField(
  341. verbose_name=_('color'),
  342. default=ColorChoices.COLOR_GREY
  343. )
  344. vm_role = models.BooleanField(
  345. default=True,
  346. verbose_name=_('VM role'),
  347. help_text=_('Virtual machines may be assigned to this role')
  348. )
  349. config_template = models.ForeignKey(
  350. to='extras.ConfigTemplate',
  351. on_delete=models.PROTECT,
  352. related_name='device_roles',
  353. blank=True,
  354. null=True
  355. )
  356. clone_fields = ('parent', 'description')
  357. class Meta:
  358. ordering = ('name',)
  359. verbose_name = _('device role')
  360. verbose_name_plural = _('device roles')
  361. class Platform(OrganizationalModel):
  362. """
  363. Platform refers to the software or firmware running on a Device. For example, "Cisco IOS-XR" or "Juniper Junos". A
  364. Platform may optionally be associated with a particular Manufacturer.
  365. """
  366. manufacturer = models.ForeignKey(
  367. to='dcim.Manufacturer',
  368. on_delete=models.PROTECT,
  369. related_name='platforms',
  370. blank=True,
  371. null=True,
  372. help_text=_('Optionally limit this platform to devices of a certain manufacturer')
  373. )
  374. config_template = models.ForeignKey(
  375. to='extras.ConfigTemplate',
  376. on_delete=models.PROTECT,
  377. related_name='platforms',
  378. blank=True,
  379. null=True
  380. )
  381. class Meta:
  382. ordering = ('name',)
  383. verbose_name = _('platform')
  384. verbose_name_plural = _('platforms')
  385. class Device(
  386. ContactsMixin,
  387. ImageAttachmentsMixin,
  388. RenderConfigMixin,
  389. ConfigContextModel,
  390. TrackingModelMixin,
  391. PrimaryModel
  392. ):
  393. """
  394. A Device represents a piece of physical hardware mounted within a Rack. Each Device is assigned a DeviceType,
  395. DeviceRole, and (optionally) a Platform. Device names are not required, however if one is set it must be unique.
  396. Each Device must be assigned to a site, and optionally to a rack within that site. Associating a device with a
  397. particular rack face or unit is optional (for example, vertically mounted PDUs do not consume rack units).
  398. When a new Device is created, console/power/interface/device bay components are created along with it as dictated
  399. by the component templates assigned to its DeviceType. Components can also be added, modified, or deleted after the
  400. creation of a Device.
  401. """
  402. device_type = models.ForeignKey(
  403. to='dcim.DeviceType',
  404. on_delete=models.PROTECT,
  405. related_name='instances'
  406. )
  407. role = models.ForeignKey(
  408. to='dcim.DeviceRole',
  409. on_delete=models.PROTECT,
  410. related_name='devices',
  411. help_text=_("The function this device serves")
  412. )
  413. tenant = models.ForeignKey(
  414. to='tenancy.Tenant',
  415. on_delete=models.PROTECT,
  416. related_name='devices',
  417. blank=True,
  418. null=True
  419. )
  420. platform = models.ForeignKey(
  421. to='dcim.Platform',
  422. on_delete=models.SET_NULL,
  423. related_name='devices',
  424. blank=True,
  425. null=True
  426. )
  427. name = models.CharField(
  428. verbose_name=_('name'),
  429. max_length=64,
  430. blank=True,
  431. null=True,
  432. db_collation="natural_sort"
  433. )
  434. serial = models.CharField(
  435. max_length=50,
  436. blank=True,
  437. verbose_name=_('serial number'),
  438. help_text=_("Chassis serial number, assigned by the manufacturer")
  439. )
  440. asset_tag = models.CharField(
  441. max_length=50,
  442. blank=True,
  443. null=True,
  444. unique=True,
  445. verbose_name=_('asset tag'),
  446. help_text=_('A unique tag used to identify this device')
  447. )
  448. site = models.ForeignKey(
  449. to='dcim.Site',
  450. on_delete=models.PROTECT,
  451. related_name='devices'
  452. )
  453. location = models.ForeignKey(
  454. to='dcim.Location',
  455. on_delete=models.PROTECT,
  456. related_name='devices',
  457. blank=True,
  458. null=True
  459. )
  460. rack = models.ForeignKey(
  461. to='dcim.Rack',
  462. on_delete=models.PROTECT,
  463. related_name='devices',
  464. blank=True,
  465. null=True
  466. )
  467. position = models.DecimalField(
  468. max_digits=4,
  469. decimal_places=1,
  470. blank=True,
  471. null=True,
  472. validators=[MinValueValidator(1), MaxValueValidator(RACK_U_HEIGHT_MAX + 0.5)],
  473. verbose_name=_('position (U)'),
  474. help_text=_('The lowest-numbered unit occupied by the device')
  475. )
  476. face = models.CharField(
  477. max_length=50,
  478. blank=True,
  479. null=True,
  480. choices=DeviceFaceChoices,
  481. verbose_name=_('rack face')
  482. )
  483. status = models.CharField(
  484. verbose_name=_('status'),
  485. max_length=50,
  486. choices=DeviceStatusChoices,
  487. default=DeviceStatusChoices.STATUS_ACTIVE
  488. )
  489. airflow = models.CharField(
  490. verbose_name=_('airflow'),
  491. max_length=50,
  492. choices=DeviceAirflowChoices,
  493. blank=True,
  494. null=True
  495. )
  496. primary_ip4 = models.OneToOneField(
  497. to='ipam.IPAddress',
  498. on_delete=models.SET_NULL,
  499. related_name='+',
  500. blank=True,
  501. null=True,
  502. verbose_name=_('primary IPv4')
  503. )
  504. primary_ip6 = models.OneToOneField(
  505. to='ipam.IPAddress',
  506. on_delete=models.SET_NULL,
  507. related_name='+',
  508. blank=True,
  509. null=True,
  510. verbose_name=_('primary IPv6')
  511. )
  512. oob_ip = models.OneToOneField(
  513. to='ipam.IPAddress',
  514. on_delete=models.SET_NULL,
  515. related_name='+',
  516. blank=True,
  517. null=True,
  518. verbose_name=_('out-of-band IP')
  519. )
  520. cluster = models.ForeignKey(
  521. to='virtualization.Cluster',
  522. on_delete=models.SET_NULL,
  523. related_name='devices',
  524. blank=True,
  525. null=True
  526. )
  527. virtual_chassis = models.ForeignKey(
  528. to='VirtualChassis',
  529. on_delete=models.SET_NULL,
  530. related_name='members',
  531. blank=True,
  532. null=True
  533. )
  534. vc_position = models.PositiveIntegerField(
  535. verbose_name=_('VC position'),
  536. blank=True,
  537. null=True,
  538. help_text=_('Virtual chassis position')
  539. )
  540. vc_priority = models.PositiveSmallIntegerField(
  541. verbose_name=_('VC priority'),
  542. blank=True,
  543. null=True,
  544. validators=[MaxValueValidator(255)],
  545. help_text=_('Virtual chassis master election priority')
  546. )
  547. latitude = models.DecimalField(
  548. verbose_name=_('latitude'),
  549. max_digits=8,
  550. decimal_places=6,
  551. blank=True,
  552. null=True,
  553. help_text=_("GPS coordinate in decimal format (xx.yyyyyy)")
  554. )
  555. longitude = models.DecimalField(
  556. verbose_name=_('longitude'),
  557. max_digits=9,
  558. decimal_places=6,
  559. blank=True,
  560. null=True,
  561. help_text=_("GPS coordinate in decimal format (xx.yyyyyy)")
  562. )
  563. # Counter fields
  564. console_port_count = CounterCacheField(
  565. to_model='dcim.ConsolePort',
  566. to_field='device'
  567. )
  568. console_server_port_count = CounterCacheField(
  569. to_model='dcim.ConsoleServerPort',
  570. to_field='device'
  571. )
  572. power_port_count = CounterCacheField(
  573. to_model='dcim.PowerPort',
  574. to_field='device'
  575. )
  576. power_outlet_count = CounterCacheField(
  577. to_model='dcim.PowerOutlet',
  578. to_field='device'
  579. )
  580. interface_count = CounterCacheField(
  581. to_model='dcim.Interface',
  582. to_field='device'
  583. )
  584. front_port_count = CounterCacheField(
  585. to_model='dcim.FrontPort',
  586. to_field='device'
  587. )
  588. rear_port_count = CounterCacheField(
  589. to_model='dcim.RearPort',
  590. to_field='device'
  591. )
  592. device_bay_count = CounterCacheField(
  593. to_model='dcim.DeviceBay',
  594. to_field='device'
  595. )
  596. module_bay_count = CounterCacheField(
  597. to_model='dcim.ModuleBay',
  598. to_field='device'
  599. )
  600. inventory_item_count = CounterCacheField(
  601. to_model='dcim.InventoryItem',
  602. to_field='device'
  603. )
  604. objects = ConfigContextModelQuerySet.as_manager()
  605. clone_fields = (
  606. 'device_type', 'role', 'tenant', 'platform', 'site', 'location', 'rack', 'face', 'status', 'airflow',
  607. 'cluster', 'virtual_chassis',
  608. )
  609. prerequisite_models = (
  610. 'dcim.Site',
  611. 'dcim.DeviceRole',
  612. 'dcim.DeviceType',
  613. )
  614. class Meta:
  615. ordering = ('name', 'pk') # Name may be null
  616. constraints = (
  617. models.UniqueConstraint(
  618. Lower('name'), 'site', 'tenant',
  619. name='%(app_label)s_%(class)s_unique_name_site_tenant'
  620. ),
  621. models.UniqueConstraint(
  622. Lower('name'), 'site',
  623. name='%(app_label)s_%(class)s_unique_name_site',
  624. condition=Q(tenant__isnull=True),
  625. violation_error_message=_("Device name must be unique per site.")
  626. ),
  627. models.UniqueConstraint(
  628. fields=('rack', 'position', 'face'),
  629. name='%(app_label)s_%(class)s_unique_rack_position_face'
  630. ),
  631. models.UniqueConstraint(
  632. fields=('virtual_chassis', 'vc_position'),
  633. name='%(app_label)s_%(class)s_unique_virtual_chassis_vc_position'
  634. ),
  635. )
  636. verbose_name = _('device')
  637. verbose_name_plural = _('devices')
  638. def __str__(self):
  639. if self.name and self.asset_tag:
  640. return f'{self.name} ({self.asset_tag})'
  641. elif self.name:
  642. return self.name
  643. elif self.virtual_chassis and self.asset_tag:
  644. return f'{self.virtual_chassis.name}:{self.vc_position} ({self.asset_tag})'
  645. elif self.virtual_chassis:
  646. return f'{self.virtual_chassis.name}:{self.vc_position} ({self.pk})'
  647. elif self.device_type and self.asset_tag:
  648. return f'{self.device_type.manufacturer} {self.device_type.model} ({self.asset_tag})'
  649. elif self.device_type:
  650. return f'{self.device_type.manufacturer} {self.device_type.model} ({self.pk})'
  651. return super().__str__()
  652. def clean(self):
  653. super().clean()
  654. # Validate site/location/rack combination
  655. if self.rack and self.site != self.rack.site:
  656. raise ValidationError({
  657. 'rack': _("Rack {rack} does not belong to site {site}.").format(rack=self.rack, site=self.site),
  658. })
  659. if self.location and self.site != self.location.site:
  660. raise ValidationError({
  661. 'location': _(
  662. "Location {location} does not belong to site {site}."
  663. ).format(location=self.location, site=self.site)
  664. })
  665. if self.rack and self.location and self.rack.location != self.location:
  666. raise ValidationError({
  667. 'rack': _(
  668. "Rack {rack} does not belong to location {location}."
  669. ).format(rack=self.rack, location=self.location)
  670. })
  671. if self.rack is None:
  672. if self.face:
  673. raise ValidationError({
  674. 'face': _("Cannot select a rack face without assigning a rack."),
  675. })
  676. if self.position:
  677. raise ValidationError({
  678. 'position': _("Cannot select a rack position without assigning a rack."),
  679. })
  680. # Validate rack position and face
  681. if self.position and self.position % decimal.Decimal(0.5):
  682. raise ValidationError({
  683. 'position': _("Position must be in increments of 0.5 rack units.")
  684. })
  685. if self.position and not self.face:
  686. raise ValidationError({
  687. 'face': _("Must specify rack face when defining rack position."),
  688. })
  689. # Prevent 0U devices from being assigned to a specific position
  690. if hasattr(self, 'device_type'):
  691. if self.position and self.device_type.u_height == 0:
  692. raise ValidationError({
  693. 'position': _(
  694. "A 0U device type ({device_type}) cannot be assigned to a rack position."
  695. ).format(device_type=self.device_type)
  696. })
  697. if self.rack:
  698. try:
  699. # Child devices cannot be assigned to a rack face/unit
  700. if self.device_type.is_child_device and self.face:
  701. raise ValidationError({
  702. 'face': _(
  703. "Child device types cannot be assigned to a rack face. This is an attribute of the parent "
  704. "device."
  705. )
  706. })
  707. if self.device_type.is_child_device and self.position:
  708. raise ValidationError({
  709. 'position': _(
  710. "Child device types cannot be assigned to a rack position. This is an attribute of the "
  711. "parent device."
  712. )
  713. })
  714. # Validate rack space
  715. rack_face = self.face if not self.device_type.is_full_depth else None
  716. exclude_list = [self.pk] if self.pk else []
  717. available_units = self.rack.get_available_units(
  718. u_height=self.device_type.u_height, rack_face=rack_face, exclude=exclude_list
  719. )
  720. if self.position and self.position not in available_units:
  721. raise ValidationError({
  722. 'position': _(
  723. "U{position} is already occupied or does not have sufficient space to accommodate this "
  724. "device type: {device_type} ({u_height}U)"
  725. ).format(
  726. position=self.position, device_type=self.device_type, u_height=self.device_type.u_height
  727. )
  728. })
  729. except DeviceType.DoesNotExist:
  730. pass
  731. # Validate primary & OOB IP addresses
  732. vc_interfaces = self.vc_interfaces(if_master=False)
  733. if self.primary_ip4:
  734. if self.primary_ip4.family != 4:
  735. raise ValidationError({
  736. 'primary_ip4': _("{ip} is not an IPv4 address.").format(ip=self.primary_ip4)
  737. })
  738. if self.primary_ip4.assigned_object in vc_interfaces:
  739. pass
  740. elif (
  741. self.primary_ip4.nat_inside is not None and
  742. self.primary_ip4.nat_inside.assigned_object in vc_interfaces
  743. ):
  744. pass
  745. else:
  746. raise ValidationError({
  747. 'primary_ip4': _(
  748. "The specified IP address ({ip}) is not assigned to this device."
  749. ).format(ip=self.primary_ip4)
  750. })
  751. if self.primary_ip6:
  752. if self.primary_ip6.family != 6:
  753. raise ValidationError({
  754. 'primary_ip6': _("{ip} is not an IPv6 address.").format(ip=self.primary_ip6)
  755. })
  756. if self.primary_ip6.assigned_object in vc_interfaces:
  757. pass
  758. elif (
  759. self.primary_ip6.nat_inside is not None and
  760. self.primary_ip6.nat_inside.assigned_object in vc_interfaces
  761. ):
  762. pass
  763. else:
  764. raise ValidationError({
  765. 'primary_ip6': _(
  766. "The specified IP address ({ip}) is not assigned to this device."
  767. ).format(ip=self.primary_ip6)
  768. })
  769. if self.oob_ip:
  770. if self.oob_ip.assigned_object in vc_interfaces:
  771. pass
  772. elif self.oob_ip.nat_inside is not None and self.oob_ip.nat_inside.assigned_object in vc_interfaces:
  773. pass
  774. else:
  775. raise ValidationError({
  776. 'oob_ip': f"The specified IP address ({self.oob_ip}) is not assigned to this device."
  777. })
  778. # Validate manufacturer/platform
  779. if hasattr(self, 'device_type') and self.platform:
  780. if self.platform.manufacturer and self.platform.manufacturer != self.device_type.manufacturer:
  781. raise ValidationError({
  782. 'platform': _(
  783. "The assigned platform is limited to {platform_manufacturer} device types, but this device's "
  784. "type belongs to {devicetype_manufacturer}."
  785. ).format(
  786. platform_manufacturer=self.platform.manufacturer,
  787. devicetype_manufacturer=self.device_type.manufacturer
  788. )
  789. })
  790. # A Device can only be assigned to a Cluster in the same Site (or no Site)
  791. if self.cluster and self.cluster._site is not None and self.cluster._site != self.site:
  792. raise ValidationError({
  793. 'cluster': _("The assigned cluster belongs to a different site ({site})").format(
  794. site=self.cluster._site
  795. )
  796. })
  797. if self.cluster and self.cluster._location is not None and self.cluster._location != self.location:
  798. raise ValidationError({
  799. 'cluster': _("The assigned cluster belongs to a different location ({location})").format(
  800. site=self.cluster._location
  801. )
  802. })
  803. # Validate virtual chassis assignment
  804. if self.virtual_chassis and self.vc_position is None:
  805. raise ValidationError({
  806. 'vc_position': _("A device assigned to a virtual chassis must have its position defined.")
  807. })
  808. if hasattr(self, 'vc_master_for') and self.vc_master_for and self.vc_master_for != self.virtual_chassis:
  809. raise ValidationError({
  810. 'virtual_chassis': _(
  811. 'Device cannot be removed from virtual chassis {virtual_chassis} because it is currently '
  812. 'designated as its master.'
  813. ).format(virtual_chassis=self.vc_master_for)
  814. })
  815. def _instantiate_components(self, queryset, bulk_create=True):
  816. """
  817. Instantiate components for the device from the specified component templates.
  818. Args:
  819. bulk_create: If True, bulk_create() will be called to create all components in a single query
  820. (default). Otherwise, save() will be called on each instance individually.
  821. """
  822. model = queryset.model.component_model
  823. if bulk_create:
  824. components = [obj.instantiate(device=self) for obj in queryset]
  825. if not components:
  826. return
  827. # Set default values for any applicable custom fields
  828. if cf_defaults := CustomField.objects.get_defaults_for_model(model):
  829. for component in components:
  830. component.custom_field_data = cf_defaults
  831. model.objects.bulk_create(components)
  832. # Manually send the post_save signal for each of the newly created components
  833. for component in components:
  834. post_save.send(
  835. sender=model,
  836. instance=component,
  837. created=True,
  838. raw=False,
  839. using='default',
  840. update_fields=None
  841. )
  842. else:
  843. for obj in queryset:
  844. component = obj.instantiate(device=self)
  845. # Set default values for any applicable custom fields
  846. if cf_defaults := CustomField.objects.get_defaults_for_model(model):
  847. component.custom_field_data = cf_defaults
  848. component.save()
  849. def save(self, *args, **kwargs):
  850. is_new = not bool(self.pk)
  851. # Inherit airflow attribute from DeviceType if not set
  852. if is_new and not self.airflow:
  853. self.airflow = self.device_type.airflow
  854. # Inherit default_platform from DeviceType if not set
  855. if is_new and not self.platform:
  856. self.platform = self.device_type.default_platform
  857. # Inherit location from Rack if not set
  858. if self.rack and self.rack.location:
  859. self.location = self.rack.location
  860. super().save(*args, **kwargs)
  861. # If this is a new Device, instantiate all the related components per the DeviceType definition
  862. if is_new:
  863. self._instantiate_components(self.device_type.consoleporttemplates.all())
  864. self._instantiate_components(self.device_type.consoleserverporttemplates.all())
  865. self._instantiate_components(self.device_type.powerporttemplates.all())
  866. self._instantiate_components(self.device_type.poweroutlettemplates.all())
  867. self._instantiate_components(self.device_type.interfacetemplates.all())
  868. self._instantiate_components(self.device_type.rearporttemplates.all())
  869. self._instantiate_components(self.device_type.frontporttemplates.all())
  870. # Disable bulk_create to accommodate MPTT
  871. self._instantiate_components(self.device_type.modulebaytemplates.all(), bulk_create=False)
  872. self._instantiate_components(self.device_type.devicebaytemplates.all())
  873. # Disable bulk_create to accommodate MPTT
  874. self._instantiate_components(self.device_type.inventoryitemtemplates.all(), bulk_create=False)
  875. # Interface bridges have to be set after interface instantiation
  876. update_interface_bridges(self, self.device_type.interfacetemplates.all())
  877. # Update Site and Rack assignment for any child Devices
  878. devices = Device.objects.filter(parent_bay__device=self)
  879. for device in devices:
  880. device.site = self.site
  881. device.rack = self.rack
  882. device.location = self.location
  883. device.save()
  884. @property
  885. def identifier(self):
  886. """
  887. Return the device name if set; otherwise return the Device's primary key as {pk}
  888. """
  889. if self.name is not None:
  890. return self.name
  891. return '{{{}}}'.format(self.pk)
  892. @property
  893. def primary_ip(self):
  894. if ConfigItem('PREFER_IPV4')() and self.primary_ip4:
  895. return self.primary_ip4
  896. elif self.primary_ip6:
  897. return self.primary_ip6
  898. elif self.primary_ip4:
  899. return self.primary_ip4
  900. else:
  901. return None
  902. @property
  903. def interfaces_count(self):
  904. return self.vc_interfaces().count()
  905. def get_vc_master(self):
  906. """
  907. If this Device is a VirtualChassis member, return the VC master. Otherwise, return None.
  908. """
  909. return self.virtual_chassis.master if self.virtual_chassis else None
  910. def vc_interfaces(self, if_master=True):
  911. """
  912. Return a QuerySet matching all Interfaces assigned to this Device or, if this Device is a VC master, to another
  913. Device belonging to the same VirtualChassis.
  914. :param if_master: If True, return VC member interfaces only if this Device is the VC master.
  915. """
  916. filter = Q(device=self) if self.pk else Q()
  917. if self.virtual_chassis and (self.virtual_chassis.master == self or not if_master):
  918. filter |= Q(device__virtual_chassis=self.virtual_chassis, mgmt_only=False)
  919. return Interface.objects.filter(filter)
  920. def get_cables(self, pk_list=False):
  921. """
  922. Return a QuerySet or PK list matching all Cables connected to a component of this Device.
  923. """
  924. from .cables import Cable
  925. cable_pks = []
  926. for component_model in [
  927. ConsolePort, ConsoleServerPort, PowerPort, PowerOutlet, Interface, FrontPort, RearPort
  928. ]:
  929. cable_pks += component_model.objects.filter(
  930. device=self, cable__isnull=False
  931. ).values_list('cable', flat=True)
  932. if pk_list:
  933. return cable_pks
  934. return Cable.objects.filter(pk__in=cable_pks)
  935. def get_children(self):
  936. """
  937. Return the set of child Devices installed in DeviceBays within this Device.
  938. """
  939. return Device.objects.filter(parent_bay__device=self.pk)
  940. def get_status_color(self):
  941. return DeviceStatusChoices.colors.get(self.status)
  942. @cached_property
  943. def total_weight(self):
  944. total_weight = sum(
  945. module.module_type._abs_weight
  946. for module in Module.objects.filter(device=self)
  947. .exclude(module_type___abs_weight__isnull=True)
  948. .prefetch_related('module_type')
  949. )
  950. if self.device_type._abs_weight:
  951. total_weight += self.device_type._abs_weight
  952. return round(total_weight / 1000, 2)
  953. #
  954. # Virtual chassis
  955. #
  956. class VirtualChassis(PrimaryModel):
  957. """
  958. A collection of Devices which operate with a shared control plane (e.g. a switch stack).
  959. """
  960. master = models.OneToOneField(
  961. to='Device',
  962. on_delete=models.PROTECT,
  963. related_name='vc_master_for',
  964. blank=True,
  965. null=True
  966. )
  967. name = models.CharField(
  968. verbose_name=_('name'),
  969. max_length=64,
  970. db_collation="natural_sort"
  971. )
  972. domain = models.CharField(
  973. verbose_name=_('domain'),
  974. max_length=30,
  975. blank=True
  976. )
  977. # Counter fields
  978. member_count = CounterCacheField(
  979. to_model='dcim.Device',
  980. to_field='virtual_chassis'
  981. )
  982. class Meta:
  983. ordering = ['name']
  984. verbose_name = _('virtual chassis')
  985. verbose_name_plural = _('virtual chassis')
  986. def __str__(self):
  987. return self.name
  988. def clean(self):
  989. super().clean()
  990. # Verify that the selected master device has been assigned to this VirtualChassis. (Skip when creating a new
  991. # VirtualChassis.)
  992. if not self._state.adding and self.master and self.master not in self.members.all():
  993. raise ValidationError({
  994. 'master': _("The selected master ({master}) is not assigned to this virtual chassis.").format(
  995. master=self.master
  996. )
  997. })
  998. def delete(self, *args, **kwargs):
  999. # Check for LAG interfaces split across member chassis
  1000. interfaces = Interface.objects.filter(
  1001. device__in=self.members.all(),
  1002. lag__isnull=False
  1003. ).exclude(
  1004. lag__device=F('device')
  1005. )
  1006. if interfaces:
  1007. raise ProtectedError(_(
  1008. "Unable to delete virtual chassis {self}. There are member interfaces which form a cross-chassis LAG "
  1009. "interfaces."
  1010. ).format(self=self, interfaces=InterfaceSpeedChoices))
  1011. return super().delete(*args, **kwargs)
  1012. class VirtualDeviceContext(PrimaryModel):
  1013. device = models.ForeignKey(
  1014. to='Device',
  1015. on_delete=models.PROTECT,
  1016. related_name='vdcs',
  1017. blank=True,
  1018. null=True
  1019. )
  1020. name = models.CharField(
  1021. verbose_name=_('name'),
  1022. max_length=64,
  1023. db_collation="natural_sort"
  1024. )
  1025. status = models.CharField(
  1026. verbose_name=_('status'),
  1027. max_length=50,
  1028. choices=VirtualDeviceContextStatusChoices,
  1029. )
  1030. identifier = models.PositiveSmallIntegerField(
  1031. verbose_name=_('identifier'),
  1032. help_text=_('Numeric identifier unique to the parent device'),
  1033. blank=True,
  1034. null=True,
  1035. )
  1036. primary_ip4 = models.OneToOneField(
  1037. to='ipam.IPAddress',
  1038. on_delete=models.SET_NULL,
  1039. related_name='+',
  1040. blank=True,
  1041. null=True,
  1042. verbose_name=_('primary IPv4')
  1043. )
  1044. primary_ip6 = models.OneToOneField(
  1045. to='ipam.IPAddress',
  1046. on_delete=models.SET_NULL,
  1047. related_name='+',
  1048. blank=True,
  1049. null=True,
  1050. verbose_name=_('primary IPv6')
  1051. )
  1052. tenant = models.ForeignKey(
  1053. to='tenancy.Tenant',
  1054. on_delete=models.PROTECT,
  1055. related_name='vdcs',
  1056. blank=True,
  1057. null=True
  1058. )
  1059. comments = models.TextField(
  1060. verbose_name=_('comments'),
  1061. blank=True
  1062. )
  1063. class Meta:
  1064. ordering = ['name']
  1065. constraints = (
  1066. models.UniqueConstraint(
  1067. fields=('device', 'identifier',),
  1068. name='%(app_label)s_%(class)s_device_identifier'
  1069. ),
  1070. models.UniqueConstraint(
  1071. fields=('device', 'name',),
  1072. name='%(app_label)s_%(class)s_device_name'
  1073. ),
  1074. )
  1075. verbose_name = _('virtual device context')
  1076. verbose_name_plural = _('virtual device contexts')
  1077. def __str__(self):
  1078. return self.name
  1079. def get_status_color(self):
  1080. return VirtualDeviceContextStatusChoices.colors.get(self.status)
  1081. @property
  1082. def primary_ip(self):
  1083. if ConfigItem('PREFER_IPV4')() and self.primary_ip4:
  1084. return self.primary_ip4
  1085. elif self.primary_ip6:
  1086. return self.primary_ip6
  1087. elif self.primary_ip4:
  1088. return self.primary_ip4
  1089. else:
  1090. return None
  1091. def clean(self):
  1092. super().clean()
  1093. # Validate primary IPv4/v6 assignment
  1094. for primary_ip, family in ((self.primary_ip4, 4), (self.primary_ip6, 6)):
  1095. if not primary_ip:
  1096. continue
  1097. if primary_ip.family != family:
  1098. raise ValidationError({
  1099. f'primary_ip{family}': _(
  1100. "{ip} is not an IPv{family} address."
  1101. ).format(family=family, ip=primary_ip)
  1102. })
  1103. device_interfaces = self.device.vc_interfaces(if_master=False)
  1104. if primary_ip.assigned_object not in device_interfaces:
  1105. raise ValidationError({
  1106. f'primary_ip{family}': _('Primary IP address must belong to an interface on the assigned device.')
  1107. })
  1108. #
  1109. # Addressing
  1110. #
  1111. class MACAddress(PrimaryModel):
  1112. mac_address = MACAddressField(
  1113. verbose_name=_('MAC address')
  1114. )
  1115. assigned_object_type = models.ForeignKey(
  1116. to='contenttypes.ContentType',
  1117. on_delete=models.PROTECT,
  1118. related_name='+',
  1119. blank=True,
  1120. null=True
  1121. )
  1122. assigned_object_id = models.PositiveBigIntegerField(
  1123. blank=True,
  1124. null=True
  1125. )
  1126. assigned_object = GenericForeignKey(
  1127. ct_field='assigned_object_type',
  1128. fk_field='assigned_object_id'
  1129. )
  1130. class Meta:
  1131. ordering = ('mac_address',)
  1132. verbose_name = _('MAC address')
  1133. verbose_name_plural = _('MAC addresses')
  1134. def __str__(self):
  1135. return str(self.mac_address)
  1136. def __init__(self, *args, **kwargs):
  1137. super().__init__(*args, **kwargs)
  1138. # Denote the original assigned object (if any) for validation in clean()
  1139. self._original_assigned_object_id = self.__dict__.get('assigned_object_id')
  1140. self._original_assigned_object_type_id = self.__dict__.get('assigned_object_type_id')
  1141. @cached_property
  1142. def is_primary(self):
  1143. if self.assigned_object and hasattr(self.assigned_object, 'primary_mac_address'):
  1144. if self.assigned_object.primary_mac_address and self.assigned_object.primary_mac_address.pk == self.pk:
  1145. return True
  1146. return False
  1147. def clean(self, *args, **kwargs):
  1148. super().clean()
  1149. if self._original_assigned_object_id and self._original_assigned_object_type_id:
  1150. assigned_object = self.assigned_object
  1151. ct = ObjectType.objects.get_for_id(self._original_assigned_object_type_id)
  1152. original_assigned_object = ct.get_object_for_this_type(pk=self._original_assigned_object_id)
  1153. if original_assigned_object.primary_mac_address:
  1154. if not assigned_object:
  1155. raise ValidationError(
  1156. _("Cannot unassign MAC Address while it is designated as the primary MAC for an object")
  1157. )
  1158. elif original_assigned_object != assigned_object:
  1159. raise ValidationError(
  1160. _("Cannot reassign MAC Address while it is designated as the primary MAC for an object")
  1161. )