1
0
mirror of https://github.com/netbox-community/netbox.git synced 2024-05-10 07:54:54 +00:00

83 lines
2.7 KiB
Python
Raw Normal View History

2020-09-30 15:07:56 -04:00
from django.contrib.contenttypes.models import ContentType
from .choices import CableStatusChoices
2020-09-30 15:07:56 -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)
return compile_path_node(ct.pk, obj.pk)
2020-09-30 15:07:56 -04:00
def path_node_to_object(repr):
2020-10-06 16:34:03 -04:00
"""
Given a path node representation, return the corresponding object.
"""
ct_id, object_id = decompile_path_node(repr)
2020-10-06 16:34:03 -04:00
model_class = ContentType.objects.get(pk=ct_id).model_class()
2020-09-30 15:07:56 -04:00
return model_class.objects.get(pk=int(object_id))
2020-10-01 14:16:43 -04:00
def trace_path(node):
2020-10-02 14:54:16 -04:00
from .models import FrontPort, RearPort
2020-09-30 15:07:56 -04:00
destination = None
path = []
position_stack = []
is_active = True
2020-09-30 15:07:56 -04:00
2020-10-05 10:08:16 -04:00
if node is None or node.cable is None:
return [], None, False
2020-09-30 15:07:56 -04:00
while node.cable is not None:
if node.cable.status != CableStatusChoices.STATUS_CONNECTED:
is_active = False
2020-09-30 15:07:56 -04:00
# Follow the cable to its far-end termination
path.append(object_to_path_node(node.cable))
peer_termination = node.get_cable_peer()
# Follow a FrontPort to its corresponding RearPort
if isinstance(peer_termination, FrontPort):
path.append(object_to_path_node(peer_termination))
node = peer_termination.rear_port
if node.positions > 1:
position_stack.append(peer_termination.rear_port_position)
2020-09-30 15:07:56 -04:00
path.append(object_to_path_node(node))
# Follow a RearPort to its corresponding FrontPort
elif isinstance(peer_termination, RearPort):
path.append(object_to_path_node(peer_termination))
if peer_termination.positions == 1:
node = FrontPort.objects.get(rear_port=peer_termination, rear_port_position=1)
path.append(object_to_path_node(node))
elif position_stack:
2020-09-30 15:07:56 -04:00
position = position_stack.pop()
node = FrontPort.objects.get(rear_port=peer_termination, rear_port_position=position)
path.append(object_to_path_node(node))
else:
# No position indicated: path has split, so we stop at the RearPort
break
2020-09-30 15:07:56 -04:00
# Anything else marks the end of the path
else:
destination = peer_termination
break
if destination is None:
is_active = False
return path, destination, is_active