devices.py 51 KB

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