device_components.py 36 KB

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