device_components.py 27 KB

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