Implement shared idempotency, health-aware balancing and replica lifecycle checks

This commit is contained in:
2026-11-06 17:58:43 +03:00
parent 0ab3a341aa
commit 029bf9b377
35 changed files with 2470 additions and 20 deletions
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env python3
"""Create a private local secret directory once; never rotate existing volumes implicitly."""
import os
import secrets
from pathlib import Path
root = Path(__file__).resolve().parents[1]
private = root / "secrets"
private.mkdir(mode=0o700, exist_ok=True)
os.chmod(private, 0o700)
password_file = private / "postgres_password"
if not password_file.exists():
password_file.write_text(secrets.token_urlsafe(32))
password = password_file.read_text().strip()
values = {
"database_url": "postgresql://messenger:" + password + "@postgres:5432/messenger",
"cache_url": "redis://cache:6379/0",
}
for name, value in values.items():
path = private / name
if not path.exists():
path.write_text(value)
# The parent directory is private on the host; files must be readable by non-root API
# through Compose's file-backed secret mount (uid/mode mapping is not portable).
for path in private.iterdir():
os.chmod(path, 0o644)
if not (root / ".env").exists():
(root / ".env").write_text("PUBLIC_PORT=8083\nSESSION_TTL_SECONDS=3600\n")
print("Local configuration ready; existing secret values preserved.")
+14
View File
@@ -0,0 +1,14 @@
"""Record non-secret container identity/lifecycle fields for restart evidence."""
import json
import subprocess
import sys
from pathlib import Path
ids = subprocess.check_output(["docker", "compose", "ps", "-q"], text=True).split()
rows = []
for cid in ids:
raw = json.loads(subprocess.check_output(["docker", "inspect", cid], text=True))[0]
rows.append({"id": cid, "service": raw["Config"]["Labels"]["com.docker.compose.service"],
"image_id": raw["Image"], "started_at": raw["State"]["StartedAt"],
"cpu_quota": raw["HostConfig"]["NanoCpus"], "memory": raw["HostConfig"]["Memory"]})
Path(sys.argv[1]).write_text(json.dumps(rows, indent=2) + "\n")
+7
View File
@@ -0,0 +1,7 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
python3 scripts/container_snapshot.py evidence/restart-before.json
docker compose restart postgres cache api lb
docker compose up -d --wait --no-recreate
python3 scripts/container_snapshot.py evidence/restart-after.json
+14
View File
@@ -0,0 +1,14 @@
#!/bin/sh
# Sequential replacement; never stop the surviving healthy replica.
set -eu
cd "$(dirname "$0")/.."
: "${API_IMAGE:?Set API_IMAGE to the already built target image}"
export API_IMAGE
ids=$(docker compose ps -q api)
for id in $ids; do
python3 scripts/wait_replicas.py 2
docker stop --time 8 "$id" >/dev/null
docker rm "$id" >/dev/null
docker compose up -d --no-deps --no-recreate --scale api=2 --wait api
python3 scripts/wait_replicas.py 2
done
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
python3 scripts/stop_one.py
+19
View File
@@ -0,0 +1,19 @@
"""Map a process alias to its real container, then leave exactly it stopped."""
import json
import os
import subprocess
wanted = os.environ["TARGET_INSTANCE_ID"]
ids = subprocess.check_output(["docker", "compose", "ps", "-q", "api"], text=True).split()
for cid in ids:
result = subprocess.run(
["docker", "exec", cid, "python", "-c",
"import urllib.request; r=urllib.request.urlopen('http://127.0.0.1:8080/health/live'); print(r.headers['X-Instance-Id'])"],
text=True, capture_output=True, check=False,
)
if result.returncode == 0 and result.stdout.strip() == wanted:
subprocess.run(["docker", "stop", "--time", "8", cid], check=True, stdout=subprocess.DEVNULL)
print(json.dumps({"stopped_container": cid, "instance_id": wanted}))
break
else:
raise SystemExit("Target instance not found among this project's API containers")
+53
View File
@@ -0,0 +1,53 @@
"""A live process with lost DB network must be excluded by the LB."""
import json
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client
def cmd(*args):
return subprocess.check_output(args, cwd=ROOT, text=True).strip()
def main():
c = Client("http://127.0.0.1:8083")
actor = c.user("readiness")
target = cmd("docker", "compose", "ps", "-q", "api").split()[0]
raw = json.loads(cmd("docker", "inspect", target))[0]
backend = next(n for n in raw["NetworkSettings"]["Networks"] if n.endswith("_backend"))
probe = """import json,urllib.request,urllib.error
try: r=urllib.request.urlopen('http://127.0.0.1:8080/health/ready',timeout=8)
except urllib.error.HTTPError as e: r=e
print(json.dumps({'status':r.code,'alias':r.headers['X-Instance-Id']}))"""
initial = json.loads(cmd("docker", "exec", target, "python", "-c", probe))
assert initial["status"] == 200
started = time.monotonic()
cmd("docker", "network", "disconnect", backend, target)
try:
failed = json.loads(cmd("docker", "exec", target, "python", "-c", probe))
assert failed["status"] == 503
time.sleep(4)
observations = []
for _ in range(30):
response = c.call("GET", "/api/v1/users/me", actor=actor, schema="User")
alias = response["headers"]["X-Instance-Id"]
assert alias != initial["alias"]
observations.append(alias)
result = {"target": target, "failed_instance": initial["alias"], "direct_readiness": 503,
"seconds_until_verification": time.monotonic() - started,
"lb_successful_requests": len(observations), "lb_instances": sorted(set(observations))}
finally:
cmd("docker", "network", "connect", "--alias", "api", backend, target)
subprocess.run([sys.executable, "scripts/wait_replicas.py", "2"], cwd=ROOT, check=True)
result["recovered_two_instances"] = True
(ROOT / "evidence/readiness-isolation.json").write_text(json.dumps(result, indent=2) + "\n")
print(json.dumps(result, indent=2))
if __name__ == "__main__":
main()
+95
View File
@@ -0,0 +1,95 @@
"""Stop each real API process under traffic; retain confirmed writes and source aliases."""
import json
import os
import subprocess
import sys
import threading
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure
def compose(*args):
return subprocess.check_output(["docker", "compose", *args], cwd=ROOT, text=True)
def aliases():
result = {}
for cid in compose("ps", "-q", "api").split():
alias = subprocess.check_output([
"docker", "exec", cid, "python", "-c",
"import urllib.request; print(urllib.request.urlopen('http://127.0.0.1:8080/health/live').headers['X-Instance-Id'])",
], text=True).strip()
result[cid] = alias
return result
def main():
compose("up", "-d", "--no-recreate", "--wait")
subprocess.run([sys.executable, "scripts/wait_replicas.py", "2"], cwd=ROOT, check=True)
c = Client("http://127.0.0.1:8083")
actor, _, _, chat = c.bootstrap()
initial = aliases()
runs = []
for target_container, target_alias in initial.items():
successful, errors = [], []
stop = threading.Event()
stopped_at = None
def traffic():
while not stop.is_set():
try:
response = c.message(actor, chat, "failover-proof")
successful.append({"at": time.monotonic(), "id": response["json"]["id"],
"instance": response["headers"]["X-Instance-Id"]})
except Failure:
errors.append(time.monotonic())
started = time.monotonic()
thread = threading.Thread(target=traffic)
thread.start()
time.sleep(1)
stopped_at = time.monotonic()
subprocess.run(["scripts/stop-one.sh"], cwd=ROOT,
env={**os.environ, "TARGET_INSTANCE_ID": target_alias}, check=True)
time.sleep(4)
stop.set()
thread.join()
elapsed = time.monotonic() - started
after = [x for x in successful if x["at"] > stopped_at]
assert after and all(x["instance"] != target_alias for x in after[-5:])
assert min(x["at"] for x in after) - stopped_at <= 10
state = json.loads(subprocess.check_output(["docker", "inspect", target_container], text=True))[0]["State"]
assert not state["Running"]
runs.append({"target_container": target_container, "target_alias": target_alias,
"successful_writes": len(successful), "failed_attempts": len(errors),
"successful_rps": len(successful) / elapsed,
"recovery_seconds": min(x["at"] for x in after) - stopped_at,
"observed_after": sorted({x["instance"] for x in after[-5:]}),
"target_running_after_hook": state["Running"]})
subprocess.run(["docker", "start", target_container], check=True, stdout=subprocess.DEVNULL)
subprocess.run([sys.executable, "scripts/wait_replicas.py", "2"], cwd=ROOT, check=True)
# Verify every acknowledged write, without assuming failed requests did not commit.
items, cursor = [], None
while True:
path = f"/api/v1/chats/{chat['id']}/messages?limit=100"
if cursor:
path += "&cursor=" + cursor
page = c.call("GET", path, actor=actor, schema="MessagePage")["json"]
items.extend(page["items"])
cursor = page["next_cursor"]
if cursor is None:
break
ids = {x["id"] for x in items}
assert all(x["id"] in ids for x in successful)
runs[-1]["all_confirmed_present"] = True
report = {"real_instances_before": initial, "runs": runs, "pass": True}
(ROOT / "evidence/replica-failures.json").write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps(report, indent=2))
if __name__ == "__main__":
main()
+79
View File
@@ -0,0 +1,79 @@
"""Sequential real image replacement under message traffic."""
import json
import os
import subprocess
import sys
import threading
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure
def snapshots():
ids = subprocess.check_output(["docker", "compose", "ps", "-q", "api"], cwd=ROOT, text=True).split()
rows = []
for cid in ids:
raw = json.loads(subprocess.check_output(["docker", "inspect", cid], text=True))[0]
rows.append({"id": cid, "image_id": raw["Image"], "started_at": raw["State"]["StartedAt"]})
return rows
def main():
subprocess.run(["docker", "build", "-t", "mtusi-vasilev:lab3-rolling", "-"],
input="FROM mtusi-vasilev:lab3\nLABEL org.mtusi.rolling-proof=revision-2\n", text=True, check=True)
before = snapshots()
c = Client("http://127.0.0.1:8083")
actor, _, _, chat = c.bootstrap()
stop = threading.Event()
successes, errors = [], []
def traffic():
while not stop.is_set():
try:
response = c.message(actor, chat, "rolling-proof")
successes.append({"id": response["json"]["id"], "at": time.monotonic(),
"instance": response["headers"]["X-Instance-Id"]})
except Failure:
errors.append(time.monotonic())
started = time.monotonic()
thread = threading.Thread(target=traffic)
thread.start()
try:
time.sleep(1)
subprocess.run(["scripts/rolling-update.sh"], cwd=ROOT,
env={**os.environ, "API_IMAGE": "mtusi-vasilev:lab3-rolling"}, check=True)
time.sleep(2)
finally:
stop.set()
thread.join()
elapsed = time.monotonic() - started
after = snapshots()
assert not {x["id"] for x in before} & {x["id"] for x in after}
assert {x["image_id"] for x in before} != {x["image_id"] for x in after}
items, cursor = [], None
while True:
path = f"/api/v1/chats/{chat['id']}/messages?limit=100"
if cursor:
path += "&cursor=" + cursor
page = c.call("GET", path, actor=actor, schema="MessagePage")["json"]
items.extend(page["items"])
cursor = page["next_cursor"]
if cursor is None:
break
assert {x["id"] for x in successes} <= {x["id"] for x in items}
times = [started, *[x["at"] for x in successes], started + elapsed]
result = {"before": before, "after": after, "successful_writes": len(successes),
"failed_attempts": len(errors), "elapsed_seconds": elapsed,
"successful_rps": len(successes) / elapsed,
"observed_instances": sorted({x["instance"] for x in successes}),
"largest_success_gap_seconds": max(b-a for a,b in zip(times,times[1:])),
"all_confirmed_present": True,
"note": "Target image differs by revision label; same API/schema. This verifies sequential replacement, not arbitrary schema compatibility."}
(ROOT / "evidence/rolling-update.json").write_text(json.dumps(result, indent=2) + "\n")
print(json.dumps(result, indent=2))
if __name__ == "__main__":
main()
+21
View File
@@ -0,0 +1,21 @@
import os
import sys
import time
import urllib.error
import urllib.request
wanted = int(sys.argv[1])
url = "http://127.0.0.1:" + os.environ.get("PUBLIC_PORT", "8083") + "/health/ready"
deadline = time.monotonic() + 40
seen = set()
while time.monotonic() < deadline:
try:
with urllib.request.urlopen(url, timeout=2) as response:
seen.add(response.headers["X-Instance-Id"])
if len(seen) >= wanted:
break
except (urllib.error.URLError, TimeoutError):
seen.clear()
time.sleep(0.1)
else:
raise SystemExit("LB did not expose enough healthy replicas")