Реализовать lab3 на оценку 4: HAProxy, реплики API и общая идемпотентность.

This commit is contained in:
2026-10-30 15:27:54 +03:00
parent 0ab3a341aa
commit 5946fe214c
47 changed files with 3035 additions and 31 deletions
+11
View File
@@ -0,0 +1,11 @@
@echo off
setlocal
cd /d "%~dp0\.."
if "%API_REPLICAS%"=="" set API_REPLICAS=2
docker compose --env-file .env restart postgres redis
if errorlevel 1 exit /b 1
docker compose --env-file .env up -d --no-deps --scale api=%API_REPLICAS% api
if errorlevel 1 exit /b 1
docker compose --env-file .env restart lb
if errorlevel 1 exit /b 1
exit /b 0
+10
View File
@@ -0,0 +1,10 @@
#!/bin/sh
set -eu
# Restart API replicas and all state stores; preserve volumes.
cd "$(dirname "$0")/.."
REPLICAS="${API_REPLICAS:-2}"
docker compose --env-file .env restart postgres redis
# Recreate API fleet at desired scale (migrate already applied; skip one-shot).
docker compose --env-file .env up -d --no-deps --scale "api=${REPLICAS}" api
docker compose --env-file .env restart lb
exit 0
+28
View File
@@ -0,0 +1,28 @@
#!/bin/sh
set -eu
# Grade-4 rolling replacement: recreate API containers one-by-one under LB.
# Usage: scripts/rolling-update.sh
cd "$(dirname "$0")/.."
REPLICAS="${API_REPLICAS:-2}"
ids=$(docker compose --env-file .env ps -q api)
count=0
for id in $ids; do
[ -n "$id" ] || continue
count=$((count + 1))
printf '%s\n' "rolling: stopping $id"
docker stop -t 10 "$id" >/dev/null
# Bring fleet back to desired scale (starts a fresh replica; old stopped removed by up).
docker compose --env-file .env up -d --no-deps --scale "api=${REPLICAS}" --remove-orphans api
# Wait until LB again sees healthy backends via public ready.
i=0
while [ "$i" -lt 60 ]; do
if curl -sf "http://127.0.0.1:8080/health/ready" >/dev/null 2>&1; then
break
fi
i=$((i + 1))
sleep 1
done
printf '%s\n' "rolling: step $count ready"
done
printf '%s\n' "rolling update finished ($count steps, scale=${REPLICAS})"
+150
View File
@@ -0,0 +1,150 @@
#!/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()
+167
View File
@@ -0,0 +1,167 @@
#!/usr/bin/env python3
"""Grade-4 evidence: stop each observed API replica in turn; restore between steps."""
from __future__ import annotations
import base64
import json
import os
import subprocess
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, expected=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
raw = resp.read()
status = resp.code
if expected is not None and status != expected:
raise RuntimeError(f"{method} {path}: expected {expected}, got {status}: {raw[:200]!r}")
js = None
if raw and resp.headers.get_content_type() == "application/json":
js = json.loads(raw.decode("utf-8"))
return {"status": status, "headers": resp.headers, "json": js}
def header(resp, name: str) -> str:
return resp["headers"].get(name) or resp["headers"].get(name.lower()) or ""
def restore_api():
replicas = os.environ.get("API_REPLICAS", "2")
subprocess.check_call(
[
"docker",
"compose",
"--env-file",
".env",
"up",
"-d",
"--no-deps",
"--scale",
f"api={replicas}",
"--remove-orphans",
"api",
],
cwd=ROOT,
)
for _ in range(60):
try:
call("GET", "/health/ready", expected=200)
return
except Exception:
time.sleep(1)
raise RuntimeError("API did not become ready after restore")
def one_round(round_no: int) -> dict:
uname = "seq_" + uuid.uuid4().hex[:10]
pw = "T3st-" + uuid.uuid4().hex
user = call(
"POST",
"/api/v1/users",
{"username": uname, "display_name": "Seq", "password": pw},
expected=201,
)["json"]
cred = base64.b64encode(f"{uname}:{pw}".encode()).decode()
tok = call(
"POST",
"/api/v1/auth/sessions",
headers={"Authorization": "Basic " + cred},
expected=201,
)["json"]["token"]
peer_u = "seqb_" + uuid.uuid4().hex[:10]
peer = call(
"POST",
"/api/v1/users",
{"username": peer_u, "display_name": "SeqB", "password": pw},
expected=201,
)["json"]
chat = call(
"POST",
"/api/v1/chats",
{"title": "seq", "member_ids": [user["id"], peer["id"]]},
token=tok,
expected=201,
)["json"]
observed = set()
for _ in range(40):
observed.add(header(call("GET", "/api/v1/users/me", token=tok, expected=200), "X-Instance-Id"))
if len(observed) < 2:
raise RuntimeError(f"need ≥2 instances, got {observed}")
target = sorted(observed)[round_no % len(observed)]
env = dict(os.environ)
env["TARGET_INSTANCE_ID"] = target
script = ROOT / ("scripts/stop-one.cmd" if os.name == "nt" else "scripts/stop-one.sh")
started = time.monotonic()
proc = subprocess.Popen([str(script)], env=env, cwd=ROOT)
ok = fail = 0
first = None
after = []
while time.monotonic() - started < 20:
code = proc.poll()
try:
key = uuid.uuid4().hex
r = call(
"POST",
f"/api/v1/chats/{chat['id']}/messages",
{"text": "seq-" + key},
token=tok,
headers={"Idempotency-Key": key},
expected=201,
)
ok += 1
if code == 0:
if first is None:
first = time.monotonic() - started
after.append(header(r, "X-Instance-Id"))
except Exception:
fail += 1
time.sleep(0.1)
if proc.poll() is None:
proc.wait(timeout=10)
result = {
"round": round_no,
"observed_before": sorted(observed),
"target": target,
"successful_writes": ok,
"failed_attempts": fail,
"first_recovery_seconds": round(first, 3) if first is not None else None,
"target_absent_in_last5": target not in after[-5:],
}
restore_api()
return result
def main():
results = []
for i in range(2):
results.append(one_round(i))
print(json.dumps(results[-1], ensure_ascii=False))
out = ROOT / "evidence" / "seq-failover.json"
out.write_text(json.dumps(results, ensure_ascii=False, indent=2), encoding="utf-8")
print("WROTE", out)
if __name__ == "__main__":
main()
+17
View File
@@ -0,0 +1,17 @@
@echo off
setlocal EnableExtensions
cd /d "%~dp0\.."
if "%TARGET_INSTANCE_ID%"=="" (
echo stop-one: TARGET_INSTANCE_ID required >&2
exit /b 1
)
for /f "usebackq delims=" %%I in (`docker compose --env-file .env ps -q api`) do (
for /f "usebackq delims=" %%H in (`docker inspect -f "{{.Config.Hostname}}" %%I`) do (
if /I "%%H"=="%TARGET_INSTANCE_ID%" (
docker stop -t 10 %%I >nul
exit /b 0
)
)
)
echo stop-one: replica not found >&2
exit /b 1
+43
View File
@@ -0,0 +1,43 @@
#!/bin/sh
set -eu
# Stop ONE API replica matching TARGET_INSTANCE_ID (= X-Instance-Id / hostname).
# Leave it stopped; do not touch DB/Redis/LB/volumes.
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
cd "$(dirname "$0")/.."
found=""
# Compose project containers for service api
ids=$(docker compose --env-file .env ps -q api 2>/dev/null || true)
for id in $ids; do
[ -n "$id" ] || continue
host=$(docker inspect -f '{{.Config.Hostname}}' "$id")
if [ "$host" = "$TARGET_INSTANCE_ID" ]; then
found=$id
break
fi
iid=$(docker inspect -f '{{range .Config.Env}}{{println .}}{{end}}' "$id" | sed -n 's/^INSTANCE_ID=//p' | head -n1)
if [ -n "$iid" ] && [ "$iid" = "$TARGET_INSTANCE_ID" ]; then
found=$id
break
fi
done
if [ -z "$found" ]; then
# Fallback: any running container with matching hostname (scaled names differ).
for id in $(docker ps -q --filter "ancestor=mtusi-messenger:lab3"); do
host=$(docker inspect -f '{{.Config.Hostname}}' "$id")
if [ "$host" = "$TARGET_INSTANCE_ID" ]; then
found=$id
break
fi
done
fi
if [ -z "$found" ]; then
printf '%s\n' "stop-one: replica not found for TARGET_INSTANCE_ID" >&2
exit 1
fi
# Graceful stop; API marks not-ready on SIGTERM before exit (uvicorn grace ~8s).
docker stop -t 10 "$found" >/dev/null
exit 0
+10
View File
@@ -0,0 +1,10 @@
@echo off
setlocal
cd /d "%~dp0\.."
if "%API_REPLICAS%"=="" set API_REPLICAS=2
docker compose --env-file .env config --quiet
if errorlevel 1 exit /b 1
docker compose --env-file .env up -d --build --scale api=%API_REPLICAS%
if errorlevel 1 exit /b 1
echo stack up: api scale=%API_REPLICAS%, entry http://127.0.0.1:8080
exit /b 0
+8
View File
@@ -0,0 +1,8 @@
#!/bin/sh
set -eu
# Bootstrap lab3 stack with ≥2 API replicas behind LB.
cd "$(dirname "$0")/.."
REPLICAS="${API_REPLICAS:-2}"
docker compose --env-file .env config --quiet
docker compose --env-file .env up -d --build --scale "api=${REPLICAS}"
printf '%s\n' "stack up: api scale=${REPLICAS}, entry http://127.0.0.1:8080"