init commit
This commit is contained in:
@@ -0,0 +1,252 @@
|
||||
"""Сборка графа маршрутизации Remnawave: профиль + хосты + ноды -> {nodes, edges, warnings}.
|
||||
|
||||
Колонки слева направо: host -> inbound -> rule(ы) -> balancer -> outbound -> node.
|
||||
Только чтение, без статистики и юзеров.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
# Ключи правила, которые мы умеем вычислять точно (остальные = "условные").
|
||||
_TARGET_KEYS = {"outboundTag", "balancerTag", "ruleTag", "type"}
|
||||
_EXACT_KEYS = {"vlessRoute", "inboundTag"}
|
||||
|
||||
|
||||
def parse_vless_route(value) -> set[int] | None:
|
||||
"""1 | "8-14" | "1,3,8-10" -> множество номеров; None, если поля нет."""
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, int):
|
||||
return {value}
|
||||
out: set[int] = set()
|
||||
for part in str(value).split(","):
|
||||
part = part.strip()
|
||||
if "-" in part:
|
||||
a, b = part.split("-", 1)
|
||||
out.update(range(int(a), int(b) + 1))
|
||||
elif part:
|
||||
out.add(int(part))
|
||||
return out
|
||||
|
||||
|
||||
def _conditions(rule: dict) -> set[str]:
|
||||
return set(rule) - _TARGET_KEYS
|
||||
|
||||
|
||||
def _opaque(rule: dict) -> set[str]:
|
||||
"""Условия, которые нельзя вычислить статически (domain, ip, port, protocol...)."""
|
||||
return _conditions(rule) - _EXACT_KEYS
|
||||
|
||||
|
||||
def rule_label(rule: dict) -> str:
|
||||
parts = []
|
||||
for k in sorted(_conditions(rule)):
|
||||
v = rule[k]
|
||||
if isinstance(v, list):
|
||||
shown = ", ".join(map(str, v[:3])) + (f" +{len(v) - 3}" if len(v) > 3 else "")
|
||||
else:
|
||||
shown = str(v)
|
||||
parts.append(f"{k}: {shown}")
|
||||
return "; ".join(parts) or "любой трафик"
|
||||
|
||||
|
||||
def find_shadowed(rules: list[dict], inbound_tags: set[str]) -> set[int]:
|
||||
"""Правила после catch-all недостижимы (Xray: первое совпавшее правило выигрывает)."""
|
||||
for i, r in enumerate(rules):
|
||||
cond = _conditions(r)
|
||||
if not cond or (cond == {"inboundTag"} and set(r["inboundTag"]) >= inbound_tags):
|
||||
return set(range(i + 1, len(rules)))
|
||||
return set()
|
||||
|
||||
|
||||
def trace_host(rules: list[dict], route: int | None, inbound_tag: str) -> list[int]:
|
||||
"""Индексы правил, через которые может пройти трафик хоста, до первого безусловного."""
|
||||
path: list[int] = []
|
||||
for i, r in enumerate(rules):
|
||||
routes = parse_vless_route(r.get("vlessRoute"))
|
||||
if routes is not None and route not in routes:
|
||||
continue
|
||||
tags = r.get("inboundTag")
|
||||
if tags and inbound_tag not in tags:
|
||||
continue
|
||||
path.append(i)
|
||||
if not _opaque(r):
|
||||
break
|
||||
return path
|
||||
|
||||
|
||||
def node_state(n: dict) -> str:
|
||||
"""disabled | connecting | offline | online."""
|
||||
if n.get("isDisabled"):
|
||||
return "disabled"
|
||||
if n.get("isConnecting"):
|
||||
return "connecting"
|
||||
return "offline" if n.get("isConnected") is False else "online"
|
||||
|
||||
|
||||
def build_node_index(nodes: list[dict]) -> dict[str, dict]:
|
||||
"""ip -> нода. MANAGEMENT-адреса в приоритете, затем address, затем остальные ips.
|
||||
|
||||
Живые ноды идут первыми: если отключённая нода хранит тот же адрес, что и рабочая,
|
||||
выигрывает рабочая.
|
||||
"""
|
||||
ordered = sorted(nodes, key=lambda n: node_state(n) != "online") # sort стабильный
|
||||
idx: dict[str, dict] = {}
|
||||
for n in ordered:
|
||||
for e in n.get("ips") or []:
|
||||
if e["status"] == "MANAGEMENT":
|
||||
idx.setdefault(e["ip"], n)
|
||||
for n in ordered:
|
||||
idx.setdefault(n["address"], n)
|
||||
for e in n.get("ips") or []:
|
||||
idx.setdefault(e["ip"], n)
|
||||
return idx
|
||||
|
||||
|
||||
def node_info(n: dict) -> dict:
|
||||
ips = n.get("ips") or []
|
||||
by = lambda st: [e["ip"] for e in ips if e["status"] == st] # noqa: E731
|
||||
ifaces = ((n.get("system") or {}).get("info") or {}).get("networkInterfaces") or []
|
||||
return {
|
||||
"name": n["name"],
|
||||
"country": n.get("countryCode"),
|
||||
"state": node_state(n),
|
||||
"connected": n.get("isConnected"),
|
||||
"disabled": bool(n.get("isDisabled")),
|
||||
"mgmt": by("MANAGEMENT"),
|
||||
"exit": by("OUTBOUND"),
|
||||
"inbound": by("INBOUND"),
|
||||
"reserve": by("RESERVE"),
|
||||
"netbird": "wt0" in ifaces,
|
||||
}
|
||||
|
||||
|
||||
def outbound_ip(ob: dict) -> str | None:
|
||||
try:
|
||||
return ob["settings"]["servers"][0]["address"]
|
||||
except (KeyError, IndexError, TypeError):
|
||||
return None # freedom / blackhole
|
||||
|
||||
|
||||
def build_graph(profile: dict, hosts: list[dict], nodes: list[dict]) -> dict:
|
||||
cfg = profile["config"]
|
||||
rules = cfg.get("routing", {}).get("rules", [])
|
||||
balancers = cfg.get("routing", {}).get("balancers", [])
|
||||
outbounds = cfg.get("outbounds", [])
|
||||
inbounds = cfg.get("inbounds", [])
|
||||
inbound_tags = {i["tag"] for i in inbounds}
|
||||
|
||||
G_nodes: list[dict] = []
|
||||
G_edges: list[dict] = []
|
||||
warnings: list[str] = []
|
||||
|
||||
def add_node(id_, type_, label, **data):
|
||||
G_nodes.append({"id": id_, "type": type_, "label": label, "data": data})
|
||||
|
||||
def add_edge(src, dst, kind="flow", label=None, **data):
|
||||
G_edges.append({"id": f"{src}->{dst}:{kind}", "source": src, "target": dst,
|
||||
"kind": kind, "label": label, "data": data})
|
||||
|
||||
shadowed = find_shadowed(rules, inbound_tags)
|
||||
|
||||
idx = build_node_index(nodes)
|
||||
|
||||
def _out_alive(o: dict) -> bool:
|
||||
ip = outbound_ip(o)
|
||||
if ip is None: # freedom / blackhole
|
||||
return True
|
||||
n = idx.get(ip)
|
||||
return n is not None and node_state(n) == "online"
|
||||
|
||||
alive = {o["tag"]: _out_alive(o) for o in outbounds}
|
||||
bal_members = {
|
||||
b["tag"]: [o["tag"] for o in outbounds
|
||||
if any(o["tag"].startswith(x) for x in b.get("selector", []))]
|
||||
for b in balancers
|
||||
}
|
||||
|
||||
def target_alive(r: dict) -> bool:
|
||||
if "balancerTag" in r:
|
||||
return any(alive.get(m, False) for m in bal_members.get(r["balancerTag"], []))
|
||||
return alive.get(r.get("outboundTag"), False)
|
||||
|
||||
# inbounds
|
||||
for i in inbounds:
|
||||
add_node(f"inb:{i['tag']}", "inbound", i["tag"],
|
||||
port=i.get("port"), protocol=i.get("protocol"))
|
||||
|
||||
# rules + цепочка fallthrough + цель
|
||||
for i, r in enumerate(rules):
|
||||
rid = f"rule:{i}"
|
||||
add_node(rid, "rule", f"#{i} {rule_label(r)}", index=i, shadowed=i in shadowed,
|
||||
vlessRoute=sorted(parse_vless_route(r.get("vlessRoute")) or []))
|
||||
target = f"bal:{r['balancerTag']}" if "balancerTag" in r else f"out:{r.get('outboundTag')}"
|
||||
add_edge(rid, target, "target", dead=i in shadowed)
|
||||
if i + 1 < len(rules):
|
||||
add_edge(rid, f"rule:{i + 1}", "fallthrough", dead=(i + 1) in shadowed)
|
||||
if i in shadowed:
|
||||
warnings.append(f"rule #{i} ({rule_label(r)}) недостижимо: выше есть catch-all")
|
||||
if rules:
|
||||
for tag in inbound_tags:
|
||||
add_edge(f"inb:{tag}", "rule:0", "flow")
|
||||
|
||||
# balancers
|
||||
for b in balancers:
|
||||
members = bal_members[b["tag"]]
|
||||
live = [m for m in members if alive[m]]
|
||||
add_node(f"bal:{b['tag']}", "balancer", b["tag"],
|
||||
strategy=(b.get("strategy") or {}).get("type"), members=members,
|
||||
aliveMembers=live)
|
||||
for m in members:
|
||||
add_edge(f"bal:{b['tag']}", f"out:{m}", "member", dead=not alive[m])
|
||||
fb = b.get("fallbackTag")
|
||||
if fb:
|
||||
add_edge(f"bal:{b['tag']}", f"out:{fb}", "fallback", "fallback",
|
||||
dead=not alive.get(fb, False))
|
||||
if not live:
|
||||
warnings.append(f"balancer {b['tag']}: нет ни одного живого члена")
|
||||
elif fb and not alive.get(fb, False):
|
||||
warnings.append(f"balancer {b['tag']}: fallback {fb} ведёт на нерабочую ноду")
|
||||
|
||||
# outbounds -> ноды
|
||||
seen_nodes: set[str] = set()
|
||||
for o in outbounds:
|
||||
ip = outbound_ip(o)
|
||||
add_node(f"out:{o['tag']}", "outbound", o["tag"], protocol=o["protocol"], ip=ip,
|
||||
alive=alive[o["tag"]])
|
||||
if ip is None:
|
||||
continue
|
||||
n = idx.get(ip)
|
||||
if n is None:
|
||||
add_node(f"unresolved:{ip}", "unresolved", ip)
|
||||
add_edge(f"out:{o['tag']}", f"unresolved:{ip}", "link")
|
||||
warnings.append(f"outbound {o['tag']}: адрес {ip} не найден ни в одной карточке ноды")
|
||||
continue
|
||||
nid = f"node:{n['name']}"
|
||||
if nid not in seen_nodes:
|
||||
seen_nodes.add(nid)
|
||||
add_node(nid, "node", n["name"], **node_info(n))
|
||||
add_edge(f"out:{o['tag']}", nid, "link", ip, dead=not alive[o["tag"]])
|
||||
if not alive[o["tag"]]:
|
||||
warnings.append(f"outbound {o['tag']} → {n['name']}: нода {node_state(n)}")
|
||||
|
||||
# хосты профиля
|
||||
uuid_to_tag = {i["uuid"]: i["tag"] for i in (profile.get("inbounds") or [])}
|
||||
for h in hosts:
|
||||
tag = uuid_to_tag.get((h.get("inbound") or {}).get("configProfileInboundUuid"))
|
||||
if tag is None:
|
||||
continue # хост другого профиля
|
||||
route = h.get("vlessRouteId")
|
||||
path = trace_host(rules, route, tag)
|
||||
end = path[-1] if path else None
|
||||
hid = f"host:{h['uuid']}"
|
||||
add_node(hid, "host", h["remark"], address=h.get("address"), port=h.get("port"),
|
||||
vlessRouteId=route, disabled=h.get("isDisabled"),
|
||||
trace=[f"rule:{i}" for i in path],
|
||||
exitAlive=target_alive(rules[end]) if end is not None else False)
|
||||
add_edge(hid, f"inb:{tag}", "flow")
|
||||
if end is not None:
|
||||
add_edge(hid, f"rule:{end}", "route", f"route {route}" if route is not None else "default",
|
||||
dead=not target_alive(rules[end]))
|
||||
if not target_alive(rules[end]) and not h.get("isDisabled"):
|
||||
warnings.append(f"хост {h['remark']}: выход правила #{end} ведёт на нерабочую ноду")
|
||||
|
||||
return {"nodes": G_nodes, "edges": G_edges, "warnings": warnings}
|
||||
Reference in New Issue
Block a user