cables.py 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398
  1. import itertools
  2. import logging
  3. import threading
  4. from collections import Counter
  5. from django.contrib.contenttypes.fields import GenericForeignKey
  6. from django.contrib.contenttypes.models import ContentType
  7. from django.contrib.postgres.fields import ArrayField
  8. from django.contrib.postgres.indexes import GinIndex
  9. from django.core.exceptions import ValidationError
  10. from django.core.validators import MaxValueValidator, MinValueValidator
  11. from django.db import models, router, transaction
  12. from django.dispatch import Signal
  13. from django.urls import reverse
  14. from django.utils.translation import gettext_lazy as _
  15. from core.models import ObjectType
  16. from dcim.choices import *
  17. from dcim.constants import *
  18. from dcim.exceptions import UnsupportedCablePath
  19. from dcim.fields import PathField
  20. from dcim.utils import decompile_path_node, object_to_path_node, rebuild_cable_paths
  21. from netbox.choices import ColorChoices
  22. from netbox.models import ChangeLoggedModel, PrimaryModel
  23. from utilities.conversion import to_meters
  24. from utilities.data import normalize_update_fields
  25. from utilities.exceptions import AbortRequest
  26. from utilities.fields import ColorField, GenericArrayForeignKey
  27. from utilities.querysets import RestrictedQuerySet, chunked_update
  28. from utilities.serialization import deserialize_object, serialize_object
  29. from wireless.models import WirelessLink
  30. from .device_components import FrontPort, Interface, PathEndpoint, PortMapping, RearPort
  31. __all__ = (
  32. 'Cable',
  33. 'CableBundle',
  34. 'CablePath',
  35. 'CableTermination',
  36. )
  37. logger = logging.getLogger(f'netbox.{__name__}')
  38. trace_paths = Signal()
  39. #
  40. # Cable bundles
  41. #
  42. class CableBundle(PrimaryModel):
  43. """
  44. A logical grouping of individual cables.
  45. """
  46. name = models.CharField(
  47. verbose_name=_('name'),
  48. max_length=100,
  49. unique=True,
  50. )
  51. class Meta:
  52. ordering = ('name',)
  53. verbose_name = _('cable bundle')
  54. verbose_name_plural = _('cable bundles')
  55. def __str__(self):
  56. return self.name
  57. def get_absolute_url(self):
  58. return reverse('dcim:cablebundle', args=[self.pk])
  59. #
  60. # Cables
  61. #
  62. class CableQuerySet(RestrictedQuerySet):
  63. def delete(self):
  64. # Track these Cables as being deleted for the duration, as Cable.delete() does for a single
  65. # instance: a queryset delete never calls it. Between them the two cover every deletion, as a
  66. # Cable is never itself cascade-deleted (nothing points at it with on_delete=CASCADE).
  67. # Resolve the PKs on the DB the delete will use, so read routing can't miss a lagging replica.
  68. using = self._db or router.db_for_write(self.model, **self._hints)
  69. pks = list(self.using(using).values_list('pk', flat=True))
  70. for pk in pks:
  71. Cable._track_deletion(pk)
  72. try:
  73. return super().delete()
  74. finally:
  75. for pk in pks:
  76. Cable._untrack_deletion(pk)
  77. class Cable(PrimaryModel):
  78. """
  79. A physical connection between two endpoints.
  80. """
  81. # Per-thread tracking of Cable PKs currently being deleted; referenced by
  82. # dcim.signals.nullify_connected_endpoints to record the disconnect on each terminating object and
  83. # to skip per-CableTermination path retracing during the cascade (retrace_cable_paths does it once).
  84. _deletion_tracking = threading.local()
  85. type = models.CharField(
  86. verbose_name=_('type'),
  87. max_length=50,
  88. choices=CableTypeChoices,
  89. blank=True,
  90. null=True
  91. )
  92. status = models.CharField(
  93. verbose_name=_('status'),
  94. max_length=50,
  95. choices=LinkStatusChoices,
  96. default=LinkStatusChoices.STATUS_CONNECTED
  97. )
  98. profile = models.CharField(
  99. verbose_name=_('profile'),
  100. max_length=50,
  101. choices=CableProfileChoices,
  102. blank=True,
  103. )
  104. tenant = models.ForeignKey(
  105. to='tenancy.Tenant',
  106. on_delete=models.PROTECT,
  107. related_name='cables',
  108. blank=True,
  109. null=True
  110. )
  111. label = models.CharField(
  112. verbose_name=_('label'),
  113. max_length=100,
  114. blank=True
  115. )
  116. color = ColorField(
  117. verbose_name=_('color'),
  118. blank=True
  119. )
  120. length = models.DecimalField(
  121. verbose_name=_('length'),
  122. max_digits=8,
  123. decimal_places=2,
  124. blank=True,
  125. null=True
  126. )
  127. length_unit = models.CharField(
  128. verbose_name=_('length unit'),
  129. max_length=50,
  130. choices=CableLengthUnitChoices,
  131. blank=True,
  132. null=True
  133. )
  134. # Stores the normalized length (in meters) for database ordering
  135. _abs_length = models.DecimalField(
  136. max_digits=14,
  137. decimal_places=4,
  138. blank=True,
  139. null=True
  140. )
  141. bundle = models.ForeignKey(
  142. to='dcim.CableBundle',
  143. on_delete=models.SET_NULL,
  144. related_name='cables',
  145. blank=True,
  146. null=True,
  147. verbose_name=_('bundle'),
  148. )
  149. clone_fields = ('tenant', 'type', 'profile', 'bundle')
  150. objects = CableQuerySet.as_manager()
  151. class Meta:
  152. ordering = ('pk',)
  153. verbose_name = _('cable')
  154. verbose_name_plural = _('cables')
  155. def __init__(self, *args, a_terminations=None, b_terminations=None, **kwargs):
  156. super().__init__(*args, **kwargs)
  157. # A copy of the PK to be used by __str__ in case the object is deleted
  158. self._pk = self.__dict__.get('id')
  159. # Cache the original profile & status so we can check later whether either has been changed
  160. self._orig_status = self.__dict__.get('status')
  161. self._orig_profile = self.__dict__.get('profile')
  162. self._terminations_modified = False
  163. # Assign or retrieve A/B terminations
  164. if a_terminations:
  165. self.a_terminations = a_terminations
  166. if b_terminations:
  167. self.b_terminations = b_terminations
  168. def __str__(self):
  169. pk = self.pk or self._pk
  170. return self.label or f'#{pk}'
  171. def get_status_color(self):
  172. return LinkStatusChoices.colors.get(self.status)
  173. @property
  174. def profile_class(self):
  175. from dcim import cable_profiles
  176. return {
  177. CableProfileChoices.SINGLE_1C1P: cable_profiles.Single1C1PCableProfile,
  178. CableProfileChoices.SINGLE_1C2P: cable_profiles.Single1C2PCableProfile,
  179. CableProfileChoices.SINGLE_1C4P: cable_profiles.Single1C4PCableProfile,
  180. CableProfileChoices.SINGLE_1C6P: cable_profiles.Single1C6PCableProfile,
  181. CableProfileChoices.SINGLE_1C8P: cable_profiles.Single1C8PCableProfile,
  182. CableProfileChoices.SINGLE_1C12P: cable_profiles.Single1C12PCableProfile,
  183. CableProfileChoices.SINGLE_1C16P: cable_profiles.Single1C16PCableProfile,
  184. CableProfileChoices.TRUNK_2C1P: cable_profiles.Trunk2C1PCableProfile,
  185. CableProfileChoices.TRUNK_2C2P: cable_profiles.Trunk2C2PCableProfile,
  186. CableProfileChoices.TRUNK_2C4P: cable_profiles.Trunk2C4PCableProfile,
  187. CableProfileChoices.TRUNK_2C4P_SHUFFLE: cable_profiles.Trunk2C4PShuffleCableProfile,
  188. CableProfileChoices.TRUNK_2C6P: cable_profiles.Trunk2C6PCableProfile,
  189. CableProfileChoices.TRUNK_2C8P: cable_profiles.Trunk2C8PCableProfile,
  190. CableProfileChoices.TRUNK_2C12P: cable_profiles.Trunk2C12PCableProfile,
  191. CableProfileChoices.TRUNK_4C1P: cable_profiles.Trunk4C1PCableProfile,
  192. CableProfileChoices.TRUNK_4C2P: cable_profiles.Trunk4C2PCableProfile,
  193. CableProfileChoices.TRUNK_4C4P: cable_profiles.Trunk4C4PCableProfile,
  194. CableProfileChoices.TRUNK_4C4P_SHUFFLE: cable_profiles.Trunk4C4PShuffleCableProfile,
  195. CableProfileChoices.TRUNK_4C6P: cable_profiles.Trunk4C6PCableProfile,
  196. CableProfileChoices.TRUNK_4C8P: cable_profiles.Trunk4C8PCableProfile,
  197. CableProfileChoices.TRUNK_8C4P: cable_profiles.Trunk8C4PCableProfile,
  198. CableProfileChoices.BREAKOUT_1C2P_2C1P: cable_profiles.Breakout1C2Px2C1PCableProfile,
  199. CableProfileChoices.BREAKOUT_1C4P_4C1P: cable_profiles.Breakout1C4Px4C1PCableProfile,
  200. CableProfileChoices.BREAKOUT_1C6P_6C1P: cable_profiles.Breakout1C6Px6C1PCableProfile,
  201. CableProfileChoices.BREAKOUT_1C8P_8C1P: cable_profiles.Breakout1C8Px8C1PCableProfile,
  202. CableProfileChoices.BREAKOUT_2C4P_8C1P_SHUFFLE: cable_profiles.Breakout2C4Px8C1PShuffleCableProfile,
  203. }.get(self.profile)
  204. def _get_x_terminations(self, side):
  205. """
  206. Return the terminating objects for the given cable end (A or B).
  207. """
  208. if side not in (CableEndChoices.SIDE_A, CableEndChoices.SIDE_B):
  209. raise ValueError(f"Unknown cable side: {side}")
  210. attr = f'_{side.lower()}_terminations'
  211. if hasattr(self, attr):
  212. return getattr(self, attr)
  213. if not self.pk:
  214. return []
  215. return [
  216. # Query self.terminations.all() to leverage cached results
  217. ct.termination for ct in self.terminations.all() if ct.cable_end == side
  218. ]
  219. def _set_x_terminations(self, side, value):
  220. """
  221. Set the terminating objects for the given cable end (A or B).
  222. """
  223. if side not in (CableEndChoices.SIDE_A, CableEndChoices.SIDE_B):
  224. raise ValueError(f"Unknown cable side: {side}")
  225. _attr = f'_{side.lower()}_terminations'
  226. # If the provided value is a list of CableTermination IDs, resolve them
  227. # to their corresponding termination objects.
  228. if all(isinstance(item, int) for item in value):
  229. value = [
  230. ct.termination for ct in CableTermination.objects.filter(pk__in=value).prefetch_related('termination')
  231. ]
  232. if not self.pk or getattr(self, _attr, []) != list(value):
  233. self._terminations_modified = True
  234. setattr(self, _attr, value)
  235. @property
  236. def a_terminations(self):
  237. return self._get_x_terminations(CableEndChoices.SIDE_A)
  238. @a_terminations.setter
  239. def a_terminations(self, value):
  240. self._set_x_terminations(CableEndChoices.SIDE_A, value)
  241. @property
  242. def b_terminations(self):
  243. return self._get_x_terminations(CableEndChoices.SIDE_B)
  244. @b_terminations.setter
  245. def b_terminations(self, value):
  246. self._set_x_terminations(CableEndChoices.SIDE_B, value)
  247. @property
  248. def color_name(self):
  249. color_name = ""
  250. for hex_code, label in ColorChoices.CHOICES:
  251. if hex_code.lower() == self.color.lower():
  252. color_name = str(label)
  253. return color_name
  254. def clean(self):
  255. super().clean()
  256. # Validate length and length_unit
  257. if self.length is not None and not self.length_unit:
  258. raise ValidationError(_("Must specify a unit when setting a cable length"))
  259. if self._state.adding and self.pk is None and (not self.a_terminations or not self.b_terminations):
  260. raise ValidationError(_("Must define A and B terminations when creating a new cable."))
  261. # Validate terminations against the assigned cable profile (if any)
  262. if self.profile:
  263. self.profile_class().clean(self)
  264. if self._terminations_modified:
  265. # Check that all termination objects for either end are of the same type
  266. for terms in (self.a_terminations, self.b_terminations):
  267. if len(terms) > 1 and not all(isinstance(t, type(terms[0])) for t in terms[1:]):
  268. raise ValidationError(_("Cannot connect different termination types to same end of cable."))
  269. # Check that termination types are compatible
  270. if self.a_terminations and self.b_terminations:
  271. a_type = self.a_terminations[0]._meta.model_name
  272. b_type = self.b_terminations[0]._meta.model_name
  273. if b_type not in COMPATIBLE_TERMINATION_TYPES.get(a_type):
  274. raise ValidationError(
  275. _("Incompatible termination types: {type_a} and {type_b}").format(type_a=a_type, type_b=b_type)
  276. )
  277. if a_type == b_type:
  278. # can't directly use self.a_terminations here as possible they
  279. # don't have pk yet
  280. a_pks = set(obj.pk for obj in self.a_terminations if obj.pk)
  281. b_pks = set(obj.pk for obj in self.b_terminations if obj.pk)
  282. if (a_pks & b_pks):
  283. raise ValidationError(
  284. _("A and B terminations cannot connect to the same object.")
  285. )
  286. # Run clean() on any new CableTerminations
  287. for termination in self.a_terminations:
  288. CableTermination(cable=self, cable_end='A', termination=termination).clean()
  289. for termination in self.b_terminations:
  290. CableTermination(cable=self, cable_end='B', termination=termination).clean()
  291. def save(self, *args, force_insert=False, force_update=False, using=None, update_fields=None):
  292. _created = self.pk is None
  293. save_kwargs = {
  294. 'using': using,
  295. 'update_fields': update_fields,
  296. }
  297. update_fields = normalize_update_fields(save_kwargs)
  298. length_written = update_fields is None or 'length' in update_fields
  299. length_unit_written = update_fields is None or 'length_unit' in update_fields
  300. if length_written or length_unit_written:
  301. if length_written and length_unit_written:
  302. stored = {}
  303. else:
  304. # Read from the database this save will write, so a router cannot split the two
  305. db = using or router.db_for_write(Cable, instance=self)
  306. stored = Cable.objects.using(db).filter(pk=self.pk).values('length', 'length_unit').first() or {}
  307. length = self.length if length_written else stored.get('length')
  308. length_unit = self.length_unit if length_unit_written else stored.get('length_unit')
  309. # Clear length_unit if no length is defined
  310. if length is None and length_unit_written:
  311. self.length_unit = None
  312. # Store the given length (if any) in meters for use in database ordering
  313. if length is not None and length_unit:
  314. self._abs_length = to_meters(length, length_unit)
  315. else:
  316. self._abs_length = None
  317. # _abs_length is a denormalized cache of length and length_unit, so persist them together
  318. if update_fields is not None:
  319. save_kwargs['update_fields'] = update_fields | {'_abs_length'}
  320. # A field counts as changed only when this save actually writes it
  321. status_written = update_fields is None or 'status' in update_fields
  322. profile_written = update_fields is None or 'profile' in update_fields
  323. # If this is a new Cable, save it before attempting to create its CableTerminations
  324. if self._state.adding:
  325. super().save(*args, force_insert=True, **save_kwargs)
  326. # Update the private PK used in __str__()
  327. self._pk = self.pk
  328. if profile_written and self._orig_profile != self.profile:
  329. self.update_terminations(force=True)
  330. elif self._terminations_modified:
  331. self.update_terminations()
  332. super().save(*args, force_update=True, **save_kwargs)
  333. try:
  334. trace_paths.send(Cable, instance=self, created=_created)
  335. except UnsupportedCablePath as e:
  336. raise AbortRequest(e)
  337. # Reset change tracking for the next save of this instance
  338. if status_written:
  339. self._orig_status = self.status
  340. if profile_written:
  341. self._orig_profile = self.profile
  342. self._terminations_modified = False
  343. def delete(self, *args, **kwargs):
  344. # Cache the PK locally because super().delete() clears self.pk before the finally block runs; the
  345. # finally also guarantees the PK is discarded if the delete raises. CableQuerySet.delete() tracks
  346. # the same way for a queryset delete, which never calls this.
  347. pk = self.pk
  348. Cable._track_deletion(pk)
  349. try:
  350. return super().delete(*args, **kwargs)
  351. finally:
  352. Cable._untrack_deletion(pk)
  353. @classmethod
  354. def _track_deletion(cls, pk):
  355. """
  356. Track a Cable as being deleted, so that the post_delete handler for its cascaded CableTerminations can
  357. record the disconnect on each terminating object and skip redundant path retracing (retrace_cable_paths()
  358. retraces each affected path once, after the Cable itself is deleted). The tracking set lives on a
  359. threading.local() to isolate concurrent deletions across threads.
  360. """
  361. if not hasattr(cls._deletion_tracking, 'pks'):
  362. cls._deletion_tracking.pks = set()
  363. cls._deletion_tracking.pks.add(pk)
  364. @classmethod
  365. def _untrack_deletion(cls, pk):
  366. if hasattr(cls._deletion_tracking, 'pks'):
  367. cls._deletion_tracking.pks.discard(pk)
  368. @classmethod
  369. def _is_being_deleted(cls, pk):
  370. return pk in getattr(cls._deletion_tracking, 'pks', ())
  371. def clone(self):
  372. """
  373. Return attributes suitable for cloning this cable.
  374. In addition to the fields defined in `clone_fields`, include the termination
  375. type and parent selector fields used by dcim.forms.connections.get_cable_form().
  376. """
  377. attrs = super().clone()
  378. # Mirror dcim.forms.connections.get_cable_form() parent-field logic
  379. for cable_end, terminations in (('a', self.a_terminations), ('b', self.b_terminations)):
  380. if not terminations:
  381. continue
  382. term_cls = type(terminations[0])
  383. term_label = term_cls._meta.label_lower
  384. # Matches CableForm choices: "<app_label>.<model>"
  385. attrs[f'{cable_end}_terminations_type'] = term_label
  386. # Device component
  387. if hasattr(term_cls, 'device'):
  388. device_ids = sorted({t.device_id for t in terminations if t.device_id})
  389. if device_ids:
  390. attrs[f'termination_{cable_end}_device'] = device_ids
  391. # PowerFeed
  392. elif term_label == 'dcim.powerfeed':
  393. powerpanel_ids = sorted({t.power_panel_id for t in terminations if t.power_panel_id})
  394. if powerpanel_ids:
  395. attrs[f'termination_{cable_end}_powerpanel'] = powerpanel_ids
  396. # CircuitTermination
  397. elif term_label == 'circuits.circuittermination':
  398. circuit_ids = sorted({t.circuit_id for t in terminations if t.circuit_id})
  399. if circuit_ids:
  400. attrs[f'termination_{cable_end}_circuit'] = circuit_ids
  401. # Never clone the actual terminations, as they are already occupied
  402. attrs.pop('a_terminations', None)
  403. attrs.pop('b_terminations', None)
  404. return attrs
  405. def serialize_object(self, exclude=None):
  406. data = serialize_object(self, exclude=exclude or [])
  407. # Add A & B terminations to the serialized data
  408. a_terminations, b_terminations = self.get_terminations()
  409. data['a_terminations'] = sorted([ct.pk for ct in a_terminations.values()])
  410. data['b_terminations'] = sorted([ct.pk for ct in b_terminations.values()])
  411. return data
  412. @classmethod
  413. def deserialize_object(cls, data, pk=None):
  414. a_terminations = data.pop('a_terminations', [])
  415. b_terminations = data.pop('b_terminations', [])
  416. instance = deserialize_object(cls, data, pk=pk)
  417. # Assign A & B termination objects to the Cable instance
  418. queryset = CableTermination.objects.prefetch_related('termination')
  419. instance.a_terminations = [
  420. ct.termination for ct in queryset.filter(pk__in=a_terminations)
  421. ]
  422. instance.b_terminations = [
  423. ct.termination for ct in queryset.filter(pk__in=b_terminations)
  424. ]
  425. return instance
  426. def update_dependent_objects(self):
  427. """
  428. Recreate the CablePaths traversing this Cable from its current terminations.
  429. """
  430. with transaction.atomic(using=router.db_for_write(CablePath)):
  431. # Restore channel cable attributes omitted by bulk-update change logging.
  432. for ct in CableTermination.objects.filter(cable=self).prefetch_related('termination'):
  433. if isinstance(ct.termination, Interface) and ct.termination.channels:
  434. ct.termination.propagate_channel_cables()
  435. rebuild_cable_paths(self)
  436. update_dependent_objects.alters_data = True
  437. def get_terminations(self):
  438. """
  439. Return two dictionaries mapping A & B side terminating objects to their corresponding CableTerminations
  440. for this Cable.
  441. """
  442. a_terminations = {}
  443. b_terminations = {}
  444. for ct in CableTermination.objects.filter(cable=self).prefetch_related('termination'):
  445. if ct.cable_end == CableEndChoices.SIDE_A:
  446. a_terminations[ct.termination] = ct
  447. else:
  448. b_terminations[ct.termination] = ct
  449. return a_terminations, b_terminations
  450. def _connectors_reassigned(self, existing, terminations):
  451. """
  452. Return True if any of the given terminating objects already terminates this Cable, but would be
  453. assigned to a different connector than the one it currently occupies.
  454. Args:
  455. existing: Mapping of terminating objects to their current CableTerminations, as returned by
  456. get_terminations()
  457. terminations: The ordered list of terminating objects to be assigned to this end of the Cable
  458. """
  459. if not self.profile:
  460. # Connectors are assigned only for a Cable which has a profile
  461. return False
  462. for connector, termination in enumerate(terminations, start=1):
  463. if (ct := existing.get(termination)) and ct.connector != connector:
  464. return True
  465. return False
  466. def update_terminations(self, force=False):
  467. """
  468. Create/delete CableTerminations for this Cable to reflect its current state.
  469. Args:
  470. force: Force the recreation of all CableTerminations, even if no changes have been made. Needed e.g. when
  471. altering a Cable's assigned profile.
  472. """
  473. a_terminations, b_terminations = self.get_terminations()
  474. # A CableTermination's connector is derived from its position within its end's list of terminating
  475. # objects, so reordering that list (or removing an object from the middle of it) rewires the Cable
  476. # without changing which objects it connects. Recreate the affected end's CableTerminations so that
  477. # each is reassigned to its new connector.
  478. force_a = force or self._connectors_reassigned(a_terminations, self.a_terminations)
  479. force_b = force or self._connectors_reassigned(b_terminations, self.b_terminations)
  480. # When force-recreating terminations (e.g. after a profile change), cache the termination objects
  481. # from the database before deleting, so they are available for recreation. Without this, the
  482. # a_terminations/b_terminations properties would query the DB after deletion and return empty lists.
  483. if force_a and not hasattr(self, '_a_terminations'):
  484. self._a_terminations = list(a_terminations.keys())
  485. if force_b and not hasattr(self, '_b_terminations'):
  486. self._b_terminations = list(b_terminations.keys())
  487. # Recreating terminations invalidates existing paths, even when the endpoints are unchanged
  488. self._terminations_modified = True
  489. # Delete any stale CableTerminations
  490. for termination, ct in a_terminations.items():
  491. if force_a or (termination.pk and termination not in self.a_terminations):
  492. ct.delete()
  493. for termination, ct in b_terminations.items():
  494. if force_b or (termination.pk and termination not in self.b_terminations):
  495. ct.delete()
  496. # Save any new CableTerminations
  497. profile = self.profile_class() if self.profile else None
  498. for i, termination in enumerate(self.a_terminations, start=1):
  499. if force_a or not termination.pk or termination not in a_terminations:
  500. connector = positions = None
  501. if profile:
  502. connector = i
  503. positions = profile.get_position_list(profile.a_connectors[i])
  504. CableTermination(
  505. cable=self,
  506. cable_end=CableEndChoices.SIDE_A,
  507. connector=connector,
  508. positions=positions,
  509. termination=termination
  510. ).save()
  511. for i, termination in enumerate(self.b_terminations, start=1):
  512. if force_b or not termination.pk or termination not in b_terminations:
  513. connector = positions = None
  514. if profile:
  515. connector = i
  516. positions = profile.get_position_list(profile.b_connectors[i])
  517. CableTermination(
  518. cable=self,
  519. cable_end=CableEndChoices.SIDE_B,
  520. connector=connector,
  521. positions=positions,
  522. termination=termination
  523. ).save()
  524. class CableTermination(ChangeLoggedModel):
  525. """
  526. A mapping between side A or B of a Cable and a terminating object (e.g. an Interface or CircuitTermination).
  527. """
  528. cable = models.ForeignKey(
  529. to='dcim.Cable',
  530. on_delete=models.CASCADE,
  531. related_name='terminations'
  532. )
  533. cable_end = models.CharField(
  534. max_length=1,
  535. choices=CableEndChoices,
  536. verbose_name=_('end')
  537. )
  538. termination_type = models.ForeignKey(
  539. to='contenttypes.ContentType',
  540. on_delete=models.PROTECT,
  541. related_name='+'
  542. )
  543. termination_id = models.PositiveBigIntegerField()
  544. termination = GenericForeignKey(
  545. ct_field='termination_type',
  546. fk_field='termination_id'
  547. )
  548. connector = models.PositiveSmallIntegerField(
  549. blank=True,
  550. null=True,
  551. validators=(
  552. MinValueValidator(CABLE_CONNECTOR_MIN),
  553. MaxValueValidator(CABLE_CONNECTOR_MAX)
  554. ),
  555. )
  556. positions = ArrayField(
  557. base_field=models.PositiveSmallIntegerField(
  558. validators=(
  559. MinValueValidator(CABLE_POSITION_MIN),
  560. MaxValueValidator(CABLE_POSITION_MAX)
  561. )
  562. ),
  563. blank=True,
  564. null=True,
  565. )
  566. # Cached associations to enable efficient filtering
  567. _device = models.ForeignKey(
  568. to='dcim.Device',
  569. on_delete=models.CASCADE,
  570. blank=True,
  571. null=True
  572. )
  573. _rack = models.ForeignKey(
  574. to='dcim.Rack',
  575. on_delete=models.CASCADE,
  576. blank=True,
  577. null=True
  578. )
  579. _location = models.ForeignKey(
  580. to='dcim.Location',
  581. on_delete=models.CASCADE,
  582. blank=True,
  583. null=True
  584. )
  585. _site = models.ForeignKey(
  586. to='dcim.Site',
  587. on_delete=models.CASCADE,
  588. blank=True,
  589. null=True
  590. )
  591. objects = RestrictedQuerySet.as_manager()
  592. class Meta:
  593. ordering = ('cable', 'cable_end', 'connector', 'pk')
  594. constraints = (
  595. models.UniqueConstraint(
  596. fields=('termination_type', 'termination_id'),
  597. name='%(app_label)s_%(class)s_unique_termination'
  598. ),
  599. models.UniqueConstraint(
  600. fields=('cable', 'cable_end', 'connector'),
  601. name='%(app_label)s_%(class)s_unique_connector'
  602. ),
  603. )
  604. verbose_name = _('cable termination')
  605. verbose_name_plural = _('cable terminations')
  606. def __str__(self):
  607. return f'Cable {self.cable} to {self.termination}'
  608. def clean(self):
  609. super().clean()
  610. # Disallow connecting a cable to any termination object that is
  611. # explicitly flagged as "mark connected".
  612. termination = getattr(self, 'termination', None)
  613. if termination is not None and getattr(termination, "mark_connected", False):
  614. raise ValidationError(
  615. _("Cannot connect a cable to {obj_parent} > {obj} because it is marked as connected.").format(
  616. obj_parent=termination.parent_object,
  617. obj=termination,
  618. )
  619. )
  620. # Check for existing termination
  621. qs = CableTermination.objects.filter(
  622. termination_type=self.termination_type,
  623. termination_id=self.termination_id
  624. )
  625. if self.cable.pk:
  626. qs = qs.exclude(cable=self.cable)
  627. existing_termination = qs.first()
  628. if existing_termination is not None:
  629. raise ValidationError(
  630. _("Duplicate termination found for {app_label}.{model} {termination_id}: cable {cable_pk}").format(
  631. app_label=self.termination_type.app_label,
  632. model=self.termination_type.model,
  633. termination_id=self.termination_id,
  634. cable_pk=existing_termination.cable.pk
  635. )
  636. )
  637. # A channel subinterface derives its cable from its parent interface and cannot be cabled directly. Checked
  638. # ahead of the generic type validation below (channel is a nonconnectable type) to surface the more specific
  639. # guidance.
  640. if self.termination_type.model == 'interface' and self.termination.channel_id:
  641. raise ValidationError(
  642. _("Cables cannot be terminated directly to a channel subinterface; cable the parent interface instead.")
  643. )
  644. # Validate the interface type (if applicable)
  645. if self.termination_type.model == 'interface' and self.termination.type in NONCONNECTABLE_IFACE_TYPES:
  646. raise ValidationError(
  647. _("Cables cannot be terminated to {type_display} interfaces").format(
  648. type_display=self.termination.get_type_display()
  649. )
  650. )
  651. # A CircuitTermination attached to a ProviderNetwork cannot have a Cable
  652. if self.termination_type.model == 'circuittermination' and self.termination._provider_network is not None:
  653. raise ValidationError(_("Circuit terminations attached to a provider network may not be cabled."))
  654. def save(self, *args, **kwargs):
  655. # Cache objects associated with the terminating object (for filtering)
  656. self.cache_related_objects()
  657. super().save(*args, **kwargs)
  658. # Set the cable on the terminating object
  659. termination = self.termination._meta.model.objects.get(pk=self.termination_id)
  660. termination.snapshot()
  661. termination.set_cable_termination(self)
  662. termination.save()
  663. def delete(self, *args, **kwargs):
  664. # Delete the cable association on the terminating object
  665. termination = self.termination._meta.model.objects.get(pk=self.termination_id)
  666. termination.snapshot()
  667. termination.clear_cable_termination(self)
  668. termination.save()
  669. super().delete(*args, **kwargs)
  670. def cache_related_objects(self):
  671. """
  672. Cache objects related to the termination (e.g. device, rack, site) directly on the object to
  673. enable efficient filtering.
  674. """
  675. if self.termination is None:
  676. raise ValueError(
  677. _("Invalid cable termination: the assigned termination object does not exist.")
  678. )
  679. # Device components
  680. if getattr(self.termination, 'device', None):
  681. self._device = self.termination.device
  682. self._rack = self.termination.device.rack
  683. self._location = self.termination.device.location
  684. self._site = self.termination.device.site
  685. # Power feeds
  686. elif getattr(self.termination, 'rack', None):
  687. self._rack = self.termination.rack
  688. self._location = self.termination.rack.location
  689. self._site = self.termination.rack.site
  690. # Circuit terminations (which cache their own site/location)
  691. elif self.termination._meta.label_lower == 'circuits.circuittermination':
  692. self._site = self.termination._site
  693. self._location = self.termination._location
  694. cache_related_objects.alters_data = True
  695. def to_objectchange(self, action):
  696. objectchange = super().to_objectchange(action)
  697. objectchange.related_object = self.termination
  698. return objectchange
  699. class CablePath(models.Model):
  700. """
  701. A CablePath instance represents the physical path from a set of origin nodes to a set of destination nodes,
  702. including all intermediate elements.
  703. `path` contains the ordered set of nodes, arranged in lists of (type, ID) tuples. (Each cable in the path can
  704. terminate to one or more objects.) For example, consider the following
  705. topology:
  706. A B C
  707. Interface 1 --- Front Port 1 | Rear Port 1 --- Rear Port 2 | Front Port 3 --- Interface 2
  708. Front Port 2 Front Port 4
  709. This path would be expressed as:
  710. CablePath(
  711. path = [
  712. [Interface 1],
  713. [Cable A],
  714. [Front Port 1, Front Port 2],
  715. [Rear Port 1],
  716. [Cable B],
  717. [Rear Port 2],
  718. [Front Port 3, Front Port 4],
  719. [Cable C],
  720. [Interface 2],
  721. ]
  722. )
  723. `is_active` is set to True only if every Cable within the path has a status of "connected". `is_complete` is True
  724. if the instance represents a complete end-to-end path from origin(s) to destination(s). `is_split` is True if the
  725. path diverges across multiple cables.
  726. `_nodes` retains a flattened list of all nodes within the path to enable simple filtering.
  727. """
  728. path = models.JSONField(
  729. verbose_name=_('path'),
  730. default=list
  731. )
  732. is_active = models.BooleanField(
  733. verbose_name=_('is active'),
  734. default=False
  735. )
  736. is_complete = models.BooleanField(
  737. verbose_name=_('is complete'),
  738. default=False
  739. )
  740. is_split = models.BooleanField(
  741. verbose_name=_('is split'),
  742. default=False
  743. )
  744. _nodes = PathField()
  745. _netbox_private = True
  746. class Meta:
  747. indexes = (
  748. # GIN index supports @> operator used by `_nodes__contains` lookups,
  749. # which fire on every cable/termination delete and path retrace.
  750. GinIndex(fields=('_nodes',)),
  751. )
  752. verbose_name = _('cable path')
  753. verbose_name_plural = _('cable paths')
  754. def __str__(self):
  755. return f"Path #{self.pk}: {len(self.path)} hops"
  756. def save(self, *args, **kwargs):
  757. # Save the flattened nodes list
  758. self._nodes = list(itertools.chain(*self.path))
  759. super().save(*args, **kwargs)
  760. # Record a direct reference to this CablePath on its originating object(s). Only PathEndpoint
  761. # subclasses carry the denormalized `_path` back-reference; other valid origins (e.g.
  762. # CircuitTermination) do not, so skip the update for them.
  763. origin_model = self.origin_type.model_class()
  764. if issubclass(origin_model, PathEndpoint):
  765. origin_ids = [decompile_path_node(node)[1] for node in self.path[0]]
  766. chunked_update(origin_model.objects.filter(pk__in=origin_ids), _path=self.pk)
  767. def delete(self, *args, **kwargs):
  768. # Mirror save() - clear _path on origins to prevent stale references
  769. # in table views that render _path.destinations. Only PathEndpoint subclasses carry `_path`.
  770. if self.path:
  771. origin_model = self.origin_type.model_class()
  772. if issubclass(origin_model, PathEndpoint):
  773. origin_ids = [decompile_path_node(node)[1] for node in self.path[0]]
  774. chunked_update(origin_model.objects.filter(pk__in=origin_ids, _path=self.pk), _path=None)
  775. super().delete(*args, **kwargs)
  776. @property
  777. def origin_type(self):
  778. if self.path:
  779. ct_id, _ = decompile_path_node(self.path[0][0])
  780. return ContentType.objects.get_for_id(ct_id)
  781. return None
  782. @property
  783. def destination_type(self):
  784. if self.is_complete:
  785. ct_id, _ = decompile_path_node(self.path[-1][0])
  786. return ContentType.objects.get_for_id(ct_id)
  787. return None
  788. @property
  789. def _path_decompiled(self):
  790. res = []
  791. for step in self.path:
  792. nodes = []
  793. for node in step:
  794. nodes.append(decompile_path_node(node))
  795. res.append(nodes)
  796. return res
  797. path_objects = GenericArrayForeignKey("_path_decompiled")
  798. @property
  799. def origins(self):
  800. """
  801. Return the list of originating objects.
  802. """
  803. return self.path_objects[0]
  804. @property
  805. def destinations(self):
  806. """
  807. Return the list of destination objects, if the path is complete.
  808. """
  809. if not self.is_complete:
  810. return []
  811. return self.path_objects[-1]
  812. @property
  813. def segment_count(self):
  814. return int(len(self.path) / 3)
  815. @classmethod
  816. def from_origin(cls, terminations):
  817. """
  818. Create a new CablePath instance as traced from the given termination objects. These can be any object to which a
  819. Cable or WirelessLink connects (interfaces, console ports, circuit termination, etc.). All terminations must be
  820. of the same type and must belong to the same parent object.
  821. """
  822. from circuits.models import Circuit, CircuitTermination
  823. if not terminations:
  824. return None
  825. # Ensure all originating terminations are attached to the same link
  826. if len(terminations) > 1 and not all(t.link == terminations[0].link for t in terminations[1:]):
  827. raise UnsupportedCablePath(_("All originating terminations must be attached to the same link"))
  828. path = []
  829. position_stack = []
  830. is_complete = False
  831. is_active = True
  832. is_split = False
  833. logger.debug(f'Tracing cable path from {terminations}...')
  834. segment = 0
  835. while terminations:
  836. segment += 1
  837. logger.debug(f'[Path segment #{segment}] Position stack: {position_stack}')
  838. logger.debug(f'[Path segment #{segment}] Local terminations: {terminations}')
  839. # Terminations must all be of the same type
  840. if not all(isinstance(t, type(terminations[0])) for t in terminations[1:]):
  841. raise UnsupportedCablePath(_("All mid-span terminations must have the same termination type"))
  842. # All mid-span terminations must all be attached to the same device
  843. if (
  844. not isinstance(terminations[0], PathEndpoint) and
  845. not isinstance(terminations[0].parent_object, Circuit) and
  846. not all(t.parent_object == terminations[0].parent_object for t in terminations[1:])
  847. ):
  848. raise UnsupportedCablePath(_("All mid-span terminations must have the same parent object"))
  849. # Check for a split path (e.g. rear port fanning out to multiple front ports with
  850. # different cables attached)
  851. if len(set(t.link for t in terminations)) > 1 and (
  852. position_stack and len(terminations) != len(position_stack[-1])
  853. ):
  854. is_split = True
  855. break
  856. # Step 1: Record the near-end termination object(s)
  857. path.append([
  858. object_to_path_node(t) for t in terminations
  859. ])
  860. # If not null, push cable positions onto the stack
  861. if isinstance(terminations[0], PathEndpoint) and terminations[0].cable_positions:
  862. position_stack.append(list(terminations[0].cable_positions))
  863. # Step 2: Determine the attached links (Cable or WirelessLink), if any
  864. links = list(dict.fromkeys(
  865. termination.link for termination in terminations if termination.link is not None
  866. ))
  867. logger.debug(f'[Path segment #{segment}] Links: {links}')
  868. if len(links) == 0:
  869. if len(path) == 1:
  870. # If this is the start of the path and no link exists, return None
  871. return None
  872. # Otherwise, halt the trace if no link exists
  873. break
  874. if not all(type(link) in (Cable, WirelessLink) for link in links):
  875. raise UnsupportedCablePath(_("All links must be cable or wireless"))
  876. if not all(isinstance(link, type(links[0])) for link in links):
  877. raise UnsupportedCablePath(_("All links must match first link type"))
  878. # Step 3: Record asymmetric paths as split
  879. not_connected_terminations = [termination.link for termination in terminations if termination.link is None]
  880. if len(not_connected_terminations) > 0:
  881. is_complete = False
  882. is_split = True
  883. # Step 4: Record the links, keeping cables in order to allow for SVG rendering
  884. cables = []
  885. for link in links:
  886. if object_to_path_node(link) not in cables:
  887. cables.append(object_to_path_node(link))
  888. path.append(cables)
  889. # Step 5: Update the path status if a link is not connected
  890. links_status = [link.status for link in links if link.status != LinkStatusChoices.STATUS_CONNECTED]
  891. if any([status != LinkStatusChoices.STATUS_CONNECTED for status in links_status]):
  892. is_active = False
  893. # Step 6: Determine the far-end terminations
  894. if isinstance(links[0], Cable):
  895. # Profile-based tracing
  896. if links[0].profile:
  897. cable_profile = links[0].profile_class()
  898. if position_stack:
  899. positions = position_stack.pop()
  900. else:
  901. # When the position stack is empty (e.g. the trace reached this
  902. # profiled cable after crossing single-position pass-through ports
  903. # which don't push onto the stack), derive positions from each
  904. # termination's own cable_positions — which were set by this
  905. # profiled cable when it was saved.
  906. positions = [
  907. pos for term in terminations for pos in (term.cable_positions or [])
  908. ]
  909. remote_terminations = []
  910. new_positions = []
  911. # Build (termination, position) pairs by matching stacked positions
  912. # to each termination's cable_positions. This correctly handles
  913. # multiple terminations on different connectors of the same cable.
  914. remaining = Counter(positions)
  915. term_position_pairs = []
  916. for term in terminations:
  917. if term.cable_positions:
  918. for cp in term.cable_positions:
  919. if remaining[cp]:
  920. term_position_pairs.append((term, cp))
  921. remaining[cp] -= 1
  922. # Fallback for when positions don't match cable_positions
  923. if not term_position_pairs:
  924. term_position_pairs = [(terminations[0], pos) for pos in positions or [None]]
  925. peer_results = cable_profile.get_peer_terminations(term_position_pairs)
  926. seen = set()
  927. for peer, new_pos in peer_results:
  928. # If the far-end termination is a channelized interface, resolve to the specific channel
  929. # subinterface bound to the mapped connector position (the far end is channelized on the same
  930. # physical connector, so the peer lookup returns the parent rather than the channel). A
  931. # channelized parent is never itself a path endpoint, so an unoccupied position yields no peer.
  932. if new_pos is not None and getattr(peer, 'channels', None):
  933. peer = peer.child_interfaces.filter(channel_id=new_pos).first()
  934. # Deduplicate peer terminations by model type & PK.
  935. key = None if peer is None else (peer._meta.concrete_model, peer.pk)
  936. if key not in seen:
  937. seen.add(key)
  938. remote_terminations.append(peer)
  939. new_positions.append(new_pos)
  940. # If all peers resolved to None (no far-end terminations exist),
  941. # treat as an empty result so the path is recorded as incomplete
  942. # rather than falling through to the endpoint check with a stale
  943. # None entry.
  944. if remote_terminations and all(peer is None for peer in remote_terminations):
  945. remote_terminations = []
  946. position_stack.append(new_positions)
  947. # Legacy (positionless) behavior
  948. else:
  949. termination_type = ObjectType.objects.get_for_model(terminations[0])
  950. local_cable_terminations = CableTermination.objects.filter(
  951. termination_type=termination_type,
  952. termination_id__in=[t.pk for t in terminations]
  953. )
  954. q_filter = Q()
  955. for lct in local_cable_terminations:
  956. cable_end = 'A' if lct.cable_end == 'B' else 'B'
  957. q_filter |= Q(cable=lct.cable, cable_end=cable_end)
  958. # Make sure this filter has been populated; if not, we have probably been given invalid data
  959. if not q_filter:
  960. break
  961. remote_cable_terminations = CableTermination.objects.filter(q_filter).prefetch_related(
  962. 'termination'
  963. )
  964. remote_terminations = [ct.termination for ct in remote_cable_terminations]
  965. else:
  966. # WirelessLink
  967. remote_terminations = [
  968. link.interface_b if link.interface_a is terminations[0] else link.interface_a for link in links
  969. ]
  970. logger.debug(f'[Path segment #{segment}] Remote terminations: {remote_terminations}')
  971. # Remote Terminations must all be of the same type, otherwise return a split path
  972. if not all(isinstance(t, type(remote_terminations[0])) for t in remote_terminations[1:]):
  973. is_complete = False
  974. is_split = True
  975. logger.debug('Remote termination types differ; aborting trace.')
  976. break
  977. # Step 7: Record the far-end termination object(s)
  978. path.append([
  979. object_to_path_node(t) for t in remote_terminations if t is not None
  980. ])
  981. # Step 8: Determine the "next hop" terminations, if applicable
  982. if not remote_terminations:
  983. break
  984. if isinstance(remote_terminations[0], FrontPort):
  985. # Follow FrontPorts to their corresponding RearPorts
  986. if remote_terminations[0].positions > 1 and position_stack:
  987. positions = position_stack.pop()
  988. q_filter = Q()
  989. for rt in remote_terminations:
  990. q_filter |= Q(front_port=rt, front_port_position__in=positions)
  991. port_mappings = PortMapping.objects.filter(q_filter)
  992. elif remote_terminations[0].positions > 1:
  993. is_split = True
  994. logger.debug(
  995. 'Encountered front port mapped to multiple rear ports but position stack is empty; aborting '
  996. 'trace.'
  997. )
  998. break
  999. else:
  1000. port_mappings = PortMapping.objects.filter(front_port__in=remote_terminations)
  1001. if not port_mappings:
  1002. break
  1003. # Compile the list of RearPorts without duplication or altering their ordering
  1004. terminations = list(dict.fromkeys(mapping.rear_port for mapping in port_mappings))
  1005. if any(t.positions > 1 for t in terminations):
  1006. position_stack.append([mapping.rear_port_position for mapping in port_mappings])
  1007. elif isinstance(remote_terminations[0], RearPort):
  1008. # Follow RearPorts to their corresponding FrontPorts
  1009. if remote_terminations[0].positions > 1 and position_stack:
  1010. positions = position_stack.pop()
  1011. q_filter = Q()
  1012. for rt in remote_terminations:
  1013. q_filter |= Q(rear_port=rt, rear_port_position__in=positions)
  1014. port_mappings = PortMapping.objects.filter(q_filter)
  1015. elif remote_terminations[0].positions > 1:
  1016. is_split = True
  1017. logger.debug(
  1018. 'Encountered rear port mapped to multiple front ports but position stack is empty; aborting '
  1019. 'trace.'
  1020. )
  1021. break
  1022. else:
  1023. port_mappings = PortMapping.objects.filter(rear_port__in=remote_terminations)
  1024. if not port_mappings:
  1025. break
  1026. # Compile the list of FrontPorts without duplication or altering their ordering
  1027. terminations = list(dict.fromkeys(mapping.front_port for mapping in port_mappings))
  1028. if any(t.positions > 1 for t in terminations):
  1029. position_stack.append([mapping.front_port_position for mapping in port_mappings])
  1030. elif isinstance(remote_terminations[0], CircuitTermination):
  1031. # Follow a CircuitTermination to its corresponding CircuitTermination (A to Z or vice versa)
  1032. qs = Q()
  1033. for remote_termination in remote_terminations:
  1034. qs |= Q(
  1035. circuit=remote_termination.circuit,
  1036. term_side='Z' if remote_termination.term_side == 'A' else 'A'
  1037. )
  1038. # Get all circuit terminations
  1039. circuit_terminations = CircuitTermination.objects.filter(qs)
  1040. if not circuit_terminations.exists():
  1041. break
  1042. if all([ct._provider_network for ct in circuit_terminations]):
  1043. # Circuit terminates to a ProviderNetwork
  1044. path.extend([
  1045. [object_to_path_node(ct) for ct in circuit_terminations],
  1046. [object_to_path_node(ct._provider_network) for ct in circuit_terminations],
  1047. ])
  1048. is_complete = True
  1049. break
  1050. if all([ct.termination and not ct.cable for ct in circuit_terminations]):
  1051. # Circuit terminates to a Region/Site/etc.
  1052. path.extend([
  1053. [object_to_path_node(ct) for ct in circuit_terminations],
  1054. [object_to_path_node(ct.termination) for ct in circuit_terminations],
  1055. ])
  1056. break
  1057. if any([ct.cable in links for ct in circuit_terminations]):
  1058. # No valid path
  1059. is_split = True
  1060. break
  1061. terminations = circuit_terminations
  1062. else:
  1063. # Check for non-symmetric path
  1064. if all(isinstance(t, type(remote_terminations[0])) for t in remote_terminations[1:]):
  1065. is_complete = True
  1066. elif len(remote_terminations) == 0:
  1067. is_complete = False
  1068. else:
  1069. # Unsupported topology, mark as split and exit
  1070. is_complete = False
  1071. is_split = True
  1072. logger.warning('Encountered an unsupported topology; aborting trace.')
  1073. break
  1074. return cls(
  1075. path=path,
  1076. is_complete=is_complete,
  1077. is_active=is_active,
  1078. is_split=is_split
  1079. )
  1080. def retrace(self):
  1081. """
  1082. Retrace the path from the currently-defined originating termination(s)
  1083. """
  1084. _new = self.from_origin(self.origins)
  1085. if _new:
  1086. self.path = _new.path
  1087. self.is_complete = _new.is_complete
  1088. self.is_active = _new.is_active
  1089. self.is_split = _new.is_split
  1090. self.save()
  1091. else:
  1092. self.delete()
  1093. retrace.alters_data = True
  1094. def get_cable_ids(self):
  1095. """
  1096. Return all Cable IDs within the path.
  1097. """
  1098. cable_ct = ObjectType.objects.get_for_model(Cable).pk
  1099. cable_ids = []
  1100. for node in self._nodes:
  1101. ct, id = decompile_path_node(node)
  1102. if ct == cable_ct:
  1103. cable_ids.append(id)
  1104. return cable_ids
  1105. def get_total_length(self):
  1106. """
  1107. Return a tuple containing the sum of the length of each cable and the distance of each circuit
  1108. crossed by the path, and a flag indicating whether the length is definitive.
  1109. """
  1110. from circuits.models import CircuitTermination
  1111. object_types = ObjectType.objects.get_for_models(Cable, CircuitTermination)
  1112. cable_ct = object_types[Cable].pk
  1113. circuit_termination_ct = object_types[CircuitTermination].pk
  1114. # Pre-cache cable lengths by ID
  1115. cable_ids = self.get_cable_ids()
  1116. cables = {
  1117. cable['pk']: cable['_abs_length']
  1118. for cable in Cable.objects.filter(id__in=cable_ids, _abs_length__isnull=False).values('pk', '_abs_length')
  1119. }
  1120. # Pre-cache the circuit terminations within the path, along with their circuits
  1121. circuit_termination_ids = []
  1122. for node in self._nodes:
  1123. ct, pk = decompile_path_node(node)
  1124. if ct == circuit_termination_ct:
  1125. circuit_termination_ids.append(pk)
  1126. circuit_terminations = CircuitTermination.objects.select_related('circuit').in_bulk(circuit_termination_ids)
  1127. # Iterate through each set of nodes in the path. For cables, add the length of the longest cable to the total
  1128. # length of the path. Also map each set of nodes to its circuit terminations, keyed by circuit ID.
  1129. total_length = 0
  1130. circuit_hops = []
  1131. for node_set in self.path:
  1132. hop_length = 0
  1133. hop_terminations = {}
  1134. for node in node_set:
  1135. ct, pk = decompile_path_node(node)
  1136. if ct == cable_ct:
  1137. if pk in cables and cables[pk] > hop_length:
  1138. hop_length = cables[pk]
  1139. elif ct == circuit_termination_ct:
  1140. termination = circuit_terminations.get(pk)
  1141. if termination is not None:
  1142. hop_terminations[termination.circuit_id] = termination
  1143. else:
  1144. break # Neither a cable nor a circuit termination
  1145. total_length += hop_length
  1146. circuit_hops.append(hop_terminations)
  1147. # Unresolvable circuit terminations may conceal a crossing, so they render the total non-definitive
  1148. is_definitive = len(cables) == len(cable_ids) and len(circuit_terminations) == len(set(circuit_termination_ids))
  1149. # A circuit crossing appears as two adjacent sets of opposing terminations of the same circuit. For each
  1150. # crossing, add the longest distance among the circuits crossed, mirroring the handling of parallel cables.
  1151. for near_hop, far_hop in itertools.pairwise(circuit_hops):
  1152. crossing_distance = 0
  1153. for circuit_id in near_hop.keys() & far_hop.keys():
  1154. if near_hop[circuit_id].term_side == far_hop[circuit_id].term_side:
  1155. continue
  1156. distance = near_hop[circuit_id].circuit._abs_distance
  1157. if distance is None:
  1158. is_definitive = False
  1159. elif distance > crossing_distance:
  1160. crossing_distance = distance
  1161. total_length += crossing_distance
  1162. return total_length, is_definitive
  1163. def get_split_nodes(self):
  1164. """
  1165. Return all available next segments in a split cable path.
  1166. """
  1167. from circuits.models import CircuitTermination
  1168. nodes = self.path_objects[-1]
  1169. # RearPort splitting to multiple FrontPorts with no stack position
  1170. if type(nodes[0]) is RearPort:
  1171. return [
  1172. mapping.front_port for mapping in
  1173. PortMapping.objects.filter(rear_port__in=nodes).prefetch_related('front_port')
  1174. ]
  1175. # Cable terminating to multiple FrontPorts mapped to different
  1176. # RearPorts connected to different cables
  1177. if type(nodes[0]) is FrontPort:
  1178. return [
  1179. mapping.rear_port for mapping in
  1180. PortMapping.objects.filter(front_port__in=nodes).prefetch_related('rear_port')
  1181. ]
  1182. # Cable terminating to multiple CircuitTerminations
  1183. if type(nodes[0]) is CircuitTermination:
  1184. return [
  1185. ct.get_peer_termination() for ct in nodes
  1186. ]
  1187. return []
  1188. def get_asymmetric_nodes(self):
  1189. """
  1190. Return all available next segments in a split cable path.
  1191. """
  1192. from circuits.models import CircuitTermination
  1193. asymmetric_nodes = []
  1194. for nodes in self.path_objects:
  1195. if type(nodes[0]) in [RearPort, FrontPort, CircuitTermination]:
  1196. asymmetric_nodes.extend([node for node in nodes if node.link is None])
  1197. return asymmetric_nodes