Files

277 lines
15 KiB
Python

"""Isolated v2 Docker runtime; reuse the v1 workload and fixture unchanged."""
import asyncio
import csv
import hashlib
import importlib.util
import io
import json
import os
import platform
import secrets
import socket
import subprocess
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[1]
V1 = HERE.parent / "lab3-scale"
sys.path.insert(0, str(V1))
import common as original
import load as workload
import aiohttp
def module(path, name):
spec = importlib.util.spec_from_file_location(name, path)
result = importlib.util.module_from_spec(spec)
spec.loader.exec_module(result)
return result
legacy_analysis = module(V1 / "analyze.py", "scale_v1_analysis")
def save(path, data):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
def digest(data):
return hashlib.sha256(json.dumps(data, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
def sources():
paths = [p for base in (ROOT / "src/backend", V1, HERE) for p in base.rglob("*")
if p.is_file() and "__pycache__" not in p.parts and p.suffix.lower() != ".md"]
paths += [ROOT / name for name in ("src/go.mod", "src/go.sum", "src/Dockerfile")]
return {str(path.relative_to(ROOT)): hashlib.sha256(path.read_bytes()).hexdigest() for path in sorted(paths)}
def shell(args):
result = subprocess.run(args, cwd=ROOT, text=True, capture_output=True)
if result.returncode:
# Avoid echoing expanded connection strings or private Docker output.
raise RuntimeError("Command failed: " + " ".join(args[:3]))
return result.stdout.strip()
def docker_endpoint():
context = json.loads(shell(["docker", "context", "inspect"]))[0]
endpoint = os.environ.get("DOCKER_HOST") or context["Endpoints"]["docker"]["Host"]
if not endpoint.startswith("unix://"):
raise RuntimeError("v2 telemetry requires a local unix:// Docker context (WSL/Linux/macOS)")
path = endpoint.removeprefix("unix://")
if not Path(path).exists():
raise RuntimeError("Docker socket from the current context is unavailable")
return path
def check_ports():
for port in (18082, 18406):
with socket.socket() as probe:
try:
probe.bind(("127.0.0.1", port))
except OSError as error:
raise RuntimeError(f"Port {port} is occupied; no unrelated container will be stopped") from error
def environment():
info = json.loads(shell(["docker", "info", "--format",
'{"cpus":{{.NCPU}},"memory":{{.MemTotal}},"architecture":{{json .Architecture}},"os":{{json .OperatingSystem}}}']))
return {"time_utc": datetime.now(timezone.utc).isoformat(), "platform": platform.platform(),
"python": platform.python_version(), "docker_resources": info,
"docker_version": json.loads(shell(["docker", "version", "--format", "{{json .Server}}"])),
"compose_version": shell(["docker", "compose", "version"]),
"git_commit": shell(["git", "rev-parse", "HEAD"]),
"worktree_files": shell(["git", "status", "--porcelain"]).splitlines(),
"docker_socket": docker_endpoint(), "app_code_sha256": original.code_hash()}
DB_SAMPLE = """SELECT json_build_object(
'active',(SELECT count(*) FROM pg_stat_activity WHERE datname='benchmark' AND state='active' AND pid<>pg_backend_pid()),
'waits',(SELECT coalesce(json_agg(json_build_object('event_type',wait_event_type,'event',wait_event,'count',n)),'[]'::json)
FROM (SELECT wait_event_type,wait_event,count(*) n FROM pg_stat_activity WHERE datname='benchmark' AND pid<>pg_backend_pid() GROUP BY 1,2) t),
'database',(SELECT row_to_json(d) FROM (SELECT xact_commit,xact_rollback,blks_read,blks_hit,tup_inserted,deadlocks FROM pg_stat_database WHERE datname='benchmark') d),
'wal',(SELECT row_to_json(w) FROM pg_stat_wal w),
'io',(SELECT coalesce(json_agg(i),'[]'::json) FROM pg_stat_io i WHERE backend_type='client backend')
);"""
class Runtime:
def __init__(self, series, image, env_info):
self.series = series
self.private = ROOT / ".memory/lab3-scale-v2" / series
self.private.mkdir(parents=True, exist_ok=True)
self.project = "highload-lab3-v2-" + hashlib.sha256(series.encode()).hexdigest()[:10]
self.image = image
self.env_info = env_info
self.socket = env_info["docker_socket"]
self.db_cpu = None
credentials = self.private / "environment"
if not credentials.exists():
credentials.write_text("BENCH_PASSWORD=" + secrets.token_hex(24) + "\n")
credentials.chmod(0o600)
# Only this process is adapted. No v1 source or historical evidence changes.
original.compose = self.compose
original.PROJECT = self.project
workload.BASE = "http://127.0.0.1:18082"
workload.STATS = "http://127.0.0.1:18406/stats;csv"
workload.collect = self.collect
def compose(self, args, config=None):
config = config or {"cpu": .5, "memory": "128m", "replicas": 2, "pool": 6,
"gomaxprocs": 16, "db_cpu": 1}
env = {**os.environ, "BENCH_CPU": str(config["cpu"]), "BENCH_MEMORY": config["memory"],
"BENCH_REPLICAS": str(config["replicas"]), "BENCH_POOL": str(config["pool"]),
"BENCH_GOMAXPROCS": str(config["gomaxprocs"]), "BENCH_DB_CPU": str(config["db_cpu"]),
"BENCH_IMAGE": self.image}
result = subprocess.run(["docker", "compose", "--project-name", self.project, "--project-directory", str(ROOT),
"--env-file", str(self.private / "environment"), "-f", str(HERE / "compose.yml"), *args],
cwd=ROOT, env=env, text=True, capture_output=True)
if result.returncode:
(self.private / "compose-error.log").write_text(result.stdout + result.stderr)
raise RuntimeError("v2 Compose failed; see " + str(self.private / "compose-error.log"))
return result.stdout.strip()
def suspend_main(self):
ids = shell(["docker", "ps", "-q", "--filter", "label=com.docker.compose.project=highload-lab3"]).split()
records = []
for container in ids:
data = json.loads(shell(["docker", "inspect", "--format",
'{"id":{{json .Id}},"service":{{json (index .Config.Labels "com.docker.compose.service")}}}', container]))
records.append(data)
save(self.private / "original-state.json", records)
if ids:
shell(["docker", "stop", *ids])
def restore(self):
errors = []
try:
self.compose(["stop"])
except Exception as error:
errors.append(str(error))
path = self.private / "original-state.json"
records = json.loads(path.read_text()) if path.exists() else []
for group in (("db", "redis"), ("api",), ("haproxy", "frontend")):
for record in records:
if record["service"] not in group:
continue
try:
project = shell(["docker", "inspect", "--format", '{{index .Config.Labels "com.docker.compose.project"}}', record["id"]])
if project != "highload-lab3":
raise RuntimeError("Original container identity changed")
shell(["docker", "start", record["id"]])
deadline = time.monotonic() + 60
while time.monotonic() < deadline:
state = json.loads(shell(["docker", "inspect", "--format", "{{json .State}}", record["id"]]))
if state["Running"] and state.get("Health", {}).get("Status", "healthy") == "healthy":
break
time.sleep(1)
else:
raise RuntimeError("Original container did not become healthy: " + record["service"])
except Exception as error:
errors.append(str(error))
save(self.private / "restoration.json", {"ok": not errors, "errors": errors})
return not errors
def prepare_services(self, config):
if self.db_cpu != config["db_cpu"]:
self.compose(["up", "-d", "--wait", "db", "redis"], config)
# One explicit migration job, not migrations in each API.
self.compose(["run", "--rm", "--no-deps", "migrate"], config)
self.db_cpu = config["db_cpu"]
self.compose(["up", "-d", "--no-deps", "--force-recreate", "--wait", "api"], config)
self.compose(["up", "-d", "--no-deps", "haproxy"], config)
def execute(self, point, directory, protocol_sha, timings, sequence):
if directory.exists():
raise RuntimeError("Run already exists; raw measurements are never overwritten: " + str(directory))
directory.mkdir(parents=True)
config = point["config"]
self.prepare_services(config)
actors = original.restore_fixture()
actual = original.current_containers()
apis = [row for row in actual if row["service"] == "api"]
for name, cpu, memory in (("api", config["cpu"], int(config["memory"].removesuffix("m")) * 1048576),
("db", config["db_cpu"], 512 * 1048576), ("redis", .25, 128 * 1048576),
("haproxy", .5, 128 * 1048576)):
rows = [row for row in actual if row["service"] == name]
if not rows or any(row["cpu"] != cpu * 1e9 or row["memory"] != memory for row in rows):
raise RuntimeError("Effective limits differ from protocol: " + name)
if len(apis) != config["replicas"] or any(row["ports"] for row in apis):
raise RuntimeError("API replica count or exposed ports differ")
manifest = {**point, "run_id": directory.name, "sequence": sequence, "protocol_sha256": protocol_sha,
"code_sha256": original.code_hash(), "containers": actual,
"docker_cpus": self.env_info["docker_resources"]["cpus"],
"started_utc": datetime.now(timezone.utc).isoformat()}
save(directory / "manifest.json", manifest)
result = asyncio.run(workload.measure(actors, directory, config, rate=point["rate"],
duration=timings["duration_s"], warmup=timings["warmup_s"], seed=230300,
prefix=self.series + ":" + str(sequence), limit=8192))
samples = json.loads((directory / "pool.json").read_text())
expected = {row["instance"] for row in apis}
observed = {row["instance"] for row in samples}
runtime_ok = observed == expected and all(row.get("gomaxprocs") == config["gomaxprocs"] and row["max"] == config["pool"] for row in samples)
result["runtime_settings_verified"] = runtime_ok
result["valid"] = result["valid"] and runtime_ok
result["slo_pass"] = result["slo_pass"] and result["valid"]
result["rate"] = point["rate"]
save(directory / "summary.json", result)
diagnostic = legacy_analysis.diagnostics(directory, manifest)
save(directory / "diagnostics.json", diagnostic)
print(json.dumps({"run": directory.name, "rate": point["rate"], "p95_ms": result["p95_ms"],
"success": result["success_ratio"], "valid": result["valid"], "slo_pass": result["slo_pass"]}), flush=True)
return result
async def sample_db(self, container):
process = await asyncio.create_subprocess_exec("docker", "exec", "-i", "-e", "PGOPTIONS=-c statement_timeout=2000", container,
"psql", "-X", "-q", "-t", "-A", "-v", "ON_ERROR_STOP=1", "-U", "benchmark", "-d", "benchmark",
stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
try:
stdout, _ = await asyncio.wait_for(process.communicate(DB_SAMPLE.encode()), 4)
except BaseException:
if process.returncode is None:
process.kill()
await process.communicate()
raise
if process.returncode:
raise RuntimeError("DB telemetry unavailable")
return json.loads(stdout)
async def collect(self, stop, containers, rows):
db = next(row["id"] for row in containers if row["service"] == "db")
async with aiohttp.ClientSession(connector=aiohttp.UnixConnector(path=self.socket), timeout=aiohttp.ClientTimeout(total=4)) as engine, \
aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=4)) as http:
async def stats(container):
async with engine.get(f"http://docker/v1.47/containers/{container['id']}/stats?stream=false&one-shot=true") as response:
data = await response.json()
cpu = dict(data.get("cpu_stats") or {})
observed = cpu.get("online_cpus")
cpu["online_cpus"] = observed or self.env_info["docker_resources"]["cpus"]
return {"instance": container["instance"], "service": container["service"], "cpu_stats": cpu,
"cpu_count_source": "stats" if observed else "docker_info", "memory_stats": data.get("memory_stats"),
"blkio_stats": data.get("blkio_stats"), "stats_available": response.status == 200}
while not stop.is_set():
begin = time.monotonic()
try:
resources, database = await asyncio.gather(asyncio.gather(*(stats(row) for row in containers)), self.sample_db(db))
haproxy, stats_error = [], None
try:
async with http.get(workload.STATS) as response:
haproxy = [row for row in csv.DictReader(io.StringIO((await response.text()).removeprefix("# ")))
if row["pxname"] in ("api_replicas", "api_entry")]
except (aiohttp.ClientError, TimeoutError):
stats_error = "unavailable"
rows.append({"time": datetime.now(timezone.utc).isoformat(), "resources": resources,
"postgres": database, "haproxy": haproxy, "haproxy_stats_error": stats_error,
"generator_cpu_seconds": time.process_time(), "collection_seconds": time.monotonic() - begin})
except Exception as error:
rows.append({"time": datetime.now(timezone.utc).isoformat(), "error": type(error).__name__})
try:
await asyncio.wait_for(stop.wait(), max(.01, 1 - (time.monotonic() - begin)))
except TimeoutError:
pass