Created
April 19, 2023 20:14
-
-
Save DanSheps/e957ae0465883a0d813bb1114f34dbab to your computer and use it in GitHub Desktop.
Network Trace
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def trace(port, graph=None, last=None, position_stack=None): | |
if position_stack is None: | |
position_stack = [] | |
nodes = [] | |
paths = [] | |
# Add edge if last is set. Supports: Cables, WirelessLinks, PortPair. Todo: Bridges | |
if last: | |
if isinstance(port, RearPort) and isinstance(last, FrontPort): | |
nodes.append(port) | |
elif isinstance(port, FrontPort) and isinstance(last, RearPort): | |
nodes.append(port) | |
elif isinstance(port.link, Cable) and isinstance(last.link, Cable) and last.link == port.link: | |
nodes.append(port.link) | |
nodes.append(port) | |
elif isinstance(port.link, WirelessLink) and isinstance(last.link, WirelessLink) and last.link == port.link: | |
nodes.append(port.link) | |
nodes.append(port) | |
else: | |
raise Exception("No edge added, this shouldn't be possible") | |
else: | |
nodes.append(port) | |
# Trace link peers | |
if port.link and last not in port.link_peers: | |
if len(port.link_peers) > 1: | |
multi = True | |
else: | |
multi = False | |
for remote in port.link_peers: | |
if multi: | |
paths.append(trace(port=remote, graph=graph, last=port, position_stack=position_stack)) | |
else: | |
paths.extend(trace(port=remote, graph=graph, last=port, position_stack=position_stack)) | |
if multi: | |
nodes.append(paths) | |
else: | |
nodes.extend(paths) | |
elif isinstance(port, FrontPort) and last != port.rear_port: | |
position_stack.append(port.rear_port_position) | |
remote = port.rear_port | |
nodes.extend(trace(port=port.rear_port, graph=graph, last=port, position_stack=position_stack)) | |
elif isinstance(port, RearPort): | |
# Check for split path | |
if len(position_stack) == 0: | |
return nodes | |
position = position_stack.pop() | |
remote = port.frontports.get(rear_port_position=position) | |
if remote != last: | |
nodes.extend(trace(port=remote, graph=graph, last=port, position_stack=position_stack)) | |
elif isinstance(port, CircuitTermination) and last != port.get_peer_termination(): | |
remote = port.get_peer_termination() | |
nodes.extend(trace(port=remote, graph=graph, last=port, position_stack=position_stack)) | |
return nodes | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment