device_components.py 42 KB

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