devices.py 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790
  1. import decimal
  2. from functools import cached_property, partial
  3. import yaml
  4. from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
  5. from django.contrib.contenttypes.models import ContentType
  6. from django.contrib.postgres.indexes import GistIndex
  7. from django.core.exceptions import ValidationError
  8. from django.core.files.storage import default_storage
  9. from django.core.validators import MaxValueValidator, MinValueValidator
  10. from django.db import models, router, transaction
  11. from django.db.models import Count, F, ProtectedError, prefetch_related_objects
  12. from django.db.models.functions import Lower
  13. from django.db.models.signals import post_save
  14. from django.urls import reverse
  15. from django.utils.safestring import mark_safe
  16. from django.utils.translation import gettext_lazy as _
  17. from netaddr import EUI, AddrFormatError
  18. from dcim.choices import *
  19. from dcim.constants import *
  20. from dcim.fields import MACAddressField, mac_unix_expanded_uppercase
  21. from dcim.querysets import MACBlockQuerySet
  22. from dcim.utils import create_port_mappings, update_interface_bridges, update_interface_parents
  23. from extras.models import ConfigContextModel, CustomField
  24. from extras.querysets import ConfigContextModelQuerySet
  25. from netbox.choices import ColorChoices
  26. from netbox.config import ConfigItem
  27. from netbox.models import NestedLtreeGroupModel, OrganizationalModel, PrimaryModel
  28. from netbox.models.features import ContactsMixin, ImageAttachmentsMixin
  29. from netbox.models.mixins import WeightMixin
  30. from utilities.data import normalize_update_fields
  31. from utilities.exceptions import AbortRequest
  32. from utilities.fields import ColorField, CounterCacheField
  33. from utilities.prefetch import get_prefetchable_fields
  34. from utilities.tracking import TrackingModelMixin
  35. from .device_components import *
  36. from .mixins import RenderConfigMixin, WebMercatorMixin
  37. from .modules import Module
  38. __all__ = (
  39. 'Device',
  40. 'DeviceRole',
  41. 'DeviceType',
  42. 'MACAddress',
  43. 'MACBlock',
  44. 'Manufacturer',
  45. 'Platform',
  46. 'VirtualChassis',
  47. 'VirtualDeviceContext',
  48. )
  49. #
  50. # Device Types
  51. #
  52. class Manufacturer(ContactsMixin, OrganizationalModel):
  53. """
  54. A Manufacturer represents a company which produces hardware devices; for example, Juniper or Dell.
  55. """
  56. class Meta:
  57. ordering = ('name',)
  58. verbose_name = _('manufacturer')
  59. verbose_name_plural = _('manufacturers')
  60. class DeviceType(ImageAttachmentsMixin, PrimaryModel, WeightMixin):
  61. """
  62. A DeviceType represents a particular make (Manufacturer) and model of device. It specifies rack height and depth, as
  63. well as high-level functional role(s).
  64. Each DeviceType can have an arbitrary number of component templates assigned to it, which define console, power, and
  65. interface objects. For example, a Juniper EX4300-48T DeviceType would have:
  66. * 1 ConsolePortTemplate
  67. * 2 PowerPortTemplates
  68. * 48 InterfaceTemplates
  69. When a new Device of this type is created, the appropriate console, power, and interface objects (as defined by the
  70. DeviceType) are automatically created as well.
  71. """
  72. manufacturer = models.ForeignKey(
  73. to='dcim.Manufacturer',
  74. on_delete=models.PROTECT,
  75. related_name='device_types'
  76. )
  77. model = models.CharField(
  78. verbose_name=_('model'),
  79. max_length=100
  80. )
  81. slug = models.SlugField(
  82. verbose_name=_('slug'),
  83. max_length=100
  84. )
  85. default_platform = models.ForeignKey(
  86. to='dcim.Platform',
  87. on_delete=models.SET_NULL,
  88. related_name='+',
  89. blank=True,
  90. null=True,
  91. verbose_name=_('default platform')
  92. )
  93. part_number = models.CharField(
  94. verbose_name=_('part number'),
  95. max_length=50,
  96. blank=True,
  97. help_text=_('Discrete part number (optional)')
  98. )
  99. u_height = models.DecimalField(
  100. max_digits=4,
  101. decimal_places=1,
  102. default=1.0,
  103. verbose_name=_('height (U)')
  104. )
  105. exclude_from_utilization = models.BooleanField(
  106. default=False,
  107. verbose_name=_('exclude from utilization'),
  108. help_text=_('Devices of this type are excluded when calculating rack utilization.')
  109. )
  110. is_full_depth = models.BooleanField(
  111. default=True,
  112. verbose_name=_('is full depth'),
  113. help_text=_('Device consumes both front and rear rack faces.')
  114. )
  115. subdevice_role = models.CharField(
  116. max_length=50,
  117. choices=SubdeviceRoleChoices,
  118. blank=True,
  119. null=True,
  120. verbose_name=_('parent/child status'),
  121. help_text=_('Parent devices house child devices in device bays. Leave blank '
  122. 'if this device type is neither a parent nor a child.')
  123. )
  124. airflow = models.CharField(
  125. verbose_name=_('airflow'),
  126. max_length=50,
  127. choices=DeviceAirflowChoices,
  128. blank=True,
  129. null=True
  130. )
  131. cooling_method = models.CharField(
  132. verbose_name=_('cooling method'),
  133. max_length=50,
  134. choices=CoolingMethodChoices,
  135. blank=True,
  136. null=True
  137. )
  138. end_of_life = models.DateField(
  139. verbose_name=_('end of life'),
  140. blank=True,
  141. null=True,
  142. help_text=_('The date after which this device type is no longer supported by the manufacturer')
  143. )
  144. front_image = models.ImageField(
  145. upload_to='devicetype-images',
  146. blank=True
  147. )
  148. rear_image = models.ImageField(
  149. upload_to='devicetype-images',
  150. blank=True
  151. )
  152. # Counter fields
  153. console_port_template_count = CounterCacheField(
  154. to_model='dcim.ConsolePortTemplate',
  155. to_field='device_type'
  156. )
  157. console_server_port_template_count = CounterCacheField(
  158. to_model='dcim.ConsoleServerPortTemplate',
  159. to_field='device_type'
  160. )
  161. power_port_template_count = CounterCacheField(
  162. to_model='dcim.PowerPortTemplate',
  163. to_field='device_type'
  164. )
  165. power_outlet_template_count = CounterCacheField(
  166. to_model='dcim.PowerOutletTemplate',
  167. to_field='device_type'
  168. )
  169. cooling_intake_template_count = CounterCacheField(
  170. to_model='dcim.CoolingIntakeTemplate',
  171. to_field='device_type'
  172. )
  173. cooling_outflow_template_count = CounterCacheField(
  174. to_model='dcim.CoolingOutflowTemplate',
  175. to_field='device_type'
  176. )
  177. interface_template_count = CounterCacheField(
  178. to_model='dcim.InterfaceTemplate',
  179. to_field='device_type'
  180. )
  181. front_port_template_count = CounterCacheField(
  182. to_model='dcim.FrontPortTemplate',
  183. to_field='device_type'
  184. )
  185. rear_port_template_count = CounterCacheField(
  186. to_model='dcim.RearPortTemplate',
  187. to_field='device_type'
  188. )
  189. device_bay_template_count = CounterCacheField(
  190. to_model='dcim.DeviceBayTemplate',
  191. to_field='device_type'
  192. )
  193. module_bay_template_count = CounterCacheField(
  194. to_model='dcim.ModuleBayTemplate',
  195. to_field='device_type'
  196. )
  197. inventory_item_template_count = CounterCacheField(
  198. to_model='dcim.InventoryItemTemplate',
  199. to_field='device_type'
  200. )
  201. device_count = CounterCacheField(
  202. to_model='dcim.Device',
  203. to_field='device_type'
  204. )
  205. clone_fields = (
  206. 'manufacturer', 'default_platform', 'u_height', 'is_full_depth', 'subdevice_role', 'airflow',
  207. 'cooling_method', 'weight', 'weight_unit',
  208. )
  209. prerequisite_models = (
  210. 'dcim.Manufacturer',
  211. )
  212. # Related objects read by to_yaml(). Prefetched objects don't inherit the export's fetch mode, so the
  213. # foreign keys of component templates are listed too.
  214. yaml_prefetch = (
  215. 'consoleporttemplates',
  216. 'consoleserverporttemplates',
  217. 'powerporttemplates',
  218. 'poweroutlettemplates__power_port',
  219. 'coolingintaketemplates',
  220. 'coolingoutflowtemplates__cooling_intake',
  221. 'interfacetemplates__parent',
  222. 'interfacetemplates__bridge',
  223. 'frontporttemplates',
  224. 'rearporttemplates',
  225. 'port_mappings__front_port',
  226. 'port_mappings__rear_port',
  227. 'modulebaytemplates__module_bay_types',
  228. 'devicebaytemplates',
  229. )
  230. class Meta:
  231. ordering = ['manufacturer', 'model']
  232. constraints = (
  233. models.UniqueConstraint(
  234. fields=('manufacturer', 'model'),
  235. name='%(app_label)s_%(class)s_unique_manufacturer_model'
  236. ),
  237. models.UniqueConstraint(
  238. fields=('manufacturer', 'slug'),
  239. name='%(app_label)s_%(class)s_unique_manufacturer_slug'
  240. ),
  241. )
  242. verbose_name = _('device type')
  243. verbose_name_plural = _('device types')
  244. def __str__(self):
  245. return self.model
  246. def __init__(self, *args, **kwargs):
  247. super().__init__(*args, **kwargs)
  248. # Save a copy of u_height for validation in clean()
  249. self._original_u_height = self.__dict__.get('u_height')
  250. @property
  251. def full_name(self):
  252. return f"{self.manufacturer} {self.model}"
  253. def get_cooling_method_color(self):
  254. return CoolingMethodChoices.colors.get(self.cooling_method)
  255. def to_yaml(self):
  256. data = {
  257. 'manufacturer': self.manufacturer.name,
  258. 'model': self.model,
  259. 'slug': self.slug,
  260. 'description': self.description,
  261. 'default_platform': self.default_platform.name if self.default_platform else None,
  262. 'part_number': self.part_number,
  263. 'u_height': float(self.u_height),
  264. 'is_full_depth': self.is_full_depth,
  265. 'subdevice_role': self.subdevice_role,
  266. 'airflow': self.airflow,
  267. 'cooling_method': self.cooling_method,
  268. 'weight': float(self.weight) if self.weight is not None else None,
  269. 'weight_unit': self.weight_unit,
  270. 'end_of_life': self.end_of_life.isoformat() if self.end_of_life else None,
  271. 'comments': self.comments,
  272. }
  273. # Component templates
  274. if self.consoleporttemplates.exists():
  275. data['console-ports'] = [
  276. c.to_yaml() for c in self.consoleporttemplates.all()
  277. ]
  278. if self.consoleserverporttemplates.exists():
  279. data['console-server-ports'] = [
  280. c.to_yaml() for c in self.consoleserverporttemplates.all()
  281. ]
  282. if self.powerporttemplates.exists():
  283. data['power-ports'] = [
  284. c.to_yaml() for c in self.powerporttemplates.all()
  285. ]
  286. if self.poweroutlettemplates.exists():
  287. data['power-outlets'] = [
  288. c.to_yaml() for c in self.poweroutlettemplates.all()
  289. ]
  290. if self.coolingintaketemplates.exists():
  291. data['cooling-intakes'] = [
  292. c.to_yaml() for c in self.coolingintaketemplates.all()
  293. ]
  294. if self.coolingoutflowtemplates.exists():
  295. data['cooling-outflows'] = [
  296. c.to_yaml() for c in self.coolingoutflowtemplates.all()
  297. ]
  298. if self.interfacetemplates.exists():
  299. data['interfaces'] = [
  300. c.to_yaml() for c in self.interfacetemplates.all()
  301. ]
  302. if self.frontporttemplates.exists():
  303. data['front-ports'] = [
  304. c.to_yaml() for c in self.frontporttemplates.all()
  305. ]
  306. if self.rearporttemplates.exists():
  307. data['rear-ports'] = [
  308. c.to_yaml() for c in self.rearporttemplates.all()
  309. ]
  310. # Port mappings
  311. port_mapping_data = [
  312. c.to_yaml() for c in self.port_mappings.all()
  313. ]
  314. if port_mapping_data:
  315. data['port-mappings'] = port_mapping_data
  316. if self.modulebaytemplates.exists():
  317. data['module-bays'] = [
  318. c.to_yaml() for c in self.modulebaytemplates.all()
  319. ]
  320. if self.devicebaytemplates.exists():
  321. data['device-bays'] = [
  322. c.to_yaml() for c in self.devicebaytemplates.all()
  323. ]
  324. return yaml.dump(dict(data), sort_keys=False)
  325. def clean(self):
  326. super().clean()
  327. # U height must be divisible by 0.5
  328. if decimal.Decimal(self.u_height) % decimal.Decimal(0.5):
  329. raise ValidationError({
  330. 'u_height': _("U height must be in increments of 0.5 rack units.")
  331. })
  332. # If editing an existing DeviceType to have a larger u_height, first validate that *all* instances of it have
  333. # room to expand within their racks. This validation will impose a very high performance penalty when there are
  334. # many instances to check, but increasing the u_height of a DeviceType should be a very rare occurrence.
  335. if not self._state.adding and self.u_height > self._original_u_height:
  336. for d in Device.objects.filter(device_type=self, position__isnull=False):
  337. face_required = None if self.is_full_depth else d.face
  338. u_available = d.rack.get_available_units(
  339. u_height=self.u_height,
  340. rack_face=face_required,
  341. exclude=[d.pk]
  342. )
  343. if d.position not in u_available:
  344. raise ValidationError({
  345. 'u_height': _(
  346. "Device {device} in rack {rack} does not have sufficient space to accommodate a "
  347. "height of {height}U"
  348. ).format(device=d, rack=d.rack, height=self.u_height)
  349. })
  350. # If modifying the height of an existing DeviceType to 0U, check for any instances assigned to a rack position.
  351. elif not self._state.adding and self._original_u_height > 0 and self.u_height == 0:
  352. racked_instance_count = Device.objects.filter(
  353. device_type=self,
  354. position__isnull=False
  355. ).count()
  356. if racked_instance_count:
  357. url = f"{reverse('dcim:device_list')}?manufactuer_id={self.manufacturer_id}&device_type_id={self.pk}"
  358. raise ValidationError({
  359. 'u_height': mark_safe(_(
  360. 'Unable to set 0U height: Found <a href="{url}">{racked_instance_count} instances</a> already '
  361. 'mounted within racks.'
  362. ).format(url=url, racked_instance_count=racked_instance_count))
  363. })
  364. if (
  365. self.subdevice_role != SubdeviceRoleChoices.ROLE_PARENT
  366. ) and self.pk and self.devicebaytemplates.count():
  367. raise ValidationError({
  368. 'subdevice_role': _("Must delete all device bay templates associated with this device before "
  369. "declassifying it as a parent device.")
  370. })
  371. if self.u_height and self.subdevice_role == SubdeviceRoleChoices.ROLE_CHILD:
  372. raise ValidationError({
  373. 'u_height': _("Child device types must be 0U.")
  374. })
  375. def save(self, *args, **kwargs):
  376. update_fields = normalize_update_fields(kwargs)
  377. # Use the write database for the image lookup and cleanup transaction.
  378. using = kwargs.get('using') or router.db_for_write(self.__class__, instance=self)
  379. # Retrieve stored image names only for fields being saved.
  380. deferred_fields = self.get_deferred_fields()
  381. image_fields = [
  382. field_name for field_name in ('front_image', 'rear_image')
  383. if field_name not in deferred_fields and (update_fields is None or field_name in update_fields)
  384. ]
  385. original_images = {}
  386. if image_fields and self.pk is not None:
  387. original_images = DeviceType.objects.using(using).filter(pk=self.pk).values(*image_fields).first() or {}
  388. kwargs['using'] = using
  389. ret = super().save(*args, **kwargs)
  390. # Delete replaced files after commit to preserve them on rollback.
  391. # Log cleanup failures without failing an already committed save.
  392. for field_name, original_name in original_images.items():
  393. if original_name and getattr(self, field_name).name != original_name:
  394. transaction.on_commit(partial(default_storage.delete, original_name), using=using, robust=True)
  395. return ret
  396. def delete(self, *args, **kwargs):
  397. super().delete(*args, **kwargs)
  398. # Delete any uploaded image files
  399. if self.front_image:
  400. self.front_image.delete(save=False)
  401. if self.rear_image:
  402. self.rear_image.delete(save=False)
  403. @property
  404. def is_parent_device(self):
  405. return self.subdevice_role == SubdeviceRoleChoices.ROLE_PARENT
  406. @property
  407. def is_child_device(self):
  408. return self.subdevice_role == SubdeviceRoleChoices.ROLE_CHILD
  409. #
  410. # Devices
  411. #
  412. class DeviceRole(NestedLtreeGroupModel):
  413. """
  414. Devices are organized by functional role; for example, "Core Switch" or "File Server". Each DeviceRole is assigned a
  415. color to be used when displaying rack elevations. The vm_role field determines whether the role is applicable to
  416. virtual machines as well.
  417. """
  418. color = ColorField(
  419. verbose_name=_('color'),
  420. default=ColorChoices.COLOR_GREY
  421. )
  422. vm_role = models.BooleanField(
  423. default=True,
  424. verbose_name=_('VM role'),
  425. help_text=_('Virtual machines may be assigned to this role')
  426. )
  427. config_template = models.ForeignKey(
  428. to='extras.ConfigTemplate',
  429. on_delete=models.PROTECT,
  430. related_name='device_roles',
  431. blank=True,
  432. null=True
  433. )
  434. clone_fields = ('parent', 'description')
  435. class Meta:
  436. ordering = ('sort_path',)
  437. indexes = (
  438. GistIndex(fields=['path'], name='dcim_devicerole_path_gist'),
  439. models.Index(fields=['sort_path'], name='dcim_devicerole_sort_path_idx'),
  440. )
  441. constraints = (
  442. models.UniqueConstraint(
  443. fields=('parent', 'name'),
  444. name='%(app_label)s_%(class)s_parent_name',
  445. nulls_distinct=False,
  446. violation_error_message=_("A device role with this name already exists.")
  447. ),
  448. models.UniqueConstraint(
  449. fields=('parent', 'slug'),
  450. name='%(app_label)s_%(class)s_parent_slug',
  451. nulls_distinct=False,
  452. violation_error_message=_("A device role with this slug already exists.")
  453. ),
  454. )
  455. verbose_name = _('device role')
  456. verbose_name_plural = _('device roles')
  457. class Platform(NestedLtreeGroupModel):
  458. """
  459. Platform refers to the software or firmware running on a Device. For example, "Cisco IOS-XR" or "Juniper Junos". A
  460. Platform may optionally be associated with a particular Manufacturer.
  461. """
  462. manufacturer = models.ForeignKey(
  463. to='dcim.Manufacturer',
  464. on_delete=models.PROTECT,
  465. related_name='platforms',
  466. blank=True,
  467. null=True,
  468. help_text=_('Optionally limit this platform to devices of a certain manufacturer')
  469. )
  470. config_template = models.ForeignKey(
  471. to='extras.ConfigTemplate',
  472. on_delete=models.PROTECT,
  473. related_name='platforms',
  474. blank=True,
  475. null=True
  476. )
  477. clone_fields = ('parent', 'description')
  478. class Meta:
  479. ordering = ('sort_path',)
  480. indexes = (
  481. GistIndex(fields=['path'], name='dcim_platform_path_gist'),
  482. models.Index(fields=['sort_path'], name='dcim_platform_sort_path_idx'),
  483. )
  484. verbose_name = _('platform')
  485. verbose_name_plural = _('platforms')
  486. constraints = (
  487. models.UniqueConstraint(
  488. fields=('manufacturer', 'name'),
  489. name='%(app_label)s_%(class)s_manufacturer_name',
  490. nulls_distinct=False,
  491. violation_error_message=_("Platform name must be unique.")
  492. ),
  493. models.UniqueConstraint(
  494. fields=('manufacturer', 'slug'),
  495. name='%(app_label)s_%(class)s_manufacturer_slug',
  496. nulls_distinct=False,
  497. violation_error_message=_("Platform slug must be unique.")
  498. ),
  499. )
  500. class Device(
  501. ContactsMixin,
  502. ImageAttachmentsMixin,
  503. RenderConfigMixin,
  504. WebMercatorMixin,
  505. ConfigContextModel,
  506. TrackingModelMixin,
  507. PrimaryModel
  508. ):
  509. """
  510. A Device represents a piece of physical hardware mounted within a Rack. Each Device is assigned a DeviceType,
  511. DeviceRole, and (optionally) a Platform. Device names are not required, however if one is set it must be unique.
  512. Each Device must be assigned to a site, and optionally to a rack within that site. Associating a device with a
  513. particular rack face or unit is optional (for example, vertically mounted PDUs do not consume rack units).
  514. When a new Device is created, console/power/interface/device bay components are created along with it as dictated
  515. by the component templates assigned to its DeviceType. Components can also be added, modified, or deleted after the
  516. creation of a Device.
  517. """
  518. device_type = models.ForeignKey(
  519. to='dcim.DeviceType',
  520. on_delete=models.PROTECT,
  521. related_name='instances'
  522. )
  523. role = models.ForeignKey(
  524. to='dcim.DeviceRole',
  525. on_delete=models.PROTECT,
  526. related_name='devices',
  527. help_text=_("The function this device serves")
  528. )
  529. tenant = models.ForeignKey(
  530. to='tenancy.Tenant',
  531. on_delete=models.PROTECT,
  532. related_name='devices',
  533. blank=True,
  534. null=True
  535. )
  536. platform = models.ForeignKey(
  537. to='dcim.Platform',
  538. on_delete=models.SET_NULL,
  539. related_name='devices',
  540. blank=True,
  541. null=True
  542. )
  543. name = models.CharField(
  544. verbose_name=_('name'),
  545. max_length=64,
  546. blank=True,
  547. null=True,
  548. db_collation="natural_sort"
  549. )
  550. serial = models.CharField(
  551. max_length=50,
  552. blank=True,
  553. verbose_name=_('serial number'),
  554. help_text=_("Chassis serial number, assigned by the manufacturer")
  555. )
  556. asset_tag = models.CharField(
  557. max_length=50,
  558. blank=True,
  559. null=True,
  560. unique=True,
  561. verbose_name=_('asset tag'),
  562. help_text=_('A unique tag used to identify this device')
  563. )
  564. site = models.ForeignKey(
  565. to='dcim.Site',
  566. on_delete=models.PROTECT,
  567. related_name='devices'
  568. )
  569. location = models.ForeignKey(
  570. to='dcim.Location',
  571. on_delete=models.PROTECT,
  572. related_name='devices',
  573. blank=True,
  574. null=True
  575. )
  576. rack = models.ForeignKey(
  577. to='dcim.Rack',
  578. on_delete=models.PROTECT,
  579. related_name='devices',
  580. blank=True,
  581. null=True
  582. )
  583. position = models.DecimalField(
  584. max_digits=4,
  585. decimal_places=1,
  586. blank=True,
  587. null=True,
  588. validators=[MinValueValidator(1), MaxValueValidator(RACK_U_HEIGHT_MAX + 0.5)],
  589. verbose_name=_('position (U)'),
  590. help_text=_('The lowest-numbered unit occupied by the device')
  591. )
  592. face = models.CharField(
  593. max_length=50,
  594. blank=True,
  595. null=True,
  596. choices=DeviceFaceChoices,
  597. verbose_name=_('rack face')
  598. )
  599. status = models.CharField(
  600. verbose_name=_('status'),
  601. max_length=50,
  602. choices=DeviceStatusChoices,
  603. default=DeviceStatusChoices.STATUS_ACTIVE
  604. )
  605. airflow = models.CharField(
  606. verbose_name=_('airflow'),
  607. max_length=50,
  608. choices=DeviceAirflowChoices,
  609. blank=True,
  610. null=True
  611. )
  612. cooling_method = models.CharField(
  613. verbose_name=_('cooling method'),
  614. max_length=50,
  615. choices=CoolingMethodChoices,
  616. blank=True,
  617. null=True
  618. )
  619. primary_ip4 = models.OneToOneField(
  620. to='ipam.IPAddress',
  621. on_delete=models.SET_NULL,
  622. related_name='+',
  623. blank=True,
  624. null=True,
  625. verbose_name=_('primary IPv4')
  626. )
  627. primary_ip6 = models.OneToOneField(
  628. to='ipam.IPAddress',
  629. on_delete=models.SET_NULL,
  630. related_name='+',
  631. blank=True,
  632. null=True,
  633. verbose_name=_('primary IPv6')
  634. )
  635. oob_ip = models.OneToOneField(
  636. to='ipam.IPAddress',
  637. on_delete=models.SET_NULL,
  638. related_name='+',
  639. blank=True,
  640. null=True,
  641. verbose_name=_('out-of-band IP')
  642. )
  643. cluster = models.ForeignKey(
  644. to='virtualization.Cluster',
  645. on_delete=models.SET_NULL,
  646. related_name='devices',
  647. blank=True,
  648. null=True
  649. )
  650. virtual_chassis = models.ForeignKey(
  651. to='VirtualChassis',
  652. on_delete=models.SET_NULL,
  653. related_name='members',
  654. blank=True,
  655. null=True
  656. )
  657. vc_position = models.PositiveIntegerField(
  658. verbose_name=_('VC position'),
  659. blank=True,
  660. null=True,
  661. help_text=_('Virtual chassis position')
  662. )
  663. vc_priority = models.PositiveSmallIntegerField(
  664. verbose_name=_('VC priority'),
  665. blank=True,
  666. null=True,
  667. validators=[MaxValueValidator(255)],
  668. help_text=_('Virtual chassis master election priority')
  669. )
  670. latitude = models.DecimalField(
  671. verbose_name=_('latitude'),
  672. max_digits=8,
  673. decimal_places=6,
  674. blank=True,
  675. null=True,
  676. validators=[
  677. MinValueValidator(decimal.Decimal('-90.0')),
  678. MaxValueValidator(decimal.Decimal('90.0'))
  679. ],
  680. help_text=_("GPS coordinate in decimal format (xx.yyyyyy)")
  681. )
  682. longitude = models.DecimalField(
  683. verbose_name=_('longitude'),
  684. max_digits=9,
  685. decimal_places=6,
  686. blank=True,
  687. null=True,
  688. validators=[
  689. MinValueValidator(decimal.Decimal('-180.0')),
  690. MaxValueValidator(decimal.Decimal('180.0'))
  691. ],
  692. help_text=_("GPS coordinate in decimal format (xx.yyyyyy)")
  693. )
  694. services = GenericRelation(
  695. to='ipam.Service',
  696. content_type_field='parent_object_type',
  697. object_id_field='parent_object_id',
  698. related_query_name='device',
  699. )
  700. # Counter fields
  701. console_port_count = CounterCacheField(
  702. to_model='dcim.ConsolePort',
  703. to_field='device'
  704. )
  705. console_server_port_count = CounterCacheField(
  706. to_model='dcim.ConsoleServerPort',
  707. to_field='device'
  708. )
  709. power_port_count = CounterCacheField(
  710. to_model='dcim.PowerPort',
  711. to_field='device'
  712. )
  713. power_outlet_count = CounterCacheField(
  714. to_model='dcim.PowerOutlet',
  715. to_field='device'
  716. )
  717. cooling_intake_count = CounterCacheField(
  718. to_model='dcim.CoolingIntake',
  719. to_field='device'
  720. )
  721. cooling_outflow_count = CounterCacheField(
  722. to_model='dcim.CoolingOutflow',
  723. to_field='device'
  724. )
  725. interface_count = CounterCacheField(
  726. to_model='dcim.Interface',
  727. to_field='device'
  728. )
  729. front_port_count = CounterCacheField(
  730. to_model='dcim.FrontPort',
  731. to_field='device'
  732. )
  733. rear_port_count = CounterCacheField(
  734. to_model='dcim.RearPort',
  735. to_field='device'
  736. )
  737. device_bay_count = CounterCacheField(
  738. to_model='dcim.DeviceBay',
  739. to_field='device'
  740. )
  741. module_bay_count = CounterCacheField(
  742. to_model='dcim.ModuleBay',
  743. to_field='device'
  744. )
  745. inventory_item_count = CounterCacheField(
  746. to_model='dcim.InventoryItem',
  747. to_field='device'
  748. )
  749. objects = ConfigContextModelQuerySet.as_manager()
  750. clone_fields = (
  751. 'device_type', 'role', 'tenant', 'platform', 'site', 'location', 'rack', 'face', 'status', 'airflow',
  752. 'cooling_method', 'cluster', 'virtual_chassis',
  753. )
  754. prerequisite_models = (
  755. 'dcim.Site',
  756. 'dcim.DeviceRole',
  757. 'dcim.DeviceType',
  758. )
  759. class Meta:
  760. ordering = ('name', 'pk') # Name may be null
  761. indexes = (
  762. models.Index(fields=('name', 'id')), # Default ordering
  763. # Partial index supporting the background renderer's scan for objects whose config
  764. # context cache has been invalidated (see extras.jobs.RenderConfigContextJob and
  765. # extras.cache). Indexing only the NULL-cache rows keeps that lookup cheap on large
  766. # tables where the steady state is for nearly every row to be populated.
  767. models.Index(
  768. fields=('id',),
  769. condition=Q(_config_context_data__isnull=True),
  770. name='dcim_device_cc_null',
  771. ),
  772. )
  773. constraints = (
  774. models.UniqueConstraint(
  775. Lower('name'), 'site', 'tenant',
  776. name='%(app_label)s_%(class)s_unique_name_site_tenant',
  777. condition=Q(name__isnull=False),
  778. nulls_distinct=False,
  779. violation_error_message=_("Device name must be unique per site and tenant.")
  780. ),
  781. models.UniqueConstraint(
  782. fields=('rack', 'position', 'face'),
  783. name='%(app_label)s_%(class)s_unique_rack_position_face'
  784. ),
  785. models.UniqueConstraint(
  786. fields=('virtual_chassis', 'vc_position'),
  787. name='%(app_label)s_%(class)s_unique_virtual_chassis_vc_position'
  788. ),
  789. )
  790. verbose_name = _('device')
  791. verbose_name_plural = _('devices')
  792. permissions = [
  793. ('render_config', 'Render configuration'),
  794. ]
  795. def __init__(self, *args, replicate_components=True, **kwargs):
  796. super().__init__(*args, **kwargs)
  797. # Controls whether components are instantiated from the DeviceType when a new Device is saved
  798. self._disable_replication = not replicate_components
  799. def __str__(self):
  800. if self.label and self.asset_tag:
  801. return f'{self.label} ({self.asset_tag})'
  802. if self.label:
  803. return self.label
  804. if self.device_type and self.asset_tag:
  805. return f'{self.device_type.manufacturer} {self.device_type.model} ({self.asset_tag})'
  806. if self.device_type:
  807. return f'{self.device_type.manufacturer} {self.device_type.model} ({self.pk})'
  808. return super().__str__()
  809. def clean(self):
  810. super().clean()
  811. # Validate site/location/rack combination
  812. if self.rack and self.site != self.rack.site:
  813. raise ValidationError({
  814. 'rack': _("Rack {rack} does not belong to site {site}.").format(rack=self.rack, site=self.site),
  815. })
  816. if self.location and self.site != self.location.site:
  817. raise ValidationError({
  818. 'location': _(
  819. "Location {location} does not belong to site {site}."
  820. ).format(location=self.location, site=self.site)
  821. })
  822. if self.rack and self.location and self.rack.location != self.location:
  823. raise ValidationError({
  824. 'rack': _(
  825. "Rack {rack} does not belong to location {location}."
  826. ).format(rack=self.rack, location=self.location)
  827. })
  828. if self.rack is None:
  829. if self.face:
  830. raise ValidationError({
  831. 'face': _("Cannot select a rack face without assigning a rack."),
  832. })
  833. if self.position:
  834. raise ValidationError({
  835. 'position': _("Cannot select a rack position without assigning a rack."),
  836. })
  837. # Validate rack position and face
  838. if self.position and self.position % decimal.Decimal(0.5):
  839. raise ValidationError({
  840. 'position': _("Position must be in increments of 0.5 rack units.")
  841. })
  842. if self.position and not self.face:
  843. raise ValidationError({
  844. 'face': _("Must specify rack face when defining rack position."),
  845. })
  846. # Prevent 0U devices from being assigned to a specific position
  847. if hasattr(self, 'device_type'):
  848. if self.position and self.device_type.u_height == 0:
  849. raise ValidationError({
  850. 'position': _(
  851. "A 0U device type ({device_type}) cannot be assigned to a rack position."
  852. ).format(device_type=self.device_type)
  853. })
  854. if self.rack:
  855. try:
  856. # Child devices cannot be assigned to a rack face/unit
  857. if self.device_type.is_child_device and self.face:
  858. raise ValidationError({
  859. 'face': _(
  860. "Child device types cannot be assigned to a rack face. This is an attribute of the parent "
  861. "device."
  862. )
  863. })
  864. if self.device_type.is_child_device and self.position:
  865. raise ValidationError({
  866. 'position': _(
  867. "Child device types cannot be assigned to a rack position. This is an attribute of the "
  868. "parent device."
  869. )
  870. })
  871. # Validate rack space
  872. rack_face = self.face if not self.device_type.is_full_depth else None
  873. exclude_list = [self.pk] if self.pk else []
  874. available_units = self.rack.get_available_units(
  875. u_height=self.device_type.u_height, rack_face=rack_face, exclude=exclude_list
  876. )
  877. if self.position and self.position not in available_units:
  878. raise ValidationError({
  879. 'position': _(
  880. "U{position} is already occupied or does not have sufficient space to accommodate this "
  881. "device type: {device_type} ({u_height}U)"
  882. ).format(
  883. position=self.position, device_type=self.device_type, u_height=self.device_type.u_height
  884. )
  885. })
  886. except DeviceType.DoesNotExist:
  887. pass
  888. # Validate primary & OOB IP addresses
  889. vc_interfaces = self.vc_interfaces(if_master=False)
  890. if self.primary_ip4:
  891. if self.primary_ip4.family != 4:
  892. raise ValidationError({
  893. 'primary_ip4': _("{ip} is not an IPv4 address.").format(ip=self.primary_ip4)
  894. })
  895. if self.primary_ip4.assigned_object in vc_interfaces:
  896. pass
  897. elif (
  898. self.primary_ip4.nat_inside is not None and
  899. self.primary_ip4.nat_inside.assigned_object in vc_interfaces
  900. ):
  901. pass
  902. else:
  903. raise ValidationError({
  904. 'primary_ip4': _(
  905. "The specified IP address ({ip}) is not assigned to this device."
  906. ).format(ip=self.primary_ip4)
  907. })
  908. if self.primary_ip6:
  909. if self.primary_ip6.family != 6:
  910. raise ValidationError({
  911. 'primary_ip6': _("{ip} is not an IPv6 address.").format(ip=self.primary_ip6)
  912. })
  913. if self.primary_ip6.assigned_object in vc_interfaces:
  914. pass
  915. elif (
  916. self.primary_ip6.nat_inside is not None and
  917. self.primary_ip6.nat_inside.assigned_object in vc_interfaces
  918. ):
  919. pass
  920. else:
  921. raise ValidationError({
  922. 'primary_ip6': _(
  923. "The specified IP address ({ip}) is not assigned to this device."
  924. ).format(ip=self.primary_ip6)
  925. })
  926. if self.oob_ip:
  927. if self.oob_ip.assigned_object in vc_interfaces:
  928. pass
  929. elif self.oob_ip.nat_inside is not None and self.oob_ip.nat_inside.assigned_object in vc_interfaces:
  930. pass
  931. else:
  932. raise ValidationError({
  933. 'oob_ip': f"The specified IP address ({self.oob_ip}) is not assigned to this device."
  934. })
  935. # Validate manufacturer/platform
  936. if hasattr(self, 'device_type') and self.platform:
  937. if self.platform.manufacturer and self.platform.manufacturer != self.device_type.manufacturer:
  938. raise ValidationError({
  939. 'platform': _(
  940. "The assigned platform is limited to {platform_manufacturer} device types, but this device's "
  941. "type belongs to {devicetype_manufacturer}."
  942. ).format(
  943. platform_manufacturer=self.platform.manufacturer,
  944. devicetype_manufacturer=self.device_type.manufacturer
  945. )
  946. })
  947. # A Device can only be assigned to a Cluster in the same Site (or no Site)
  948. if self.cluster and self.cluster._site is not None and self.cluster._site != self.site:
  949. raise ValidationError({
  950. 'cluster': _("The assigned cluster belongs to a different site ({site})").format(
  951. site=self.cluster._site
  952. )
  953. })
  954. if self.cluster and self.cluster._location is not None and self.cluster._location != self.location:
  955. raise ValidationError({
  956. 'cluster': _("The assigned cluster belongs to a different location ({location})").format(
  957. location=self.cluster._location
  958. )
  959. })
  960. # Validate virtual chassis assignment
  961. if self.virtual_chassis and self.vc_position is None:
  962. raise ValidationError({
  963. 'vc_position': _("A device assigned to a virtual chassis must have its position defined.")
  964. })
  965. if hasattr(self, 'vc_master_for') and self.vc_master_for and self.vc_master_for != self.virtual_chassis:
  966. raise ValidationError({
  967. 'virtual_chassis': _(
  968. 'Device cannot be removed from virtual chassis {virtual_chassis} because it is currently '
  969. 'designated as its master.'
  970. ).format(virtual_chassis=self.vc_master_for)
  971. })
  972. # Validate cross-chassis LAGs only when virtual chassis membership changes
  973. if self.pk:
  974. stored_vc_id = Device.objects.filter(pk=self.pk).values_list('virtual_chassis_id', flat=True).first()
  975. if self.virtual_chassis_id != stored_vc_id:
  976. self.clean_vc_lag_membership()
  977. def clean_vc_lag_membership(self, members=None):
  978. """
  979. Raise ValidationError if any interface would form a LAG with a device outside this device's virtual chassis.
  980. `members` overrides the set of fellow chassis members (used when the chassis has not been saved yet).
  981. """
  982. lag_members = Interface.objects.filter(device=self, lag__isnull=False).exclude(lag__device=self)
  983. lag_peers = Interface.objects.filter(lag__device=self).exclude(device=self)
  984. if members is not None:
  985. lag_members = lag_members.exclude(lag__device__in=members)
  986. lag_peers = lag_peers.exclude(device__in=members)
  987. elif self.virtual_chassis_id:
  988. lag_members = lag_members.exclude(lag__device__virtual_chassis=self.virtual_chassis_id)
  989. lag_peers = lag_peers.exclude(device__virtual_chassis=self.virtual_chassis_id)
  990. interfaces = [
  991. *lag_members.select_related('device', 'lag__device'),
  992. *lag_peers.select_related('device', 'lag__device'),
  993. ]
  994. if interfaces:
  995. # Cap the listed interfaces to keep the message readable
  996. max_listed = 5
  997. listed = ', '.join(f'{i.device}:{i} ({i.lag.device}:{i.lag})' for i in interfaces[:max_listed])
  998. if len(interfaces) > max_listed:
  999. listed += _(' (and {count} more)').format(count=len(interfaces) - max_listed)
  1000. raise ValidationError({
  1001. 'virtual_chassis': _(
  1002. 'Virtual chassis membership cannot be changed while interfaces form a LAG with another device '
  1003. 'outside the virtual chassis: {interfaces}'
  1004. ).format(interfaces=listed)
  1005. })
  1006. def _check_duplicate_component_names(self, components):
  1007. """
  1008. Check for duplicate component names after resolving {vc_position} placeholders.
  1009. Raises AbortRequest if duplicates are found.
  1010. """
  1011. names = [c.name for c in components]
  1012. duplicates = {n for n in names if names.count(n) > 1}
  1013. if duplicates:
  1014. raise AbortRequest(
  1015. _("Component name conflict after resolving {{vc_position}}: {names}").format(
  1016. names=', '.join(duplicates)
  1017. )
  1018. )
  1019. def _instantiate_components(self, queryset, bulk_create=True):
  1020. """
  1021. Instantiate components for the device from the specified component templates.
  1022. Args:
  1023. bulk_create: If True, bulk_create() will be called to create all components in a single query
  1024. (default). Otherwise, save() will be called on each instance individually.
  1025. """
  1026. model = queryset.model.component_model
  1027. using = self._state.db
  1028. if bulk_create:
  1029. components = [obj.instantiate(device=self) for obj in queryset]
  1030. if not components:
  1031. return
  1032. # Check for duplicate names after resolution {vc_position}
  1033. self._check_duplicate_component_names(components)
  1034. # Set default values for any applicable custom fields
  1035. if cf_defaults := CustomField.objects.get_defaults_for_model(model):
  1036. for component in components:
  1037. component.custom_field_data = cf_defaults
  1038. # Set denormalized references
  1039. for component in components:
  1040. component._site = self.site
  1041. component._location = self.location
  1042. component._rack = self.rack
  1043. components = model.objects.using(using).bulk_create(components)
  1044. # Prefetch related objects to minimize queries needed during post_save
  1045. prefetch_fields = get_prefetchable_fields(model)
  1046. prefetch_related_objects(components, *prefetch_fields)
  1047. # Manually send the post_save signal for each of the newly created components
  1048. for component in components:
  1049. post_save.send(
  1050. sender=model,
  1051. instance=component,
  1052. created=True,
  1053. raw=False,
  1054. using=using,
  1055. update_fields=None
  1056. )
  1057. else:
  1058. components = [obj.instantiate(device=self) for obj in queryset]
  1059. if not components:
  1060. return
  1061. # Check for duplicate names after resolution {vc_position}
  1062. self._check_duplicate_component_names(components)
  1063. for component in components:
  1064. # Set default values for any applicable custom fields
  1065. if cf_defaults := CustomField.objects.get_defaults_for_model(model):
  1066. component.custom_field_data = cf_defaults
  1067. component.save(using=using)
  1068. # Copy module_bay_types from the source template (set by instantiate()).
  1069. if src := getattr(component, '_source_template', None):
  1070. if hasattr(component, 'module_bay_types'):
  1071. component.module_bay_types.set(src.module_bay_types.db_manager(using).all())
  1072. def save(self, *args, **kwargs):
  1073. is_new = not bool(self.pk)
  1074. # Inherit airflow attribute from DeviceType if not set
  1075. if is_new and not self.airflow:
  1076. self.airflow = self.device_type.airflow
  1077. # Inherit cooling_method attribute from DeviceType if not set
  1078. if is_new and not self.cooling_method:
  1079. self.cooling_method = self.device_type.cooling_method
  1080. # Inherit default_platform from DeviceType if not set
  1081. if is_new and not self.platform:
  1082. self.platform = self.device_type.default_platform
  1083. # Inherit location from Rack if not set
  1084. if self.rack and self.rack.location:
  1085. self.location = self.rack.location
  1086. super().save(*args, **kwargs)
  1087. # Instantiate components from the device type
  1088. if is_new and not self._disable_replication:
  1089. self._instantiate_components(self.device_type.consoleporttemplates.all())
  1090. self._instantiate_components(self.device_type.consoleserverporttemplates.all())
  1091. self._instantiate_components(self.device_type.powerporttemplates.all())
  1092. self._instantiate_components(self.device_type.poweroutlettemplates.all())
  1093. self._instantiate_components(self.device_type.coolingintaketemplates.all())
  1094. self._instantiate_components(self.device_type.coolingoutflowtemplates.all())
  1095. self._instantiate_components(self.device_type.interfacetemplates.all())
  1096. self._instantiate_components(self.device_type.rearporttemplates.all())
  1097. self._instantiate_components(self.device_type.frontporttemplates.all())
  1098. # Replicate any front/rear port mappings from the DeviceType
  1099. create_port_mappings(self, self.device_type)
  1100. # Disable bulk_create to accommodate MPTT
  1101. self._instantiate_components(self.device_type.modulebaytemplates.all(), bulk_create=False)
  1102. self._instantiate_components(self.device_type.devicebaytemplates.all())
  1103. # Disable bulk_create to accommodate MPTT
  1104. self._instantiate_components(self.device_type.inventoryitemtemplates.all(), bulk_create=False)
  1105. # Interface parents & bridges have to be set after interface instantiation. Parents are applied first so
  1106. # that channel subinterfaces validate against a populated parent.
  1107. update_interface_parents(self, self.device_type.interfacetemplates.all())
  1108. update_interface_bridges(self, self.device_type.interfacetemplates.all())
  1109. # Update Site and Rack assignment for any child Devices
  1110. devices = Device.objects.filter(parent_bay__device=self)
  1111. for device in devices:
  1112. device.snapshot()
  1113. device.site = self.site
  1114. device.rack = self.rack
  1115. device.location = self.location
  1116. device.save()
  1117. @property
  1118. def label(self):
  1119. """
  1120. Return the device name if set; otherwise return a generated name if available.
  1121. """
  1122. if self.name:
  1123. return self.name
  1124. if self.virtual_chassis:
  1125. return f'{self.virtual_chassis.name}:{self.vc_position}'
  1126. return None
  1127. @property
  1128. def identifier(self):
  1129. """
  1130. Return the device name if set; otherwise return the Device's primary key as {pk}
  1131. """
  1132. return self.label or '{{{}}}'.format(self.pk)
  1133. @property
  1134. def primary_ip(self):
  1135. if ConfigItem('PREFER_IPV4')() and self.primary_ip4:
  1136. return self.primary_ip4
  1137. if self.primary_ip6:
  1138. return self.primary_ip6
  1139. if self.primary_ip4:
  1140. return self.primary_ip4
  1141. return None
  1142. @property
  1143. def interfaces_count(self):
  1144. return self.vc_interfaces().count()
  1145. def get_vc_master(self):
  1146. """
  1147. If this Device is a VirtualChassis member, return the VC master. Otherwise, return None.
  1148. """
  1149. return self.virtual_chassis.master if self.virtual_chassis else None
  1150. def vc_interfaces(self, if_master=True):
  1151. """
  1152. Return a QuerySet matching all Interfaces assigned to this Device or, if this Device is a VC master, to another
  1153. Device belonging to the same VirtualChassis.
  1154. :param if_master: If True, return VC member interfaces only if this Device is the VC master.
  1155. """
  1156. # An unsaved device owns no interfaces. Q() would match all of them.
  1157. filter = Q(device=self) if self.pk else Q(pk__in=[])
  1158. if self.virtual_chassis and (self.virtual_chassis.master == self or not if_master):
  1159. filter |= Q(device__virtual_chassis=self.virtual_chassis, mgmt_only=False)
  1160. return Interface.objects.filter(filter)
  1161. def get_cables(self, pk_list=False):
  1162. """
  1163. Return a QuerySet or PK list matching all Cables connected to a component of this Device.
  1164. """
  1165. from .cables import Cable
  1166. cable_pks = []
  1167. for component_model in [
  1168. ConsolePort, ConsoleServerPort, PowerPort, PowerOutlet, Interface, FrontPort, RearPort
  1169. ]:
  1170. cable_pks += component_model.objects.filter(
  1171. device=self, cable__isnull=False
  1172. ).values_list('cable', flat=True)
  1173. if pk_list:
  1174. return cable_pks
  1175. return Cable.objects.filter(pk__in=cable_pks)
  1176. def get_children(self):
  1177. """
  1178. Return the set of child Devices installed in DeviceBays within this Device.
  1179. """
  1180. return Device.objects.filter(parent_bay__device=self.pk)
  1181. def get_status_color(self):
  1182. return DeviceStatusChoices.colors.get(self.status)
  1183. def get_cooling_method_color(self):
  1184. return CoolingMethodChoices.colors.get(self.cooling_method)
  1185. @cached_property
  1186. def total_weight(self):
  1187. total_weight = sum(
  1188. module.module_type._abs_weight
  1189. for module in Module.objects.filter(device=self)
  1190. .exclude(module_type___abs_weight__isnull=True)
  1191. .prefetch_related('module_type')
  1192. )
  1193. if self.device_type._abs_weight:
  1194. total_weight += self.device_type._abs_weight
  1195. return round(total_weight / 1000, 2)
  1196. #
  1197. # Virtual chassis
  1198. #
  1199. class VirtualChassis(PrimaryModel):
  1200. """
  1201. A collection of Devices which operate with a shared control plane (e.g. a switch stack).
  1202. """
  1203. master = models.OneToOneField(
  1204. to='Device',
  1205. on_delete=models.PROTECT,
  1206. related_name='vc_master_for',
  1207. blank=True,
  1208. null=True
  1209. )
  1210. name = models.CharField(
  1211. verbose_name=_('name'),
  1212. max_length=64,
  1213. db_collation="natural_sort"
  1214. )
  1215. domain = models.CharField(
  1216. verbose_name=_('domain'),
  1217. max_length=30,
  1218. blank=True
  1219. )
  1220. # Counter fields
  1221. member_count = CounterCacheField(
  1222. to_model='dcim.Device',
  1223. to_field='virtual_chassis'
  1224. )
  1225. class Meta:
  1226. ordering = ['name']
  1227. indexes = (
  1228. models.Index(fields=('name',)), # Default ordering
  1229. )
  1230. verbose_name = _('virtual chassis')
  1231. verbose_name_plural = _('virtual chassis')
  1232. def __str__(self):
  1233. return self.name
  1234. def clean(self):
  1235. super().clean()
  1236. # Verify that the selected master device has been assigned to this VirtualChassis. (Skip when creating a new
  1237. # VirtualChassis.)
  1238. if not self._state.adding and self.master and self.master not in self.members.all():
  1239. raise ValidationError({
  1240. 'master': _("The selected master ({master}) is not assigned to this virtual chassis.").format(
  1241. master=self.master
  1242. )
  1243. })
  1244. def delete(self, *args, **kwargs):
  1245. # Check for LAG interfaces split across member chassis
  1246. interfaces = Interface.objects.filter(
  1247. device__in=self.members.all(),
  1248. lag__isnull=False
  1249. ).exclude(
  1250. lag__device=F('device')
  1251. )
  1252. if interfaces:
  1253. raise ProtectedError(
  1254. _(
  1255. "Unable to delete virtual chassis {virtual_chassis}. One or more member interfaces form a "
  1256. "cross-chassis LAG."
  1257. ).format(virtual_chassis=self),
  1258. set(interfaces),
  1259. )
  1260. # Core's pre_delete handler detaches each member (clearing virtual_chassis) and records that change. Clear the
  1261. # now-meaningless position and priority afterwards, as a second change which is valid on its own.
  1262. using = kwargs.get('using') or router.db_for_write(self.__class__, instance=self)
  1263. member_ids = list(self.members.values_list('pk', flat=True))
  1264. with transaction.atomic(using=using):
  1265. ret = super().delete(*args, **kwargs)
  1266. for device in Device.objects.using(using).filter(pk__in=member_ids):
  1267. device.snapshot()
  1268. device.vc_position = None
  1269. device.vc_priority = None
  1270. device.save(using=using)
  1271. return ret
  1272. class VirtualDeviceContext(PrimaryModel):
  1273. device = models.ForeignKey(
  1274. to='Device',
  1275. on_delete=models.PROTECT,
  1276. related_name='vdcs',
  1277. blank=True,
  1278. null=True
  1279. )
  1280. name = models.CharField(
  1281. verbose_name=_('name'),
  1282. max_length=64,
  1283. db_collation="natural_sort"
  1284. )
  1285. status = models.CharField(
  1286. verbose_name=_('status'),
  1287. max_length=50,
  1288. choices=VirtualDeviceContextStatusChoices,
  1289. )
  1290. identifier = models.PositiveSmallIntegerField(
  1291. verbose_name=_('identifier'),
  1292. help_text=_('Numeric identifier unique to the parent device'),
  1293. blank=True,
  1294. null=True,
  1295. )
  1296. primary_ip4 = models.OneToOneField(
  1297. to='ipam.IPAddress',
  1298. on_delete=models.SET_NULL,
  1299. related_name='+',
  1300. blank=True,
  1301. null=True,
  1302. verbose_name=_('primary IPv4')
  1303. )
  1304. primary_ip6 = models.OneToOneField(
  1305. to='ipam.IPAddress',
  1306. on_delete=models.SET_NULL,
  1307. related_name='+',
  1308. blank=True,
  1309. null=True,
  1310. verbose_name=_('primary IPv6')
  1311. )
  1312. tenant = models.ForeignKey(
  1313. to='tenancy.Tenant',
  1314. on_delete=models.PROTECT,
  1315. related_name='vdcs',
  1316. blank=True,
  1317. null=True
  1318. )
  1319. comments = models.TextField(
  1320. verbose_name=_('comments'),
  1321. blank=True
  1322. )
  1323. class Meta:
  1324. ordering = ['name']
  1325. constraints = (
  1326. models.UniqueConstraint(
  1327. fields=('device', 'identifier',),
  1328. name='%(app_label)s_%(class)s_device_identifier'
  1329. ),
  1330. models.UniqueConstraint(
  1331. fields=('device', 'name',),
  1332. name='%(app_label)s_%(class)s_device_name'
  1333. ),
  1334. )
  1335. indexes = (
  1336. models.Index(fields=('name',)), # Default ordering
  1337. )
  1338. verbose_name = _('virtual device context')
  1339. verbose_name_plural = _('virtual device contexts')
  1340. def __str__(self):
  1341. return self.name
  1342. def get_status_color(self):
  1343. return VirtualDeviceContextStatusChoices.colors.get(self.status)
  1344. @property
  1345. def primary_ip(self):
  1346. if ConfigItem('PREFER_IPV4')() and self.primary_ip4:
  1347. return self.primary_ip4
  1348. if self.primary_ip6:
  1349. return self.primary_ip6
  1350. if self.primary_ip4:
  1351. return self.primary_ip4
  1352. return None
  1353. def clean(self):
  1354. super().clean()
  1355. # Validate primary IPv4/v6 assignment
  1356. for primary_ip, family in ((self.primary_ip4, 4), (self.primary_ip6, 6)):
  1357. if not primary_ip:
  1358. continue
  1359. if primary_ip.family != family:
  1360. raise ValidationError({
  1361. f'primary_ip{family}': _(
  1362. "{ip} is not an IPv{family} address."
  1363. ).format(family=family, ip=primary_ip)
  1364. })
  1365. device_interfaces = self.device.vc_interfaces(if_master=False) if self.device_id else []
  1366. if primary_ip.assigned_object not in device_interfaces:
  1367. raise ValidationError({
  1368. f'primary_ip{family}': _('Primary IP address must belong to an interface on the assigned device.')
  1369. })
  1370. #
  1371. # Addressing
  1372. #
  1373. class MACAddress(PrimaryModel):
  1374. mac_address = MACAddressField(
  1375. verbose_name=_('MAC address')
  1376. )
  1377. assigned_object_type = models.ForeignKey(
  1378. to='contenttypes.ContentType',
  1379. on_delete=models.PROTECT,
  1380. related_name='+',
  1381. blank=True,
  1382. null=True
  1383. )
  1384. assigned_object_id = models.PositiveBigIntegerField(
  1385. blank=True,
  1386. null=True
  1387. )
  1388. assigned_object = GenericForeignKey(
  1389. ct_field='assigned_object_type',
  1390. fk_field='assigned_object_id'
  1391. )
  1392. class Meta:
  1393. ordering = ('mac_address', 'pk')
  1394. indexes = (
  1395. models.Index(fields=('mac_address', 'id')), # Default ordering
  1396. models.Index(fields=('assigned_object_type', 'assigned_object_id')),
  1397. )
  1398. verbose_name = _('MAC address')
  1399. verbose_name_plural = _('MAC addresses')
  1400. def __str__(self):
  1401. return str(self.mac_address)
  1402. def __init__(self, *args, **kwargs):
  1403. super().__init__(*args, **kwargs)
  1404. # Denote the original assigned object (if any) for validation in clean()
  1405. self._original_assigned_object_id = self.__dict__.get('assigned_object_id')
  1406. self._original_assigned_object_type_id = self.__dict__.get('assigned_object_type_id')
  1407. @cached_property
  1408. def is_primary(self):
  1409. # Compare against primary_mac_address_id (a column already loaded on the assigned object) rather than
  1410. # dereferencing primary_mac_address, to avoid an extra query per object in list responses.
  1411. if (obj := self.assigned_object) is not None and hasattr(obj, 'primary_mac_address_id'):
  1412. return obj.primary_mac_address_id == self.pk
  1413. return False
  1414. def clean(self, *args, **kwargs):
  1415. super().clean()
  1416. if self._original_assigned_object_id and self._original_assigned_object_type_id:
  1417. assigned_object = self.assigned_object
  1418. ct = ContentType.objects.get_for_id(self._original_assigned_object_type_id)
  1419. original_assigned_object = ct.get_object_for_this_type(pk=self._original_assigned_object_id)
  1420. if (
  1421. original_assigned_object.primary_mac_address
  1422. and original_assigned_object.primary_mac_address.pk == self.pk
  1423. ):
  1424. if not assigned_object:
  1425. raise ValidationError(
  1426. _("Cannot unassign MAC Address while it is designated as the primary MAC for an object")
  1427. )
  1428. if original_assigned_object != assigned_object:
  1429. raise ValidationError(
  1430. _("Cannot reassign MAC Address while it is designated as the primary MAC for an object")
  1431. )
  1432. # Enforce uniqueness within any MAC block which requires it
  1433. if self.mac_address and (
  1434. mac_block := self.get_mac_blocks().filter(enforce_unique=True).order_by('-prefix_length').first()
  1435. ):
  1436. duplicates = MACAddress.objects.filter(mac_address=self.mac_address).exclude(pk=self.pk)
  1437. if duplicates.exists():
  1438. raise ValidationError({
  1439. 'mac_address': _(
  1440. "Duplicate MAC address found within MAC address block {mac_block}, which enforces uniqueness"
  1441. ).format(mac_block=mac_block)
  1442. })
  1443. def get_mac_blocks(self):
  1444. """
  1445. Return all MACBlocks which contain this MAC address.
  1446. """
  1447. return MACBlock.objects.filter(prefix__lte=self.mac_address, _last_address__gte=self.mac_address)
  1448. @cached_property
  1449. def mac_block(self):
  1450. """
  1451. Return the most specific MACBlock which contains this MAC address (if any).
  1452. """
  1453. if not self.mac_address:
  1454. return None
  1455. return self.get_mac_blocks().order_by('-prefix_length').first()
  1456. class MACBlock(PrimaryModel):
  1457. """
  1458. A block of MAC addresses which share a common prefix, such as an organizationally unique identifier (OUI).
  1459. """
  1460. prefix = MACAddressField(
  1461. verbose_name=_('prefix'),
  1462. help_text=_('The first MAC address in the block')
  1463. )
  1464. prefix_length = models.PositiveSmallIntegerField(
  1465. verbose_name=_('prefix length'),
  1466. default=MACBLOCK_LENGTH_DEFAULT,
  1467. validators=(
  1468. MinValueValidator(MACBLOCK_LENGTH_MIN),
  1469. MaxValueValidator(MACBLOCK_LENGTH_MAX),
  1470. ),
  1471. help_text=_('Number of leading bits shared by all MAC addresses in the block (e.g. 24 for an OUI)')
  1472. )
  1473. name = models.CharField(
  1474. verbose_name=_('name'),
  1475. max_length=100,
  1476. blank=True,
  1477. help_text=_('For example, the organization to which the block is assigned')
  1478. )
  1479. enforce_unique = models.BooleanField(
  1480. verbose_name=_('enforce unique'),
  1481. default=False,
  1482. help_text=_('Prevent duplicate MAC addresses within this block')
  1483. )
  1484. # Cached last MAC address in the block, for finding the MAC addresses and blocks it contains
  1485. _last_address = MACAddressField(
  1486. blank=True,
  1487. editable=False
  1488. )
  1489. objects = MACBlockQuerySet.as_manager()
  1490. clone_fields = ('prefix_length', 'enforce_unique', 'description')
  1491. class Meta:
  1492. ordering = ('prefix', 'prefix_length', 'pk')
  1493. indexes = (
  1494. models.Index(fields=('prefix', 'prefix_length', 'id')), # Default ordering
  1495. models.Index(fields=('prefix', '_last_address')),
  1496. )
  1497. constraints = (
  1498. models.UniqueConstraint(
  1499. fields=('prefix', 'prefix_length'),
  1500. name='%(app_label)s_%(class)s_unique_prefix_prefix_length',
  1501. violation_error_message=_("A MAC address block with this prefix and length already exists.")
  1502. ),
  1503. )
  1504. verbose_name = _('MAC address block')
  1505. verbose_name_plural = _('MAC address blocks')
  1506. def __str__(self):
  1507. return f'{self.prefix}/{self.prefix_length}'
  1508. def _get_bounds(self):
  1509. """
  1510. Return the first and last MAC addresses in the block as integers, or None if the prefix or its length is
  1511. invalid.
  1512. """
  1513. try:
  1514. prefix = int(EUI(self.prefix, version=48))
  1515. prefix_length = int(self.prefix_length)
  1516. except (AddrFormatError, TypeError, ValueError):
  1517. return None
  1518. if not MACBLOCK_LENGTH_MIN <= prefix_length <= MACBLOCK_LENGTH_MAX:
  1519. return None
  1520. host_mask = (1 << (48 - prefix_length)) - 1
  1521. return prefix & ~host_mask, prefix | host_mask
  1522. @property
  1523. def first_address(self):
  1524. """
  1525. Return the first MAC address in the block (the prefix with any host bits cleared).
  1526. """
  1527. if bounds := self._get_bounds():
  1528. return EUI(bounds[0], version=48, dialect=mac_unix_expanded_uppercase)
  1529. return None
  1530. @property
  1531. def last_address(self):
  1532. """
  1533. Return the last MAC address in the block.
  1534. """
  1535. if bounds := self._get_bounds():
  1536. return EUI(bounds[1], version=48, dialect=mac_unix_expanded_uppercase)
  1537. return None
  1538. @property
  1539. def size(self):
  1540. """
  1541. Return the number of MAC addresses in the block.
  1542. """
  1543. return 2 ** (48 - self.prefix_length)
  1544. def clean(self):
  1545. super().clean()
  1546. # Clear any host bits from the prefix, so that its uniqueness is validated against the value to be saved
  1547. if (first_address := self.first_address) is not None:
  1548. self.prefix = first_address
  1549. self._last_address = self.last_address
  1550. # Uniqueness cannot be enforced if the block already contains duplicate MAC addresses
  1551. if self.enforce_unique and self.first_address is not None:
  1552. duplicate = self.get_mac_addresses().values('mac_address').annotate(
  1553. count=Count('pk')
  1554. ).filter(count__gt=1).order_by('mac_address').first()
  1555. if duplicate:
  1556. raise ValidationError({
  1557. 'enforce_unique': _(
  1558. "Cannot enforce uniqueness: duplicate MAC address {mac_address} exists within this block"
  1559. ).format(mac_address=duplicate['mac_address'])
  1560. })
  1561. def save(self, *args, **kwargs):
  1562. if self.first_address is None:
  1563. raise ValueError(f"Invalid MAC address block: {self.prefix}/{self.prefix_length}")
  1564. # Clear any host bits from the prefix, and cache the last address in the block
  1565. self.prefix = self.first_address
  1566. self._last_address = self.last_address
  1567. super().save(*args, **kwargs)
  1568. def get_mac_addresses(self):
  1569. """
  1570. Return all MACAddresses within this block.
  1571. """
  1572. return MACAddress.objects.filter(mac_address__gte=self.first_address, mac_address__lte=self.last_address)
  1573. def get_child_blocks(self):
  1574. """
  1575. Return all MACBlocks within this block.
  1576. """
  1577. return MACBlock.objects.filter(
  1578. prefix__gte=self.first_address,
  1579. _last_address__lte=self.last_address,
  1580. prefix_length__gt=self.prefix_length,
  1581. )
  1582. @cached_property
  1583. def mac_address_count(self):
  1584. """
  1585. Return the number of distinct MAC addresses within the block. (May be annotated by
  1586. MACBlockQuerySet.annotate_mac_address_count().)
  1587. """
  1588. return self.get_mac_addresses().order_by().values('mac_address').distinct().count()
  1589. @property
  1590. def utilization(self):
  1591. """
  1592. Return the percentage of MAC addresses within the block which exist in NetBox.
  1593. """
  1594. return self.mac_address_count / self.size * 100
  1595. def _iter_occupied(self, batch_size=5000):
  1596. """
  1597. Yield the distinct MAC addresses within the block which exist in NetBox as integers, in ascending order.
  1598. Addresses are fetched in batches, so that stopping early stops reading from the database.
  1599. """
  1600. resume = self.first_address
  1601. while True:
  1602. mac_addresses = list(
  1603. MACAddress.objects.filter(mac_address__gte=resume, mac_address__lte=self.last_address)
  1604. .order_by('mac_address')
  1605. .values_list('mac_address', flat=True)
  1606. .distinct()[:batch_size]
  1607. )
  1608. for mac_address in mac_addresses:
  1609. yield int(mac_address)
  1610. if len(mac_addresses) < batch_size or mac_addresses[-1] == self.last_address:
  1611. return
  1612. resume = EUI(int(mac_addresses[-1]) + 1, version=48)
  1613. def iter_available_mac_addresses(self):
  1614. """
  1615. Yield the MAC addresses within the block which do not exist in NetBox, in ascending order.
  1616. """
  1617. candidate = int(self.first_address)
  1618. for occupied in self._iter_occupied():
  1619. for value in range(candidate, occupied):
  1620. yield EUI(value, version=48, dialect=mac_unix_expanded_uppercase)
  1621. candidate = occupied + 1
  1622. for value in range(candidate, int(self.last_address) + 1):
  1623. yield EUI(value, version=48, dialect=mac_unix_expanded_uppercase)
  1624. def get_first_available_mac_address(self):
  1625. """
  1626. Return the first MAC address within the block which does not exist in NetBox (or None).
  1627. """
  1628. return next(self.iter_available_mac_addresses(), None)