device_components.py 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  1. from functools import cached_property
  2. from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
  3. from django.contrib.contenttypes.models import ContentType
  4. from django.core.exceptions import ValidationError
  5. from django.core.validators import MaxValueValidator, MinValueValidator
  6. from django.db import models
  7. from django.db.models import Sum
  8. from django.urls import reverse
  9. from django.utils.translation import gettext as _
  10. from mptt.models import MPTTModel, TreeForeignKey
  11. from dcim.choices import *
  12. from dcim.constants import *
  13. from dcim.fields import MACAddressField, WWNField
  14. from netbox.models import OrganizationalModel, NetBoxModel
  15. from utilities.choices import ColorChoices
  16. from utilities.fields import ColorField, NaturalOrderingField
  17. from utilities.mptt import TreeManager
  18. from utilities.ordering import naturalize_interface
  19. from utilities.query_functions import CollateAsChar
  20. from utilities.tracking import TrackingModelMixin
  21. from wireless.choices import *
  22. from wireless.utils import get_channel_attr
  23. __all__ = (
  24. 'BaseInterface',
  25. 'CabledObjectModel',
  26. 'ConsolePort',
  27. 'ConsoleServerPort',
  28. 'DeviceBay',
  29. 'FrontPort',
  30. 'Interface',
  31. 'InventoryItem',
  32. 'InventoryItemRole',
  33. 'ModuleBay',
  34. 'PathEndpoint',
  35. 'PowerOutlet',
  36. 'PowerPort',
  37. 'RearPort',
  38. )
  39. class ComponentModel(NetBoxModel):
  40. """
  41. An abstract model inherited by any model which has a parent Device.
  42. """
  43. device = models.ForeignKey(
  44. to='dcim.Device',
  45. on_delete=models.CASCADE,
  46. related_name='%(class)ss'
  47. )
  48. name = models.CharField(
  49. max_length=64
  50. )
  51. _name = NaturalOrderingField(
  52. target_field='name',
  53. max_length=100,
  54. blank=True
  55. )
  56. label = models.CharField(
  57. max_length=64,
  58. blank=True,
  59. help_text=_("Physical label")
  60. )
  61. description = models.CharField(
  62. max_length=200,
  63. blank=True
  64. )
  65. class Meta:
  66. abstract = True
  67. ordering = ('device', '_name')
  68. constraints = (
  69. models.UniqueConstraint(
  70. fields=('device', 'name'),
  71. name='%(app_label)s_%(class)s_unique_device_name'
  72. ),
  73. )
  74. def __init__(self, *args, **kwargs):
  75. super().__init__(*args, **kwargs)
  76. # Cache the original Device ID for reference under clean()
  77. self._original_device = self.device_id
  78. def __str__(self):
  79. if self.label:
  80. return f"{self.name} ({self.label})"
  81. return self.name
  82. def to_objectchange(self, action):
  83. objectchange = super().to_objectchange(action)
  84. objectchange.related_object = self.device
  85. return objectchange
  86. def clean(self):
  87. super().clean()
  88. # Check list of Modules that allow device field to be changed
  89. if (type(self) not in [InventoryItem]) and (self.pk is not None) and (self._original_device != self.device_id):
  90. raise ValidationError({
  91. "device": "Components cannot be moved to a different device."
  92. })
  93. @property
  94. def parent_object(self):
  95. return self.device
  96. class ModularComponentModel(ComponentModel):
  97. module = models.ForeignKey(
  98. to='dcim.Module',
  99. on_delete=models.CASCADE,
  100. related_name='%(class)ss',
  101. blank=True,
  102. null=True
  103. )
  104. inventory_items = GenericRelation(
  105. to='dcim.InventoryItem',
  106. content_type_field='component_type',
  107. object_id_field='component_id'
  108. )
  109. class Meta(ComponentModel.Meta):
  110. abstract = True
  111. class CabledObjectModel(models.Model):
  112. """
  113. An abstract model inherited by all models to which a Cable can terminate. Provides the `cable` and `cable_end`
  114. fields for caching cable associations, as well as `mark_connected` to designate "fake" connections.
  115. """
  116. cable = models.ForeignKey(
  117. to='dcim.Cable',
  118. on_delete=models.SET_NULL,
  119. related_name='+',
  120. blank=True,
  121. null=True
  122. )
  123. cable_end = models.CharField(
  124. max_length=1,
  125. blank=True,
  126. choices=CableEndChoices
  127. )
  128. mark_connected = models.BooleanField(
  129. default=False,
  130. help_text=_("Treat as if a cable is connected")
  131. )
  132. cable_terminations = GenericRelation(
  133. to='dcim.CableTermination',
  134. content_type_field='termination_type',
  135. object_id_field='termination_id',
  136. related_query_name='%(class)s',
  137. )
  138. class Meta:
  139. abstract = True
  140. def clean(self):
  141. super().clean()
  142. if self.cable and not self.cable_end:
  143. raise ValidationError({
  144. "cable_end": "Must specify cable end (A or B) when attaching a cable."
  145. })
  146. if self.cable_end and not self.cable:
  147. raise ValidationError({
  148. "cable_end": "Cable end must not be set without a cable."
  149. })
  150. if self.mark_connected and self.cable:
  151. raise ValidationError({
  152. "mark_connected": "Cannot mark as connected with a cable attached."
  153. })
  154. @property
  155. def link(self):
  156. """
  157. Generic wrapper for a Cable, WirelessLink, or some other relation to a connected termination.
  158. """
  159. return self.cable
  160. @cached_property
  161. def link_peers(self):
  162. if self.cable:
  163. peers = self.cable.terminations.exclude(cable_end=self.cable_end).prefetch_related('termination')
  164. return [peer.termination for peer in peers]
  165. return []
  166. @property
  167. def _occupied(self):
  168. return bool(self.mark_connected or self.cable_id)
  169. @property
  170. def parent_object(self):
  171. raise NotImplementedError(f"{self.__class__.__name__} models must declare a parent_object property")
  172. @property
  173. def opposite_cable_end(self):
  174. if not self.cable_end:
  175. return None
  176. return CableEndChoices.SIDE_A if self.cable_end == CableEndChoices.SIDE_B else CableEndChoices.SIDE_B
  177. class PathEndpoint(models.Model):
  178. """
  179. An abstract model inherited by any CabledObjectModel subclass which represents the end of a CablePath; specifically,
  180. these include ConsolePort, ConsoleServerPort, PowerPort, PowerOutlet, Interface, and PowerFeed.
  181. `_path` references the CablePath originating from this instance, if any. It is set or cleared by the receivers in
  182. dcim.signals in response to changes in the cable path, and complements the `origin` GenericForeignKey field on the
  183. CablePath model. `_path` should not be accessed directly; rather, use the `path` property.
  184. `connected_endpoints()` is a convenience method for returning the destination of the associated CablePath, if any.
  185. """
  186. _path = models.ForeignKey(
  187. to='dcim.CablePath',
  188. on_delete=models.SET_NULL,
  189. null=True,
  190. blank=True
  191. )
  192. class Meta:
  193. abstract = True
  194. def trace(self):
  195. origin = self
  196. path = []
  197. # Construct the complete path (including e.g. bridged interfaces)
  198. while origin is not None:
  199. if origin._path is None:
  200. break
  201. path.extend(origin._path.path_objects)
  202. # If the path ends at a non-connected pass-through port, pad out the link and far-end terminations
  203. if len(path) % 3 == 1:
  204. path.extend(([], []))
  205. # If the path ends at a site or provider network, inject a null "link" to render an attachment
  206. elif len(path) % 3 == 2:
  207. path.insert(-1, [])
  208. # Check for a bridged relationship to continue the trace
  209. destinations = origin._path.destinations
  210. if len(destinations) == 1:
  211. origin = getattr(destinations[0], 'bridge', None)
  212. else:
  213. origin = None
  214. # Return the path as a list of three-tuples (A termination(s), cable(s), B termination(s))
  215. return list(zip(*[iter(path)] * 3))
  216. @property
  217. def path(self):
  218. return self._path
  219. @cached_property
  220. def connected_endpoints(self):
  221. """
  222. Caching accessor for the attached CablePath's destination (if any)
  223. """
  224. return self._path.destinations if self._path else []
  225. #
  226. # Console components
  227. #
  228. class ConsolePort(ModularComponentModel, CabledObjectModel, PathEndpoint, TrackingModelMixin):
  229. """
  230. A physical console port within a Device. ConsolePorts connect to ConsoleServerPorts.
  231. """
  232. type = models.CharField(
  233. max_length=50,
  234. choices=ConsolePortTypeChoices,
  235. blank=True,
  236. help_text=_('Physical port type')
  237. )
  238. speed = models.PositiveIntegerField(
  239. choices=ConsolePortSpeedChoices,
  240. blank=True,
  241. null=True,
  242. help_text=_('Port speed in bits per second')
  243. )
  244. clone_fields = ('device', 'module', 'type', 'speed')
  245. def get_absolute_url(self):
  246. return reverse('dcim:consoleport', kwargs={'pk': self.pk})
  247. class ConsoleServerPort(ModularComponentModel, CabledObjectModel, PathEndpoint, TrackingModelMixin):
  248. """
  249. A physical port within a Device (typically a designated console server) which provides access to ConsolePorts.
  250. """
  251. type = models.CharField(
  252. max_length=50,
  253. choices=ConsolePortTypeChoices,
  254. blank=True,
  255. help_text=_('Physical port type')
  256. )
  257. speed = models.PositiveIntegerField(
  258. choices=ConsolePortSpeedChoices,
  259. blank=True,
  260. null=True,
  261. help_text=_('Port speed in bits per second')
  262. )
  263. clone_fields = ('device', 'module', 'type', 'speed')
  264. def get_absolute_url(self):
  265. return reverse('dcim:consoleserverport', kwargs={'pk': self.pk})
  266. #
  267. # Power components
  268. #
  269. class PowerPort(ModularComponentModel, CabledObjectModel, PathEndpoint, TrackingModelMixin):
  270. """
  271. A physical power supply (intake) port within a Device. PowerPorts connect to PowerOutlets.
  272. """
  273. type = models.CharField(
  274. max_length=50,
  275. choices=PowerPortTypeChoices,
  276. blank=True,
  277. help_text=_('Physical port type')
  278. )
  279. maximum_draw = models.PositiveIntegerField(
  280. blank=True,
  281. null=True,
  282. validators=[MinValueValidator(1)],
  283. help_text=_("Maximum power draw (watts)")
  284. )
  285. allocated_draw = models.PositiveIntegerField(
  286. blank=True,
  287. null=True,
  288. validators=[MinValueValidator(1)],
  289. help_text=_("Allocated power draw (watts)")
  290. )
  291. clone_fields = ('device', 'module', 'maximum_draw', 'allocated_draw')
  292. def get_absolute_url(self):
  293. return reverse('dcim:powerport', kwargs={'pk': self.pk})
  294. def clean(self):
  295. super().clean()
  296. if self.maximum_draw is not None and self.allocated_draw is not None:
  297. if self.allocated_draw > self.maximum_draw:
  298. raise ValidationError({
  299. 'allocated_draw': f"Allocated draw cannot exceed the maximum draw ({self.maximum_draw}W)."
  300. })
  301. def get_downstream_powerports(self, leg=None):
  302. """
  303. Return a queryset of all PowerPorts connected via cable to a child PowerOutlet. For example, in the topology
  304. below, PP1.get_downstream_powerports() would return PP2-4.
  305. ---- PO1 <---> PP2
  306. /
  307. PP1 ------- PO2 <---> PP3
  308. \
  309. ---- PO3 <---> PP4
  310. """
  311. poweroutlets = self.poweroutlets.filter(cable__isnull=False)
  312. if leg:
  313. poweroutlets = poweroutlets.filter(feed_leg=leg)
  314. if not poweroutlets:
  315. return PowerPort.objects.none()
  316. q = Q()
  317. for poweroutlet in poweroutlets:
  318. q |= Q(
  319. cable=poweroutlet.cable,
  320. cable_end=poweroutlet.opposite_cable_end
  321. )
  322. return PowerPort.objects.filter(q)
  323. def get_power_draw(self):
  324. """
  325. Return the allocated and maximum power draw (in VA) and child PowerOutlet count for this PowerPort.
  326. """
  327. from dcim.models import PowerFeed
  328. # Calculate aggregate draw of all child power outlets if no numbers have been defined manually
  329. if self.allocated_draw is None and self.maximum_draw is None:
  330. utilization = self.get_downstream_powerports().aggregate(
  331. maximum_draw_total=Sum('maximum_draw'),
  332. allocated_draw_total=Sum('allocated_draw'),
  333. )
  334. ret = {
  335. 'allocated': utilization['allocated_draw_total'] or 0,
  336. 'maximum': utilization['maximum_draw_total'] or 0,
  337. 'outlet_count': self.poweroutlets.count(),
  338. 'legs': [],
  339. }
  340. # Calculate per-leg aggregates for three-phase power feeds
  341. if len(self.link_peers) == 1 and isinstance(self.link_peers[0], PowerFeed) and \
  342. self.link_peers[0].phase == PowerFeedPhaseChoices.PHASE_3PHASE:
  343. for leg, leg_name in PowerOutletFeedLegChoices:
  344. utilization = self.get_downstream_powerports(leg=leg).aggregate(
  345. maximum_draw_total=Sum('maximum_draw'),
  346. allocated_draw_total=Sum('allocated_draw'),
  347. )
  348. ret['legs'].append({
  349. 'name': leg_name,
  350. 'allocated': utilization['allocated_draw_total'] or 0,
  351. 'maximum': utilization['maximum_draw_total'] or 0,
  352. 'outlet_count': self.poweroutlets.filter(feed_leg=leg).count(),
  353. })
  354. return ret
  355. # Default to administratively defined values
  356. return {
  357. 'allocated': self.allocated_draw or 0,
  358. 'maximum': self.maximum_draw or 0,
  359. 'outlet_count': self.poweroutlets.count(),
  360. 'legs': [],
  361. }
  362. class PowerOutlet(ModularComponentModel, CabledObjectModel, PathEndpoint, TrackingModelMixin):
  363. """
  364. A physical power outlet (output) within a Device which provides power to a PowerPort.
  365. """
  366. type = models.CharField(
  367. max_length=50,
  368. choices=PowerOutletTypeChoices,
  369. blank=True,
  370. help_text=_('Physical port type')
  371. )
  372. power_port = models.ForeignKey(
  373. to='dcim.PowerPort',
  374. on_delete=models.SET_NULL,
  375. blank=True,
  376. null=True,
  377. related_name='poweroutlets'
  378. )
  379. feed_leg = models.CharField(
  380. max_length=50,
  381. choices=PowerOutletFeedLegChoices,
  382. blank=True,
  383. help_text=_("Phase (for three-phase feeds)")
  384. )
  385. clone_fields = ('device', 'module', 'type', 'power_port', 'feed_leg')
  386. def get_absolute_url(self):
  387. return reverse('dcim:poweroutlet', kwargs={'pk': self.pk})
  388. def clean(self):
  389. super().clean()
  390. # Validate power port assignment
  391. if self.power_port and self.power_port.device != self.device:
  392. raise ValidationError(f"Parent power port ({self.power_port}) must belong to the same device")
  393. #
  394. # Interfaces
  395. #
  396. class BaseInterface(models.Model):
  397. """
  398. Abstract base class for fields shared by dcim.Interface and virtualization.VMInterface.
  399. """
  400. enabled = models.BooleanField(
  401. default=True
  402. )
  403. mac_address = MACAddressField(
  404. null=True,
  405. blank=True,
  406. verbose_name='MAC Address'
  407. )
  408. mtu = models.PositiveIntegerField(
  409. blank=True,
  410. null=True,
  411. validators=[
  412. MinValueValidator(INTERFACE_MTU_MIN),
  413. MaxValueValidator(INTERFACE_MTU_MAX)
  414. ],
  415. verbose_name='MTU'
  416. )
  417. mode = models.CharField(
  418. max_length=50,
  419. choices=InterfaceModeChoices,
  420. blank=True,
  421. help_text=_("IEEE 802.1Q tagging strategy")
  422. )
  423. parent = models.ForeignKey(
  424. to='self',
  425. on_delete=models.SET_NULL,
  426. related_name='child_interfaces',
  427. null=True,
  428. blank=True,
  429. verbose_name='Parent interface'
  430. )
  431. bridge = models.ForeignKey(
  432. to='self',
  433. on_delete=models.SET_NULL,
  434. related_name='bridge_interfaces',
  435. null=True,
  436. blank=True,
  437. verbose_name='Bridge interface'
  438. )
  439. class Meta:
  440. abstract = True
  441. def save(self, *args, **kwargs):
  442. # Remove untagged VLAN assignment for non-802.1Q interfaces
  443. if not self.mode:
  444. self.untagged_vlan = None
  445. # Only "tagged" interfaces may have tagged VLANs assigned. ("tagged all" implies all VLANs are assigned.)
  446. if self.pk and self.mode != InterfaceModeChoices.MODE_TAGGED:
  447. self.tagged_vlans.clear()
  448. return super().save(*args, **kwargs)
  449. @property
  450. def count_ipaddresses(self):
  451. return self.ip_addresses.count()
  452. @property
  453. def count_fhrp_groups(self):
  454. return self.fhrp_group_assignments.count()
  455. class Interface(ModularComponentModel, BaseInterface, CabledObjectModel, PathEndpoint, TrackingModelMixin):
  456. """
  457. A network interface within a Device. A physical Interface can connect to exactly one other Interface.
  458. """
  459. # Override ComponentModel._name to specify naturalize_interface function
  460. _name = NaturalOrderingField(
  461. target_field='name',
  462. naturalize_function=naturalize_interface,
  463. max_length=100,
  464. blank=True
  465. )
  466. vdcs = models.ManyToManyField(
  467. to='dcim.VirtualDeviceContext',
  468. related_name='interfaces'
  469. )
  470. lag = models.ForeignKey(
  471. to='self',
  472. on_delete=models.SET_NULL,
  473. related_name='member_interfaces',
  474. null=True,
  475. blank=True,
  476. verbose_name='Parent LAG'
  477. )
  478. type = models.CharField(
  479. max_length=50,
  480. choices=InterfaceTypeChoices
  481. )
  482. mgmt_only = models.BooleanField(
  483. default=False,
  484. verbose_name='Management only',
  485. help_text=_('This interface is used only for out-of-band management')
  486. )
  487. speed = models.PositiveIntegerField(
  488. blank=True,
  489. null=True,
  490. verbose_name='Speed (Kbps)'
  491. )
  492. duplex = models.CharField(
  493. max_length=50,
  494. blank=True,
  495. null=True,
  496. choices=InterfaceDuplexChoices
  497. )
  498. wwn = WWNField(
  499. null=True,
  500. blank=True,
  501. verbose_name='WWN',
  502. help_text=_('64-bit World Wide Name')
  503. )
  504. rf_role = models.CharField(
  505. max_length=30,
  506. choices=WirelessRoleChoices,
  507. blank=True,
  508. verbose_name='Wireless role'
  509. )
  510. rf_channel = models.CharField(
  511. max_length=50,
  512. choices=WirelessChannelChoices,
  513. blank=True,
  514. verbose_name='Wireless channel'
  515. )
  516. rf_channel_frequency = models.DecimalField(
  517. max_digits=7,
  518. decimal_places=2,
  519. blank=True,
  520. null=True,
  521. verbose_name='Channel frequency (MHz)',
  522. help_text=_("Populated by selected channel (if set)")
  523. )
  524. rf_channel_width = models.DecimalField(
  525. max_digits=7,
  526. decimal_places=3,
  527. blank=True,
  528. null=True,
  529. verbose_name='Channel width (MHz)',
  530. help_text=_("Populated by selected channel (if set)")
  531. )
  532. tx_power = models.PositiveSmallIntegerField(
  533. blank=True,
  534. null=True,
  535. validators=(MaxValueValidator(127),),
  536. verbose_name='Transmit power (dBm)'
  537. )
  538. poe_mode = models.CharField(
  539. max_length=50,
  540. choices=InterfacePoEModeChoices,
  541. blank=True,
  542. verbose_name='PoE mode'
  543. )
  544. poe_type = models.CharField(
  545. max_length=50,
  546. choices=InterfacePoETypeChoices,
  547. blank=True,
  548. verbose_name='PoE type'
  549. )
  550. wireless_link = models.ForeignKey(
  551. to='wireless.WirelessLink',
  552. on_delete=models.SET_NULL,
  553. related_name='+',
  554. blank=True,
  555. null=True
  556. )
  557. wireless_lans = models.ManyToManyField(
  558. to='wireless.WirelessLAN',
  559. related_name='interfaces',
  560. blank=True,
  561. verbose_name='Wireless LANs'
  562. )
  563. untagged_vlan = models.ForeignKey(
  564. to='ipam.VLAN',
  565. on_delete=models.SET_NULL,
  566. related_name='interfaces_as_untagged',
  567. null=True,
  568. blank=True,
  569. verbose_name='Untagged VLAN'
  570. )
  571. tagged_vlans = models.ManyToManyField(
  572. to='ipam.VLAN',
  573. related_name='interfaces_as_tagged',
  574. blank=True,
  575. verbose_name='Tagged VLANs'
  576. )
  577. vrf = models.ForeignKey(
  578. to='ipam.VRF',
  579. on_delete=models.SET_NULL,
  580. related_name='interfaces',
  581. null=True,
  582. blank=True,
  583. verbose_name='VRF'
  584. )
  585. ip_addresses = GenericRelation(
  586. to='ipam.IPAddress',
  587. content_type_field='assigned_object_type',
  588. object_id_field='assigned_object_id',
  589. related_query_name='interface'
  590. )
  591. fhrp_group_assignments = GenericRelation(
  592. to='ipam.FHRPGroupAssignment',
  593. content_type_field='interface_type',
  594. object_id_field='interface_id',
  595. related_query_name='+'
  596. )
  597. l2vpn_terminations = GenericRelation(
  598. to='ipam.L2VPNTermination',
  599. content_type_field='assigned_object_type',
  600. object_id_field='assigned_object_id',
  601. related_query_name='interface',
  602. )
  603. clone_fields = (
  604. 'device', 'module', 'parent', 'bridge', 'lag', 'type', 'mgmt_only', 'mtu', 'mode', 'speed', 'duplex', 'rf_role',
  605. 'rf_channel', 'rf_channel_frequency', 'rf_channel_width', 'tx_power', 'poe_mode', 'poe_type', 'vrf',
  606. )
  607. class Meta(ModularComponentModel.Meta):
  608. ordering = ('device', CollateAsChar('_name'))
  609. def get_absolute_url(self):
  610. return reverse('dcim:interface', kwargs={'pk': self.pk})
  611. def clean(self):
  612. super().clean()
  613. # Virtual Interfaces cannot have a Cable attached
  614. if self.is_virtual and self.cable:
  615. raise ValidationError({
  616. 'type': f"{self.get_type_display()} interfaces cannot have a cable attached."
  617. })
  618. # Virtual Interfaces cannot be marked as connected
  619. if self.is_virtual and self.mark_connected:
  620. raise ValidationError({
  621. 'mark_connected': f"{self.get_type_display()} interfaces cannot be marked as connected."
  622. })
  623. # Parent validation
  624. # An interface cannot be its own parent
  625. if self.pk and self.parent_id == self.pk:
  626. raise ValidationError({'parent': "An interface cannot be its own parent."})
  627. # A physical interface cannot have a parent interface
  628. if self.type != InterfaceTypeChoices.TYPE_VIRTUAL and self.parent is not None:
  629. raise ValidationError({'parent': "Only virtual interfaces may be assigned to a parent interface."})
  630. # An interface's parent must belong to the same device or virtual chassis
  631. if self.parent and self.parent.device != self.device:
  632. if self.device.virtual_chassis is None:
  633. raise ValidationError({
  634. 'parent': f"The selected parent interface ({self.parent}) belongs to a different device "
  635. f"({self.parent.device})."
  636. })
  637. elif self.parent.device.virtual_chassis != self.parent.virtual_chassis:
  638. raise ValidationError({
  639. 'parent': f"The selected parent interface ({self.parent}) belongs to {self.parent.device}, which "
  640. f"is not part of virtual chassis {self.device.virtual_chassis}."
  641. })
  642. # Bridge validation
  643. # An interface cannot be bridged to itself
  644. if self.pk and self.bridge_id == self.pk:
  645. raise ValidationError({'bridge': "An interface cannot be bridged to itself."})
  646. # A bridged interface belong to the same device or virtual chassis
  647. if self.bridge and self.bridge.device != self.device:
  648. if self.device.virtual_chassis is None:
  649. raise ValidationError({
  650. 'bridge': f"The selected bridge interface ({self.bridge}) belongs to a different device "
  651. f"({self.bridge.device})."
  652. })
  653. elif self.bridge.device.virtual_chassis != self.device.virtual_chassis:
  654. raise ValidationError({
  655. 'bridge': f"The selected bridge interface ({self.bridge}) belongs to {self.bridge.device}, which "
  656. f"is not part of virtual chassis {self.device.virtual_chassis}."
  657. })
  658. # LAG validation
  659. # A virtual interface cannot have a parent LAG
  660. if self.type == InterfaceTypeChoices.TYPE_VIRTUAL and self.lag is not None:
  661. raise ValidationError({'lag': "Virtual interfaces cannot have a parent LAG interface."})
  662. # A LAG interface cannot be its own parent
  663. if self.pk and self.lag_id == self.pk:
  664. raise ValidationError({'lag': "A LAG interface cannot be its own parent."})
  665. # An interface's LAG must belong to the same device or virtual chassis
  666. if self.lag and self.lag.device != self.device:
  667. if self.device.virtual_chassis is None:
  668. raise ValidationError({
  669. 'lag': f"The selected LAG interface ({self.lag}) belongs to a different device ({self.lag.device})."
  670. })
  671. elif self.lag.device.virtual_chassis != self.device.virtual_chassis:
  672. raise ValidationError({
  673. 'lag': f"The selected LAG interface ({self.lag}) belongs to {self.lag.device}, which is not part "
  674. f"of virtual chassis {self.device.virtual_chassis}."
  675. })
  676. # PoE validation
  677. # Only physical interfaces may have a PoE mode/type assigned
  678. if self.poe_mode and self.is_virtual:
  679. raise ValidationError({
  680. 'poe_mode': "Virtual interfaces cannot have a PoE mode."
  681. })
  682. if self.poe_type and self.is_virtual:
  683. raise ValidationError({
  684. 'poe_type': "Virtual interfaces cannot have a PoE type."
  685. })
  686. # An interface with a PoE type set must also specify a mode
  687. if self.poe_type and not self.poe_mode:
  688. raise ValidationError({
  689. 'poe_type': "Must specify PoE mode when designating a PoE type."
  690. })
  691. # Wireless validation
  692. # RF role & channel may only be set for wireless interfaces
  693. if self.rf_role and not self.is_wireless:
  694. raise ValidationError({'rf_role': "Wireless role may be set only on wireless interfaces."})
  695. if self.rf_channel and not self.is_wireless:
  696. raise ValidationError({'rf_channel': "Channel may be set only on wireless interfaces."})
  697. # Validate channel frequency against interface type and selected channel (if any)
  698. if self.rf_channel_frequency:
  699. if not self.is_wireless:
  700. raise ValidationError({
  701. 'rf_channel_frequency': "Channel frequency may be set only on wireless interfaces.",
  702. })
  703. if self.rf_channel and self.rf_channel_frequency != get_channel_attr(self.rf_channel, 'frequency'):
  704. raise ValidationError({
  705. 'rf_channel_frequency': "Cannot specify custom frequency with channel selected.",
  706. })
  707. # Validate channel width against interface type and selected channel (if any)
  708. if self.rf_channel_width:
  709. if not self.is_wireless:
  710. raise ValidationError({'rf_channel_width': "Channel width may be set only on wireless interfaces."})
  711. if self.rf_channel and self.rf_channel_width != get_channel_attr(self.rf_channel, 'width'):
  712. raise ValidationError({'rf_channel_width': "Cannot specify custom width with channel selected."})
  713. # VLAN validation
  714. # Validate untagged VLAN
  715. if self.untagged_vlan and self.untagged_vlan.site not in [self.device.site, None]:
  716. raise ValidationError({
  717. 'untagged_vlan': f"The untagged VLAN ({self.untagged_vlan}) must belong to the same site as the "
  718. f"interface's parent device, or it must be global."
  719. })
  720. def save(self, *args, **kwargs):
  721. # Set absolute channel attributes from selected options
  722. if self.rf_channel and not self.rf_channel_frequency:
  723. self.rf_channel_frequency = get_channel_attr(self.rf_channel, 'frequency')
  724. if self.rf_channel and not self.rf_channel_width:
  725. self.rf_channel_width = get_channel_attr(self.rf_channel, 'width')
  726. super().save(*args, **kwargs)
  727. @property
  728. def _occupied(self):
  729. return super()._occupied or bool(self.wireless_link_id)
  730. @property
  731. def is_wired(self):
  732. return not self.is_virtual and not self.is_wireless
  733. @property
  734. def is_virtual(self):
  735. return self.type in VIRTUAL_IFACE_TYPES
  736. @property
  737. def is_wireless(self):
  738. return self.type in WIRELESS_IFACE_TYPES
  739. @property
  740. def is_lag(self):
  741. return self.type == InterfaceTypeChoices.TYPE_LAG
  742. @property
  743. def is_bridge(self):
  744. return self.type == InterfaceTypeChoices.TYPE_BRIDGE
  745. @property
  746. def link(self):
  747. return self.cable or self.wireless_link
  748. @cached_property
  749. def link_peers(self):
  750. if self.cable:
  751. return super().link_peers
  752. if self.wireless_link:
  753. # Return the opposite side of the attached wireless link
  754. if self.wireless_link.interface_a == self:
  755. return [self.wireless_link.interface_b]
  756. else:
  757. return [self.wireless_link.interface_a]
  758. return []
  759. @property
  760. def l2vpn_termination(self):
  761. return self.l2vpn_terminations.first()
  762. #
  763. # Pass-through ports
  764. #
  765. class FrontPort(ModularComponentModel, CabledObjectModel, TrackingModelMixin):
  766. """
  767. A pass-through port on the front of a Device.
  768. """
  769. type = models.CharField(
  770. max_length=50,
  771. choices=PortTypeChoices
  772. )
  773. color = ColorField(
  774. blank=True
  775. )
  776. rear_port = models.ForeignKey(
  777. to='dcim.RearPort',
  778. on_delete=models.CASCADE,
  779. related_name='frontports'
  780. )
  781. rear_port_position = models.PositiveSmallIntegerField(
  782. default=1,
  783. validators=[
  784. MinValueValidator(REARPORT_POSITIONS_MIN),
  785. MaxValueValidator(REARPORT_POSITIONS_MAX)
  786. ],
  787. help_text=_('Mapped position on corresponding rear port')
  788. )
  789. clone_fields = ('device', 'type', 'color')
  790. class Meta(ModularComponentModel.Meta):
  791. constraints = (
  792. models.UniqueConstraint(
  793. fields=('device', 'name'),
  794. name='%(app_label)s_%(class)s_unique_device_name'
  795. ),
  796. models.UniqueConstraint(
  797. fields=('rear_port', 'rear_port_position'),
  798. name='%(app_label)s_%(class)s_unique_rear_port_position'
  799. ),
  800. )
  801. def get_absolute_url(self):
  802. return reverse('dcim:frontport', kwargs={'pk': self.pk})
  803. def clean(self):
  804. super().clean()
  805. if hasattr(self, 'rear_port'):
  806. # Validate rear port assignment
  807. if self.rear_port.device != self.device:
  808. raise ValidationError({
  809. "rear_port": f"Rear port ({self.rear_port}) must belong to the same device"
  810. })
  811. # Validate rear port position assignment
  812. if self.rear_port_position > self.rear_port.positions:
  813. raise ValidationError({
  814. "rear_port_position": f"Invalid rear port position ({self.rear_port_position}): Rear port "
  815. f"{self.rear_port.name} has only {self.rear_port.positions} positions"
  816. })
  817. class RearPort(ModularComponentModel, CabledObjectModel, TrackingModelMixin):
  818. """
  819. A pass-through port on the rear of a Device.
  820. """
  821. type = models.CharField(
  822. max_length=50,
  823. choices=PortTypeChoices
  824. )
  825. color = ColorField(
  826. blank=True
  827. )
  828. positions = models.PositiveSmallIntegerField(
  829. default=1,
  830. validators=[
  831. MinValueValidator(REARPORT_POSITIONS_MIN),
  832. MaxValueValidator(REARPORT_POSITIONS_MAX)
  833. ],
  834. help_text=_('Number of front ports which may be mapped')
  835. )
  836. clone_fields = ('device', 'type', 'color', 'positions')
  837. def get_absolute_url(self):
  838. return reverse('dcim:rearport', kwargs={'pk': self.pk})
  839. def clean(self):
  840. super().clean()
  841. # Check that positions count is greater than or equal to the number of associated FrontPorts
  842. if self.pk:
  843. frontport_count = self.frontports.count()
  844. if self.positions < frontport_count:
  845. raise ValidationError({
  846. "positions": f"The number of positions cannot be less than the number of mapped front ports "
  847. f"({frontport_count})"
  848. })
  849. #
  850. # Bays
  851. #
  852. class ModuleBay(ComponentModel, TrackingModelMixin):
  853. """
  854. An empty space within a Device which can house a child device
  855. """
  856. position = models.CharField(
  857. max_length=30,
  858. blank=True,
  859. help_text=_('Identifier to reference when renaming installed components')
  860. )
  861. clone_fields = ('device',)
  862. def get_absolute_url(self):
  863. return reverse('dcim:modulebay', kwargs={'pk': self.pk})
  864. class DeviceBay(ComponentModel, TrackingModelMixin):
  865. """
  866. An empty space within a Device which can house a child device
  867. """
  868. installed_device = models.OneToOneField(
  869. to='dcim.Device',
  870. on_delete=models.SET_NULL,
  871. related_name='parent_bay',
  872. blank=True,
  873. null=True
  874. )
  875. clone_fields = ('device',)
  876. def get_absolute_url(self):
  877. return reverse('dcim:devicebay', kwargs={'pk': self.pk})
  878. def clean(self):
  879. super().clean()
  880. # Validate that the parent Device can have DeviceBays
  881. if not self.device.device_type.is_parent_device:
  882. raise ValidationError("This type of device ({}) does not support device bays.".format(
  883. self.device.device_type
  884. ))
  885. # Cannot install a device into itself, obviously
  886. if self.device == self.installed_device:
  887. raise ValidationError("Cannot install a device into itself.")
  888. # Check that the installed device is not already installed elsewhere
  889. if self.installed_device:
  890. current_bay = DeviceBay.objects.filter(installed_device=self.installed_device).first()
  891. if current_bay and current_bay != self:
  892. raise ValidationError({
  893. 'installed_device': "Cannot install the specified device; device is already installed in {}".format(
  894. current_bay
  895. )
  896. })
  897. #
  898. # Inventory items
  899. #
  900. class InventoryItemRole(OrganizationalModel):
  901. """
  902. Inventory items may optionally be assigned a functional role.
  903. """
  904. color = ColorField(
  905. default=ColorChoices.COLOR_GREY
  906. )
  907. def get_absolute_url(self):
  908. return reverse('dcim:inventoryitemrole', args=[self.pk])
  909. class InventoryItem(MPTTModel, ComponentModel, TrackingModelMixin):
  910. """
  911. An InventoryItem represents a serialized piece of hardware within a Device, such as a line card or power supply.
  912. InventoryItems are used only for inventory purposes.
  913. """
  914. parent = TreeForeignKey(
  915. to='self',
  916. on_delete=models.CASCADE,
  917. related_name='child_items',
  918. blank=True,
  919. null=True,
  920. db_index=True
  921. )
  922. component_type = models.ForeignKey(
  923. to=ContentType,
  924. limit_choices_to=MODULAR_COMPONENT_MODELS,
  925. on_delete=models.PROTECT,
  926. related_name='+',
  927. blank=True,
  928. null=True
  929. )
  930. component_id = models.PositiveBigIntegerField(
  931. blank=True,
  932. null=True
  933. )
  934. component = GenericForeignKey(
  935. ct_field='component_type',
  936. fk_field='component_id'
  937. )
  938. role = models.ForeignKey(
  939. to='dcim.InventoryItemRole',
  940. on_delete=models.PROTECT,
  941. related_name='inventory_items',
  942. blank=True,
  943. null=True
  944. )
  945. manufacturer = models.ForeignKey(
  946. to='dcim.Manufacturer',
  947. on_delete=models.PROTECT,
  948. related_name='inventory_items',
  949. blank=True,
  950. null=True
  951. )
  952. part_id = models.CharField(
  953. max_length=50,
  954. verbose_name='Part ID',
  955. blank=True,
  956. help_text=_('Manufacturer-assigned part identifier')
  957. )
  958. serial = models.CharField(
  959. max_length=50,
  960. verbose_name='Serial number',
  961. blank=True
  962. )
  963. asset_tag = models.CharField(
  964. max_length=50,
  965. unique=True,
  966. blank=True,
  967. null=True,
  968. verbose_name='Asset tag',
  969. help_text=_('A unique tag used to identify this item')
  970. )
  971. discovered = models.BooleanField(
  972. default=False,
  973. help_text=_('This item was automatically discovered')
  974. )
  975. objects = TreeManager()
  976. clone_fields = ('device', 'parent', 'role', 'manufacturer', 'part_id',)
  977. class Meta:
  978. ordering = ('device__id', 'parent__id', '_name')
  979. constraints = (
  980. models.UniqueConstraint(
  981. fields=('device', 'parent', 'name'),
  982. name='%(app_label)s_%(class)s_unique_device_parent_name'
  983. ),
  984. )
  985. def get_absolute_url(self):
  986. return reverse('dcim:inventoryitem', kwargs={'pk': self.pk})
  987. def clean(self):
  988. super().clean()
  989. # An InventoryItem cannot be its own parent
  990. if self.pk and self.parent_id == self.pk:
  991. raise ValidationError({
  992. "parent": "Cannot assign self as parent."
  993. })
  994. # Validation for moving InventoryItems
  995. if self.pk:
  996. # Cannot move an InventoryItem to another device if it has a parent
  997. if self.parent and self.parent.device != self.device:
  998. raise ValidationError({
  999. "parent": "Parent inventory item does not belong to the same device."
  1000. })
  1001. # Prevent moving InventoryItems with children
  1002. first_child = self.get_children().first()
  1003. if first_child and first_child.device != self.device:
  1004. raise ValidationError("Cannot move an inventory item with dependent children")
  1005. # When moving an InventoryItem to another device, remove any associated component
  1006. if self.component and self.component.device != self.device:
  1007. self.component = None
  1008. else:
  1009. if self.component and self.component.device != self.device:
  1010. raise ValidationError({
  1011. "device": "Cannot assign inventory item to component on another device"
  1012. })