init commit
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
"""Flask-бэкенд визуализатора маршрутов Remnawave."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hmac
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from types import SimpleNamespace
|
||||
|
||||
from flask import Flask, abort, jsonify, request, send_from_directory
|
||||
|
||||
from .cache import SnapshotCache
|
||||
from .config import Settings
|
||||
from .positions import PositionStore
|
||||
from .remnawave import RemnawaveClient
|
||||
from .routes import bp
|
||||
|
||||
|
||||
def create_app(settings: Settings | None = None, client=None) -> Flask:
|
||||
settings = settings or Settings.from_env()
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||
if client is None:
|
||||
client = RemnawaveClient(settings.remnawave_url, settings.remnawave_token,
|
||||
settings.http_timeout, settings.verify_tls, settings.extra_headers)
|
||||
|
||||
def load():
|
||||
data = client.fetch_all()
|
||||
data["fetchedAt"] = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
return data
|
||||
|
||||
app = Flask(__name__)
|
||||
app.json.ensure_ascii = False
|
||||
app.config["MAX_CONTENT_LENGTH"] = 1024 * 1024
|
||||
app.extensions["rwviz"] = SimpleNamespace(
|
||||
settings=settings,
|
||||
cache=SnapshotCache(load, settings.cache_ttl),
|
||||
positions=PositionStore(settings.data_dir / "positions.json"),
|
||||
)
|
||||
app.register_blueprint(bp)
|
||||
|
||||
if settings.basic_user and settings.basic_password:
|
||||
want_user, want_pass = settings.basic_user, settings.basic_password
|
||||
|
||||
@app.before_request
|
||||
def _auth():
|
||||
if request.method == "OPTIONS" or request.path == "/api/health":
|
||||
return None
|
||||
a = request.authorization
|
||||
ok = (a is not None
|
||||
and hmac.compare_digest(a.username or "", want_user)
|
||||
and hmac.compare_digest(a.password or "", want_pass))
|
||||
if not ok:
|
||||
return jsonify(error="unauthorized", message="Нужна авторизация"), 401, {
|
||||
"WWW-Authenticate": 'Basic realm="rw-viz"'}
|
||||
return None
|
||||
else:
|
||||
logging.getLogger(__name__).warning(
|
||||
"BASIC_AUTH_USER/PASSWORD не заданы: API открыт всем, кто достанет до порта")
|
||||
|
||||
if settings.cors_origins:
|
||||
@app.after_request
|
||||
def _cors(resp):
|
||||
origin = request.headers.get("Origin")
|
||||
if origin in settings.cors_origins:
|
||||
resp.headers["Access-Control-Allow-Origin"] = origin
|
||||
resp.headers["Vary"] = "Origin"
|
||||
resp.headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization"
|
||||
resp.headers["Access-Control-Allow-Methods"] = "GET, PUT, DELETE, OPTIONS"
|
||||
return resp
|
||||
|
||||
dist = settings.frontend_dist
|
||||
if dist and dist.is_dir():
|
||||
@app.get("/", defaults={"path": ""})
|
||||
@app.get("/<path:path>")
|
||||
def _spa(path: str):
|
||||
if path.startswith("api/"):
|
||||
abort(404)
|
||||
if path and (dist / path).is_file():
|
||||
return send_from_directory(dist, path)
|
||||
return send_from_directory(dist, "index.html")
|
||||
|
||||
@app.errorhandler(404)
|
||||
def _404(_e):
|
||||
return jsonify(error="not_found", message="Не найдено"), 404
|
||||
|
||||
@app.errorhandler(413)
|
||||
def _413(_e):
|
||||
return jsonify(error="too_large", message="Слишком большое тело запроса"), 413
|
||||
|
||||
return app
|
||||
@@ -0,0 +1,37 @@
|
||||
"""TTL-кэш снимка панели. При ошибке панели отдаёт устаревший снимок."""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from typing import Any, Callable
|
||||
|
||||
from .remnawave import RemnawaveError
|
||||
|
||||
MIN_REFRESH_INTERVAL = 5.0 # ?refresh=1 не чаще, чем раз в 5 секунд
|
||||
|
||||
|
||||
class SnapshotCache:
|
||||
def __init__(self, loader: Callable[[], Any], ttl: float):
|
||||
self._loader = loader
|
||||
self._ttl = ttl
|
||||
self._lock = threading.Lock()
|
||||
self._value: Any = None
|
||||
self._at = 0.0
|
||||
|
||||
def get(self, force: bool = False) -> tuple[Any, dict]:
|
||||
with self._lock:
|
||||
age = time.monotonic() - self._at
|
||||
fresh = self._value is not None and age < self._ttl
|
||||
if force and age < MIN_REFRESH_INTERVAL:
|
||||
force = False
|
||||
if fresh and not force:
|
||||
return self._value, {"cached": True, "stale": False, "ageSeconds": round(age, 1)}
|
||||
try:
|
||||
self._value = self._loader()
|
||||
self._at = time.monotonic()
|
||||
return self._value, {"cached": False, "stale": False, "ageSeconds": 0.0}
|
||||
except RemnawaveError as e:
|
||||
if self._value is None:
|
||||
raise
|
||||
return self._value, {"cached": True, "stale": True,
|
||||
"ageSeconds": round(age, 1), "lastError": e.message}
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Настройки из переменных окружения."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
try: # python-dotenv необязателен: в Docker всё приходит из env_file
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
except ImportError: # pragma: no cover
|
||||
pass
|
||||
|
||||
|
||||
def _bool(value: str | None, default: bool) -> bool:
|
||||
if value is None or value == "":
|
||||
return default
|
||||
return value.strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Settings:
|
||||
remnawave_url: str
|
||||
remnawave_token: str
|
||||
cache_ttl: float = 30.0
|
||||
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
|
||||
frontend_dist: Path | None = None
|
||||
cors_origins: tuple[str, ...] = ()
|
||||
|
||||
@classmethod
|
||||
def from_env(cls) -> "Settings":
|
||||
url = os.environ.get("REMNAWAVE_URL", "").strip().rstrip("/")
|
||||
token = os.environ.get("REMNAWAVE_TOKEN", "").strip()
|
||||
if not url or not token:
|
||||
raise RuntimeError("Нужны переменные REMNAWAVE_URL и REMNAWAVE_TOKEN")
|
||||
|
||||
extra: dict[str, str] = {}
|
||||
raw_headers = os.environ.get("REMNAWAVE_EXTRA_HEADERS", "").strip()
|
||||
if raw_headers:
|
||||
try:
|
||||
extra = {str(k): str(v) for k, v in json.loads(raw_headers).items()}
|
||||
except (ValueError, AttributeError) as e:
|
||||
raise RuntimeError("REMNAWAVE_EXTRA_HEADERS должен быть JSON-объектом") from e
|
||||
|
||||
dist = os.environ.get("FRONTEND_DIST", "").strip()
|
||||
origins = tuple(o.strip() for o in os.environ.get("CORS_ORIGINS", "").split(",") if o.strip())
|
||||
return cls(
|
||||
remnawave_url=url,
|
||||
remnawave_token=token,
|
||||
cache_ttl=float(os.environ.get("CACHE_TTL", "30")),
|
||||
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,
|
||||
frontend_dist=Path(dist) if dist else None,
|
||||
cors_origins=origins,
|
||||
)
|
||||
@@ -0,0 +1,252 @@
|
||||
"""Сборка графа маршрутизации Remnawave: профиль + хосты + ноды -> {nodes, edges, warnings}.
|
||||
|
||||
Колонки слева направо: host -> inbound -> rule(ы) -> balancer -> outbound -> node.
|
||||
Только чтение, без статистики и юзеров.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
# Ключи правила, которые мы умеем вычислять точно (остальные = "условные").
|
||||
_TARGET_KEYS = {"outboundTag", "balancerTag", "ruleTag", "type"}
|
||||
_EXACT_KEYS = {"vlessRoute", "inboundTag"}
|
||||
|
||||
|
||||
def parse_vless_route(value) -> set[int] | None:
|
||||
"""1 | "8-14" | "1,3,8-10" -> множество номеров; None, если поля нет."""
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, int):
|
||||
return {value}
|
||||
out: set[int] = set()
|
||||
for part in str(value).split(","):
|
||||
part = part.strip()
|
||||
if "-" in part:
|
||||
a, b = part.split("-", 1)
|
||||
out.update(range(int(a), int(b) + 1))
|
||||
elif part:
|
||||
out.add(int(part))
|
||||
return out
|
||||
|
||||
|
||||
def _conditions(rule: dict) -> set[str]:
|
||||
return set(rule) - _TARGET_KEYS
|
||||
|
||||
|
||||
def _opaque(rule: dict) -> set[str]:
|
||||
"""Условия, которые нельзя вычислить статически (domain, ip, port, protocol...)."""
|
||||
return _conditions(rule) - _EXACT_KEYS
|
||||
|
||||
|
||||
def rule_label(rule: dict) -> str:
|
||||
parts = []
|
||||
for k in sorted(_conditions(rule)):
|
||||
v = rule[k]
|
||||
if isinstance(v, list):
|
||||
shown = ", ".join(map(str, v[:3])) + (f" +{len(v) - 3}" if len(v) > 3 else "")
|
||||
else:
|
||||
shown = str(v)
|
||||
parts.append(f"{k}: {shown}")
|
||||
return "; ".join(parts) or "любой трафик"
|
||||
|
||||
|
||||
def find_shadowed(rules: list[dict], inbound_tags: set[str]) -> set[int]:
|
||||
"""Правила после catch-all недостижимы (Xray: первое совпавшее правило выигрывает)."""
|
||||
for i, r in enumerate(rules):
|
||||
cond = _conditions(r)
|
||||
if not cond or (cond == {"inboundTag"} and set(r["inboundTag"]) >= inbound_tags):
|
||||
return set(range(i + 1, len(rules)))
|
||||
return set()
|
||||
|
||||
|
||||
def trace_host(rules: list[dict], route: int | None, inbound_tag: str) -> list[int]:
|
||||
"""Индексы правил, через которые может пройти трафик хоста, до первого безусловного."""
|
||||
path: list[int] = []
|
||||
for i, r in enumerate(rules):
|
||||
routes = parse_vless_route(r.get("vlessRoute"))
|
||||
if routes is not None and route not in routes:
|
||||
continue
|
||||
tags = r.get("inboundTag")
|
||||
if tags and inbound_tag not in tags:
|
||||
continue
|
||||
path.append(i)
|
||||
if not _opaque(r):
|
||||
break
|
||||
return path
|
||||
|
||||
|
||||
def node_state(n: dict) -> str:
|
||||
"""disabled | connecting | offline | online."""
|
||||
if n.get("isDisabled"):
|
||||
return "disabled"
|
||||
if n.get("isConnecting"):
|
||||
return "connecting"
|
||||
return "offline" if n.get("isConnected") is False else "online"
|
||||
|
||||
|
||||
def build_node_index(nodes: list[dict]) -> dict[str, dict]:
|
||||
"""ip -> нода. MANAGEMENT-адреса в приоритете, затем address, затем остальные ips.
|
||||
|
||||
Живые ноды идут первыми: если отключённая нода хранит тот же адрес, что и рабочая,
|
||||
выигрывает рабочая.
|
||||
"""
|
||||
ordered = sorted(nodes, key=lambda n: node_state(n) != "online") # sort стабильный
|
||||
idx: dict[str, dict] = {}
|
||||
for n in ordered:
|
||||
for e in n.get("ips") or []:
|
||||
if e["status"] == "MANAGEMENT":
|
||||
idx.setdefault(e["ip"], n)
|
||||
for n in ordered:
|
||||
idx.setdefault(n["address"], n)
|
||||
for e in n.get("ips") or []:
|
||||
idx.setdefault(e["ip"], n)
|
||||
return idx
|
||||
|
||||
|
||||
def node_info(n: dict) -> dict:
|
||||
ips = n.get("ips") or []
|
||||
by = lambda st: [e["ip"] for e in ips if e["status"] == st] # noqa: E731
|
||||
ifaces = ((n.get("system") or {}).get("info") or {}).get("networkInterfaces") or []
|
||||
return {
|
||||
"name": n["name"],
|
||||
"country": n.get("countryCode"),
|
||||
"state": node_state(n),
|
||||
"connected": n.get("isConnected"),
|
||||
"disabled": bool(n.get("isDisabled")),
|
||||
"mgmt": by("MANAGEMENT"),
|
||||
"exit": by("OUTBOUND"),
|
||||
"inbound": by("INBOUND"),
|
||||
"reserve": by("RESERVE"),
|
||||
"netbird": "wt0" in ifaces,
|
||||
}
|
||||
|
||||
|
||||
def outbound_ip(ob: dict) -> str | None:
|
||||
try:
|
||||
return ob["settings"]["servers"][0]["address"]
|
||||
except (KeyError, IndexError, TypeError):
|
||||
return None # freedom / blackhole
|
||||
|
||||
|
||||
def build_graph(profile: dict, hosts: list[dict], nodes: list[dict]) -> dict:
|
||||
cfg = profile["config"]
|
||||
rules = cfg.get("routing", {}).get("rules", [])
|
||||
balancers = cfg.get("routing", {}).get("balancers", [])
|
||||
outbounds = cfg.get("outbounds", [])
|
||||
inbounds = cfg.get("inbounds", [])
|
||||
inbound_tags = {i["tag"] for i in inbounds}
|
||||
|
||||
G_nodes: list[dict] = []
|
||||
G_edges: list[dict] = []
|
||||
warnings: list[str] = []
|
||||
|
||||
def add_node(id_, type_, label, **data):
|
||||
G_nodes.append({"id": id_, "type": type_, "label": label, "data": data})
|
||||
|
||||
def add_edge(src, dst, kind="flow", label=None, **data):
|
||||
G_edges.append({"id": f"{src}->{dst}:{kind}", "source": src, "target": dst,
|
||||
"kind": kind, "label": label, "data": data})
|
||||
|
||||
shadowed = find_shadowed(rules, inbound_tags)
|
||||
|
||||
idx = build_node_index(nodes)
|
||||
|
||||
def _out_alive(o: dict) -> bool:
|
||||
ip = outbound_ip(o)
|
||||
if ip is None: # freedom / blackhole
|
||||
return True
|
||||
n = idx.get(ip)
|
||||
return n is not None and node_state(n) == "online"
|
||||
|
||||
alive = {o["tag"]: _out_alive(o) for o in outbounds}
|
||||
bal_members = {
|
||||
b["tag"]: [o["tag"] for o in outbounds
|
||||
if any(o["tag"].startswith(x) for x in b.get("selector", []))]
|
||||
for b in balancers
|
||||
}
|
||||
|
||||
def target_alive(r: dict) -> bool:
|
||||
if "balancerTag" in r:
|
||||
return any(alive.get(m, False) for m in bal_members.get(r["balancerTag"], []))
|
||||
return alive.get(r.get("outboundTag"), False)
|
||||
|
||||
# inbounds
|
||||
for i in inbounds:
|
||||
add_node(f"inb:{i['tag']}", "inbound", i["tag"],
|
||||
port=i.get("port"), protocol=i.get("protocol"))
|
||||
|
||||
# rules + цепочка fallthrough + цель
|
||||
for i, r in enumerate(rules):
|
||||
rid = f"rule:{i}"
|
||||
add_node(rid, "rule", f"#{i} {rule_label(r)}", index=i, shadowed=i in shadowed,
|
||||
vlessRoute=sorted(parse_vless_route(r.get("vlessRoute")) or []))
|
||||
target = f"bal:{r['balancerTag']}" if "balancerTag" in r else f"out:{r.get('outboundTag')}"
|
||||
add_edge(rid, target, "target", dead=i in shadowed)
|
||||
if i + 1 < len(rules):
|
||||
add_edge(rid, f"rule:{i + 1}", "fallthrough", dead=(i + 1) in shadowed)
|
||||
if i in shadowed:
|
||||
warnings.append(f"rule #{i} ({rule_label(r)}) недостижимо: выше есть catch-all")
|
||||
if rules:
|
||||
for tag in inbound_tags:
|
||||
add_edge(f"inb:{tag}", "rule:0", "flow")
|
||||
|
||||
# balancers
|
||||
for b in balancers:
|
||||
members = bal_members[b["tag"]]
|
||||
live = [m for m in members if alive[m]]
|
||||
add_node(f"bal:{b['tag']}", "balancer", b["tag"],
|
||||
strategy=(b.get("strategy") or {}).get("type"), members=members,
|
||||
aliveMembers=live)
|
||||
for m in members:
|
||||
add_edge(f"bal:{b['tag']}", f"out:{m}", "member", dead=not alive[m])
|
||||
fb = b.get("fallbackTag")
|
||||
if fb:
|
||||
add_edge(f"bal:{b['tag']}", f"out:{fb}", "fallback", "fallback",
|
||||
dead=not alive.get(fb, False))
|
||||
if not live:
|
||||
warnings.append(f"balancer {b['tag']}: нет ни одного живого члена")
|
||||
elif fb and not alive.get(fb, False):
|
||||
warnings.append(f"balancer {b['tag']}: fallback {fb} ведёт на нерабочую ноду")
|
||||
|
||||
# outbounds -> ноды
|
||||
seen_nodes: set[str] = set()
|
||||
for o in outbounds:
|
||||
ip = outbound_ip(o)
|
||||
add_node(f"out:{o['tag']}", "outbound", o["tag"], protocol=o["protocol"], ip=ip,
|
||||
alive=alive[o["tag"]])
|
||||
if ip is None:
|
||||
continue
|
||||
n = idx.get(ip)
|
||||
if n is None:
|
||||
add_node(f"unresolved:{ip}", "unresolved", ip)
|
||||
add_edge(f"out:{o['tag']}", f"unresolved:{ip}", "link")
|
||||
warnings.append(f"outbound {o['tag']}: адрес {ip} не найден ни в одной карточке ноды")
|
||||
continue
|
||||
nid = f"node:{n['name']}"
|
||||
if nid not in seen_nodes:
|
||||
seen_nodes.add(nid)
|
||||
add_node(nid, "node", n["name"], **node_info(n))
|
||||
add_edge(f"out:{o['tag']}", nid, "link", ip, dead=not alive[o["tag"]])
|
||||
if not alive[o["tag"]]:
|
||||
warnings.append(f"outbound {o['tag']} → {n['name']}: нода {node_state(n)}")
|
||||
|
||||
# хосты профиля
|
||||
uuid_to_tag = {i["uuid"]: i["tag"] for i in (profile.get("inbounds") or [])}
|
||||
for h in hosts:
|
||||
tag = uuid_to_tag.get((h.get("inbound") or {}).get("configProfileInboundUuid"))
|
||||
if tag is None:
|
||||
continue # хост другого профиля
|
||||
route = h.get("vlessRouteId")
|
||||
path = trace_host(rules, route, tag)
|
||||
end = path[-1] if path else None
|
||||
hid = f"host:{h['uuid']}"
|
||||
add_node(hid, "host", h["remark"], address=h.get("address"), port=h.get("port"),
|
||||
vlessRouteId=route, disabled=h.get("isDisabled"),
|
||||
trace=[f"rule:{i}" for i in path],
|
||||
exitAlive=target_alive(rules[end]) if end is not None else False)
|
||||
add_edge(hid, f"inb:{tag}", "flow")
|
||||
if end is not None:
|
||||
add_edge(hid, f"rule:{end}", "route", f"route {route}" if route is not None else "default",
|
||||
dead=not target_alive(rules[end]))
|
||||
if not target_alive(rules[end]) and not h.get("isDisabled"):
|
||||
warnings.append(f"хост {h['remark']}: выход правила #{end} ведёт на нерабочую ноду")
|
||||
|
||||
return {"nodes": G_nodes, "edges": G_edges, "warnings": warnings}
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Хранилище позиций узлов (JSON-файл, запись атомарная)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import tempfile
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
MAX_ENTRIES = 5000
|
||||
_KEY_RE = re.compile(r"^[0-9A-Za-z-]{8,64}$")
|
||||
|
||||
|
||||
def valid_key(key: str) -> bool:
|
||||
return bool(_KEY_RE.match(key))
|
||||
|
||||
|
||||
def clean_positions(raw) -> dict[str, dict[str, float]]:
|
||||
if not isinstance(raw, dict):
|
||||
raise ValueError("positions должен быть объектом {id: {x, y}}")
|
||||
if len(raw) > MAX_ENTRIES:
|
||||
raise ValueError("слишком много узлов")
|
||||
out: dict[str, dict[str, float]] = {}
|
||||
for node_id, pos in raw.items():
|
||||
if not isinstance(node_id, str) or not 0 < len(node_id) <= 200:
|
||||
raise ValueError("некорректный id узла")
|
||||
if not isinstance(pos, dict):
|
||||
raise ValueError(f"позиция {node_id!r} должна быть объектом")
|
||||
coords = []
|
||||
for axis in ("x", "y"):
|
||||
v = pos.get(axis)
|
||||
if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v):
|
||||
raise ValueError(f"{node_id!r}: {axis} должно быть конечным числом")
|
||||
coords.append(float(v))
|
||||
out[node_id] = {"x": coords[0], "y": coords[1]}
|
||||
return out
|
||||
|
||||
|
||||
class PositionStore:
|
||||
def __init__(self, path: Path):
|
||||
self.path = path
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def _read(self) -> dict:
|
||||
try:
|
||||
return json.loads(self.path.read_text(encoding="utf-8"))
|
||||
except FileNotFoundError:
|
||||
return {}
|
||||
except ValueError:
|
||||
log.warning("positions: файл %s повреждён, начинаю с пустого", self.path)
|
||||
return {}
|
||||
|
||||
def _write(self, data: dict) -> None:
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fd, tmp = tempfile.mkstemp(dir=self.path.parent, prefix=".positions-")
|
||||
try:
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, ensure_ascii=False, indent=1)
|
||||
os.replace(tmp, self.path)
|
||||
except BaseException:
|
||||
Path(tmp).unlink(missing_ok=True)
|
||||
raise
|
||||
|
||||
def get(self, key: str) -> dict:
|
||||
with self._lock:
|
||||
return self._read().get(key, {})
|
||||
|
||||
def put(self, key: str, positions: dict) -> None:
|
||||
with self._lock:
|
||||
data = self._read()
|
||||
data[key] = positions
|
||||
self._write(data)
|
||||
|
||||
def delete(self, key: str) -> None:
|
||||
with self._lock:
|
||||
data = self._read()
|
||||
if data.pop(key, None) is not None:
|
||||
self._write(data)
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Клиент Remnawave API (только чтение)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
|
||||
|
||||
class RemnawaveError(Exception):
|
||||
"""Ошибка обращения к панели. Токен в сообщения не попадает."""
|
||||
|
||||
def __init__(self, message: str, code: str = "upstream_error", http_status: int = 502):
|
||||
super().__init__(message)
|
||||
self.message = message
|
||||
self.code = code
|
||||
self.http_status = http_status
|
||||
|
||||
|
||||
class RemnawaveClient:
|
||||
def __init__(self, base_url: str, token: str, timeout: float = 10.0,
|
||||
verify: bool = True, extra_headers: dict[str, str] | None = None):
|
||||
self.base = base_url.rstrip("/")
|
||||
self.timeout = timeout
|
||||
self.verify = verify
|
||||
self.headers = {"Authorization": f"Bearer {token}", "Accept": "application/json",
|
||||
**(extra_headers or {})}
|
||||
|
||||
def _get(self, path: str) -> Any:
|
||||
try:
|
||||
r = requests.get(f"{self.base}{path}", headers=self.headers,
|
||||
timeout=self.timeout, verify=self.verify)
|
||||
except requests.Timeout:
|
||||
raise RemnawaveError(f"Таймаут запроса {path}", "upstream_timeout", 504) from None
|
||||
except requests.RequestException as e:
|
||||
raise RemnawaveError(f"Не удалось подключиться к Remnawave ({type(e).__name__})",
|
||||
"upstream_unreachable") from None
|
||||
if r.status_code in (401, 403):
|
||||
raise RemnawaveError("Remnawave отклонил токен (401/403)", "upstream_auth")
|
||||
if not r.ok:
|
||||
raise RemnawaveError(f"{path}: HTTP {r.status_code}", "upstream_http")
|
||||
try:
|
||||
body = r.json()
|
||||
except ValueError:
|
||||
raise RemnawaveError(f"{path}: ответ не JSON (проверь REMNAWAVE_URL)",
|
||||
"upstream_bad_response") from None
|
||||
return body.get("response", body) if isinstance(body, dict) else body
|
||||
|
||||
def profiles(self) -> list[dict]:
|
||||
data = self._get("/api/config-profiles")
|
||||
return data.get("configProfiles", []) if isinstance(data, dict) else data
|
||||
|
||||
def hosts(self) -> list[dict]:
|
||||
return self._get("/api/hosts")
|
||||
|
||||
def nodes(self) -> list[dict]:
|
||||
return self._get("/api/nodes")
|
||||
|
||||
def fetch_all(self) -> dict[str, list[dict]]:
|
||||
"""Три запроса параллельно."""
|
||||
calls = {"profiles": self.profiles, "hosts": self.hosts, "nodes": self.nodes}
|
||||
with ThreadPoolExecutor(max_workers=3) as ex:
|
||||
futures = {k: ex.submit(fn) for k, fn in calls.items()}
|
||||
return {k: f.result() for k, f in futures.items()}
|
||||
@@ -0,0 +1,116 @@
|
||||
"""HTTP API."""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request
|
||||
|
||||
from .graph import build_graph
|
||||
from .positions import clean_positions, valid_key
|
||||
from .remnawave import RemnawaveError
|
||||
|
||||
bp = Blueprint("api", __name__, url_prefix="/api")
|
||||
|
||||
|
||||
class ProfileNotFound(LookupError):
|
||||
pass
|
||||
|
||||
|
||||
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"])
|
||||
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
|
||||
return jsonify({
|
||||
"profile": {"uuid": profile["uuid"], "name": profile["name"]},
|
||||
"graph": result,
|
||||
"positions": svc.positions.get(profile["uuid"]),
|
||||
"meta": {**meta, "fetchedAt": snap["fetchedAt"]},
|
||||
})
|
||||
|
||||
|
||||
@bp.get("/positions/<key>")
|
||||
def get_positions(key: str):
|
||||
if not valid_key(key):
|
||||
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
|
||||
body = request.get_json(silent=True)
|
||||
if not isinstance(body, dict) or "positions" not in body:
|
||||
return jsonify(error="bad_body", message='Ожидается {"positions": {...}}'), 400
|
||||
try:
|
||||
positions = clean_positions(body["positions"])
|
||||
except ValueError as e:
|
||||
return jsonify(error="bad_positions", message=str(e)), 400
|
||||
_svc().positions.put(key, positions)
|
||||
return jsonify({"saved": len(positions)})
|
||||
|
||||
|
||||
@bp.delete("/positions/<key>")
|
||||
def delete_positions(key: str):
|
||||
if not valid_key(key):
|
||||
return jsonify(error="bad_key", message="Некорректный идентификатор профиля"), 400
|
||||
_svc().positions.delete(key)
|
||||
return "", 204
|
||||
|
||||
|
||||
@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
|
||||
Reference in New Issue
Block a user