"""Graceful shutdown of an API replica (RUN_DOCKER_TESTS=1). Each test stops ONE API replica and brings it back; dependencies are not touched. """ from __future__ import annotations import hashlib import json import os import subprocess import threading import time import uuid from datetime import datetime import imagegen from helpers import call, chat_for, register ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") STOP_TIMEOUT_S = 15 # = stop_grace_period of the api service # Runs inside the replica: SIGTERM to PID 1 (as `docker stop` does), then probes the # same process directly while HAProxy is still expected to route to it. PROBE = r""" import json, os, signal, time, urllib.error, urllib.request def get(path, token=None): req = urllib.request.Request("http://127.0.0.1:8080" + path) if token: req.add_header("Authorization", "Bearer " + token) try: with urllib.request.urlopen(req, timeout=2) as resp: return resp.status except urllib.error.HTTPError as err: return err.code except Exception as exc: return type(exc).__name__ token = os.environ["DRAIN_TOKEN"] drain = float(os.environ.get("SHUTDOWN_DRAIN_SECONDS", "3")) with open("/proc/1/cmdline", "rb") as f: pid1 = f.read().replace(b"\0", b" ").decode().strip() before = [get("/health/ready"), get("/api/v1/users/me", token)] sent_at = time.time() t0 = time.monotonic() os.kill(1, signal.SIGTERM) samples = [] while time.monotonic() - t0 < drain - 0.8: samples.append([round(time.monotonic() - t0, 2), get("/health/ready"), get("/api/v1/users/me", token)]) time.sleep(0.1) print(json.dumps({"pid1": pid1, "drain": drain, "before": before, "sent_at": sent_at, "samples": samples})) """ # Runs inside the replica: a slow upload (body from stdin) whose body is still being sent # when the drain window ends and the listener is closed. SLOW_UPLOAD = r""" import http.client, json, os, signal, sys, time body = sys.stdin.buffer.read() drain = float(os.environ.get("SHUTDOWN_DRAIN_SECONDS", "3")) conn = http.client.HTTPConnection("127.0.0.1", 8080, timeout=30) conn.putrequest("POST", "/api/v1/chats/%s/attachments?filename=drain.png" % os.environ["DRAIN_CHAT"]) conn.putheader("Authorization", "Bearer " + os.environ["DRAIN_TOKEN"]) conn.putheader("Content-Type", "image/png") conn.putheader("Content-Length", str(len(body))) conn.endheaders() t0 = time.monotonic() step = len(body) // 40 + 1 for i in range(0, len(body), step): conn.send(body[i:i + step]) if i == 0: os.kill(1, signal.SIGTERM) time.sleep((drain + 2) / 40) resp = conn.getresponse() print(json.dumps({"status": resp.status, "body_sent_s": round(time.monotonic() - t0, 2), "json": json.loads(resp.read() or b"null")})) """ def _enabled(name: str) -> bool: if os.environ.get("RUN_DOCKER_TESTS") != "1": print(f"SKIP {name} (set RUN_DOCKER_TESTS=1)") return False return True def _run(args, check=True): proc = subprocess.run(args, cwd=ROOT, capture_output=True, text=True, encoding="utf-8") if check and proc.returncode != 0: raise AssertionError(f"{' '.join(args[:6])} rc={proc.returncode}: {proc.stdout[-800:]}{proc.stderr[-400:]}") return proc def _api_containers(): out = _run(["docker", "compose", "--env-file", ".env", "ps", "-q", "api"]).stdout.split() assert len(out) >= 2, out return out def _inspect(container: str, fmt: str) -> str: return _run(["docker", "inspect", "-f", fmt, container]).stdout.strip() def _docker_time(value: str) -> float: # 2026-11-06T15:37:12.123456789Z → POSIX seconds (nanoseconds cut to microseconds). head, _, frac = value.rstrip("Z").partition(".") stamp = datetime.fromisoformat(head + "+00:00").timestamp() return stamp + (float("0." + frac[:6]) if frac else 0.0) def _wait_in_rotation(host: str, timeout_s: int = 90) -> float: started = time.monotonic() while time.monotonic() - started < timeout_s: try: if call("GET", "/health/ready")["headers"].get("X-Instance-Id") == host: return time.monotonic() - started except Exception: pass time.sleep(0.5) raise AssertionError(f"replica {host} not back in LB rotation after {timeout_s}s") def _wait_restarted(container: str, restarts: int) -> None: # unless-stopped restarts the container after a SIGTERM sent from inside it. deadline = time.monotonic() + 60 while int(_inspect(container, "{{.RestartCount}}")) == restarts: assert time.monotonic() < deadline, "replica did not exit after SIGTERM" time.sleep(0.5) def test_sigterm_drains_readiness_but_keeps_serving(): # After SIGTERM the replica must report /health/ready 503 at once (HAProxy takes it # out after `inter 1s fall 2`) but keep answering normal requests until then. if not _enabled("test_sigterm_drains_readiness_but_keeps_serving"): return actor = register("drain") target = _api_containers()[0] host = _inspect(target, "{{.Config.Hostname}}") restarts = int(_inspect(target, "{{.RestartCount}}")) proc = subprocess.run(["docker", "exec", "-e", "DRAIN_TOKEN", target, "python", "-c", PROBE], cwd=ROOT, capture_output=True, text=True, encoding="utf-8", env=dict(os.environ, DRAIN_TOKEN=actor["token"])) if proc.returncode != 0: _wait_in_rotation(host) raise AssertionError(f"replica exited during the drain window (probe rc={proc.returncode}) {proc.stderr[-300:]}") probe = json.loads(proc.stdout[proc.stdout.index("{"):]) samples = probe["samples"] assert probe["pid1"].startswith("python -m messenger"), probe["pid1"] assert probe["drain"] >= 2, f"drain window {probe['drain']}s < HAProxy inter 1s x fall 2" assert probe["before"] == [200, 200], probe["before"] assert len(samples) >= 5, samples not_served = [s for s in samples if s[2] != 200] assert not not_served, f"requests failed during the drain window: {not_served}" still_ready = [s for s in samples if s[0] >= 0.3 and s[1] != 503] assert not still_ready, f"/health/ready not 503 while draining: {still_ready}" _wait_restarted(target, restarts) # FinishedAt is the exit of the drained process (same clock as the probe in the container). stop_s = _docker_time(_inspect(target, "{{.State.FinishedAt}}")) - probe["sent_at"] assert probe["drain"] - 0.2 <= stop_s < STOP_TIMEOUT_S, stop_s back_s = _wait_in_rotation(host) print(" drain: %d probes, ready 503 / users/me 200; exit %.2fs after SIGTERM; back in LB in %.1fs" % (len(samples), stop_s, back_s)) def test_inflight_upload_finishes_after_listener_closed(): # The body is still arriving when the drain window ends: the listener closes, but the # in-flight upload (spool → S3 PUT → DB commit) must complete before the process exits. if not _enabled("test_inflight_upload_finishes_after_listener_closed"): return alice, bob = register("drain_up_a"), register("drain_up_b") chat = chat_for(alice, bob, title="drain upload") data = imagegen.large_png(2 * 1024 * 1024) target = _api_containers()[0] host = _inspect(target, "{{.Config.Hostname}}") restarts = int(_inspect(target, "{{.RestartCount}}")) proc = subprocess.run(["docker", "exec", "-i", "-e", "DRAIN_TOKEN", "-e", "DRAIN_CHAT", target, "python", "-c", SLOW_UPLOAD], cwd=ROOT, input=data, capture_output=True, env=dict(os.environ, DRAIN_TOKEN=alice["token"], DRAIN_CHAT=chat["id"])) out = proc.stdout.decode("utf-8", "replace") _wait_restarted(target, restarts) back_s = _wait_in_rotation(host) assert proc.returncode == 0, f"upload probe rc={proc.returncode}: {proc.stderr[-300:]!r}" result = json.loads(out[out.index("{"):]) assert result["status"] == 201, result att = result["json"] assert att["sha256"] == hashlib.sha256(data).hexdigest(), att dl = call("GET", f"/api/v1/attachments/{att['id']}/content", 200, token=bob["token"]) assert hashlib.sha256(dl["bytes"]).hexdigest() == att["sha256"] print(" in-flight upload: body sent over %.1fs across listener close -> 201, download via LB OK; back in LB in %.1fs" % (result["body_sent_s"], back_s)) def test_replica_stop_under_load_has_no_errors(): # Closed-loop POSTs through the LB while one replica gets `docker stop`: requests # that HAProxy still sends to it during the drain window must succeed. if not _enabled("test_replica_stop_under_load_has_no_errors"): return alice, bob = register("drain_load_a"), register("drain_load_b") chat = chat_for(alice, bob, title="drain") target = _api_containers()[0] host = _inspect(target, "{{.Config.Hostname}}") stats = {"ok": 0, "target_after_stop": 0, "errors": []} lock = threading.Lock() stop = threading.Event() stopping = threading.Event() def worker(): while not stop.is_set(): key = uuid.uuid4().hex try: r = call("POST", f"/api/v1/chats/{chat['id']}/messages", token=alice["token"], body={"text": "drain-" + key}, headers={"Idempotency-Key": key}) status, instance = r["status"], r["headers"].get("X-Instance-Id") except Exception as exc: status, instance = type(exc).__name__, None with lock: if status == 201: stats["ok"] += 1 if stopping.is_set() and instance == host: stats["target_after_stop"] += 1 else: stats["errors"].append(status) time.sleep(0.05) threads = [threading.Thread(target=worker, daemon=True) for _ in range(4)] for th in threads: th.start() try: time.sleep(1.5) stopping.set() started = time.monotonic() _run(["docker", "stop", "-t", str(STOP_TIMEOUT_S), target]) stop_s = time.monotonic() - started time.sleep(1.5) finally: stop.set() for th in threads: th.join(timeout=10) _run(["docker", "start", target]) back_s = _wait_in_rotation(host) assert not stats["errors"], f"{len(stats['errors'])} errors during replica stop: {stats['errors'][:10]}" assert stats["ok"] >= 20, stats assert stats["target_after_stop"] >= 1, "stopped replica served nothing during its drain window" assert stop_s < STOP_TIMEOUT_S, stop_s print(" stop under load: %d x 201, 0 errors, %d served by stopping replica; docker stop %.2fs; back in LB in %.1fs" % (stats["ok"], stats["target_after_stop"], stop_s, back_s))