fix topology of cards
This commit is contained in:
@@ -28,7 +28,6 @@ class Settings:
|
||||
http_timeout: float = 10.0
|
||||
verify_tls: bool = True
|
||||
extra_headers: dict[str, str] = field(default_factory=dict)
|
||||
default_profile: str | None = None
|
||||
data_dir: Path = Path("data")
|
||||
basic_user: str | None = None
|
||||
basic_password: str | None = None
|
||||
@@ -59,7 +58,6 @@ class Settings:
|
||||
http_timeout=float(os.environ.get("HTTP_TIMEOUT", "10")),
|
||||
verify_tls=_bool(os.environ.get("VERIFY_TLS"), True),
|
||||
extra_headers=extra,
|
||||
default_profile=os.environ.get("DEFAULT_PROFILE", "").strip() or None,
|
||||
data_dir=Path(os.environ.get("DATA_DIR", "data")),
|
||||
basic_user=os.environ.get("BASIC_AUTH_USER") or None,
|
||||
basic_password=os.environ.get("BASIC_AUTH_PASSWORD") or None,
|
||||
|
||||
+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}
|
||||
|
||||
+8
-49
@@ -9,69 +9,33 @@ from .remnawave import RemnawaveError
|
||||
|
||||
bp = Blueprint("api", __name__, url_prefix="/api")
|
||||
|
||||
|
||||
class ProfileNotFound(LookupError):
|
||||
pass
|
||||
NETWORK_KEY = "network-v2" # ключ, под которым хранится раскладка всей сети
|
||||
|
||||
|
||||
def _svc():
|
||||
return current_app.extensions["rwviz"]
|
||||
|
||||
|
||||
def _rules(profile: dict) -> list[dict]:
|
||||
return ((profile.get("config") or {}).get("routing") or {}).get("rules") or []
|
||||
|
||||
|
||||
def pick_profile(profiles: list[dict], wanted: str | None, default: str | None) -> dict | None:
|
||||
profiles = [p for p in profiles if isinstance(p.get("config"), dict)]
|
||||
key = (wanted or default or "").strip().lower()
|
||||
if key:
|
||||
for p in profiles:
|
||||
if p["uuid"].lower() == key or p["name"].lower() == key:
|
||||
return p
|
||||
raise ProfileNotFound(wanted or default)
|
||||
for p in profiles: # по умолчанию - первый профиль с vlessRoute
|
||||
if any("vlessRoute" in r for r in _rules(p)):
|
||||
return p
|
||||
return profiles[0] if profiles else None
|
||||
|
||||
|
||||
@bp.get("/health")
|
||||
def health():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@bp.get("/profiles")
|
||||
def profiles():
|
||||
snap, meta = _svc().cache.get()
|
||||
items = [{
|
||||
"uuid": p["uuid"],
|
||||
"name": p["name"],
|
||||
"inbounds": len(p.get("inbounds") or []),
|
||||
"rules": len(_rules(p)),
|
||||
"nodes": [n.get("name") for n in p.get("nodes") or []],
|
||||
} for p in snap["profiles"] if isinstance(p.get("config"), dict)]
|
||||
return jsonify({"profiles": items, "meta": {**meta, "fetchedAt": snap["fetchedAt"]}})
|
||||
|
||||
|
||||
@bp.get("/graph")
|
||||
def graph():
|
||||
svc = _svc()
|
||||
force = request.args.get("refresh", "").lower() in {"1", "true", "yes"}
|
||||
snap, meta = svc.cache.get(force=force)
|
||||
profile = pick_profile(snap["profiles"], request.args.get("profile"), svc.settings.default_profile)
|
||||
if profile is None:
|
||||
return jsonify(error="no_profiles", message="В панели нет config-профилей"), 404
|
||||
try:
|
||||
result = build_graph(profile, snap["hosts"], snap["nodes"])
|
||||
result = build_graph(snap["profiles"], snap["hosts"], snap["nodes"])
|
||||
except (KeyError, TypeError, ValueError) as e:
|
||||
current_app.logger.exception("graph build failed")
|
||||
return jsonify(error="graph_build_failed",
|
||||
message=f"Не удалось разобрать профиль {profile['name']!r}: {type(e).__name__}: {e}"), 422
|
||||
message=f"Не удалось разобрать данные панели: {type(e).__name__}: {e}"), 422
|
||||
return jsonify({
|
||||
"profile": {"uuid": profile["uuid"], "name": profile["name"]},
|
||||
"graph": result,
|
||||
"positions": svc.positions.get(profile["uuid"]),
|
||||
"positionsKey": NETWORK_KEY,
|
||||
"positions": svc.positions.get(NETWORK_KEY),
|
||||
"meta": {**meta, "fetchedAt": snap["fetchedAt"]},
|
||||
})
|
||||
|
||||
@@ -79,14 +43,14 @@ def graph():
|
||||
@bp.get("/positions/<key>")
|
||||
def get_positions(key: str):
|
||||
if not valid_key(key):
|
||||
return jsonify(error="bad_key", message="Некорректный идентификатор профиля"), 400
|
||||
return jsonify(error="bad_key", message="Некорректный идентификатор раскладки"), 400
|
||||
return jsonify({"positions": _svc().positions.get(key)})
|
||||
|
||||
|
||||
@bp.put("/positions/<key>")
|
||||
def put_positions(key: str):
|
||||
if not valid_key(key):
|
||||
return jsonify(error="bad_key", message="Некорректный идентификатор профиля"), 400
|
||||
return jsonify(error="bad_key", message="Некорректный идентификатор раскладки"), 400
|
||||
body = request.get_json(silent=True)
|
||||
if not isinstance(body, dict) or "positions" not in body:
|
||||
return jsonify(error="bad_body", message='Ожидается {"positions": {...}}'), 400
|
||||
@@ -101,7 +65,7 @@ def put_positions(key: str):
|
||||
@bp.delete("/positions/<key>")
|
||||
def delete_positions(key: str):
|
||||
if not valid_key(key):
|
||||
return jsonify(error="bad_key", message="Некорректный идентификатор профиля"), 400
|
||||
return jsonify(error="bad_key", message="Некорректный идентификатор раскладки"), 400
|
||||
_svc().positions.delete(key)
|
||||
return "", 204
|
||||
|
||||
@@ -109,8 +73,3 @@ def delete_positions(key: str):
|
||||
@bp.errorhandler(RemnawaveError)
|
||||
def _upstream(e: RemnawaveError):
|
||||
return jsonify(error=e.code, message=e.message), e.http_status
|
||||
|
||||
|
||||
@bp.errorhandler(ProfileNotFound)
|
||||
def _no_profile(e: ProfileNotFound):
|
||||
return jsonify(error="profile_not_found", message=f"Профиль {e} не найден"), 404
|
||||
|
||||
+57
-17
@@ -1,11 +1,17 @@
|
||||
"""Фикстура, повторяющая профиль BridgeOverNetbird и ноды из панели."""
|
||||
"""Фикстура сети: вход RU-01 (профиль Bridge) + 6 выходных нод (профиль Default)."""
|
||||
SC = ["domain:soundcloud.com", "domain:sndcdn.com", "domain:soundcloud.cloud"]
|
||||
BRIDGE_IPS = ["100.106.180.60", "100.106.64.26", "100.106.214.118",
|
||||
"100.106.134.18", "100.106.36.222", "100.106.221.7"]
|
||||
NODE_NAMES = ["FR-01", "NL-01", "FI-01", "NL-04", "CH-01", "BR-01"]
|
||||
EXIT_NAMES = ["FR-01", "NL-01", "FI-01", "NL-04", "CH-01", "BR-01"]
|
||||
|
||||
BRIDGE_UUID = "aaaaaaaa-0000-0000-0000-000000000001"
|
||||
DEFAULT_UUID = "bbbbbbbb-0000-0000-0000-000000000002"
|
||||
INB_BRIDGE = "inb-bridge" # RU_NODE_IN
|
||||
INB_VLESS = "inb-def-vless" # DEFAULT_IN, 443
|
||||
INB_SS = "inb-def-ss" # BRIDGE_SS_IN, 9999
|
||||
|
||||
|
||||
def make_profile() -> dict:
|
||||
def bridge_profile() -> dict:
|
||||
rules = [
|
||||
{"port": 25, "outboundTag": "BLOCK"},
|
||||
{"ip": ["geoip:private"], "outboundTag": "BLOCK"},
|
||||
@@ -32,25 +38,59 @@ def make_profile() -> dict:
|
||||
{"tag": "BRIDGE_AUTO", "selector": ["BRIDGE_"], "strategy": {"type": "leastPing"},
|
||||
"fallbackTag": "BRIDGE_1"}]},
|
||||
}
|
||||
return {"uuid": "aaaaaaaa-0000-0000-0000-000000000001", "name": "BridgeOverNetbird",
|
||||
"config": config, "inbounds": [{"uuid": "inb-1", "tag": "RU_NODE_IN"}],
|
||||
"nodes": [{"uuid": "n-ru", "name": "RU-01", "countryCode": "RU"}]}
|
||||
return {"uuid": BRIDGE_UUID, "name": "BridgeOverNetbird", "config": config,
|
||||
"inbounds": [{"uuid": INB_BRIDGE, "tag": "RU_NODE_IN", "type": "vless", "port": 443}]}
|
||||
|
||||
|
||||
def default_profile() -> dict:
|
||||
config = {
|
||||
"inbounds": [
|
||||
{"tag": "DEFAULT_IN", "port": 443, "protocol": "vless"},
|
||||
{"tag": "BRIDGE_SS_IN", "port": 9999, "protocol": "shadowsocks",
|
||||
"settings": {"password": "SECRET-SS"}},
|
||||
],
|
||||
"outbounds": [{"tag": "DIRECT", "protocol": "freedom"}, {"tag": "BLOCK", "protocol": "blackhole"}],
|
||||
"routing": {"rules": [
|
||||
{"protocol": ["bittorrent"], "outboundTag": "BLOCK"},
|
||||
{"ip": ["geoip:private"], "outboundTag": "BLOCK"},
|
||||
]},
|
||||
}
|
||||
return {"uuid": DEFAULT_UUID, "name": "Default", "config": config, "inbounds": [
|
||||
{"uuid": INB_VLESS, "tag": "DEFAULT_IN", "type": "vless", "port": 443},
|
||||
{"uuid": INB_SS, "tag": "BRIDGE_SS_IN", "type": "shadowsocks", "port": 9999}]}
|
||||
|
||||
|
||||
def make_profiles() -> list[dict]:
|
||||
return [default_profile(), bridge_profile()]
|
||||
|
||||
|
||||
def make_nodes() -> list[dict]:
|
||||
nodes = [{"name": n, "address": ip, "countryCode": "XX", "isConnected": True, "isDisabled": False,
|
||||
ru = {"uuid": "n-ru", "name": "RU-01", "address": "100.106.247.44", "countryCode": "RU",
|
||||
"isConnected": True, "isDisabled": False,
|
||||
"ips": [{"ip": "91.201.43.187", "status": "OUTBOUND"}, {"ip": "100.106.247.44", "status": "MANAGEMENT"}],
|
||||
"configProfile": {"activeConfigProfileUuid": BRIDGE_UUID, "activeInbounds": [{"uuid": INB_BRIDGE}]},
|
||||
"system": {"info": {"networkInterfaces": ["lo", "wt0"]}}}
|
||||
exits = [{"uuid": f"n-{i}", "name": n, "address": ip, "countryCode": "XX",
|
||||
"isConnected": True, "isDisabled": False,
|
||||
"ips": [{"ip": ip, "status": "MANAGEMENT"}, {"ip": f"1.1.1.{i}", "status": "OUTBOUND"}],
|
||||
"configProfile": {"activeConfigProfileUuid": DEFAULT_UUID,
|
||||
"activeInbounds": [{"uuid": INB_VLESS}, {"uuid": INB_SS}]},
|
||||
"system": {"info": {"networkInterfaces": ["lo", "wt0"]}}}
|
||||
for i, (n, ip) in enumerate(zip(NODE_NAMES, BRIDGE_IPS))]
|
||||
nodes.append({"name": "US-01", "address": "78.153.155.226", "ips": [], "system": None})
|
||||
return nodes
|
||||
for i, (n, ip) in enumerate(zip(EXIT_NAMES, BRIDGE_IPS))]
|
||||
unused = {"uuid": "n-us", "name": "US-01", "address": "78.153.155.226", "ips": [],
|
||||
"configProfile": {"activeConfigProfileUuid": None, "activeInbounds": []}, "system": None}
|
||||
return [ru, *exits, unused]
|
||||
|
||||
|
||||
def make_hosts() -> list[dict]:
|
||||
inbound = {"configProfileInboundUuid": "inb-1"}
|
||||
hosts = [{"uuid": f"h{r}", "remark": f"host-r{r}", "vlessRouteId": r, "inbound": inbound}
|
||||
for r in (3, 7, 8)]
|
||||
hosts.append({"uuid": "hn", "remark": "no-route", "vlessRouteId": None, "inbound": inbound})
|
||||
hosts.append({"uuid": "hx", "remark": "other-profile", "vlessRouteId": 1,
|
||||
"inbound": {"configProfileInboundUuid": "foreign"}})
|
||||
return hosts
|
||||
def host(uuid, remark, node, inbound, route=None):
|
||||
return {"uuid": uuid, "remark": remark, "address": "node-ru.example", "port": 443,
|
||||
"vlessRouteId": route, "nodes": [node],
|
||||
"inbound": {"configProfileUuid": "x", "configProfileInboundUuid": inbound}}
|
||||
return [
|
||||
host("h3", "Bridge-Ivi", "n-ru", INB_BRIDGE, 3),
|
||||
host("h7", "Bridge-Auto", "n-ru", INB_BRIDGE, 7),
|
||||
host("h8", "Bridge-Mira-SC", "n-ru", INB_BRIDGE, 8),
|
||||
host("hn", "Bridge-NoRoute", "n-ru", INB_BRIDGE, None),
|
||||
host("hd", "Direct-FI", "n-2", INB_VLESS), # прямое подключение к выходной ноде
|
||||
]
|
||||
|
||||
@@ -5,9 +5,9 @@ import pytest
|
||||
from app import create_app
|
||||
from app.config import Settings
|
||||
from app.remnawave import RemnawaveError
|
||||
from .fixtures import make_hosts, make_nodes, make_profile
|
||||
from .fixtures import make_hosts, make_nodes, make_profiles
|
||||
|
||||
KEY = "aaaaaaaa-0000-0000-0000-000000000001"
|
||||
KEY = "network-v2"
|
||||
|
||||
|
||||
class FakeClient:
|
||||
@@ -19,9 +19,7 @@ class FakeClient:
|
||||
self.calls += 1
|
||||
if self.fail:
|
||||
raise RemnawaveError("панель недоступна", "upstream_unreachable")
|
||||
other = {"uuid": "bbbbbbbb-0000-0000-0000-000000000002", "name": "Default",
|
||||
"config": {"inbounds": [], "outbounds": [], "routing": {"rules": []}}, "inbounds": []}
|
||||
return {"profiles": [other, make_profile()], "hosts": make_hosts(), "nodes": make_nodes()}
|
||||
return {"profiles": make_profiles(), "hosts": make_hosts(), "nodes": make_nodes()}
|
||||
|
||||
|
||||
def make_settings(tmp_path, **kw):
|
||||
@@ -37,29 +35,18 @@ def client_and_fake(tmp_path):
|
||||
return app.test_client(), fake
|
||||
|
||||
|
||||
def test_graph_default_profile_is_the_one_with_vless_route(client_and_fake):
|
||||
def test_graph_endpoint_returns_whole_network(client_and_fake):
|
||||
c, _ = client_and_fake
|
||||
r = c.get("/api/graph")
|
||||
assert r.status_code == 200
|
||||
body = r.get_json()
|
||||
assert body["profile"]["name"] == "BridgeOverNetbird"
|
||||
assert body["graph"]["warnings"]
|
||||
g = body["graph"]
|
||||
assert {n["type"] for n in g["nodes"]} == {"host", "node", "balancer", "outbound"}
|
||||
assert g["warnings"] and g["paths"]
|
||||
assert body["positionsKey"] == KEY
|
||||
assert "SECRET" not in r.get_data(as_text=True)
|
||||
|
||||
|
||||
def test_profile_by_name_and_unknown(client_and_fake):
|
||||
c, _ = client_and_fake
|
||||
assert c.get("/api/graph?profile=default").get_json()["profile"]["name"] == "Default"
|
||||
r = c.get("/api/graph?profile=nope")
|
||||
assert r.status_code == 404 and r.get_json()["error"] == "profile_not_found"
|
||||
|
||||
|
||||
def test_profiles_list(client_and_fake):
|
||||
c, _ = client_and_fake
|
||||
names = [p["name"] for p in c.get("/api/profiles").get_json()["profiles"]]
|
||||
assert names == ["Default", "BridgeOverNetbird"]
|
||||
|
||||
|
||||
def test_cache_and_refresh_throttle(client_and_fake):
|
||||
c, fake = client_and_fake
|
||||
c.get("/api/graph"); c.get("/api/graph"); c.get("/api/profiles")
|
||||
|
||||
+209
-52
@@ -2,96 +2,253 @@ import copy
|
||||
|
||||
import pytest
|
||||
|
||||
from app.graph import build_graph, parse_vless_route
|
||||
from .fixtures import make_hosts, make_nodes, make_profile
|
||||
from app.graph import build_graph, parse_vless_route, ranges
|
||||
from .fixtures import (EXIT_NAMES, INB_BRIDGE, INB_SS, INB_VLESS, make_hosts, make_nodes, make_profiles)
|
||||
|
||||
|
||||
def build(profiles=None, hosts=None, nodes=None):
|
||||
return build_graph(profiles or make_profiles(), hosts or make_hosts(), nodes or make_nodes())
|
||||
|
||||
|
||||
def by_id(g):
|
||||
return {n["id"]: n for n in g["nodes"]}
|
||||
|
||||
|
||||
def targets(g, src):
|
||||
return [e["target"] for e in g["edges"] if e["source"] == src]
|
||||
def edges_from(g, src):
|
||||
return [e for e in g["edges"] if e["source"] == src]
|
||||
|
||||
|
||||
def card_by_name(g, name):
|
||||
return next(n for n in g["nodes"] if n["type"] == "node" and n["label"] == name)
|
||||
|
||||
|
||||
def out_card(g, tag):
|
||||
return next(n for n in g["nodes"] if n["type"] == "outbound" and tag in n["label"].split(" · "))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def g():
|
||||
return build_graph(make_profile(), make_hosts(), make_nodes())
|
||||
return build()
|
||||
|
||||
|
||||
def test_parse_vless_route():
|
||||
def test_parse_vless_route_and_ranges():
|
||||
assert parse_vless_route(None) is None
|
||||
assert parse_vless_route(5) == {5}
|
||||
assert parse_vless_route("8-14") == set(range(8, 15))
|
||||
assert parse_vless_route("1,3,8-10") == {1, 3, 8, 9, 10}
|
||||
assert ranges([14, 15, 16, 20]) == "#14–#16, #20"
|
||||
|
||||
|
||||
def test_all_bridges_resolve(g):
|
||||
assert not [n for n in g["nodes"] if n["type"] == "unresolved"]
|
||||
expected = {"BRIDGE_1": "FR-01", "BRIDGE_2": "NL-01", "BRIDGE_3": "FI-01",
|
||||
"BRIDGE_4": "NL-04", "BRIDGE_5": "CH-01", "BRIDGE_6": "BR-01"}
|
||||
for out, node in expected.items():
|
||||
assert targets(g, f"out:{out}") == [f"node:{node}"]
|
||||
assert "node:US-01" not in by_id(g)
|
||||
def test_each_host_has_exactly_one_thread_to_its_node(g):
|
||||
for h in (n for n in g["nodes"] if n["type"] == "host"):
|
||||
assert len(edges_from(g, h["id"])) == 1
|
||||
assert {n["id"] for n in g["nodes"] if n["type"] == "host"} == {"host:h3", "host:h7", "host:h8", "host:hn", "host:hd"}
|
||||
|
||||
|
||||
def test_shadowed_rules(g):
|
||||
shadowed = [n["data"]["index"] for n in g["nodes"] if n["type"] == "rule" and n["data"]["shadowed"]]
|
||||
assert shadowed == list(range(14, 22))
|
||||
assert sum("недостижимо" in w for w in g["warnings"]) == 8
|
||||
def test_bridge_host_lands_on_its_rule_row(g):
|
||||
land = {e["source"]: e["targetHandle"] for e in g["edges"] if e["kind"] == "host"}
|
||||
assert land["host:h3"] == f"rin:{INB_BRIDGE}:8" # vlessRoute 3 -> BRIDGE_3
|
||||
assert land["host:h7"] == f"rin:{INB_BRIDGE}:12" # vlessRoute 7 -> балансер
|
||||
assert land["host:h8"] == f"rin:{INB_BRIDGE}:13" # route 8 упирается в catch-all
|
||||
assert land["host:hn"] == f"rin:{INB_BRIDGE}:13"
|
||||
e3 = next(e for e in g["edges"] if e["source"] == "host:h3")
|
||||
assert e3["target"] == "node:n-ru" and e3["label"] == "route 3"
|
||||
|
||||
|
||||
def test_host_trace(g):
|
||||
b = by_id(g)
|
||||
assert b["host:h3"]["data"]["trace"][-1] == "rule:8" # route 3 -> BRIDGE_3
|
||||
assert b["host:h7"]["data"]["trace"][-1] == "rule:12" # route 7 -> BRIDGE_AUTO
|
||||
assert b["host:h8"]["data"]["trace"][-1] == "rule:13" # route 8 упирается в catch-all
|
||||
assert b["host:hn"]["data"]["trace"][-1] == "rule:13"
|
||||
assert "host:hx" not in b # хост другого профиля
|
||||
def test_direct_host_lands_on_default_row_of_exit_node(g):
|
||||
e = next(e for e in g["edges"] if e["source"] == "host:hd")
|
||||
assert e["target"] == "node:n-2"
|
||||
assert e["targetHandle"] == f"rin:{INB_VLESS}:default" # правила условные -> дальше "по умолчанию"
|
||||
|
||||
|
||||
def test_node_card_sections_and_rows(g):
|
||||
ru = card_by_name(g, "RU-01")["data"]
|
||||
assert ru["profile"]["name"] == "BridgeOverNetbird"
|
||||
(sec,) = ru["sections"]
|
||||
assert (sec["tag"], sec["port"], sec["protocol"]) == ("RU_NODE_IN", 443, "vless")
|
||||
assert len(sec["rows"]) == 22
|
||||
assert [r["index"] for r in sec["rows"] if r["shadowed"]] == list(range(14, 22))
|
||||
assert all(not r["hasEdge"] for r in sec["rows"] if r["shadowed"])
|
||||
fi = card_by_name(g, "FI-01")["data"]
|
||||
assert [s["tag"] for s in fi["sections"]] == ["DEFAULT_IN", "BRIDGE_SS_IN"]
|
||||
assert all(s["rows"][-1]["default"] for s in fi["sections"])
|
||||
assert all(r["common"] for s in fi["sections"] for r in s["rows"])
|
||||
|
||||
|
||||
def test_shadowed_warning_is_aggregated(g):
|
||||
w = [w["text"] for w in g["warnings"] if "недостижимы" in w["text"]]
|
||||
assert w == ["RU-01 / RU_NODE_IN: недостижимы правила #14–#21 (выше catch-all #13)"]
|
||||
|
||||
|
||||
def test_bridge_outbound_leads_to_exit_nodes_inbound_row(g):
|
||||
o = out_card(g, "BRIDGE_3")
|
||||
assert o["data"]["destName"] == "FI-01"
|
||||
(link,) = edges_from(g, o["id"])
|
||||
assert (link["target"], link["targetHandle"]) == ("node:n-2", f"inb:{INB_SS}")
|
||||
assert link["label"] == "100.106.214.118:9999"
|
||||
|
||||
|
||||
def test_outbound_shared_by_several_nodes_is_one_card():
|
||||
nodes = make_nodes()
|
||||
ru2 = copy.deepcopy(nodes[0])
|
||||
ru2.update(uuid="n-ru2", name="RU-02", address="100.106.247.45")
|
||||
ru2["ips"] = [{"ip": "100.106.247.45", "status": "MANAGEMENT"}]
|
||||
g = build(nodes=[*nodes, ru2], hosts=make_hosts() + [
|
||||
{"uuid": "h-ru2", "remark": "Bridge-RU2", "vlessRouteId": 3, "nodes": ["n-ru2"],
|
||||
"inbound": {"configProfileInboundUuid": INB_BRIDGE}}])
|
||||
cards = [n for n in g["nodes"] if n["type"] == "outbound" and "BRIDGE_3" in n["label"]]
|
||||
assert len(cards) == 1
|
||||
assert cards[0]["data"]["users"] == ["RU-01", "RU-02"]
|
||||
# а вот DIRECT у каждой ноды свой: у него разные публичные IP
|
||||
directs = [n for n in g["nodes"] if n["type"] == "outbound" and n["data"]["protocol"] == "freedom"]
|
||||
assert len({n["data"]["owner"] for n in directs}) == len(directs) >= 2
|
||||
|
||||
|
||||
def test_blackhole_is_shared_but_direct_is_per_node(g):
|
||||
blocks = [n for n in g["nodes"] if n["type"] == "outbound" and n["data"]["protocol"] == "blackhole"]
|
||||
assert len(blocks) == 1 and blocks[0]["data"]["users"] == sorted(["RU-01", *EXIT_NAMES])
|
||||
directs = [n for n in g["nodes"] if n["type"] == "outbound" and n["data"]["protocol"] == "freedom"]
|
||||
assert sorted(n["data"]["owner"] for n in directs) == sorted(["RU-01", *EXIT_NAMES])
|
||||
assert all(n["data"]["exit"] for n in directs) # у каждой ноды свой публичный IP
|
||||
|
||||
|
||||
def test_balancer_card_and_members(g):
|
||||
(bal,) = [n for n in g["nodes"] if n["type"] == "balancer"]
|
||||
assert bal["label"] == "BRIDGE_AUTO" and len(bal["data"]["members"]) == 6
|
||||
assert bal["data"]["aliveMembers"] == bal["data"]["members"]
|
||||
es = edges_from(g, bal["id"])
|
||||
assert {e["kind"] for e in es} == {"member"}
|
||||
assert [e["label"] for e in es if e["label"]] == ["fallback"] # BRIDGE_1 входит в селектор
|
||||
assert next(e for e in es if e["label"])["target"] == out_card(g, "BRIDGE_1")["id"]
|
||||
|
||||
|
||||
def test_fallback_outside_selector_gets_its_own_edge():
|
||||
profiles = make_profiles()
|
||||
profiles[1]["config"]["routing"]["balancers"][0]["fallbackTag"] = "DIRECT"
|
||||
g = build(profiles=profiles)
|
||||
(bal,) = [n for n in g["nodes"] if n["type"] == "balancer"]
|
||||
fb = [e for e in edges_from(g, bal["id"]) if e["kind"] == "fallback"]
|
||||
assert len(fb) == 1 and fb[0]["target"] == out_card(g, "DIRECT")["id"]
|
||||
|
||||
|
||||
def test_path_of_bridge_host_crosses_both_nodes(g):
|
||||
p = g["paths"]["host:h3"]
|
||||
o = out_card(g, "BRIDGE_3")["id"]
|
||||
assert {"node:n-ru", o, "node:n-2"} <= set(p["nodes"])
|
||||
assert "node:n-3" not in p["nodes"] # NL-04 не задействован
|
||||
ru = p["rows"]["node:n-ru"]
|
||||
assert f"{INB_BRIDGE}:8" in ru["active"] and f"{INB_BRIDGE}:0" in ru["active"]
|
||||
assert set(ru["pass"]) == {f"{INB_BRIDGE}:6", f"{INB_BRIDGE}:7"}
|
||||
fi = p["rows"]["node:n-2"]
|
||||
assert f"inb:{INB_SS}" in fi["active"] and f"{INB_SS}:default" in fi["active"]
|
||||
link = edges_from(g, o)[0]["id"]
|
||||
assert link in p["edges"]
|
||||
|
||||
|
||||
def test_path_through_balancer_reaches_every_member(g):
|
||||
p = g["paths"]["host:h7"]
|
||||
assert all(n in p["nodes"] for n in ("node:n-0", "node:n-1", "node:n-2", "node:n-3", "node:n-4", "node:n-5"))
|
||||
assert [n for n in p["nodes"] if n.startswith("bal:")]
|
||||
|
||||
|
||||
def test_direct_host_path_stays_on_one_node(g):
|
||||
p = g["paths"]["host:hd"]
|
||||
assert "node:n-ru" not in p["nodes"]
|
||||
assert f"{INB_VLESS}:default" in p["rows"]["node:n-2"]["active"]
|
||||
|
||||
|
||||
def test_unused_nodes_are_not_drawn(g):
|
||||
assert "node:n-us" not in by_id(g)
|
||||
|
||||
|
||||
def test_no_secrets_in_output(g):
|
||||
dump = str(g)
|
||||
assert "SECRET" not in dump
|
||||
assert "SECRET" not in str(g)
|
||||
|
||||
|
||||
def test_disabled_and_offline_nodes():
|
||||
def test_disabled_and_offline_exit_nodes():
|
||||
nodes = make_nodes()
|
||||
for n in nodes:
|
||||
if n["name"] == "NL-04":
|
||||
n["isDisabled"] = True
|
||||
if n["name"] == "BR-01":
|
||||
n["isConnected"] = False
|
||||
nodes.insert(0, {"name": "OLD-FR", "address": "100.106.180.60", "isDisabled": True,
|
||||
"ips": [{"ip": "100.106.180.60", "status": "MANAGEMENT"}], "system": None})
|
||||
g = build_graph(make_profile(), make_hosts(), nodes)
|
||||
b = by_id(g)
|
||||
assert targets(g, "out:BRIDGE_1") == ["node:FR-01"] # живая нода выигрывает у дубля
|
||||
assert b["node:NL-04"]["data"]["state"] == "disabled"
|
||||
assert b["node:BR-01"]["data"]["state"] == "offline"
|
||||
assert b["bal:BRIDGE_AUTO"]["data"]["aliveMembers"] == ["BRIDGE_1", "BRIDGE_2", "BRIDGE_3", "BRIDGE_5"]
|
||||
dead = {e["source"] for e in g["edges"] if e["kind"] == "link" and e["data"].get("dead")}
|
||||
assert dead == {"out:BRIDGE_4", "out:BRIDGE_6"}
|
||||
g = build(nodes=nodes)
|
||||
assert card_by_name(g, "NL-04")["data"]["state"] == "disabled"
|
||||
assert card_by_name(g, "BR-01")["data"]["state"] == "offline"
|
||||
dead = {e["source"] for e in g["edges"] if e["kind"] == "link" and e["data"]["dead"]}
|
||||
assert dead == {out_card(g, "BRIDGE_4")["id"], out_card(g, "BRIDGE_6")["id"]}
|
||||
(bal,) = [n for n in g["nodes"] if n["type"] == "balancer"]
|
||||
assert len(bal["data"]["aliveMembers"]) == 4
|
||||
assert any("нода disabled" in w["text"] for w in g["warnings"])
|
||||
|
||||
|
||||
def test_all_nodes_down_warns():
|
||||
def test_all_exits_down_warns_and_marks_hosts():
|
||||
nodes = make_nodes()
|
||||
for n in nodes:
|
||||
for n in nodes[1:]:
|
||||
n["isDisabled"] = True
|
||||
g = build_graph(make_profile(), make_hosts(), nodes)
|
||||
assert any("нет ни одного живого члена" in w for w in g["warnings"])
|
||||
assert by_id(g)["host:h3"]["data"]["exitAlive"] is False
|
||||
g = build(nodes=nodes)
|
||||
assert any("без живых членов" in w["text"] for w in g["warnings"])
|
||||
assert by_id(g)["host:h7"]["data"]["exitAlive"] is False
|
||||
|
||||
|
||||
def test_unresolved_outbound():
|
||||
def test_duplicate_disabled_node_with_same_address_does_not_win():
|
||||
nodes = make_nodes()
|
||||
nodes.insert(0, {"uuid": "n-old", "name": "OLD-FR", "address": BRIDGE_FIRST, "isDisabled": True,
|
||||
"ips": [{"ip": BRIDGE_FIRST, "status": "MANAGEMENT"}], "system": None,
|
||||
"configProfile": {"activeConfigProfileUuid": None, "activeInbounds": []}})
|
||||
g = build(nodes=nodes)
|
||||
assert out_card(g, "BRIDGE_1")["data"]["destName"] == "FR-01"
|
||||
|
||||
|
||||
BRIDGE_FIRST = "100.106.180.60"
|
||||
|
||||
|
||||
def test_unresolved_internal_address_is_flagged():
|
||||
nodes = [n for n in make_nodes() if n["name"] != "NL-04"]
|
||||
g = build_graph(make_profile(), make_hosts(), nodes)
|
||||
assert "unresolved:100.106.134.18" in by_id(g)
|
||||
assert any("не найден" in w for w in g["warnings"])
|
||||
g = build(nodes=nodes)
|
||||
o = out_card(g, "BRIDGE_4")
|
||||
assert o["data"]["alive"] is False and o["data"]["destName"] is None
|
||||
assert any("не найден" in w["text"] for w in g["warnings"])
|
||||
|
||||
|
||||
def test_host_not_bound_to_single_node_warns():
|
||||
hosts = make_hosts()
|
||||
hosts[0]["nodes"] = [] # пусто -> все ноды с этим инбаундом (здесь только RU-01)
|
||||
hosts[1]["nodes"] = ["n-ru", "n-2"]
|
||||
g = build(hosts=hosts)
|
||||
texts = [w["text"] for w in g["warnings"]]
|
||||
assert any("Bridge-Auto" in t and "2 нодам" in t for t in texts)
|
||||
assert len(edges_from(g, "host:h7")) == 2
|
||||
|
||||
|
||||
def test_host_inbound_not_active_on_node():
|
||||
hosts = make_hosts()
|
||||
hosts[4]["inbound"]["configProfileInboundUuid"] = INB_BRIDGE # у FI-01 такого инбаунда нет
|
||||
g = build(hosts=hosts)
|
||||
e = next(e for e in g["edges"] if e["source"] == "host:hd")
|
||||
assert e["targetHandle"] == "head"
|
||||
assert any("не активен на ноде FI-01" in w["text"] for w in g["warnings"])
|
||||
|
||||
|
||||
def test_missing_outbound_and_balancer_are_reported():
|
||||
profiles = make_profiles()
|
||||
profiles[1]["config"]["routing"]["rules"][0]["outboundTag"] = "NOPE"
|
||||
profiles[1]["config"]["routing"]["rules"][1]["balancerTag"] = "NOBAL"
|
||||
del profiles[1]["config"]["routing"]["rules"][1]["outboundTag"]
|
||||
g = build(profiles=profiles)
|
||||
texts = " | ".join(w["text"] for w in g["warnings"])
|
||||
assert "несуществующий outbound NOPE" in texts and "несуществующий балансер NOBAL" in texts
|
||||
|
||||
|
||||
def test_input_not_mutated():
|
||||
profile, hosts, nodes = make_profile(), make_hosts(), make_nodes()
|
||||
snapshot = copy.deepcopy((profile, hosts, nodes))
|
||||
build_graph(profile, hosts, nodes)
|
||||
assert (profile, hosts, nodes) == snapshot
|
||||
args = (make_profiles(), make_hosts(), make_nodes())
|
||||
snapshot = copy.deepcopy(args)
|
||||
build_graph(*args)
|
||||
assert args == snapshot
|
||||
|
||||
|
||||
def test_all_edge_endpoints_exist(g):
|
||||
ids = set(by_id(g))
|
||||
for e in g["edges"]:
|
||||
assert e["source"] in ids and e["target"] in ids, e["id"]
|
||||
assert len({e["id"] for e in g["edges"]}) == len(g["edges"])
|
||||
for p in g["paths"].values():
|
||||
assert set(p["edges"]) <= {e["id"] for e in g["edges"]}
|
||||
|
||||
Reference in New Issue
Block a user