authoravatarclover caruso<git@paperclover.net>2026-11-24 09:20:21-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-30 03:08:43-08:00
logde7a02b2cce247d35442ea60067754fb47e9eed2
tree625e148a5630fb8191b727d59cf5ab21f15676d7
parentb061cf9d1c5d6098df987ff3609ace00dcc0bac8
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

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

3 files changed, 92 insertions(+), 42 deletions(-)

tools/router-health-test.py created+47
...@@ -0,0 +1,47 @@
1#!/usr/bin/env python3
2import os
3from pathlib import Path
4import tempfile
5import time
6from unittest.mock import patch
7
8import router
9
10
11def main():
12 with tempfile.TemporaryDirectory(prefix="snowglobe-router-health-") as temporary:
13 root = Path(temporary)
14 (root / "proof").write_text("a" * 64)
15 (root / "routes").mkdir()
16 environment = {"SNOWGLOBE_DOMAIN": "snowglobe.test", "SNOWGLOBE_DASHBOARD_PORT": "1",
17 "SNOWGLOBE_PROXY_TOKEN_FILE": str(root / "proof"), "SNOWGLOBE_STATE": temporary}
18 status = {}
19
20 def nomad(path, _):
21 if path == "/v1/services":
22 return [{"Namespace": "default", "Services": [{"ServiceName": "plain"}]}]
23 if path.startswith("/v1/service/"):
24 return [{"ServiceName": "plain", "JobID": "plain", "AllocID": "alloc", "Address": "127.0.0.1",
25 "Port": 2, "Tags": ["caddy-host=plain.snowglobe.test"]}]
26 return {"http": {"Status": status["alloc"]}}
27
28 def routed():
29 return "plain.snowglobe.test {" in router.render("fixture")
30
31 with patch.dict(os.environ, environment, clear=True), patch.object(router, "nomad", nomad), \
32 patch.object(router, "ROUTE_DIR", str(root / "routes")), patch.object(router, "HEALTH_GRACE", 0.3):
33 status["alloc"] = "pending"
34 assert not routed(), "an allocation that never passed was routed"
35 status["alloc"] = "success"
36 assert routed()
37 status["alloc"] = "failure"
38 assert routed(), "one failed check dropped the route"
39 time.sleep(0.4)
40 assert not routed(), "a failing allocation stayed routed"
41 status["alloc"] = "success"
42 assert routed()
43 print("A route survives a short check failure and drops after the grace period.")
44
45
46if __name__ == "__main__":
47 main()
tools/router-stream-test.py+34-36
...@@ -51,43 +51,41 @@ def main():...@@ -51,43 +51,41 @@ def main():
51 with tempfile.TemporaryDirectory(prefix="snowglobe-router-stream-") as temporary, ThreadingHTTPServer(("127.0.0.1", 0), Echo) as backend:51 with tempfile.TemporaryDirectory(prefix="snowglobe-router-stream-") as temporary, ThreadingHTTPServer(("127.0.0.1", 0), Echo) as backend:
52 root = Path(temporary)52 root = Path(temporary)
53 threading.Thread(target=backend.serve_forever, daemon=True).start()53 threading.Thread(target=backend.serve_forever, daemon=True).start()
54 for keep in (False, True):54 port, admin = free_port(), free_port()
55 port, admin = free_port(), free_port()55 config = root / "Caddyfile"
56 config = root / "Caddyfile"56 content = "\n".join(["{", f" admin 127.0.0.1:{admin}", " auto_https off", "}", f"http://127.0.0.1:{port} {{",
57 content = "\n".join(["{", f" admin 127.0.0.1:{admin}", " auto_https off", "}", f"http://127.0.0.1:{port} {{",57 *router.proxy(f"127.0.0.1:{backend.server_port}", " "), "}"])
58 *router.proxy(f"127.0.0.1:{backend.server_port}", " ", keep_streams=keep), "}"])58 config.write_text(content)
59 config.write_text(content)59 environment = {**os.environ, "XDG_DATA_HOME": str(root / "data"), "XDG_CONFIG_HOME": str(root / "config")}
60 environment = {**os.environ, "XDG_DATA_HOME": str(root / "data"), "XDG_CONFIG_HOME": str(root / "config")}60 with (root / "caddy.log").open("w") as log:
61 with (root / "caddy.log").open("w") as log:61 process = subprocess.Popen([args.caddy, "run", "--config", str(config)], stdout=log, stderr=log, env=environment)
62 process = subprocess.Popen([args.caddy, "run", "--config", str(config)], stdout=log, stderr=log, env=environment)62 try:
63 try:63 deadline = time.monotonic() + 10
64 deadline = time.monotonic() + 1064 while True:
65 while True:65 try:
66 try:66 client = socket.create_connection(("127.0.0.1", port), timeout=2)
67 client = socket.create_connection(("127.0.0.1", port), timeout=2)67 break
68 break68 except OSError:
69 except OSError:69 assert process.poll() is None and time.monotonic() < deadline, (root / "caddy.log").read_text()
70 assert process.poll() is None and time.monotonic() < deadline, (root / "caddy.log").read_text()70 time.sleep(.05)
71 time.sleep(.05)71 with client, client.makefile("rb") as incoming:
72 with client, client.makefile("rb") as incoming:72 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())
73 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())73 assert b"101" in incoming.readline()
74 assert b"101" in incoming.readline()74 while incoming.readline() != b"\r\n":
75 while incoming.readline() != b"\r\n":75 pass
76 pass76 client.sendall(b"\x81\x84\0\0\0\0ping")
77 client.sendall(b"\x81\x84\0\0\0\0ping")77 assert incoming.read(6) == b"\x81\x04ping"
78 assert incoming.read(6) == b"\x81\x04ping"78 config.write_text(content.replace(" reverse_proxy", " header X-Reload verified\n reverse_proxy"))
79 config.write_text(content.replace(" reverse_proxy", " header X-Reload verified\n reverse_proxy"))79 subprocess.run([args.caddy, "reload", "--config", str(config), "--address", f"127.0.0.1:{admin}"], check=True, capture_output=True, env=environment)
80 subprocess.run([args.caddy, "reload", "--config", str(config), "--address", f"127.0.0.1:{admin}"], check=True, capture_output=True, env=environment)80 client.sendall(b"\x81\x84\0\0\0\0pong")
81 client.sendall(b"\x81\x84\0\0\0\0pong")81 header = incoming.read(2)
82 header = incoming.read(2)82 assert header == b"\x81\x04", header
83 assert header == (b"\x81\x04" if keep else b"\x88\x02"), header83 assert incoming.read(4) == b"pong"
84 if keep:84 finally:
85 assert incoming.read(4) == b"pong"85 process.terminate()
86 finally:86 process.wait(timeout=5)
87 process.terminate()
88 process.wait(timeout=5)
89 backend.shutdown()87 backend.shutdown()
90 print("Caddy reload closes default WebSockets and preserves dashboard streams.")88 print("Caddy reload preserves proxied WebSocket streams.")
9189
9290
93if __name__ == "__main__":91if __name__ == "__main__":
tools/router.py+11-6
...@@ -13,6 +13,9 @@ ROUTES = "/var/lib/caddy/routes.caddy"...@@ -13,6 +13,9 @@ ROUTES = "/var/lib/caddy/routes.caddy"
13TOKEN = "/var/lib/snowglobe/router.token"13TOKEN = "/var/lib/snowglobe/router.token"
14ROUTE_DIR = "/var/lib/snowglobe/routes"14ROUTE_DIR = "/var/lib/snowglobe/routes"
15HOST = re.compile(r"[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\Z")15HOST = re.compile(r"[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\Z")
16# A reload closes every proxied WebSocket, so one failed check must not drop a route.
17HEALTH_GRACE = 30
18last_passing = {}
1619
1720
18def nomad(path, token):21def nomad(path, token):
...@@ -28,15 +31,13 @@ def passive_health(upstreams, indent):...@@ -28,15 +31,13 @@ def passive_health(upstreams, indent):
28 return [f"{indent}fail_duration 30s"] if len(upstreams.split()) > 1 else []31 return [f"{indent}fail_duration 30s"] if len(upstreams.split()) > 1 else []
2932
3033
31def proxy(upstreams, indent, uncompressed=False, host=None, keep_streams=False):34def proxy(upstreams, indent, uncompressed=False, host=None):
32 lines = [f"{indent}reverse_proxy {upstreams} {{", f"{indent} lb_try_duration 5s",35 lines = [f"{indent}reverse_proxy {upstreams} {{", f"{indent} lb_try_duration 5s", f"{indent} stream_close_delay 8h",
33 *passive_health(upstreams, indent + " ")]36 *passive_health(upstreams, indent + " ")]
34 if uncompressed:37 if uncompressed:
35 lines.append(f"{indent} header_up Accept-Encoding identity")38 lines.append(f"{indent} header_up Accept-Encoding identity")
36 if host:39 if host:
37 lines += [f"{indent} header_up Host {host}", f"{indent} header_up X-Forwarded-Host {host}"]40 lines += [f"{indent} header_up Host {host}", f"{indent} header_up X-Forwarded-Host {host}"]
38 if keep_streams:
39 lines.append(f"{indent} stream_close_delay 8h")
40 return [*lines, f"{indent}}}"]41 return [*lines, f"{indent}}}"]
4142
4243
...@@ -225,7 +226,9 @@ def render(token):...@@ -225,7 +226,9 @@ def render(token):
225 if alloc not in allocation_checks:226 if alloc not in allocation_checks:
226 allocation_checks[alloc] = nomad(f"/v1/allocation/{alloc}/checks", token)227 allocation_checks[alloc] = nomad(f"/v1/allocation/{alloc}/checks", token)
227 service_checks = list(allocation_checks[alloc].values())228 service_checks = list(allocation_checks[alloc].values())
228 if not service_checks or any(check["Status"] != "success" for check in service_checks):229 if service_checks and all(check["Status"] == "success" for check in service_checks):
230 last_passing[alloc] = time.monotonic()
231 elif time.monotonic() - last_passing.get(alloc, float("-inf")) > HEALTH_GRACE:
229 continue232 continue
230 if instance["ServiceName"] == "forward-auth":233 if instance["ServiceName"] == "forward-auth":
231 auth_upstreams.add(upstream)234 auth_upstreams.add(upstream)
...@@ -268,6 +271,8 @@ def render(token):...@@ -268,6 +271,8 @@ def render(token):
268 route = routes.setdefault((listener, ""), {"upstreams": set(), "services": set()})271 route = routes.setdefault((listener, ""), {"upstreams": set(), "services": set()})
269 route["upstreams"].add(upstream)272 route["upstreams"].add(upstream)
270273
274 for alloc in last_passing.keys() - allocation_checks.keys():
275 del last_passing[alloc]
271 lines = []276 lines = []
272 for (listener, host), route in sorted(routes.items()):277 for (listener, host), route in sorted(routes.items()):
273 if host:278 if host:
...@@ -490,7 +495,7 @@ def render(token):...@@ -490,7 +495,7 @@ def render(token):
490 lines += [" handle {", " request_header -User-Name", " request_header -User-Groups",495 lines += [" handle {", " request_header -User-Name", " request_header -User-Groups",
491 f" request_header Snowglobe-Proxy-Token {dashboard_proof}",496 f" request_header Snowglobe-Proxy-Token {dashboard_proof}",
492 " request_header X-Snowglobe-Client-IP {remote_host}",497 " request_header X-Snowglobe-Client-IP {remote_host}",
493 *proxy(f"127.0.0.1:{dashboard_port}", " ", keep_streams=True), " }", "}"]498 *proxy(f"127.0.0.1:{dashboard_port}", " "), " }", "}"]
494 internal_port = os.environ.get("SNOWGLOBE_INTERNAL_PORT")499 internal_port = os.environ.get("SNOWGLOBE_INTERNAL_PORT")
495 if internal_port is not None:500 if internal_port is not None:
496 internal_host = "dashboard.internal." + os.environ["SNOWGLOBE_DOMAIN"]501 internal_host = "dashboard.internal." + os.environ["SNOWGLOBE_DOMAIN"]