device_components.py 27 KB

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