forked from mtusi2026/mtusi2026lab5
Implement durable image queue with outbox worker and recovery checks
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
"""Create local synthetic credentials once without printing secret values."""
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def main():
|
||||
directory = ROOT / "secrets"
|
||||
directory.mkdir(exist_ok=True)
|
||||
for name in ("postgres_password", "redis_password", "cursor_key", "s3_root_password", "s3_secret_key"):
|
||||
path = directory / name
|
||||
if not path.exists():
|
||||
path.write_text(secrets.token_hex(32) + "\n", encoding="utf-8", newline="\n")
|
||||
else:
|
||||
# Shell command substitution on Linux must not retain a Windows CR.
|
||||
value = path.read_text(encoding="utf-8").strip()
|
||||
path.write_text(value + "\n", encoding="utf-8", newline="\n")
|
||||
pg_password = (directory / "postgres_password").read_text().strip()
|
||||
redis_password = (directory / "redis_password").read_text().strip()
|
||||
for name, value in {
|
||||
"database_url": f"postgresql://messenger:{pg_password}@postgres:5432/messenger",
|
||||
"cache_url": f"redis://:{redis_password}@redis:6379/0",
|
||||
}.items():
|
||||
path = directory / name
|
||||
if not path.exists():
|
||||
path.write_text(value + "\n", encoding="utf-8", newline="\n")
|
||||
env = ROOT / ".env"
|
||||
if not env.exists():
|
||||
env.write_bytes((ROOT / ".env.example").read_bytes())
|
||||
print("PASS: local .env and secret files exist; existing values preserved")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Docker operations scoped to the configured local Compose project."""
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def command(args, timeout=120, env=None):
|
||||
result = subprocess.run(args, cwd=ROOT, capture_output=True, text=True,
|
||||
encoding="utf-8", errors="replace", timeout=timeout, env=env)
|
||||
if result.returncode:
|
||||
# Commands and stderr can contain secrets. Keep detailed errors local.
|
||||
raise RuntimeError("Local command failed: " + " ".join(args[:3]) + "\n" + result.stderr[-1500:])
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def compose(*args, timeout=120, env=None):
|
||||
return command(["docker", "compose", "--env-file", ".env", *args], timeout, env)
|
||||
|
||||
|
||||
def project():
|
||||
return os.getenv("COMPOSE_PROJECT_NAME") or json.loads(compose("config", "--format", "json"))["name"]
|
||||
|
||||
|
||||
def containers(service="api", running=True):
|
||||
args = ["docker", "ps"] + ([] if running else ["-a"])
|
||||
ids = command(args + ["--filter", "label=com.docker.compose.project=" + project(),
|
||||
"--filter", "label=com.docker.compose.service=" + service,
|
||||
"--filter", "label=com.docker.compose.oneoff=False", "--format", "{{.ID}}"])
|
||||
return json.loads(command(["docker", "inspect", *ids.split()])) if ids else []
|
||||
|
||||
|
||||
def summary():
|
||||
result = []
|
||||
for service in ("api", "postgres", "redis", "broker", "worker", "publisher", "minio", "lb"):
|
||||
for row in containers(service, running=False):
|
||||
result.append({"service": service, "id": row["Id"], "name": row["Name"].lstrip("/"),
|
||||
"started_at": row["State"]["StartedAt"], "status": row["State"]["Status"],
|
||||
"image": row["Image"], "user": row["Config"]["User"],
|
||||
"memory_bytes": row["HostConfig"]["Memory"], "nano_cpus": row["HostConfig"]["NanoCpus"],
|
||||
"published_ports": row["HostConfig"]["PortBindings"],
|
||||
"volumes": [m["Name"] for m in row["Mounts"] if m["Type"] == "volume"]})
|
||||
return result
|
||||
|
||||
|
||||
def runtime(line):
|
||||
with socket.create_connection(("lb", 9999), timeout=3) as sock:
|
||||
sock.sendall((line + "\n").encode())
|
||||
sock.shutdown(socket.SHUT_WR)
|
||||
chunks = []
|
||||
while True:
|
||||
data = sock.recv(65536)
|
||||
if not data:
|
||||
return b"".join(chunks).decode()
|
||||
chunks.append(data)
|
||||
|
||||
|
||||
def drain(address):
|
||||
lines = runtime("show servers state messenger").splitlines()
|
||||
fields = next(line[2:].split() for line in lines if line.startswith("# "))
|
||||
for line in lines:
|
||||
values = line.split()
|
||||
if not values or line.startswith("#") or len(values) != len(fields):
|
||||
continue
|
||||
row = dict(zip(fields, values))
|
||||
if row["srv_addr"] == address:
|
||||
slot = "messenger/" + row["srv_name"]
|
||||
runtime("set server " + slot + " state drain")
|
||||
# Let requests already assigned to this replica finish (HTTP budget 5 s).
|
||||
deadline = time.monotonic() + 7
|
||||
while time.monotonic() < deadline:
|
||||
stats = list(csv.DictReader(io.StringIO(runtime("show stat").lstrip("# "))))
|
||||
active = [s for s in stats if s["pxname"] == "messenger" and s["svname"] == row["srv_name"]]
|
||||
if active and int(active[0]["scur"]) == 0:
|
||||
return slot
|
||||
time.sleep(.1)
|
||||
raise RuntimeError("Replica did not drain within 7 seconds")
|
||||
raise RuntimeError("Backend address was not found in HAProxy")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
if sys.argv[1] == "drain":
|
||||
print(drain(sys.argv[2]))
|
||||
elif sys.argv[1] == "ready":
|
||||
runtime("set server " + sys.argv[2] + " state ready")
|
||||
elif sys.argv[1] == "summary":
|
||||
print(json.dumps(summary(), indent=2))
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose --env-file .env restart --timeout 6 api postgres redis broker minio lb worker publisher
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
exec python scripts/stop_one.py
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Stop exactly the replica selected by the public failover scenario."""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from ops import ROOT, command, containers
|
||||
|
||||
|
||||
def main():
|
||||
target = os.environ["TARGET_INSTANCE_ID"]
|
||||
matches = [row for row in containers() if target.startswith(row["Config"]["Hostname"] + "-")]
|
||||
if len(matches) != 1:
|
||||
raise RuntimeError("Target does not identify exactly one running API replica")
|
||||
row = matches[0]
|
||||
started = time.monotonic()
|
||||
command(["docker", "stop", "--time", "6", row["Id"]], timeout=9)
|
||||
state = json.loads(command(["docker", "inspect", row["Id"]]))[0]["State"]
|
||||
assert not state["Running"] and state["ExitCode"] == 0, "Graceful shutdown failed"
|
||||
report = {"target_instance": target, "container": row["Id"], "exit_code": state["ExitCode"],
|
||||
"stop_seconds": round(time.monotonic() - started, 3), "remains_stopped": True}
|
||||
(ROOT / "evidence" / "last-stop.json").write_text(json.dumps(report, indent=2) + "\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Explicit local verification with sanitized logs; never deletes volumes."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
EVIDENCE=ROOT/'evidence'
|
||||
def run(name,args):
|
||||
start=time.monotonic()
|
||||
result=subprocess.run(['docker','compose','--env-file','.env',*args],cwd=ROOT,
|
||||
stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,encoding='utf-8',errors='replace')
|
||||
(EVIDENCE/name).write_text(result.stdout,encoding='utf-8')
|
||||
if result.returncode:raise RuntimeError(name+' failed; inspect evidence')
|
||||
print('PASS',name,flush=True)
|
||||
return round(time.monotonic()-start,3)
|
||||
def main():
|
||||
EVIDENCE.mkdir(exist_ok=True)
|
||||
results={}
|
||||
if '--build' in sys.argv:run('build.txt',['build','api','checks'])
|
||||
run('startup.txt',['up','-d','--no-build','--wait','--wait-timeout','180'])
|
||||
results['public']=run('smoke.txt',['run','--rm','--no-deps','checks','make','check','test'])
|
||||
results['images']=run('images.txt',['run','--rm','--no-deps','-e','PYTHONPATH=/app','checks','python','-m','unittest','discover','-s','student-tests','-p','test_images.py','-v'])
|
||||
results['pipeline']=run('pipeline.txt',['run','--rm','--no-deps','-e','PYTHONPATH=/app','checks','python','student-tests/pipeline_checks.py'])
|
||||
run('before-restart.json',['run','--rm','--no-deps','checks','python','scripts/ops.py','summary'])
|
||||
results['persistence']=run('persistence.txt',['run','--rm','--no-deps','checks','sh','-ec','chmod +x scripts/restart.sh; make test-persistence ACTION_SCRIPT=scripts/restart.sh'])
|
||||
run('after-restart.json',['run','--rm','--no-deps','checks','python','scripts/ops.py','summary'])
|
||||
results['failover']=run('failover.txt',['run','--rm','--no-deps','checks','sh','-ec','chmod +x scripts/stop-one.sh; make test-failover ACTION_SCRIPT=scripts/stop-one.sh'])
|
||||
run('restore.txt',['start','api'])
|
||||
results['final_smoke']=run('smoke-final.txt',['run','--rm','--no-deps','checks','make','test'])
|
||||
(EVIDENCE/'verification.json').write_text(json.dumps({'date':'2026-11-21','seconds':results,'result':'PASS'},indent=2))
|
||||
if __name__=='__main__':main()
|
||||
Reference in New Issue
Block a user