device_components.py 33 KB

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