device_components.py 42 KB

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