forked from mtusi2026/mtusi2026lab3
ЛР3: HAProxy, реплики API, идемпотентность, отказы и rolling update, исследование масштабирования
This commit is contained in:
@@ -0,0 +1,91 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Уровень 4: согласованность health/readiness/SIGTERM и время обнаружения отказа балансировщиком.
|
||||
|
||||
Опыт 1 (штатная остановка, SIGTERM): под нагрузкой ~100 запросов/с на одну реплику посылаем SIGTERM; фиксируем
|
||||
t_ready_fail — когда реплика перестала быть в ротации LB (последний ответ с её X-Instance-Id),
|
||||
t_exit — когда контейнер завершился, число ошибок клиента за это время (ожидаем 0).
|
||||
Опыт 2 (внезапный отказ, SIGKILL): время до прекращения ошибок клиента = время обнаружения отказа LB.
|
||||
Повторяется N раз. Результат: evidence/drain_timing.json.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
|
||||
BASE = "http://127.0.0.1:8080"
|
||||
PROJECT = "mtusi-lab3"
|
||||
|
||||
|
||||
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=" + PROJECT, "--filter", "label=com.docker.compose.service=api").split()
|
||||
|
||||
|
||||
class Prober(threading.Thread):
|
||||
def __init__(self):
|
||||
super().__init__(daemon=True)
|
||||
self.events, self.stop = [], threading.Event()
|
||||
|
||||
def run(self):
|
||||
while not self.stop.is_set():
|
||||
t = time.time()
|
||||
try:
|
||||
with urllib.request.urlopen(BASE + "/health/live", timeout=2) as r:
|
||||
self.events.append((t, r.status, r.headers.get("X-Instance-Id")))
|
||||
except Exception as exc:
|
||||
self.events.append((t, type(exc).__name__, None))
|
||||
time.sleep(0.01)
|
||||
|
||||
|
||||
def trial(kind):
|
||||
ids = api_ids()
|
||||
target = ids[0]
|
||||
prober = Prober()
|
||||
prober.start()
|
||||
time.sleep(2)
|
||||
t0 = time.time()
|
||||
if kind == "sigterm":
|
||||
sh("docker", "kill", "--signal=SIGTERM", target)
|
||||
else:
|
||||
sh("docker", "kill", target)
|
||||
deadline = time.time() + 30
|
||||
t_exit = None
|
||||
while time.time() < deadline:
|
||||
if sh("docker", "inspect", "-f", "{{.State.Running}}", target) == "false":
|
||||
t_exit = time.time() - t0
|
||||
break
|
||||
time.sleep(0.05)
|
||||
time.sleep(3)
|
||||
prober.stop.set()
|
||||
prober.join()
|
||||
served = [e for e in prober.events if e[0] >= t0 and e[2] == target]
|
||||
last_served = max((e[0] for e in served), default=t0) - t0
|
||||
errors = [e for e in prober.events if e[0] >= t0 and e[1] != 200]
|
||||
last_error = max((e[0] for e in errors), default=t0) - t0
|
||||
sh("docker", "rm", "-f", target)
|
||||
sh("sh", "scripts/restore-replicas.sh")
|
||||
time.sleep(8)
|
||||
return {"kind": kind, "seconds_until_replica_stops_serving": round(last_served, 2),
|
||||
"seconds_until_container_exit": round(t_exit, 2) if t_exit else None, "client_errors": len(errors),
|
||||
"seconds_until_errors_stop": round(last_error, 2) if errors else 0.0}
|
||||
|
||||
|
||||
def main():
|
||||
n = int(sys.argv[1]) if len(sys.argv) > 1 else 3
|
||||
results = [trial(k) for k in ("sigterm", "sigkill") for _ in range(n)]
|
||||
report = {"date": time.strftime("%Y-%m-%d %H:%M:%S"), "lb_health_check": "inter 1s, fall 2, rise 2",
|
||||
"drain_seconds": 4, "graceful_shutdown_seconds": 8, "trials": results}
|
||||
with open(os.path.join(ROOT, "evidence", "drain_timing.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__":
|
||||
main()
|
||||
@@ -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-lab3",
|
||||
"--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 @@
|
||||
"""Генератор нагрузки для экспериментов lab3+ (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,57 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Графики трека 1 из evidence/scaling_*.json: python research/plot_scaling.py --out evidence"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
|
||||
import matplotlib
|
||||
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt # noqa: E402
|
||||
|
||||
|
||||
def load(out, series, tag):
|
||||
path = os.path.join(out, "scaling_%s_%s.json" % (series, tag))
|
||||
return json.load(open(path, encoding="utf-8")) if os.path.exists(path) else None
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--out", default="evidence")
|
||||
out = ap.parse_args().out
|
||||
fig, ax = plt.subplots(1, 3, figsize=(17, 5))
|
||||
# A: фиксированный суммарный CPU
|
||||
for tag, color, shift in (("base", "#1565c0", -0.2), ("improved", "#2e7d32", 0.2)):
|
||||
d = load(out, "A", tag)
|
||||
if not d:
|
||||
continue
|
||||
names = [r["config"] for r in d["results"]]
|
||||
ax[0].bar([i + shift for i in range(len(names))], [r["total_rps"] for r in d["results"]], width=0.4, color=color,
|
||||
label={"base": "до (несколько запросов)", "improved": "после (функция БД)"}[tag])
|
||||
ax[0].set_xticks(range(len(names)))
|
||||
ax[0].set_xticklabels(["%s" % n.replace("x", " × ") + " CPU" for n in names])
|
||||
ax[0].set_title("A: суммарно 2.0 CPU на API (число реплик × CPU)"); ax[0].set_ylabel("успешных запросов/с"); ax[0].legend()
|
||||
# B: рост ресурсов
|
||||
for tag, color, label in (("base", "#1565c0", "БД 2 CPU, до"), ("base_pg4", "#ef6c00", "БД 4 CPU, до"), ("improved", "#2e7d32", "БД 2 CPU, после")):
|
||||
d = load(out, "B", tag)
|
||||
if not d:
|
||||
continue
|
||||
ax[1].plot([r["replicas"] for r in d["results"]], [r["total_rps"] for r in d["results"]], marker="o", color=color, label=label)
|
||||
ax[1].set_xscale("log", base=2); ax[1].set_xticks([1, 2, 4, 8]); ax[1].set_xticklabels(["1", "2", "4", "8"])
|
||||
ax[1].set_title("B: реплики по 1.0 CPU — насыщение"); ax[1].set_xlabel("число API-реплик"); ax[1].set_ylabel("успешных запросов/с"); ax[1].legend()
|
||||
# CPU компонентов в серии B (до)
|
||||
d = load(out, "B", "base")
|
||||
if d:
|
||||
reps = [r["replicas"] for r in d["results"]]
|
||||
for svc, color in (("postgres", "#c62828"), ("api", "#1565c0"), ("lb", "#6a1b9a")):
|
||||
ax[2].plot(reps, [r["docker_stats"].get(svc, {}).get("avg_cpu_percent_per_container") for r in d["results"]], marker="s", color=color,
|
||||
label={"postgres": "PostgreSQL (лимит 200 %)", "api": "API, на реплику (лимит 100 %)", "lb": "HAProxy (лимит 200 %)"}[svc])
|
||||
ax[2].set_xscale("log", base=2); ax[2].set_xticks([1, 2, 4, 8]); ax[2].set_xticklabels(["1", "2", "4", "8"])
|
||||
ax[2].set_title("B (до): загрузка CPU компонентов, % одного ядра"); ax[2].set_xlabel("число API-реплик"); ax[2].legend()
|
||||
fig.tight_layout()
|
||||
fig.savefig(os.path.join(out, "scaling.png"), dpi=110)
|
||||
print("saved")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -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()))
|
||||
Executable
+18
@@ -0,0 +1,18 @@
|
||||
#!/bin/sh
|
||||
# Полная серия трека 1: base (SEND_STRATEGY=multi) и improved (function); см. REPORT.md. Занимает ~35 минут.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
PY="${PY:-python}"
|
||||
export PYTHONUTF8=1
|
||||
set_strategy() {
|
||||
SEND_STRATEGY="$1" docker compose --env-file .env up -d --no-deps --force-recreate api >/dev/null 2>&1
|
||||
sleep 12
|
||||
}
|
||||
set_strategy multi
|
||||
$PY research/scaling.py --series A --concurrency 64 --tag base --out evidence
|
||||
$PY research/scaling.py --series B --concurrency 64 --tag base --out evidence
|
||||
$PY research/scaling.py --series B --concurrency 64 --pg-cpus 4 --tag base_pg4 --out evidence
|
||||
set_strategy function
|
||||
$PY research/scaling.py --series A --concurrency 64 --tag improved --out evidence
|
||||
$PY research/scaling.py --series B --concurrency 64 --tag improved --out evidence
|
||||
echo ALL-DONE
|
||||
@@ -0,0 +1,191 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Трек 1 (цена масштабирования), lab3.
|
||||
|
||||
Серия A (фиксированный суммарный CPU/RAM API): 1×2.0 CPU, 2×1.0, 4×0.5 — один и тот же профиль нагрузки.
|
||||
Серия B (рост ресурсов): 1, 2, 4, 8 реплик по 1.0 CPU; показывает точку насыщения (БД / LB / пул / клиент).
|
||||
Для каждой конфигурации: прогрев 5 с, затем N с нагрузки несколькими процессами-клиентами (closed-loop, 90 % POST / 10 % GET),
|
||||
параллельно семплируются `docker stats` (CPU каждого сервиса). Ресурсы меняются на лету `docker update`, реплики — `compose --scale`.
|
||||
|
||||
python research/scaling.py --series A --out evidence --tag base
|
||||
python research/scaling.py --series B --out evidence --tag base
|
||||
Переменные окружения стенда (SEND_STRATEGY=...) задаются при запуске compose и описываются в --tag.
|
||||
"""
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import multiprocessing as mp
|
||||
import os
|
||||
import statistics
|
||||
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"
|
||||
FILTER = ["--filter", "label=com.docker.compose.project=mtusi-lab3"]
|
||||
|
||||
|
||||
def sh(*args, check=False):
|
||||
return subprocess.run(args, cwd=ROOT, capture_output=True, text=True, env=dict(os.environ, **{"PYTHONUTF8": "1"})).stdout.strip()
|
||||
|
||||
|
||||
def containers(service):
|
||||
return sh("docker", "ps", "-q", *FILTER, "--filter", "label=com.docker.compose.service=" + service).split()
|
||||
|
||||
|
||||
def configure(replicas, api_cpus, pg_cpus, lb_cpus):
|
||||
sh("docker", "compose", "--env-file", ".env", "up", "-d", "--no-deps", "--no-recreate", "--scale", "api=%d" % replicas, "api")
|
||||
# лишние реплики (если было больше) удаляем
|
||||
ids = containers("api")
|
||||
for extra in ids[replicas:]:
|
||||
sh("docker", "stop", "--time", "5", extra)
|
||||
sh("docker", "rm", extra)
|
||||
for cid in containers("api"):
|
||||
sh("docker", "update", "--cpus", str(api_cpus), "--memory", "256m", "--memory-swap", "256m", cid)
|
||||
for cid in containers("postgres"):
|
||||
sh("docker", "update", "--cpus", str(pg_cpus), "--memory", "512m", "--memory-swap", "512m", cid)
|
||||
for cid in containers("lb"):
|
||||
sh("docker", "update", "--cpus", str(lb_cpus), "--memory", "128m", "--memory-swap", "128m", cid)
|
||||
deadline = time.time() + 60
|
||||
while time.time() < deadline:
|
||||
states = [sh("docker", "inspect", "-f", "{{.State.Health.Status}}", c) for c in containers("api")]
|
||||
if len(states) == replicas and all(s == "healthy" for s in states):
|
||||
break
|
||||
time.sleep(1)
|
||||
wait_lb(replicas)
|
||||
|
||||
|
||||
def wait_lb(replicas, timeout=90):
|
||||
"""Ждём, пока LB реально раздаёт запросы всем репликам (каждая видна по X-Instance-Id)."""
|
||||
import urllib.request
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
seen = set()
|
||||
try:
|
||||
for _ in range(replicas * 12):
|
||||
with urllib.request.urlopen(BASE + "/health/ready", timeout=2) as r:
|
||||
seen.add(r.headers.get("X-Instance-Id"))
|
||||
except Exception:
|
||||
time.sleep(1)
|
||||
continue
|
||||
if len(seen) >= replicas:
|
||||
return
|
||||
time.sleep(1)
|
||||
raise RuntimeError("LB не раздаёт запросы всем %d репликам" % replicas)
|
||||
|
||||
|
||||
def child(args):
|
||||
stand_data, seconds, concurrency, seed, t0 = args
|
||||
import random
|
||||
random.seed(seed)
|
||||
stand = loadgen.Stand(BASE)
|
||||
stand.users, stand.chats = stand_data["users"], stand_data["chats"]
|
||||
rec = loadgen.Recorder()
|
||||
rec.t0 = t0
|
||||
|
||||
async def go():
|
||||
await loadgen.run_load(stand, rec, seconds, concurrency)
|
||||
asyncio.run(go())
|
||||
return rec.events, len(rec.confirmed), rec.final_failures
|
||||
|
||||
|
||||
class Sampler(threading.Thread):
|
||||
def __init__(self):
|
||||
super().__init__(daemon=True)
|
||||
self.rows, self.stop = [], threading.Event()
|
||||
|
||||
def run(self):
|
||||
while not self.stop.is_set():
|
||||
out = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{.Name}} {{.CPUPerc}} {{.MemUsage}}"],
|
||||
capture_output=True, text=True).stdout.splitlines()
|
||||
self.rows.append((time.time(), [l.split() for l in out if "mtusi-lab3" in l]))
|
||||
|
||||
def summary(self, t_from, t_to):
|
||||
agg = {}
|
||||
for ts, rows in self.rows:
|
||||
if not t_from <= ts <= t_to:
|
||||
continue
|
||||
for r in rows:
|
||||
service = r[0].replace("mtusi-lab3-", "").rsplit("-", 1)[0]
|
||||
agg.setdefault(service, []).append(float(r[1].rstrip("%")))
|
||||
return {k: {"avg_cpu_percent_per_container": round(statistics.mean(v), 1), "samples": len(v)} for k, v in agg.items()}
|
||||
|
||||
|
||||
def run_config(name, replicas, api_cpus, pg_cpus, lb_cpus, args, stand_data):
|
||||
configure(replicas, api_cpus, pg_cpus, lb_cpus)
|
||||
# прогрев
|
||||
t0 = time.time()
|
||||
with mp.get_context("spawn").Pool(args.procs) as pool:
|
||||
pool.map(child, [(stand_data, 5, max(1, args.concurrency // args.procs), i, t0) for i in range(args.procs)])
|
||||
sampler = Sampler()
|
||||
sampler.start()
|
||||
t_start = time.time()
|
||||
with mp.get_context("spawn").Pool(args.procs) as pool:
|
||||
results = pool.map(child, [(stand_data, args.seconds, args.concurrency // args.procs, 100 + i, t_start) for i in range(args.procs)])
|
||||
t_end = time.time()
|
||||
sampler.stop.set()
|
||||
rec = loadgen.Recorder()
|
||||
rec.t0 = t_start
|
||||
for events, confirmed, failures in results:
|
||||
rec.events.extend(events)
|
||||
post = loadgen.summarize(rec, 0, args.seconds, "POST")
|
||||
get = loadgen.summarize(rec, 0, args.seconds, "GET")
|
||||
instances = {}
|
||||
for e in rec.events:
|
||||
if e[1] == "POST" and e[4]:
|
||||
instances[e[4]] = instances.get(e[4], 0) + 1
|
||||
out = {"config": name, "replicas": replicas, "api_cpus_each": api_cpus, "api_cpus_total": round(replicas * api_cpus, 2),
|
||||
"postgres_cpus": pg_cpus, "lb_cpus": lb_cpus, "concurrency": args.concurrency, "client_processes": args.procs,
|
||||
"post": post, "get": get, "total_rps": round((post.get("ok", 0) + get.get("ok", 0)) / args.seconds, 1),
|
||||
"replica_share": sorted(instances.values()), "docker_stats": sampler.summary(t_start + 2, t_end)}
|
||||
print(json.dumps({k: out[k] for k in ("config", "total_rps")} | {"p95": post.get("p95_ms"), "err": post.get("error_ratio"),
|
||||
"stats": out["docker_stats"]}, ensure_ascii=False))
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--series", choices=["A", "B", "C"], required=True)
|
||||
ap.add_argument("--out", default="evidence")
|
||||
ap.add_argument("--tag", default="base")
|
||||
ap.add_argument("--seconds", type=int, default=30)
|
||||
ap.add_argument("--concurrency", type=int, default=256)
|
||||
ap.add_argument("--procs", type=int, default=8)
|
||||
ap.add_argument("--pg-cpus", type=float, default=2.0)
|
||||
ap.add_argument("--lb-cpus", type=float, default=2.0)
|
||||
ap.add_argument("--repeat", type=int, default=2)
|
||||
args = ap.parse_args()
|
||||
configure(2, 1.0, args.pg_cpus, args.lb_cpus)
|
||||
stand = loadgen.Stand(BASE, users=40, chats=40)
|
||||
asyncio.run(stand.setup())
|
||||
stand_data = {"users": stand.users, "chats": stand.chats}
|
||||
if args.series == "A":
|
||||
configs = [("1x2.0", 1, 2.0), ("2x1.0", 2, 1.0), ("4x0.5", 4, 0.5)]
|
||||
elif args.series == "B":
|
||||
configs = [("1x1.0", 1, 1.0), ("2x1.0", 2, 1.0), ("4x1.0", 4, 1.0), ("8x1.0", 8, 1.0)]
|
||||
else: # C: только 2 и 4 реплики при увеличенном CPU БД — проверка гипотезы «узкое место — БД»
|
||||
configs = [("2x1.0", 2, 1.0), ("4x1.0", 4, 1.0)]
|
||||
results = []
|
||||
for name, n, cpus in configs:
|
||||
runs = [run_config(name, n, cpus, args.pg_cpus, args.lb_cpus, args, stand_data) for _ in range(args.repeat)]
|
||||
best = dict(runs[0])
|
||||
best["total_rps_runs"] = [r["total_rps"] for r in runs]
|
||||
best["total_rps"] = round(statistics.mean(r["total_rps"] for r in runs), 1)
|
||||
best["post_p95_runs"] = [r["post"].get("p95_ms") for r in runs]
|
||||
best["runs"] = runs
|
||||
results.append(best)
|
||||
report = {"date": time.strftime("%Y-%m-%d %H:%M:%S"), "series": args.series, "tag": args.tag, "args": vars(args), "results": results}
|
||||
path = os.path.join(args.out, "scaling_%s_%s.json" % (args.series, args.tag))
|
||||
with open(path, "w", encoding="utf-8") as fh:
|
||||
json.dump(report, fh, ensure_ascii=False, indent=2)
|
||||
configure(2, 1.0, 1.0, 1.0)
|
||||
print("saved", path)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
mp.freeze_support()
|
||||
main()
|
||||
Reference in New Issue
Block a user