483 lines
22 KiB
Python
483 lines
22 KiB
Python
"""Граф сети Remnawave: хост -> нода (профиль: инбаунды + правила) -> балансер/outbound -> нода ...
|
||
|
||
Только чтение. Секреты конфигов (ключи, пароли) в граф не попадают.
|
||
|
||
Модель:
|
||
* хост ведёт ровно на одну ноду и садится на строку правила, которое для него срабатывает;
|
||
* карточка ноды содержит секции активных инбаундов, в секции строки-правила по порядку
|
||
(правила инбаунда + общие без inboundTag);
|
||
* у каждой строки свой выход к outbound/балансеру; outbound'ы общие: если несколько нод
|
||
выходят в одну точку, это одна карточка;
|
||
* outbound, смотрящий на адрес другой ноды, ведёт в строку её инбаунда (по порту).
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import ipaddress
|
||
|
||
# Ключи правила, которые мы умеем вычислять точно (остальные = "условные").
|
||
_TARGET_KEYS = {"outboundTag", "balancerTag", "ruleTag", "type"}
|
||
_EXACT_KEYS = {"vlessRoute", "inboundTag"}
|
||
_INTERNAL = [ipaddress.ip_network(n) for n in
|
||
("100.64.0.0/10", "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16")]
|
||
|
||
|
||
# ---------------------------------------------------------------- правила
|
||
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 _as_list(v) -> list:
|
||
return [] if v is None else ([v] if isinstance(v, str) else list(v))
|
||
|
||
|
||
def applies_to(rule: dict, inbound_tag: str | None) -> bool:
|
||
tags = _as_list(rule.get("inboundTag"))
|
||
return not tags or inbound_tag in tags
|
||
|
||
|
||
def is_catch_all(rule: dict) -> bool:
|
||
"""Правило без условий (кроме inboundTag) забирает весь трафик инбаунда."""
|
||
return _conditions(rule) <= {"inboundTag"}
|
||
|
||
|
||
def rule_label(rule: dict) -> str:
|
||
parts = []
|
||
for k in sorted(_conditions(rule) - {"inboundTag"}):
|
||
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 ranges(nums) -> str:
|
||
out, start, prev = [], None, None
|
||
for n in sorted(nums):
|
||
if start is None:
|
||
start = prev = n
|
||
elif n == prev + 1:
|
||
prev = n
|
||
else:
|
||
out.append((start, prev))
|
||
start = prev = n
|
||
if start is not None:
|
||
out.append((start, prev))
|
||
return ", ".join(f"#{a}" if a == b else f"#{a}–#{b}" for a, b in out)
|
||
|
||
|
||
# ---------------------------------------------------------------- ноды
|
||
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),
|
||
"mgmt": by("MANAGEMENT"),
|
||
"exit": by("OUTBOUND"),
|
||
"inbound": by("INBOUND"),
|
||
"reserve": by("RESERVE"),
|
||
"netbird": "wt0" in ifaces,
|
||
}
|
||
|
||
|
||
# ---------------------------------------------------------------- outbound'ы
|
||
def _port(v) -> int | None:
|
||
try:
|
||
return int(v)
|
||
except (TypeError, ValueError):
|
||
return None
|
||
|
||
|
||
def outbound_endpoint(ob: dict) -> tuple[str, int | None] | None:
|
||
"""(адрес, порт) назначения прокси-outbound; None для freedom/blackhole."""
|
||
s = ob.get("settings") or {}
|
||
try:
|
||
for key in ("servers", "vnext"):
|
||
if s.get(key):
|
||
return str(s[key][0]["address"]), _port(s[key][0].get("port"))
|
||
if s.get("peers"): # wireguard
|
||
host, _, port = str(s["peers"][0]["endpoint"]).rpartition(":")
|
||
return host.strip("[]"), _port(port)
|
||
except (KeyError, IndexError, TypeError, AttributeError):
|
||
pass
|
||
return None
|
||
|
||
|
||
def _is_internal(addr: str) -> bool:
|
||
try:
|
||
ip = ipaddress.ip_address(addr)
|
||
except ValueError:
|
||
return False
|
||
return any(ip in net for net in _INTERNAL)
|
||
|
||
|
||
# ---------------------------------------------------------------- секции ноды
|
||
def _row(key: str, index: int | None, rule: dict, shadowed: bool = False, default: bool = False) -> dict:
|
||
kind, tag = (("balancer", rule["balancerTag"]) if "balancerTag" in rule
|
||
else ("outbound", rule.get("outboundTag")))
|
||
routes = parse_vless_route(rule.get("vlessRoute"))
|
||
return {
|
||
"key": key, "index": index,
|
||
"label": "иначе (по умолчанию)" if default else rule_label(rule),
|
||
"common": default or not rule.get("inboundTag"),
|
||
"shadowed": shadowed, "default": default,
|
||
"vlessRoute": sorted(routes) if routes else [],
|
||
"targetKind": kind, "targetTag": tag,
|
||
"_routes": routes, "_opaque": bool(_opaque(rule)), "tid": None, "edge": None,
|
||
}
|
||
|
||
|
||
def build_sections(node: dict, profile: dict) -> list[dict]:
|
||
"""Секции активных инбаундов ноды: правила инбаунда + общие, в порядке выполнения."""
|
||
cfg = profile["config"]
|
||
rules = (cfg.get("routing") or {}).get("rules") or []
|
||
outbounds = cfg.get("outbounds") or []
|
||
inb_defs = {i.get("uuid"): i for i in profile.get("inbounds") or []}
|
||
cfg_inb = {i.get("tag"): i for i in cfg.get("inbounds") or []}
|
||
sections = []
|
||
for a in (node.get("configProfile") or {}).get("activeInbounds") or []:
|
||
d = inb_defs.get(a.get("uuid")) or a
|
||
tag = d.get("tag")
|
||
c = cfg_inb.get(tag) or {}
|
||
rows: list[dict] = []
|
||
catch: int | None = None
|
||
for idx, r in enumerate(rules):
|
||
if not applies_to(r, tag):
|
||
continue
|
||
rows.append(_row(str(idx), idx, r, shadowed=catch is not None))
|
||
if catch is None and is_catch_all(r):
|
||
catch = idx
|
||
if catch is None and outbounds: # Xray: без совпадений трафик идёт в первый outbound
|
||
rows.append(_row("default", None, {"outboundTag": outbounds[0].get("tag")}, default=True))
|
||
sections.append({"uuid": a.get("uuid"), "tag": tag,
|
||
"port": _port(d.get("port") or c.get("port")),
|
||
"protocol": d.get("type") or c.get("protocol"),
|
||
"rows": rows, "catchAll": catch})
|
||
return sections
|
||
|
||
|
||
def trace_rows(rows: list[dict], route: int | None) -> list[dict]:
|
||
"""Строки, через которые может пройти трафик, до первой безусловной."""
|
||
trace: list[dict] = []
|
||
for r in rows:
|
||
if r["shadowed"]:
|
||
break
|
||
if r["_routes"] is not None and route not in r["_routes"]:
|
||
continue
|
||
trace.append(r)
|
||
if not r["_opaque"]:
|
||
break
|
||
return trace
|
||
|
||
|
||
# ---------------------------------------------------------------- граф
|
||
def E(src: str, sh: str, dst: str, th: str) -> str:
|
||
return f"{src}#{sh}>{dst}#{th}"
|
||
|
||
|
||
def build_graph(profiles: list[dict], hosts: list[dict], nodes: list[dict]) -> dict:
|
||
prof = {p["uuid"]: p for p in profiles if isinstance(p.get("config"), dict)}
|
||
by_uuid = {n["uuid"]: n for n in nodes if n.get("uuid")}
|
||
idx = build_node_index(nodes)
|
||
|
||
warnings: list[dict] = []
|
||
seen_warn: set[str] = set()
|
||
|
||
def warn(text: str, target: str | None = None) -> None:
|
||
if text not in seen_warn:
|
||
seen_warn.add(text)
|
||
warnings.append({"text": text, "target": target})
|
||
|
||
edges: list[dict] = []
|
||
edge_ids: set[str] = set()
|
||
|
||
def add_edge(src, sh, dst, th, kind, label=None, dead=False) -> str:
|
||
eid = E(src, sh, dst, th)
|
||
if eid not in edge_ids:
|
||
edge_ids.add(eid)
|
||
edges.append({"id": eid, "source": src, "sourceHandle": sh, "target": dst,
|
||
"targetHandle": th, "kind": kind, "label": label, "data": {"dead": dead}})
|
||
return eid
|
||
|
||
ctxs: dict[str, dict] = {}
|
||
queue: list[dict] = []
|
||
|
||
def ctx_of(n: dict) -> dict:
|
||
nid = f"node:{n.get('uuid') or n['name']}"
|
||
if nid not in ctxs:
|
||
p = prof.get((n.get("configProfile") or {}).get("activeConfigProfileUuid"))
|
||
cfg = p["config"] if p else {}
|
||
ctx = {"id": nid, "node": n, "profile": p,
|
||
"sections": build_sections(n, p) if p else [],
|
||
"outbounds": {o.get("tag"): o for o in cfg.get("outbounds") or []},
|
||
"balancers": {b.get("tag"): b for b in (cfg.get("routing") or {}).get("balancers") or []}}
|
||
ctxs[nid] = ctx
|
||
queue.append(ctx)
|
||
return ctxs[nid]
|
||
|
||
outs: dict[str, dict] = {}
|
||
bals: dict[str, dict] = {}
|
||
|
||
def alive_of(cid: str) -> bool:
|
||
return (outs.get(cid) or bals[cid])["alive"]
|
||
|
||
def out_card(ctx: dict, tag: str) -> str:
|
||
ob = ctx["outbounds"].get(tag)
|
||
n = ctx["node"]
|
||
protocol = (ob or {}).get("protocol", "?")
|
||
ep = outbound_endpoint(ob) if ob else None
|
||
if ep:
|
||
key = f"{protocol}:{ep[0]}:{ep[1]}" # прокси: общий для всех нод с тем же назначением
|
||
elif protocol == "blackhole":
|
||
key = f"blackhole:{tag}" # BLOCK у всех нод одинаков: одна карточка
|
||
else:
|
||
key = f"{protocol}:{ctx['id']}:{tag}" # freedom: у каждой ноды свой публичный выход
|
||
cid = f"out:{key}"
|
||
card = outs.get(cid)
|
||
if card is None:
|
||
card = {"id": cid, "tags": set(), "users": set(), "protocol": protocol,
|
||
"address": ep[0] if ep else None, "port": ep[1] if ep else None,
|
||
"alive": True, "dest": None, "destName": None, "exit": [], "owner": None}
|
||
outs[cid] = card
|
||
if ob is None:
|
||
card["alive"] = False
|
||
warn(f"{n['name']}: правило ведёт в несуществующий outbound {tag}", ctx["id"])
|
||
if protocol == "freedom":
|
||
card["owner"] = n["name"]
|
||
card["exit"] = node_info(n)["exit"]
|
||
if ep:
|
||
dn = idx.get(ep[0])
|
||
if dn is not None:
|
||
dctx = ctx_of(dn)
|
||
sec = next((s for s in dctx["sections"] if ep[1] is not None and s["port"] == ep[1]), None)
|
||
state = node_state(dn)
|
||
card["alive"] = state == "online"
|
||
card["destName"] = dn["name"]
|
||
card["dest"] = {
|
||
"node": dctx["id"], "uuid": sec["uuid"] if sec else None,
|
||
"edge": add_edge(cid, "out", dctx["id"], f"inb:{sec['uuid']}" if sec else "head",
|
||
"link", f"{ep[0]}:{ep[1]}", dead=state != "online"),
|
||
}
|
||
if state != "online":
|
||
warn(f"outbound {tag} → {dn['name']}: нода {state}", cid)
|
||
if sec is None:
|
||
warn(f"outbound {tag} → {dn['name']}: на ноде нет активного инбаунда на порту {ep[1]}", dctx["id"])
|
||
elif _is_internal(ep[0]):
|
||
card["alive"] = False
|
||
warn(f"outbound {tag}: адрес {ep[0]} не найден ни в одной карточке ноды", cid)
|
||
card["tags"].add(tag)
|
||
card["users"].add(n["name"])
|
||
return cid
|
||
|
||
def bal_card(ctx: dict, tag: str) -> str | None:
|
||
bid = f"bal:{ctx['id']}:{tag}"
|
||
if bid in bals:
|
||
return bid
|
||
b = ctx["balancers"].get(tag)
|
||
if b is None:
|
||
warn(f"{ctx['node']['name']}: правило ведёт в несуществующий балансер {tag}", ctx["id"])
|
||
return None
|
||
sels = [str(s) for s in _as_list(b.get("selector"))]
|
||
member_tags = [t for t in ctx["outbounds"] if any(str(t).startswith(s) for s in sels)]
|
||
members = list(dict.fromkeys(out_card(ctx, t) for t in member_tags))
|
||
fb = b.get("fallbackTag")
|
||
fb_id = out_card(ctx, fb) if fb in ctx["outbounds"] else None
|
||
live = [m for m in members if outs[m]["alive"]]
|
||
bals[bid] = {"id": bid, "tag": tag, "strategy": (b.get("strategy") or {}).get("type"),
|
||
"members": members, "aliveMembers": live, "alive": bool(live),
|
||
"node": ctx["node"]["name"]}
|
||
for m in members: # fallback, входящий в селектор, помечается на ребре члена
|
||
add_edge(bid, "out", m, "in", "member", "fallback" if m == fb_id else None,
|
||
dead=not outs[m]["alive"])
|
||
if fb_id and fb_id not in members:
|
||
add_edge(bid, "out", fb_id, "in", "fallback", "fallback", dead=not outs[fb_id]["alive"])
|
||
if not live:
|
||
warn(f"{ctx['node']['name']}: балансер {tag} без живых членов", bid)
|
||
return bid
|
||
|
||
# --- хосты: к какой ноде ведут ---
|
||
plans = []
|
||
for h in hosts:
|
||
inb_uuid = (h.get("inbound") or {}).get("configProfileInboundUuid")
|
||
if not inb_uuid:
|
||
continue
|
||
cand = [by_uuid[u] for u in h.get("nodes") or [] if u in by_uuid]
|
||
if not cand:
|
||
cand = [n for n in nodes if any(a.get("uuid") == inb_uuid for a in
|
||
(n.get("configProfile") or {}).get("activeInbounds") or [])]
|
||
if len(cand) != 1:
|
||
warn(f"хост {h['remark']}: привязан к {len(cand)} нодам, ожидается ровно одна", f"host:{h['uuid']}")
|
||
plans.append((h, inb_uuid, [ctx_of(n) for n in cand]))
|
||
|
||
# --- обход нод: цели строк, outbound'ы, ноды-приёмники ---
|
||
while queue:
|
||
ctx = queue.pop(0)
|
||
for sec in ctx["sections"]:
|
||
shadowed = [r["index"] for r in sec["rows"] if r["shadowed"]]
|
||
if shadowed:
|
||
warn(f"{ctx['node']['name']} / {sec['tag']}: недостижимы правила {ranges(shadowed)} "
|
||
f"(выше catch-all #{sec['catchAll']})", ctx["id"])
|
||
for r in sec["rows"]:
|
||
if r["shadowed"] or not r["targetTag"]:
|
||
continue
|
||
cid = (out_card(ctx, r["targetTag"]) if r["targetKind"] == "outbound"
|
||
else bal_card(ctx, r["targetTag"]))
|
||
r["tid"] = cid
|
||
if cid:
|
||
r["edge"] = add_edge(ctx["id"], f"rout:{sec['uuid']}:{r['key']}", cid, "in",
|
||
"target", dead=not alive_of(cid))
|
||
|
||
# --- пути хостов ---
|
||
def section_of(ctx: dict, uuid: str | None) -> dict | None:
|
||
return next((s for s in ctx["sections"] if s["uuid"] == uuid), None)
|
||
|
||
def walk(ctx: dict, uuid: str | None, route: int | None, path: dict, seen: set) -> None:
|
||
if (ctx["id"], uuid) in seen:
|
||
return
|
||
seen.add((ctx["id"], uuid))
|
||
path["nodes"].add(ctx["id"])
|
||
rows = path["rows"].setdefault(ctx["id"], {"active": set(), "pass": set()})
|
||
sec = section_of(ctx, uuid)
|
||
if sec is None:
|
||
return
|
||
rows["active"].add(f"inb:{sec['uuid']}")
|
||
trace = trace_rows(sec["rows"], route)
|
||
if trace:
|
||
last = sec["rows"].index(trace[-1])
|
||
in_trace = {id(r) for r in trace}
|
||
for r in sec["rows"][: last + 1]:
|
||
rows["active" if id(r) in in_trace else "pass"].add(f"{sec['uuid']}:{r['key']}")
|
||
for r in trace:
|
||
if r["tid"]:
|
||
path["edges"].add(r["edge"])
|
||
follow(r["tid"], path, seen)
|
||
|
||
def follow(cid: str, path: dict, seen: set) -> None:
|
||
path["nodes"].add(cid)
|
||
if cid in bals:
|
||
for m in bals[cid]["members"]:
|
||
path["edges"].add(E(cid, "out", m, "in"))
|
||
follow_out(m, path, seen)
|
||
else:
|
||
follow_out(cid, path, seen)
|
||
|
||
def follow_out(oid: str, path: dict, seen: set) -> None:
|
||
path["nodes"].add(oid)
|
||
d = outs[oid]["dest"]
|
||
if d:
|
||
path["edges"].add(d["edge"])
|
||
walk(ctxs[d["node"]], d["uuid"], None, path, seen) # трафик моста: vlessRoute неизвестен
|
||
|
||
host_nodes: list[dict] = []
|
||
paths: dict[str, dict] = {}
|
||
for h, inb_uuid, cands in sorted(
|
||
plans, key=lambda p: (p[2][0]["node"]["name"] if p[2] else "", p[0].get("vlessRouteId") is None,
|
||
p[0].get("vlessRouteId") or 0, p[0]["remark"])):
|
||
hid = f"host:{h['uuid']}"
|
||
route = h.get("vlessRouteId")
|
||
path = {"nodes": {hid}, "edges": set(), "rows": {}}
|
||
seen: set = set()
|
||
exit_alive, tag = False, None
|
||
for ctx in cands:
|
||
sec = section_of(ctx, inb_uuid)
|
||
state = node_state(ctx["node"])
|
||
if sec is None:
|
||
th = "head"
|
||
warn(f"хост {h['remark']}: инбаунд хоста не активен на ноде {ctx['node']['name']}", hid)
|
||
else:
|
||
tag = sec["tag"]
|
||
trace = trace_rows(sec["rows"], route)
|
||
th = f"rin:{sec['uuid']}:{trace[-1]['key']}" if trace else f"inb:{sec['uuid']}"
|
||
last_tid = trace[-1]["tid"] if trace else None
|
||
exit_alive = exit_alive or (state == "online" and last_tid is not None and alive_of(last_tid))
|
||
path["edges"].add(add_edge(hid, "out", ctx["id"], th, "host",
|
||
f"route {route}" if route is not None else None,
|
||
dead=state != "online"))
|
||
walk(ctx, inb_uuid, route, path, seen)
|
||
host_nodes.append({"id": hid, "type": "host", "label": h["remark"], "data": {
|
||
"address": h.get("address"), "port": h.get("port"), "vlessRouteId": route,
|
||
"disabled": bool(h.get("isDisabled")), "nodeNames": [c["node"]["name"] for c in cands],
|
||
"inboundTag": tag, "exitAlive": exit_alive}})
|
||
paths[hid] = {"nodes": sorted(path["nodes"]), "edges": sorted(path["edges"]),
|
||
"rows": {k: {"active": sorted(v["active"]), "pass": sorted(v["pass"])}
|
||
for k, v in path["rows"].items()}}
|
||
|
||
# --- карточки ---
|
||
node_cards = []
|
||
for ctx in ctxs.values():
|
||
p = ctx["profile"]
|
||
node_cards.append({"id": ctx["id"], "type": "node", "label": ctx["node"]["name"], "data": {
|
||
**node_info(ctx["node"]),
|
||
"profile": {"uuid": p["uuid"], "name": p["name"]} if p else None,
|
||
"sections": [{
|
||
"uuid": s["uuid"], "tag": s["tag"], "port": s["port"], "protocol": s["protocol"],
|
||
"rows": [{"key": r["key"], "index": r["index"], "label": r["label"], "common": r["common"],
|
||
"shadowed": r["shadowed"], "default": r["default"], "vlessRoute": r["vlessRoute"],
|
||
"targetKind": r["targetKind"], "target": r["targetTag"],
|
||
"hasEdge": r["edge"] is not None} for r in s["rows"]],
|
||
} for s in ctx["sections"]]}})
|
||
bal_cards = [{"id": b["id"], "type": "balancer", "label": b["tag"], "data": {
|
||
"strategy": b["strategy"], "members": b["members"], "aliveMembers": b["aliveMembers"],
|
||
"alive": b["alive"], "node": b["node"]}} for b in bals.values()]
|
||
out_cards = [{"id": o["id"], "type": "outbound", "label": " · ".join(sorted(o["tags"])), "data": {
|
||
"protocol": o["protocol"], "address": o["address"], "port": o["port"], "alive": o["alive"],
|
||
"users": sorted(o["users"]), "destName": o["destName"], "exit": o["exit"], "owner": o["owner"]}}
|
||
for o in outs.values()]
|
||
|
||
return {"nodes": host_nodes + node_cards + bal_cards + out_cards, "edges": edges,
|
||
"warnings": warnings, "paths": paths}
|