device_components.py 30 KB

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