#!/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( '{}'.format(px(i), height - 18, x) ) labels.append( '{:.1f}'.format(px(i), py(y) - 8, y) ) body = """ {title} {dots} {labels} {xlabel} успешные RPS """.format( w=width, h=height, w2=width // 2, title=title, left=left, axis=height - bottom, right=width - 20, poly=polyline, dots="".join( ''.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()