traceroute_map/app/collector.py

104 lines
2.7 KiB
Python
Raw Permalink Normal View History

import json
import uuid
import hashlib
from datetime import datetime
from .db import Database
def parse_traceroute_output(data: str, origin: str):
2024-06-02 19:38:39 +03:00
# TODO: data validation
lines = data.strip().split("\n")
target = lines[0].split()[2]
created = datetime.now().isoformat()
trace = {"target": target, "created": created, "origin": origin, "hops": []}
2024-06-02 19:38:39 +03:00
prev_latency = None
for line in lines[1:]:
hop_info = line.split()
print("LINE:", hop_info)
try:
2024-06-02 19:38:39 +03:00
# Regular lines.
number, name, ip, latency, _ = hop_info
2024-06-02 19:38:39 +03:00
latency = float(latency)
hop = {
"created": created,
"number": number,
"name": name,
"ip": ip.strip("()"),
2024-06-02 19:38:39 +03:00
"latency": latency,
"link_latency": round(latency if prev_latency else latency, 3),
}
2024-06-02 19:38:39 +03:00
prev_latency = latency
except ValueError:
2024-06-02 19:38:39 +03:00
# Asterisks, no data found for hop.
number, name = hop_info
hop = {
"created": created,
"number": number,
"name": name,
"ip": None,
"latency": None,
2024-06-02 19:38:39 +03:00
"link_latency": "?",
}
trace["hops"].append(hop)
return trace
def store_traceroute(trace):
db = Database()
# hops_json = json.dumps(trace['hops'])
path_ids = {}
previous_hop_ip = None
previous_hop_latency = None
for hop in trace["hops"]:
hop_number = hop["number"]
hop_name = hop.get("name")
hop_ip = hop.get("ip")
hop_latency = hop.get("latency")
link_id = None
# insert links and get their id's
if previous_hop_ip:
link_id = db.create_link(previous_hop_ip, hop_ip)
path_ids[hop_number] = link_id
previous_hop_ip = hop_ip
# Save hop details
db.create_hop(hop_name, hop_ip, hop_latency)
# calculate link latency if possible and store it
if link_id and previous_hop_latency:
link_latency = hop_latency - previous_hop_latency
db.create_latency(link_id, trace["created"], link_latency)
# make entry to "Paths" table
if path_ids:
json_path_ids = json.dumps(path_ids)
db.create_path(node, trace["target"], json_path_ids)
db.end()
def generate_node_id():
mac = uuid.getnode()
mac_str = ":".join(
["{:02x}".format((mac >> ele) & 0xFF) for ele in range(0, 8 * 6, 8)][::-1]
)
# Hash the MAC address using SHA-256 to generate a unique ID
unique_id = hashlib.sha256(mac_str.encode()).hexdigest()
return unique_id