fix topology of cards
This commit is contained in:
+374
-144
@@ -1,15 +1,27 @@
|
||||
"""Сборка графа маршрутизации Remnawave: профиль + хосты + ноды -> {nodes, edges, warnings}.
|
||||
"""Граф сети Remnawave: хост -> нода (профиль: инбаунды + правила) -> балансер/outbound -> нода ...
|
||||
|
||||
Колонки слева направо: host -> inbound -> rule(ы) -> balancer -> outbound -> node.
|
||||
Только чтение, без статистики и юзеров.
|
||||
Только чтение. Секреты конфигов (ключи, пароли) в граф не попадают.
|
||||
|
||||
Модель:
|
||||
* хост ведёт ровно на одну ноду и садится на строку правила, которое для него срабатывает;
|
||||
* карточка ноды содержит секции активных инбаундов, в секции строки-правила по порядку
|
||||
(правила инбаунда + общие без 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:
|
||||
@@ -36,43 +48,48 @@ def _opaque(rule: dict) -> set[str]:
|
||||
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)):
|
||||
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 "любой трафик"
|
||||
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 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"):
|
||||
@@ -109,8 +126,6 @@ def node_info(n: dict) -> dict:
|
||||
"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"),
|
||||
@@ -119,134 +134,349 @@ def node_info(n: dict) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def outbound_ip(ob: dict) -> str | None:
|
||||
# ---------------------------------------------------------------- outbound'ы
|
||||
def _port(v) -> int | None:
|
||||
try:
|
||||
return ob["settings"]["servers"][0]["address"]
|
||||
except (KeyError, IndexError, TypeError):
|
||||
return None # freedom / blackhole
|
||||
return int(v)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
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}
|
||||
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
|
||||
|
||||
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 _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 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 _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 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"))
|
||||
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
|
||||
|
||||
# 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])
|
||||
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")
|
||||
if fb:
|
||||
add_edge(f"bal:{b['tag']}", f"out:{fb}", "fallback", "fallback",
|
||||
dead=not alive.get(fb, False))
|
||||
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:
|
||||
warnings.append(f"balancer {b['tag']}: нет ни одного живого члена")
|
||||
elif fb and not alive.get(fb, False):
|
||||
warnings.append(f"balancer {b['tag']}: fallback {fb} ведёт на нерабочую ноду")
|
||||
warn(f"{ctx['node']['name']}: балансер {tag} без живых членов", bid)
|
||||
return bid
|
||||
|
||||
# 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 [])}
|
||||
# --- хосты: к какой ноде ведут ---
|
||||
plans = []
|
||||
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} ведёт на нерабочую ноду")
|
||||
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]))
|
||||
|
||||
return {"nodes": G_nodes, "edges": G_edges, "warnings": warnings}
|
||||
# --- обход нод: цели строк, 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}
|
||||
|
||||
Reference in New Issue
Block a user