2
0

devices.py 51 KB

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