101 lines
4.0 KiB
Python
101 lines
4.0 KiB
Python
"""Repeat the same load over 1, 2 and 4 replicas under two resource strategies."""
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
import statistics
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / "tests"))
|
|
from client import Client, Failure # noqa: E402
|
|
|
|
|
|
def compose(env, *args):
|
|
return subprocess.run(["docker", "compose", *args], cwd=ROOT, env=env,
|
|
capture_output=True, text=True, check=True, timeout=90).stdout
|
|
|
|
|
|
def start(env):
|
|
compose(env, "up", "-d", "--no-deps", "--wait", "api")
|
|
client = Client(env["BASE_URL"], timeout=2)
|
|
target = int(env["API_REPLICAS"])
|
|
deadline = time.monotonic() + 40
|
|
seen = set()
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
seen.add(client.call("GET", "/health/ready", schema="Health")["headers"]["X-Instance-Id"])
|
|
except Failure:
|
|
time.sleep(0.2)
|
|
else:
|
|
if len(seen) >= target:
|
|
return
|
|
raise RuntimeError("Configured replica count not visible through HAProxy")
|
|
|
|
|
|
def sample_stats(env):
|
|
ids = compose(env, "ps", "-q", "api", "db", "cache", "lb").split()
|
|
snapshot = subprocess.run(
|
|
["docker", "stats", "--no-stream", "--format", "{{json .}}", *ids],
|
|
cwd=ROOT, env=env, capture_output=True, check=True, text=True, timeout=12,
|
|
).stdout
|
|
rows = [json.loads(line) for line in snapshot.splitlines() if line.strip()]
|
|
return [{"name": row["Name"], "cpu": row["CPUPerc"], "memory": row["MemUsage"]} for row in rows]
|
|
|
|
|
|
def load(env, seconds, concurrency):
|
|
with subprocess.Popen(
|
|
[sys.executable, "-X", "utf8", "tests/load.py", "--duration", str(seconds),
|
|
"--concurrency", str(concurrency)], cwd=ROOT, env=env, text=True,
|
|
encoding="utf-8", stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
|
) as process:
|
|
observed = []
|
|
started = time.monotonic()
|
|
try:
|
|
while process.poll() is None and time.monotonic() - started < seconds + 20:
|
|
observed.append(sample_stats(env))
|
|
time.sleep(2)
|
|
output, errors = process.communicate(timeout=15)
|
|
except BaseException:
|
|
process.kill()
|
|
raise
|
|
if process.returncode:
|
|
raise RuntimeError(f"load script failed: {errors or output}")
|
|
return {"load": json.loads(output), "resource_samples": observed}
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--base-url", default="http://localhost:8080")
|
|
parser.add_argument("--seconds", type=int, default=15)
|
|
parser.add_argument("--repeat", type=int, default=3)
|
|
parser.add_argument("--concurrency", type=int, default=12)
|
|
parser.add_argument("--output", type=Path, default=ROOT / "evidence/scaling.json")
|
|
args = parser.parse_args()
|
|
base = {**os.environ, "BASE_URL": args.base_url}
|
|
original = {**base, "API_REPLICAS": base.get("API_REPLICAS", "2"),
|
|
"API_CPUS": base.get("API_CPUS", "0.75"), "API_MEMORY": base.get("API_MEMORY", "256m")}
|
|
rows = []
|
|
try:
|
|
for strategy in ("fixed_total", "fixed_per_replica"):
|
|
for replicas in (1, 2, 4):
|
|
cpu, memory = (2 / replicas, 1024 // replicas) if strategy == "fixed_total" else (0.5, 256)
|
|
env = {**base, "API_REPLICAS": str(replicas), "API_CPUS": str(cpu), "API_MEMORY": f"{memory}m"}
|
|
start(env)
|
|
load(env, 4, args.concurrency)
|
|
attempts = [load(env, args.seconds, args.concurrency) for _ in range(args.repeat)]
|
|
rows.append({"strategy": strategy, "replicas": replicas, "cpu_per_replica": cpu,
|
|
"memory_mib_per_replica": memory, "runs": attempts,
|
|
"median_success_rps": statistics.median(x["load"]["successful_rps"] for x in attempts)})
|
|
finally:
|
|
start(original)
|
|
args.output.write_text(json.dumps(rows, indent=2) + "\n", encoding="utf-8")
|
|
print(f"Saved {len(rows)} observed resource profiles")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|