From de7a02b2cce247d35442ea60067754fb47e9eed2 Mon Sep 17 00:00:00 2001 From: clover caruso Date: Tue, 24 Nov 2026 09:20:21 -0800 Subject: [PATCH] router: keep proxied WebSockets across Caddy reloads ddns-updater closes idle connections after 10 s, the same as Nomad's check interval, so one check in a few fails with EOF. The router dropped the route and reloaded Caddy, twice per flap, and every reload closed each proxied WebSocket with 1001. - An allocation stays routed until its checks have failed for 30 s; one that never passed is still not routed. - Every proxy holds open streams for 8 h across a reload, not only the dashboard. Assisted-by: claude-sonnet-5.5 --- tools/router-health-test.py | 47 +++++++++++++++++++++++++ tools/router-stream-test.py | 70 ++++++++++++++++++------------------- tools/router.py | 17 +++++---- 3 files changed, 92 insertions(+), 42 deletions(-) create mode 100755 tools/router-health-test.py diff --git a/tools/router-health-test.py b/tools/router-health-test.py new file mode 100755 index 0000000000000000000000000000000000000000..d8f032e6f0b198102625e79d9ed94ff38cbe3a5b --- /dev/null +++ b/tools/router-health-test.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +import os +from pathlib import Path +import tempfile +import time +from unittest.mock import patch + +import router + + +def main(): + with tempfile.TemporaryDirectory(prefix="snowglobe-router-health-") as temporary: + root = Path(temporary) + (root / "proof").write_text("a" * 64) + (root / "routes").mkdir() + environment = {"SNOWGLOBE_DOMAIN": "snowglobe.test", "SNOWGLOBE_DASHBOARD_PORT": "1", + "SNOWGLOBE_PROXY_TOKEN_FILE": str(root / "proof"), "SNOWGLOBE_STATE": temporary} + status = {} + + def nomad(path, _): + if path == "/v1/services": + return [{"Namespace": "default", "Services": [{"ServiceName": "plain"}]}] + if path.startswith("/v1/service/"): + return [{"ServiceName": "plain", "JobID": "plain", "AllocID": "alloc", "Address": "127.0.0.1", + "Port": 2, "Tags": ["caddy-host=plain.snowglobe.test"]}] + return {"http": {"Status": status["alloc"]}} + + def routed(): + return "plain.snowglobe.test {" in router.render("fixture") + + with patch.dict(os.environ, environment, clear=True), patch.object(router, "nomad", nomad), \ + patch.object(router, "ROUTE_DIR", str(root / "routes")), patch.object(router, "HEALTH_GRACE", 0.3): + status["alloc"] = "pending" + assert not routed(), "an allocation that never passed was routed" + status["alloc"] = "success" + assert routed() + status["alloc"] = "failure" + assert routed(), "one failed check dropped the route" + time.sleep(0.4) + assert not routed(), "a failing allocation stayed routed" + status["alloc"] = "success" + assert routed() + print("A route survives a short check failure and drops after the grace period.") + + +if __name__ == "__main__": + main() diff --git a/tools/router-stream-test.py b/tools/router-stream-test.py index 36df08ec2254eddf65e5245f62b77289e33ea2e8..2acdd822e23fe76cef25e79938c89c986c458455 100644 --- a/tools/router-stream-test.py +++ b/tools/router-stream-test.py @@ -51,43 +51,41 @@ def main(): with tempfile.TemporaryDirectory(prefix="snowglobe-router-stream-") as temporary, ThreadingHTTPServer(("127.0.0.1", 0), Echo) as backend: root = Path(temporary) threading.Thread(target=backend.serve_forever, daemon=True).start() - for keep in (False, True): - port, admin = free_port(), free_port() - config = root / "Caddyfile" - content = "\n".join(["{", f" admin 127.0.0.1:{admin}", " auto_https off", "}", f"http://127.0.0.1:{port} {{", - *router.proxy(f"127.0.0.1:{backend.server_port}", " ", keep_streams=keep), "}"]) - config.write_text(content) - environment = {**os.environ, "XDG_DATA_HOME": str(root / "data"), "XDG_CONFIG_HOME": str(root / "config")} - with (root / "caddy.log").open("w") as log: - process = subprocess.Popen([args.caddy, "run", "--config", str(config)], stdout=log, stderr=log, env=environment) - try: - deadline = time.monotonic() + 10 - while True: - try: - client = socket.create_connection(("127.0.0.1", port), timeout=2) - break - except OSError: - assert process.poll() is None and time.monotonic() < deadline, (root / "caddy.log").read_text() - time.sleep(.05) - with client, client.makefile("rb") as incoming: - client.sendall(f"GET / HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: c3RyZWFtLWZpeHR1cmUtMQ==\r\nSec-WebSocket-Version: 13\r\n\r\n".encode()) - assert b"101" in incoming.readline() - while incoming.readline() != b"\r\n": - pass - client.sendall(b"\x81\x84\0\0\0\0ping") - assert incoming.read(6) == b"\x81\x04ping" - config.write_text(content.replace(" reverse_proxy", " header X-Reload verified\n reverse_proxy")) - subprocess.run([args.caddy, "reload", "--config", str(config), "--address", f"127.0.0.1:{admin}"], check=True, capture_output=True, env=environment) - client.sendall(b"\x81\x84\0\0\0\0pong") - header = incoming.read(2) - assert header == (b"\x81\x04" if keep else b"\x88\x02"), header - if keep: - assert incoming.read(4) == b"pong" - finally: - process.terminate() - process.wait(timeout=5) + port, admin = free_port(), free_port() + config = root / "Caddyfile" + content = "\n".join(["{", f" admin 127.0.0.1:{admin}", " auto_https off", "}", f"http://127.0.0.1:{port} {{", + *router.proxy(f"127.0.0.1:{backend.server_port}", " "), "}"]) + config.write_text(content) + environment = {**os.environ, "XDG_DATA_HOME": str(root / "data"), "XDG_CONFIG_HOME": str(root / "config")} + with (root / "caddy.log").open("w") as log: + process = subprocess.Popen([args.caddy, "run", "--config", str(config)], stdout=log, stderr=log, env=environment) + try: + deadline = time.monotonic() + 10 + while True: + try: + client = socket.create_connection(("127.0.0.1", port), timeout=2) + break + except OSError: + assert process.poll() is None and time.monotonic() < deadline, (root / "caddy.log").read_text() + time.sleep(.05) + with client, client.makefile("rb") as incoming: + client.sendall(f"GET / HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: c3RyZWFtLWZpeHR1cmUtMQ==\r\nSec-WebSocket-Version: 13\r\n\r\n".encode()) + assert b"101" in incoming.readline() + while incoming.readline() != b"\r\n": + pass + client.sendall(b"\x81\x84\0\0\0\0ping") + assert incoming.read(6) == b"\x81\x04ping" + config.write_text(content.replace(" reverse_proxy", " header X-Reload verified\n reverse_proxy")) + subprocess.run([args.caddy, "reload", "--config", str(config), "--address", f"127.0.0.1:{admin}"], check=True, capture_output=True, env=environment) + client.sendall(b"\x81\x84\0\0\0\0pong") + header = incoming.read(2) + assert header == b"\x81\x04", header + assert incoming.read(4) == b"pong" + finally: + process.terminate() + process.wait(timeout=5) backend.shutdown() - print("Caddy reload closes default WebSockets and preserves dashboard streams.") + print("Caddy reload preserves proxied WebSocket streams.") if __name__ == "__main__": diff --git a/tools/router.py b/tools/router.py index 1aab5b7fd45cbb065515ef9a73abb7bb412bc0fc..8fca738e211859c209cc38f7fbe3fb019207e30c 100644 --- a/tools/router.py +++ b/tools/router.py @@ -13,6 +13,9 @@ ROUTES = "/var/lib/caddy/routes.caddy" TOKEN = "/var/lib/snowglobe/router.token" ROUTE_DIR = "/var/lib/snowglobe/routes" HOST = re.compile(r"[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\Z") +# A reload closes every proxied WebSocket, so one failed check must not drop a route. +HEALTH_GRACE = 30 +last_passing = {} def nomad(path, token): @@ -28,15 +31,13 @@ def passive_health(upstreams, indent): return [f"{indent}fail_duration 30s"] if len(upstreams.split()) > 1 else [] -def proxy(upstreams, indent, uncompressed=False, host=None, keep_streams=False): - lines = [f"{indent}reverse_proxy {upstreams} {{", f"{indent} lb_try_duration 5s", +def proxy(upstreams, indent, uncompressed=False, host=None): + lines = [f"{indent}reverse_proxy {upstreams} {{", f"{indent} lb_try_duration 5s", f"{indent} stream_close_delay 8h", *passive_health(upstreams, indent + " ")] if uncompressed: lines.append(f"{indent} header_up Accept-Encoding identity") if host: lines += [f"{indent} header_up Host {host}", f"{indent} header_up X-Forwarded-Host {host}"] - if keep_streams: - lines.append(f"{indent} stream_close_delay 8h") return [*lines, f"{indent}}}"] @@ -225,7 +226,9 @@ def render(token): if alloc not in allocation_checks: allocation_checks[alloc] = nomad(f"/v1/allocation/{alloc}/checks", token) service_checks = list(allocation_checks[alloc].values()) - if not service_checks or any(check["Status"] != "success" for check in service_checks): + if service_checks and all(check["Status"] == "success" for check in service_checks): + last_passing[alloc] = time.monotonic() + elif time.monotonic() - last_passing.get(alloc, float("-inf")) > HEALTH_GRACE: continue if instance["ServiceName"] == "forward-auth": auth_upstreams.add(upstream) @@ -268,6 +271,8 @@ def render(token): route = routes.setdefault((listener, ""), {"upstreams": set(), "services": set()}) route["upstreams"].add(upstream) + for alloc in last_passing.keys() - allocation_checks.keys(): + del last_passing[alloc] lines = [] for (listener, host), route in sorted(routes.items()): if host: @@ -490,7 +495,7 @@ def render(token): lines += [" handle {", " request_header -User-Name", " request_header -User-Groups", f" request_header Snowglobe-Proxy-Token {dashboard_proof}", " request_header X-Snowglobe-Client-IP {remote_host}", - *proxy(f"127.0.0.1:{dashboard_port}", " ", keep_streams=True), " }", "}"] + *proxy(f"127.0.0.1:{dashboard_port}", " "), " }", "}"] internal_port = os.environ.get("SNOWGLOBE_INTERNAL_PORT") if internal_port is not None: internal_host = "dashboard.internal." + os.environ["SNOWGLOBE_DOMAIN"] -- 2.54.1