device_components.py 37 KB

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