445 lines
17 KiB
Python
445 lines
17 KiB
Python
#!/usr/bin/env python3
|
|
"""Grade 4 verification suite for Lab 3:
|
|
1. Resource limits, no exposed API ports bypassing LB, single migration execution.
|
|
2. Cross-replica stateless sessions & shared logout.
|
|
3. Concurrent Idempotency-Key across multiple replicas, canonical JSON replay, 409 conflict, scope isolation.
|
|
4. Sequential failover of each API replica under load with RPS, error count, and recovery time.
|
|
5. Rolling replacement of API replicas under active write load.
|
|
"""
|
|
import base64
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
import datetime as dt
|
|
import json
|
|
from pathlib import Path
|
|
import subprocess
|
|
import sys
|
|
import threading
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
import uuid
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
EVIDENCE_PATH = ROOT / "evidence" / "grade4_checks.json"
|
|
BASE_URL = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:8080"
|
|
|
|
|
|
def run_cmd(cmd):
|
|
return subprocess.run(cmd, cwd=str(ROOT), text=True, capture_output=True, check=True)
|
|
|
|
|
|
def http_call(method, path, body=None, raw_bytes=None, headers=None, timeout=5):
|
|
h = {"Accept": "application/json"}
|
|
data = raw_bytes
|
|
if body is not None:
|
|
data = json.dumps(body).encode("utf-8")
|
|
h["Content-Type"] = "application/json"
|
|
elif raw_bytes is not None:
|
|
h["Content-Type"] = "application/json"
|
|
if headers:
|
|
h.update(headers)
|
|
req = urllib.request.Request(BASE_URL + path, data=data, headers=h, method=method)
|
|
start = time.monotonic()
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
raw = resp.read()
|
|
return (
|
|
resp.code,
|
|
{k.lower(): v for k, v in resp.headers.items()},
|
|
json.loads(raw.decode("utf-8")) if raw else None,
|
|
time.monotonic() - start,
|
|
)
|
|
except urllib.error.HTTPError as err:
|
|
raw = err.read()
|
|
return (
|
|
err.code,
|
|
{k.lower(): v for k, v in err.headers.items()},
|
|
json.loads(raw.decode("utf-8")) if raw else None,
|
|
time.monotonic() - start,
|
|
)
|
|
|
|
|
|
def register_and_login(label):
|
|
username = f"g4_{label}_{uuid.uuid4().hex[:8]}"
|
|
password = f"Grade4Pass-{uuid.uuid4().hex}"
|
|
st, _, user, _ = http_call("POST", "/api/v1/users", {
|
|
"username": username,
|
|
"display_name": f"Student {label}",
|
|
"password": password,
|
|
})
|
|
assert st == 201, f"register failed: {st}"
|
|
basic = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii")
|
|
st, _, sess, _ = http_call("POST", "/api/v1/auth/sessions", headers={"Authorization": f"Basic {basic}"})
|
|
assert st == 201, f"login failed: {st}"
|
|
return {"id": user["id"], "username": username, "token": sess["token"], "headers": {"Authorization": f"Bearer {sess['token']}"}}
|
|
|
|
|
|
def wait_ready(timeout_s=45):
|
|
deadline = time.monotonic() + timeout_s
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
st, _, _, _ = http_call("GET", "/health/ready", timeout=2)
|
|
if st == 200:
|
|
return
|
|
except Exception:
|
|
pass
|
|
time.sleep(0.5)
|
|
raise RuntimeError("LB/API did not become ready within timeout")
|
|
|
|
|
|
def get_api_containers():
|
|
out = run_cmd(["docker", "compose", "--env-file", ".env", "ps", "-q", "api"]).stdout.strip().splitlines()
|
|
result = []
|
|
for cid in out:
|
|
cid = cid.strip()
|
|
if not cid:
|
|
continue
|
|
info = json.loads(run_cmd(["docker", "inspect", cid]).stdout)[0]
|
|
result.append({
|
|
"id": cid,
|
|
"short_id": cid[:12],
|
|
"name": info["Name"].lstrip("/"),
|
|
"hostname": info["Config"]["Hostname"],
|
|
"running": info["State"]["Running"],
|
|
"nano_cpus": info["HostConfig"]["NanoCpus"],
|
|
"memory": info["HostConfig"]["Memory"],
|
|
"ports": info["NetworkSettings"]["Ports"],
|
|
})
|
|
return result
|
|
|
|
|
|
def wait_two_instances(headers, timeout_s=30):
|
|
deadline = time.monotonic() + timeout_s
|
|
seen = set()
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
st, hdrs, _, _ = http_call("GET", "/api/v1/users/me", headers=headers, timeout=2)
|
|
if st == 200:
|
|
inst = hdrs.get("x-instance-id", "")
|
|
if inst:
|
|
seen.add(inst)
|
|
if len(seen) >= 2:
|
|
return sorted(seen)
|
|
except Exception:
|
|
pass
|
|
time.sleep(0.2)
|
|
raise RuntimeError(f"Expected >=2 active instances behind LB, saw {seen}")
|
|
|
|
|
|
def test_infra_and_migrations():
|
|
containers = get_api_containers()
|
|
assert len(containers) >= 2, f"Expected >=2 API replicas, got {len(containers)}"
|
|
for c in containers:
|
|
assert c["nano_cpus"] > 0, f"{c['name']} missing CPU limit"
|
|
assert c["memory"] > 0, f"{c['name']} missing Memory limit"
|
|
for port_key, bindings in (c["ports"] or {}).items():
|
|
assert not bindings, f"{c['name']} exposes host port {port_key}: {bindings}"
|
|
|
|
pg_cid = run_cmd(["docker", "compose", "--env-file", ".env", "ps", "-q", "postgres"]).stdout.strip()
|
|
migs = run_cmd([
|
|
"docker", "exec", pg_cid, "psql", "-U", "messenger", "-d", "messenger", "-tA",
|
|
"-c", "SELECT version FROM schema_migrations ORDER BY version;",
|
|
]).stdout.strip().splitlines()
|
|
assert migs == ["001_init.sql", "002_idempotency.sql"], f"Unexpected schema_migrations: {migs}"
|
|
return {
|
|
"status": "PASS",
|
|
"api_replicas": len(containers),
|
|
"containers": [{"name": c["name"], "short_id": c["short_id"], "nano_cpus": c["nano_cpus"], "memory": c["memory"]} for c in containers],
|
|
"applied_migrations": migs,
|
|
}
|
|
|
|
|
|
def test_stateless_sessions():
|
|
alice = register_and_login("stateless")
|
|
instances = set()
|
|
for _ in range(30):
|
|
st, hdrs, data, _ = http_call("GET", "/api/v1/users/me", headers=alice["headers"])
|
|
assert st == 200 and data["id"] == alice["id"]
|
|
instances.add(hdrs.get("x-instance-id", ""))
|
|
assert len(instances) >= 2, f"Expected >=2 instances serving single session, saw {instances}"
|
|
|
|
# Logout once -> must immediately invalidate across all replicas
|
|
st, _, _, _ = http_call("DELETE", "/api/v1/auth/sessions/current", headers=alice["headers"])
|
|
assert st == 204
|
|
for _ in range(10):
|
|
st, _, _, _ = http_call("GET", "/api/v1/users/me", headers=alice["headers"])
|
|
assert st == 401
|
|
return {"status": "PASS", "observed_instances": sorted(instances)}
|
|
|
|
|
|
def test_concurrent_idempotency():
|
|
alice = register_and_login("idem_a")
|
|
bob = register_and_login("idem_b")
|
|
st, _, chat1, _ = http_call("POST", "/api/v1/chats", {
|
|
"title": "Idempotency Race Chat 1",
|
|
"member_ids": [alice["id"], bob["id"]],
|
|
}, headers=alice["headers"])
|
|
assert st == 201
|
|
st, _, chat2, _ = http_call("POST", "/api/v1/chats", {
|
|
"title": "Idempotency Race Chat 2",
|
|
"member_ids": [alice["id"], bob["id"]],
|
|
}, headers=alice["headers"])
|
|
assert st == 201
|
|
|
|
shared_key = f"race-{uuid.uuid4().hex}"
|
|
text = f"Concurrent payload {shared_key}"
|
|
|
|
def send_once(_i):
|
|
return http_call("POST", f"/api/v1/chats/{chat1['id']}/messages", {"text": text}, headers={
|
|
**alice["headers"],
|
|
"Idempotency-Key": shared_key,
|
|
})
|
|
|
|
with ThreadPoolExecutor(max_workers=20) as pool:
|
|
results = list(pool.map(send_once, range(20)))
|
|
|
|
msg_ids = set()
|
|
insts = set()
|
|
for st, hdrs, msg, _ in results:
|
|
assert st == 201, f"Expected 201 on concurrent idempotent send, got {st}"
|
|
msg_ids.add(msg["id"])
|
|
insts.add(hdrs.get("x-instance-id", ""))
|
|
assert len(msg_ids) == 1, f"Expected single message ID across 20 concurrent calls, got {msg_ids}"
|
|
assert len(insts) >= 2, f"Expected >=2 replicas handling concurrent retries, saw {insts}"
|
|
winning_id = next(iter(msg_ids))
|
|
|
|
# Canonical JSON formatting equivalence (escaped unicode / whitespace)
|
|
escaped_text = "".join(f"\\u{ord(ch):04x}" if ch.isalpha() else ch for ch in text)
|
|
raw_equiv = ('{ "text" : "' + escaped_text + '" }').encode("utf-8")
|
|
st, _, msg_equiv, _ = http_call(
|
|
"POST",
|
|
f"/api/v1/chats/{chat1['id']}/messages",
|
|
raw_bytes=raw_equiv,
|
|
headers={**alice["headers"], "Idempotency-Key": shared_key},
|
|
)
|
|
assert st == 201 and msg_equiv["id"] == winning_id, f"Canonical JSON replay mismatch: {st}"
|
|
|
|
# Different body with same key -> 409 conflict
|
|
st, _, err_body, _ = http_call(
|
|
"POST",
|
|
f"/api/v1/chats/{chat1['id']}/messages",
|
|
{"text": text + " altered"},
|
|
headers={**alice["headers"], "Idempotency-Key": shared_key},
|
|
)
|
|
assert st == 409 and err_body["error"]["code"] == "conflict", f"Expected 409 conflict, got {st}"
|
|
|
|
# Different user with SAME key in SAME chat -> independent message (201, new ID)
|
|
st, _, bob_msg, _ = http_call(
|
|
"POST",
|
|
f"/api/v1/chats/{chat1['id']}/messages",
|
|
{"text": "Bob message with same key"},
|
|
headers={**bob["headers"], "Idempotency-Key": shared_key},
|
|
)
|
|
assert st == 201 and bob_msg["id"] != winning_id
|
|
|
|
# Same user + same key in DIFFERENT chat -> independent message (201, new ID)
|
|
st, _, c2_msg, _ = http_call(
|
|
"POST",
|
|
f"/api/v1/chats/{chat2['id']}/messages",
|
|
{"text": text},
|
|
headers={**alice["headers"], "Idempotency-Key": shared_key},
|
|
)
|
|
assert st == 201 and c2_msg["id"] != winning_id
|
|
|
|
# Verify history of chat1 has strictly 2 messages (alice once + bob once)
|
|
st, _, page, _ = http_call("GET", f"/api/v1/chats/{chat1['id']}/messages?limit=100", headers=alice["headers"])
|
|
assert st == 200 and len(page["items"]) == 2, f"Expected 2 messages in chat1, got {len(page['items'])}"
|
|
|
|
return {
|
|
"status": "PASS",
|
|
"concurrent_requests": 20,
|
|
"unique_message_ids": len(msg_ids),
|
|
"replicas_involved": sorted(insts),
|
|
"canonical_json_replay": "201_same_id",
|
|
"different_body_conflict": 409,
|
|
"scope_isolation_verified": True,
|
|
}
|
|
|
|
|
|
def stop_and_measure_failover(actor, chat, target_container, duration_s=10.0):
|
|
stop_flag = threading.Event()
|
|
results = []
|
|
lock = threading.Lock()
|
|
started = time.monotonic()
|
|
|
|
def worker(wid):
|
|
idx = 0
|
|
while not stop_flag.is_set():
|
|
key = f"seq-{target_container['short_id']}-{wid}-{idx}"
|
|
idx += 1
|
|
t0 = time.monotonic()
|
|
try:
|
|
st, hdrs, msg, lat = http_call("POST", f"/api/v1/chats/{chat['id']}/messages", {
|
|
"text": f"Failover msg {key}",
|
|
}, headers={**actor["headers"], "Idempotency-Key": key}, timeout=3)
|
|
with lock:
|
|
results.append((t0 - started, st == 201, st, hdrs.get("x-instance-id", ""), lat))
|
|
except Exception:
|
|
with lock:
|
|
results.append((t0 - started, False, 0, "", time.monotonic() - t0))
|
|
time.sleep(0.03)
|
|
|
|
threads = [threading.Thread(target=worker, args=(i,)) for i in range(4)]
|
|
for th in threads:
|
|
th.start()
|
|
|
|
time.sleep(1.5)
|
|
t_stop_start = time.monotonic()
|
|
run_cmd(["docker", "stop", "-t", "5", target_container["id"]])
|
|
t_stop_done = time.monotonic()
|
|
|
|
# Continue load after stop
|
|
time.sleep(duration_s - 1.5)
|
|
stop_flag.set()
|
|
for th in threads:
|
|
th.join()
|
|
|
|
total = len(results)
|
|
ok = [r for r in results if r[1]]
|
|
errs = [r for r in results if not r[1]]
|
|
# Find recovery window: last error timestamp relative to stop start (or 0 if 0 errors)
|
|
post_stop_errs = [r[0] - (t_stop_start - started) for r in errs if r[0] >= (t_stop_start - started)]
|
|
recovery_s = max(post_stop_errs) if post_stop_errs else 0.0
|
|
after_stop_insts = sorted({r[3] for r in ok if r[0] > (t_stop_done - started) + 2.0 and r[3]})
|
|
assert target_container["short_id"] not in after_stop_insts, f"Stopped container still served after 2s: {after_stop_insts}"
|
|
|
|
return {
|
|
"stopped_container": target_container["name"],
|
|
"stopped_short_id": target_container["short_id"],
|
|
"stop_duration_s": round(t_stop_done - t_stop_start, 3),
|
|
"total_requests": total,
|
|
"successful_writes": len(ok),
|
|
"failed_requests": len(errs),
|
|
"error_rate": round(len(errs) / total, 5) if total else 0.0,
|
|
"rps": round(len(ok) / duration_s, 2),
|
|
"recovery_seconds_after_stop": round(max(0.0, recovery_s), 3),
|
|
"serving_instances_after_failover": after_stop_insts,
|
|
}
|
|
|
|
|
|
def test_sequential_failover():
|
|
alice = register_and_login("seq_fail")
|
|
st, _, chat, _ = http_call("POST", "/api/v1/chats", {
|
|
"title": "Sequential Failover Chat",
|
|
"member_ids": [alice["id"]],
|
|
}, headers=alice["headers"])
|
|
assert st == 201
|
|
|
|
wait_two_instances(alice["headers"])
|
|
containers = get_api_containers()
|
|
assert len(containers) == 2
|
|
|
|
step1 = stop_and_measure_failover(alice, chat, containers[0], duration_s=10.0)
|
|
run_cmd(["docker", "start", containers[0]["id"]])
|
|
wait_two_instances(alice["headers"])
|
|
|
|
step2 = stop_and_measure_failover(alice, chat, containers[1], duration_s=10.0)
|
|
run_cmd(["docker", "start", containers[1]["id"]])
|
|
wait_two_instances(alice["headers"])
|
|
|
|
return {"status": "PASS", "replica_1_failover": step1, "replica_2_failover": step2}
|
|
|
|
|
|
def test_rolling_update():
|
|
alice = register_and_login("rolling")
|
|
st, _, chat, _ = http_call("POST", "/api/v1/chats", {
|
|
"title": "Rolling Update Chat",
|
|
"member_ids": [alice["id"]],
|
|
}, headers=alice["headers"])
|
|
assert st == 201
|
|
|
|
wait_two_instances(alice["headers"])
|
|
old_containers = get_api_containers()
|
|
old_ids = [c["id"] for c in old_containers]
|
|
|
|
stop_flag = threading.Event()
|
|
stats = {"ok": 0, "err": 0, "insts": set()}
|
|
lock = threading.Lock()
|
|
|
|
def writer(wid):
|
|
idx = 0
|
|
while not stop_flag.is_set():
|
|
key = f"roll-{wid}-{idx}"
|
|
idx += 1
|
|
try:
|
|
st_c, hdrs, _, _ = http_call("POST", f"/api/v1/chats/{chat['id']}/messages", {
|
|
"text": f"Rolling msg {key}",
|
|
}, headers={**alice["headers"], "Idempotency-Key": key}, timeout=4)
|
|
with lock:
|
|
if st_c == 201:
|
|
stats["ok"] += 1
|
|
stats["insts"].add(hdrs.get("x-instance-id", ""))
|
|
else:
|
|
stats["err"] += 1
|
|
except Exception:
|
|
with lock:
|
|
stats["err"] += 1
|
|
time.sleep(0.05)
|
|
|
|
threads = [threading.Thread(target=writer, args=(i,)) for i in range(4)]
|
|
for th in threads:
|
|
th.start()
|
|
|
|
try:
|
|
# Step 1: Surge capacity 2 -> 3 before replacing old replicas one by one
|
|
run_cmd(["docker", "compose", "--env-file", ".env", "up", "-d", "--no-deps", "--scale", "api=3", "--no-recreate", "api"])
|
|
time.sleep(3.5)
|
|
|
|
# Step 2: Gracefully replace each old replica one at a time
|
|
for cid in old_ids:
|
|
run_cmd(["docker", "stop", "-t", "8", cid])
|
|
run_cmd(["docker", "rm", cid])
|
|
run_cmd(["docker", "compose", "--env-file", ".env", "up", "-d", "--no-deps", "--scale", "api=3", "--no-recreate", "api"])
|
|
time.sleep(3.5)
|
|
|
|
# Step 3: Scale back down cleanly 3 -> 2
|
|
current = get_api_containers()
|
|
extra = [c for c in current if c["id"] not in old_ids][-1]
|
|
run_cmd(["docker", "stop", "-t", "8", extra["id"]])
|
|
run_cmd(["docker", "rm", extra["id"]])
|
|
finally:
|
|
stop_flag.set()
|
|
for th in threads:
|
|
th.join()
|
|
|
|
new_ids = sorted(c["short_id"] for c in get_api_containers())
|
|
assert set(new_ids).isdisjoint({c["short_id"] for c in old_containers}), "Old containers were not all replaced"
|
|
total = stats["ok"] + stats["err"]
|
|
return {
|
|
"status": "PASS",
|
|
"old_replicas": [c["short_id"] for c in old_containers],
|
|
"new_replicas": new_ids,
|
|
"total_requests_during_rollout": total,
|
|
"successful_writes": stats["ok"],
|
|
"failed_requests": stats["err"],
|
|
"error_rate": round(stats["err"] / total, 5) if total else 0.0,
|
|
"observed_serving_instances": sorted(x for x in stats["insts"] if x),
|
|
}
|
|
|
|
|
|
def main():
|
|
wait_ready()
|
|
report = {
|
|
"timestamp_utc": dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
"base_url": BASE_URL,
|
|
"checks": {},
|
|
}
|
|
report["checks"]["infra_and_migrations"] = test_infra_and_migrations()
|
|
print("PASS: infra_and_migrations")
|
|
report["checks"]["stateless_sessions"] = test_stateless_sessions()
|
|
print("PASS: stateless_sessions")
|
|
report["checks"]["concurrent_idempotency"] = test_concurrent_idempotency()
|
|
print("PASS: concurrent_idempotency")
|
|
report["checks"]["sequential_failover"] = test_sequential_failover()
|
|
print("PASS: sequential_failover")
|
|
report["checks"]["rolling_update"] = test_rolling_update()
|
|
print("PASS: rolling_update")
|
|
|
|
EVIDENCE_PATH.parent.mkdir(parents=True, exist_ok=True)
|
|
EVIDENCE_PATH.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
|
|
print(f"PASS: all Grade 4 checks succeeded; evidence saved to {EVIDENCE_PATH}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|