device_components.py 33 KB

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