devices.py 48 KB

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