forked from mtusi2026/mtusi2026lab3
Lab 3: HAProxy + 2 replicas, idempotency, graceful shutdown, track 1
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
# Трек 1 «Цена масштабирования»: override к compose.yaml.
|
||||
# docker compose --env-file .env -f compose.yaml -f research/compose.track1.yaml ...
|
||||
# Изоляция по ядрам: реплики API — только на API_CPUSET (их суммарный бюджет CPU фиксирован
|
||||
# квотой API_CPUS на реплику), всё остальное (LB, PostgreSQL, Redis, генератор) — на AUX_CPUSET,
|
||||
# чтобы генератор и БД не отнимали CPU у измеряемого API и наоборот. Значения задаёт
|
||||
# research/track1.py для каждой конфигурации.
|
||||
services:
|
||||
api:
|
||||
cpuset: "${API_CPUSET:-0}"
|
||||
environment:
|
||||
DB_POOL_MAX: ${DB_POOL_MAX:-10}
|
||||
SESSION_CACHE: ${SESSION_CACHE:-redis}
|
||||
lb:
|
||||
cpuset: "${AUX_CPUSET:-1}"
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "1.0", memory: 256M}
|
||||
postgres:
|
||||
cpuset: "${AUX_CPUSET:-1}"
|
||||
redis:
|
||||
cpuset: "${AUX_CPUSET:-1}"
|
||||
migrate:
|
||||
cpuset: "${AUX_CPUSET:-1}"
|
||||
loadgen:
|
||||
build: research/loadgen
|
||||
image: mtusi-lab3-loadgen:local
|
||||
profiles: [bench]
|
||||
networks: [edge]
|
||||
cpuset: "${AUX_CPUSET:-1}"
|
||||
read_only: true
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "1.0", memory: 512M}
|
||||
@@ -0,0 +1,41 @@
|
||||
#!/bin/sh
|
||||
# Демонстрация «expand-only» миграций при rolling update (уровень 4). Шаги:
|
||||
# 1. новая версия образа содержит дополнительную миграцию 0004 (временная, создаётся этим скриптом);
|
||||
# 2. контейнер новой версии, запущенный ДО миграции, не становится ready (схема отстаёт) —
|
||||
# LB не отправил бы на него трафик;
|
||||
# 3. migrate применяет 0004 один раз; старые реплики (знают 0001–0003) остаются ready: более новая
|
||||
# схема для них допустима;
|
||||
# 4. rolling update на новую версию под нагрузкой — research/lb_experiments.py rolling-update.
|
||||
# Вывод — evidence/lb/expand-migration.txt. После шага 4 удалите временный $MIG (БД сохранит таблицу;
|
||||
# код без файла 0004 остаётся совместимым — проверяются только известные ему миграции).
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
. scripts/lib.sh
|
||||
OUT=evidence/lb/expand-migration.txt
|
||||
mkdir -p evidence/lb
|
||||
MIG=migrations/0004_demo_expand.sql
|
||||
VERSION=${APP_VERSION:-expand-demo}
|
||||
BUILD_CMD=${BUILD_CMD:-"docker compose --env-file $ENV_FILE build --build-arg APP_VERSION=$VERSION api"}
|
||||
cat > "$MIG" <<'SQL'
|
||||
-- ДЕМО (expand): новая необязательная таблица; старый код её не использует.
|
||||
CREATE TABLE IF NOT EXISTS rollout_demo (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, note text);
|
||||
SQL
|
||||
{
|
||||
echo "# $(now) expand-migration demo, new version $VERSION"
|
||||
APP_VERSION=$VERSION $BUILD_CMD >/dev/null
|
||||
echo "== 1) new-version container before migrate:"
|
||||
cid=$(dc run -d --rm --no-deps api serve)
|
||||
sleep 6
|
||||
echo "health/ready inside new container: $(docker exec "$cid" python -m messenger healthcheck && echo 200 || echo NOT-READY)"
|
||||
docker logs "$cid" 2>&1 | grep -m1 'schema is behind' | sed 's/^/log: /' || true
|
||||
docker stop -t 5 "$cid" >/dev/null
|
||||
echo "== 2) migrate (one-shot):"
|
||||
dc run --rm --no-deps migrate 2>/dev/null | tail -1
|
||||
echo "== 3) old replicas after migrate:"
|
||||
for c in $(dc ps -q api); do
|
||||
printf '%s ready=%s version=%s\n' "$(docker inspect -f '{{.Name}}' "$c")" \
|
||||
"$(docker exec "$c" python -m messenger healthcheck && echo yes || echo no)" \
|
||||
"$(docker exec "$c" python -m messenger stats | python3 -c 'import json,sys;print(json.load(sys.stdin)["version"])')"
|
||||
done
|
||||
} > "$OUT" 2>&1
|
||||
cat "$OUT"
|
||||
@@ -0,0 +1,249 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Эксперименты уровня 4 (stdlib, Python 3.9+): отказ каждой API-реплики под нагрузкой и rolling update.
|
||||
|
||||
python3 research/lb_experiments.py failover-series [--mode stop|kill|both]
|
||||
python3 research/lb_experiments.py rolling-update
|
||||
|
||||
Нагрузка: closed-loop, W потоков через LB; каждый поток — свой пользователь, 1 POST сообщения
|
||||
(Idempotency-Key; при ошибке/таймауте повтор С ТЕМ ЖЕ ключом и телом) на 3 GET истории.
|
||||
Каждая попытка журналируется (время, операция, статус, X-Instance-Id, задержка). Итог — JSON в
|
||||
evidence/lb/*.json + текстовая сводка. Токены не сохраняются.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import shlex
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from urllib.parse import quote
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "student-tests"))
|
||||
from common import BASE_URL, Client, Failure, login, new_user # noqa: E402
|
||||
|
||||
OUT = ROOT / "evidence" / "lb"
|
||||
DC = shlex.split(os.environ.get("COMPOSE", "docker compose --env-file .env"))
|
||||
|
||||
|
||||
def sh(*args, check=True):
|
||||
return subprocess.run(list(args), cwd=ROOT, check=check, capture_output=True, text=True).stdout.strip()
|
||||
|
||||
|
||||
def api_containers():
|
||||
"""[(container_id, name, instance_id)] запущенных реплик сервиса api."""
|
||||
res = []
|
||||
for cid in sh(*DC, "ps", "-q", "api").split():
|
||||
name = sh("docker", "inspect", "-f", "{{.Name}}", cid).lstrip("/")
|
||||
iid = sh("docker", "exec", cid, "cat", "/tmp/instance-id", check=False)
|
||||
res.append((cid, name, iid))
|
||||
return sorted(res, key=lambda x: x[1])
|
||||
|
||||
|
||||
def wait_healthy(cid, timeout=60):
|
||||
t = time.monotonic()
|
||||
while time.monotonic() - t < timeout:
|
||||
if sh("docker", "inspect", "-f", "{{.State.Health.Status}}", cid, check=False) == "healthy":
|
||||
return time.monotonic() - t
|
||||
time.sleep(0.25)
|
||||
raise RuntimeError("container not healthy: " + cid)
|
||||
|
||||
|
||||
class Load:
|
||||
def __init__(self, workers, timeout=2.0):
|
||||
self.workers, self.timeout = workers, timeout
|
||||
self.events, self.lock, self.stop = [], threading.Lock(), threading.Event()
|
||||
boot = Client(BASE_URL)
|
||||
self.actors = []
|
||||
for i in range(workers):
|
||||
a = new_user(boot, "lb%d" % i); login(boot, a)
|
||||
a["chat"] = boot.call("POST", "/api/v1/chats", 201, actor=a, schema="Chat",
|
||||
body={"title": "lb", "member_ids": [a["id"]]})["json"]
|
||||
self.actors.append(a)
|
||||
self.t0 = None
|
||||
self.confirmed = {} # message id -> text (подтверждено 201)
|
||||
|
||||
def record(self, op, ok, status, instance, latency):
|
||||
with self.lock:
|
||||
self.events.append((time.monotonic() - self.t0, op, ok, status, instance, latency))
|
||||
|
||||
def worker(self, a):
|
||||
c = Client(BASE_URL, timeout=self.timeout)
|
||||
path = "/api/v1/chats/" + a["chat"]["id"] + "/messages"
|
||||
n, pending = 0, None
|
||||
while not self.stop.is_set():
|
||||
n += 1
|
||||
if n % 4 == 1:
|
||||
if pending is None:
|
||||
pending = (uuid.uuid4().hex, "lb-%s-%d" % (a["id"][:8], n))
|
||||
key, text = pending
|
||||
op, kw = "post", dict(method="POST", path=path, expected=201, actor=a, body={"text": text},
|
||||
headers={"Idempotency-Key": key}, schema="Message")
|
||||
else:
|
||||
op, kw = "get", dict(method="GET", path=path + "?limit=20", expected=200, actor=a, schema="MessagePage")
|
||||
t = time.monotonic()
|
||||
try:
|
||||
r = c.call(**kw)
|
||||
self.record(op, True, r["status"], r["headers"].get("X-Instance-Id"), time.monotonic() - t)
|
||||
if op == "post":
|
||||
with self.lock:
|
||||
self.confirmed[r["json"]["id"]] = r["json"]["text"]
|
||||
pending = None
|
||||
except Failure as exc:
|
||||
code = str(exc).rsplit("received ", 1)[-1] if "received" in str(exc) else "conn"
|
||||
self.record(op, False, code, None, time.monotonic() - t)
|
||||
time.sleep(0.05) # pending остаётся: повтор с тем же ключом и телом
|
||||
|
||||
def __enter__(self):
|
||||
self.t0 = time.monotonic()
|
||||
self.threads = [threading.Thread(target=self.worker, args=(a,), daemon=True) for a in self.actors]
|
||||
[t.start() for t in self.threads]
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
self.stop.set()
|
||||
[t.join(timeout=10) for t in self.threads]
|
||||
|
||||
def now(self):
|
||||
return time.monotonic() - self.t0
|
||||
|
||||
def verify(self):
|
||||
"""Все подтверждённые сообщения на месте, дублей текста (неуверенных повторов) нет."""
|
||||
c = Client(BASE_URL, timeout=10)
|
||||
texts, ids = [], set()
|
||||
for a in self.actors:
|
||||
path = "/api/v1/chats/" + a["chat"]["id"] + "/messages?limit=100"
|
||||
cursor = None
|
||||
while True:
|
||||
q = path + ("&cursor=" + quote(cursor, safe="") if cursor else "")
|
||||
page = c.call("GET", q, actor=a, schema="MessagePage")["json"]
|
||||
for m in page["items"]:
|
||||
texts.append(m["text"]); ids.add(m["id"])
|
||||
cursor = page["next_cursor"]
|
||||
if not cursor:
|
||||
break
|
||||
lost = [i for i in self.confirmed if i not in ids]
|
||||
return {"confirmed": len(self.confirmed), "lost_confirmed": len(lost),
|
||||
"stored": len(texts), "duplicate_texts": len(texts) - len(set(texts))}
|
||||
|
||||
|
||||
def window(events, a, b):
|
||||
ev = [e for e in events if a <= e[0] < b]
|
||||
ok = [e for e in ev if e[2]]
|
||||
lat = sorted(e[5] for e in ok)
|
||||
pct = (lambda p: round(1000 * lat[min(len(lat) - 1, int(p * len(lat)))], 1)) if lat else (lambda p: None)
|
||||
return {"seconds": round(b - a, 2), "ok": len(ok), "errors": len(ev) - len(ok),
|
||||
"rps_ok": round(len(ok) / (b - a), 1) if b > a else None,
|
||||
"p50_ms": pct(0.5), "p99_ms": pct(0.99),
|
||||
"by_instance": dict(sorted({i: sum(1 for e in ok if e[4] == i) for i in {e[4] for e in ok}}.items())),
|
||||
"error_codes": dict(sorted({s: sum(1 for e in ev if not e[2] and e[3] == s)
|
||||
for s in {e[3] for e in ev if not e[2]}}.items()))}
|
||||
|
||||
|
||||
def failover_series(args):
|
||||
modes = ["stop", "kill"] if args.mode == "both" else [args.mode]
|
||||
results = {"measured_at": datetime.now(timezone.utc).isoformat(timespec="seconds"), "workers": args.workers,
|
||||
"client_timeout_s": 2.0, "phases_s": {"before": args.before, "after_action": args.after},
|
||||
"runs": []}
|
||||
for mode in modes:
|
||||
for idx in range(len(api_containers())):
|
||||
targets = api_containers()
|
||||
cid, name, iid = targets[idx]
|
||||
load = Load(args.workers)
|
||||
with load:
|
||||
time.sleep(args.before)
|
||||
t_action = load.now()
|
||||
if mode == "stop":
|
||||
sh("docker", "stop", "-t", "15", cid) # SIGTERM → drain → exit
|
||||
else:
|
||||
sh("docker", "kill", "-s", "KILL", cid) # внезапная смерть процесса
|
||||
t_done = load.now()
|
||||
time.sleep(args.after)
|
||||
t_restore = load.now()
|
||||
sh("docker", "start", cid)
|
||||
healthy_after = wait_healthy(cid)
|
||||
new_iid = sh("docker", "exec", cid, "cat", "/tmp/instance-id", check=False)
|
||||
time.sleep(args.settle)
|
||||
t_end = load.now()
|
||||
ev = load.events
|
||||
errs = [e for e in ev if not e[2] and e[0] >= t_action]
|
||||
target_seen = [e[0] for e in ev if e[2] and e[4] == iid and e[0] >= t_action]
|
||||
back_seen = [e[0] for e in ev if e[2] and e[4] == new_iid and e[0] >= t_restore]
|
||||
posts_ok = sorted(e[0] for e in ev if e[2] and e[1] == "post")
|
||||
gaps = [b - a for a, b in zip(posts_ok, posts_ok[1:]) if a >= t_action - 1 and b <= t_restore]
|
||||
run = {
|
||||
"mode": mode, "container": name, "instance_id": iid,
|
||||
"action_seconds": round(t_done - t_action, 2),
|
||||
"before": window(ev, 0, t_action), "during": window(ev, t_action, t_restore),
|
||||
"after_restore": window(ev, t_restore, t_end),
|
||||
"errors_after_action": len(errs),
|
||||
"last_error_after_action_s": round(max(e[0] for e in errs) - t_action, 2) if errs else 0,
|
||||
"target_last_served_after_action_s": round(max(target_seen) - t_action, 2) if target_seen else 0,
|
||||
"max_gap_between_successful_writes_s": round(max(gaps), 2) if gaps else None,
|
||||
"replica_healthy_after_start_s": round(healthy_after, 2),
|
||||
"restarted_replica_first_served_s": round(min(back_seen) - t_restore, 2) if back_seen else None,
|
||||
"data": load.verify(),
|
||||
}
|
||||
results["runs"].append(run)
|
||||
print("%-4s %-18s errors=%-3d last_err=%5.2fs target_last=%5.2fs max_write_gap=%ss rps(before/during)=%s/%s data=%s" % (
|
||||
mode, name, run["errors_after_action"], run["last_error_after_action_s"],
|
||||
run["target_last_served_after_action_s"], run["max_gap_between_successful_writes_s"],
|
||||
run["before"]["rps_ok"], run["during"]["rps_ok"], run["data"]), flush=True)
|
||||
time.sleep(2)
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
(OUT / "failover-series.json").write_text(json.dumps(results, ensure_ascii=False, indent=2) + "\n")
|
||||
print("saved evidence/lb/failover-series.json")
|
||||
|
||||
|
||||
def rolling_update(args):
|
||||
before = api_containers()
|
||||
images_before = sorted({sh("docker", "inspect", "-f", "{{.Image}}", b[0])[:19] for b in before})
|
||||
load = Load(args.workers)
|
||||
with load:
|
||||
time.sleep(args.before)
|
||||
t_a = load.now()
|
||||
env = dict(os.environ)
|
||||
proc = subprocess.run([str(ROOT / "scripts" / "rolling-update.sh")], cwd=ROOT, env=env,
|
||||
capture_output=True, text=True)
|
||||
t_b = load.now()
|
||||
time.sleep(args.after)
|
||||
t_end = load.now()
|
||||
after = api_containers()
|
||||
ev = load.events
|
||||
res = {
|
||||
"measured_at": datetime.now(timezone.utc).isoformat(timespec="seconds"), "workers": args.workers,
|
||||
"script_exit": proc.returncode, "script_seconds": round(t_b - t_a, 2),
|
||||
"before_replicas": [{"container": n, "instance_id": i} for _, n, i in before],
|
||||
"after_replicas": [{"container": n, "instance_id": i} for _, n, i in after],
|
||||
"images_before": images_before,
|
||||
"images_after": sorted({sh("docker", "inspect", "-f", "{{.Image}}", a[0])[:19] for a in after}),
|
||||
"before": window(ev, 0, t_a), "during": window(ev, t_a, t_b), "after": window(ev, t_b, t_end),
|
||||
"data": load.verify(),
|
||||
}
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
(OUT / "rolling-update.json").write_text(json.dumps(res, ensure_ascii=False, indent=2) + "\n")
|
||||
print(json.dumps({k: res[k] for k in ("script_exit", "script_seconds", "before_replicas", "after_replicas",
|
||||
"during", "data")}, ensure_ascii=False, indent=1))
|
||||
if proc.returncode:
|
||||
print(proc.stderr[-2000:])
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
p.add_argument("experiment", choices=["failover-series", "rolling-update"])
|
||||
p.add_argument("--mode", choices=["stop", "kill", "both"], default="both")
|
||||
p.add_argument("--workers", type=int, default=8)
|
||||
p.add_argument("--before", type=float, default=5)
|
||||
p.add_argument("--after", type=float, default=10)
|
||||
p.add_argument("--settle", type=float, default=5)
|
||||
args = p.parse_args()
|
||||
{"failover-series": failover_series, "rolling-update": rolling_update}[args.experiment](args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,10 @@
|
||||
# Генератор нагрузки трека 1: только stdlib Go, статический бинарник в scratch.
|
||||
FROM golang:1.24.7-alpine AS build
|
||||
WORKDIR /src
|
||||
COPY go.mod main.go ./
|
||||
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /loadgen .
|
||||
|
||||
FROM scratch
|
||||
COPY --from=build /loadgen /loadgen
|
||||
USER 65534:65534
|
||||
ENTRYPOINT ["/loadgen"]
|
||||
@@ -0,0 +1,3 @@
|
||||
module mtusi/loadgen
|
||||
|
||||
go 1.22
|
||||
@@ -0,0 +1,274 @@
|
||||
// Open-loop HTTP load generator for track 1 (stdlib only, Go 1.22+).
|
||||
//
|
||||
// Сценарий: N синтетических пользователей, у каждого свой чат с историей; смесь запросов через LB:
|
||||
// GET истории (limit=50), POST сообщения (уникальный Idempotency-Key), GET /users/me.
|
||||
// Модель — открытая: запросы запускаются по расписанию (rate req/s) независимо от ответов;
|
||||
// задержка считается ОТ ЗАПЛАНИРОВАННОГО момента отправки (без coordinated omission).
|
||||
// Вывод — JSON-строки в stdout: {"event":"step",...} на каждую ступень rate. Токены не печатаются.
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net/http"
|
||||
"os"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
type actor struct {
|
||||
token, chat string
|
||||
}
|
||||
|
||||
var (
|
||||
target = flag.String("target", "http://lb:8080", "LB base URL")
|
||||
nUsers = flag.Int("users", 64, "synthetic users (one chat each)")
|
||||
seed = flag.Int("seed", 30, "messages per chat before measuring")
|
||||
rates = flag.String("rates", "100,200,300", "comma-separated request rates (req/s)")
|
||||
duration = flag.Duration("duration", 15*time.Second, "measured time per step")
|
||||
warmup = flag.Duration("warmup", 3*time.Second, "unmeasured time per step at the same rate")
|
||||
mixFlag = flag.String("mix", "history=70,post=20,me=10", "request mix, percent")
|
||||
timeout = flag.Duration("timeout", 5*time.Second, "client timeout per request")
|
||||
maxIn = flag.Int("maxinflight", 4000, "in-flight cap; above it a request is counted as dropped")
|
||||
label = flag.String("label", "", "free-form label copied into output")
|
||||
stopErr = flag.Float64("stoperr", 0.3, "stop the sweep after 2 consecutive steps with error ratio above this")
|
||||
)
|
||||
|
||||
var client, setupClient *http.Client
|
||||
|
||||
func rnd(n int) string {
|
||||
b := make([]byte, n)
|
||||
_, _ = rand.Read(b)
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
func do(method, path string, body []byte, hdr map[string]string) (int, []byte, error) {
|
||||
return doWith(client, method, path, body, hdr)
|
||||
}
|
||||
|
||||
func doWith(c *http.Client, method, path string, body []byte, hdr map[string]string) (int, []byte, error) {
|
||||
req, err := http.NewRequest(method, *target+path, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
for k, v := range hdr {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
resp, err := c.Do(req)
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
data, err := io.ReadAll(resp.Body)
|
||||
return resp.StatusCode, data, err
|
||||
}
|
||||
|
||||
func must(want int, what, method, path string, body []byte, hdr map[string]string) []byte {
|
||||
code, data, err := doWith(setupClient, method, path, body, hdr) // KDF медленный: отдельный таймаут
|
||||
if err != nil || code != want {
|
||||
fmt.Fprintf(os.Stderr, "setup %s failed: code=%d err=%v\n", what, code, err)
|
||||
os.Exit(2)
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
func setup() []actor {
|
||||
actors := make([]actor, *nUsers)
|
||||
var wg sync.WaitGroup
|
||||
sem := make(chan struct{}, 4)
|
||||
for i := range actors {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
sem <- struct{}{}
|
||||
defer func() { <-sem }()
|
||||
user, pw := "lg_"+rnd(6), "Lg-"+rnd(12)
|
||||
b, _ := json.Marshal(map[string]string{"username": user, "display_name": "load " + strconv.Itoa(i), "password": pw})
|
||||
var u struct{ ID string }
|
||||
_ = json.Unmarshal(must(201, "user", "POST", "/api/v1/users", b, nil), &u)
|
||||
basic := "Basic " + base64.StdEncoding.EncodeToString([]byte(user+":"+pw))
|
||||
var s struct{ Token string }
|
||||
_ = json.Unmarshal(must(201, "login", "POST", "/api/v1/auth/sessions", nil, map[string]string{"Authorization": basic}), &s)
|
||||
auth := map[string]string{"Authorization": "Bearer " + s.Token}
|
||||
cb, _ := json.Marshal(map[string]any{"title": "load", "member_ids": []string{u.ID}})
|
||||
var c struct{ ID string }
|
||||
_ = json.Unmarshal(must(201, "chat", "POST", "/api/v1/chats", cb, auth), &c)
|
||||
for k := 0; k < *seed; k++ {
|
||||
auth["Idempotency-Key"] = rnd(8)
|
||||
mb, _ := json.Marshal(map[string]string{"text": "seed " + strconv.Itoa(k)})
|
||||
must(201, "seed", "POST", "/api/v1/chats/"+c.ID+"/messages", mb, auth)
|
||||
}
|
||||
actors[i] = actor{token: s.Token, chat: c.ID}
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
return actors
|
||||
}
|
||||
|
||||
type sample struct {
|
||||
op int
|
||||
latency time.Duration // от запланированного момента
|
||||
service time.Duration // от фактической отправки
|
||||
status int
|
||||
}
|
||||
|
||||
func pct(v []float64, p float64) float64 {
|
||||
if len(v) == 0 {
|
||||
return math.NaN()
|
||||
}
|
||||
i := int(math.Ceil(p*float64(len(v)))) - 1
|
||||
if i < 0 {
|
||||
i = 0
|
||||
}
|
||||
return math.Round(v[i]*100) / 100
|
||||
}
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
client = &http.Client{Timeout: *timeout, Transport: &http.Transport{
|
||||
MaxIdleConns: 10000, MaxIdleConnsPerHost: 10000, IdleConnTimeout: 30 * time.Second, DisableCompression: true,
|
||||
}}
|
||||
setupClient = &http.Client{Timeout: 60 * time.Second}
|
||||
ops := []string{"history", "post", "me"}
|
||||
weights := map[string]int{}
|
||||
for _, part := range strings.Split(*mixFlag, ",") {
|
||||
kv := strings.SplitN(part, "=", 2)
|
||||
w, _ := strconv.Atoi(kv[1])
|
||||
weights[kv[0]] = w
|
||||
}
|
||||
var wheel []int
|
||||
for i, op := range ops {
|
||||
for k := 0; k < weights[op]; k++ {
|
||||
wheel = append(wheel, i)
|
||||
}
|
||||
}
|
||||
t0 := time.Now()
|
||||
actors := setup()
|
||||
setupSec := time.Since(t0).Seconds()
|
||||
_ = json.NewEncoder(os.Stdout).Encode(map[string]any{"event": "setup", "label": *label, "users": len(actors), "seed": *seed, "seconds": setupSec})
|
||||
|
||||
bad := 0
|
||||
for _, rs := range strings.Split(*rates, ",") {
|
||||
if bad >= 2 {
|
||||
break
|
||||
}
|
||||
rate, _ := strconv.ParseFloat(strings.TrimSpace(rs), 64)
|
||||
var mu sync.Mutex
|
||||
var samples []sample
|
||||
var inflight, dropped, errs int64
|
||||
errKinds := map[string]int{}
|
||||
total := *warmup + *duration
|
||||
interval := time.Duration(float64(time.Second) / rate)
|
||||
start := time.Now().Add(50 * time.Millisecond)
|
||||
measureFrom := start.Add(*warmup)
|
||||
_ = json.NewEncoder(os.Stdout).Encode(map[string]any{"event": "step_start", "label": *label, "rate": rate,
|
||||
"warmup_s": warmup.Seconds(), "duration_s": duration.Seconds(), "ts": float64(start.UnixNano()) / 1e9})
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; ; i++ {
|
||||
sched := start.Add(time.Duration(i) * interval)
|
||||
if sched.Sub(start) >= total {
|
||||
break
|
||||
}
|
||||
if d := time.Until(sched); d > 0 {
|
||||
time.Sleep(d)
|
||||
}
|
||||
measured := !sched.Before(measureFrom)
|
||||
if atomic.LoadInt64(&inflight) >= int64(*maxIn) {
|
||||
if measured {
|
||||
atomic.AddInt64(&dropped, 1)
|
||||
}
|
||||
continue
|
||||
}
|
||||
atomic.AddInt64(&inflight, 1)
|
||||
wg.Add(1)
|
||||
a := actors[i%len(actors)]
|
||||
op := wheel[i%len(wheel)]
|
||||
go func(a actor, op int, sched time.Time, measured bool) {
|
||||
defer wg.Done()
|
||||
defer atomic.AddInt64(&inflight, -1)
|
||||
hdr := map[string]string{"Authorization": "Bearer " + a.token}
|
||||
var code int
|
||||
var err error
|
||||
sent := time.Now()
|
||||
switch op {
|
||||
case 0:
|
||||
code, _, err = do("GET", "/api/v1/chats/"+a.chat+"/messages?limit=50", nil, hdr)
|
||||
case 1:
|
||||
hdr["Idempotency-Key"] = rnd(8)
|
||||
code, _, err = do("POST", "/api/v1/chats/"+a.chat+"/messages", []byte(`{"text":"load message"}`), hdr)
|
||||
case 2:
|
||||
code, _, err = do("GET", "/api/v1/users/me", nil, hdr)
|
||||
}
|
||||
done := time.Now()
|
||||
if !measured {
|
||||
return
|
||||
}
|
||||
want := 200
|
||||
if op == 1 {
|
||||
want = 201
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if err != nil || code != want {
|
||||
errs++
|
||||
k := strconv.Itoa(code)
|
||||
if err != nil {
|
||||
k = "transport"
|
||||
if strings.Contains(err.Error(), "Timeout") || strings.Contains(err.Error(), "deadline") {
|
||||
k = "timeout"
|
||||
}
|
||||
}
|
||||
errKinds[k]++
|
||||
return
|
||||
}
|
||||
samples = append(samples, sample{op, done.Sub(sched), done.Sub(sent), code})
|
||||
}(a, op, sched, measured)
|
||||
}
|
||||
wg.Wait()
|
||||
lat := make([]float64, 0, len(samples))
|
||||
svc := make([]float64, 0, len(samples))
|
||||
perOp := map[string][]float64{}
|
||||
for _, s := range samples {
|
||||
ms := float64(s.latency.Microseconds()) / 1000
|
||||
lat = append(lat, ms)
|
||||
svc = append(svc, float64(s.service.Microseconds())/1000)
|
||||
perOp[ops[s.op]] = append(perOp[ops[s.op]], ms)
|
||||
}
|
||||
sort.Float64s(lat)
|
||||
sort.Float64s(svc)
|
||||
opStats := map[string]any{}
|
||||
for k, v := range perOp {
|
||||
sort.Float64s(v)
|
||||
opStats[k] = map[string]any{"ok": len(v), "p50_ms": pct(v, .5), "p99_ms": pct(v, .99)}
|
||||
}
|
||||
attempted := float64(len(samples)) + float64(errs) + float64(dropped)
|
||||
if (float64(errs)+float64(dropped))/math.Max(attempted, 1) > *stopErr {
|
||||
bad++
|
||||
} else {
|
||||
bad = 0
|
||||
}
|
||||
_ = json.NewEncoder(os.Stdout).Encode(map[string]any{
|
||||
"event": "step", "label": *label, "rate": rate, "duration_s": duration.Seconds(),
|
||||
"attempted": attempted, "ok": len(samples), "errors": errs, "dropped": dropped, "error_kinds": errKinds,
|
||||
"throughput_ok_rps": math.Round(float64(len(samples))/duration.Seconds()*10) / 10,
|
||||
"error_ratio": math.Round((float64(errs)+float64(dropped))/math.Max(attempted, 1)*1e4) / 1e4,
|
||||
"latency_ms": map[string]float64{"p50": pct(lat, .5), "p90": pct(lat, .9), "p99": pct(lat, .99), "p999": pct(lat, .999), "max": pct(lat, 1)},
|
||||
"service_ms": map[string]float64{"p50": pct(svc, .5), "p99": pct(svc, .99)},
|
||||
"per_op": opStats,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Трек 1 «Цена масштабирования» (stdlib, Python 3.9+). Оркестратор серий нагрузки.
|
||||
|
||||
python3 research/track1.py run <series>... # fixed-cpu | growth | machine | admission | all
|
||||
python3 research/track1.py report # сводка + графики из evidence/track1/*.json
|
||||
|
||||
Для каждой конфигурации: пересоздать реплики с заданными CPU/RAM/числом (compose.yaml +
|
||||
research/compose.track1.yaml), дождаться, пока LB видит все реплики UP, запустить генератор
|
||||
(research/loadgen, open-loop, ступени rate) внутри сети стенда и параллельно собирать:
|
||||
CPU%/RAM контейнеров (docker stats), очередь/сессии HAProxy (stats CSV), состояния соединений
|
||||
PostgreSQL (pg_stat_activity), счётчики пула psycopg в каждой реплике (до/после серии).
|
||||
Результат — evidence/track1/<config>.json. Токенов и паролей в выводе нет.
|
||||
"""
|
||||
import argparse
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shlex
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.request
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OUT = ROOT / "evidence" / "track1"
|
||||
BASE_FILES = os.environ.get("COMPOSE_FILE", "compose.yaml:research/compose.track1.yaml")
|
||||
DC = shlex.split(os.environ.get("COMPOSE", "docker compose --env-file .env"))
|
||||
STATS_URL = os.environ.get("LB_STATS_URL", "http://127.0.0.1:8404/stats;csv")
|
||||
SLO_P99_MS, SLO_ERR = 250.0, 0.01
|
||||
|
||||
# Ступени offered rate (req/s). Генератор останавливает серию после 2 ступеней с >30 % ошибок.
|
||||
RATES = "40,80,120,160,200,240,280,320,360,400,460,520,600,700,800"
|
||||
CONFIGS = {
|
||||
# Серия A: фиксированный суммарный бюджет API = 1 ядро и 512 MiB (KDF-параллелизм 4) делим на 1/2/4.
|
||||
"fixed-1x1.00": dict(series="fixed-cpu", API_REPLICAS=1, API_CPUS="1.0", API_MEMORY="512M", KDF_CONCURRENCY=4),
|
||||
"fixed-2x0.50": dict(series="fixed-cpu", API_REPLICAS=2, API_CPUS="0.5", API_MEMORY="256M", KDF_CONCURRENCY=2),
|
||||
"fixed-4x0.25": dict(series="fixed-cpu", API_REPLICAS=4, API_CPUS="0.25", API_MEMORY="128M", KDF_CONCURRENCY=1),
|
||||
# Серия B: рост ресурсов — добавляем реплики по 0.25 ядра/128 MiB (4x0.25 = fixed-4x0.25).
|
||||
"growth-1x0.25": dict(series="growth", API_REPLICAS=1, API_CPUS="0.25", API_MEMORY="128M", KDF_CONCURRENCY=1),
|
||||
"growth-2x0.25": dict(series="growth", API_REPLICAS=2, API_CPUS="0.25", API_MEMORY="128M", KDF_CONCURRENCY=1),
|
||||
"growth-3x0.25": dict(series="growth", API_REPLICAS=3, API_CPUS="0.25", API_MEMORY="128M", KDF_CONCURRENCY=1),
|
||||
# Серия C: снять изоляцию ядер — API делит всю машину (2 vCPU) с LB/БД/генератором.
|
||||
"machine-2x1.00": dict(series="machine", API_REPLICAS=2, API_CPUS="1.0", API_MEMORY="256M", KDF_CONCURRENCY=2,
|
||||
API_CPUSET="0-1", AUX_CPUSET="0-1"),
|
||||
"machine-4x1.00": dict(series="machine", API_REPLICAS=4, API_CPUS="1.0", API_MEMORY="256M", KDF_CONCURRENCY=2,
|
||||
API_CPUSET="0-1", AUX_CPUSET="0-1"),
|
||||
# Серия P: размер пула соединений при 1x1.00 (p10 = fixed-1x1.00).
|
||||
"pool-1x1.00-p5": dict(series="pool", API_REPLICAS=1, API_CPUS="1.0", API_MEMORY="512M", KDF_CONCURRENCY=4, DB_POOL_MAX=5),
|
||||
"pool-1x1.00-p20": dict(series="pool", API_REPLICAS=1, API_CPUS="1.0", API_MEMORY="512M", KDF_CONCURRENCY=4, DB_POOL_MAX=20),
|
||||
"pool-1x1.00-p40": dict(series="pool", API_REPLICAS=1, API_CPUS="1.0", API_MEMORY="512M", KDF_CONCURRENCY=4, DB_POOL_MAX=40),
|
||||
# Серия D: улучшение — ограничение конкуренции на LB (maxconn на реплику; mc0 = fixed-1x1.00).
|
||||
"admission-1x1.00-mc10": dict(series="admission", API_REPLICAS=1, API_CPUS="1.0", API_MEMORY="512M",
|
||||
KDF_CONCURRENCY=4, LB_SERVER_MAXCONN=10),
|
||||
"admission-1x1.00-mc20": dict(series="admission", API_REPLICAS=1, API_CPUS="1.0", API_MEMORY="512M",
|
||||
KDF_CONCURRENCY=4, LB_SERVER_MAXCONN=20),
|
||||
"admission-1x1.00-mc10-q250": dict(series="admission", API_REPLICAS=1, API_CPUS="1.0", API_MEMORY="512M",
|
||||
KDF_CONCURRENCY=4, LB_SERVER_MAXCONN=10, LB_QUEUE_TIMEOUT="250ms"),
|
||||
"admission-2x0.50-mc10": dict(series="admission", API_REPLICAS=2, API_CPUS="0.5", API_MEMORY="256M",
|
||||
KDF_CONCURRENCY=2, LB_SERVER_MAXCONN=10),
|
||||
}
|
||||
DEFAULTS = dict(API_CPUSET="0", AUX_CPUSET="1", DB_POOL_MAX="10", SESSION_CACHE="redis",
|
||||
LB_SERVER_MAXCONN="0", LB_QUEUE_TIMEOUT="2s")
|
||||
|
||||
|
||||
def run(args, env=None, check=True, capture=True, timeout=900):
|
||||
return subprocess.run(args, cwd=ROOT, env=env, check=check, timeout=timeout,
|
||||
stdout=subprocess.PIPE if capture else None, stderr=subprocess.PIPE, text=True)
|
||||
|
||||
|
||||
def cfg_env(cfg):
|
||||
env = dict(os.environ)
|
||||
env.setdefault("COMPOSE_FILE", BASE_FILES)
|
||||
for k, v in {**DEFAULTS, **cfg}.items():
|
||||
if k.isupper():
|
||||
env[k] = str(v)
|
||||
return env
|
||||
|
||||
|
||||
def lb_rows():
|
||||
with urllib.request.urlopen(STATS_URL, timeout=2) as r:
|
||||
text = r.read().decode().lstrip("# ")
|
||||
return list(csv.DictReader(io.StringIO(text)))
|
||||
|
||||
|
||||
def wait_lb(n, timeout=90):
|
||||
t = time.monotonic()
|
||||
while time.monotonic() - t < timeout:
|
||||
try:
|
||||
up = [r for r in lb_rows() if r["pxname"] == "api" and r["svname"].startswith("api")
|
||||
and not r["svname"].startswith("apibk") and r["status"] == "UP"]
|
||||
if len(up) == n:
|
||||
return
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(1)
|
||||
raise SystemExit("LB does not see %d UP replicas" % n)
|
||||
|
||||
|
||||
def pool_stats(env):
|
||||
res = {}
|
||||
for cid in run(DC + ["ps", "-q", "api"], env).stdout.split():
|
||||
out = run(["docker", "exec", cid, "python", "-m", "messenger", "stats"], check=False).stdout
|
||||
try:
|
||||
d = json.loads(out)
|
||||
res[d["instance_id"]] = {"pool": d["pool"], "cache": d["cache"], "requests": d["app"]["requests"]}
|
||||
except (ValueError, KeyError):
|
||||
pass
|
||||
return res
|
||||
|
||||
|
||||
class Sampler:
|
||||
"""docker stats (CPU%, RAM), HAProxy CSV и pg_stat_activity раз в ~1 с с отметками времени."""
|
||||
|
||||
ANSI = re.compile(r"\x1b\[[0-9;]*[A-Za-z]")
|
||||
|
||||
def __init__(self, env):
|
||||
self.env, self.stop = env, threading.Event()
|
||||
self.docker, self.lb, self.pg, self.throttle = [], [], [], []
|
||||
|
||||
def _docker(self):
|
||||
p = subprocess.Popen(["docker", "stats", "--format", "{{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}"],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, cwd=ROOT)
|
||||
try:
|
||||
for line in p.stdout:
|
||||
if self.stop.is_set():
|
||||
break
|
||||
line = self.ANSI.sub("", line).strip()
|
||||
parts = line.split("\t")
|
||||
if len(parts) == 3 and parts[1].endswith("%") and parts[0].startswith("mtusi-lab3-"):
|
||||
mem = parts[2].split("/")[0].strip()
|
||||
mib = float(re.sub(r"[^0-9.]", "", mem) or 0) * (1024 if "GiB" in mem else 1 / 1024 if "KiB" in mem else 1)
|
||||
self.docker.append((time.time(), parts[0].replace("mtusi-lab3-", ""), float(parts[1][:-1]), mib))
|
||||
finally:
|
||||
p.kill()
|
||||
|
||||
@staticmethod
|
||||
def _throttle(cid):
|
||||
for path in ("/sys/fs/cgroup/cpu/docker/%s/cpu.stat" % cid, "/sys/fs/cgroup/system.slice/docker-%s.scope/cpu.stat" % cid):
|
||||
try:
|
||||
d = dict(line.split() for line in open(path))
|
||||
return int(d.get("nr_periods", 0)), int(d.get("nr_throttled", 0))
|
||||
except OSError:
|
||||
continue
|
||||
return None
|
||||
|
||||
def _poll(self):
|
||||
ids = [c for c in run(DC + ["ps", "-q", "--no-trunc", "api"], self.env, check=False).stdout.split()]
|
||||
while not self.stop.is_set():
|
||||
t = time.time()
|
||||
thr = [self._throttle(c) for c in ids]
|
||||
if all(thr) and thr:
|
||||
self.throttle.append((t, sum(x[0] for x in thr), sum(x[1] for x in thr)))
|
||||
try:
|
||||
rows = lb_rows()
|
||||
api = [r for r in rows if r["pxname"] == "api" and r["svname"] not in ("FRONTEND",)]
|
||||
be = next(r for r in api if r["svname"] == "BACKEND")
|
||||
self.lb.append((t, int(be["qcur"] or 0), int(be["scur"] or 0),
|
||||
sum(int(r["qcur"] or 0) for r in api if r["svname"].startswith("api"))))
|
||||
except (OSError, StopIteration, ValueError):
|
||||
pass
|
||||
self.stop.wait(1.0)
|
||||
|
||||
PG_SQL = ("SELECT 'S', extract(epoch FROM now()), coalesce(state, '?'), count(*) FROM pg_stat_activity"
|
||||
" WHERE datname = 'messenger' AND backend_type = 'client backend' AND pid <> pg_backend_pid() GROUP BY 3"
|
||||
" UNION ALL SELECT 'W', extract(epoch FROM now()), coalesce(wait_event_type || ':' || wait_event, 'CPU'), count(*)"
|
||||
" FROM pg_stat_activity WHERE datname = 'messenger' AND state = 'active' AND pid <> pg_backend_pid() GROUP BY 3")
|
||||
|
||||
def _pg(self):
|
||||
"""ОДНА долгоживущая сессия psql с \\watch 1 (не docker exec каждую секунду — он сам грузит хост)."""
|
||||
p = subprocess.Popen(DC + ["exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-At", "-F", "|"],
|
||||
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True,
|
||||
cwd=ROOT, env=self.env)
|
||||
p.stdin.write(self.PG_SQL + " \\watch 1\n"); p.stdin.flush()
|
||||
snap, cur_ts = {}, None
|
||||
try:
|
||||
for line in p.stdout:
|
||||
if self.stop.is_set():
|
||||
break
|
||||
parts = line.strip().split("|")
|
||||
if len(parts) != 4:
|
||||
continue
|
||||
kind, ts, key, n = parts
|
||||
ts = float(ts)
|
||||
if cur_ts is not None and ts != cur_ts:
|
||||
self.pg.append((cur_ts, snap)); snap = {}
|
||||
cur_ts = ts
|
||||
snap[("state:" if kind == "S" else "wait:") + key] = int(n)
|
||||
finally:
|
||||
p.kill()
|
||||
|
||||
def __enter__(self):
|
||||
self.threads = [threading.Thread(target=self._docker, daemon=True), threading.Thread(target=self._poll, daemon=True),
|
||||
threading.Thread(target=self._pg, daemon=True)]
|
||||
[t.start() for t in self.threads]
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
self.stop.set()
|
||||
|
||||
def window(self, a, b):
|
||||
cpu, mem = {}, {}
|
||||
for t, name, c, m in self.docker:
|
||||
if a <= t <= b:
|
||||
key = "api" if re.fullmatch(r"api-\d+", name) else re.sub(r"-\d+$", "", name)
|
||||
cpu.setdefault((key, name), []).append(c)
|
||||
mem.setdefault(key, []).append(m)
|
||||
agg = {}
|
||||
for (key, name), vals in cpu.items():
|
||||
agg.setdefault(key, 0.0)
|
||||
agg[key] += statistics.mean(vals)
|
||||
lb = [x for x in self.lb if a <= x[0] <= b]
|
||||
th = [x for x in self.throttle if a <= x[0] <= b]
|
||||
throttled = (round((th[-1][2] - th[0][2]) / max(1, th[-1][1] - th[0][1]), 3) if len(th) >= 2 else None)
|
||||
pg = [x[1] for x in self.pg if a <= x[0] <= b]
|
||||
return {
|
||||
"cpu_percent_mean": {k: round(v, 1) for k, v in sorted(agg.items())},
|
||||
"mem_mib_max": {k: round(max(v), 1) for k, v in sorted(mem.items())},
|
||||
"lb_queue_max": max((x[1] + x[3] for x in lb), default=None),
|
||||
"lb_sessions_mean": round(statistics.mean(x[2] for x in lb), 1) if lb else None,
|
||||
"pg_active_mean": round(statistics.mean(p.get("state:active", 0) for p in pg), 2) if pg else None,
|
||||
"pg_wait_events_mean": ({k[5:]: round(sum(p.get(k, 0) for p in pg) / len(pg), 2)
|
||||
for k in sorted({k for p in pg for k in p if k.startswith("wait:")})} if pg else None),
|
||||
"api_cfs_throttled_period_ratio": throttled,
|
||||
"pg_connections_mean": round(statistics.mean(sum(v for k, v in p.items() if k.startswith("state:")) for p in pg), 1) if pg else None,
|
||||
}
|
||||
|
||||
|
||||
def run_config(name, cfg, args, rep=1):
|
||||
if rep > 1:
|
||||
name = "%s-r%d" % (name, rep)
|
||||
env = cfg_env(cfg)
|
||||
print("== %s %s" % (name, {k: v for k, v in cfg.items() if k.isupper()}), flush=True)
|
||||
run(DC + ["up", "-d", "--wait", "--force-recreate", "lb", "api"], env, timeout=300)
|
||||
wait_lb(int(cfg["API_REPLICAS"]))
|
||||
time.sleep(3)
|
||||
pools_before = pool_stats(env)
|
||||
rates = cfg.get("RATES", args.rates)
|
||||
cmd = DC + ["--profile", "bench", "run", "--rm", "-T", "loadgen", "-rates", rates,
|
||||
"-duration", "%ds" % args.duration, "-warmup", "%ds" % args.warmup,
|
||||
"-users", str(args.users), "-seed", str(args.seed), "-label", name]
|
||||
steps, starts = [], {}
|
||||
with Sampler(env) as sampler:
|
||||
p = subprocess.Popen(cmd, cwd=ROOT, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
for line in p.stdout:
|
||||
try:
|
||||
ev = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
if ev["event"] == "step_start":
|
||||
starts[ev["rate"]] = ev["ts"] + ev["warmup_s"]
|
||||
elif ev["event"] == "step":
|
||||
a = starts[ev["rate"]]
|
||||
ev["resources"] = sampler.window(a, a + ev["duration_s"])
|
||||
ev["slo_ok"] = ev["latency_ms"]["p99"] <= SLO_P99_MS and ev["error_ratio"] <= SLO_ERR
|
||||
steps.append(ev)
|
||||
print(" rate %5.0f ok %6.1f rps err %5.1f%% p50 %7.1f p99 %8.1f ms cpu %s pgActive %s lbQ %s" % (
|
||||
ev["rate"], ev["throughput_ok_rps"], 100 * ev["error_ratio"], ev["latency_ms"]["p50"],
|
||||
ev["latency_ms"]["p99"], ev["resources"]["cpu_percent_mean"], ev["resources"]["pg_active_mean"],
|
||||
ev["resources"]["lb_queue_max"]), flush=True)
|
||||
elif ev["event"] == "setup":
|
||||
print(" setup %.1fs" % ev["seconds"], flush=True)
|
||||
p.wait()
|
||||
if p.returncode:
|
||||
print(p.stderr.read()[-1500:])
|
||||
pools_after = pool_stats(env)
|
||||
ok = [s for s in steps if s["slo_ok"]]
|
||||
result = {
|
||||
"config": name, "repeat": rep, "series": cfg["series"], "params": {**DEFAULTS, **{k: v for k, v in cfg.items() if k.isupper()}},
|
||||
"measured_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
||||
"slo": {"p99_ms": SLO_P99_MS, "error_ratio": SLO_ERR},
|
||||
"capacity_at_slo_rps": max((s["throughput_ok_rps"] for s in ok), default=0),
|
||||
"peak_ok_rps": max((s["throughput_ok_rps"] for s in steps), default=0),
|
||||
"steps": steps, "pool_before": pools_before, "pool_after": pools_after,
|
||||
"loadgen": {"users": args.users, "seed": args.seed, "duration_s": args.duration, "warmup_s": args.warmup,
|
||||
"mix": "history=70,post=20,me=10", "model": "open-loop, latency from scheduled time"},
|
||||
}
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
(OUT / (name + ".json")).write_text(json.dumps(result, ensure_ascii=False, indent=1) + "\n")
|
||||
print(" => capacity@SLO %.1f rps, peak %.1f rps" % (result["capacity_at_slo_rps"], result["peak_ok_rps"]), flush=True)
|
||||
|
||||
|
||||
def report(args):
|
||||
from track1_report import build # noqa: E402 (рядом в research/)
|
||||
build(OUT)
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
p.add_argument("action", choices=["run", "report", "list"])
|
||||
p.add_argument("targets", nargs="*", default=["all"])
|
||||
p.add_argument("--rates", default=RATES)
|
||||
p.add_argument("--duration", type=int, default=10)
|
||||
p.add_argument("--warmup", type=int, default=3)
|
||||
p.add_argument("--users", type=int, default=48)
|
||||
p.add_argument("--seed", type=int, default=10)
|
||||
p.add_argument("--rep", type=int, default=1, help="номер повтора (сохраняется как <config>-r<rep>.json)")
|
||||
args = p.parse_args()
|
||||
if args.action == "list":
|
||||
for k, v in CONFIGS.items():
|
||||
print(k, v)
|
||||
return
|
||||
if args.action == "report":
|
||||
sys.path.insert(0, str(Path(__file__).parent))
|
||||
return report(args)
|
||||
names = [n for n, c in CONFIGS.items() if "all" in args.targets or c["series"] in args.targets or n in args.targets]
|
||||
for n in names:
|
||||
run_config(n, CONFIGS[n], args, args.rep)
|
||||
# вернуть штатную конфигурацию стенда
|
||||
run(DC + ["up", "-d", "--wait", "--force-recreate", "lb", "api"], cfg_env({"API_REPLICAS": 2}), timeout=300)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,208 @@
|
||||
"""Сводка и графики трека 1 из evidence/track1/*.json (stdlib; SVG без внешних библиотек).
|
||||
|
||||
Графики: одна ось Y на график, линии 2 px, маркеры ≥ 8 px разной формы (вторичное кодирование),
|
||||
подписи серий у конца линии + легенда, всплывающие подсказки через <title>, таблица в summary.md.
|
||||
"""
|
||||
import json
|
||||
import statistics
|
||||
from pathlib import Path
|
||||
|
||||
# Категориальная палитра (validated: dataviz reference palette, slots 1–4, light surface).
|
||||
SERIES = ["#2a78d6", "#eb6834", "#1baf7a", "#eda100"]
|
||||
SURFACE, INK, INK2, GRID = "#fcfcfb", "#0b0b0b", "#52514e", "#e4e3df"
|
||||
SHAPES = ["circle", "square", "triangle", "diamond"]
|
||||
|
||||
|
||||
def load(out):
|
||||
runs = {}
|
||||
for f in sorted(Path(out).glob("*.json")):
|
||||
if f.name.startswith("summary"):
|
||||
continue
|
||||
d = json.loads(f.read_text())
|
||||
base = d["config"].rsplit("-r", 1)[0] if d.get("repeat", 1) > 1 else d["config"]
|
||||
runs.setdefault(base, []).append(d)
|
||||
return runs
|
||||
|
||||
|
||||
def metrics(d):
|
||||
steps = d["steps"]
|
||||
err_ok = [s for s in steps if s["error_ratio"] <= 0.01]
|
||||
return {
|
||||
"capacity_slo": d["capacity_at_slo_rps"],
|
||||
"capacity_err1": max((s["throughput_ok_rps"] for s in err_ok), default=0),
|
||||
"peak": d["peak_ok_rps"],
|
||||
}
|
||||
|
||||
|
||||
def marker(shape, x, y, color, tip):
|
||||
t = "<title>%s</title>" % tip
|
||||
if shape == "circle":
|
||||
return '<circle cx="%.1f" cy="%.1f" r="4.5" fill="%s" stroke="%s" stroke-width="2">%s</circle>' % (x, y, color, SURFACE, t)
|
||||
if shape == "square":
|
||||
return '<rect x="%.1f" y="%.1f" width="9" height="9" rx="1.5" fill="%s" stroke="%s" stroke-width="2">%s</rect>' % (x - 4.5, y - 4.5, color, SURFACE, t)
|
||||
if shape == "triangle":
|
||||
return '<path d="M%.1f %.1fL%.1f %.1fL%.1f %.1fZ" fill="%s" stroke="%s" stroke-width="2">%s</path>' % (
|
||||
x, y - 5.5, x + 5.5, y + 4.5, x - 5.5, y + 4.5, color, SURFACE, t)
|
||||
return '<path d="M%.1f %.1fL%.1f %.1fL%.1f %.1fL%.1f %.1fZ" fill="%s" stroke="%s" stroke-width="2">%s</path>' % (
|
||||
x, y - 6, x + 6, y, x, y + 6, x - 6, y, color, SURFACE, t)
|
||||
|
||||
|
||||
def line_chart(path, title, subtitle, series, xlabel, ylabel, ymax=None, diagonal=False, refline=None):
|
||||
"""series: [(label, [(x, y, tip)])]."""
|
||||
W, H, L, R, T, B = 760, 400, 64, 190, 64, 52
|
||||
xs = [p[0] for _, pts in series for p in pts]
|
||||
ys = [p[1] for _, pts in series for p in pts]
|
||||
xmax = max(xs) * 1.05
|
||||
ymax = ymax or max(ys) * 1.12
|
||||
sx = lambda v: L + (W - L - R) * v / xmax # noqa: E731
|
||||
sy = lambda v: H - B - (H - T - B) * v / ymax # noqa: E731
|
||||
o = ['<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 %d %d" font-family="system-ui,-apple-system,Segoe UI,sans-serif">' % (W, H),
|
||||
'<rect width="100%%" height="100%%" fill="%s"/>' % SURFACE,
|
||||
'<text x="%d" y="26" font-size="16" font-weight="600" fill="%s">%s</text>' % (L, INK, title),
|
||||
'<text x="%d" y="46" font-size="12" fill="%s">%s</text>' % (L, INK2, subtitle)]
|
||||
step = 10 ** len(str(int(ymax / 5))) / 10
|
||||
step = next(s for s in (step, step * 2, step * 2.5, step * 5, step * 10) if ymax / s <= 6)
|
||||
v = 0
|
||||
while v <= ymax:
|
||||
o.append('<line x1="%d" x2="%d" y1="%.1f" y2="%.1f" stroke="%s" stroke-width="1"/>' % (L, W - R, sy(v), sy(v), GRID))
|
||||
o.append('<text x="%d" y="%.1f" font-size="11" fill="%s" text-anchor="end">%g</text>' % (L - 8, sy(v) + 4, INK2, v))
|
||||
v += step
|
||||
xstep = next(s for s in (50, 100, 200, 250, 500) if xmax / s <= 9)
|
||||
v = 0
|
||||
while v <= xmax:
|
||||
o.append('<text x="%.1f" y="%d" font-size="11" fill="%s" text-anchor="middle">%g</text>' % (sx(v), H - B + 18, INK2, v))
|
||||
v += xstep
|
||||
o.append('<line x1="%d" x2="%d" y1="%d" y2="%d" stroke="%s" stroke-width="1"/>' % (L, W - R, H - B, H - B, INK2))
|
||||
o.append('<text x="%d" y="%d" font-size="12" fill="%s" text-anchor="middle">%s</text>' % ((L + W - R) / 2, H - 12, INK2, xlabel))
|
||||
o.append('<text x="16" y="%d" font-size="12" fill="%s" transform="rotate(-90 16 %d)" text-anchor="middle">%s</text>' % (
|
||||
(T + H - B) / 2, INK2, (T + H - B) / 2, ylabel))
|
||||
if refline:
|
||||
val, text = refline
|
||||
o.append('<line x1="%d" x2="%d" y1="%.1f" y2="%.1f" stroke="%s" stroke-width="1" stroke-dasharray="4 4"/>' % (L, W - R, sy(val), sy(val), INK2))
|
||||
o.append('<text x="%d" y="%.1f" font-size="11" fill="%s" text-anchor="end">%s</text>' % (W - R - 4, sy(val) - 5, INK2, text))
|
||||
if diagonal:
|
||||
m = min(xmax, ymax)
|
||||
o.append('<line x1="%.1f" y1="%.1f" x2="%.1f" y2="%.1f" stroke="%s" stroke-width="1" stroke-dasharray="4 4"/>' % (
|
||||
sx(0), sy(0), sx(m), sy(m), INK2))
|
||||
o.append('<text x="%.1f" y="%.1f" font-size="11" fill="%s" text-anchor="end">пунктир: полезная = поданная</text>' % (sx(m * 0.92) - 8, sy(m * 0.92), INK2))
|
||||
for i, (label, pts) in enumerate(series):
|
||||
c = SERIES[i % len(SERIES)]
|
||||
pts = sorted(pts)
|
||||
o.append('<polyline fill="none" stroke="%s" stroke-width="2" stroke-linejoin="round" points="%s"/>' % (
|
||||
c, " ".join("%.1f,%.1f" % (sx(x), sy(y)) for x, y, _ in pts)))
|
||||
for x, y, tip in pts:
|
||||
o.append(marker(SHAPES[i % 4], sx(x), sy(y), c, "%s — %s" % (label, tip)))
|
||||
# легенда сверху справа
|
||||
lx = W - R + 10
|
||||
for i, (label, _) in enumerate(series):
|
||||
y = T + 4 + i * 18
|
||||
o.append(marker(SHAPES[i % 4], lx + 6, y, SERIES[i % len(SERIES)], label))
|
||||
o.append('<text x="%d" y="%.1f" font-size="11" fill="%s">%s</text>' % (lx + 16, y + 4, INK2, label))
|
||||
o.append("</svg>")
|
||||
Path(path).write_text("\n".join(o) + "\n")
|
||||
|
||||
|
||||
def bar_chart(path, title, subtitle, groups, ylabel):
|
||||
"""groups: [(label, value, tip)] — одна серия, одна ось."""
|
||||
W, H, L, R, T, B = 760, 360, 64, 24, 64, 70
|
||||
ymax = max(v for _, v, _ in groups) * 1.18
|
||||
n = len(groups)
|
||||
bw = (W - L - R) / n
|
||||
sy = lambda v: H - B - (H - T - B) * v / ymax # noqa: E731
|
||||
o = ['<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 %d %d" font-family="system-ui,-apple-system,Segoe UI,sans-serif">' % (W, H),
|
||||
'<rect width="100%%" height="100%%" fill="%s"/>' % SURFACE,
|
||||
'<text x="%d" y="26" font-size="16" font-weight="600" fill="%s">%s</text>' % (L, INK, title),
|
||||
'<text x="%d" y="46" font-size="12" fill="%s">%s</text>' % (L, INK2, subtitle)]
|
||||
step = next(s for s in (25, 50, 100, 200) if ymax / s <= 6)
|
||||
v = 0
|
||||
while v <= ymax:
|
||||
o.append('<line x1="%d" x2="%d" y1="%.1f" y2="%.1f" stroke="%s"/>' % (L, W - R, sy(v), sy(v), GRID))
|
||||
o.append('<text x="%d" y="%.1f" font-size="11" fill="%s" text-anchor="end">%g</text>' % (L - 8, sy(v) + 4, INK2, v))
|
||||
v += step
|
||||
for i, (label, val, tip) in enumerate(groups):
|
||||
x = L + i * bw + bw * 0.22
|
||||
w = bw * 0.56
|
||||
y = sy(val)
|
||||
h = H - B - y
|
||||
r = min(4, w / 2)
|
||||
o.append('<path d="M%.1f %.1fV%.1fQ%.1f %.1f %.1f %.1fH%.1fQ%.1f %.1f %.1f %.1fV%.1fZ" fill="%s"><title>%s</title></path>' % (
|
||||
x, H - B, y + r, x, y, x + r, y, x + w - r, x + w, y, x + w, y + r, H - B, SERIES[0], tip))
|
||||
o.append('<text x="%.1f" y="%.1f" font-size="12" fill="%s" text-anchor="middle">%g</text>' % (x + w / 2, y - 6, INK, val))
|
||||
for k, part in enumerate(label.split("\n")):
|
||||
o.append('<text x="%.1f" y="%.1f" font-size="11" fill="%s" text-anchor="middle">%s</text>' % (
|
||||
x + w / 2, H - B + 16 + 13 * k, INK2, part))
|
||||
o.append('<line x1="%d" x2="%d" y1="%d" y2="%d" stroke="%s"/>' % (L, W - R, H - B, H - B, INK2))
|
||||
o.append('<text x="16" y="%d" font-size="12" fill="%s" transform="rotate(-90 16 %d)" text-anchor="middle">%s</text>' % (
|
||||
(T + H - B) / 2, INK2, (T + H - B) / 2, ylabel))
|
||||
o.append("</svg>")
|
||||
Path(path).write_text("\n".join(o) + "\n")
|
||||
|
||||
|
||||
def build(out):
|
||||
out = Path(out)
|
||||
runs = load(out)
|
||||
table, summary = [], {}
|
||||
for name, ds in sorted(runs.items()):
|
||||
ms = [metrics(d) for d in ds]
|
||||
agg = {k: statistics.median(m[k] for m in ms) for k in ms[0]}
|
||||
spread = {k: [m[k] for m in ms] for k in ms[0]}
|
||||
p = ds[0]["params"]
|
||||
sat = max(ds[0]["steps"], key=lambda s: s["throughput_ok_rps"])
|
||||
res = sat["resources"]
|
||||
summary[name] = {"series": ds[0]["series"], "repeats": len(ds), "median": agg, "values": spread,
|
||||
"params": {k: p[k] for k in ("API_REPLICAS", "API_CPUS", "API_MEMORY", "API_CPUSET", "DB_POOL_MAX",
|
||||
"LB_SERVER_MAXCONN", "LB_QUEUE_TIMEOUT") if k in p},
|
||||
"at_peak": {"rate": sat["rate"], "cpu_percent": res["cpu_percent_mean"],
|
||||
"cfs_throttled": res.get("api_cfs_throttled_period_ratio"),
|
||||
"lb_queue_max": res["lb_queue_max"], "pg_connections": res["pg_connections_mean"]}}
|
||||
table.append("| %s | %s | %s×%s CPU, %s | pool %s, maxconn %s, queue %s | %s | %s | %s | %s |" % (
|
||||
name, ds[0]["series"], p["API_REPLICAS"], p["API_CPUS"], p["API_MEMORY"], p.get("DB_POOL_MAX"),
|
||||
p.get("LB_SERVER_MAXCONN"), p.get("LB_QUEUE_TIMEOUT"),
|
||||
"/".join("%g" % v for v in spread["capacity_slo"]), "/".join("%g" % v for v in spread["capacity_err1"]),
|
||||
"/".join("%g" % v for v in spread["peak"]), len(ds)))
|
||||
(out / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=1) + "\n")
|
||||
head = ("| Конфигурация | Серия | Реплики × CPU, RAM | Пул / LB | Ёмкость при SLO, rps | Макс. при ошибках ≤1 %, rps | "
|
||||
"Пик полезной, rps | Повторов |\n|---|---|---|---|---|---|---|---|")
|
||||
(out / "summary.md").write_text(head + "\n" + "\n".join(table) + "\n")
|
||||
|
||||
def curve(name, field):
|
||||
"""Медиана по повторам для каждой ступени rate (повторы могут остановиться на разных ступенях)."""
|
||||
by_rate = {}
|
||||
for d in runs[name]:
|
||||
for s in d["steps"]:
|
||||
by_rate.setdefault(s["rate"], []).append(s)
|
||||
pts = []
|
||||
for rate, ss in sorted(by_rate.items()):
|
||||
ok = statistics.median(s["throughput_ok_rps"] for s in ss)
|
||||
p99 = statistics.median(s["latency_ms"]["p99"] for s in ss)
|
||||
err = statistics.median(s["error_ratio"] for s in ss)
|
||||
pts.append((rate, ok if field == "ok" else p99, "%g req/s: полезная %.0f rps, ошибок %.1f %%, p99 %.0f мс (медиана %d прогонов)" % (
|
||||
rate, ok, 100 * err, p99, len(ss))))
|
||||
return pts
|
||||
|
||||
fixed = [("1 × 1.0 CPU", "fixed-1x1.00"), ("2 × 0.5 CPU", "fixed-2x0.50"), ("4 × 0.25 CPU", "fixed-4x0.25")]
|
||||
fixed = [f for f in fixed if f[1] in runs]
|
||||
if fixed:
|
||||
line_chart(out / "fixed-cpu-goodput.svg", "Фиксированный бюджет API (1 CPU, 512 MiB): дробление на реплики",
|
||||
"Полезная пропускная способность (2xx), медиана 3 прогонов; open-loop, смесь 70/20/10",
|
||||
[(l, curve(n, "ok")) for l, n in fixed], "Поданная нагрузка, req/s", "Полезная, rps", diagonal=True)
|
||||
line_chart(out / "fixed-cpu-p99.svg", "Фиксированный бюджет API: хвост задержки",
|
||||
"p99 успешных ответов от запланированного момента, медиана 3 прогонов",
|
||||
[(l, [(x, min(y, 2500), t) for x, y, t in curve(n, "p99")]) for l, n in fixed],
|
||||
"Поданная нагрузка, req/s", "p99, мс (обрезано на 2500)", ymax=2600, refline=(250, "SLO 250 мс"))
|
||||
adm = [("без лимита (maxconn 0)", "fixed-1x1.00"), ("maxconn 10", "admission-1x1.00-mc10"),
|
||||
("maxconn 20", "admission-1x1.00-mc20"), ("maxconn 10, queue 250 мс", "admission-1x1.00-mc10-q250")]
|
||||
adm = [a for a in adm if a[1] in runs]
|
||||
if len(adm) > 1:
|
||||
line_chart(out / "admission-goodput.svg", "maxconn на LB против перегрузки (1 × 1.0 CPU)",
|
||||
"Полезная пропускная способность; пул 10; без лимита и maxconn 10 — медиана 3 прогонов",
|
||||
[(l, curve(n, "ok")) for l, n in adm], "Поданная нагрузка, req/s", "Полезная, rps", diagonal=True)
|
||||
bars = [("growth-1x0.25", "1×0.25\n(0.25 CPU)"), ("growth-2x0.25", "2×0.25\n(0.5 CPU)"), ("growth-3x0.25", "3×0.25\n(0.75 CPU)"),
|
||||
("fixed-4x0.25", "4×0.25\n(1 CPU)"), ("fixed-1x1.00", "1×1.0\n(1 CPU)"), ("machine-2x1.00", "2×1.0\n(2 vCPU хоста)"),
|
||||
("machine-4x1.00", "4×1.0\n(2 vCPU хоста)")]
|
||||
bars = [(summary[n]["median"]["peak"], l, n) for n, l in bars if n in summary]
|
||||
if bars:
|
||||
bar_chart(out / "growth-peak.svg", "Рост ресурсов: пик полезной пропускной способности",
|
||||
"Ступени 0.25 CPU на изолированном ядре, затем вся машина (2 vCPU, общие с БД/LB/генератором)",
|
||||
[(l, round(v), "%s: пик %.0f rps" % (n, v)) for v, l, n in bars], "Пик полезной, rps")
|
||||
print((out / "summary.md").read_text())
|
||||
Reference in New Issue
Block a user