device_components.py 45 KB

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