devices.py 52 KB

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