device_components.py 32 KB

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