devices.py 49 KB

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