Реализовать лабораторную 3: две API-реплики за Nginx, Idempotency-Key, failover и эксперимент масштабирования

This commit is contained in:
alenchha
2026-10-28 17:28:48 +03:00
parent 0ab3a341aa
commit fbb8916fc8
97 changed files with 2838 additions and 21 deletions
+28
View File
@@ -0,0 +1,28 @@
#!/bin/bash
set -eu
cd "$(dirname "$0")/.."
OUT="${OUT:-evidence}"
DURATION="${DURATION:-60}"
wait_healthy() {
local deadline=$((SECONDS + 60))
until [ "$(docker inspect -f '{{.State.Health.Status}}' "$(docker compose ps -q "$1")")" = healthy ]; do
[ $SECONDS -lt $deadline ] || { echo "ERROR: $1 not healthy" >&2; return 1; }
sleep 1
done
}
python3 tests/load.py --duration "$DURATION" --concurrency 4 --output "$OUT/rolling_load.json" > /dev/null &
load_pid=$!
sleep 10
for api in api-1 api-2; do
old=$(docker compose ps -q "$api")
echo "$(date -u +%H:%M:%S) recreate $api (old container ${old:0:12})"
docker compose up -d --no-deps --force-recreate "$api" > /dev/null 2>&1
wait_healthy "$api"
echo "$(date -u +%H:%M:%S) $api healthy (new container $(docker compose ps -q "$api" | cut -c1-12))"
sleep 10
done
wait "$load_pid"
cat "$OUT/rolling_load.json"
+70
View File
@@ -0,0 +1,70 @@
#!/bin/bash
set -eu
cd "$(dirname "$0")/.."
BASE_URL="${BASE_URL:-http://localhost:8080}"
DURATION="${DURATION:-30}"
CONCURRENCY="${CONCURRENCY:-16}"
RUNS="${RUNS:-3}"
OUT="${OUT:-evidence/scaling}"
CONFIGS="${CONFIGS:-A1:1:1.00:512M A2:2:0.50:256M A4:4:0.25:128M B1:1:0.50:256M B4:4:0.50:256M}"
mkdir -p "$OUT"
wait_instances() {
local want=$1 deadline=$((SECONDS + 90)) seen
while [ $SECONDS -lt $deadline ]; do
seen=$(for _ in $(seq 1 $((want * 4))); do
curl -s -D - -o /dev/null "$BASE_URL/health/ready" | tr -d '\r' | awk -F': ' 'tolower($1)=="x-instance-id"{print $2}'
done | sort -u | grep -c . || true)
[ "$seen" -eq "$want" ] && return 0
sleep 2
done
echo "ERROR: expected $want instances, saw $seen" >&2
return 1
}
for cfg in $CONFIGS; do
IFS=: read -r label replicas cpus mem <<< "$cfg"
export REPLICAS=$replicas API_CPUS=$cpus API_MEM=$mem
files=(-f compose.yaml -f infra/scaling/limits.yaml)
[ "$replicas" -eq 4 ] && files+=(-f infra/scaling/replicas-4.yaml)
apis=$(seq -f "api-%g" 1 "$replicas" | tr '\n' ' ')
echo "=== $label: $replicas x ${cpus} CPU / $mem ==="
docker compose "${files[@]}" up -d --force-recreate $apis >/dev/null 2>&1
for extra in api-2 api-3 api-4; do
n=${extra#api-}
[ "$n" -gt "$replicas" ] && docker compose -f compose.yaml -f infra/scaling/limits.yaml -f infra/scaling/replicas-4.yaml stop "$extra" >/dev/null 2>&1 || true
done
docker compose "${files[@]}" up -d --no-deps --force-recreate nginx >/dev/null 2>&1
wait_instances "$replicas"
{
echo "config=$label replicas=$replicas api_cpus=$cpus api_mem=$mem concurrency=$CONCURRENCY duration=$DURATION"
for c in $apis; do
docker inspect --format "$c NanoCpus={{.HostConfig.NanoCpus}} Memory={{.HostConfig.Memory}}" \
"$(docker compose "${files[@]}" ps -q "$c")"
done
} > "$OUT/${label}_limits.txt"
python3 tests/load.py --base-url "$BASE_URL" --duration 5 --concurrency "$CONCURRENCY" >/dev/null
since=$(date -u +%Y-%m-%dT%H:%M:%SZ)
for run in $(seq 1 "$RUNS"); do
(sleep $((DURATION / 2)); docker stats --no-stream --format '{{.Name}} {{.CPUPerc}} {{.MemUsage}}' \
> "$OUT/${label}_run${run}_stats.txt") &
python3 tests/load.py --base-url "$BASE_URL" --duration "$DURATION" --concurrency "$CONCURRENCY" \
--output "$OUT/${label}_run${run}.json" >/dev/null
wait
python3 -c "import json;d=json.load(open('$OUT/${label}_run${run}.json'));l=d['successful_latency_ms'];print(' run $run: rps=%s err=%s p50=%s p95=%s p99=%s'%(d['successful_rps'],d['failed_requests'],l['p50'],l['p95'],l['p99']))"
done
docker compose "${files[@]}" logs --since "$since" nginx 2>&1 \
| grep -E '" [45][0-9][0-9] |\[(error|warn)\]' > "$OUT/${label}_nginx_problems.txt" || true
done
export REPLICAS=2 API_CPUS=0.50 API_MEM=256M
docker compose -f compose.yaml -f infra/scaling/replicas-4.yaml rm -sf api-3 api-4 >/dev/null 2>&1 || true
docker compose up -d --force-recreate api-1 api-2 nginx >/dev/null 2>&1
wait_instances 2
python3 student-tests/scaling_summary.py "$OUT"
+98
View File
@@ -0,0 +1,98 @@
#!/usr/bin/env python3
import glob
import json
import os
import re
import statistics
import sys
out = sys.argv[1] if len(sys.argv) > 1 else "evidence/scaling"
rows = {}
for path in sorted(glob.glob(os.path.join(out, "*_run*.json"))):
label = re.match(r"(.+)_run\d+\.json", os.path.basename(path)).group(1)
d = json.load(open(path))
rows.setdefault(label, []).append(d)
meta = {}
for label in rows:
with open(os.path.join(out, label + "_limits.txt")) as f:
meta[label] = dict(kv.split("=") for kv in f.readline().split())
def med(runs, key):
return statistics.median(key(r) for r in runs)
table = []
for label in sorted(rows):
runs = rows[label]
m = meta[label]
table.append({
"config": label,
"replicas": int(m["replicas"]),
"api_cpus": float(m["api_cpus"]),
"api_mem": m["api_mem"],
"runs": len(runs),
"rps_median": round(med(runs, lambda r: r["successful_rps"]), 1),
"rps_min": round(min(r["successful_rps"] for r in runs), 1),
"rps_max": round(max(r["successful_rps"] for r in runs), 1),
"p50_ms": round(med(runs, lambda r: r["successful_latency_ms"]["p50"]), 1),
"p95_ms": round(med(runs, lambda r: r["successful_latency_ms"]["p95"]), 1),
"p99_ms": round(med(runs, lambda r: r["successful_latency_ms"]["p99"]), 1),
"errors": sum(r["failed_requests"] for r in runs),
})
cols = list(table[0])
with open(os.path.join(out, "summary.csv"), "w") as f:
f.write(",".join(cols) + "\n")
for t in table:
f.write(",".join(str(t[c]) for c in cols) + "\n")
for t in table:
print("%(config)s %(replicas)dx%(api_cpus).2f CPU rps=%(rps_median)s [%(rps_min)s..%(rps_max)s] "
"p50=%(p50_ms)s p95=%(p95_ms)s p99=%(p99_ms)s errors=%(errors)s" % t)
def series(prefix):
return sorted((t["replicas"], t["rps_median"], t["p95_ms"]) for t in table if t["config"].startswith(prefix))
W, H, L, B, T, R = 640, 360, 60, 50, 40, 150
xs = {1: 0, 2: 1, 4: 2}
ymax = max(t["rps_max"] for t in table) * 1.15
def px(n):
return L + xs[n] * (W - L - R) / 2
def py(v):
return H - B - v * (H - B - T) / ymax
svg = ['<svg xmlns="http://www.w3.org/2000/svg" width="%d" height="%d" font-family="sans-serif" font-size="12">' % (W, H),
'<rect width="100%" height="100%" fill="white"/>',
'<text x="%d" y="22" font-size="14">RPS (медиана 3 прогонов) от числа API-реплик</text>' % L]
for i in range(6):
v = ymax * i / 5
svg.append('<line x1="%d" x2="%d" y1="%.1f" y2="%.1f" stroke="#ddd"/>' % (L, W - R, py(v), py(v)))
svg.append('<text x="%d" y="%.1f" text-anchor="end">%d</text>' % (L - 6, py(v) + 4, v))
for n in xs:
svg.append('<text x="%.1f" y="%d" text-anchor="middle">%d</text>' % (px(n), H - B + 18, n))
svg.append('<text x="%.1f" y="%d" text-anchor="middle">реплики</text>' % ((L + W - R) / 2, H - 12))
for (prefix, color, name), dy in zip((("A", "#2a6fdb", "A: всего 1.0 CPU"), ("B", "#d9480f", "B: 0.5 CPU на реплику")), (0, 20)):
pts = series(prefix)
if prefix == "B":
pts = sorted(set(pts) | {(t["replicas"], t["rps_median"], t["p95_ms"]) for t in table if t["config"] == "A2"})
svg.append('<polyline fill="none" stroke="%s" stroke-width="2" points="%s"/>' %
(color, " ".join("%.1f,%.1f" % (px(n), py(v)) for n, v, _ in pts)))
for n, v, _ in pts:
svg.append('<circle cx="%.1f" cy="%.1f" r="4" fill="%s"/>' % (px(n), py(v), color))
svg.append('<text x="%.1f" y="%.1f" fill="%s" text-anchor="middle">%d</text>' % (px(n), py(v) - 8 - dy / 2, color, v))
svg.append('<rect x="%d" y="%d" width="12" height="12" fill="%s"/>' % (W - R + 12, T + dy, color))
svg.append('<text x="%d" y="%d">%s</text>' % (W - R + 28, T + dy + 10, name))
svg.append("</svg>")
with open(os.path.join(out, "rps.svg"), "w") as f:
f.write("\n".join(svg) + "\n")
print("wrote", os.path.join(out, "summary.csv"), os.path.join(out, "rps.svg"))
@@ -0,0 +1,99 @@
#!/usr/bin/env python3
"""Test shared idempotency: N parallel POST requests with the same Idempotency-Key
must create exactly one message and return identical responses."""
import argparse
import base64
import concurrent.futures
import json
import sys
import urllib.error
import urllib.request
import uuid
def main():
p = argparse.ArgumentParser()
p.add_argument("--base-url", default="http://localhost:8080")
p.add_argument("--concurrency", type=int, default=8)
args = p.parse_args()
base = args.base_url.rstrip("/")
def api(method, path, body=None, headers=None):
h = {"Accept": "application/json"}
h.update(headers or {})
data = None
if body is not None:
data = json.dumps(body).encode()
h["Content-Type"] = "application/json"
req = urllib.request.Request(base + path, data=data, headers=h, method=method)
try:
resp = urllib.request.urlopen(req, timeout=10)
except urllib.error.HTTPError as e:
resp = e
return resp.code, json.loads(resp.read())
pw = "TestPassword-" + uuid.uuid4().hex[:8]
u1 = "u_idem_" + uuid.uuid4().hex[:8]
u2 = "u_idem_" + uuid.uuid4().hex[:8]
_, alice = api("POST", "/api/v1/users", {"username": u1, "display_name": "Alice", "password": pw})
_, bob = api("POST", "/api/v1/users", {"username": u2, "display_name": "Bob", "password": pw})
cred = base64.b64encode((u1 + ":" + pw).encode()).decode()
_, sess = api("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + cred})
token = sess["token"]
_, chat = api("POST", "/api/v1/chats", {"title": "Idempotency test", "member_ids": [alice["id"], bob["id"]]},
headers={"Authorization": "Bearer " + token})
idem_key = uuid.uuid4().hex
text = "Parallel idempotency test " + idem_key
path = "/api/v1/chats/" + chat["id"] + "/messages"
def send(_):
h = {"Authorization": "Bearer " + token, "Idempotency-Key": idem_key,
"Content-Type": "application/json", "Accept": "application/json"}
data = json.dumps({"text": text}).encode()
req = urllib.request.Request(base + path, data=data, headers=h, method="POST")
try:
resp = urllib.request.urlopen(req, timeout=10)
except urllib.error.HTTPError as e:
resp = e
body = json.loads(resp.read())
return resp.code, body, resp.headers.get("X-Instance-Id", "")
with concurrent.futures.ThreadPoolExecutor(max_workers=args.concurrency) as pool:
results = list(pool.map(send, range(args.concurrency)))
codes = [r[0] for r in results]
bodies = [r[1] for r in results]
instances = set(r[2] for r in results)
assert all(c == 201 for c in codes), "not all responses are 201: %s" % codes
message_ids = set(b["id"] for b in bodies)
assert len(message_ids) == 1, "expected exactly 1 message, got %d different IDs" % len(message_ids)
first = bodies[0]
for b in bodies[1:]:
assert b == first, "response mismatch: %s vs %s" % (first, b)
print("PASS: %d parallel requests, 1 message created, %d distinct replicas observed: %s"
% (args.concurrency, len(instances), sorted(instances)))
# Verify different body with same key gives 409
h = {"Authorization": "Bearer " + token, "Idempotency-Key": idem_key,
"Content-Type": "application/json", "Accept": "application/json"}
data = json.dumps({"text": "different body"}).encode()
req = urllib.request.Request(base + path, data=data, headers=h, method="POST")
try:
resp = urllib.request.urlopen(req, timeout=10)
code = resp.code
except urllib.error.HTTPError as e:
code = e.code
assert code == 409, "expected 409 for different body with same key, got %d" % code
print("PASS: same key + different body → 409")
if __name__ == "__main__":
main()