refactor(opnsense/xray): replace 310-line Jinja loop with sync_xray.py
ansible-deploy / plan (push) Successful in 1s
ansible-lint / lint (push) Successful in 3s
ansible-deploy / deploy (opnsense, ) (push) Successful in 3s

This commit is contained in:
karpenok committed 2026-11-15 23:07:41 +07:00
1 parent ae9beee5ca
commit aab0611aaf
4 files changed
+245 -289

No files matched your search

@@ -0,0 +1,194 @@
#!/usr/bin/env python3
"""Идемпотентная синхронизация подписок Xray на OPNsense (os-xray API)."""
from __future__ import annotations
import base64
import json
import os
import ssl
import sys
import urllib.error
import urllib.request
from typing import Any
from vless_to_outbound import convert_vless
class OPNsenseXrayAPI:
"""Минимальный клиент API плагина os-xray на OPNsense."""
def __init__(self, host: str, key: str, secret: str) -> None:
self.base_url = f"https://{host}/api/xray"
creds = base64.b64encode(f"{key}:{secret}".encode("utf-8")).decode("ascii")
self.auth_header = f"Basic {creds}"
self.ctx = ssl.create_default_context()
self.ctx.check_hostname = False
self.ctx.verify_mode = ssl.CERT_NONE
def request(self, method: str, path: str, payload: dict[str, Any] | None = None) -> Any:
data = None
headers = {"Authorization": self.auth_header}
if payload is not None:
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
headers["Content-Type"] = "application/json"
req = urllib.request.Request(f"{self.base_url}{path}", data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(req, context=self.ctx, timeout=30) as resp:
raw = resp.read().decode("utf-8", errors="replace")
return json.loads(raw) if raw.strip() else {}
except urllib.error.HTTPError as exc:
body = exc.read().decode("utf-8", errors="replace")
raise RuntimeError(f"OPNsense API {method} {path} -> HTTP {exc.code}: {body}") from exc
def _selected_option(field: Any) -> str:
if isinstance(field, dict):
for k, v in field.items():
if isinstance(v, dict) and v.get("selected") == 1:
return str(k)
return str(field or "")
def _has_drift(cur: dict[str, Any], want: dict[str, Any]) -> bool:
try:
cur_out = json.loads(cur.get("outbound_config") or "{}")
want_out = json.loads(want["outbound_config"])
if cur_out != want_out:
return True
except json.JSONDecodeError:
if (cur.get("outbound_config") or "") != want["outbound_config"]:
return True
return (
cur.get("name") != want["name"]
or str(cur.get("enabled", "")) != str(want["enabled"])
or (cur.get("socks5_listen") or "") != want["socks5_listen"]
or str(cur.get("socks5_port", "")) != str(want["socks5_port"])
or (cur.get("tun_interface") or "") != want["tun_interface"]
or str(cur.get("mtu", "")) != str(want["mtu"])
or (cur.get("bypass_networks") or "") != want["bypass_networks"]
or _selected_option(cur.get("loglevel")) != want["loglevel"]
)
def main() -> int:
cfg = json.load(sys.stdin)
api_key = os.environ.get("OPNSENSE_API_KEY", "").strip()
api_secret = os.environ.get("OPNSENSE_API_SECRET", "").strip()
if not api_key or not api_secret:
print("Отсутствуют OPNSENSE_API_KEY / OPNSENSE_API_SECRET", file=sys.stderr)
return 1
instances = cfg.get("instances", [])
active_list = [i for i in instances if i.get("active")]
if len(active_list) != 1:
print("В instances.yml должна быть ровно одна подписка с active: true.", file=sys.stderr)
return 1
active_name = active_list[0]["name"]
desired: list[dict[str, Any]] = []
for inst in instances:
link = os.environ.get(inst["secret"], "").strip()
if not link:
print(f"Подписка {inst['name']}: нет ссылки в Infisical (ключ {inst['secret']})", file=sys.stderr)
return 1
try:
outbound = convert_vless(link)
except ValueError as exc:
print(f"Подписка {inst['name']}: {exc}", file=sys.stderr)
return 1
desired.append(
{
"enabled": "1" if inst.get("active") else "0",
"name": inst["name"],
"outbound_config": outbound,
"socks5_listen": cfg["socks5_listen"],
"socks5_port": str(cfg["socks5_port"]),
"tun_interface": cfg["tun_interface"],
"mtu": str(cfg["mtu"]),
"bypass_networks": cfg["bypass_networks"],
"loglevel": cfg["loglevel"],
}
)
api = OPNsenseXrayAPI(cfg["opnsense_host"], api_key, api_secret)
current_rows = api.request("GET", "/instance/searchItem").get("rows") or []
by_name = {r["name"]: r for r in current_rows if r.get("name")}
desired_names = {d["name"] for d in desired}
stale = [r for r in current_rows if r.get("name") not in desired_names]
prev_active_stale = [r for r in stale if str(r.get("enabled")) == "1"]
changes: list[str] = []
for r in prev_active_stale:
api.request("POST", f"/instance/toggleItem/{r['uuid']}/0", {})
changes.append(f"disabled stale {r['name']}")
active_uuid = ""
for want in desired:
name = want["name"]
existing = by_name.get(name)
if not existing:
added = api.request("POST", "/instance/addItem", {"instance": want})
uid = added.get("uuid", "")
changes.append(f"added {name}")
else:
uid = existing["uuid"]
cur = api.request("GET", f"/instance/getItem/{uid}").get("instance") or {}
if _has_drift(cur, want):
api.request("POST", f"/instance/setItem/{uid}", {"instance": want})
changes.append(f"updated {name}")
if name == active_name:
active_uuid = uid
if not active_uuid:
print("Активная подписка не найдена в OPNsense после синхронизации.", file=sys.stderr)
return 1
restart_needed = len(changes) > 0
test_message = "не запускался (без изменений)"
test_ok = True
if restart_needed:
val = api.request("POST", f"/service/validate/{active_uuid}", {})
if val.get("result") != "ok":
print(f"xray -test отклонил конфиг активной подписки: {val.get('message')}", file=sys.stderr)
return 1
api.request("POST", "/service/reconfigure", {})
test = api.request("POST", f"/service/testconnect/{active_uuid}", {})
test_ok = test.get("result") == "ok"
test_message = test.get("message") or str(test.get("result") or "")
if not test_ok and prev_active_stale:
for r in prev_active_stale:
api.request("POST", f"/instance/toggleItem/{r['uuid']}/1", {})
api.request("POST", "/service/reconfigure", {})
print(f"testconnect не прошёл ({test_message}), выполнен откат на прежнюю подписку", file=sys.stderr)
return 1
if not restart_needed or test_ok:
for r in stale:
api.request("POST", f"/instance/delItem/{r['uuid']}", {})
changes.append(f"deleted stale {r['name']}")
status_resp = api.request("GET", f"/service/status/{active_uuid}")
print(
json.dumps(
{
"changed": len(changes) > 0,
"changes": changes,
"instances": [d["name"] for d in desired],
"active": active_name,
"service_status": status_resp.get("status", "?"),
"restart_needed": restart_needed,
"test_message": test_message,
},
ensure_ascii=False,
)
)
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -13,11 +13,11 @@ import sys
from urllib.parse import unquote, urlparse, parse_qs
def main() -> None:
link = sys.argv[1] if len(sys.argv) > 1 else sys.stdin.read()
def convert_vless(link: str) -> str:
"""Конвертирует vless:// ссылку в компактный JSON outbound-объекта."""
link = link.strip().strip("\"'")
if not link.startswith("vless://"):
sys.exit("error: link must start with vless://")
raise ValueError("link must start with vless://")
parsed = urlparse(link)
uuid = parsed.username
@@ -26,7 +26,7 @@ def main() -> None:
params = {k: v[0] for k, v in parse_qs(parsed.query).items()}
if not uuid or not host or not port:
sys.exit("error: link must look like vless://uuid@host:port?...")
raise ValueError("link must look like vless://uuid@host:port?...")
network = params.get("type", "tcp")
security = params.get("security", "reality")
@@ -82,8 +82,16 @@ def main() -> None:
if t or network == "grpc":
ss[transport_key] = t
json.dump(outbound, sys.stdout, separators=(",", ":"), ensure_ascii=False)
sys.stdout.write("\n")
return json.dumps(outbound, separators=(",", ":"), ensure_ascii=False)
def main() -> None:
link = sys.argv[1] if len(sys.argv) > 1 else sys.stdin.read()
try:
out = convert_vless(link)
except ValueError as exc:
sys.exit(f"error: {exc}")
sys.stdout.write(out + "\n")
if __name__ == "__main__":