cables.py 26 KB

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