forked from mtusi2026/mtusi2026lab3
151 lines
4.6 KiB
Python
151 lines
4.6 KiB
Python
#!/usr/bin/env python3
|
|
"""Grade-4: closed-loop POSTs during rolling API replacement."""
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import json
|
|
import os
|
|
import subprocess
|
|
import threading
|
|
import time
|
|
import uuid
|
|
import urllib.error
|
|
import urllib.request
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/")
|
|
|
|
|
|
def call(method, path, body=None, token=None, headers=None):
|
|
h = {"Accept": "application/json"}
|
|
if token:
|
|
h["Authorization"] = "Bearer " + token
|
|
data = None
|
|
if body is not None:
|
|
data = json.dumps(body).encode("utf-8")
|
|
h["Content-Type"] = "application/json"
|
|
if headers:
|
|
h.update(headers)
|
|
req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
|
|
try:
|
|
resp = urllib.request.urlopen(req, timeout=5)
|
|
except urllib.error.HTTPError as err:
|
|
resp = err
|
|
except Exception as exc:
|
|
return {"status": 0, "error": type(exc).__name__}
|
|
raw = resp.read()
|
|
js = None
|
|
if raw and resp.headers.get_content_type() == "application/json":
|
|
js = json.loads(raw.decode("utf-8"))
|
|
return {"status": resp.code, "json": js, "ms": 0}
|
|
|
|
|
|
def bootstrap():
|
|
uname = "roll_" + uuid.uuid4().hex[:10]
|
|
pw = "T3st-" + uuid.uuid4().hex
|
|
user = call("POST", "/api/v1/users", {"username": uname, "display_name": "Roll", "password": pw})
|
|
assert user["status"] == 201, user
|
|
cred = base64.b64encode(f"{uname}:{pw}".encode()).decode()
|
|
tok = call("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + cred})["json"]["token"]
|
|
peer_u = "rollb_" + uuid.uuid4().hex[:10]
|
|
peer = call("POST", "/api/v1/users", {"username": peer_u, "display_name": "RollB", "password": pw})["json"]
|
|
chat = call(
|
|
"POST",
|
|
"/api/v1/chats",
|
|
{"title": "roll", "member_ids": [user["json"]["id"], peer["id"]]},
|
|
token=tok,
|
|
)["json"]
|
|
return tok, chat["id"]
|
|
|
|
|
|
def main():
|
|
tok, chat_id = bootstrap()
|
|
stats = {"ok": 0, "err": 0, "latencies_ms": []}
|
|
stop = threading.Event()
|
|
|
|
def worker():
|
|
while not stop.is_set():
|
|
key = uuid.uuid4().hex
|
|
t0 = time.monotonic()
|
|
r = call(
|
|
"POST",
|
|
f"/api/v1/chats/{chat_id}/messages",
|
|
{"text": "roll-" + key},
|
|
token=tok,
|
|
headers={"Idempotency-Key": key},
|
|
)
|
|
dt = (time.monotonic() - t0) * 1000
|
|
if r.get("status") == 201:
|
|
stats["ok"] += 1
|
|
stats["latencies_ms"].append(dt)
|
|
else:
|
|
stats["err"] += 1
|
|
time.sleep(0.05)
|
|
|
|
threads = [threading.Thread(target=worker, daemon=True) for _ in range(4)]
|
|
for th in threads:
|
|
th.start()
|
|
time.sleep(2) # warm-up
|
|
# Rolling: stop one container, scale back, repeat for each current replica.
|
|
ids = (
|
|
subprocess.check_output(
|
|
["docker", "compose", "--env-file", ".env", "ps", "-q", "api"],
|
|
cwd=ROOT,
|
|
text=True,
|
|
)
|
|
.strip()
|
|
.split()
|
|
)
|
|
for cid in ids:
|
|
subprocess.check_call(["docker", "stop", "-t", "10", cid], cwd=ROOT)
|
|
subprocess.check_call(
|
|
[
|
|
"docker",
|
|
"compose",
|
|
"--env-file",
|
|
".env",
|
|
"up",
|
|
"-d",
|
|
"--no-deps",
|
|
"--scale",
|
|
"api=2",
|
|
"--remove-orphans",
|
|
"api",
|
|
],
|
|
cwd=ROOT,
|
|
)
|
|
# wait until ready through LB
|
|
for _ in range(60):
|
|
if call("GET", "/health/ready").get("status") == 200:
|
|
break
|
|
time.sleep(0.5)
|
|
time.sleep(2)
|
|
time.sleep(2)
|
|
stop.set()
|
|
for th in threads:
|
|
th.join(timeout=5)
|
|
lats = sorted(stats["latencies_ms"])
|
|
def pct(p):
|
|
if not lats:
|
|
return None
|
|
return round(lats[min(len(lats) - 1, int(len(lats) * p))], 2)
|
|
duration = max(sum(lats) / 1000.0, 1e-6)
|
|
# Approximate wall duration from thread runtime ~ warm+rolling
|
|
summary = {
|
|
"successful": stats["ok"],
|
|
"errors": stats["err"],
|
|
"p50_ms": pct(0.50),
|
|
"p95_ms": pct(0.95),
|
|
"p99_ms": pct(0.99),
|
|
"replicas_rolled": len(ids),
|
|
}
|
|
out = ROOT / "evidence" / "rolling-load.json"
|
|
out.write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
print(json.dumps(summary, ensure_ascii=False))
|
|
print("WROTE", out)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|