ЛР 3 уровень 4: drain при SIGTERM, лимиты ресурсов, нагрузка с отказами, rolling update

This commit is contained in:
2026-11-10 04:17:24 +03:00
parent de55dd1d8a
commit 32442d06db
24 changed files with 1429 additions and 13 deletions
+34
View File
@@ -0,0 +1,34 @@
import base64
import json
import urllib.error
import urllib.request
import uuid
def call(base, method, path, body=None, headers=None, timeout=3.0):
"""Возвращает (status, headers с ключами в нижнем регистре, bytes). Сетевые ошибки поднимаются наружу."""
data = json.dumps(body).encode() if body is not None else None
h = {"Content-Type": "application/json"} if data else {}
h.update(headers or {})
req = urllib.request.Request(base + path, data=data, method=method, headers=h)
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
return r.status, {k.lower(): v for k, v in r.headers.items()}, r.read()
except urllib.error.HTTPError as e:
return e.code, {k.lower(): v for k, v in e.headers.items()}, e.read()
def setup(base):
"""Синтетический пользователь, сессия и чат из одного участника. Возвращает (auth_headers, chat_id)."""
name = "load_" + uuid.uuid4().hex[:12]
password = "load-password-" + uuid.uuid4().hex[:8]
s, _, b = call(base, "POST", "/api/v1/users", {"username": name, "display_name": "Load", "password": password})
assert s == 201, f"register failed: {s}"
uid = json.loads(b)["id"]
cred = base64.b64encode(f"{name}:{password}".encode()).decode()
s, _, b = call(base, "POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + cred})
assert s == 201, f"login failed: {s}"
auth = {"Authorization": "Bearer " + json.loads(b)["token"]}
s, _, b = call(base, "POST", "/api/v1/chats", {"title": "load", "member_ids": [uid]}, auth)
assert s == 201, f"chat failed: {s}"
return auth, json.loads(b)["id"]
+106
View File
@@ -0,0 +1,106 @@
#!/usr/bin/env python3
"""Closed-loop нагрузка POST /messages через LB; во время неё выполняется action-скрипт (остановка реплики).
Без прозрачных retry: каждая неудача = ошибка. Токены в вывод не попадают."""
import argparse
import json
import os
import subprocess
import threading
import time
import uuid
from common import call, setup
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--base-url", default="http://localhost:8080")
ap.add_argument("--duration", type=float, default=40)
ap.add_argument("--concurrency", type=int, default=8)
ap.add_argument("--action-script")
ap.add_argument("--action-at", type=float, default=10)
ap.add_argument("--target-index", type=int, default=0)
ap.add_argument("--output")
a = ap.parse_args()
auth, chat = setup(a.base_url)
path = f"/api/v1/chats/{chat}/messages"
ids = set()
for _ in range(40): # какие реплики видны через LB
_, h, _ = call(a.base_url, "GET", "/api/v1/users/me", headers=auth)
ids.add(h.get("x-instance-id"))
ids = sorted(i for i in ids if i)
records, lock = [], threading.Lock() # (t, status, latency, instance)
t_start = time.monotonic()
t_end = t_start + a.duration
def worker():
while time.monotonic() < t_end:
t0 = time.monotonic()
try:
s, h, _ = call(a.base_url, "POST", path, {"text": "load"},
{**auth, "Idempotency-Key": uuid.uuid4().hex}, timeout=3)
inst, ver = h.get("x-instance-id"), h.get("x-app-version")
except Exception:
s, inst, ver = 0, None, None
with lock:
records.append((t0 - t_start, s, time.monotonic() - t0, inst, ver))
threads = [threading.Thread(target=worker) for _ in range(a.concurrency)]
for t in threads:
t.start()
action = {}
if a.action_script:
time.sleep(a.action_at)
target = ids[a.target_index % len(ids)]
t0 = time.monotonic() - t_start
rc = subprocess.run([a.action_script], env={**os.environ, "TARGET_INSTANCE_ID": target},
capture_output=True, timeout=300).returncode
action = {"target": target, "started_at": round(t0, 2),
"finished_at": round(time.monotonic() - t_start, 2), "exit_code": rc}
for t in threads:
t.join()
ok = [r for r in records if r[1] == 201]
bad = [r for r in records if r[1] != 201]
lat = sorted(r[2] for r in ok)
pct = lambda p: round(lat[min(len(lat) - 1, int(len(lat) * p))] * 1000, 1) if lat else None
summary = {
"duration_s": a.duration, "concurrency": a.concurrency, "replicas_seen": ids,
"requests": len(records), "ok": len(ok), "errors": len(bad),
"error_rate": round(len(bad) / max(1, len(records)), 4),
"rps_ok": round(len(ok) / a.duration, 1),
"latency_ms": {"p50": pct(0.50), "p95": pct(0.95), "p99": pct(0.99)},
"error_statuses": {str(s): sum(1 for r in bad if r[1] == s) for s in {r[1] for r in bad}},
"action": action,
}
if action:
errs_after = [r[0] for r in bad if r[0] >= action["started_at"]]
times = sorted(r[0] for r in ok if r[0] >= action["started_at"])
gaps = [b - a_ for a_, b in zip([action["started_at"]] + times, times)]
summary["errors_after_action"] = len(errs_after)
summary["recovery_s"] = round(max(errs_after) - action["started_at"], 2) if errs_after else 0.0
summary["max_stall_s"] = round(max(gaps), 2) if gaps else None
summary["instances_in_last_5s"] = sorted({r[3] for r in ok if r[0] >= a.duration - 5 and r[3]})
vers = {}
for r in ok:
if r[4]:
v = vers.setdefault(r[4], [r[0], r[0]])
v[0], v[1] = min(v[0], r[0]), max(v[1], r[0])
summary["versions_first_last_seen_s"] = {k: [round(x, 1) for x in v] for k, v in vers.items()}
timeline = {}
for t, s, *_ in records:
b = timeline.setdefault(int(t), {"ok": 0, "err": 0})
b["ok" if s == 201 else "err"] += 1
print(json.dumps(summary, ensure_ascii=False, indent=2))
if a.output:
with open(a.output, "w") as f:
json.dump({"summary": summary, "per_second": timeline}, f, ensure_ascii=False, indent=1)
if __name__ == "__main__":
main()
@@ -0,0 +1,43 @@
#!/usr/bin/env python3
"""30 параллельных POST с одним Idempotency-Key через LB: ровно одно сообщение, везде 201 и один id."""
import json
import sys
import threading
import uuid
from common import call, setup
BASE = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:8080"
THREADS, ROUNDS = 30, 5
auth, chat = setup(BASE)
path = f"/api/v1/chats/{chat}/messages"
replicas = set()
for rnd in range(ROUNDS):
key = uuid.uuid4().hex
barrier = threading.Barrier(THREADS)
results = [None] * THREADS
def work(i, rnd=rnd, key=key, barrier=barrier, results=results):
barrier.wait()
s, h, b = call(BASE, "POST", path, {"text": f"parallel {rnd}"}, {**auth, "Idempotency-Key": key}, timeout=10)
results[i] = (s, h.get("x-instance-id"), json.loads(b) if s == 201 else None)
ts = [threading.Thread(target=work, args=(i,)) for i in range(THREADS)]
[t.start() for t in ts]
[t.join() for t in ts]
codes = {r[0] for r in results}
msg_ids = {r[2]["id"] for r in results if r[0] == 201}
replicas |= {r[1] for r in results}
assert codes == {201}, f"round {rnd}: codes {codes}"
assert len(msg_ids) == 1, f"round {rnd}: {len(msg_ids)} different messages"
s, _, _ = call(BASE, "POST", path, {"text": "other body"}, {**auth, "Idempotency-Key": key})
assert s == 409, f"round {rnd}: other body gave {s}"
s, _, b = call(BASE, "GET", path + "?limit=100", headers=auth)
count = len(json.loads(b)["items"])
assert count == ROUNDS, f"history has {count} messages, expected {ROUNDS}"
print(json.dumps({"rounds": ROUNDS, "parallel_requests_per_round": THREADS,
"messages_in_history": count, "replicas_that_answered": sorted(r for r in replicas if r)}))
print("PASS: same key in parallel -> exactly one message; different body -> 409")
+18 -9
View File
@@ -12,8 +12,8 @@ import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
IMAGE = os.environ.get("IMAGE", "mtusi-messenger:lab2")
NETWORK = os.environ.get("COMPOSE_NETWORK", "mtusi-lab2_default")
IMAGE = os.environ.get("IMAGE", "mtusi-messenger:lab3")
NETWORK = os.environ.get("COMPOSE_NETWORK", "mtusi-lab3_default")
PORT = int(os.environ.get("SIGTERM_PORT", "18080"))
@@ -55,6 +55,15 @@ def connection_rejected(base_url):
except (urllib.error.URLError, ConnectionError, TimeoutError):
return True
def not_ready(base_url):
# Во время drain /health/ready отвечает 503 (или соединение уже закрыто)
try:
with urllib.request.urlopen(base_url + "/health/ready", timeout=0.5):
return False
except urllib.error.HTTPError as exc:
return exc.code == 503
except (urllib.error.URLError, ConnectionError, TimeoutError):
return True
def test_shutdown(incomplete_request):
name = "mtusi-messenger-sigterm-" + uuid.uuid4().hex[:8]
@@ -82,24 +91,24 @@ def test_shutdown(incomplete_request):
raise AssertionError(f"Expected 100 Continue, received {response!r}")
pending.sendall(b"{")
print(f"Scenario: {scenario}; docker stop --timeout 10 {name}", flush=True)
print(f"Scenario: {scenario}; docker stop --timeout 20 {name}", flush=True)
start = time.monotonic()
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
stopped = executor.submit(run, "docker", "stop", "--timeout", "10", name)
stopped = executor.submit(run, "docker", "stop", "--timeout", "20", name)
deadline = start + 2
while not connection_rejected(base_url):
while not not_ready(base_url):
if time.monotonic() >= deadline:
raise AssertionError("New connections are still accepted during shutdown")
raise AssertionError("Readiness still OK after SIGTERM")
time.sleep(0.05)
rejected_after = time.monotonic() - start
stopped.result(timeout=12)
stopped.result(timeout=25)
elapsed = time.monotonic() - start
exit_code = int(run("docker", "inspect", name, "--format", "{{.State.ExitCode}}").stdout)
if exit_code != 0:
raise AssertionError(f"Container exited with code {exit_code}, expected 0")
if elapsed > 10:
raise AssertionError(f"Shutdown exceeded 10 seconds: {elapsed:.3f}s")
if elapsed > 15:
raise AssertionError(f"Shutdown exceeded 15 seconds: {elapsed:.3f}s")
if not connection_rejected(base_url):
raise AssertionError("API still accepts connections after shutdown")