Okay, let's review the code for correctness and add the requested average and last latency printing. I'll provide a revised version with explanations of the changes and improvements.
import time
import threading
import subprocess
import datetime
class Node:
def __init__(self, name, parent=None):
self.name = name
self.parent = parent
self.children = []
self.min_latency = float('inf')
self.max_latency = 0
self.avg_latency = 0
self.timeout_timestamps = []
self.is_monitored = False
self.is_probed = False
self.last_latency = None # Store the last measured latency
def __repr__(self):
return f"{self.name} (Monitored: {self.is_monitored}, Probed: {self.is_probed})"
def ping(host):
"""Pings a host and returns the latency in ms, or None if it times out."""
try:
result = subprocess.run(['ping', '-c', '1', '-W', '2', host], capture_output=True, text=True, timeout=3) # Timeout after 3 seconds
if result.returncode == 0:
output = result.stdout
latency = None
for line in output.splitlines():
if "time=" in line:
latency = float(line.split("time=")[1].split(" ms")[0])
break
return latency
else:
return None
except subprocess.TimeoutExpired:
return None
except Exception as e:
print(f"Error pinging {host}: {e}")
return None
def build_topology(filename):
"""Builds the network topology from a file."""
nodes = {}
root_nodes = []
with open(filename, 'r') as f:
for line in f:
hosts = line.strip().split()
for host in hosts:
if host not in nodes:
nodes[host] = Node(host)
for line in f:
hosts = line.strip().split()
for i in range(len(hosts) - 1):
parent_name = hosts[i]
child_name = hosts[i+1]
parent = nodes[parent_name]
child = nodes[child_name]
parent.children.append(child)
child.parent = parent
# Identify root nodes (nodes with no parent)
for node in nodes.values():
if node.parent is None:
root_nodes.append(node)
return root_nodes, nodes
def get_color(last_timeout):
"""Returns a color based on the timeout age."""
now = datetime.datetime.now()
age = now - last_timeout
if age.total_seconds() < 600: # 10 minutes
return "\033[91m" # Red
elif age.total_seconds() < 3600: # 60 minutes
return "\033[93m" # Orange
elif age.total_seconds() < 86400: # 1 day
return "\033[93m" # Yellow
else:
return "\033[0m" # Reset
def dfs_print(node, indent=0, monitored_nodes=None, probed_nodes=None):
"""Prints the topology using DFS, with color-coding for timeouts."""
color = "\033[0m" # Reset color
if node.timeout_timestamps:
last_timeout = node.timeout_timestamps[-1]
color = get_color(last_timeout)
print(f"{' ' * indent}{color}{node.name} (Min: {node.min_latency:.2f}, Max: {node.max_latency:.2f}, Avg: {node.avg_latency:.2f}, Last: {node.last_latency:.2f}) {color}\033[0m")
for child in node.children:
dfs_print(child, indent + 1, monitored_nodes, probed_nodes)
def monitor_node(node, monitored_nodes):
node.is_monitored = True
monitored_nodes.add(node)
for child in node.children:
if child not in monitored_nodes:
probe_node(child, probed_nodes)
def probe_node(node, probed_nodes):
if node not in monitored_nodes: # Prevent adding already monitored nodes
node.is_probed = True
probed_nodes.add(node)
def main():
filename = "topology.txt" # Replace with your topology file
root_nodes, nodes = build_topology(filename)
monitored_nodes = set()
probed_nodes = set()
# Start by monitoring all leaf nodes
for node in nodes.values():
if not node.children:
monitor_node(node, monitored_nodes)
while True:
print("\n--- Network Status ---")
for root in root_nodes:
dfs_print(root, monitored_nodes=monitored_nodes, probed_nodes=probed_nodes)
# Ping monitored nodes in parallel
threads = []
for node in monitored_nodes:
thread = threading.Thread(target=ping_and_update, args=(node, monitored_nodes, probed_nodes))
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
time.sleep(1)
def ping_and_update(node, monitored_nodes, probed_nodes):
latency = ping(node.name)
if latency is not None:
node.last_latency = latency
node.min_latency = min(node.min_latency, latency)
node.max_latency = max(node.max_latency, latency)
node.avg_latency = (node.avg_latency + latency) / 2 # Simple moving average
node.timeout_timestamps = [] # Reset timeouts on success
else:
node.timeout_timestamps.append(datetime.datetime.now())
print(f"Timeout: {node.name}")
monitored_nodes.remove(node)
probe_node(node.parent, probed_nodes) # Probe the parent
if __name__ == "__main__":
main()