| author | |
| committer | |
| log | de7a02b2cce247d35442ea60067754fb47e9eed2 |
| tree | 625e148a5630fb8191b727d59cf5ab21f15676d7 |
| parent | b061cf9d1c5d6098df987ff3609ace00dcc0bac8 |
| signature | Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU |
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.53 files changed, 92 insertions(+), 42 deletions(-)
tools/router-health-test.py created+47| ... | ... | @@ -0,0 +1,47 @@ |
| 1 | #!/usr/bin/env python3 | |
| 2 | import os | |
| 3 | from pathlib import Path | |
| 4 | import tempfile | |
| 5 | import time | |
| 6 | from unittest.mock import patch | |
| 7 | ||
| 8 | import router | |
| 9 | ||
| 10 | ||
| 11 | def 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 | ||
| 46 | if __name__ == "__main__": | |
| 47 | main() |
tools/router-stream-test.py+34-36| ... | ... | @@ -51,43 +51,41 @@ def main(): |
| 51 | 51 | with tempfile.TemporaryDirectory(prefix="snowglobe-router-stream-") as temporary, ThreadingHTTPServer(("127.0.0.1", 0), Echo) as backend: |
| 52 | 52 | root = Path(temporary) |
| 53 | 53 | threading.Thread(target=backend.serve_forever, daemon=True).start() |
| 54 | for keep in (False, True): | |
| 55 | port, admin = free_port(), free_port() | |
| 56 | config = root / "Caddyfile" | |
| 57 | content = "\n".join(["{", f" admin 127.0.0.1:{admin}", " auto_https off", "}", f"http://127.0.0.1:{port} {{", | |
| 58 | *router.proxy(f"127.0.0.1:{backend.server_port}", " ", keep_streams=keep), "}"]) | |
| 59 | config.write_text(content) | |
| 60 | environment = {**os.environ, "XDG_DATA_HOME": str(root / "data"), "XDG_CONFIG_HOME": str(root / "config")} | |
| 61 | with (root / "caddy.log").open("w") as log: | |
| 62 | process = subprocess.Popen([args.caddy, "run", "--config", str(config)], stdout=log, stderr=log, env=environment) | |
| 63 | try: | |
| 64 | deadline = time.monotonic() + 10 | |
| 65 | while True: | |
| 66 | try: | |
| 67 | client = socket.create_connection(("127.0.0.1", port), timeout=2) | |
| 68 | break | |
| 69 | except OSError: | |
| 70 | assert process.poll() is None and time.monotonic() < deadline, (root / "caddy.log").read_text() | |
| 71 | time.sleep(.05) | |
| 72 | with client, client.makefile("rb") as incoming: | |
| 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()) | |
| 74 | assert b"101" in incoming.readline() | |
| 75 | while incoming.readline() != b"\r\n": | |
| 76 | pass | |
| 77 | client.sendall(b"\x81\x84\0\0\0\0ping") | |
| 78 | assert incoming.read(6) == b"\x81\x04ping" | |
| 79 | config.write_text(content.replace(" reverse_proxy", " header X-Reload verified\n reverse_proxy")) | |
| 80 | subprocess.run([args.caddy, "reload", "--config", str(config), "--address", f"127.0.0.1:{admin}"], check=True, capture_output=True, env=environment) | |
| 81 | client.sendall(b"\x81\x84\0\0\0\0pong") | |
| 82 | header = incoming.read(2) | |
| 83 | assert header == (b"\x81\x04" if keep else b"\x88\x02"), header | |
| 84 | if keep: | |
| 85 | assert incoming.read(4) == b"pong" | |
| 86 | finally: | |
| 87 | process.terminate() | |
| 88 | process.wait(timeout=5) | |
| 54 | port, admin = free_port(), free_port() | |
| 55 | 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 | *router.proxy(f"127.0.0.1:{backend.server_port}", " "), "}"]) | |
| 58 | config.write_text(content) | |
| 59 | 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 | process = subprocess.Popen([args.caddy, "run", "--config", str(config)], stdout=log, stderr=log, env=environment) | |
| 62 | try: | |
| 63 | deadline = time.monotonic() + 10 | |
| 64 | while True: | |
| 65 | try: | |
| 66 | client = socket.create_connection(("127.0.0.1", port), timeout=2) | |
| 67 | break | |
| 68 | except OSError: | |
| 69 | assert process.poll() is None and time.monotonic() < deadline, (root / "caddy.log").read_text() | |
| 70 | time.sleep(.05) | |
| 71 | 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 | assert b"101" in incoming.readline() | |
| 74 | while incoming.readline() != b"\r\n": | |
| 75 | pass | |
| 76 | client.sendall(b"\x81\x84\0\0\0\0ping") | |
| 77 | assert incoming.read(6) == b"\x81\x04ping" | |
| 78 | 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 | client.sendall(b"\x81\x84\0\0\0\0pong") | |
| 81 | header = incoming.read(2) | |
| 82 | assert header == b"\x81\x04", header | |
| 83 | assert incoming.read(4) == b"pong" | |
| 84 | finally: | |
| 85 | process.terminate() | |
| 86 | process.wait(timeout=5) | |
| 89 | 87 | backend.shutdown() |
| 90 | print("Caddy reload closes default WebSockets and preserves dashboard streams.") | |
| 88 | print("Caddy reload preserves proxied WebSocket streams.") | |
| 91 | 89 | |
| 92 | 90 | |
| 93 | 91 | if __name__ == "__main__": |
tools/router.py+11-6| ... | ... | @@ -13,6 +13,9 @@ ROUTES = "/var/lib/caddy/routes.caddy" |
| 13 | 13 | TOKEN = "/var/lib/snowglobe/router.token" |
| 14 | 14 | ROUTE_DIR = "/var/lib/snowglobe/routes" |
| 15 | 15 | HOST = 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. | |
| 17 | HEALTH_GRACE = 30 | |
| 18 | last_passing = {} | |
| 16 | 19 | |
| 17 | 20 | |
| 18 | 21 | def nomad(path, token): |
| ... | ... | @@ -28,15 +31,13 @@ def passive_health(upstreams, indent): |
| 28 | 31 | return [f"{indent}fail_duration 30s"] if len(upstreams.split()) > 1 else [] |
| 29 | 32 | |
| 30 | 33 | |
| 31 | def proxy(upstreams, indent, uncompressed=False, host=None, keep_streams=False): | |
| 32 | lines = [f"{indent}reverse_proxy {upstreams} {{", f"{indent} lb_try_duration 5s", | |
| 34 | def proxy(upstreams, indent, uncompressed=False, host=None): | |
| 35 | lines = [f"{indent}reverse_proxy {upstreams} {{", f"{indent} lb_try_duration 5s", f"{indent} stream_close_delay 8h", | |
| 33 | 36 | *passive_health(upstreams, indent + " ")] |
| 34 | 37 | if uncompressed: |
| 35 | 38 | lines.append(f"{indent} header_up Accept-Encoding identity") |
| 36 | 39 | if host: |
| 37 | 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 | 41 | return [*lines, f"{indent}}}"] |
| 41 | 42 | |
| 42 | 43 | |
| ... | ... | @@ -225,7 +226,9 @@ def render(token): |
| 225 | 226 | if alloc not in allocation_checks: |
| 226 | 227 | allocation_checks[alloc] = nomad(f"/v1/allocation/{alloc}/checks", token) |
| 227 | 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 | 232 | continue |
| 230 | 233 | if instance["ServiceName"] == "forward-auth": |
| 231 | 234 | auth_upstreams.add(upstream) |
| ... | ... | @@ -268,6 +271,8 @@ def render(token): |
| 268 | 271 | route = routes.setdefault((listener, ""), {"upstreams": set(), "services": set()}) |
| 269 | 272 | route["upstreams"].add(upstream) |
| 270 | 273 | |
| 274 | for alloc in last_passing.keys() - allocation_checks.keys(): | |
| 275 | del last_passing[alloc] | |
| 271 | 276 | lines = [] |
| 272 | 277 | for (listener, host), route in sorted(routes.items()): |
| 273 | 278 | if host: |
| ... | ... | @@ -490,7 +495,7 @@ def render(token): |
| 490 | 495 | lines += [" handle {", " request_header -User-Name", " request_header -User-Groups", |
| 491 | 496 | f" request_header Snowglobe-Proxy-Token {dashboard_proof}", |
| 492 | 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 | 499 | internal_port = os.environ.get("SNOWGLOBE_INTERNAL_PORT") |
| 495 | 500 | if internal_port is not None: |
| 496 | 501 | internal_host = "dashboard.internal." + os.environ["SNOWGLOBE_DOMAIN"] |