device_components.py 31 KB

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