device_components.py 32 KB

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