365 lines
19 KiB
Python
365 lines
19 KiB
Python
#!/usr/bin/env python3
|
|
"""Repeatable, disposable Compose experiment for lab 3 scaling research."""
|
|
|
|
import argparse
|
|
import csv
|
|
import io
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import platform
|
|
import socket
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import threading
|
|
import time
|
|
from datetime import datetime, timezone
|
|
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
|
|
from uuid import UUID, uuid4
|
|
|
|
ROOT = Path(__file__).resolve().parents[3]
|
|
sys.path.insert(0, str(ROOT / "tests"))
|
|
from client import Client # noqa: E402
|
|
|
|
|
|
def utc_now():
|
|
return datetime.now(timezone.utc).isoformat(timespec="milliseconds")
|
|
|
|
|
|
def command(argv, *, timeout=180, allow_failure=False, log=None):
|
|
result = subprocess.run(argv, cwd=ROOT, capture_output=True, text=True, timeout=timeout)
|
|
if log is not None:
|
|
log.write_text(result.stdout + result.stderr)
|
|
if result.returncode and not allow_failure:
|
|
detail = (result.stderr or result.stdout)[-1200:]
|
|
raise RuntimeError("command failed (%s): %s" % (result.returncode, detail))
|
|
return result.stdout
|
|
|
|
|
|
def free_port():
|
|
with socket.socket() as listener:
|
|
listener.bind(("127.0.0.1", 0))
|
|
return listener.getsockname()[1]
|
|
|
|
|
|
def write_override(path, *, lb_port, replicas, total_cpus, total_memory_mib, postgres_cpus,
|
|
database_url_file=None):
|
|
if replicas not in (1, 2, 4) or total_cpus <= 0 or total_memory_mib < 256:
|
|
raise ValueError("invalid replica count or API budget")
|
|
if total_memory_mib % replicas:
|
|
raise ValueError("API memory budget must divide evenly between replicas")
|
|
per_cpu = total_cpus / replicas
|
|
per_memory = total_memory_mib // replicas
|
|
source = (
|
|
"services:\n"
|
|
" api:\n"
|
|
" scale: %d\n"
|
|
" cpus: \"%.3f\"\n"
|
|
" mem_limit: %dm\n"
|
|
" secrets: !override\n"
|
|
" - source: database_url_api\n"
|
|
" target: database_url\n"
|
|
" lb:\n"
|
|
" ports: !override\n"
|
|
" - \"127.0.0.1:%d:8080\"\n"
|
|
" postgres:\n"
|
|
" cpus: \"%.3f\"\n"
|
|
" ports: !reset []\n"
|
|
" command: [\"postgres\", \"-c\", \"shared_preload_libraries=pg_stat_statements\", \"-c\", \"track_io_timing=on\", \"-c\", \"track_wal_io_timing=on\"]\n"
|
|
% (replicas, per_cpu, per_memory, lb_port, postgres_cpus)
|
|
)
|
|
if database_url_file:
|
|
source += "secrets:\n database_url_api:\n file: %s\n" % json.dumps(str(database_url_file))
|
|
path.write_text(source)
|
|
|
|
|
|
def write_database_url(path, pool_max_conns):
|
|
original = (ROOT / "secrets" / "database_url").read_text().strip()
|
|
if pool_max_conns is None:
|
|
path.write_text(original + "\n")
|
|
else:
|
|
if not isinstance(pool_max_conns, int) or pool_max_conns <= 0:
|
|
raise ValueError("pool_max_conns must be positive")
|
|
parsed = urlsplit(original)
|
|
query = dict(parse_qsl(parsed.query, keep_blank_values=True))
|
|
query["pool_max_conns"] = str(pool_max_conns)
|
|
path.write_text(urlunsplit(parsed._replace(query=urlencode(query))) + "\n")
|
|
os.chmod(path, 0o600)
|
|
|
|
|
|
def psql(compose, sql, *, timeout=60):
|
|
output = command(compose + ["exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-v", "ON_ERROR_STOP=1", "-Atc", sql], timeout=timeout)
|
|
return output.strip()
|
|
|
|
|
|
def message_count(compose):
|
|
return int(psql(compose, "SELECT count(*) FROM messages"))
|
|
|
|
|
|
def reset_dataset(compose, chat_id, user_id, seed_count):
|
|
chat_id, user_id = str(UUID(chat_id)), str(UUID(user_id))
|
|
psql(compose, "TRUNCATE message_idempotency, messages")
|
|
if seed_count:
|
|
sql = ("INSERT INTO messages (chat_id, sender_id, text, created_at) "
|
|
"SELECT '%s'::uuid, '%s'::uuid, 'seed-' || g, now() - interval '1 day' "
|
|
"FROM generate_series(1, %d) AS g" % (chat_id, user_id, seed_count))
|
|
psql(compose, sql, timeout=180)
|
|
psql(compose, "ANALYZE messages; ANALYZE message_idempotency")
|
|
actual = message_count(compose)
|
|
if actual != seed_count:
|
|
raise RuntimeError("dataset reset produced %d messages, expected %d" % (actual, seed_count))
|
|
|
|
|
|
def api_ids(compose):
|
|
return command(compose + ["ps", "-q", "api"]).splitlines()
|
|
|
|
|
|
def api_limits(compose):
|
|
identifiers = api_ids(compose)
|
|
output = command(["docker", "inspect", "--format",
|
|
"{{.Id}} {{.HostConfig.NanoCpus}} {{.HostConfig.Memory}}"] + identifiers,
|
|
timeout=15)
|
|
return [dict(zip(("container_id", "nano_cpus", "memory_bytes"), line.split()))
|
|
for line in output.splitlines()]
|
|
|
|
|
|
def wait_instances(base_url, expected, seconds=60):
|
|
client = Client(base_url, timeout=3)
|
|
found = set()
|
|
deadline = time.monotonic() + seconds
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
response = client.call("GET", "/health/ready", schema="Health")
|
|
found.add(response["headers"].get("X-Instance-Id"))
|
|
if len(found) == expected:
|
|
return sorted(found)
|
|
except Exception:
|
|
pass
|
|
time.sleep(.15)
|
|
raise RuntimeError("LB observed %d of %d API instances" % (len(found), expected))
|
|
|
|
|
|
def sample_loop(stop, compose, path):
|
|
ids = []
|
|
for service in ("api", "lb", "postgres", "redis"):
|
|
ids += command(compose + ["ps", "-q", service], timeout=10).splitlines()
|
|
lb = command(compose + ["ps", "-q", "lb"], timeout=10).strip()
|
|
with path.open("w") as output:
|
|
while not stop.is_set():
|
|
sample = {"at_utc": utc_now()}
|
|
try:
|
|
raw = command(["docker", "stats", "--no-stream", "--format", "{{json .}}"] + ids, timeout=15)
|
|
sample["docker_stats"] = [json.loads(line) for line in raw.splitlines() if line.strip()]
|
|
sample["docker_at_utc"] = utc_now()
|
|
except Exception as exc:
|
|
sample["docker_error"] = type(exc).__name__
|
|
try:
|
|
raw = psql(compose, "SELECT json_build_object('connections', count(*), 'active', count(*) FILTER (WHERE state='active'), 'lock_wait', count(*) FILTER (WHERE wait_event_type='Lock'), 'io_wait', count(*) FILTER (WHERE wait_event_type='IO')) FROM pg_stat_activity WHERE datname=current_database()", timeout=10)
|
|
sample["postgres_activity"] = json.loads(raw)
|
|
sample["postgres_at_utc"] = utc_now()
|
|
except Exception as exc:
|
|
sample["postgres_error"] = type(exc).__name__
|
|
try:
|
|
raw = command(["docker", "exec", lb, "sh", "-c", "printf 'show stat\\n' | socat - TCP4:127.0.0.1:9999"], timeout=10)
|
|
rows = list(csv.DictReader(io.StringIO(raw.lstrip("# "))))
|
|
sample["haproxy"] = [
|
|
{key: row.get(key) for key in ("pxname", "svname", "status", "scur", "qcur", "stot", "ereq", "econ", "eresp", "wretr")}
|
|
for row in rows if row.get("pxname") == "api_replicas"
|
|
]
|
|
sample["haproxy_at_utc"] = utc_now()
|
|
except Exception as exc:
|
|
sample["haproxy_error"] = type(exc).__name__
|
|
output.write(json.dumps(sample, ensure_ascii=False) + "\n")
|
|
output.flush()
|
|
stop.wait(.5)
|
|
|
|
|
|
def diagnostic_snapshot(compose):
|
|
snapshot = {"at_utc": utc_now(), "cgroups": {}}
|
|
snapshot["durability"] = json.loads(psql(compose, "SELECT json_build_object('fsync',current_setting('fsync'),'synchronous_commit',current_setting('synchronous_commit'),'commit_delay',current_setting('commit_delay'),'commit_siblings',current_setting('commit_siblings'))"))
|
|
for service in ("api", "postgres", "lb", "redis"):
|
|
for identifier in command(compose + ["ps", "-q", service]).splitlines():
|
|
raw = command(["docker", "exec", identifier, "cat", "/sys/fs/cgroup/cpu.stat"], timeout=10)
|
|
snapshot["cgroups"][identifier] = {"service": service,
|
|
**{line.split()[0]: int(line.split()[1]) for line in raw.splitlines()}}
|
|
snapshot["wal_io"] = json.loads(psql(compose, "SELECT coalesce(json_agg(row_to_json(i)), '[]'::json) FROM pg_stat_io i WHERE object='wal'"))
|
|
snapshot["wal"] = json.loads(psql(compose, "SELECT row_to_json(w) FROM pg_stat_wal w"))
|
|
return snapshot
|
|
|
|
|
|
def pg_stat_statements(compose):
|
|
sql = ("SELECT coalesce(json_agg(row_to_json(q)), '[]'::json) FROM "
|
|
"(SELECT queryid, calls, round(total_exec_time::numeric,3) AS total_exec_ms, "
|
|
"round(mean_exec_time::numeric,3) AS mean_exec_ms, rows, shared_blks_hit, "
|
|
"shared_blks_read, temp_blks_written, left(query,160) AS query "
|
|
"FROM pg_stat_statements WHERE dbid=(SELECT oid FROM pg_database WHERE datname=current_database()) "
|
|
"ORDER BY total_exec_time DESC LIMIT 15) AS q")
|
|
return json.loads(psql(compose, sql))
|
|
|
|
|
|
def run_load(binary, base_url, auth_file, rate, duration, max_inflight, output_path):
|
|
raw = command([str(binary), "-base-url", base_url, "-auth-file", str(auth_file),
|
|
"-rate", str(rate), "-duration", str(duration) + "s",
|
|
"-max-inflight", str(max_inflight), "-timeout", "5s"], timeout=duration + 40)
|
|
result = json.loads(raw)
|
|
output_path.write_text(json.dumps(result, indent=2, ensure_ascii=False) + "\n")
|
|
return result
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--plan", type=Path, required=True)
|
|
parser.add_argument("--output", type=Path, required=True)
|
|
args = parser.parse_args()
|
|
plan = json.loads(args.plan.read_text())
|
|
runs = plan["runs"]
|
|
if not runs or not all(run["replicas"] in (1, 2, 4) for run in runs):
|
|
raise ValueError("plan must have runs with 1, 2, or 4 replicas")
|
|
output_dir = args.output.resolve()
|
|
if output_dir.exists() and any(output_dir.iterdir()):
|
|
raise FileExistsError("output directory must be empty")
|
|
output_dir.mkdir(parents=True, exist_ok=True)
|
|
(output_dir / "plan.json").write_text(json.dumps(plan, indent=2, ensure_ascii=False) + "\n")
|
|
project = "lab3-grade5-" + uuid4().hex[:10]
|
|
lb_port = free_port()
|
|
base_url = "http://127.0.0.1:%d" % lb_port
|
|
summary = {"project": project, "base_url": base_url, "started_at_utc": utc_now(),
|
|
"host": {"platform": platform.platform(), "machine": platform.machine()},
|
|
"runs": [], "cleanup": "not_started"}
|
|
(output_dir / "summary.json").write_text(json.dumps(summary, indent=2, ensure_ascii=False) + "\n")
|
|
with tempfile.TemporaryDirectory(prefix="lab3-grade5-") as temporary:
|
|
temporary = Path(temporary)
|
|
override = temporary / "override.yaml"
|
|
auth_file = temporary / "auth.json"
|
|
database_url_file = temporary / "database_url"
|
|
binary = temporary / "grade5-load"
|
|
first = runs[0]
|
|
write_database_url(database_url_file, first.get("pool_max_conns"))
|
|
write_override(override, lb_port=lb_port, replicas=first["replicas"],
|
|
total_cpus=first["api_total_cpus"], total_memory_mib=first["api_total_memory_mib"],
|
|
postgres_cpus=first.get("postgres_cpus", 2), database_url_file=database_url_file)
|
|
compose = ["docker", "compose", "-p", project, "--env-file", ".env",
|
|
"-f", "compose.yaml", "-f", str(override)]
|
|
try:
|
|
command(["go", "build", "-o", str(binary), "student-tests/lab3/grade5/load.go"], timeout=180,
|
|
log=output_dir / "go-build.log")
|
|
command(compose + ["config", "--quiet"], timeout=30)
|
|
print("Building and starting disposable project", project, flush=True)
|
|
command(compose + ["up", "-d", "--build"], timeout=900, log=output_dir / "compose-up.log")
|
|
wait_instances(base_url, first["replicas"])
|
|
psql(compose, "CREATE EXTENSION IF NOT EXISTS pg_stat_statements")
|
|
client = Client(base_url)
|
|
alice, _, _, chat = client.bootstrap()
|
|
auth_file.write_text(json.dumps({"token": alice["token"], "chat_id": chat["id"]}))
|
|
os.chmod(auth_file, 0o600)
|
|
summary["chat_id"] = chat["id"]
|
|
summary["seed_messages"] = plan["seed_messages"]
|
|
summary["docker_server"] = command(["docker", "version", "--format", "{{.Server.Version}}"], timeout=15).strip()
|
|
summary["compose_version"] = command(["docker", "compose", "version", "--short"], timeout=15).strip()
|
|
summary["docker_resources"] = command(["docker", "info", "--format", "{{.NCPU}} CPUs, {{.MemTotal}} bytes RAM"], timeout=15).strip()
|
|
previous_postgres_cpus = first.get("postgres_cpus", 2)
|
|
for index, run in enumerate(runs, 1):
|
|
name = run["name"]
|
|
if not name.replace("-", "").replace("_", "").isalnum():
|
|
raise ValueError("unsafe run name")
|
|
run_dir = output_dir / ("%02d-%s" % (index, name))
|
|
run_dir.mkdir()
|
|
write_database_url(database_url_file, run.get("pool_max_conns"))
|
|
write_override(override, lb_port=lb_port, replicas=run["replicas"],
|
|
total_cpus=run["api_total_cpus"], total_memory_mib=run["api_total_memory_mib"],
|
|
postgres_cpus=run.get("postgres_cpus", 2), database_url_file=database_url_file)
|
|
command(compose + ["config", "--quiet"], timeout=30)
|
|
print("Run %d/%d: %s" % (index, len(runs), name), flush=True)
|
|
delay = run.get("commit_delay_us", 0)
|
|
if not isinstance(delay, int) or not 0 <= delay <= 100000:
|
|
raise ValueError("invalid commit_delay_us")
|
|
psql(compose, "ALTER SYSTEM SET commit_delay='%d'" % delay)
|
|
psql(compose, "SELECT pg_reload_conf()")
|
|
if run.get("postgres_cpus", 2) != previous_postgres_cpus:
|
|
command(compose + ["up", "-d", "--no-deps", "--no-build", "--force-recreate", "postgres"],
|
|
timeout=120, log=run_dir / "compose-postgres.log")
|
|
deadline = time.monotonic() + 60
|
|
while True:
|
|
try:
|
|
if psql(compose, "SELECT 1", timeout=5) == "1":
|
|
break
|
|
except Exception:
|
|
pass
|
|
if time.monotonic() > deadline:
|
|
raise RuntimeError("PostgreSQL did not become ready after budget change")
|
|
time.sleep(1)
|
|
previous_postgres_cpus = run.get("postgres_cpus", 2)
|
|
command(compose + ["up", "-d", "--no-deps", "--no-build", "--force-recreate", "--scale", "api=%d" % run["replicas"], "api"],
|
|
timeout=180, log=run_dir / "compose-scale.log")
|
|
instances = wait_instances(base_url, run["replicas"])
|
|
warmup = plan.get("warmup_seconds", 3)
|
|
reset_dataset(compose, chat["id"], alice["id"], plan["seed_messages"])
|
|
if warmup:
|
|
warmup_rate = plan.get("warmup_rate", min(200, run["rate"]))
|
|
if warmup_rate == "target":
|
|
warmup_rate = run["rate"]
|
|
run_load(binary, base_url, auth_file, warmup_rate, warmup,
|
|
plan.get("max_inflight", 1024),
|
|
run_dir / "warmup.json")
|
|
reset_dataset(compose, chat["id"], alice["id"], plan["seed_messages"])
|
|
if plan.get("settle_seconds", 0):
|
|
psql(compose, "CHECKPOINT")
|
|
time.sleep(plan["settle_seconds"])
|
|
psql(compose, "SELECT pg_stat_statements_reset()")
|
|
before = message_count(compose)
|
|
(run_dir / "diagnostics-before.json").write_text(json.dumps(diagnostic_snapshot(compose), indent=2) + "\n")
|
|
stop = threading.Event()
|
|
sampler = threading.Thread(target=sample_loop, args=(stop, compose, run_dir / "samples.jsonl"))
|
|
sampler.start()
|
|
try:
|
|
load = run_load(binary, base_url, auth_file, run["rate"], run["duration_seconds"],
|
|
run.get("max_inflight", plan.get("max_inflight", 1024)),
|
|
run_dir / "load.json")
|
|
finally:
|
|
stop.set()
|
|
sampler.join(timeout=30)
|
|
after = message_count(compose)
|
|
(run_dir / "diagnostics-after.json").write_text(json.dumps(diagnostic_snapshot(compose), indent=2) + "\n")
|
|
sql_stats = pg_stat_statements(compose)
|
|
(run_dir / "postgres-statements.json").write_text(json.dumps(sql_stats, indent=2, ensure_ascii=False) + "\n")
|
|
item = {"name": name, "phase": run.get("phase", "unspecified"),
|
|
"replicas": run["replicas"], "api_total_cpus": run["api_total_cpus"],
|
|
"api_total_memory_mib": run["api_total_memory_mib"],
|
|
"postgres_cpus": run.get("postgres_cpus", 2), "rate": run["rate"],
|
|
"pool_max_conns_per_replica": run.get("pool_max_conns", "pgx_default"),
|
|
"commit_delay_us": delay,
|
|
"duration_seconds": run["duration_seconds"], "instances": instances,
|
|
"api_limits": api_limits(compose),
|
|
"messages_before": before, "messages_after": after,
|
|
"messages_added": after-before, "load": load}
|
|
summary["runs"].append(item)
|
|
(output_dir / "summary.json").write_text(json.dumps(summary, indent=2, ensure_ascii=False) + "\n")
|
|
print(" success=%d/%d, rps=%.1f, p99=%.1f ms" %
|
|
(load["successful_requests"], load["scheduled_requests"],
|
|
load["successful_rps_window"], load["success_latency_ms"]["p99"]), flush=True)
|
|
except Exception as exc:
|
|
summary["error"] = str(exc)
|
|
raise
|
|
finally:
|
|
print("Cleaning disposable project", project, flush=True)
|
|
try:
|
|
command(compose + ["down", "-v", "--remove-orphans"], timeout=180,
|
|
log=output_dir / "cleanup.log")
|
|
remaining_containers = command(["docker", "ps", "-aq", "--filter",
|
|
"label=com.docker.compose.project=" + project], timeout=15).splitlines()
|
|
remaining_volumes = command(["docker", "volume", "ls", "-q", "--filter",
|
|
"label=com.docker.compose.project=" + project], timeout=15).splitlines()
|
|
after = {"project": project, "containers": remaining_containers,
|
|
"volumes": remaining_volumes, "at_utc": utc_now()}
|
|
(output_dir / "environment-after.json").write_text(json.dumps(after, indent=2) + "\n")
|
|
summary["cleanup"] = "PASS" if not remaining_containers and not remaining_volumes else "FAIL: resources remain"
|
|
except Exception as exc:
|
|
summary["cleanup"] = "FAIL: " + str(exc)
|
|
summary["finished_at_utc"] = utc_now()
|
|
(output_dir / "summary.json").write_text(json.dumps(summary, indent=2, ensure_ascii=False) + "\n")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|