#!/usr/bin/env python3 """Render a sing-box config from proxylab's healthy.json. Puts the healthy outbounds behind a sing-box `urltest` group so failover happens inside the process without a restart, and drops outbounds that the quality probe found to be flaky (they pass one health check, then answer 503). Writes atomically to data/serve.json and validates with `sing-box check`. Exit codes: 0 ok, 1 no usable config (file untouched), 2 validation failed. """ import json import os import subprocess import sys import tempfile import time BASE = "/opt/proxy-lab" DATA = os.path.join(BASE, "data") HEALTHY = os.path.join(DATA, "healthy.json") SERVE = os.path.join(DATA, "serve.json") QUALITY = os.path.join(DATA, "quality.json") BIN = os.path.join(BASE, "bin", "sing-box") PORT = int(os.environ.get("SERVE_PORT", "20808")) MAX_OUT = int(os.environ.get("MAX_OUTBOUNDS", "8")) LISTEN = ["127.0.0.1", "172.19.0.1", "172.17.0.1"] TEST_URL = "https://www.gstatic.com/generate_204" QUALITY_MIN_RATIO = 0.8 # Measured: adding flaky members "for failover" makes it worse, because urltest # prefers the faster-but-503-prone one. Reliability wins over member count. MIN_MEMBERS = 1 QUALITY_MAX_AGE = 3 * 3600 def key_of(ob): return "%s|%s|%s|%s" % ( ob.get("server"), ob.get("server_port"), (ob.get("tls") or {}).get("server_name"), (ob.get("transport") or {}).get("path"), ) def load_quality(): try: if time.time() - os.path.getmtime(QUALITY) > QUALITY_MAX_AGE: print("quality.json is stale, ignoring it") return {} with open(QUALITY, encoding="utf-8") as fh: return json.load(fh) except Exception: # noqa: BLE001 return {} def candidates(entries): seen = set() out = [] for entry in sorted(entries, key=lambda e: e.get("latency_ms") or 10 ** 9): ob = entry.get("outbound") if not isinstance(ob, dict) or "type" not in ob or "server" not in ob: continue key = key_of(ob) if key in seen: continue seen.add(key) out.append((key, ob)) return out def select(cands, quality): if not quality: return cands def score(item): q = quality.get(item[0]) or {} ok = q.get("ok", 0) total = q.get("total") or 1 return ok / total, -(q.get("avg_ms") or 99999) good = [c for c in cands if score(c)[0] >= QUALITY_MIN_RATIO] if not good: print("no outbound passed the quality bar, keeping all of them") good = list(cands) else: print("quality filter: %d of %d passed" % (len(good), len(cands))) good.sort(key=score, reverse=True) # A single member is a single point of failure: top up with the next best # candidates so urltest has something to fail over to. if len(good) < MIN_MEMBERS: chosen = {c[0] for c in good} rest = [c for c in cands if c[0] not in chosen] rest.sort(key=score, reverse=True) for c in rest: if len(good) >= MIN_MEMBERS: break good.append(c) print("topped up to %d members for failover" % len(good)) return good[:MAX_OUT] def build(entries, quality): chosen = select(candidates(entries), quality) outs = [] for _, ob in chosen[:MAX_OUT]: ob = dict(ob) ob["tag"] = "p%d" % len(outs) outs.append(ob) if not outs: return None tags = [o["tag"] for o in outs] return { "log": {"level": "warn"}, "dns": {"servers": [{"type": "local", "tag": "local"}]}, "inbounds": [ {"type": "mixed", "tag": "in-%d" % i, "listen": addr, "listen_port": PORT} for i, addr in enumerate(LISTEN) ], "outbounds": outs + [ { "type": "urltest", "tag": "auto", "outbounds": tags, "url": TEST_URL, "interval": "60s", "tolerance": 50, "idle_timeout": "5m", } ], "route": {"final": "auto", "default_domain_resolver": "local"}, } def main(): try: with open(HEALTHY, encoding="utf-8") as fh: entries = json.load(fh) except Exception as exc: # noqa: BLE001 print("cannot read %s: %s" % (HEALTHY, exc)) return 1 config = build(entries, load_quality()) if config is None: print("no usable outbound in healthy.json; keeping current config") return 1 fd, tmp = tempfile.mkstemp(dir=DATA, prefix=".serve-", suffix=".json") try: with os.fdopen(fd, "w", encoding="utf-8") as fh: json.dump(config, fh, ensure_ascii=False) os.chmod(tmp, 0o600) check = subprocess.run([BIN, "check", "-c", tmp], capture_output=True, text=True) if check.returncode != 0: print("sing-box check failed:\n%s" % (check.stderr or check.stdout)[:600]) return 2 os.replace(tmp, SERVE) finally: if os.path.exists(tmp): os.unlink(tmp) best = config["outbounds"][0] print( "rendered %d outbound(s) best=%s:%s -> %s" % (len(config["outbounds"]) - 1, best.get("server"), best.get("server_port"), SERVE) ) return 0 if __name__ == "__main__": sys.exit(main())