device_components.py 36 KB

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