cables.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  1. import itertools
  2. from collections import defaultdict
  3. from django.contrib.contenttypes.fields import GenericForeignKey
  4. from django.core.exceptions import ValidationError
  5. from django.db import models
  6. from django.db.models import Sum
  7. from django.dispatch import Signal
  8. from django.urls import reverse
  9. from django.utils.translation import gettext_lazy as _
  10. from core.models import ContentType
  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, PathEndpoint
  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. if a_type == b_type:
  152. # can't directly use self.a_terminations here as possible they
  153. # don't have pk yet
  154. a_pks = set(obj.pk for obj in self.a_terminations if obj.pk)
  155. b_pks = set(obj.pk for obj in self.b_terminations if obj.pk)
  156. if (a_pks & b_pks):
  157. raise ValidationError(
  158. _("A and B terminations cannot connect to the same object.")
  159. )
  160. # Run clean() on any new CableTerminations
  161. for termination in self.a_terminations:
  162. CableTermination(cable=self, cable_end='A', termination=termination).clean()
  163. for termination in self.b_terminations:
  164. CableTermination(cable=self, cable_end='B', termination=termination).clean()
  165. def save(self, *args, **kwargs):
  166. _created = self.pk is None
  167. # Store the given length (if any) in meters for use in database ordering
  168. if self.length is not None and self.length_unit:
  169. self._abs_length = to_meters(self.length, self.length_unit)
  170. else:
  171. self._abs_length = None
  172. # Clear length_unit if no length is defined
  173. if self.length is None:
  174. self.length_unit = ''
  175. super().save(*args, **kwargs)
  176. # Update the private pk used in __str__ in case this is a new object (i.e. just got its pk)
  177. self._pk = self.pk
  178. # Retrieve existing A/B terminations for the Cable
  179. a_terminations = {ct.termination: ct for ct in self.terminations.filter(cable_end='A')}
  180. b_terminations = {ct.termination: ct for ct in self.terminations.filter(cable_end='B')}
  181. # Delete stale CableTerminations
  182. if self._terminations_modified:
  183. for termination, ct in a_terminations.items():
  184. if termination.pk and termination not in self.a_terminations:
  185. ct.delete()
  186. for termination, ct in b_terminations.items():
  187. if termination.pk and termination not in self.b_terminations:
  188. ct.delete()
  189. # Save new CableTerminations (if any)
  190. if self._terminations_modified:
  191. for termination in self.a_terminations:
  192. if not termination.pk or termination not in a_terminations:
  193. CableTermination(cable=self, cable_end='A', termination=termination).save()
  194. for termination in self.b_terminations:
  195. if not termination.pk or termination not in b_terminations:
  196. CableTermination(cable=self, cable_end='B', termination=termination).save()
  197. trace_paths.send(Cable, instance=self, created=_created)
  198. def get_status_color(self):
  199. return LinkStatusChoices.colors.get(self.status)
  200. class CableTermination(ChangeLoggedModel):
  201. """
  202. A mapping between side A or B of a Cable and a terminating object (e.g. an Interface or CircuitTermination).
  203. """
  204. cable = models.ForeignKey(
  205. to='dcim.Cable',
  206. on_delete=models.CASCADE,
  207. related_name='terminations'
  208. )
  209. cable_end = models.CharField(
  210. max_length=1,
  211. choices=CableEndChoices,
  212. verbose_name=_('end')
  213. )
  214. termination_type = models.ForeignKey(
  215. to='contenttypes.ContentType',
  216. limit_choices_to=CABLE_TERMINATION_MODELS,
  217. on_delete=models.PROTECT,
  218. related_name='+'
  219. )
  220. termination_id = models.PositiveBigIntegerField()
  221. termination = GenericForeignKey(
  222. ct_field='termination_type',
  223. fk_field='termination_id'
  224. )
  225. # Cached associations to enable efficient filtering
  226. _device = models.ForeignKey(
  227. to='dcim.Device',
  228. on_delete=models.CASCADE,
  229. blank=True,
  230. null=True
  231. )
  232. _rack = models.ForeignKey(
  233. to='dcim.Rack',
  234. on_delete=models.CASCADE,
  235. blank=True,
  236. null=True
  237. )
  238. _location = models.ForeignKey(
  239. to='dcim.Location',
  240. on_delete=models.CASCADE,
  241. blank=True,
  242. null=True
  243. )
  244. _site = models.ForeignKey(
  245. to='dcim.Site',
  246. on_delete=models.CASCADE,
  247. blank=True,
  248. null=True
  249. )
  250. objects = RestrictedQuerySet.as_manager()
  251. class Meta:
  252. ordering = ('cable', 'cable_end', 'pk')
  253. indexes = (
  254. models.Index(fields=('termination_type', 'termination_id')),
  255. )
  256. constraints = (
  257. models.UniqueConstraint(
  258. fields=('termination_type', 'termination_id'),
  259. name='%(app_label)s_%(class)s_unique_termination'
  260. ),
  261. )
  262. verbose_name = _('cable termination')
  263. verbose_name_plural = _('cable terminations')
  264. def __str__(self):
  265. return f'Cable {self.cable} to {self.termination}'
  266. def clean(self):
  267. super().clean()
  268. # Check for existing termination
  269. qs = CableTermination.objects.filter(
  270. termination_type=self.termination_type,
  271. termination_id=self.termination_id
  272. )
  273. if self.cable.pk:
  274. qs = qs.exclude(cable=self.cable)
  275. existing_termination = qs.first()
  276. if existing_termination is not None:
  277. raise ValidationError(
  278. f"Duplicate termination found for {self.termination_type.app_label}.{self.termination_type.model} "
  279. f"{self.termination_id}: cable {existing_termination.cable.pk}"
  280. )
  281. # Validate interface type (if applicable)
  282. if self.termination_type.model == 'interface' and self.termination.type in NONCONNECTABLE_IFACE_TYPES:
  283. raise ValidationError(f"Cables cannot be terminated to {self.termination.get_type_display()} interfaces")
  284. # A CircuitTermination attached to a ProviderNetwork cannot have a Cable
  285. if self.termination_type.model == 'circuittermination' and self.termination.provider_network is not None:
  286. raise ValidationError("Circuit terminations attached to a provider network may not be cabled.")
  287. def save(self, *args, **kwargs):
  288. # Cache objects associated with the terminating object (for filtering)
  289. self.cache_related_objects()
  290. super().save(*args, **kwargs)
  291. # Set the cable on the terminating object
  292. termination_model = self.termination._meta.model
  293. termination_model.objects.filter(pk=self.termination_id).update(
  294. cable=self.cable,
  295. cable_end=self.cable_end
  296. )
  297. def delete(self, *args, **kwargs):
  298. # Delete the cable association on the terminating object
  299. termination_model = self.termination._meta.model
  300. termination_model.objects.filter(pk=self.termination_id).update(
  301. cable=None,
  302. cable_end=''
  303. )
  304. super().delete(*args, **kwargs)
  305. def cache_related_objects(self):
  306. """
  307. Cache objects related to the termination (e.g. device, rack, site) directly on the object to
  308. enable efficient filtering.
  309. """
  310. assert self.termination is not None
  311. # Device components
  312. if getattr(self.termination, 'device', None):
  313. self._device = self.termination.device
  314. self._rack = self.termination.device.rack
  315. self._location = self.termination.device.location
  316. self._site = self.termination.device.site
  317. # Power feeds
  318. elif getattr(self.termination, 'rack', None):
  319. self._rack = self.termination.rack
  320. self._location = self.termination.rack.location
  321. self._site = self.termination.rack.site
  322. # Circuit terminations
  323. elif getattr(self.termination, 'site', None):
  324. self._site = self.termination.site
  325. cache_related_objects.alters_data = True
  326. def to_objectchange(self, action):
  327. objectchange = super().to_objectchange(action)
  328. objectchange.related_object = self.termination
  329. return objectchange
  330. class CablePath(models.Model):
  331. """
  332. A CablePath instance represents the physical path from a set of origin nodes to a set of destination nodes,
  333. including all intermediate elements.
  334. `path` contains the ordered set of nodes, arranged in lists of (type, ID) tuples. (Each cable in the path can
  335. terminate to one or more objects.) For example, consider the following
  336. topology:
  337. A B C
  338. Interface 1 --- Front Port 1 | Rear Port 1 --- Rear Port 2 | Front Port 3 --- Interface 2
  339. Front Port 2 Front Port 4
  340. This path would be expressed as:
  341. CablePath(
  342. path = [
  343. [Interface 1],
  344. [Cable A],
  345. [Front Port 1, Front Port 2],
  346. [Rear Port 1],
  347. [Cable B],
  348. [Rear Port 2],
  349. [Front Port 3, Front Port 4],
  350. [Cable C],
  351. [Interface 2],
  352. ]
  353. )
  354. `is_active` is set to True only if every Cable within the path has a status of "connected". `is_complete` is True
  355. if the instance represents a complete end-to-end path from origin(s) to destination(s). `is_split` is True if the
  356. path diverges across multiple cables.
  357. `_nodes` retains a flattened list of all nodes within the path to enable simple filtering.
  358. """
  359. path = models.JSONField(
  360. verbose_name=_('path'),
  361. default=list
  362. )
  363. is_active = models.BooleanField(
  364. verbose_name=_('is active'),
  365. default=False
  366. )
  367. is_complete = models.BooleanField(
  368. verbose_name=_('is complete'),
  369. default=False
  370. )
  371. is_split = models.BooleanField(
  372. verbose_name=_('is split'),
  373. default=False
  374. )
  375. _nodes = PathField()
  376. _netbox_private = True
  377. class Meta:
  378. verbose_name = _('cable path')
  379. verbose_name_plural = _('cable paths')
  380. def __str__(self):
  381. return f"Path #{self.pk}: {len(self.path)} hops"
  382. def save(self, *args, **kwargs):
  383. # Save the flattened nodes list
  384. self._nodes = list(itertools.chain(*self.path))
  385. super().save(*args, **kwargs)
  386. # Record a direct reference to this CablePath on its originating object(s)
  387. origin_model = self.origin_type.model_class()
  388. origin_ids = [decompile_path_node(node)[1] for node in self.path[0]]
  389. origin_model.objects.filter(pk__in=origin_ids).update(_path=self.pk)
  390. @property
  391. def origin_type(self):
  392. if self.path:
  393. ct_id, _ = decompile_path_node(self.path[0][0])
  394. return ContentType.objects.get_for_id(ct_id)
  395. @property
  396. def destination_type(self):
  397. if self.is_complete:
  398. ct_id, _ = decompile_path_node(self.path[-1][0])
  399. return ContentType.objects.get_for_id(ct_id)
  400. @property
  401. def path_objects(self):
  402. """
  403. Cache and return the complete path as lists of objects, derived from their annotation within the path.
  404. """
  405. if not hasattr(self, '_path_objects'):
  406. self._path_objects = self._get_path()
  407. return self._path_objects
  408. @property
  409. def origins(self):
  410. """
  411. Return the list of originating objects.
  412. """
  413. return self.path_objects[0]
  414. @property
  415. def destinations(self):
  416. """
  417. Return the list of destination objects, if the path is complete.
  418. """
  419. if not self.is_complete:
  420. return []
  421. return self.path_objects[-1]
  422. @property
  423. def segment_count(self):
  424. return int(len(self.path) / 3)
  425. @classmethod
  426. def from_origin(cls, terminations):
  427. """
  428. Create a new CablePath instance as traced from the given termination objects. These can be any object to which a
  429. Cable or WirelessLink connects (interfaces, console ports, circuit termination, etc.). All terminations must be
  430. of the same type and must belong to the same parent object.
  431. """
  432. from circuits.models import CircuitTermination
  433. if not terminations:
  434. return None
  435. # Ensure all originating terminations are attached to the same link
  436. if len(terminations) > 1:
  437. assert all(t.link == terminations[0].link for t in terminations[1:])
  438. path = []
  439. position_stack = []
  440. is_complete = False
  441. is_active = True
  442. is_split = False
  443. while terminations:
  444. # Terminations must all be of the same type
  445. assert all(isinstance(t, type(terminations[0])) for t in terminations[1:])
  446. # All mid-span terminations must all be attached to the same device
  447. if not isinstance(terminations[0], PathEndpoint):
  448. assert all(isinstance(t, type(terminations[0])) for t in terminations[1:])
  449. assert all(t.parent_object == terminations[0].parent_object for t in terminations[1:])
  450. # Check for a split path (e.g. rear port fanning out to multiple front ports with
  451. # different cables attached)
  452. if len(set(t.link for t in terminations)) > 1 and (
  453. position_stack and len(terminations) != len(position_stack[-1])
  454. ):
  455. is_split = True
  456. break
  457. # Step 1: Record the near-end termination object(s)
  458. path.append([
  459. object_to_path_node(t) for t in terminations
  460. ])
  461. # Step 2: Determine the attached links (Cable or WirelessLink), if any
  462. links = [termination.link for termination in terminations if termination.link is not None]
  463. if len(links) == 0:
  464. if len(path) == 1:
  465. # If this is the start of the path and no link exists, return None
  466. return None
  467. # Otherwise, halt the trace if no link exists
  468. break
  469. assert all(type(link) in (Cable, WirelessLink) for link in links)
  470. assert all(isinstance(link, type(links[0])) for link in links)
  471. # Step 3: Record asymmetric paths as split
  472. not_connected_terminations = [termination.link for termination in terminations if termination.link is None]
  473. if len(not_connected_terminations) > 0:
  474. is_complete = False
  475. is_split = True
  476. # Step 4: Record the links, keeping cables in order to allow for SVG rendering
  477. cables = []
  478. for link in links:
  479. if object_to_path_node(link) not in cables:
  480. cables.append(object_to_path_node(link))
  481. path.append(cables)
  482. # Step 5: Update the path status if a link is not connected
  483. links_status = [link.status for link in links if link.status != LinkStatusChoices.STATUS_CONNECTED]
  484. if any([status != LinkStatusChoices.STATUS_CONNECTED for status in links_status]):
  485. is_active = False
  486. # Step 6: Determine the far-end terminations
  487. if isinstance(links[0], Cable):
  488. termination_type = ContentType.objects.get_for_model(terminations[0])
  489. local_cable_terminations = CableTermination.objects.filter(
  490. termination_type=termination_type,
  491. termination_id__in=[t.pk for t in terminations]
  492. )
  493. q_filter = Q()
  494. for lct in local_cable_terminations:
  495. cable_end = 'A' if lct.cable_end == 'B' else 'B'
  496. q_filter |= Q(cable=lct.cable, cable_end=cable_end)
  497. remote_cable_terminations = CableTermination.objects.filter(q_filter)
  498. remote_terminations = [ct.termination for ct in remote_cable_terminations]
  499. else:
  500. # WirelessLink
  501. remote_terminations = [
  502. link.interface_b if link.interface_a is terminations[0] else link.interface_a for link in links
  503. ]
  504. # Remote Terminations must all be of the same type, otherwise return a split path
  505. if not all(isinstance(t, type(remote_terminations[0])) for t in remote_terminations[1:]):
  506. is_complete = False
  507. is_split = True
  508. break
  509. # Step 7: Record the far-end termination object(s)
  510. path.append([
  511. object_to_path_node(t) for t in remote_terminations if t is not None
  512. ])
  513. # Step 8: Determine the "next hop" terminations, if applicable
  514. if not remote_terminations:
  515. break
  516. if isinstance(remote_terminations[0], FrontPort):
  517. # Follow FrontPorts to their corresponding RearPorts
  518. rear_ports = RearPort.objects.filter(
  519. pk__in=[t.rear_port_id for t in remote_terminations]
  520. )
  521. if len(rear_ports) > 1 or rear_ports[0].positions > 1:
  522. position_stack.append([fp.rear_port_position for fp in remote_terminations])
  523. terminations = rear_ports
  524. elif isinstance(remote_terminations[0], RearPort):
  525. if len(remote_terminations) == 1 and remote_terminations[0].positions == 1:
  526. front_ports = FrontPort.objects.filter(
  527. rear_port_id__in=[rp.pk for rp in remote_terminations],
  528. rear_port_position=1
  529. )
  530. # Obtain the individual front ports based on the termination and all positions
  531. elif len(remote_terminations) > 1 and position_stack:
  532. positions = position_stack.pop()
  533. # Ensure we have a number of positions equal to the amount of remote terminations
  534. assert len(remote_terminations) == len(positions)
  535. # Get our front ports
  536. q_filter = Q()
  537. for rt in remote_terminations:
  538. position = positions.pop()
  539. q_filter |= Q(rear_port_id=rt.pk, rear_port_position=position)
  540. assert q_filter is not Q()
  541. front_ports = FrontPort.objects.filter(q_filter)
  542. # Obtain the individual front ports based on the termination and position
  543. elif position_stack:
  544. front_ports = FrontPort.objects.filter(
  545. rear_port_id=remote_terminations[0].pk,
  546. rear_port_position__in=position_stack.pop()
  547. )
  548. else:
  549. # No position indicated: path has split, so we stop at the RearPorts
  550. is_split = True
  551. break
  552. terminations = front_ports
  553. elif isinstance(remote_terminations[0], CircuitTermination):
  554. # Follow a CircuitTermination to its corresponding CircuitTermination (A to Z or vice versa)
  555. if len(remote_terminations) > 1:
  556. is_split = True
  557. break
  558. circuit_termination = CircuitTermination.objects.filter(
  559. circuit=remote_terminations[0].circuit,
  560. term_side='Z' if remote_terminations[0].term_side == 'A' else 'A'
  561. ).first()
  562. if circuit_termination is None:
  563. break
  564. elif circuit_termination.provider_network:
  565. # Circuit terminates to a ProviderNetwork
  566. path.extend([
  567. [object_to_path_node(circuit_termination)],
  568. [object_to_path_node(circuit_termination.provider_network)],
  569. ])
  570. is_complete = True
  571. break
  572. elif circuit_termination.site and not circuit_termination.cable:
  573. # Circuit terminates to a Site
  574. path.extend([
  575. [object_to_path_node(circuit_termination)],
  576. [object_to_path_node(circuit_termination.site)],
  577. ])
  578. break
  579. terminations = [circuit_termination]
  580. else:
  581. # Check for non-symmetric path
  582. if all(isinstance(t, type(remote_terminations[0])) for t in remote_terminations[1:]):
  583. is_complete = True
  584. elif len(remote_terminations) == 0:
  585. is_complete = False
  586. else:
  587. # Unsupported topology, mark as split and exit
  588. is_complete = False
  589. is_split = True
  590. break
  591. return cls(
  592. path=path,
  593. is_complete=is_complete,
  594. is_active=is_active,
  595. is_split=is_split
  596. )
  597. def retrace(self):
  598. """
  599. Retrace the path from the currently-defined originating termination(s)
  600. """
  601. _new = self.from_origin(self.origins)
  602. if _new:
  603. self.path = _new.path
  604. self.is_complete = _new.is_complete
  605. self.is_active = _new.is_active
  606. self.is_split = _new.is_split
  607. self.save()
  608. else:
  609. self.delete()
  610. retrace.alters_data = True
  611. def _get_path(self):
  612. """
  613. Return the path as a list of prefetched objects.
  614. """
  615. # Compile a list of IDs to prefetch for each type of model in the path
  616. to_prefetch = defaultdict(list)
  617. for node in self._nodes:
  618. ct_id, object_id = decompile_path_node(node)
  619. to_prefetch[ct_id].append(object_id)
  620. # Prefetch path objects using one query per model type. Prefetch related devices where appropriate.
  621. prefetched = {}
  622. for ct_id, object_ids in to_prefetch.items():
  623. model_class = ContentType.objects.get_for_id(ct_id).model_class()
  624. queryset = model_class.objects.filter(pk__in=object_ids)
  625. if hasattr(model_class, 'device'):
  626. queryset = queryset.prefetch_related('device')
  627. prefetched[ct_id] = {
  628. obj.id: obj for obj in queryset
  629. }
  630. # Replicate the path using the prefetched objects.
  631. path = []
  632. for step in self.path:
  633. nodes = []
  634. for node in step:
  635. ct_id, object_id = decompile_path_node(node)
  636. try:
  637. nodes.append(prefetched[ct_id][object_id])
  638. except KeyError:
  639. # Ignore stale (deleted) object IDs
  640. pass
  641. path.append(nodes)
  642. return path
  643. def get_cable_ids(self):
  644. """
  645. Return all Cable IDs within the path.
  646. """
  647. cable_ct = ContentType.objects.get_for_model(Cable).pk
  648. cable_ids = []
  649. for node in self._nodes:
  650. ct, id = decompile_path_node(node)
  651. if ct == cable_ct:
  652. cable_ids.append(id)
  653. return cable_ids
  654. def get_total_length(self):
  655. """
  656. Return a tuple containing the sum of the length of each cable in the path
  657. and a flag indicating whether the length is definitive.
  658. """
  659. cable_ids = self.get_cable_ids()
  660. cables = Cable.objects.filter(id__in=cable_ids, _abs_length__isnull=False)
  661. total_length = cables.aggregate(total=Sum('_abs_length'))['total']
  662. is_definitive = len(cables) == len(cable_ids)
  663. return total_length, is_definitive
  664. def get_split_nodes(self):
  665. """
  666. Return all available next segments in a split cable path.
  667. """
  668. from circuits.models import CircuitTermination
  669. nodes = self.path_objects[-1]
  670. # RearPort splitting to multiple FrontPorts with no stack position
  671. if type(nodes[0]) is RearPort:
  672. return FrontPort.objects.filter(rear_port__in=nodes)
  673. # Cable terminating to multiple FrontPorts mapped to different
  674. # RearPorts connected to different cables
  675. elif type(nodes[0]) is FrontPort:
  676. return RearPort.objects.filter(pk__in=[fp.rear_port_id for fp in nodes])
  677. # Cable terminating to multiple CircuitTerminations
  678. elif type(nodes[0]) is CircuitTermination:
  679. return [
  680. ct.get_peer_termination() for ct in nodes
  681. ]
  682. def get_asymmetric_nodes(self):
  683. """
  684. Return all available next segments in a split cable path.
  685. """
  686. from circuits.models import CircuitTermination
  687. asymmetric_nodes = []
  688. for nodes in self.path_objects:
  689. if type(nodes[0]) in [RearPort, FrontPort, CircuitTermination]:
  690. asymmetric_nodes.extend([node for node in nodes if node.link is None])
  691. return asymmetric_nodes