device_components.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  1. import logging
  2. from django.contrib.contenttypes.fields import GenericRelation
  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 taggit.managers import TaggableManager
  9. from dcim.choices import *
  10. from dcim.constants import *
  11. from dcim.exceptions import CableTraceSplit
  12. from dcim.fields import MACAddressField
  13. from extras.models import ObjectChange, TaggedItem
  14. from extras.utils import extras_features
  15. from utilities.fields import NaturalOrderingField
  16. from utilities.ordering import naturalize_interface
  17. from utilities.querysets import RestrictedQuerySet
  18. from utilities.query_functions import CollateAsChar
  19. from utilities.utils import serialize_object
  20. __all__ = (
  21. 'CableTermination',
  22. 'ConsolePort',
  23. 'ConsoleServerPort',
  24. 'DeviceBay',
  25. 'FrontPort',
  26. 'Interface',
  27. 'InventoryItem',
  28. 'PowerOutlet',
  29. 'PowerPort',
  30. 'RearPort',
  31. )
  32. class ComponentModel(models.Model):
  33. device = models.ForeignKey(
  34. to='dcim.Device',
  35. on_delete=models.CASCADE,
  36. related_name='%(class)ss'
  37. )
  38. name = models.CharField(
  39. max_length=64
  40. )
  41. _name = NaturalOrderingField(
  42. target_field='name',
  43. max_length=100,
  44. blank=True
  45. )
  46. label = models.CharField(
  47. max_length=64,
  48. blank=True,
  49. help_text="Physical label"
  50. )
  51. description = models.CharField(
  52. max_length=200,
  53. blank=True
  54. )
  55. objects = RestrictedQuerySet.as_manager()
  56. class Meta:
  57. abstract = True
  58. def __str__(self):
  59. if self.label:
  60. return f"{self.name} ({self.label})"
  61. return self.name
  62. def to_objectchange(self, action):
  63. # Annotate the parent Device
  64. try:
  65. device = self.device
  66. except ObjectDoesNotExist:
  67. # The parent Device has already been deleted
  68. device = None
  69. return ObjectChange(
  70. changed_object=self,
  71. object_repr=str(self),
  72. action=action,
  73. related_object=device,
  74. object_data=serialize_object(self)
  75. )
  76. @property
  77. def parent(self):
  78. return getattr(self, 'device', None)
  79. class CableTermination(models.Model):
  80. cable = models.ForeignKey(
  81. to='dcim.Cable',
  82. on_delete=models.SET_NULL,
  83. related_name='+',
  84. blank=True,
  85. null=True
  86. )
  87. # Generic relations to Cable. These ensure that an attached Cable is deleted if the terminated object is deleted.
  88. _cabled_as_a = GenericRelation(
  89. to='dcim.Cable',
  90. content_type_field='termination_a_type',
  91. object_id_field='termination_a_id'
  92. )
  93. _cabled_as_b = GenericRelation(
  94. to='dcim.Cable',
  95. content_type_field='termination_b_type',
  96. object_id_field='termination_b_id'
  97. )
  98. class Meta:
  99. abstract = True
  100. def trace(self):
  101. """
  102. Return three items: the traceable portion of a cable path, the termination points where it splits (if any), and
  103. the remaining positions on the position stack (if any). Splits occur when the trace is initiated from a midpoint
  104. along a path which traverses a RearPort. In cases where the originating endpoint is unknown, it is not possible
  105. to know which corresponding FrontPort to follow. Remaining positions occur when tracing a path that traverses
  106. a FrontPort without traversing a RearPort again.
  107. The path is a list representing a complete cable path, with each individual segment represented as a
  108. three-tuple:
  109. [
  110. (termination A, cable, termination B),
  111. (termination C, cable, termination D),
  112. (termination E, cable, termination F)
  113. ]
  114. """
  115. endpoint = self
  116. path = []
  117. position_stack = []
  118. def get_peer_port(termination):
  119. from circuits.models import CircuitTermination
  120. # Map a front port to its corresponding rear port
  121. if isinstance(termination, FrontPort):
  122. # Retrieve the corresponding RearPort from database to ensure we have an up-to-date instance
  123. peer_port = RearPort.objects.get(pk=termination.rear_port.pk)
  124. # Don't use the stack for RearPorts with a single position. Only remember the position at
  125. # many-to-one points so we can select the correct FrontPort when we reach the corresponding
  126. # one-to-many point.
  127. if peer_port.positions > 1:
  128. position_stack.append(termination)
  129. return peer_port
  130. # Map a rear port/position to its corresponding front port
  131. elif isinstance(termination, RearPort):
  132. if termination.positions > 1:
  133. # Can't map to a FrontPort without a position if there are multiple options
  134. if not position_stack:
  135. raise CableTraceSplit(termination)
  136. front_port = position_stack.pop()
  137. position = front_port.rear_port_position
  138. # Validate the position
  139. if position not in range(1, termination.positions + 1):
  140. raise Exception("Invalid position for {} ({} positions): {})".format(
  141. termination, termination.positions, position
  142. ))
  143. else:
  144. # Don't use the stack for RearPorts with a single position. The only possible position is 1.
  145. position = 1
  146. try:
  147. peer_port = FrontPort.objects.get(
  148. rear_port=termination,
  149. rear_port_position=position,
  150. )
  151. return peer_port
  152. except ObjectDoesNotExist:
  153. return None
  154. # Follow a circuit to its other termination
  155. elif isinstance(termination, CircuitTermination):
  156. peer_termination = termination.get_peer_termination()
  157. if peer_termination is None:
  158. return None
  159. return peer_termination
  160. # Termination is not a pass-through port
  161. else:
  162. return None
  163. logger = logging.getLogger('netbox.dcim.cable.trace')
  164. logger.debug("Tracing cable from {} {}".format(self.parent, self))
  165. while endpoint is not None:
  166. # No cable connected; nothing to trace
  167. if not endpoint.cable:
  168. path.append((endpoint, None, None))
  169. logger.debug("No cable connected")
  170. return path, None, position_stack
  171. # Check for loops
  172. if endpoint.cable in [segment[1] for segment in path]:
  173. logger.debug("Loop detected!")
  174. return path, None, position_stack
  175. # Record the current segment in the path
  176. far_end = endpoint.get_cable_peer()
  177. path.append((endpoint, endpoint.cable, far_end))
  178. logger.debug("{}[{}] --- Cable {} ---> {}[{}]".format(
  179. endpoint.parent, endpoint, endpoint.cable.pk, far_end.parent, far_end
  180. ))
  181. # Get the peer port of the far end termination
  182. try:
  183. endpoint = get_peer_port(far_end)
  184. except CableTraceSplit as e:
  185. return path, e.termination.frontports.all(), position_stack
  186. if endpoint is None:
  187. return path, None, position_stack
  188. def get_cable_peer(self):
  189. if self.cable is None:
  190. return None
  191. if self._cabled_as_a.exists():
  192. return self.cable.termination_b
  193. if self._cabled_as_b.exists():
  194. return self.cable.termination_a
  195. def get_path_endpoints(self):
  196. """
  197. Return all endpoints of paths which traverse this object.
  198. """
  199. endpoints = []
  200. # Get the far end of the last path segment
  201. path, split_ends, position_stack = self.trace()
  202. endpoint = path[-1][2]
  203. if split_ends is not None:
  204. for termination in split_ends:
  205. endpoints.extend(termination.get_path_endpoints())
  206. elif endpoint is not None:
  207. endpoints.append(endpoint)
  208. return endpoints
  209. #
  210. # Console ports
  211. #
  212. @extras_features('export_templates', 'webhooks')
  213. class ConsolePort(CableTermination, ComponentModel):
  214. """
  215. A physical console port within a Device. ConsolePorts connect to ConsoleServerPorts.
  216. """
  217. type = models.CharField(
  218. max_length=50,
  219. choices=ConsolePortTypeChoices,
  220. blank=True,
  221. help_text='Physical port type'
  222. )
  223. connected_endpoint = models.OneToOneField(
  224. to='dcim.ConsoleServerPort',
  225. on_delete=models.SET_NULL,
  226. related_name='connected_endpoint',
  227. blank=True,
  228. null=True
  229. )
  230. connection_status = models.BooleanField(
  231. choices=CONNECTION_STATUS_CHOICES,
  232. blank=True,
  233. null=True
  234. )
  235. tags = TaggableManager(through=TaggedItem)
  236. csv_headers = ['device', 'name', 'label', 'type', 'description']
  237. class Meta:
  238. ordering = ('device', '_name')
  239. unique_together = ('device', 'name')
  240. def get_absolute_url(self):
  241. return reverse('dcim:consoleport', kwargs={'pk': self.pk})
  242. def to_csv(self):
  243. return (
  244. self.device.identifier,
  245. self.name,
  246. self.label,
  247. self.type,
  248. self.description,
  249. )
  250. #
  251. # Console server ports
  252. #
  253. @extras_features('webhooks')
  254. class ConsoleServerPort(CableTermination, ComponentModel):
  255. """
  256. A physical port within a Device (typically a designated console server) which provides access to ConsolePorts.
  257. """
  258. type = models.CharField(
  259. max_length=50,
  260. choices=ConsolePortTypeChoices,
  261. blank=True,
  262. help_text='Physical port type'
  263. )
  264. connection_status = models.BooleanField(
  265. choices=CONNECTION_STATUS_CHOICES,
  266. blank=True,
  267. null=True
  268. )
  269. tags = TaggableManager(through=TaggedItem)
  270. csv_headers = ['device', 'name', 'label', 'type', 'description']
  271. class Meta:
  272. ordering = ('device', '_name')
  273. unique_together = ('device', 'name')
  274. def get_absolute_url(self):
  275. return reverse('dcim:consoleserverport', kwargs={'pk': self.pk})
  276. def to_csv(self):
  277. return (
  278. self.device.identifier,
  279. self.name,
  280. self.label,
  281. self.type,
  282. self.description,
  283. )
  284. #
  285. # Power ports
  286. #
  287. @extras_features('export_templates', 'webhooks')
  288. class PowerPort(CableTermination, ComponentModel):
  289. """
  290. A physical power supply (intake) port within a Device. PowerPorts connect to PowerOutlets.
  291. """
  292. type = models.CharField(
  293. max_length=50,
  294. choices=PowerPortTypeChoices,
  295. blank=True,
  296. help_text='Physical port type'
  297. )
  298. maximum_draw = models.PositiveSmallIntegerField(
  299. blank=True,
  300. null=True,
  301. validators=[MinValueValidator(1)],
  302. help_text="Maximum power draw (watts)"
  303. )
  304. allocated_draw = models.PositiveSmallIntegerField(
  305. blank=True,
  306. null=True,
  307. validators=[MinValueValidator(1)],
  308. help_text="Allocated power draw (watts)"
  309. )
  310. _connected_poweroutlet = models.OneToOneField(
  311. to='dcim.PowerOutlet',
  312. on_delete=models.SET_NULL,
  313. related_name='connected_endpoint',
  314. blank=True,
  315. null=True
  316. )
  317. _connected_powerfeed = models.OneToOneField(
  318. to='dcim.PowerFeed',
  319. on_delete=models.SET_NULL,
  320. related_name='+',
  321. blank=True,
  322. null=True
  323. )
  324. connection_status = models.BooleanField(
  325. choices=CONNECTION_STATUS_CHOICES,
  326. blank=True,
  327. null=True
  328. )
  329. tags = TaggableManager(through=TaggedItem)
  330. csv_headers = ['device', 'name', 'label', 'type', 'maximum_draw', 'allocated_draw', 'description']
  331. class Meta:
  332. ordering = ('device', '_name')
  333. unique_together = ('device', 'name')
  334. def get_absolute_url(self):
  335. return reverse('dcim:powerport', kwargs={'pk': self.pk})
  336. def to_csv(self):
  337. return (
  338. self.device.identifier,
  339. self.name,
  340. self.label,
  341. self.get_type_display(),
  342. self.maximum_draw,
  343. self.allocated_draw,
  344. self.description,
  345. )
  346. @property
  347. def connected_endpoint(self):
  348. """
  349. Return the connected PowerOutlet, if it exists, or the connected PowerFeed, if it exists. We have to check for
  350. ObjectDoesNotExist in case the referenced object has been deleted from the database.
  351. """
  352. try:
  353. if self._connected_poweroutlet:
  354. return self._connected_poweroutlet
  355. except ObjectDoesNotExist:
  356. pass
  357. try:
  358. if self._connected_powerfeed:
  359. return self._connected_powerfeed
  360. except ObjectDoesNotExist:
  361. pass
  362. return None
  363. @connected_endpoint.setter
  364. def connected_endpoint(self, value):
  365. # TODO: Fix circular import
  366. from . import PowerFeed
  367. if value is None:
  368. self._connected_poweroutlet = None
  369. self._connected_powerfeed = None
  370. elif isinstance(value, PowerOutlet):
  371. self._connected_poweroutlet = value
  372. self._connected_powerfeed = None
  373. elif isinstance(value, PowerFeed):
  374. self._connected_poweroutlet = None
  375. self._connected_powerfeed = value
  376. else:
  377. raise ValueError(
  378. "Connected endpoint must be a PowerOutlet or PowerFeed, not {}.".format(type(value))
  379. )
  380. def get_power_draw(self):
  381. """
  382. Return the allocated and maximum power draw (in VA) and child PowerOutlet count for this PowerPort.
  383. """
  384. # Calculate aggregate draw of all child power outlets if no numbers have been defined manually
  385. if self.allocated_draw is None and self.maximum_draw is None:
  386. outlet_ids = PowerOutlet.objects.filter(power_port=self).values_list('pk', flat=True)
  387. utilization = PowerPort.objects.filter(_connected_poweroutlet_id__in=outlet_ids).aggregate(
  388. maximum_draw_total=Sum('maximum_draw'),
  389. allocated_draw_total=Sum('allocated_draw'),
  390. )
  391. ret = {
  392. 'allocated': utilization['allocated_draw_total'] or 0,
  393. 'maximum': utilization['maximum_draw_total'] or 0,
  394. 'outlet_count': len(outlet_ids),
  395. 'legs': [],
  396. }
  397. # Calculate per-leg aggregates for three-phase feeds
  398. if self._connected_powerfeed and self._connected_powerfeed.phase == PowerFeedPhaseChoices.PHASE_3PHASE:
  399. for leg, leg_name in PowerOutletFeedLegChoices:
  400. outlet_ids = PowerOutlet.objects.filter(power_port=self, feed_leg=leg).values_list('pk', flat=True)
  401. utilization = PowerPort.objects.filter(_connected_poweroutlet_id__in=outlet_ids).aggregate(
  402. maximum_draw_total=Sum('maximum_draw'),
  403. allocated_draw_total=Sum('allocated_draw'),
  404. )
  405. ret['legs'].append({
  406. 'name': leg_name,
  407. 'allocated': utilization['allocated_draw_total'] or 0,
  408. 'maximum': utilization['maximum_draw_total'] or 0,
  409. 'outlet_count': len(outlet_ids),
  410. })
  411. return ret
  412. # Default to administratively defined values
  413. return {
  414. 'allocated': self.allocated_draw or 0,
  415. 'maximum': self.maximum_draw or 0,
  416. 'outlet_count': PowerOutlet.objects.filter(power_port=self).count(),
  417. 'legs': [],
  418. }
  419. #
  420. # Power outlets
  421. #
  422. @extras_features('webhooks')
  423. class PowerOutlet(CableTermination, ComponentModel):
  424. """
  425. A physical power outlet (output) within a Device which provides power to a PowerPort.
  426. """
  427. type = models.CharField(
  428. max_length=50,
  429. choices=PowerOutletTypeChoices,
  430. blank=True,
  431. help_text='Physical port type'
  432. )
  433. power_port = models.ForeignKey(
  434. to='dcim.PowerPort',
  435. on_delete=models.SET_NULL,
  436. blank=True,
  437. null=True,
  438. related_name='poweroutlets'
  439. )
  440. feed_leg = models.CharField(
  441. max_length=50,
  442. choices=PowerOutletFeedLegChoices,
  443. blank=True,
  444. help_text="Phase (for three-phase feeds)"
  445. )
  446. connection_status = models.BooleanField(
  447. choices=CONNECTION_STATUS_CHOICES,
  448. blank=True,
  449. null=True
  450. )
  451. tags = TaggableManager(through=TaggedItem)
  452. csv_headers = ['device', 'name', 'label', 'type', 'power_port', 'feed_leg', 'description']
  453. class Meta:
  454. ordering = ('device', '_name')
  455. unique_together = ('device', 'name')
  456. def get_absolute_url(self):
  457. return reverse('dcim:poweroutlet', kwargs={'pk': self.pk})
  458. def to_csv(self):
  459. return (
  460. self.device.identifier,
  461. self.name,
  462. self.label,
  463. self.get_type_display(),
  464. self.power_port.name if self.power_port else None,
  465. self.get_feed_leg_display(),
  466. self.description,
  467. )
  468. def clean(self):
  469. # Validate power port assignment
  470. if self.power_port and self.power_port.device != self.device:
  471. raise ValidationError(
  472. "Parent power port ({}) must belong to the same device".format(self.power_port)
  473. )
  474. #
  475. # Interfaces
  476. #
  477. class BaseInterface(models.Model):
  478. """
  479. Abstract base class for fields shared by dcim.Interface and virtualization.VMInterface.
  480. """
  481. enabled = models.BooleanField(
  482. default=True
  483. )
  484. mac_address = MACAddressField(
  485. null=True,
  486. blank=True,
  487. verbose_name='MAC Address'
  488. )
  489. mtu = models.PositiveIntegerField(
  490. blank=True,
  491. null=True,
  492. validators=[MinValueValidator(1), MaxValueValidator(65536)],
  493. verbose_name='MTU'
  494. )
  495. mode = models.CharField(
  496. max_length=50,
  497. choices=InterfaceModeChoices,
  498. blank=True
  499. )
  500. class Meta:
  501. abstract = True
  502. @extras_features('graphs', 'export_templates', 'webhooks')
  503. class Interface(CableTermination, ComponentModel, BaseInterface):
  504. """
  505. A network interface within a Device. A physical Interface can connect to exactly one other Interface.
  506. """
  507. # Override ComponentModel._name to specify naturalize_interface function
  508. _name = NaturalOrderingField(
  509. target_field='name',
  510. naturalize_function=naturalize_interface,
  511. max_length=100,
  512. blank=True
  513. )
  514. _connected_interface = models.OneToOneField(
  515. to='self',
  516. on_delete=models.SET_NULL,
  517. related_name='+',
  518. blank=True,
  519. null=True
  520. )
  521. _connected_circuittermination = models.OneToOneField(
  522. to='circuits.CircuitTermination',
  523. on_delete=models.SET_NULL,
  524. related_name='+',
  525. blank=True,
  526. null=True
  527. )
  528. connection_status = models.BooleanField(
  529. choices=CONNECTION_STATUS_CHOICES,
  530. blank=True,
  531. null=True
  532. )
  533. lag = models.ForeignKey(
  534. to='self',
  535. on_delete=models.SET_NULL,
  536. related_name='member_interfaces',
  537. null=True,
  538. blank=True,
  539. verbose_name='Parent LAG'
  540. )
  541. type = models.CharField(
  542. max_length=50,
  543. choices=InterfaceTypeChoices
  544. )
  545. mgmt_only = models.BooleanField(
  546. default=False,
  547. verbose_name='OOB Management',
  548. help_text='This interface is used only for out-of-band management'
  549. )
  550. untagged_vlan = models.ForeignKey(
  551. to='ipam.VLAN',
  552. on_delete=models.SET_NULL,
  553. related_name='interfaces_as_untagged',
  554. null=True,
  555. blank=True,
  556. verbose_name='Untagged VLAN'
  557. )
  558. tagged_vlans = models.ManyToManyField(
  559. to='ipam.VLAN',
  560. related_name='interfaces_as_tagged',
  561. blank=True,
  562. verbose_name='Tagged VLANs'
  563. )
  564. ip_addresses = GenericRelation(
  565. to='ipam.IPAddress',
  566. content_type_field='assigned_object_type',
  567. object_id_field='assigned_object_id',
  568. related_query_name='interface'
  569. )
  570. tags = TaggableManager(through=TaggedItem)
  571. csv_headers = [
  572. 'device', 'name', 'label', 'lag', 'type', 'enabled', 'mac_address', 'mtu', 'mgmt_only', 'description', 'mode',
  573. ]
  574. class Meta:
  575. ordering = ('device', CollateAsChar('_name'))
  576. unique_together = ('device', 'name')
  577. def get_absolute_url(self):
  578. return reverse('dcim:interface', kwargs={'pk': self.pk})
  579. def to_csv(self):
  580. return (
  581. self.device.identifier if self.device else None,
  582. self.name,
  583. self.label,
  584. self.lag.name if self.lag else None,
  585. self.get_type_display(),
  586. self.enabled,
  587. self.mac_address,
  588. self.mtu,
  589. self.mgmt_only,
  590. self.description,
  591. self.get_mode_display(),
  592. )
  593. def clean(self):
  594. # Virtual interfaces cannot be connected
  595. if self.type in NONCONNECTABLE_IFACE_TYPES and (
  596. self.cable or getattr(self, 'circuit_termination', False)
  597. ):
  598. raise ValidationError({
  599. 'type': "Virtual and wireless interfaces cannot be connected to another interface or circuit. "
  600. "Disconnect the interface or choose a suitable type."
  601. })
  602. # An interface's LAG must belong to the same device (or VC master)
  603. if self.lag and self.lag.device not in [self.device, self.device.get_vc_master()]:
  604. raise ValidationError({
  605. 'lag': "The selected LAG interface ({}) belongs to a different device ({}).".format(
  606. self.lag.name, self.lag.device.name
  607. )
  608. })
  609. # A virtual interface cannot have a parent LAG
  610. if self.type in NONCONNECTABLE_IFACE_TYPES and self.lag is not None:
  611. raise ValidationError({
  612. 'lag': "{} interfaces cannot have a parent LAG interface.".format(self.get_type_display())
  613. })
  614. # Only a LAG can have LAG members
  615. if self.type != InterfaceTypeChoices.TYPE_LAG and self.member_interfaces.exists():
  616. raise ValidationError({
  617. 'type': "Cannot change interface type; it has LAG members ({}).".format(
  618. ", ".join([iface.name for iface in self.member_interfaces.all()])
  619. )
  620. })
  621. # Validate untagged VLAN
  622. if self.untagged_vlan and self.untagged_vlan.site not in [self.parent.site, None]:
  623. raise ValidationError({
  624. 'untagged_vlan': "The untagged VLAN ({}) must belong to the same site as the interface's parent "
  625. "device, or it must be global".format(self.untagged_vlan)
  626. })
  627. def save(self, *args, **kwargs):
  628. # Remove untagged VLAN assignment for non-802.1Q interfaces
  629. if self.mode is None:
  630. self.untagged_vlan = None
  631. # Only "tagged" interfaces may have tagged VLANs assigned. ("tagged all" implies all VLANs are assigned.)
  632. if self.pk and self.mode != InterfaceModeChoices.MODE_TAGGED:
  633. self.tagged_vlans.clear()
  634. return super().save(*args, **kwargs)
  635. @property
  636. def connected_endpoint(self):
  637. """
  638. Return the connected Interface, if it exists, or the connected CircuitTermination, if it exists. We have to
  639. check for ObjectDoesNotExist in case the referenced object has been deleted from the database.
  640. """
  641. try:
  642. if self._connected_interface:
  643. return self._connected_interface
  644. except ObjectDoesNotExist:
  645. pass
  646. try:
  647. if self._connected_circuittermination:
  648. return self._connected_circuittermination
  649. except ObjectDoesNotExist:
  650. pass
  651. return None
  652. @connected_endpoint.setter
  653. def connected_endpoint(self, value):
  654. from circuits.models import CircuitTermination
  655. if value is None:
  656. self._connected_interface = None
  657. self._connected_circuittermination = None
  658. elif isinstance(value, Interface):
  659. self._connected_interface = value
  660. self._connected_circuittermination = None
  661. elif isinstance(value, CircuitTermination):
  662. self._connected_interface = None
  663. self._connected_circuittermination = value
  664. else:
  665. raise ValueError(
  666. "Connected endpoint must be an Interface or CircuitTermination, not {}.".format(type(value))
  667. )
  668. @property
  669. def parent(self):
  670. return self.device
  671. @property
  672. def is_connectable(self):
  673. return self.type not in NONCONNECTABLE_IFACE_TYPES
  674. @property
  675. def is_virtual(self):
  676. return self.type in VIRTUAL_IFACE_TYPES
  677. @property
  678. def is_wireless(self):
  679. return self.type in WIRELESS_IFACE_TYPES
  680. @property
  681. def is_lag(self):
  682. return self.type == InterfaceTypeChoices.TYPE_LAG
  683. @property
  684. def count_ipaddresses(self):
  685. return self.ip_addresses.count()
  686. #
  687. # Pass-through ports
  688. #
  689. @extras_features('webhooks')
  690. class FrontPort(CableTermination, ComponentModel):
  691. """
  692. A pass-through port on the front of a Device.
  693. """
  694. type = models.CharField(
  695. max_length=50,
  696. choices=PortTypeChoices
  697. )
  698. rear_port = models.ForeignKey(
  699. to='dcim.RearPort',
  700. on_delete=models.CASCADE,
  701. related_name='frontports'
  702. )
  703. rear_port_position = models.PositiveSmallIntegerField(
  704. default=1,
  705. validators=[MinValueValidator(1), MaxValueValidator(64)]
  706. )
  707. tags = TaggableManager(through=TaggedItem)
  708. csv_headers = ['device', 'name', 'label', 'type', 'rear_port', 'rear_port_position', 'description']
  709. class Meta:
  710. ordering = ('device', '_name')
  711. unique_together = (
  712. ('device', 'name'),
  713. ('rear_port', 'rear_port_position'),
  714. )
  715. def get_absolute_url(self):
  716. return reverse('dcim:frontport', kwargs={'pk': self.pk})
  717. def to_csv(self):
  718. return (
  719. self.device.identifier,
  720. self.name,
  721. self.label,
  722. self.get_type_display(),
  723. self.rear_port.name,
  724. self.rear_port_position,
  725. self.description,
  726. )
  727. def clean(self):
  728. # Validate rear port assignment
  729. if self.rear_port.device != self.device:
  730. raise ValidationError(
  731. "Rear port ({}) must belong to the same device".format(self.rear_port)
  732. )
  733. # Validate rear port position assignment
  734. if self.rear_port_position > self.rear_port.positions:
  735. raise ValidationError(
  736. "Invalid rear port position ({}); rear port {} has only {} positions".format(
  737. self.rear_port_position, self.rear_port.name, self.rear_port.positions
  738. )
  739. )
  740. @extras_features('webhooks')
  741. class RearPort(CableTermination, ComponentModel):
  742. """
  743. A pass-through port on the rear of a Device.
  744. """
  745. type = models.CharField(
  746. max_length=50,
  747. choices=PortTypeChoices
  748. )
  749. positions = models.PositiveSmallIntegerField(
  750. default=1,
  751. validators=[MinValueValidator(1), MaxValueValidator(64)]
  752. )
  753. tags = TaggableManager(through=TaggedItem)
  754. csv_headers = ['device', 'name', 'label', 'type', 'positions', 'description']
  755. class Meta:
  756. ordering = ('device', '_name')
  757. unique_together = ('device', 'name')
  758. def get_absolute_url(self):
  759. return reverse('dcim:rearport', kwargs={'pk': self.pk})
  760. def to_csv(self):
  761. return (
  762. self.device.identifier,
  763. self.name,
  764. self.label,
  765. self.get_type_display(),
  766. self.positions,
  767. self.description,
  768. )
  769. #
  770. # Device bays
  771. #
  772. @extras_features('webhooks')
  773. class DeviceBay(ComponentModel):
  774. """
  775. An empty space within a Device which can house a child device
  776. """
  777. installed_device = models.OneToOneField(
  778. to='dcim.Device',
  779. on_delete=models.SET_NULL,
  780. related_name='parent_bay',
  781. blank=True,
  782. null=True
  783. )
  784. tags = TaggableManager(through=TaggedItem)
  785. csv_headers = ['device', 'name', 'label', 'installed_device', 'description']
  786. class Meta:
  787. ordering = ('device', '_name')
  788. unique_together = ('device', 'name')
  789. def get_absolute_url(self):
  790. return reverse('dcim:devicebay', kwargs={'pk': self.pk})
  791. def to_csv(self):
  792. return (
  793. self.device.identifier,
  794. self.name,
  795. self.label,
  796. self.installed_device.identifier if self.installed_device else None,
  797. self.description,
  798. )
  799. def clean(self):
  800. # Validate that the parent Device can have DeviceBays
  801. if not self.device.device_type.is_parent_device:
  802. raise ValidationError("This type of device ({}) does not support device bays.".format(
  803. self.device.device_type
  804. ))
  805. # Cannot install a device into itself, obviously
  806. if self.device == self.installed_device:
  807. raise ValidationError("Cannot install a device into itself.")
  808. # Check that the installed device is not already installed elsewhere
  809. if self.installed_device:
  810. current_bay = DeviceBay.objects.filter(installed_device=self.installed_device).first()
  811. if current_bay and current_bay != self:
  812. raise ValidationError({
  813. 'installed_device': "Cannot install the specified device; device is already installed in {}".format(
  814. current_bay
  815. )
  816. })
  817. #
  818. # Inventory items
  819. #
  820. @extras_features('export_templates', 'webhooks')
  821. class InventoryItem(ComponentModel):
  822. """
  823. An InventoryItem represents a serialized piece of hardware within a Device, such as a line card or power supply.
  824. InventoryItems are used only for inventory purposes.
  825. """
  826. parent = models.ForeignKey(
  827. to='self',
  828. on_delete=models.CASCADE,
  829. related_name='child_items',
  830. blank=True,
  831. null=True
  832. )
  833. manufacturer = models.ForeignKey(
  834. to='dcim.Manufacturer',
  835. on_delete=models.PROTECT,
  836. related_name='inventory_items',
  837. blank=True,
  838. null=True
  839. )
  840. part_id = models.CharField(
  841. max_length=50,
  842. verbose_name='Part ID',
  843. blank=True,
  844. help_text='Manufacturer-assigned part identifier'
  845. )
  846. serial = models.CharField(
  847. max_length=50,
  848. verbose_name='Serial number',
  849. blank=True
  850. )
  851. asset_tag = models.CharField(
  852. max_length=50,
  853. unique=True,
  854. blank=True,
  855. null=True,
  856. verbose_name='Asset tag',
  857. help_text='A unique tag used to identify this item'
  858. )
  859. discovered = models.BooleanField(
  860. default=False,
  861. help_text='This item was automatically discovered'
  862. )
  863. tags = TaggableManager(through=TaggedItem)
  864. csv_headers = [
  865. 'device', 'name', 'label', 'manufacturer', 'part_id', 'serial', 'asset_tag', 'discovered', 'description',
  866. ]
  867. class Meta:
  868. ordering = ('device__id', 'parent__id', '_name')
  869. unique_together = ('device', 'parent', 'name')
  870. def get_absolute_url(self):
  871. return reverse('dcim:inventoryitem', kwargs={'pk': self.pk})
  872. def to_csv(self):
  873. return (
  874. self.device.name or '{{{}}}'.format(self.device.pk),
  875. self.name,
  876. self.label,
  877. self.manufacturer.name if self.manufacturer else None,
  878. self.part_id,
  879. self.serial,
  880. self.asset_tag,
  881. self.discovered,
  882. self.description,
  883. )