Собрать стенд lab3: балансировка, идемпотентность и трек 1

This commit is contained in:
Wladislava1
2026-11-06 16:04:28 +03:00
parent 0ab3a341aa
commit d9e13a06d9
42 changed files with 3602 additions and 33 deletions
+36
View File
@@ -0,0 +1,36 @@
import json
import urllib.error
import urllib.request
BASE = "http://127.0.0.1:8080"
def call(method, path, body=None, headers=None, timeout=30, raw=None):
hdrs = {"Accept": "application/json"}
data = raw
if body is not None:
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
hdrs["Content-Type"] = "application/json"
if headers:
hdrs.update(headers)
req = urllib.request.Request(BASE + path, data=data, headers=hdrs, method=method)
try:
response = urllib.request.urlopen(req, timeout=timeout)
except urllib.error.HTTPError as error:
response = error
payload_bytes = response.read()
payload = None
if payload_bytes:
payload = json.loads(payload_bytes.decode("utf-8"))
return response.status, response.headers, payload
def bearer(token):
return {"Authorization": "Bearer " + token}
def basic(username, password):
import base64
raw = base64.b64encode((username + ":" + password).encode("utf-8")).decode("ascii")
return {"Authorization": "Basic " + raw}
+200
View File
@@ -0,0 +1,200 @@
#!/usr/bin/env python3
"""Контракт lab3 без остановки стенда: сессия, UUID, идемпотентность, две реплики."""
import json
import uuid
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from httpapi import basic, bearer, call
from sql import compose, psql
ROOT = Path(__file__).resolve().parents[1]
EVIDENCE = ROOT / "evidence" / "student_checks.txt"
LINES = []
def log(text):
print(text)
LINES.append(text)
def check(cond, message):
if not cond:
log("FAIL: " + message)
raise SystemExit(1)
def register(username, display_name, password):
status, _, payload = call(
"POST",
"/api/v1/users",
{"username": username, "display_name": display_name, "password": password},
)
check(status == 201, "register {} -> {}".format(username, status))
check("password" not in payload and "password_hash" not in payload, "password leaked")
return payload
def login(username, password):
status, headers, payload = call("POST", "/api/v1/auth/sessions", headers=basic(username, password))
check(status == 201, "login -> {}".format(status))
check(headers.get("X-Instance-Id"), "login without instance")
check(payload["token_type"] == "Bearer", "token type")
check(len(payload["token"]) >= 43, "token length")
check(username not in payload["token"], "token contains username")
return payload
def main():
suffix = uuid.uuid4().hex[:10]
alice = register("a_" + suffix, "Алиса", "long-enough-pw-1")
bob = register("b_" + suffix, "Боб", "long-enough-pw-2")
session = login("a_" + suffix, "long-enough-pw-1")
token = session["token"]
auth = bearer(token)
status, _, _ = call("GET", "/api/v1/users/me")
check(status == 401, "anon me {}".format(status))
status, headers, me = call("GET", "/api/v1/users/me", headers={**auth, "X-User-Id": bob["id"]})
check(status == 200 and me["id"] == alice["id"], "X-User-Id overrode session")
check(headers.get("X-Instance-Id"), "me without instance")
before = int(psql("SELECT count(*) FROM chats;"))
status, _, body = call(
"POST",
"/api/v1/chats",
{"title": "Дубликат UUID", "member_ids": [alice["id"], alice["id"].upper()]},
headers=auth,
)
after = int(psql("SELECT count(*) FROM chats;"))
check(status == 400 and before == after, "case-duplicate members {} chats {}->{}".format(status, before, after))
check(body.get("error", {}).get("code") == "invalid_request", "case-duplicate code")
status, _, chat = call(
"POST",
"/api/v1/chats",
{"title": "Лаба 3", "member_ids": [alice["id"], bob["id"]]},
headers=auth,
)
check(status == 201, "create chat {}".format(status))
path = "/api/v1/chats/" + chat["id"] + "/messages"
upper_path = "/api/v1/chats/" + chat["id"].upper() + "/messages"
seen = set()
for _ in range(30):
status, headers, _ = call("GET", "/api/v1/users/me", headers=auth)
check(status == 200, "spread {}".format(status))
seen.add(headers["X-Instance-Id"])
check(len(seen) >= 2, "observed instances {}".format(len(seen)))
log("instances {}".format(len(seen)))
key = "idem-" + uuid.uuid4().hex
raw_a = json.dumps({"text": "Одинаково"}, ensure_ascii=False).encode("utf-8")
raw_b = json.dumps({"attachment_ids": [], "text": "Одинаково"}, ensure_ascii=False).encode("utf-8")
status, _, first = call(
"POST",
path,
headers={**auth, "Content-Type": "application/json", "Idempotency-Key": key},
raw=raw_a,
)
check(status == 201, "first message {}".format(status))
status, _, replay = call(
"POST",
upper_path,
headers={**auth, "Content-Type": "application/json", "Idempotency-Key": key},
raw=raw_b,
)
check(status == 201 and replay == first, "replay differs")
status, _, conflict = call(
"POST",
path,
{"text": "другое тело"},
headers={**auth, "Idempotency-Key": key},
)
check(status == 409 and conflict["error"]["code"] == "conflict", "different body {}".format(status))
rows = int(psql("SELECT count(*) FROM messages WHERE id = '{}';".format(first["id"])))
check(rows == 1, "message rows {}".format(rows))
status, _, _ = call("POST", path, {"text": "без ключа"}, headers=auth)
check(status == 400, "missing key {}".format(status))
status, _, _ = call(
"POST",
path,
{"text": "плохой ключ"},
headers={**auth, "Idempotency-Key": "bad key"},
)
check(status == 400, "bad key {}".format(status))
status, _, _ = call(
"POST",
path,
{"text": " "},
headers={**auth, "Idempotency-Key": "blank-" + suffix},
)
check(status == 400, "blank text {}".format(status))
parallel_key = "par-" + uuid.uuid4().hex
text = "Параллельно " + parallel_key
def once(_n):
return call(
"POST",
path,
{"text": text},
headers={**auth, "Idempotency-Key": parallel_key},
timeout=20,
)
with ThreadPoolExecutor(max_workers=8) as pool:
results = list(pool.map(once, range(8)))
codes = sorted(item[0] for item in results)
bodies = [item[2] for item in results if item[0] == 201]
check(codes == [201] * 8, "parallel codes {}".format(codes))
check(all(item == bodies[0] for item in bodies), "parallel bodies differ")
count = int(
psql(
"SELECT count(*) FROM messages WHERE chat_id = '{}' AND body = '{}';".format(chat["id"], text)
)
)
check(count == 1, "parallel rows {}".format(count))
log("parallel same key: 8x201, 1 row")
psql(
"UPDATE idempotency_keys SET created_at = now() - interval '25 hours' WHERE idem_key = '{}';".format(key)
)
status, _, renewed = call(
"POST",
path,
{"text": "Одинаково"},
headers={**auth, "Idempotency-Key": key},
)
check(status == 201 and renewed["id"] != first["id"], "expired key did not create a new message")
log("expired key created a new message")
versions = psql("SELECT version FROM schema_migrations ORDER BY 1;")
check(versions == "001_init\n002_idempotency", "migrations [{}]".format(versions))
log("migrations " + versions.replace("\n", ","))
inspected = compose("ps", "-q", "api")
api_ids = [line.strip() for line in inspected.stdout.decode().splitlines() if line.strip()]
check(len(api_ids) >= 2, "running api replicas {}".format(len(api_ids)))
for api_id in api_ids:
info = __import__("subprocess").run(
["docker", "inspect", api_id],
stdout=__import__("subprocess").PIPE,
check=True,
)
data = json.loads(info.stdout.decode())[0]
ports = data["HostConfig"].get("PortBindings") or {}
check(not ports, "api publishes ports")
check(data["HostConfig"]["NanoCpus"] > 0, "api cpu limit missing")
check(data["HostConfig"]["Memory"] > 0, "api memory limit missing")
log("api replicas {} have cpu/memory limits and no published ports".format(len(api_ids)))
EVIDENCE.parent.mkdir(exist_ok=True)
EVIDENCE.write_text("\n".join(LINES) + "\n", encoding="utf-8")
log("PASS student checks")
EVIDENCE.write_text("\n".join(LINES) + "\n", encoding="utf-8")
if __name__ == "__main__":
main()
+219
View File
@@ -0,0 +1,219 @@
#!/usr/bin/env python3
"""Поочерёдный отказ каждой реплики и rolling restart под нагрузкой."""
import json
import subprocess
import threading
import time
import uuid
from pathlib import Path
from httpapi import basic, bearer, call
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "evidence" / "grade4.txt"
LINES = []
def log(text):
print(text)
LINES.append(text)
def save():
OUT.parent.mkdir(exist_ok=True)
OUT.write_text("\n".join(LINES) + "\n", encoding="utf-8")
def docker(*args, check=True):
proc = subprocess.run(["docker", *args], stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)
if check and proc.returncode != 0:
raise RuntimeError(proc.stderr.decode("utf-8", "replace")[-500:])
return proc
def api_ids():
proc = docker(
"ps",
"-q",
"--filter",
"label=com.docker.compose.project=mtusi-lab3",
"--filter",
"label=com.docker.compose.service=api",
)
return [line.strip() for line in proc.stdout.decode().splitlines() if line.strip()]
def hostname(container_id):
proc = docker("inspect", "-f", "{{.Config.Hostname}}", container_id)
return proc.stdout.decode().strip()
def wait_instances(token, expect, timeout=40):
auth = bearer(token)
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
seen = set()
ok = True
for _ in range(12):
try:
status, headers, _ = call("GET", "/api/v1/users/me", headers=auth, timeout=3)
except Exception:
ok = False
break
if status != 200 or not headers.get("X-Instance-Id"):
ok = False
break
seen.add(headers["X-Instance-Id"])
if ok and len(seen) >= expect:
return seen
time.sleep(0.5)
raise RuntimeError("instances did not return to {}".format(expect))
def load_loop(auth, path, seconds, bucket):
deadline = time.monotonic() + seconds
n = 0
while time.monotonic() < deadline:
key = uuid.uuid4().hex
started = time.monotonic()
try:
status, headers, _ = call(
"POST",
path,
{"text": "load-" + key},
headers={**auth, "Idempotency-Key": key},
timeout=5,
)
bucket.append(
{
"ok": status == 201,
"status": status,
"instance": headers.get("X-Instance-Id", ""),
"at": round(started, 3),
}
)
except Exception:
bucket.append({"ok": False, "status": 0, "instance": "", "at": round(started, 3)})
n += 1
def summarize(bucket, mark):
total = len(bucket)
ok = [item for item in bucket if item["ok"]]
bad = total - len(ok)
after = [item for item in ok if item["at"] >= mark] if mark is not None else ok
instances = sorted({item["instance"] for item in after if item["instance"]})
elapsed = (bucket[-1]["at"] - bucket[0]["at"]) if len(bucket) > 1 else 0
rps = round(len(ok) / elapsed, 3) if elapsed else None
return {
"requests": total,
"ok": len(ok),
"errors": bad,
"error_ratio": round(bad / total, 4) if total else None,
"successful_rps": rps,
"instances_after_mark": instances,
}
def register_and_chat():
suffix = uuid.uuid4().hex[:10]
password = "grade4-password-1"
status, _, alice = call(
"POST",
"/api/v1/users",
{"username": "g4_" + suffix, "display_name": "Нагрузка", "password": password},
)
if status != 201:
raise RuntimeError("register {}".format(status))
status, _, session = call(
"POST",
"/api/v1/auth/sessions",
headers=basic("g4_" + suffix, password),
)
if status != 201:
raise RuntimeError("login {}".format(status))
status, _, chat = call(
"POST",
"/api/v1/chats",
{"title": "Отказы", "member_ids": [alice["id"]]},
headers=bearer(session["token"]),
)
if status != 201:
raise RuntimeError("chat {}".format(status))
return session["token"], "/api/v1/chats/" + chat["id"] + "/messages"
def failover_one(token, path, container_id):
target = hostname(container_id)
auth = bearer(token)
bucket = []
thread = threading.Thread(target=load_loop, args=(auth, path, 15, bucket))
thread.start()
time.sleep(2)
stopped_at = time.monotonic()
docker("stop", "--time", "5", container_id)
thread.join()
started_ids = set(hostname(item) for item in api_ids())
summary = summarize(bucket, stopped_at)
summary["stopped"] = target
summary["stopped_still_running"] = target in started_ids
summary["served_by_stopped_after"] = target in summary["instances_after_mark"]
log("failover " + json.dumps(summary, ensure_ascii=False))
docker("start", container_id)
seen = wait_instances(token, 2)
log("restored instances {}".format(len(seen)))
return summary
def rolling(token, path):
auth = bearer(token)
before = {item: docker("inspect", "-f", "{{.State.StartedAt}}", item).stdout.decode().strip() for item in api_ids()}
bucket = []
thread = threading.Thread(target=load_loop, args=(auth, path, 28, bucket))
thread.start()
time.sleep(2)
mark = time.monotonic()
for container_id in list(before):
docker("restart", "--time", "5", container_id)
deadline = time.monotonic() + 40
while time.monotonic() < deadline:
status = docker(
"inspect",
"-f",
"{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}",
container_id,
).stdout.decode().strip()
if status == "healthy":
break
time.sleep(1)
time.sleep(2)
thread.join()
after = {item: docker("inspect", "-f", "{{.State.StartedAt}}", item).stdout.decode().strip() for item in api_ids()}
changed = sorted(item[:12] for item in before if before.get(item) != after.get(item))
summary = summarize(bucket, mark)
summary["restarted"] = len(changed)
log("rolling " + json.dumps(summary, ensure_ascii=False))
wait_instances(token, 2)
return summary
def main():
token, path = register_and_chat()
ids = api_ids()
if len(ids) < 2:
raise SystemExit("need 2 api replicas, have {}".format(len(ids)))
rolling(token, path)
# Снимок id заново: rolling не меняет container id, но список перечитываем.
for container_id in api_ids():
failover_one(token, path, container_id)
save()
print("PASS grade4")
if __name__ == "__main__":
try:
main()
except Exception as exc:
log("FAIL: " + type(exc).__name__ + " " + str(exc)[:300])
save()
raise
+465
View File
@@ -0,0 +1,465 @@
#!/usr/bin/env python3
"""Трек 1. Фиксированный бюджет API 1/2/4, затем рост CPU Postgres и размера пула.
Числа пишет в evidence/. Это closed-loop POST, не открытый генератор и не пиковая мощность стенда.
"""
import json
import os
import statistics
import subprocess
import threading
import time
import uuid
from pathlib import Path
from httpapi import basic, bearer, call
ROOT = Path(__file__).resolve().parents[1]
EVIDENCE = ROOT / "evidence"
PROJECT = "mtusi-lab3"
def docker(*args, check=True):
proc = subprocess.run(["docker", *args], stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)
if check and proc.returncode != 0:
raise RuntimeError(args[0] + " failed: " + proc.stderr.decode("utf-8", "replace")[-400:])
return proc
def compose(*args, env=None, check=True):
merged = os.environ.copy()
if env:
merged.update(env)
proc = subprocess.run(
["docker", "compose", "--env-file", ".env", *args],
cwd=ROOT,
env=merged,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=False,
)
if check and proc.returncode != 0:
raise RuntimeError(proc.stderr.decode("utf-8", "replace")[-500:])
return proc
def api_ids():
proc = docker(
"ps",
"-q",
"--filter",
"label=com.docker.compose.project=" + PROJECT,
"--filter",
"label=com.docker.compose.service=api",
)
return [line.strip() for line in proc.stdout.decode().splitlines() if line.strip()]
def service_id(service):
proc = docker(
"ps",
"-q",
"--filter",
"label=com.docker.compose.project=" + PROJECT,
"--filter",
"label=com.docker.compose.service=" + service,
)
ids = [line.strip() for line in proc.stdout.decode().splitlines() if line.strip()]
if len(ids) != 1:
raise RuntimeError("{} containers: {}".format(service, len(ids)))
return ids[0]
def apply(replicas, api_cpus, api_memory, pg_cpus, pool_max):
compose(
"up",
"-d",
"--no-deps",
"--force-recreate",
"--scale",
"api={}".format(replicas),
"api",
env={"POOL_MAX": str(pool_max)},
)
deadline = time.monotonic() + 90
while time.monotonic() < deadline:
if len(api_ids()) == replicas:
break
time.sleep(1)
else:
raise RuntimeError("scale api={} failed".format(replicas))
for container_id in api_ids():
docker(
"update",
"--cpus",
str(api_cpus),
"--memory",
api_memory,
"--memory-swap",
api_memory,
container_id,
)
docker("update", "--cpus", str(pg_cpus), service_id("postgres"))
wait_ready(replicas)
def wait_ready(replicas):
deadline = time.monotonic() + 90
while time.monotonic() < deadline:
try:
status, headers, _ = call("GET", "/health/ready", timeout=2)
if status == 200 and headers.get("X-Instance-Id"):
break
except Exception:
pass
time.sleep(1)
else:
raise RuntimeError("ready timeout")
# Дождаться, что HAProxy видит все текущие реплики.
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
seen = set()
for _ in range(max(20, replicas * 8)):
status, headers, _ = call("GET", "/health/ready", timeout=2)
if status == 200:
seen.add(headers.get("X-Instance-Id"))
if len(seen) >= replicas:
return
time.sleep(1)
raise RuntimeError("lb did not observe {} replicas".format(replicas))
def stats_sample(ids):
if not ids:
return {}
proc = docker("stats", "--no-stream", "--format", "{{.ID}} {{.CPUPerc}} {{.MemUsage}}", *ids)
out = {}
for line in proc.stdout.decode().splitlines():
parts = line.split(None, 2)
if len(parts) < 3:
continue
cpu = parts[1].replace("%", "")
try:
cpu_value = float(cpu)
except ValueError:
cpu_value = None
out[parts[0][:12]] = {"cpu_percent": cpu_value, "mem": parts[2]}
return out
def prepare_actor():
suffix = uuid.uuid4().hex[:10]
password = "track1-password-1"
status, _, user = call(
"POST",
"/api/v1/users",
{"username": "t1_" + suffix, "display_name": "Трек", "password": password},
)
if status != 201:
raise RuntimeError("register {}".format(status))
status, _, session = call("POST", "/api/v1/auth/sessions", headers=basic("t1_" + suffix, password))
if status != 201:
raise RuntimeError("login {}".format(status))
return session["token"], user["id"]
def new_chat(token, user_id):
status, _, chat = call(
"POST",
"/api/v1/chats",
{"title": "Трек " + uuid.uuid4().hex[:6], "member_ids": [user_id]},
headers=bearer(token),
)
if status != 201:
raise RuntimeError("chat {}".format(status))
return "/api/v1/chats/" + chat["id"] + "/messages"
def run_load(token, path, concurrency, seconds):
auth = bearer(token)
bucket = []
barrier = threading.Barrier(concurrency)
def worker(worker_id):
barrier.wait()
deadline = time.monotonic() + seconds
index = 0
local = []
while time.monotonic() < deadline:
key = uuid.uuid4().hex
started = time.monotonic()
try:
status, headers, _ = call(
"POST",
path,
{"text": "t-{}-{}".format(worker_id, index)},
headers={**auth, "Idempotency-Key": key},
timeout=5,
)
local.append(
{
"ok": status == 201,
"status": status,
"seconds": time.monotonic() - started,
"instance": headers.get("X-Instance-Id", ""),
}
)
except Exception:
local.append({"ok": False, "status": 0, "seconds": time.monotonic() - started, "instance": ""})
index += 1
bucket.extend(local)
started = time.monotonic()
threads = [threading.Thread(target=worker, args=(i,)) for i in range(concurrency)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
elapsed = time.monotonic() - started
ok = [item for item in bucket if item["ok"]]
lat = sorted(item["seconds"] for item in ok)
def pct(p):
if not lat:
return None
index = min(len(lat) - 1, max(0, int(round(p * (len(lat) - 1)))))
return round(lat[index] * 1000, 1)
instances = {}
for item in ok:
instances[item["instance"]] = instances.get(item["instance"], 0) + 1
codes = {}
for item in bucket:
codes[str(item["status"])] = codes.get(str(item["status"]), 0) + 1
return {
"elapsed_seconds": round(elapsed, 3),
"ok": len(ok),
"errors": len(bucket) - len(ok),
"error_ratio": round((len(bucket) - len(ok)) / len(bucket), 4) if bucket else None,
"successful_rps": round(len(ok) / elapsed, 3) if elapsed else None,
"p50_ms": pct(0.50),
"p95_ms": pct(0.95),
"instances": instances,
"status_codes": codes,
}
def sample_during(ids, seconds):
samples = []
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
samples.append(stats_sample(ids))
time.sleep(2)
return samples
def average_cpu(samples, prefix_ids):
wanted = {item[:12] for item in prefix_ids}
values = []
for sample in samples:
for key, payload in sample.items():
if key in wanted and payload["cpu_percent"] is not None:
values.append(payload["cpu_percent"])
if not values:
return None
return round(statistics.fmean(values), 2)
def scenario_row(name, spec, repeat, result, api_cpu, pg_cpu):
return {
"name": name,
"repeat": repeat,
"api_replicas": spec["replicas"],
"api_cpus_each": spec["api_cpus"],
"api_memory_each": spec["api_memory"],
"postgres_cpus": spec["pg_cpus"],
"pool_max": spec["pool"],
"concurrency": spec["concurrency"],
"api_cpu_percent_avg": api_cpu,
"postgres_cpu_percent_avg": pg_cpu,
**result,
}
def measure(name, spec, token, user_id):
apply(spec["replicas"], spec["api_cpus"], spec["api_memory"], spec["pg_cpus"], spec["pool"])
rows = []
for repeat in (1, 2):
path = new_chat(token, user_id)
warmup = run_load(token, path, spec["concurrency"], 4)
ids = api_ids() + [service_id("postgres"), service_id("lb")]
holder = {}
def collect():
holder["samples"] = sample_during(ids, 12)
thread = threading.Thread(target=collect)
thread.start()
result = run_load(token, path, spec["concurrency"], 12)
thread.join()
samples = holder.get("samples", [])
row = scenario_row(
name,
spec,
repeat,
result,
average_cpu(samples, api_ids()),
average_cpu(samples, [service_id("postgres")]),
)
row["warmup_rps"] = warmup["successful_rps"]
rows.append(row)
print(json.dumps({k: row[k] for k in ("name", "repeat", "successful_rps", "error_ratio", "p95_ms", "postgres_cpu_percent_avg")}, ensure_ascii=False))
return rows
def svg(points, title, xlabel, path):
width, height, left, bottom = 760, 420, 70, 50
xs = [item[0] for item in points]
ys = [item[1] for item in points]
max_y = max(ys) if ys else 1
max_y = max_y * 1.15 if max_y else 1
def px(index):
return left + (width - left - 30) * (index / max(1, len(points) - 1))
def py(value):
return 30 + (height - bottom - 30) * (1 - value / max_y)
polyline = " ".join("{:.1f},{:.1f}".format(px(i), py(y)) for i, y in enumerate(ys))
labels = []
for i, (x, y) in enumerate(points):
labels.append(
'<text x="{:.1f}" y="{}" text-anchor="middle" font-size="13">{}</text>'.format(px(i), height - 18, x)
)
labels.append(
'<text x="{:.1f}" y="{:.1f}" text-anchor="middle" font-size="12">{:.1f}</text>'.format(px(i), py(y) - 8, y)
)
body = """<svg xmlns="http://www.w3.org/2000/svg" width="{w}" height="{h}">
<rect width="100%" height="100%" fill="white"/>
<text x="{w2}" y="22" text-anchor="middle" font-size="16">{title}</text>
<line x1="{left}" y1="30" x2="{left}" y2="{axis}" stroke="#222"/>
<line x1="{left}" y1="{axis}" x2="{right}" y2="{axis}" stroke="#222"/>
<polyline fill="none" stroke="#1f4e79" stroke-width="2" points="{poly}"/>
{dots}
{labels}
<text x="{w2}" y="{hbot}" text-anchor="middle" font-size="13">{xlabel}</text>
<text x="18" y="220" font-size="13" transform="rotate(-90 18 220)">успешные RPS</text>
</svg>
""".format(
w=width,
h=height,
w2=width // 2,
title=title,
left=left,
axis=height - bottom,
right=width - 20,
poly=polyline,
dots="".join(
'<circle cx="{:.1f}" cy="{:.1f}" r="4" fill="#1f4e79"/>'.format(px(i), py(y)) for i, y in enumerate(ys)
),
labels="\n".join(labels),
hbot=height - 2,
xlabel=xlabel,
)
path.write_text(body, encoding="utf-8")
def mean_rps(rows, name):
values = [row["successful_rps"] for row in rows if row["name"] == name and row["successful_rps"] is not None]
if not values:
return None
return round(statistics.fmean(values), 3)
def restore():
compose(
"up",
"-d",
"--no-deps",
"--force-recreate",
"--scale",
"api=2",
"api",
env={"POOL_MAX": "10"},
)
for container_id in api_ids():
docker("update", "--cpus", "0.50", "--memory", "256m", "--memory-swap", "256m", container_id)
docker("update", "--cpus", "1.00", service_id("postgres"))
wait_ready(2)
def main():
fixed = {"api_cpus": None, "api_memory": None, "pg_cpus": 1.0, "pool": 10, "concurrency": 8}
# Суммарно 1.0 CPU и 1024 MiB на все API.
budgets = {
"fixed-1": {**fixed, "replicas": 1, "api_cpus": 1.0, "api_memory": "1024m"},
"fixed-2": {**fixed, "replicas": 2, "api_cpus": 0.5, "api_memory": "512m"},
"fixed-4": {**fixed, "replicas": 4, "api_cpus": 0.25, "api_memory": "256m"},
}
growth = {
"pg-0.30": {"replicas": 2, "api_cpus": 0.5, "api_memory": "512m", "pg_cpus": 0.30, "pool": 10, "concurrency": 8},
"pg-0.60": {"replicas": 2, "api_cpus": 0.5, "api_memory": "512m", "pg_cpus": 0.60, "pool": 10, "concurrency": 8},
"pg-1.20": {"replicas": 2, "api_cpus": 0.5, "api_memory": "512m", "pg_cpus": 1.20, "pool": 10, "concurrency": 8},
}
pools = {
"pool-2": {"replicas": 2, "api_cpus": 0.5, "api_memory": "512m", "pg_cpus": 1.0, "pool": 2, "concurrency": 16},
"pool-10": {"replicas": 2, "api_cpus": 0.5, "api_memory": "512m", "pg_cpus": 1.0, "pool": 10, "concurrency": 16},
}
token, user_id = prepare_actor()
# Прогрев планировщика и кэша Postgres вне таблицы результатов.
apply(2, 0.5, "512m", 1.0, 10)
run_load(token, new_chat(token, user_id), 4, 8)
rows = []
try:
for name, spec in {**budgets, **growth, **pools}.items():
rows.extend(measure(name, spec, token, user_id))
finally:
EVIDENCE.mkdir(exist_ok=True)
(EVIDENCE / "track1_runs.json").write_text(json.dumps(rows, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
header = [
"name",
"repeat",
"api_replicas",
"api_cpus_each",
"postgres_cpus",
"pool_max",
"concurrency",
"successful_rps",
"error_ratio",
"p50_ms",
"p95_ms",
"api_cpu_percent_avg",
"postgres_cpu_percent_avg",
]
lines = [",".join(header)]
for row in rows:
lines.append(",".join("" if row.get(key) is None else str(row.get(key)) for key in header))
(EVIDENCE / "track1_runs.csv").write_text("\n".join(lines) + "\n", encoding="utf-8")
restore()
summary = {
"method": "closed-loop POST messages, unique Idempotency-Key, warmup 4s discarded, measure 12s, 2 repeats, fresh chat per repeat",
"fixed_total_api_cpu": 1.0,
"fixed_total_api_memory": "1024m",
"mean_successful_rps": {name: mean_rps(rows, name) for name in list(budgets) + list(growth) + list(pools)},
}
(EVIDENCE / "track1_summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
def points(names):
rows = []
for name in names:
value = summary["mean_successful_rps"].get(name)
if value is None:
continue
rows.append((name.split("-", 1)[1], value))
return rows
if points(budgets):
svg(points(budgets), "Фиксированный бюджет API: 1 / 2 / 4 реплики", "число реплик при суммарно 1.0 CPU и 1024 MiB", EVIDENCE / "track1_replicas.svg")
if points(growth):
svg(points(growth), "Рост CPU Postgres при 2 API", "лимит CPU Postgres", EVIDENCE / "track1_postgres.svg")
if points(pools):
svg(points(pools), "Размер пула соединений при concurrency 16", "POOL_MAX на реплику", EVIDENCE / "track1_pool.svg")
print(json.dumps(summary["mean_successful_rps"], ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env python3
"""Дополнительная серия трека 1: много CPU у API, узкий Postgres, затем больше CPU у Postgres."""
import json
from pathlib import Path
import run_track1 as track
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "evidence" / "track1_db.json"
SPECS = {
"api2-pg0.35": {
"replicas": 2,
"api_cpus": 1.0,
"api_memory": "512m",
"pg_cpus": 0.35,
"pool": 10,
"concurrency": 16,
},
"api4-pg0.35": {
"replicas": 4,
"api_cpus": 1.0,
"api_memory": "512m",
"pg_cpus": 0.35,
"pool": 10,
"concurrency": 16,
},
"api2-pg1.50": {
"replicas": 2,
"api_cpus": 1.0,
"api_memory": "512m",
"pg_cpus": 1.5,
"pool": 10,
"concurrency": 16,
},
}
def main():
token, user_id = track.prepare_actor()
rows = []
try:
for name, spec in SPECS.items():
rows.extend(track.measure(name, spec, token, user_id))
finally:
OUT.write_text(json.dumps(rows, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
track.restore()
summary = {name: track.mean_rps(rows, name) for name in SPECS}
print(json.dumps(summary, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
+41
View File
@@ -0,0 +1,41 @@
import subprocess
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def compose(*args, check=True, input_bytes=None, timeout=180):
proc = subprocess.run(
["docker", "compose", "--env-file", ".env", *args],
cwd=ROOT,
input=input_bytes,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
timeout=timeout,
check=False,
)
if check and proc.returncode != 0:
err = proc.stderr.decode("utf-8", "replace")[-800:]
raise RuntimeError(err or "docker compose failed")
return proc
def psql(sql, timeout=180):
proc = compose(
"exec",
"-T",
"postgres",
"psql",
"-U",
"messenger",
"-d",
"messenger",
"-v",
"ON_ERROR_STOP=1",
"-q",
"-t",
"-A",
input_bytes=sql.encode("utf-8"),
timeout=timeout,
)
return proc.stdout.decode("utf-8").strip()