cables.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. import itertools
  2. from collections import defaultdict
  3. from django.contrib.contenttypes.fields import GenericForeignKey
  4. from django.contrib.contenttypes.models import ContentType
  5. from django.core.exceptions import ValidationError
  6. from django.db import models
  7. from django.db.models import Sum
  8. from django.dispatch import Signal
  9. from django.urls import reverse
  10. from dcim.choices import *
  11. from dcim.constants import *
  12. from dcim.fields import PathField
  13. from dcim.utils import decompile_path_node, object_to_path_node, path_node_to_object
  14. from netbox.models import NetBoxModel
  15. from utilities.fields import ColorField
  16. from utilities.querysets import RestrictedQuerySet
  17. from utilities.utils import to_meters
  18. from wireless.models import WirelessLink
  19. from .device_components import FrontPort, RearPort
  20. __all__ = (
  21. 'Cable',
  22. 'CablePath',
  23. 'CableTermination',
  24. )
  25. trace_paths = Signal()
  26. #
  27. # Cables
  28. #
  29. class Cable(NetBoxModel):
  30. """
  31. A physical connection between two endpoints.
  32. """
  33. type = models.CharField(
  34. max_length=50,
  35. choices=CableTypeChoices,
  36. blank=True
  37. )
  38. status = models.CharField(
  39. max_length=50,
  40. choices=LinkStatusChoices,
  41. default=LinkStatusChoices.STATUS_CONNECTED
  42. )
  43. tenant = models.ForeignKey(
  44. to='tenancy.Tenant',
  45. on_delete=models.PROTECT,
  46. related_name='cables',
  47. blank=True,
  48. null=True
  49. )
  50. label = models.CharField(
  51. max_length=100,
  52. blank=True
  53. )
  54. color = ColorField(
  55. blank=True
  56. )
  57. length = models.DecimalField(
  58. max_digits=8,
  59. decimal_places=2,
  60. blank=True,
  61. null=True
  62. )
  63. length_unit = models.CharField(
  64. max_length=50,
  65. choices=CableLengthUnitChoices,
  66. blank=True,
  67. )
  68. # Stores the normalized length (in meters) for database ordering
  69. _abs_length = models.DecimalField(
  70. max_digits=10,
  71. decimal_places=4,
  72. blank=True,
  73. null=True
  74. )
  75. class Meta:
  76. ordering = ('pk',)
  77. def __init__(self, *args, a_terminations=None, b_terminations=None, **kwargs):
  78. super().__init__(*args, **kwargs)
  79. # A copy of the PK to be used by __str__ in case the object is deleted
  80. self._pk = self.pk
  81. # Cache the original status so we can check later if it's been changed
  82. self._orig_status = self.status
  83. self._terminations_modified = False
  84. # Assign or retrieve A/B terminations
  85. if a_terminations:
  86. self.a_terminations = a_terminations
  87. if b_terminations:
  88. self.b_terminations = b_terminations
  89. def __str__(self):
  90. pk = self.pk or self._pk
  91. return self.label or f'#{pk}'
  92. def get_absolute_url(self):
  93. return reverse('dcim:cable', args=[self.pk])
  94. @property
  95. def a_terminations(self):
  96. if hasattr(self, '_a_terminations'):
  97. return self._a_terminations
  98. # Query self.terminations.all() to leverage cached results
  99. return [
  100. ct.termination for ct in self.terminations.all() if ct.cable_end == CableEndChoices.SIDE_A
  101. ]
  102. @a_terminations.setter
  103. def a_terminations(self, value):
  104. self._terminations_modified = True
  105. self._a_terminations = value
  106. @property
  107. def b_terminations(self):
  108. if hasattr(self, '_b_terminations'):
  109. return self._b_terminations
  110. # Query self.terminations.all() to leverage cached results
  111. return [
  112. ct.termination for ct in self.terminations.all() if ct.cable_end == CableEndChoices.SIDE_B
  113. ]
  114. @b_terminations.setter
  115. def b_terminations(self, value):
  116. self._terminations_modified = True
  117. self._b_terminations = value
  118. def clean(self):
  119. super().clean()
  120. # Validate length and length_unit
  121. if self.length is not None and not self.length_unit:
  122. raise ValidationError("Must specify a unit when setting a cable length")
  123. elif self.length is None:
  124. self.length_unit = ''
  125. if self.pk is None and (not self.a_terminations or not self.b_terminations):
  126. raise ValidationError("Must define A and B terminations when creating a new cable.")
  127. if self._terminations_modified:
  128. # Check that all termination objects for either end are of the same type
  129. for terms in (self.a_terminations, self.b_terminations):
  130. if len(terms) > 1 and not all(isinstance(t, type(terms[0])) for t in terms[1:]):
  131. raise ValidationError("Cannot connect different termination types to same end of cable.")
  132. # Check that termination types are compatible
  133. if self.a_terminations and self.b_terminations:
  134. a_type = self.a_terminations[0]._meta.model_name
  135. b_type = self.b_terminations[0]._meta.model_name
  136. if b_type not in COMPATIBLE_TERMINATION_TYPES.get(a_type):
  137. raise ValidationError(f"Incompatible termination types: {a_type} and {b_type}")
  138. # Run clean() on any new CableTerminations
  139. for termination in self.a_terminations:
  140. CableTermination(cable=self, cable_end='A', termination=termination).clean()
  141. for termination in self.b_terminations:
  142. CableTermination(cable=self, cable_end='B', termination=termination).clean()
  143. def save(self, *args, **kwargs):
  144. _created = self.pk is None
  145. # Store the given length (if any) in meters for use in database ordering
  146. if self.length and self.length_unit:
  147. self._abs_length = to_meters(self.length, self.length_unit)
  148. else:
  149. self._abs_length = None
  150. super().save(*args, **kwargs)
  151. # Update the private pk used in __str__ in case this is a new object (i.e. just got its pk)
  152. self._pk = self.pk
  153. # Retrieve existing A/B terminations for the Cable
  154. a_terminations = {ct.termination: ct for ct in self.terminations.filter(cable_end='A')}
  155. b_terminations = {ct.termination: ct for ct in self.terminations.filter(cable_end='B')}
  156. # Delete stale CableTerminations
  157. if self._terminations_modified:
  158. for termination, ct in a_terminations.items():
  159. if termination.pk and termination not in self.a_terminations:
  160. ct.delete()
  161. for termination, ct in b_terminations.items():
  162. if termination.pk and termination not in self.b_terminations:
  163. ct.delete()
  164. # Save new CableTerminations (if any)
  165. if self._terminations_modified:
  166. for termination in self.a_terminations:
  167. if not termination.pk or termination not in a_terminations:
  168. CableTermination(cable=self, cable_end='A', termination=termination).save()
  169. for termination in self.b_terminations:
  170. if not termination.pk or termination not in b_terminations:
  171. CableTermination(cable=self, cable_end='B', termination=termination).save()
  172. trace_paths.send(Cable, instance=self, created=_created)
  173. def get_status_color(self):
  174. return LinkStatusChoices.colors.get(self.status)
  175. class CableTermination(models.Model):
  176. """
  177. A mapping between side A or B of a Cable and a terminating object (e.g. an Interface or CircuitTermination).
  178. """
  179. cable = models.ForeignKey(
  180. to='dcim.Cable',
  181. on_delete=models.CASCADE,
  182. related_name='terminations'
  183. )
  184. cable_end = models.CharField(
  185. max_length=1,
  186. choices=CableEndChoices,
  187. verbose_name='End'
  188. )
  189. termination_type = models.ForeignKey(
  190. to=ContentType,
  191. limit_choices_to=CABLE_TERMINATION_MODELS,
  192. on_delete=models.PROTECT,
  193. related_name='+'
  194. )
  195. termination_id = models.PositiveBigIntegerField()
  196. termination = GenericForeignKey(
  197. ct_field='termination_type',
  198. fk_field='termination_id'
  199. )
  200. # Cached associations to enable efficient filtering
  201. _device = models.ForeignKey(
  202. to='dcim.Device',
  203. on_delete=models.CASCADE,
  204. blank=True,
  205. null=True
  206. )
  207. _rack = models.ForeignKey(
  208. to='dcim.Rack',
  209. on_delete=models.CASCADE,
  210. blank=True,
  211. null=True
  212. )
  213. _location = models.ForeignKey(
  214. to='dcim.Location',
  215. on_delete=models.CASCADE,
  216. blank=True,
  217. null=True
  218. )
  219. _site = models.ForeignKey(
  220. to='dcim.Site',
  221. on_delete=models.CASCADE,
  222. blank=True,
  223. null=True
  224. )
  225. objects = RestrictedQuerySet.as_manager()
  226. class Meta:
  227. ordering = ('cable', 'cable_end', 'pk')
  228. constraints = (
  229. models.UniqueConstraint(
  230. fields=('termination_type', 'termination_id'),
  231. name='%(app_label)s_%(class)s_unique_termination'
  232. ),
  233. )
  234. def __str__(self):
  235. return f'Cable {self.cable} to {self.termination}'
  236. def clean(self):
  237. super().clean()
  238. # Validate interface type (if applicable)
  239. if self.termination_type.model == 'interface' and self.termination.type in NONCONNECTABLE_IFACE_TYPES:
  240. raise ValidationError(f"Cables cannot be terminated to {self.termination.get_type_display()} interfaces")
  241. # A CircuitTermination attached to a ProviderNetwork cannot have a Cable
  242. if self.termination_type.model == 'circuittermination' and self.termination.provider_network is not None:
  243. raise ValidationError("Circuit terminations attached to a provider network may not be cabled.")
  244. def save(self, *args, **kwargs):
  245. # Cache objects associated with the terminating object (for filtering)
  246. self.cache_related_objects()
  247. super().save(*args, **kwargs)
  248. # Set the cable on the terminating object
  249. termination_model = self.termination._meta.model
  250. termination_model.objects.filter(pk=self.termination_id).update(
  251. cable=self.cable,
  252. cable_end=self.cable_end
  253. )
  254. def delete(self, *args, **kwargs):
  255. # Delete the cable association on the terminating object
  256. termination_model = self.termination._meta.model
  257. termination_model.objects.filter(pk=self.termination_id).update(
  258. cable=None,
  259. cable_end=''
  260. )
  261. super().delete(*args, **kwargs)
  262. def cache_related_objects(self):
  263. """
  264. Cache objects related to the termination (e.g. device, rack, site) directly on the object to
  265. enable efficient filtering.
  266. """
  267. assert self.termination is not None
  268. # Device components
  269. if getattr(self.termination, 'device', None):
  270. self._device = self.termination.device
  271. self._rack = self.termination.device.rack
  272. self._location = self.termination.device.location
  273. self._site = self.termination.device.site
  274. # Power feeds
  275. elif getattr(self.termination, 'rack', None):
  276. self._rack = self.termination.rack
  277. self._location = self.termination.rack.location
  278. self._site = self.termination.rack.site
  279. # Circuit terminations
  280. elif getattr(self.termination, 'site', None):
  281. self._site = self.termination.site
  282. class CablePath(models.Model):
  283. """
  284. A CablePath instance represents the physical path from a set of origin nodes to a set of destination nodes,
  285. including all intermediate elements.
  286. `path` contains the ordered set of nodes, arranged in lists of (type, ID) tuples. (Each cable in the path can
  287. terminate to one or more objects.) For example, consider the following
  288. topology:
  289. A B C
  290. Interface 1 --- Front Port 1 | Rear Port 1 --- Rear Port 2 | Front Port 3 --- Interface 2
  291. Front Port 2 Front Port 4
  292. This path would be expressed as:
  293. CablePath(
  294. path = [
  295. [Interface 1],
  296. [Cable A],
  297. [Front Port 1, Front Port 2],
  298. [Rear Port 1],
  299. [Cable B],
  300. [Rear Port 2],
  301. [Front Port 3, Front Port 4],
  302. [Cable C],
  303. [Interface 2],
  304. ]
  305. )
  306. `is_active` is set to True only if every Cable within the path has a status of "connected". `is_complete` is True
  307. if the instance represents a complete end-to-end path from origin(s) to destination(s). `is_split` is True if the
  308. path diverges across multiple cables.
  309. `_nodes` retains a flattened list of all nodes within the path to enable simple filtering.
  310. """
  311. path = models.JSONField(
  312. default=list
  313. )
  314. is_active = models.BooleanField(
  315. default=False
  316. )
  317. is_complete = models.BooleanField(
  318. default=False
  319. )
  320. is_split = models.BooleanField(
  321. default=False
  322. )
  323. _nodes = PathField()
  324. def __str__(self):
  325. return f"Path #{self.pk}: {len(self.path)} hops"
  326. def save(self, *args, **kwargs):
  327. # Save the flattened nodes list
  328. self._nodes = list(itertools.chain(*self.path))
  329. super().save(*args, **kwargs)
  330. # Record a direct reference to this CablePath on its originating object(s)
  331. origin_model = self.origin_type.model_class()
  332. origin_ids = [decompile_path_node(node)[1] for node in self.path[0]]
  333. origin_model.objects.filter(pk__in=origin_ids).update(_path=self.pk)
  334. @property
  335. def origin_type(self):
  336. if self.path:
  337. ct_id, _ = decompile_path_node(self.path[0][0])
  338. return ContentType.objects.get_for_id(ct_id)
  339. @property
  340. def destination_type(self):
  341. if self.is_complete:
  342. ct_id, _ = decompile_path_node(self.path[-1][0])
  343. return ContentType.objects.get_for_id(ct_id)
  344. @property
  345. def path_objects(self):
  346. """
  347. Cache and return the complete path as lists of objects, derived from their annotation within the path.
  348. """
  349. if not hasattr(self, '_path_objects'):
  350. self._path_objects = self._get_path()
  351. return self._path_objects
  352. @property
  353. def origins(self):
  354. """
  355. Return the list of originating objects.
  356. """
  357. return self.path_objects[0]
  358. @property
  359. def destinations(self):
  360. """
  361. Return the list of destination objects, if the path is complete.
  362. """
  363. if not self.is_complete:
  364. return []
  365. return self.path_objects[-1]
  366. @property
  367. def segment_count(self):
  368. return int(len(self.path) / 3)
  369. @classmethod
  370. def from_origin(cls, terminations):
  371. """
  372. Create a new CablePath instance as traced from the given termination objects. These can be any object to which a
  373. Cable or WirelessLink connects (interfaces, console ports, circuit termination, etc.). All terminations must be
  374. of the same type and must belong to the same parent object.
  375. """
  376. from circuits.models import CircuitTermination
  377. if not terminations:
  378. return None
  379. # Ensure all originating terminations are attached to the same link
  380. if len(terminations) > 1:
  381. assert all(t.link == terminations[0].link for t in terminations[1:])
  382. path = []
  383. position_stack = []
  384. is_complete = False
  385. is_active = True
  386. is_split = False
  387. while terminations:
  388. # Terminations must all be of the same type
  389. assert all(isinstance(t, type(terminations[0])) for t in terminations[1:])
  390. # Check for a split path (e.g. rear port fanning out to multiple front ports with
  391. # different cables attached)
  392. if len(set(t.link for t in terminations)) > 1:
  393. is_split = True
  394. break
  395. # Step 1: Record the near-end termination object(s)
  396. path.append([
  397. object_to_path_node(t) for t in terminations
  398. ])
  399. # Step 2: Determine the attached link (Cable or WirelessLink), if any
  400. link = terminations[0].link
  401. if link is None and len(path) == 1:
  402. # If this is the start of the path and no link exists, return None
  403. return None
  404. elif link is None:
  405. # Otherwise, halt the trace if no link exists
  406. break
  407. assert type(link) in (Cable, WirelessLink)
  408. # Step 3: Record the link and update path status if not "connected"
  409. path.append([object_to_path_node(link)])
  410. if hasattr(link, 'status') and link.status != LinkStatusChoices.STATUS_CONNECTED:
  411. is_active = False
  412. # Step 4: Determine the far-end terminations
  413. if isinstance(link, Cable):
  414. termination_type = ContentType.objects.get_for_model(terminations[0])
  415. local_cable_terminations = CableTermination.objects.filter(
  416. termination_type=termination_type,
  417. termination_id__in=[t.pk for t in terminations]
  418. )
  419. # Terminations must all belong to same end of Cable
  420. local_cable_end = local_cable_terminations[0].cable_end
  421. assert all(ct.cable_end == local_cable_end for ct in local_cable_terminations[1:])
  422. remote_cable_terminations = CableTermination.objects.filter(
  423. cable=link,
  424. cable_end='A' if local_cable_end == 'B' else 'B'
  425. )
  426. remote_terminations = [ct.termination for ct in remote_cable_terminations]
  427. else:
  428. # WirelessLink
  429. remote_terminations = [link.interface_b] if link.interface_a is terminations[0] else [link.interface_a]
  430. # Step 5: Record the far-end termination object(s)
  431. path.append([
  432. object_to_path_node(t) for t in remote_terminations
  433. ])
  434. # Step 6: Determine the "next hop" terminations, if applicable
  435. if not remote_terminations:
  436. break
  437. if isinstance(remote_terminations[0], FrontPort):
  438. # Follow FrontPorts to their corresponding RearPorts
  439. rear_ports = RearPort.objects.filter(
  440. pk__in=[t.rear_port_id for t in remote_terminations]
  441. )
  442. if len(rear_ports) > 1:
  443. assert all(rp.positions == 1 for rp in rear_ports)
  444. elif rear_ports[0].positions > 1:
  445. position_stack.append([fp.rear_port_position for fp in remote_terminations])
  446. terminations = rear_ports
  447. elif isinstance(remote_terminations[0], RearPort):
  448. if len(remote_terminations) > 1 or remote_terminations[0].positions == 1:
  449. front_ports = FrontPort.objects.filter(
  450. rear_port_id__in=[rp.pk for rp in remote_terminations],
  451. rear_port_position=1
  452. )
  453. elif position_stack:
  454. front_ports = FrontPort.objects.filter(
  455. rear_port_id=remote_terminations[0].pk,
  456. rear_port_position__in=position_stack.pop()
  457. )
  458. else:
  459. # No position indicated: path has split, so we stop at the RearPorts
  460. is_split = True
  461. break
  462. terminations = front_ports
  463. elif isinstance(remote_terminations[0], CircuitTermination):
  464. # Follow a CircuitTermination to its corresponding CircuitTermination (A to Z or vice versa)
  465. term_side = remote_terminations[0].term_side
  466. assert all(ct.term_side == term_side for ct in remote_terminations[1:])
  467. circuit_termination = CircuitTermination.objects.filter(
  468. circuit=remote_terminations[0].circuit,
  469. term_side='Z' if term_side == 'A' else 'A'
  470. ).first()
  471. if circuit_termination is None:
  472. break
  473. elif circuit_termination.provider_network:
  474. # Circuit terminates to a ProviderNetwork
  475. path.extend([
  476. [object_to_path_node(circuit_termination)],
  477. [object_to_path_node(circuit_termination.provider_network)],
  478. ])
  479. break
  480. elif circuit_termination.site and not circuit_termination.cable:
  481. # Circuit terminates to a Site
  482. path.extend([
  483. [object_to_path_node(circuit_termination)],
  484. [object_to_path_node(circuit_termination.site)],
  485. ])
  486. break
  487. terminations = [circuit_termination]
  488. # Anything else marks the end of the path
  489. else:
  490. is_complete = True
  491. break
  492. return cls(
  493. path=path,
  494. is_complete=is_complete,
  495. is_active=is_active,
  496. is_split=is_split
  497. )
  498. def retrace(self):
  499. """
  500. Retrace the path from the currently-defined originating termination(s)
  501. """
  502. _new = self.from_origin(self.origins)
  503. if _new:
  504. self.path = _new.path
  505. self.is_complete = _new.is_complete
  506. self.is_active = _new.is_active
  507. self.is_split = _new.is_split
  508. self.save()
  509. else:
  510. self.delete()
  511. def _get_path(self):
  512. """
  513. Return the path as a list of prefetched objects.
  514. """
  515. # Compile a list of IDs to prefetch for each type of model in the path
  516. to_prefetch = defaultdict(list)
  517. for node in self._nodes:
  518. ct_id, object_id = decompile_path_node(node)
  519. to_prefetch[ct_id].append(object_id)
  520. # Prefetch path objects using one query per model type. Prefetch related devices where appropriate.
  521. prefetched = {}
  522. for ct_id, object_ids in to_prefetch.items():
  523. model_class = ContentType.objects.get_for_id(ct_id).model_class()
  524. queryset = model_class.objects.filter(pk__in=object_ids)
  525. if hasattr(model_class, 'device'):
  526. queryset = queryset.prefetch_related('device')
  527. prefetched[ct_id] = {
  528. obj.id: obj for obj in queryset
  529. }
  530. # Replicate the path using the prefetched objects.
  531. path = []
  532. for step in self.path:
  533. nodes = []
  534. for node in step:
  535. ct_id, object_id = decompile_path_node(node)
  536. try:
  537. nodes.append(prefetched[ct_id][object_id])
  538. except KeyError:
  539. # Ignore stale (deleted) object IDs
  540. pass
  541. path.append(nodes)
  542. return path
  543. def get_cable_ids(self):
  544. """
  545. Return all Cable IDs within the path.
  546. """
  547. cable_ct = ContentType.objects.get_for_model(Cable).pk
  548. cable_ids = []
  549. for node in self._nodes:
  550. ct, id = decompile_path_node(node)
  551. if ct == cable_ct:
  552. cable_ids.append(id)
  553. return cable_ids
  554. def get_total_length(self):
  555. """
  556. Return a tuple containing the sum of the length of each cable in the path
  557. and a flag indicating whether the length is definitive.
  558. """
  559. cable_ids = self.get_cable_ids()
  560. cables = Cable.objects.filter(id__in=cable_ids, _abs_length__isnull=False)
  561. total_length = cables.aggregate(total=Sum('_abs_length'))['total']
  562. is_definitive = len(cables) == len(cable_ids)
  563. return total_length, is_definitive
  564. def get_split_nodes(self):
  565. """
  566. Return all available next segments in a split cable path.
  567. """
  568. nodes = self.path_objects[-1]
  569. # RearPort splitting to multiple FrontPorts with no stack position
  570. if type(nodes[0]) is RearPort:
  571. return FrontPort.objects.filter(rear_port__in=nodes)
  572. # Cable terminating to multiple FrontPorts mapped to different
  573. # RearPorts connected to different cables
  574. elif type(nodes[0]) is FrontPort:
  575. return RearPort.objects.filter(pk__in=[fp.rear_port_id for fp in nodes])