cables.py 25 KB

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