2022-07-07 12:48:44 -04:00
|
|
|
import itertools
|
|
|
|
|
2020-09-30 15:07:56 -04:00
|
|
|
from django.contrib.contenttypes.models import ContentType
|
2021-10-13 13:28:14 -04:00
|
|
|
from django.db import transaction
|
2020-09-30 15:07:56 -04:00
|
|
|
|
|
|
|
|
2020-10-06 16:58:11 -04:00
|
|
|
def compile_path_node(ct_id, object_id):
|
|
|
|
return f'{ct_id}:{object_id}'
|
|
|
|
|
|
|
|
|
|
|
|
def decompile_path_node(repr):
|
|
|
|
ct_id, object_id = repr.split(':')
|
|
|
|
return int(ct_id), int(object_id)
|
|
|
|
|
|
|
|
|
2020-09-30 15:07:56 -04:00
|
|
|
def object_to_path_node(obj):
|
2020-10-06 16:34:03 -04:00
|
|
|
"""
|
|
|
|
Return a representation of an object suitable for inclusion in a CablePath path. Node representation is in the
|
|
|
|
form <ContentType ID>:<Object ID>.
|
|
|
|
"""
|
|
|
|
ct = ContentType.objects.get_for_model(obj)
|
2020-10-06 16:58:11 -04:00
|
|
|
return compile_path_node(ct.pk, obj.pk)
|
2020-09-30 15:07:56 -04:00
|
|
|
|
|
|
|
|
2020-11-16 15:49:07 -05:00
|
|
|
def path_node_to_object(repr):
|
|
|
|
"""
|
2022-08-03 12:46:16 -04:00
|
|
|
Given the string representation of a path node, return the corresponding instance. If the object no longer
|
|
|
|
exists, return None.
|
2020-11-16 15:49:07 -05:00
|
|
|
"""
|
|
|
|
ct_id, object_id = decompile_path_node(repr)
|
|
|
|
ct = ContentType.objects.get_for_id(ct_id)
|
2022-08-03 12:46:16 -04:00
|
|
|
return ct.model_class().objects.filter(pk=object_id).first()
|
2021-10-13 13:28:14 -04:00
|
|
|
|
|
|
|
|
2022-05-06 16:17:27 -04:00
|
|
|
def create_cablepath(terminations):
|
2021-10-13 13:28:14 -04:00
|
|
|
"""
|
2022-05-06 16:17:27 -04:00
|
|
|
Create CablePaths for all paths originating from the specified set of nodes.
|
|
|
|
|
|
|
|
:param terminations: Iterable of CableTermination objects
|
2021-10-13 13:28:14 -04:00
|
|
|
"""
|
|
|
|
from dcim.models import CablePath
|
|
|
|
|
2022-05-06 16:17:27 -04:00
|
|
|
cp = CablePath.from_origin(terminations)
|
2021-10-13 13:28:14 -04:00
|
|
|
if cp:
|
|
|
|
cp.save()
|
|
|
|
|
|
|
|
|
2022-05-10 10:30:58 -04:00
|
|
|
def rebuild_paths(terminations):
|
2021-10-13 13:28:14 -04:00
|
|
|
"""
|
2022-07-07 12:48:44 -04:00
|
|
|
Rebuild all CablePaths which traverse the specified nodes.
|
2021-10-13 13:28:14 -04:00
|
|
|
"""
|
|
|
|
from dcim.models import CablePath
|
|
|
|
|
2022-05-10 10:30:58 -04:00
|
|
|
for obj in terminations:
|
|
|
|
cable_paths = CablePath.objects.filter(_nodes__contains=obj)
|
2021-10-13 13:28:14 -04:00
|
|
|
|
2022-05-10 10:30:58 -04:00
|
|
|
with transaction.atomic():
|
|
|
|
for cp in cable_paths:
|
|
|
|
cp.delete()
|
2022-05-13 15:05:38 -04:00
|
|
|
create_cablepath(cp.origins)
|