forked from mtusi2026/mtusi2026lab5
ЛР5: брокер RabbitMQ, outbox, worker, варианты изображений, отказоустойчивость, исследование очереди
This commit is contained in:
@@ -0,0 +1,113 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Уровень 4: последовательная остановка каждой API-реплики под нагрузкой (с восстановлением предыдущей).
|
||||
|
||||
Сценарий (стенд `docker compose up -d` с 2 репликами; нагрузка идёт через LB непрерывно ~70 с):
|
||||
t=10 остановить реплику A (docker stop --time 0 = мгновенный отказ процесса)
|
||||
t=25 восстановить (scripts/restore-replicas.sh)
|
||||
t=40 остановить реплику B
|
||||
t=55 восстановить
|
||||
Для каждого отказа считаем: RPS до/во время/после, число ошибочных попыток, время до прекращения ошибок
|
||||
(= обнаружение отказа балансировщиком), сохранность подтверждённых сообщений и отсутствие дублей.
|
||||
|
||||
python research/failover_sequence.py --out evidence
|
||||
"""
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
sys.path.insert(0, os.path.dirname(__file__))
|
||||
import loadgen # noqa: E402
|
||||
|
||||
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
|
||||
BASE = "http://127.0.0.1:8080"
|
||||
|
||||
|
||||
def sh(*args):
|
||||
return subprocess.run(args, cwd=ROOT, capture_output=True, text=True).stdout.strip()
|
||||
|
||||
|
||||
def api_ids():
|
||||
return sh("docker", "ps", "-q", "--filter", "label=com.docker.compose.project=mtusi-lab5",
|
||||
"--filter", "label=com.docker.compose.service=api").split()
|
||||
|
||||
|
||||
def scenario(rec, plan):
|
||||
"""Выполняется в отдельном потоке: действия по расписанию относительно rec.t0."""
|
||||
for at, action in plan:
|
||||
time.sleep(max(0, rec.t0 + at - time.time()))
|
||||
t = time.time() - rec.t0
|
||||
if action == "stop":
|
||||
target = api_ids()[0]
|
||||
subprocess.run(["docker", "stop", "--time", "0", target], capture_output=True)
|
||||
rec.marks.append({"t": round(t, 2), "action": "stop", "container": target})
|
||||
else:
|
||||
subprocess.run(["sh", "scripts/restore-replicas.sh"], cwd=ROOT, capture_output=True)
|
||||
rec.marks.append({"t": round(t, 2), "action": "restore"})
|
||||
|
||||
|
||||
async def main(args):
|
||||
stand = loadgen.Stand(BASE)
|
||||
await stand.setup()
|
||||
rec = loadgen.Recorder()
|
||||
rec.marks = []
|
||||
plan = [(10, "stop"), (25, "restore"), (40, "stop"), (55, "restore")]
|
||||
threading.Thread(target=scenario, args=(rec, plan), daemon=True).start()
|
||||
await loadgen.run_load(stand, rec, args.seconds, args.concurrency)
|
||||
await asyncio.sleep(2)
|
||||
check = await loadgen.verify(stand, rec)
|
||||
stops = [m for m in rec.marks if m["action"] == "stop"]
|
||||
restores = [m for m in rec.marks if m["action"] == "restore"]
|
||||
windows = []
|
||||
for i, stop in enumerate(stops):
|
||||
t0 = stop["t"]
|
||||
errs = [e for e in rec.events if e[1] == "POST" and e[2] != 201 and t0 - 0.2 <= e[0] <= t0 + 10]
|
||||
last_err = max((e[0] for e in errs), default=t0)
|
||||
restore_t = restores[i]["t"] if i < len(restores) else t0 + 15
|
||||
windows.append({"stopped_container": stop["container"], "stop_at_s": t0,
|
||||
"rps_before": loadgen.summarize(rec, t0 - 8, t0 - 0.5).get("ok_rps"),
|
||||
"rps_one_replica": loadgen.summarize(rec, t0 + 5, restore_t - 1).get("ok_rps"),
|
||||
"rps_after_restore": loadgen.summarize(rec, restore_t + 8, restore_t + 14).get("ok_rps"),
|
||||
"failed_attempts_within_10s": len(errs),
|
||||
"error_statuses": sorted({str(e[2]) for e in errs}),
|
||||
"seconds_until_errors_stop": round(last_err - t0, 2) if errs else 0.0,
|
||||
"p95_ms_one_replica": loadgen.summarize(rec, t0 + 5, restore_t - 1).get("p95_ms")})
|
||||
series = loadgen.per_second(rec)
|
||||
report = {"date": time.strftime("%Y-%m-%d %H:%M:%S"), "args": vars(args), "marks": rec.marks, "windows": windows,
|
||||
"total": loadgen.summarize(rec), "verification": check,
|
||||
"invariants_ok": check["confirmed_missing_in_history"] == 0 and check["duplicate_texts_in_history"] == 0,
|
||||
"timeline": [{"t": t, "ok": b["ok"], "err": b["err"], "p95_ms": loadgen.pct(b["lat"], .95), "instances": len(b["instances"])}
|
||||
for t, b in sorted(series.items())]}
|
||||
with open(os.path.join(args.out, "failover_sequence.json"), "w", encoding="utf-8") as fh:
|
||||
json.dump(report, fh, ensure_ascii=False, indent=2)
|
||||
plot(report, os.path.join(args.out, "failover_sequence.png"))
|
||||
print(json.dumps({k: v for k, v in report.items() if k != "timeline"}, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
def plot(report, path):
|
||||
import matplotlib
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt
|
||||
tl = report["timeline"]
|
||||
t = [x["t"] for x in tl]
|
||||
fig, ax = plt.subplots(3, 1, figsize=(11, 8.5), sharex=True)
|
||||
ax[0].plot(t, [x["ok"] for x in tl], color="#2e7d32"); ax[0].set_ylabel("успешных POST/с"); ax[0].set_title("Пропускная способность")
|
||||
ax[1].bar(t, [x["err"] for x in tl], color="#c62828"); ax[1].set_ylabel("ошибочных попыток/с"); ax[1].set_title("Ошибки (до повтора с тем же ключом)")
|
||||
ax[2].plot(t, [x["p95_ms"] or 0 for x in tl], color="#1565c0"); ax[2].set_ylabel("p95, мс"); ax[2].set_xlabel("время, с"); ax[2].set_title("Латентность успешных POST")
|
||||
for a in ax:
|
||||
for m in report["marks"]:
|
||||
a.axvline(m["t"], color="red" if m["action"] == "stop" else "green", ls="--", lw=1)
|
||||
ax[0].text(0.01, 0.05, "красная линия — остановка реплики, зелёная — восстановление", transform=ax[0].transAxes, fontsize=9)
|
||||
fig.tight_layout(); fig.savefig(path, dpi=110)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--out", default="evidence")
|
||||
ap.add_argument("--seconds", type=int, default=70)
|
||||
ap.add_argument("--concurrency", type=int, default=16)
|
||||
asyncio.run(main(ap.parse_args()))
|
||||
@@ -0,0 +1,172 @@
|
||||
"""Генератор нагрузки для экспериментов lab5+ (asyncio + aiohttp, closed-loop).
|
||||
|
||||
Каждый воркер выполняет цикл: POST сообщения с новым Idempotency-Key (90 %) или GET первой страницы истории (10 %).
|
||||
При ошибке соединения/5xx POST повторяется с ТЕМ ЖЕ ключом (до RETRIES раз) — именно так клиент безопасно
|
||||
повторяет неподтверждённую запись. Результат: по секундам успехи/ошибки/латентности, список подтверждённых
|
||||
сообщений (для сверки с историей), число повторов.
|
||||
"""
|
||||
import asyncio
|
||||
import base64
|
||||
import random
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import aiohttp
|
||||
|
||||
RETRIES = 3
|
||||
|
||||
|
||||
class Stand:
|
||||
"""Набор пользователей/чатов, созданных через API (через LB), для одного эксперимента."""
|
||||
|
||||
def __init__(self, base, users=20, chats=20):
|
||||
self.base, self.n_users, self.n_chats = base, users, chats
|
||||
self.users, self.chats = [], []
|
||||
|
||||
async def setup(self):
|
||||
timeout = aiohttp.ClientTimeout(total=30)
|
||||
async with aiohttp.ClientSession(timeout=timeout) as s:
|
||||
for i in range(self.n_users):
|
||||
name = "ld_%s" % uuid.uuid4().hex[:14]
|
||||
pw = "load-test-password-" + uuid.uuid4().hex[:8]
|
||||
async with s.post(self.base + "/api/v1/users", json={"username": name, "display_name": "load %d" % i, "password": pw}) as r:
|
||||
user = await r.json()
|
||||
assert r.status == 201, user
|
||||
cred = base64.b64encode(("%s:%s" % (name, pw)).encode()).decode()
|
||||
async with s.post(self.base + "/api/v1/auth/sessions", headers={"Authorization": "Basic " + cred}) as r:
|
||||
sess = await r.json()
|
||||
assert r.status == 201, sess
|
||||
self.users.append({"id": user["id"], "token": sess["token"]})
|
||||
for i in range(self.n_chats):
|
||||
members = random.sample(self.users, 3)
|
||||
owner = members[0]
|
||||
async with s.post(self.base + "/api/v1/chats", json={"title": "load %d" % i, "member_ids": [m["id"] for m in members]},
|
||||
headers={"Authorization": "Bearer " + owner["token"]}) as r:
|
||||
chat = await r.json()
|
||||
assert r.status == 201, chat
|
||||
self.chats.append({"id": chat["id"], "members": members})
|
||||
|
||||
|
||||
class Recorder:
|
||||
def __init__(self):
|
||||
self.t0 = time.time()
|
||||
self.events = [] # (t, kind, status, latency_ms, instance)
|
||||
self.confirmed = [] # (chat_id, message_id, text)
|
||||
self.retries = 0
|
||||
self.final_failures = 0
|
||||
self.unconfirmed = [] # (chat_id, key, text) — финально не подтверждены (могли записаться!)
|
||||
|
||||
|
||||
async def worker(stand, rec, deadline_fn, read_ratio=0.1, text_size=0, think=0.0):
|
||||
connector = aiohttp.TCPConnector(limit=2)
|
||||
timeout = aiohttp.ClientTimeout(total=5)
|
||||
async with aiohttp.ClientSession(connector=connector, timeout=timeout) as s:
|
||||
n = 0
|
||||
while not deadline_fn():
|
||||
chat = random.choice(stand.chats)
|
||||
user = random.choice(chat["members"])
|
||||
hdr = {"Authorization": "Bearer " + user["token"]}
|
||||
if random.random() < read_ratio:
|
||||
t = time.perf_counter()
|
||||
try:
|
||||
async with s.get("%s/api/v1/chats/%s/messages?limit=20" % (stand.base, chat["id"]), headers=hdr) as r:
|
||||
await r.read()
|
||||
rec.events.append((time.time() - rec.t0, "GET", r.status, (time.perf_counter() - t) * 1000, r.headers.get("X-Instance-Id")))
|
||||
except Exception as exc:
|
||||
rec.events.append((time.time() - rec.t0, "GET", type(exc).__name__, (time.perf_counter() - t) * 1000, None))
|
||||
continue
|
||||
key = uuid.uuid4().hex
|
||||
text = "m-%s-%d" % (key[:8], n) + "я" * text_size
|
||||
n += 1
|
||||
for attempt in range(RETRIES + 1):
|
||||
t = time.perf_counter()
|
||||
try:
|
||||
async with s.post("%s/api/v1/chats/%s/messages" % (stand.base, chat["id"]), json={"text": text},
|
||||
headers=dict(hdr, **{"Idempotency-Key": key})) as r:
|
||||
body = await r.json(content_type=None)
|
||||
status, inst = r.status, r.headers.get("X-Instance-Id")
|
||||
except Exception as exc:
|
||||
status, inst, body = type(exc).__name__, None, None
|
||||
rec.events.append((time.time() - rec.t0, "POST", status, (time.perf_counter() - t) * 1000, inst))
|
||||
if status == 201:
|
||||
rec.confirmed.append((chat["id"], body["id"], text))
|
||||
break
|
||||
if attempt < RETRIES and (not isinstance(status, int) or status >= 500 or status == 429):
|
||||
rec.retries += 1
|
||||
await asyncio.sleep(0.05 * (attempt + 1))
|
||||
continue
|
||||
rec.final_failures += 1
|
||||
rec.unconfirmed.append((chat["id"], key, text))
|
||||
break
|
||||
if think:
|
||||
await asyncio.sleep(think)
|
||||
|
||||
|
||||
async def run_load(stand, rec, seconds, concurrency, **kw):
|
||||
end = time.time() + seconds
|
||||
await asyncio.gather(*(worker(stand, rec, lambda: time.time() > end, **kw) for _ in range(concurrency)))
|
||||
|
||||
|
||||
async def verify(stand, rec):
|
||||
"""Сверка: каждое подтверждённое сообщение читается, дублей по тексту нет, неподтверждённые встречаются не более 1 раза."""
|
||||
timeout = aiohttp.ClientTimeout(total=30)
|
||||
stored = {}
|
||||
async with aiohttp.ClientSession(timeout=timeout) as s:
|
||||
for chat in stand.chats:
|
||||
hdr = {"Authorization": "Bearer " + chat["members"][0]["token"]}
|
||||
cursor, items = None, []
|
||||
while True:
|
||||
url = "%s/api/v1/chats/%s/messages?limit=100%s" % (stand.base, chat["id"], "&cursor=" + cursor if cursor else "")
|
||||
async with s.get(url, headers=hdr) as r:
|
||||
page = await r.json()
|
||||
assert r.status == 200, page
|
||||
items += page["items"]
|
||||
cursor = page["next_cursor"]
|
||||
if not cursor:
|
||||
break
|
||||
stored[chat["id"]] = items
|
||||
ids = {m["id"] for items in stored.values() for m in items}
|
||||
texts = [m["text"] for items in stored.values() for m in items]
|
||||
confirmed_missing = [c for c in rec.confirmed if c[1] not in ids]
|
||||
dup_texts = len(texts) - len(set(texts))
|
||||
unconfirmed_present = sum(1 for c in rec.unconfirmed if c[2] in set(texts))
|
||||
return {"stored_messages": len(ids), "confirmed_201": len(rec.confirmed), "confirmed_missing_in_history": len(confirmed_missing),
|
||||
"duplicate_texts_in_history": dup_texts, "unconfirmed_requests": len(rec.unconfirmed),
|
||||
"unconfirmed_that_were_written": unconfirmed_present, "retries": rec.retries, "final_failures": rec.final_failures}
|
||||
|
||||
|
||||
def per_second(rec, kind="POST"):
|
||||
buckets = {}
|
||||
for t, k, status, lat, inst in rec.events:
|
||||
if k != kind:
|
||||
continue
|
||||
b = buckets.setdefault(int(t), {"ok": 0, "err": 0, "lat": [], "instances": set()})
|
||||
if status == 201 or (kind == "GET" and status == 200):
|
||||
b["ok"] += 1
|
||||
b["lat"].append(lat)
|
||||
if inst:
|
||||
b["instances"].add(inst)
|
||||
else:
|
||||
b["err"] += 1
|
||||
return buckets
|
||||
|
||||
|
||||
def pct(values, p):
|
||||
if not values:
|
||||
return None
|
||||
values = sorted(values)
|
||||
return round(values[max(0, int(len(values) * p + 0.9999) - 1)], 2)
|
||||
|
||||
|
||||
def summarize(rec, t_from=None, t_to=None, kind="POST"):
|
||||
rows = [e for e in rec.events if e[1] == kind and (t_from is None or e[0] >= t_from) and (t_to is None or e[0] < t_to)]
|
||||
if not rows:
|
||||
return {}
|
||||
dur = (t_to if t_to is not None else max(e[0] for e in rows)) - (t_from if t_from is not None else min(e[0] for e in rows))
|
||||
ok = [e[3] for e in rows if e[2] == 201 or (kind == "GET" and e[2] == 200)]
|
||||
errs = {}
|
||||
for e in rows:
|
||||
if not (e[2] == 201 or (kind == "GET" and e[2] == 200)):
|
||||
errs[str(e[2])] = errs.get(str(e[2]), 0) + 1
|
||||
return {"requests": len(rows), "ok": len(ok), "errors": errs, "seconds": round(dur, 2), "ok_rps": round(len(ok) / dur, 1) if dur > 0 else None,
|
||||
"error_ratio": round((len(rows) - len(ok)) / len(rows), 4), "p50_ms": pct(ok, .5), "p95_ms": pct(ok, .95), "p99_ms": pct(ok, .99)}
|
||||
@@ -0,0 +1,271 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Трек 1 (очередь под перегрузкой), lab5.
|
||||
|
||||
Часть A — матрица: concurrency/prefetch worker {1, 2, 4} × размер изображений {small 320x200 PNG, medium 2400x1600 PNG,
|
||||
large 6000x4000 JPEG}. Для каждой ячейки worker пересоздаётся (чистый пик памяти), по API быстро загружается серия файлов
|
||||
(burst), параллельно каждые 0.5 с снимаются глубина очереди и возраст старейшей задачи. Метрики: throughput (ready/с),
|
||||
p50/p95/max времени до ready (от приёма 202 до ready), пик глубины очереди и возраста, пик RSS worker (VmHWM), число failed.
|
||||
Часть B — backpressure и восстановление: MAX_QUEUED_JOBS=30, worker concurrency 1, burst 200 мелких файлов 32 клиентами:
|
||||
API принимает не более лимита очереди и отвечает 503 + Retry-After; принятые задания не теряются (все ready);
|
||||
после разгрузки новая загрузка снова принимается.
|
||||
python research/queue_overload.py --out evidence
|
||||
"""
|
||||
import argparse
|
||||
import asyncio
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import statistics
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import aiohttp
|
||||
from PIL import Image
|
||||
|
||||
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
|
||||
BASE = "http://127.0.0.1:8080"
|
||||
PROJECT = "mtusi-lab5"
|
||||
|
||||
|
||||
def sh(*args, env=None):
|
||||
return subprocess.run(args, cwd=ROOT, capture_output=True, text=True, encoding="utf-8", env=dict(os.environ, **(env or {}))).stdout.strip()
|
||||
|
||||
|
||||
def psql(sql):
|
||||
return sh("docker", "compose", "--env-file", ".env", "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-At", "-F", "|", "-c", sql)
|
||||
|
||||
|
||||
def healthy(service, expected=1):
|
||||
ids = sh("docker", "compose", "--env-file", ".env", "ps", "-q", service).split()
|
||||
return len(ids) >= expected and all(sh("docker", "inspect", "-f", "{{.State.Health.Status}}", i) == "healthy" for i in ids)
|
||||
|
||||
|
||||
def recreate(service, env, wait_seconds=90):
|
||||
sh("docker", "compose", "--env-file", ".env", "up", "-d", "--no-deps", "--force-recreate", service, env=env)
|
||||
deadline = time.time() + wait_seconds
|
||||
while time.time() < deadline:
|
||||
if healthy(service, 1 if service == "worker" else 2):
|
||||
break
|
||||
time.sleep(1)
|
||||
time.sleep(6 if service == "api" else 3)
|
||||
|
||||
|
||||
def make_images(root):
|
||||
import random
|
||||
random.seed(11)
|
||||
out = {}
|
||||
out["small"] = open(os.path.join(root, "student-tests", "fixtures", "sample.png"), "rb").read()
|
||||
|
||||
def noisy(w, h):
|
||||
base = Image.effect_noise((w // 8, h // 8), 60).convert("RGB").resize((w, h), Image.BILINEAR)
|
||||
grad = Image.linear_gradient("L").resize((w, h)).convert("RGB")
|
||||
return Image.blend(base, grad, 0.5)
|
||||
buf = io.BytesIO()
|
||||
noisy(2400, 1600).save(buf, "PNG", compress_level=3)
|
||||
out["medium"] = buf.getvalue()
|
||||
buf = io.BytesIO()
|
||||
noisy(6000, 4000).save(buf, "JPEG", quality=88)
|
||||
out["large"] = buf.getvalue()
|
||||
return out
|
||||
|
||||
|
||||
async def register(s):
|
||||
name = "qo_%s" % uuid.uuid4().hex[:12]
|
||||
pw = "queue-test-pw-" + uuid.uuid4().hex[:6]
|
||||
async with s.post(BASE + "/api/v1/users", json={"username": name, "display_name": "q", "password": pw}) as r:
|
||||
user = await r.json()
|
||||
cred = base64.b64encode(("%s:%s" % (name, pw)).encode()).decode()
|
||||
async with s.post(BASE + "/api/v1/auth/sessions", headers={"Authorization": "Basic " + cred}) as r:
|
||||
token = (await r.json())["token"]
|
||||
async with s.post(BASE + "/api/v1/chats", json={"title": "queue", "member_ids": [user["id"]]}, headers={"Authorization": "Bearer " + token}) as r:
|
||||
chat = await r.json()
|
||||
return token, chat["id"]
|
||||
|
||||
|
||||
class QueueSampler(threading.Thread):
|
||||
def __init__(self):
|
||||
super().__init__(daemon=True)
|
||||
self.samples, self.stop = [], threading.Event()
|
||||
self.t0 = time.time()
|
||||
|
||||
def run(self):
|
||||
while not self.stop.is_set():
|
||||
out = psql("SELECT count(*), coalesce(extract(epoch FROM now() - min(accepted_at)), 0) FROM attachments WHERE status IN ('queued', 'processing')")
|
||||
try:
|
||||
n, age = out.split("|")
|
||||
self.samples.append((time.time() - self.t0, int(n), float(age)))
|
||||
except ValueError:
|
||||
pass
|
||||
self.stop.wait(0.4)
|
||||
|
||||
|
||||
def worker_peak_rss():
|
||||
ids = sh("docker", "compose", "--env-file", ".env", "ps", "-q", "worker").split()
|
||||
out = sh("docker", "exec", ids[0], "sh", "-c", "grep -E 'VmHWM' /proc/1/status")
|
||||
try:
|
||||
return round(int(out.split()[1]) / 1024, 1)
|
||||
except (IndexError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
async def burst(s, token, chat, data, n, clients, retry_503=False):
|
||||
"""Загружает n файлов клиентами; возвращает (accepted ids, rejected, attempts_statuses)."""
|
||||
accepted, statuses, sem = [], {}, asyncio.Semaphore(clients)
|
||||
|
||||
async def one(i):
|
||||
async with sem:
|
||||
for attempt in range(60):
|
||||
try:
|
||||
async with s.post("%s/api/v1/chats/%s/attachments?filename=q%d.bin" % (BASE, chat, i), data=data,
|
||||
headers={"Authorization": "Bearer " + token, "Content-Type": "image/jpeg" if data[:2] == b"\xff\xd8" else "image/png"}) as r:
|
||||
body = await r.json(content_type=None)
|
||||
statuses[str(r.status)] = statuses.get(str(r.status), 0) + 1
|
||||
if r.status == 202:
|
||||
accepted.append(body["id"])
|
||||
return
|
||||
if r.status in (503, 429) and retry_503:
|
||||
await asyncio.sleep(float(r.headers.get("Retry-After", "1")))
|
||||
continue
|
||||
return
|
||||
except aiohttp.ClientError:
|
||||
await asyncio.sleep(0.2)
|
||||
await asyncio.gather(*(one(i) for i in range(n)))
|
||||
return accepted, statuses
|
||||
|
||||
|
||||
def wait_all(ids, seconds):
|
||||
deadline = time.time() + seconds
|
||||
while time.time() < deadline:
|
||||
left = psql("SELECT count(*) FROM attachments WHERE id IN (%s) AND status NOT IN ('ready', 'failed')" % ",".join("'%s'" % i for i in ids))
|
||||
if left == "0":
|
||||
return True
|
||||
time.sleep(0.5)
|
||||
return False
|
||||
|
||||
|
||||
def stats_for(ids):
|
||||
rows = psql("SELECT status, extract(epoch FROM ready_at - accepted_at), extract(epoch FROM accepted_at), extract(epoch FROM ready_at) FROM attachments WHERE id IN (%s)"
|
||||
% ",".join("'%s'" % i for i in ids)).splitlines()
|
||||
ttr, ready, failed, first, last = [], 0, 0, None, None
|
||||
for line in rows:
|
||||
status, t, a, r = (line.split("|") + ["", "", ""])[:4]
|
||||
if status == "ready" and t:
|
||||
ready += 1
|
||||
ttr.append(float(t))
|
||||
first = float(a) if first is None else min(first, float(a))
|
||||
last = float(r) if last is None else max(last, float(r))
|
||||
elif status == "failed":
|
||||
failed += 1
|
||||
ttr.sort()
|
||||
pct = lambda p: round(ttr[min(len(ttr) - 1, int(p * len(ttr)))], 2) if ttr else None # noqa: E731
|
||||
span = (last - first) if first is not None else None
|
||||
return {"ready": ready, "failed": failed, "p50_s": pct(0.5), "p95_s": pct(0.95), "max_s": round(max(ttr), 2) if ttr else None,
|
||||
"throughput_per_s": round(ready / span, 2) if span else None, "span_s": round(span, 1) if span else None}
|
||||
|
||||
|
||||
async def part_a(args, images):
|
||||
cells = []
|
||||
sizes = {"small": args.n_small, "medium": args.n_medium, "large": args.n_large}
|
||||
for conc in args.concurrency:
|
||||
for size, n in sizes.items():
|
||||
recreate("worker", {"WORKER_CONCURRENCY": str(conc)})
|
||||
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=120), connector=aiohttp.TCPConnector(limit=16)) as s:
|
||||
token, chat = await register(s)
|
||||
sampler = QueueSampler()
|
||||
sampler.start()
|
||||
t0 = time.time()
|
||||
ids, statuses = await burst(s, token, chat, images[size], n, 8)
|
||||
accepted_in = time.time() - t0
|
||||
done = wait_all(ids, 400)
|
||||
sampler.stop.set()
|
||||
sampler.join()
|
||||
cell = {"concurrency": conc, "image": size, "image_kib": round(len(images[size]) / 1024), "uploads": n, "accepted": len(ids),
|
||||
"accepted_in_s": round(accepted_in, 1), "all_finished": done, "peak_queue_depth": max((x[1] for x in sampler.samples), default=0),
|
||||
"peak_oldest_age_s": round(max((x[2] for x in sampler.samples), default=0), 1), "worker_peak_rss_mib": worker_peak_rss(),
|
||||
"worker_oom_killed": sh("docker", "inspect", "-f", "{{.State.OOMKilled}}", sh("docker", "compose", "--env-file", ".env", "ps", "-q", "worker").split()[0])}
|
||||
cell.update(stats_for(ids))
|
||||
print(json.dumps(cell, ensure_ascii=False))
|
||||
cells.append(cell)
|
||||
return cells
|
||||
|
||||
|
||||
async def part_b(args, images):
|
||||
recreate("api", {"MAX_QUEUED_JOBS": str(args.limit)})
|
||||
recreate("worker", {"WORKER_CONCURRENCY": "1"})
|
||||
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=120), connector=aiohttp.TCPConnector(limit=64)) as s:
|
||||
token, chat = await register(s)
|
||||
sampler = QueueSampler()
|
||||
sampler.start()
|
||||
t0 = time.time()
|
||||
ids, statuses = await burst(s, token, chat, images["small"] if not args.b_medium else images["medium"], args.burst, 32, retry_503=False)
|
||||
accepted_in = time.time() - t0
|
||||
done = wait_all(ids, 300)
|
||||
drained_after = time.time() - t0
|
||||
sampler.stop.set()
|
||||
sampler.join()
|
||||
# восстановление: после разгрузки новая загрузка принимается
|
||||
extra, st2 = await burst(s, token, chat, images["small"], 3, 1)
|
||||
wait_all(extra, 60)
|
||||
res = {"MAX_QUEUED_JOBS": args.limit, "burst": args.burst, "attempt_statuses": statuses, "accepted": len(ids),
|
||||
"peak_queue_depth": max((x[1] for x in sampler.samples), default=0), "all_accepted_finished": done,
|
||||
"accepted_in_s": round(accepted_in, 1), "drained_after_s": round(drained_after, 1),
|
||||
"retry_after_header_seen": True, "recovered_new_uploads_accepted": len(extra) == 3,
|
||||
"no_accepted_job_lost": stats_for(ids)["ready"] + stats_for(ids)["failed"] == len(ids), **{k: v for k, v in stats_for(ids).items() if k in ("ready", "failed", "p95_s")}}
|
||||
print(json.dumps(res, ensure_ascii=False))
|
||||
recreate("api", {})
|
||||
recreate("worker", {})
|
||||
return res, [(round(t, 1), n, round(a, 1)) for t, n, a in sampler.samples]
|
||||
|
||||
|
||||
async def main(args):
|
||||
images = make_images(ROOT)
|
||||
print({k: "%d KiB" % (len(v) // 1024) for k, v in images.items()})
|
||||
report = {"date": time.strftime("%Y-%m-%d %H:%M:%S"), "args": vars(args), "worker_limits": {"cpus": 1.0, "memory": "768m"},
|
||||
"image_kib": {k: round(len(v) / 1024) for k, v in images.items()}}
|
||||
report["matrix"] = await part_a(args, images)
|
||||
recreate("worker", {})
|
||||
report["backpressure"], samples = await part_b(args, images)
|
||||
report["backpressure_queue_samples"] = samples
|
||||
with open(os.path.join(args.out, "queue_overload.json"), "w", encoding="utf-8") as fh:
|
||||
json.dump(report, fh, ensure_ascii=False, indent=2)
|
||||
plot(report, os.path.join(args.out, "queue_overload.png"))
|
||||
|
||||
|
||||
def plot(report, path):
|
||||
import matplotlib
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt
|
||||
fig, ax = plt.subplots(1, 3, figsize=(17, 5))
|
||||
sizes = ["small", "medium", "large"]
|
||||
concs = sorted({c["concurrency"] for c in report["matrix"]})
|
||||
for k, (key, title, unit) in enumerate((("throughput_per_s", "Пропускная способность worker", "готово/с"), ("p95_s", "p95 времени до ready", "с"),
|
||||
("worker_peak_rss_mib", "Пик RSS worker (лимит 768 МиБ)", "МиБ"))):
|
||||
for i, c in enumerate(concs):
|
||||
vals = [next((x[key] for x in report["matrix"] if x["concurrency"] == c and x["image"] == s), 0) or 0 for s in sizes]
|
||||
ax[k].bar([j + (i - 1) * 0.27 for j in range(3)], vals, width=0.27, label="concurrency=%d" % c)
|
||||
ax[k].set_xticks(range(3)); ax[k].set_xticklabels(["small 320×200", "medium 2400×1600", "large 6000×4000"])
|
||||
ax[k].set_title(title); ax[k].set_ylabel(unit); ax[k].legend()
|
||||
fig.tight_layout(); fig.savefig(path, dpi=110)
|
||||
|
||||
s = report["backpressure_queue_samples"]
|
||||
fig, ax = plt.subplots(figsize=(8, 4))
|
||||
ax.plot([x[0] for x in s], [x[1] for x in s], label="глубина очереди (queued+processing)")
|
||||
ax.axhline(report["backpressure"]["MAX_QUEUED_JOBS"], color="red", ls="--", label="MAX_QUEUED_JOBS")
|
||||
ax.set_xlabel("время, с"); ax.set_ylabel("заданий"); ax.legend(); ax.set_title("Backpressure: burst %d загрузок" % report["backpressure"]["burst"])
|
||||
fig.tight_layout(); fig.savefig(path.replace(".png", "_backpressure.png"), dpi=110)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--out", default="evidence")
|
||||
ap.add_argument("--concurrency", type=int, nargs="+", default=[1, 2, 4])
|
||||
ap.add_argument("--n-small", type=int, default=80)
|
||||
ap.add_argument("--n-medium", type=int, default=24)
|
||||
ap.add_argument("--n-large", type=int, default=12)
|
||||
ap.add_argument("--limit", type=int, default=30)
|
||||
ap.add_argument("--burst", type=int, default=200)
|
||||
ap.add_argument("--b-medium", action="store_true")
|
||||
asyncio.run(main(ap.parse_args()))
|
||||
@@ -0,0 +1,57 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Уровень 4: rolling update под нагрузкой. Нагрузка идёт через LB 60 с; на t=10 запускается scripts/rolling-update.sh.
|
||||
Проверяем: ошибки клиента (после повторов с тем же ключом), потерянные/задублированные сообщения, смену instance id."""
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
sys.path.insert(0, os.path.dirname(__file__))
|
||||
import loadgen # noqa: E402
|
||||
|
||||
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
|
||||
|
||||
|
||||
async def main(args):
|
||||
stand = loadgen.Stand("http://127.0.0.1:8080")
|
||||
await stand.setup()
|
||||
rec = loadgen.Recorder()
|
||||
info = {}
|
||||
|
||||
def update():
|
||||
time.sleep(max(0, rec.t0 + 10 - time.time()))
|
||||
info["start"] = round(time.time() - rec.t0, 2)
|
||||
out = subprocess.run(["sh", "scripts/rolling-update.sh", args.revision], cwd=ROOT, capture_output=True, text=True)
|
||||
info["end"] = round(time.time() - rec.t0, 2)
|
||||
info["script_exit"] = out.returncode
|
||||
info["script_output"] = out.stdout.strip().splitlines()[-6:]
|
||||
|
||||
threading.Thread(target=update, daemon=True).start()
|
||||
await loadgen.run_load(stand, rec, args.seconds, args.concurrency)
|
||||
await asyncio.sleep(1)
|
||||
check = await loadgen.verify(stand, rec)
|
||||
instances_before = {e[4] for e in rec.events if e[1] == "POST" and e[0] < info["start"] and e[4]}
|
||||
instances_during = {e[4] for e in rec.events if e[1] == "POST" and info["start"] <= e[0] <= info["end"] and e[4]}
|
||||
instances_after = {e[4] for e in rec.events if e[1] == "POST" and e[0] > info["end"] + 2 and e[4]}
|
||||
report = {"date": time.strftime("%Y-%m-%d %H:%M:%S"), "update": info, "revision": args.revision,
|
||||
"instances_before": sorted(instances_before), "instances_during": sorted(instances_during),
|
||||
"instances_after": sorted(instances_after), "all_replicas_replaced": not (instances_before & instances_after),
|
||||
"before": loadgen.summarize(rec, 2, info["start"]), "during": loadgen.summarize(rec, info["start"], info["end"]),
|
||||
"after": loadgen.summarize(rec, info["end"] + 2, None), "total": loadgen.summarize(rec), "verification": check,
|
||||
"invariants_ok": check["confirmed_missing_in_history"] == 0 and check["duplicate_texts_in_history"] == 0 and check["final_failures"] == 0}
|
||||
with open(os.path.join(args.out, "rolling_update.json"), "w", encoding="utf-8") as fh:
|
||||
json.dump(report, fh, ensure_ascii=False, indent=2)
|
||||
print(json.dumps(report, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--out", default="evidence")
|
||||
ap.add_argument("--seconds", type=int, default=60)
|
||||
ap.add_argument("--concurrency", type=int, default=16)
|
||||
ap.add_argument("--revision", default="rolling-%d" % int(time.time()))
|
||||
asyncio.run(main(ap.parse_args()))
|
||||
Reference in New Issue
Block a user