device_components.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  1. from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
  2. from django.contrib.contenttypes.models import ContentType
  3. from django.core.exceptions import ObjectDoesNotExist, ValidationError
  4. from django.core.validators import MaxValueValidator, MinValueValidator
  5. from django.db import models
  6. from django.db.models import Sum
  7. from django.urls import reverse
  8. from mptt.models import MPTTModel, TreeForeignKey
  9. from dcim.choices import *
  10. from dcim.constants import *
  11. from dcim.fields import MACAddressField
  12. from dcim.svg import CableTraceSVG
  13. from extras.utils import extras_features
  14. from netbox.models import PrimaryModel
  15. from utilities.fields import ColorField, NaturalOrderingField
  16. from utilities.mptt import TreeManager
  17. from utilities.ordering import naturalize_interface
  18. from utilities.querysets import RestrictedQuerySet
  19. from utilities.query_functions import CollateAsChar
  20. __all__ = (
  21. 'BaseInterface',
  22. 'CableTermination',
  23. 'ConsolePort',
  24. 'ConsoleServerPort',
  25. 'DeviceBay',
  26. 'FrontPort',
  27. 'Interface',
  28. 'InventoryItem',
  29. 'PathEndpoint',
  30. 'PowerOutlet',
  31. 'PowerPort',
  32. 'RearPort',
  33. )
  34. class ComponentModel(PrimaryModel):
  35. """
  36. An abstract model inherited by any model which has a parent Device.
  37. """
  38. device = models.ForeignKey(
  39. to='dcim.Device',
  40. on_delete=models.CASCADE,
  41. related_name='%(class)ss'
  42. )
  43. name = models.CharField(
  44. max_length=64
  45. )
  46. _name = NaturalOrderingField(
  47. target_field='name',
  48. max_length=100,
  49. blank=True
  50. )
  51. label = models.CharField(
  52. max_length=64,
  53. blank=True,
  54. help_text="Physical label"
  55. )
  56. description = models.CharField(
  57. max_length=200,
  58. blank=True
  59. )
  60. objects = RestrictedQuerySet.as_manager()
  61. class Meta:
  62. abstract = True
  63. def __str__(self):
  64. if self.label:
  65. return f"{self.name} ({self.label})"
  66. return self.name
  67. def to_objectchange(self, action):
  68. # Annotate the parent Device
  69. try:
  70. device = self.device
  71. except ObjectDoesNotExist:
  72. # The parent Device has already been deleted
  73. device = None
  74. return super().to_objectchange(action, related_object=device)
  75. @property
  76. def parent_object(self):
  77. return self.device
  78. class CableTermination(models.Model):
  79. """
  80. An abstract model inherited by all models to which a Cable can terminate (certain device components, PowerFeed, and
  81. CircuitTermination instances). The `cable` field indicates the Cable instance which is terminated to this instance.
  82. `_cable_peer` is a GenericForeignKey used to cache the far-end CableTermination on the local instance; this is a
  83. shortcut to referencing `cable.termination_b`, for example. `_cable_peer` is set or cleared by the receivers in
  84. dcim.signals when a Cable instance is created or deleted, respectively.
  85. """
  86. cable = models.ForeignKey(
  87. to='dcim.Cable',
  88. on_delete=models.SET_NULL,
  89. related_name='+',
  90. blank=True,
  91. null=True
  92. )
  93. _cable_peer_type = models.ForeignKey(
  94. to=ContentType,
  95. on_delete=models.SET_NULL,
  96. related_name='+',
  97. blank=True,
  98. null=True
  99. )
  100. _cable_peer_id = models.PositiveIntegerField(
  101. blank=True,
  102. null=True
  103. )
  104. _cable_peer = GenericForeignKey(
  105. ct_field='_cable_peer_type',
  106. fk_field='_cable_peer_id'
  107. )
  108. mark_connected = models.BooleanField(
  109. default=False,
  110. help_text="Treat as if a cable is connected"
  111. )
  112. # Generic relations to Cable. These ensure that an attached Cable is deleted if the terminated object is deleted.
  113. _cabled_as_a = GenericRelation(
  114. to='dcim.Cable',
  115. content_type_field='termination_a_type',
  116. object_id_field='termination_a_id'
  117. )
  118. _cabled_as_b = GenericRelation(
  119. to='dcim.Cable',
  120. content_type_field='termination_b_type',
  121. object_id_field='termination_b_id'
  122. )
  123. class Meta:
  124. abstract = True
  125. def clean(self):
  126. super().clean()
  127. if self.mark_connected and self.cable_id:
  128. raise ValidationError({
  129. "mark_connected": "Cannot mark as connected with a cable attached."
  130. })
  131. def get_cable_peer(self):
  132. return self._cable_peer
  133. @property
  134. def _occupied(self):
  135. return bool(self.mark_connected or self.cable_id)
  136. @property
  137. def parent_object(self):
  138. raise NotImplementedError("CableTermination models must implement parent_object()")
  139. class PathEndpoint(models.Model):
  140. """
  141. An abstract model inherited by any CableTermination subclass which represents the end of a CablePath; specifically,
  142. these include ConsolePort, ConsoleServerPort, PowerPort, PowerOutlet, Interface, and PowerFeed.
  143. `_path` references the CablePath originating from this instance, if any. It is set or cleared by the receivers in
  144. dcim.signals in response to changes in the cable path, and complements the `origin` GenericForeignKey field on the
  145. CablePath model. `_path` should not be accessed directly; rather, use the `path` property.
  146. `connected_endpoint()` is a convenience method for returning the destination of the associated CablePath, if any.
  147. """
  148. _path = models.ForeignKey(
  149. to='dcim.CablePath',
  150. on_delete=models.SET_NULL,
  151. null=True,
  152. blank=True
  153. )
  154. class Meta:
  155. abstract = True
  156. def trace(self):
  157. if self._path is None:
  158. return []
  159. # Construct the complete path
  160. path = [self, *self._path.get_path()]
  161. while (len(path) + 1) % 3:
  162. # Pad to ensure we have complete three-tuples (e.g. for paths that end at a non-connected FrontPort)
  163. path.append(None)
  164. path.append(self._path.destination)
  165. # Return the path as a list of three-tuples (A termination, cable, B termination)
  166. return list(zip(*[iter(path)] * 3))
  167. def get_trace_svg(self, base_url=None, width=None):
  168. if width is not None:
  169. trace = CableTraceSVG(self, base_url=base_url, width=width)
  170. else:
  171. trace = CableTraceSVG(self, base_url=base_url)
  172. return trace.render()
  173. @property
  174. def path(self):
  175. return self._path
  176. @property
  177. def connected_endpoint(self):
  178. """
  179. Caching accessor for the attached CablePath's destination (if any)
  180. """
  181. if not hasattr(self, '_connected_endpoint'):
  182. self._connected_endpoint = self._path.destination if self._path else None
  183. return self._connected_endpoint
  184. #
  185. # Console ports
  186. #
  187. @extras_features('custom_fields', 'custom_links', 'export_templates', 'tags', 'webhooks')
  188. class ConsolePort(ComponentModel, CableTermination, PathEndpoint):
  189. """
  190. A physical console port within a Device. ConsolePorts connect to ConsoleServerPorts.
  191. """
  192. type = models.CharField(
  193. max_length=50,
  194. choices=ConsolePortTypeChoices,
  195. blank=True,
  196. help_text='Physical port type'
  197. )
  198. speed = models.PositiveIntegerField(
  199. choices=ConsolePortSpeedChoices,
  200. blank=True,
  201. null=True,
  202. help_text='Port speed in bits per second'
  203. )
  204. clone_fields = ['device', 'type', 'speed']
  205. class Meta:
  206. ordering = ('device', '_name')
  207. unique_together = ('device', 'name')
  208. def get_absolute_url(self):
  209. return reverse('dcim:consoleport', kwargs={'pk': self.pk})
  210. #
  211. # Console server ports
  212. #
  213. @extras_features('custom_fields', 'custom_links', 'export_templates', 'tags', 'webhooks')
  214. class ConsoleServerPort(ComponentModel, CableTermination, PathEndpoint):
  215. """
  216. A physical port within a Device (typically a designated console server) which provides access to ConsolePorts.
  217. """
  218. type = models.CharField(
  219. max_length=50,
  220. choices=ConsolePortTypeChoices,
  221. blank=True,
  222. help_text='Physical port type'
  223. )
  224. speed = models.PositiveIntegerField(
  225. choices=ConsolePortSpeedChoices,
  226. blank=True,
  227. null=True,
  228. help_text='Port speed in bits per second'
  229. )
  230. clone_fields = ['device', 'type', 'speed']
  231. class Meta:
  232. ordering = ('device', '_name')
  233. unique_together = ('device', 'name')
  234. def get_absolute_url(self):
  235. return reverse('dcim:consoleserverport', kwargs={'pk': self.pk})
  236. #
  237. # Power ports
  238. #
  239. @extras_features('custom_fields', 'custom_links', 'export_templates', 'tags', 'webhooks')
  240. class PowerPort(ComponentModel, CableTermination, PathEndpoint):
  241. """
  242. A physical power supply (intake) port within a Device. PowerPorts connect to PowerOutlets.
  243. """
  244. type = models.CharField(
  245. max_length=50,
  246. choices=PowerPortTypeChoices,
  247. blank=True,
  248. help_text='Physical port type'
  249. )
  250. maximum_draw = models.PositiveSmallIntegerField(
  251. blank=True,
  252. null=True,
  253. validators=[MinValueValidator(1)],
  254. help_text="Maximum power draw (watts)"
  255. )
  256. allocated_draw = models.PositiveSmallIntegerField(
  257. blank=True,
  258. null=True,
  259. validators=[MinValueValidator(1)],
  260. help_text="Allocated power draw (watts)"
  261. )
  262. clone_fields = ['device', 'maximum_draw', 'allocated_draw']
  263. class Meta:
  264. ordering = ('device', '_name')
  265. unique_together = ('device', 'name')
  266. def get_absolute_url(self):
  267. return reverse('dcim:powerport', kwargs={'pk': self.pk})
  268. def clean(self):
  269. super().clean()
  270. if self.maximum_draw is not None and self.allocated_draw is not None:
  271. if self.allocated_draw > self.maximum_draw:
  272. raise ValidationError({
  273. 'allocated_draw': f"Allocated draw cannot exceed the maximum draw ({self.maximum_draw}W)."
  274. })
  275. def get_power_draw(self):
  276. """
  277. Return the allocated and maximum power draw (in VA) and child PowerOutlet count for this PowerPort.
  278. """
  279. # Calculate aggregate draw of all child power outlets if no numbers have been defined manually
  280. if self.allocated_draw is None and self.maximum_draw is None:
  281. poweroutlet_ct = ContentType.objects.get_for_model(PowerOutlet)
  282. outlet_ids = PowerOutlet.objects.filter(power_port=self).values_list('pk', flat=True)
  283. utilization = PowerPort.objects.filter(
  284. _cable_peer_type=poweroutlet_ct,
  285. _cable_peer_id__in=outlet_ids
  286. ).aggregate(
  287. maximum_draw_total=Sum('maximum_draw'),
  288. allocated_draw_total=Sum('allocated_draw'),
  289. )
  290. ret = {
  291. 'allocated': utilization['allocated_draw_total'] or 0,
  292. 'maximum': utilization['maximum_draw_total'] or 0,
  293. 'outlet_count': len(outlet_ids),
  294. 'legs': [],
  295. }
  296. # Calculate per-leg aggregates for three-phase feeds
  297. if getattr(self._cable_peer, 'phase', None) == PowerFeedPhaseChoices.PHASE_3PHASE:
  298. for leg, leg_name in PowerOutletFeedLegChoices:
  299. outlet_ids = PowerOutlet.objects.filter(power_port=self, feed_leg=leg).values_list('pk', flat=True)
  300. utilization = PowerPort.objects.filter(
  301. _cable_peer_type=poweroutlet_ct,
  302. _cable_peer_id__in=outlet_ids
  303. ).aggregate(
  304. maximum_draw_total=Sum('maximum_draw'),
  305. allocated_draw_total=Sum('allocated_draw'),
  306. )
  307. ret['legs'].append({
  308. 'name': leg_name,
  309. 'allocated': utilization['allocated_draw_total'] or 0,
  310. 'maximum': utilization['maximum_draw_total'] or 0,
  311. 'outlet_count': len(outlet_ids),
  312. })
  313. return ret
  314. # Default to administratively defined values
  315. return {
  316. 'allocated': self.allocated_draw or 0,
  317. 'maximum': self.maximum_draw or 0,
  318. 'outlet_count': PowerOutlet.objects.filter(power_port=self).count(),
  319. 'legs': [],
  320. }
  321. #
  322. # Power outlets
  323. #
  324. @extras_features('custom_fields', 'custom_links', 'export_templates', 'tags', 'webhooks')
  325. class PowerOutlet(ComponentModel, CableTermination, PathEndpoint):
  326. """
  327. A physical power outlet (output) within a Device which provides power to a PowerPort.
  328. """
  329. type = models.CharField(
  330. max_length=50,
  331. choices=PowerOutletTypeChoices,
  332. blank=True,
  333. help_text='Physical port type'
  334. )
  335. power_port = models.ForeignKey(
  336. to='dcim.PowerPort',
  337. on_delete=models.SET_NULL,
  338. blank=True,
  339. null=True,
  340. related_name='poweroutlets'
  341. )
  342. feed_leg = models.CharField(
  343. max_length=50,
  344. choices=PowerOutletFeedLegChoices,
  345. blank=True,
  346. help_text="Phase (for three-phase feeds)"
  347. )
  348. clone_fields = ['device', 'type', 'power_port', 'feed_leg']
  349. class Meta:
  350. ordering = ('device', '_name')
  351. unique_together = ('device', 'name')
  352. def get_absolute_url(self):
  353. return reverse('dcim:poweroutlet', kwargs={'pk': self.pk})
  354. def clean(self):
  355. super().clean()
  356. # Validate power port assignment
  357. if self.power_port and self.power_port.device != self.device:
  358. raise ValidationError(
  359. "Parent power port ({}) must belong to the same device".format(self.power_port)
  360. )
  361. #
  362. # Interfaces
  363. #
  364. class BaseInterface(models.Model):
  365. """
  366. Abstract base class for fields shared by dcim.Interface and virtualization.VMInterface.
  367. """
  368. enabled = models.BooleanField(
  369. default=True
  370. )
  371. mac_address = MACAddressField(
  372. null=True,
  373. blank=True,
  374. verbose_name='MAC Address'
  375. )
  376. mtu = models.PositiveIntegerField(
  377. blank=True,
  378. null=True,
  379. validators=[
  380. MinValueValidator(INTERFACE_MTU_MIN),
  381. MaxValueValidator(INTERFACE_MTU_MAX)
  382. ],
  383. verbose_name='MTU'
  384. )
  385. mode = models.CharField(
  386. max_length=50,
  387. choices=InterfaceModeChoices,
  388. blank=True
  389. )
  390. class Meta:
  391. abstract = True
  392. def save(self, *args, **kwargs):
  393. # Remove untagged VLAN assignment for non-802.1Q interfaces
  394. if not self.mode:
  395. self.untagged_vlan = None
  396. # Only "tagged" interfaces may have tagged VLANs assigned. ("tagged all" implies all VLANs are assigned.)
  397. if self.pk and self.mode != InterfaceModeChoices.MODE_TAGGED:
  398. self.tagged_vlans.clear()
  399. return super().save(*args, **kwargs)
  400. @property
  401. def count_ipaddresses(self):
  402. return self.ip_addresses.count()
  403. @extras_features('custom_fields', 'custom_links', 'export_templates', 'tags', 'webhooks')
  404. class Interface(ComponentModel, BaseInterface, CableTermination, PathEndpoint):
  405. """
  406. A network interface within a Device. A physical Interface can connect to exactly one other Interface.
  407. """
  408. # Override ComponentModel._name to specify naturalize_interface function
  409. _name = NaturalOrderingField(
  410. target_field='name',
  411. naturalize_function=naturalize_interface,
  412. max_length=100,
  413. blank=True
  414. )
  415. parent = models.ForeignKey(
  416. to='self',
  417. on_delete=models.SET_NULL,
  418. related_name='child_interfaces',
  419. null=True,
  420. blank=True,
  421. verbose_name='Parent interface'
  422. )
  423. lag = models.ForeignKey(
  424. to='self',
  425. on_delete=models.SET_NULL,
  426. related_name='member_interfaces',
  427. null=True,
  428. blank=True,
  429. verbose_name='Parent LAG'
  430. )
  431. type = models.CharField(
  432. max_length=50,
  433. choices=InterfaceTypeChoices
  434. )
  435. mgmt_only = models.BooleanField(
  436. default=False,
  437. verbose_name='Management only',
  438. help_text='This interface is used only for out-of-band management'
  439. )
  440. untagged_vlan = models.ForeignKey(
  441. to='ipam.VLAN',
  442. on_delete=models.SET_NULL,
  443. related_name='interfaces_as_untagged',
  444. null=True,
  445. blank=True,
  446. verbose_name='Untagged VLAN'
  447. )
  448. tagged_vlans = models.ManyToManyField(
  449. to='ipam.VLAN',
  450. related_name='interfaces_as_tagged',
  451. blank=True,
  452. verbose_name='Tagged VLANs'
  453. )
  454. ip_addresses = GenericRelation(
  455. to='ipam.IPAddress',
  456. content_type_field='assigned_object_type',
  457. object_id_field='assigned_object_id',
  458. related_query_name='interface'
  459. )
  460. clone_fields = ['device', 'parent', 'lag', 'type', 'mgmt_only']
  461. class Meta:
  462. ordering = ('device', CollateAsChar('_name'))
  463. unique_together = ('device', 'name')
  464. def get_absolute_url(self):
  465. return reverse('dcim:interface', kwargs={'pk': self.pk})
  466. def clean(self):
  467. super().clean()
  468. # Virtual interfaces cannot be connected
  469. if not self.is_connectable and self.cable:
  470. raise ValidationError({
  471. 'type': f"{self.get_type_display()} interfaces cannot have a cable attached."
  472. })
  473. # Non-connectable interfaces cannot be marked as connected
  474. if not self.is_connectable and self.mark_connected:
  475. raise ValidationError({
  476. 'mark_connected': f"{self.get_type_display()} interfaces cannot be marked as connected."
  477. })
  478. # An interface's parent must belong to the same device or virtual chassis
  479. if self.parent and self.parent.device != self.device:
  480. if self.device.virtual_chassis is None:
  481. raise ValidationError({
  482. 'parent': f"The selected parent interface ({self.parent}) belongs to a different device "
  483. f"({self.parent.device})."
  484. })
  485. elif self.parent.device.virtual_chassis != self.parent.virtual_chassis:
  486. raise ValidationError({
  487. 'parent': f"The selected parent interface ({self.parent}) belongs to {self.parent.device}, which "
  488. f"is not part of virtual chassis {self.device.virtual_chassis}."
  489. })
  490. # An interface cannot be its own parent
  491. if self.pk and self.parent_id == self.pk:
  492. raise ValidationError({'parent': "An interface cannot be its own parent."})
  493. # A physical interface cannot have a parent interface
  494. if self.type != InterfaceTypeChoices.TYPE_VIRTUAL and self.parent is not None:
  495. raise ValidationError({'parent': "Only virtual interfaces may be assigned to a parent interface."})
  496. # An interface's LAG must belong to the same device or virtual chassis
  497. if self.lag and self.lag.device != self.device:
  498. if self.device.virtual_chassis is None:
  499. raise ValidationError({
  500. 'lag': f"The selected LAG interface ({self.lag}) belongs to a different device ({self.lag.device})."
  501. })
  502. elif self.lag.device.virtual_chassis != self.device.virtual_chassis:
  503. raise ValidationError({
  504. 'lag': f"The selected LAG interface ({self.lag}) belongs to {self.lag.device}, which is not part "
  505. f"of virtual chassis {self.device.virtual_chassis}."
  506. })
  507. # A virtual interface cannot have a parent LAG
  508. if self.type == InterfaceTypeChoices.TYPE_VIRTUAL and self.lag is not None:
  509. raise ValidationError({'lag': "Virtual interfaces cannot have a parent LAG interface."})
  510. # A LAG interface cannot be its own parent
  511. if self.pk and self.lag_id == self.pk:
  512. raise ValidationError({'lag': "A LAG interface cannot be its own parent."})
  513. # Validate untagged VLAN
  514. if self.untagged_vlan and self.untagged_vlan.site not in [self.device.site, None]:
  515. raise ValidationError({
  516. 'untagged_vlan': "The untagged VLAN ({}) must belong to the same site as the interface's parent "
  517. "device, or it must be global".format(self.untagged_vlan)
  518. })
  519. @property
  520. def is_connectable(self):
  521. return self.type not in NONCONNECTABLE_IFACE_TYPES
  522. @property
  523. def is_virtual(self):
  524. return self.type in VIRTUAL_IFACE_TYPES
  525. @property
  526. def is_wireless(self):
  527. return self.type in WIRELESS_IFACE_TYPES
  528. @property
  529. def is_lag(self):
  530. return self.type == InterfaceTypeChoices.TYPE_LAG
  531. #
  532. # Pass-through ports
  533. #
  534. @extras_features('custom_fields', 'custom_links', 'export_templates', 'tags', 'webhooks')
  535. class FrontPort(ComponentModel, CableTermination):
  536. """
  537. A pass-through port on the front of a Device.
  538. """
  539. type = models.CharField(
  540. max_length=50,
  541. choices=PortTypeChoices
  542. )
  543. color = ColorField(
  544. blank=True
  545. )
  546. rear_port = models.ForeignKey(
  547. to='dcim.RearPort',
  548. on_delete=models.CASCADE,
  549. related_name='frontports'
  550. )
  551. rear_port_position = models.PositiveSmallIntegerField(
  552. default=1,
  553. validators=[
  554. MinValueValidator(REARPORT_POSITIONS_MIN),
  555. MaxValueValidator(REARPORT_POSITIONS_MAX)
  556. ]
  557. )
  558. clone_fields = ['device', 'type']
  559. class Meta:
  560. ordering = ('device', '_name')
  561. unique_together = (
  562. ('device', 'name'),
  563. ('rear_port', 'rear_port_position'),
  564. )
  565. def get_absolute_url(self):
  566. return reverse('dcim:frontport', kwargs={'pk': self.pk})
  567. def clean(self):
  568. super().clean()
  569. # Validate rear port assignment
  570. if self.rear_port.device != self.device:
  571. raise ValidationError({
  572. "rear_port": f"Rear port ({self.rear_port}) must belong to the same device"
  573. })
  574. # Validate rear port position assignment
  575. if self.rear_port_position > self.rear_port.positions:
  576. raise ValidationError({
  577. "rear_port_position": f"Invalid rear port position ({self.rear_port_position}): Rear port "
  578. f"{self.rear_port.name} has only {self.rear_port.positions} positions"
  579. })
  580. @extras_features('custom_fields', 'custom_links', 'export_templates', 'tags', 'webhooks')
  581. class RearPort(ComponentModel, CableTermination):
  582. """
  583. A pass-through port on the rear of a Device.
  584. """
  585. type = models.CharField(
  586. max_length=50,
  587. choices=PortTypeChoices
  588. )
  589. color = ColorField(
  590. blank=True
  591. )
  592. positions = models.PositiveSmallIntegerField(
  593. default=1,
  594. validators=[
  595. MinValueValidator(REARPORT_POSITIONS_MIN),
  596. MaxValueValidator(REARPORT_POSITIONS_MAX)
  597. ]
  598. )
  599. clone_fields = ['device', 'type', 'positions']
  600. class Meta:
  601. ordering = ('device', '_name')
  602. unique_together = ('device', 'name')
  603. def get_absolute_url(self):
  604. return reverse('dcim:rearport', kwargs={'pk': self.pk})
  605. def clean(self):
  606. super().clean()
  607. # Check that positions count is greater than or equal to the number of associated FrontPorts
  608. frontport_count = self.frontports.count()
  609. if self.positions < frontport_count:
  610. raise ValidationError({
  611. "positions": f"The number of positions cannot be less than the number of mapped front ports "
  612. f"({frontport_count})"
  613. })
  614. #
  615. # Device bays
  616. #
  617. @extras_features('custom_fields', 'custom_links', 'export_templates', 'tags', 'webhooks')
  618. class DeviceBay(ComponentModel):
  619. """
  620. An empty space within a Device which can house a child device
  621. """
  622. installed_device = models.OneToOneField(
  623. to='dcim.Device',
  624. on_delete=models.SET_NULL,
  625. related_name='parent_bay',
  626. blank=True,
  627. null=True
  628. )
  629. clone_fields = ['device']
  630. class Meta:
  631. ordering = ('device', '_name')
  632. unique_together = ('device', 'name')
  633. def get_absolute_url(self):
  634. return reverse('dcim:devicebay', kwargs={'pk': self.pk})
  635. def clean(self):
  636. super().clean()
  637. # Validate that the parent Device can have DeviceBays
  638. if not self.device.device_type.is_parent_device:
  639. raise ValidationError("This type of device ({}) does not support device bays.".format(
  640. self.device.device_type
  641. ))
  642. # Cannot install a device into itself, obviously
  643. if self.device == self.installed_device:
  644. raise ValidationError("Cannot install a device into itself.")
  645. # Check that the installed device is not already installed elsewhere
  646. if self.installed_device:
  647. current_bay = DeviceBay.objects.filter(installed_device=self.installed_device).first()
  648. if current_bay and current_bay != self:
  649. raise ValidationError({
  650. 'installed_device': "Cannot install the specified device; device is already installed in {}".format(
  651. current_bay
  652. )
  653. })
  654. #
  655. # Inventory items
  656. #
  657. @extras_features('custom_fields', 'custom_links', 'export_templates', 'tags', 'webhooks')
  658. class InventoryItem(MPTTModel, ComponentModel):
  659. """
  660. An InventoryItem represents a serialized piece of hardware within a Device, such as a line card or power supply.
  661. InventoryItems are used only for inventory purposes.
  662. """
  663. parent = TreeForeignKey(
  664. to='self',
  665. on_delete=models.CASCADE,
  666. related_name='child_items',
  667. blank=True,
  668. null=True,
  669. db_index=True
  670. )
  671. manufacturer = models.ForeignKey(
  672. to='dcim.Manufacturer',
  673. on_delete=models.PROTECT,
  674. related_name='inventory_items',
  675. blank=True,
  676. null=True
  677. )
  678. part_id = models.CharField(
  679. max_length=50,
  680. verbose_name='Part ID',
  681. blank=True,
  682. help_text='Manufacturer-assigned part identifier'
  683. )
  684. serial = models.CharField(
  685. max_length=50,
  686. verbose_name='Serial number',
  687. blank=True
  688. )
  689. asset_tag = models.CharField(
  690. max_length=50,
  691. unique=True,
  692. blank=True,
  693. null=True,
  694. verbose_name='Asset tag',
  695. help_text='A unique tag used to identify this item'
  696. )
  697. discovered = models.BooleanField(
  698. default=False,
  699. help_text='This item was automatically discovered'
  700. )
  701. objects = TreeManager()
  702. clone_fields = ['device', 'parent', 'manufacturer', 'part_id']
  703. class Meta:
  704. ordering = ('device__id', 'parent__id', '_name')
  705. unique_together = ('device', 'parent', 'name')
  706. def get_absolute_url(self):
  707. return reverse('dcim:inventoryitem', kwargs={'pk': self.pk})