forked from mtusi2026/mtusi2026lab3
Добавить балансировку API и атомарные повторы сообщений
This commit is contained in:
@@ -0,0 +1,181 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Summarize independent repeats without treating them as one latency sample."""
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
import re
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
from statistics import mean, median
|
||||
|
||||
import matplotlib
|
||||
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt # noqa: E402
|
||||
|
||||
|
||||
def mib(value):
|
||||
number, unit = re.fullmatch(r"([0-9.]+)(\w+)", value.strip()).groups()
|
||||
return float(number) * {"B": 1 / 1048576, "KiB": 1 / 1024, "MiB": 1, "GiB": 1024}[unit]
|
||||
|
||||
|
||||
def resources(trial):
|
||||
cpu, memory = defaultdict(list), defaultdict(list)
|
||||
for sample in trial["resource_samples"]:
|
||||
per_role = defaultdict(float)
|
||||
for container in sample.get("containers", []):
|
||||
role = next(
|
||||
(r for r in ("api", "postgres", "valkey", "lb") if f"-{r}-" in container["Name"]),
|
||||
"generator",
|
||||
)
|
||||
per_role[role] += float(container["CPUPerc"].rstrip("%"))
|
||||
memory[role].append(mib(container["MemUsage"].split("/")[0]))
|
||||
for role, value in per_role.items():
|
||||
cpu[role].append(value)
|
||||
return {
|
||||
role: {"cpu_percent": mean(cpu[role]), "max_container_mib": max(memory[role])}
|
||||
for role in cpu
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("directory", type=Path)
|
||||
args = parser.parse_args()
|
||||
manifest = json.loads((args.directory / "manifest.json").read_text())
|
||||
groups = defaultdict(list)
|
||||
for path in sorted(args.directory.glob("trial-*.json")):
|
||||
d = json.loads(path.read_text())
|
||||
c = d["configuration"]
|
||||
groups[
|
||||
(c["series"], c["replicas"], c["concurrency"], c["optimized"], c.get("postgres_cpu", 1))
|
||||
].append(d)
|
||||
assert sum(map(len, groups.values())) == len(manifest["trials"])
|
||||
rows = []
|
||||
for (series, n, vus, optimized, pgcpu), trials in sorted(groups.items()):
|
||||
assert len(trials) == 3, "A series needs three complete independent repeats"
|
||||
resource = [resources(t) for t in trials]
|
||||
c = trials[0]["configuration"]
|
||||
row = {
|
||||
"series": series,
|
||||
"replicas": n,
|
||||
"concurrency": vus,
|
||||
"optimized": optimized,
|
||||
"postgres_cpu": pgcpu,
|
||||
"total_api_cpu": c["cpu_each"] * n,
|
||||
"total_api_memory_mib": c["memory_mib_each"] * n,
|
||||
"repeats": len(trials),
|
||||
"requests": sum(t["requests"] for t in trials),
|
||||
"errors": sum(t["errors"] for t in trials),
|
||||
}
|
||||
for metric in ("successful_rps", "p50_ms", "p95_ms", "p99_ms"):
|
||||
values = [t[metric] for t in trials]
|
||||
row[metric] = median(values)
|
||||
row[metric + "_min"] = min(values)
|
||||
row[metric + "_max"] = max(values)
|
||||
row["begin_per_http_request"] = median(
|
||||
sum(q["calls"] for q in t["sql_stats"] if q["query"].strip() == "BEGIN")
|
||||
/ t["raw_k6"]["metrics"]["http_reqs"]["values"]["count"]
|
||||
for t in trials
|
||||
)
|
||||
for role in ("api", "postgres", "lb", "valkey", "generator"):
|
||||
row[role + "_cpu_percent"] = median(r[role]["cpu_percent"] for r in resource)
|
||||
row[role + "_max_container_mib"] = max(r[role]["max_container_mib"] for r in resource)
|
||||
row["api_quota_utilization_percent"] = row["api_cpu_percent"] / row["total_api_cpu"]
|
||||
row["postgres_quota_utilization_percent"] = row["postgres_cpu_percent"] / pgcpu
|
||||
rows.append(row)
|
||||
(args.directory / "analysis.json").write_text(json.dumps(rows, indent=2) + "\n")
|
||||
with (args.directory / "analysis.csv").open("w", newline="") as stream:
|
||||
writer = csv.DictWriter(stream, fieldnames=list(rows[0]))
|
||||
writer.writeheader()
|
||||
writer.writerows(rows)
|
||||
lines = [
|
||||
"| Series | API | VU | PG CPU | RPS median [min; max] | p50/p95/p99 ms | "
|
||||
"Errors/requests | API CPU / PG CPU % | Max API MiB |",
|
||||
"| --- | ---: | ---: | ---: | --- | --- | --- | --- | ---: |",
|
||||
]
|
||||
for r in rows:
|
||||
lines.append(
|
||||
f"| {r['series']} | {r['replicas']} | {r['concurrency']} | {r['postgres_cpu']} | "
|
||||
f"{r['successful_rps']:.1f} [{r['successful_rps_min']:.1f}; "
|
||||
f"{r['successful_rps_max']:.1f}] | "
|
||||
f"{r['p50_ms']:.1f}/{r['p95_ms']:.1f}/{r['p99_ms']:.1f} | "
|
||||
f"{r['errors']}/{r['requests']} | "
|
||||
f"{r['api_cpu_percent']:.1f}/{r['postgres_cpu_percent']:.1f} | "
|
||||
f"{r['api_max_container_mib']:.1f} |"
|
||||
)
|
||||
(args.directory / "results.md").write_text("\n".join(lines) + "\n")
|
||||
plt.rcParams.update(
|
||||
{
|
||||
"font.size": 10,
|
||||
"figure.dpi": 140,
|
||||
"axes.grid": True,
|
||||
"grid.alpha": 0.2,
|
||||
"axes.spines.top": False,
|
||||
"axes.spines.right": False,
|
||||
}
|
||||
)
|
||||
fig, axes = plt.subplots(1, 3, figsize=(13, 4), constrained_layout=True)
|
||||
for series, label in [
|
||||
("fixed", "Fixed total: 2 CPU / 1 GiB"),
|
||||
("growing", "Per replica: 1 CPU / 512 MiB"),
|
||||
]:
|
||||
values = [r for r in rows if r["series"] == series]
|
||||
xs = [r["replicas"] for r in values]
|
||||
for ax, metric, title in zip(
|
||||
axes,
|
||||
["successful_rps", "p95_ms", "api_quota_utilization_percent"],
|
||||
["Successful requests/s", "p95 latency (ms)", "API CPU / quota (%)"],
|
||||
strict=True,
|
||||
):
|
||||
ax.plot(xs, [r[metric] for r in values], marker="o", label=label)
|
||||
if metric != "api_quota_utilization_percent":
|
||||
ax.fill_between(
|
||||
xs,
|
||||
[r[metric + "_min"] for r in values],
|
||||
[r[metric + "_max"] for r in values],
|
||||
alpha=0.12,
|
||||
)
|
||||
ax.set(title=title, xlabel="API replicas", xticks=[1, 2, 4])
|
||||
axes[0].legend(fontsize=8)
|
||||
fig.suptitle("Scaling: same 90% read / 10% write workload, 32 VUs; median of 3 repeats")
|
||||
fig.savefig(args.directory / "scaling.png")
|
||||
plt.close(fig)
|
||||
baseline = next(r for r in rows if r["series"] == "fixed" and r["replicas"] == 2)
|
||||
optimized = next(r for r in rows if r["series"] == "improvement")
|
||||
values = sorted(
|
||||
[baseline] + [r for r in rows if r["series"] == "saturation"],
|
||||
key=lambda r: r["concurrency"],
|
||||
)
|
||||
fig, axes = plt.subplots(1, 3, figsize=(13, 4), constrained_layout=True)
|
||||
xs = [r["concurrency"] for r in values]
|
||||
axes[0].plot(xs, [r["successful_rps"] for r in values], "o-", label="RPS")
|
||||
tail = axes[0].twinx()
|
||||
tail.plot(xs, [r["p95_ms"] for r in values], "s--", color="tab:orange", label="p95 ms")
|
||||
tail.set_ylabel("p95 ms", color="tab:orange")
|
||||
axes[0].set(title="Concurrency, baseline", xlabel="VUs", ylabel="Successful RPS")
|
||||
db = sorted(
|
||||
[optimized] + [r for r in rows if r["series"] == "database"],
|
||||
key=lambda r: r["postgres_cpu"],
|
||||
)
|
||||
axes[1].plot([r["postgres_cpu"] for r in db], [r["successful_rps"] for r in db], "o-")
|
||||
axes[1].set(
|
||||
title="Controlled PostgreSQL saturation", xlabel="PostgreSQL CPU quota", ylabel="RPS"
|
||||
)
|
||||
axes[2].bar(
|
||||
["Baseline", "Autocommit\nsingle SELECT"],
|
||||
[baseline["successful_rps"], optimized["successful_rps"]],
|
||||
color=["tab:blue", "tab:green"],
|
||||
)
|
||||
axes[2].set(title="Same 2 API / 2 CPU / 32 VUs", ylabel="Successful RPS")
|
||||
gain = (optimized["successful_rps"] / baseline["successful_rps"] - 1) * 100
|
||||
fig.suptitle(f"Bottlenecks and one change: median RPS gain {gain:+.1f}%")
|
||||
fig.savefig(args.directory / "bottlenecks.png")
|
||||
plt.close(fig)
|
||||
print("\n".join(lines))
|
||||
print(f"Optimization median gain: {gain:+.2f}%")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,61 @@
|
||||
import http from 'k6/http';
|
||||
import { Counter, Trend } from 'k6/metrics';
|
||||
|
||||
const fixture = JSON.parse(open('/input/session.json'));
|
||||
const requests = new Counter('measured_requests');
|
||||
const successes = new Counter('measured_successes');
|
||||
const errors = new Counter('measured_errors');
|
||||
const latency = new Trend('successful_latency', true);
|
||||
const allLatency = new Trend('all_latency', true);
|
||||
const allWrites = new Counter('all_confirmed_writes');
|
||||
const served = {};
|
||||
for (const alias of fixture.instances) served[alias] = new Counter('served_' + alias);
|
||||
const warmup = Number(__ENV.WARMUP || '5');
|
||||
const duration = Number(__ENV.DURATION || '15');
|
||||
const concurrency = Number(__ENV.CONCURRENCY || '32');
|
||||
|
||||
export const options = {
|
||||
scenarios: {
|
||||
warmup: { executor: 'constant-vus', vus: concurrency, duration: `${warmup}s`,
|
||||
exec: 'warm', gracefulStop: '1s' },
|
||||
measure: { executor: 'constant-vus', vus: concurrency, duration: `${duration}s`,
|
||||
startTime: `${warmup + 1}s`, exec: 'measure', gracefulStop: '5s' },
|
||||
},
|
||||
summaryTrendStats: ['avg', 'min', 'med', 'max', 'p(95)', 'p(99)'],
|
||||
discardResponseBodies: true,
|
||||
};
|
||||
|
||||
function request(measured) {
|
||||
const path = `http://lb:8080/api/v1/chats/${fixture.chat}/messages`;
|
||||
const key = `${fixture.run}:${measured ? 'm' : 'w'}:${__VU}:${__ITER}`;
|
||||
const params = { headers: { 'Authorization': 'Bearer ' + fixture.token,
|
||||
'Content-Type': 'application/json', 'Idempotency-Key': key },
|
||||
timeout: '10s', tags: { name: 'messages' } };
|
||||
const write = __ITER % 10 === 9;
|
||||
const cursor = __ITER % 2 === 0 ? `&cursor=${encodeURIComponent(fixture.cursor)}` : '';
|
||||
const response = write
|
||||
? http.post(path, JSON.stringify({ text: key }), params)
|
||||
: http.get(`${path}?limit=50${cursor}`, params);
|
||||
if (write && response.status === 201) allWrites.add(1);
|
||||
if (measured) {
|
||||
requests.add(1);
|
||||
allLatency.add(response.timings.duration);
|
||||
const alias = response.headers['X-Instance-Id'];
|
||||
const ok = response.status === (write ? 201 : 200) && alias in served
|
||||
&& Boolean(response.headers['X-Request-Id']);
|
||||
(ok ? successes : errors).add(1);
|
||||
if (ok) {
|
||||
latency.add(response.timings.duration);
|
||||
served[alias].add(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function warm() { request(false); }
|
||||
export function measure() { request(true); }
|
||||
export function handleSummary(data) {
|
||||
data.profile = { warmup_seconds: warmup, duration_seconds: duration,
|
||||
concurrency: concurrency, measurement_wall_seconds:
|
||||
data.state.testRunDurationMs / 1000 - warmup - 1 };
|
||||
return { '/output/k6.json': JSON.stringify(data, null, 2) };
|
||||
}
|
||||
+414
@@ -0,0 +1,414 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Repeatable scaling matrix on an isolated Compose project and fresh data."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import random
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
import psycopg
|
||||
from psycopg.conninfo import make_conninfo
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
from messenger.cursor import encode_cursor
|
||||
from messenger.repository import stamp
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PROJECT = "mtusi-lab3-research"
|
||||
K6 = "grafana/k6@sha256:3ddc8b1a33a2c3d8edc6e99b6a762ae36cba08788463458f5e6a7703e14eb77d"
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure # noqa: E402
|
||||
|
||||
|
||||
def dc(*args, env):
|
||||
return subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"compose",
|
||||
"-p",
|
||||
PROJECT,
|
||||
"--env-file",
|
||||
".env",
|
||||
"-f",
|
||||
"compose.yaml",
|
||||
"-f",
|
||||
"compose.test.yaml",
|
||||
*args,
|
||||
],
|
||||
cwd=ROOT,
|
||||
env=env,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=120,
|
||||
)
|
||||
|
||||
|
||||
def count(metrics, key):
|
||||
return metrics.get(key, {}).get("values", {}).get("count", 0)
|
||||
|
||||
|
||||
def wait_api(client, expected):
|
||||
seen, deadline = set(), time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
response = client.call("GET", "/health/ready", schema="Health")
|
||||
seen.add(response["headers"]["X-Instance-Id"])
|
||||
if set(expected) <= seen:
|
||||
return sorted(expected)
|
||||
except Failure:
|
||||
pass
|
||||
time.sleep(0.1)
|
||||
raise RuntimeError("Research APIs failed to become ready")
|
||||
|
||||
|
||||
def samples(stop, container_ids, result):
|
||||
while not stop.is_set():
|
||||
try:
|
||||
r = subprocess.run(
|
||||
["docker", "stats", "--no-stream", "--format", "{{json .}}", *container_ids],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
timeout=5,
|
||||
)
|
||||
result.append(
|
||||
{
|
||||
"at": datetime.now(UTC).isoformat(),
|
||||
"containers": [
|
||||
{k: value[k] for k in ("ID", "Name", "CPUPerc", "MemUsage", "MemPerc")}
|
||||
for value in map(json.loads, r.stdout.splitlines())
|
||||
],
|
||||
}
|
||||
)
|
||||
except OSError, ValueError, KeyError, subprocess.SubprocessError:
|
||||
result.append({"error": "resource_sample_unavailable"})
|
||||
stop.wait(0.25)
|
||||
|
||||
|
||||
def fixture(conn, client):
|
||||
# This connection only belongs to PROJECT's separate PostgreSQL container.
|
||||
conn.execute("TRUNCATE users,chats,chat_members,messages,sessions,message_requests CASCADE")
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
conn.execute(
|
||||
"INSERT INTO messages (id,chat_id,sender_id,text,created_at) "
|
||||
"SELECT md5(%s || g::text)::uuid,%s,%s,repeat('m',128),"
|
||||
"'2026-10-17T00:00:00Z'::timestamptz + g*interval '1 microsecond' "
|
||||
"FROM generate_series(1,10000) g",
|
||||
(chat["id"], chat["id"], alice["id"]),
|
||||
)
|
||||
conn.execute("VACUUM ANALYZE messages")
|
||||
row = conn.execute(
|
||||
"SELECT created_at,id FROM messages WHERE chat_id=%s "
|
||||
"ORDER BY created_at,id OFFSET 9000 LIMIT 1",
|
||||
(chat["id"],),
|
||||
).fetchone()
|
||||
cursor = encode_cursor("messages:" + chat["id"], (stamp(row["created_at"]), str(row["id"])))
|
||||
return {"token": alice["token"], "chat": chat["id"], "cursor": cursor, "run": uuid4().hex}
|
||||
|
||||
|
||||
def run_trial(config, env, output, dsn, duration, warmup):
|
||||
env = {
|
||||
**env,
|
||||
"API_REPLICAS": str(config["replicas"]),
|
||||
"POSTGRES_CPU": str(config.get("postgres_cpu", 1)),
|
||||
"API_CPU": str(config["cpu_each"]),
|
||||
"API_MEMORY": str(config["memory_mib_each"]) + "m",
|
||||
"DATABASE_READ_AUTOCOMMIT": str(int(config["optimized"])),
|
||||
}
|
||||
dc("up", "-d", "--no-build", "--wait", env=env)
|
||||
# PostgreSQL CPU changes recreate its container; never reuse that old socket.
|
||||
with psycopg.connect(dsn, autocommit=True, row_factory=dict_row) as conn:
|
||||
conn.execute("CREATE EXTENSION IF NOT EXISTS pg_stat_statements")
|
||||
measure(config, env, output, conn, duration, warmup)
|
||||
|
||||
|
||||
def measure(config, env, output, conn, duration, warmup):
|
||||
client = Client("http://127.0.0.1:18083", timeout=5)
|
||||
ids = dc("ps", "-q", "api", env=env).stdout.split()
|
||||
assert len(ids) == config["replicas"]
|
||||
aliases = []
|
||||
for container in ids:
|
||||
code = (
|
||||
"import urllib.request; r=urllib.request.urlopen("
|
||||
"'http://127.0.0.1:8080/health/live'); print(r.headers['X-Instance-Id'])"
|
||||
)
|
||||
aliases.append(
|
||||
subprocess.check_output(
|
||||
["docker", "exec", container, "python", "-c", code], text=True
|
||||
).strip()
|
||||
)
|
||||
aliases = wait_api(client, aliases)
|
||||
dc("exec", "-T", "valkey", "valkey-cli", "FLUSHDB", env=env)
|
||||
data = fixture(conn, client)
|
||||
data["instances"] = aliases
|
||||
conn.execute("SELECT pg_stat_statements_reset()")
|
||||
resources, stop, generator = [], threading.Event(), None
|
||||
with tempfile.TemporaryDirectory(prefix="lab3-load-") as temporary:
|
||||
temporary = Path(temporary)
|
||||
session = temporary / "session.json"
|
||||
session.write_text(json.dumps(data))
|
||||
os.chmod(session, 0o600)
|
||||
logs = temporary / "out"
|
||||
logs.mkdir()
|
||||
try:
|
||||
r = subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"run",
|
||||
"-d",
|
||||
"--network",
|
||||
PROJECT + "_backend",
|
||||
"--cpus",
|
||||
"2",
|
||||
"--memory",
|
||||
"384m",
|
||||
"--memory-swap",
|
||||
"384m",
|
||||
"--user",
|
||||
str(os.getuid()) + ":" + str(os.getgid()),
|
||||
"--read-only",
|
||||
"--tmpfs",
|
||||
"/tmp:rw,size=16m",
|
||||
"-v",
|
||||
str(ROOT / "research/load.js") + ":/script/load.js:ro",
|
||||
"-v",
|
||||
str(session) + ":/input/session.json:ro",
|
||||
"-v",
|
||||
str(logs) + ":/output",
|
||||
"-e",
|
||||
"K6_NO_USAGE_REPORT=true",
|
||||
"-e",
|
||||
"DURATION=" + str(duration),
|
||||
"-e",
|
||||
"WARMUP=" + str(warmup),
|
||||
"-e",
|
||||
"CONCURRENCY=" + str(config["concurrency"]),
|
||||
K6,
|
||||
"run",
|
||||
"--quiet",
|
||||
"/script/load.js",
|
||||
],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
generator = r.stdout.strip()
|
||||
ids = dc("ps", "-q", env=env).stdout.split() + [generator]
|
||||
sampler = threading.Thread(target=samples, args=(stop, ids, resources), daemon=True)
|
||||
sampler.start()
|
||||
result = subprocess.run(
|
||||
["docker", "wait", generator],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=duration + warmup + 35,
|
||||
)
|
||||
if result.stdout.strip() != "0":
|
||||
raise RuntimeError("Load generator failed")
|
||||
raw = json.loads((logs / "k6.json").read_text())
|
||||
finally:
|
||||
stop.set()
|
||||
if "sampler" in locals():
|
||||
sampler.join(timeout=6)
|
||||
if generator:
|
||||
subprocess.run(["docker", "rm", "-f", generator], capture_output=True, check=True)
|
||||
sql_stats = [
|
||||
dict(row)
|
||||
for row in conn.execute(
|
||||
"SELECT query,calls,total_exec_time,mean_exec_time,rows FROM pg_stat_statements "
|
||||
"WHERE dbid=(SELECT oid FROM pg_database WHERE datname=current_database()) "
|
||||
"ORDER BY calls DESC LIMIT 30"
|
||||
).fetchall()
|
||||
]
|
||||
metrics = raw["metrics"]
|
||||
requests, successful = count(metrics, "measured_requests"), count(metrics, "measured_successes")
|
||||
latency = metrics.get("successful_latency", {}).get("values", {})
|
||||
final_rows = conn.execute("SELECT count(*) AS n FROM messages").fetchone()["n"]
|
||||
key_rows = conn.execute("SELECT count(*) AS n FROM message_requests").fetchone()["n"]
|
||||
assert final_rows - 10000 == key_rows, "Message/result transaction invariant failed"
|
||||
assert key_rows >= count(metrics, "all_confirmed_writes"), "Confirmed writes missing"
|
||||
summary = {
|
||||
"configuration": config,
|
||||
"requests": requests,
|
||||
"successes": successful,
|
||||
"errors": count(metrics, "measured_errors"),
|
||||
"error_fraction": (requests - successful) / requests,
|
||||
"successful_rps": successful / raw["profile"]["measurement_wall_seconds"],
|
||||
"p50_ms": latency.get("med"),
|
||||
"p95_ms": latency.get("p(95)"),
|
||||
"p99_ms": latency.get("p(99)"),
|
||||
"final_messages": final_rows,
|
||||
"idempotency_results": key_rows,
|
||||
"resource_samples": resources,
|
||||
"sql_stats": sql_stats,
|
||||
"raw_k6": raw,
|
||||
}
|
||||
output.write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n")
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"trial": output.name,
|
||||
"rps": round(summary["successful_rps"], 2),
|
||||
"p95_ms": round(summary["p95_ms"], 2),
|
||||
"errors": summary["errors"],
|
||||
}
|
||||
),
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
def matrix(pilot):
|
||||
if pilot:
|
||||
return [
|
||||
{
|
||||
"series": "pilot",
|
||||
"replicas": 2,
|
||||
"cpu_each": 1,
|
||||
"memory_mib_each": 512,
|
||||
"concurrency": 32,
|
||||
"optimized": mode,
|
||||
"repeat": 1,
|
||||
}
|
||||
for mode in (False, True)
|
||||
]
|
||||
values = []
|
||||
for repeat in range(1, 4):
|
||||
for series in ("fixed", "growing"):
|
||||
for replicas in (1, 2, 4):
|
||||
values.append(
|
||||
{
|
||||
"series": series,
|
||||
"replicas": replicas,
|
||||
"cpu_each": 2 / replicas if series == "fixed" else 1,
|
||||
"memory_mib_each": 1024 // replicas if series == "fixed" else 512,
|
||||
"concurrency": 32,
|
||||
"optimized": False,
|
||||
"repeat": repeat,
|
||||
}
|
||||
)
|
||||
for vus in (8, 96):
|
||||
values.append(
|
||||
{
|
||||
"series": "saturation",
|
||||
"replicas": 2,
|
||||
"cpu_each": 1,
|
||||
"memory_mib_each": 512,
|
||||
"concurrency": vus,
|
||||
"optimized": False,
|
||||
"repeat": repeat,
|
||||
}
|
||||
)
|
||||
values.append(
|
||||
{
|
||||
"series": "improvement",
|
||||
"replicas": 2,
|
||||
"cpu_each": 1,
|
||||
"memory_mib_each": 512,
|
||||
"concurrency": 32,
|
||||
"optimized": True,
|
||||
"repeat": repeat,
|
||||
}
|
||||
)
|
||||
for quota in (0.1, 0.25):
|
||||
values.append(
|
||||
{
|
||||
"series": "database",
|
||||
"replicas": 2,
|
||||
"cpu_each": 1,
|
||||
"memory_mib_each": 512,
|
||||
"concurrency": 32,
|
||||
"optimized": True,
|
||||
"postgres_cpu": quota,
|
||||
"repeat": repeat,
|
||||
}
|
||||
)
|
||||
random.Random(2301).shuffle(values)
|
||||
return values
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--output", type=Path, default=ROOT / "evidence/scaling")
|
||||
parser.add_argument("--duration", type=int, default=15)
|
||||
parser.add_argument("--warmup", type=int, default=5)
|
||||
parser.add_argument("--pilot", action="store_true")
|
||||
args = parser.parse_args()
|
||||
if args.output.exists():
|
||||
raise SystemExit("Choose a new output directory")
|
||||
args.output.mkdir(parents=True)
|
||||
env = {
|
||||
**os.environ,
|
||||
"PUBLIC_PORT": "18083",
|
||||
"TEST_PG_PORT": "55434",
|
||||
"TEST_CACHE_PORT": "56381",
|
||||
"API_REPLICAS": "2",
|
||||
"SESSION_TTL_SECONDS": "3600",
|
||||
"NO_PROXY": "localhost,127.0.0.1",
|
||||
"no_proxy": "localhost,127.0.0.1",
|
||||
}
|
||||
# Separate project name and published DB port prevent touching the main lab3 data.
|
||||
dc("up", "-d", "--no-build", "--wait", env=env)
|
||||
password = (ROOT / "secrets/postgres_password").read_text().strip()
|
||||
dsn = make_conninfo(
|
||||
host="127.0.0.1",
|
||||
port=55434,
|
||||
dbname="messenger",
|
||||
user="messenger",
|
||||
password=password,
|
||||
options="-c timezone=UTC",
|
||||
connect_timeout=3,
|
||||
)
|
||||
metadata = {
|
||||
"started_at": datetime.now(UTC).isoformat(),
|
||||
"project": PROJECT,
|
||||
"source_sha256": {
|
||||
p.name: hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
for p in (ROOT / "src/messenger").glob("*.py")
|
||||
},
|
||||
"k6_image": K6,
|
||||
"docker_host": json.loads(
|
||||
subprocess.check_output(
|
||||
["docker", "info", "--format", '{"cpu":{{.NCPU}},"memory_bytes":{{.MemTotal}}}'],
|
||||
text=True,
|
||||
)
|
||||
),
|
||||
"api_image": subprocess.check_output(
|
||||
["docker", "image", "inspect", "mtusi-messenger:lab3", "--format", "{{.Id}}"], text=True
|
||||
).strip(),
|
||||
"client_architecture": platform.machine(),
|
||||
"trials": matrix(args.pilot),
|
||||
}
|
||||
try:
|
||||
for index, config in enumerate(metadata["trials"], 1):
|
||||
run_trial(
|
||||
config,
|
||||
env,
|
||||
args.output / f"trial-{index:02d}.json",
|
||||
dsn,
|
||||
args.duration,
|
||||
args.warmup,
|
||||
)
|
||||
assert metadata["source_sha256"] == {
|
||||
p.name: hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
for p in (ROOT / "src/messenger").glob("*.py")
|
||||
}, "Runtime source changed mid-run"
|
||||
metadata["finished_at"] = datetime.now(UTC).isoformat()
|
||||
(args.output / "manifest.json").write_text(json.dumps(metadata, indent=2) + "\n")
|
||||
print("PASS: isolated scaling matrix completed", flush=True)
|
||||
finally:
|
||||
dc("down", env=env) # Keeps this project's volume; never touches the main project.
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user