Реализовать лабораторную 3 на оценку 5 (трек 1)
This commit is contained in:
@@ -0,0 +1,198 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run the lab3 track-1 scaling matrix.
|
||||
|
||||
Fixed total API budget:
|
||||
1 replica x 2.0 CPU / 1G
|
||||
2 replicas x 1.0 CPU / 512M
|
||||
4 replicas x 0.5 CPU / 256M
|
||||
Growth series:
|
||||
4 replicas x 0.5, 1.0 and 2.0 CPU (256M, 512M, 1G)
|
||||
|
||||
The script changes only local Compose environment overrides; it never removes
|
||||
volumes and restores the normal 2-replica profile at the end.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
EVIDENCE = ROOT / "evidence" / "track1"
|
||||
|
||||
|
||||
def compose(*args: str, env: dict | None = None, check: bool = True) -> subprocess.CompletedProcess:
|
||||
return subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", *args],
|
||||
cwd=ROOT,
|
||||
env=env,
|
||||
check=check,
|
||||
text=True,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
)
|
||||
|
||||
|
||||
def wait_healthy(expected: int, timeout: float = 90) -> None:
|
||||
deadline = time.monotonic() + timeout
|
||||
last = ""
|
||||
while time.monotonic() < deadline:
|
||||
ids = compose("ps", "-q", "api").stdout.split()
|
||||
if len(ids) == expected:
|
||||
statuses = []
|
||||
for container_id in ids:
|
||||
status = subprocess.check_output(
|
||||
[
|
||||
"docker",
|
||||
"inspect",
|
||||
"--format",
|
||||
"{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}",
|
||||
container_id,
|
||||
],
|
||||
text=True,
|
||||
).strip()
|
||||
statuses.append(status)
|
||||
last = ",".join(statuses)
|
||||
if all(status == "healthy" for status in statuses):
|
||||
return
|
||||
else:
|
||||
last = f"{len(ids)} containers"
|
||||
time.sleep(1.0)
|
||||
raise RuntimeError(f"API replicas did not become healthy: {last}")
|
||||
|
||||
|
||||
def apply_profile(profile: dict) -> dict:
|
||||
env = os.environ.copy()
|
||||
env.update(
|
||||
{
|
||||
"API_REPLICAS": str(profile["replicas"]),
|
||||
"API_CPU_LIMIT": profile["cpu"],
|
||||
"API_MEM_LIMIT": profile["mem"],
|
||||
}
|
||||
)
|
||||
compose(
|
||||
"up",
|
||||
"-d",
|
||||
"--no-deps",
|
||||
"--scale",
|
||||
f"api={profile['replicas']}",
|
||||
"api",
|
||||
env=env,
|
||||
)
|
||||
wait_healthy(profile["replicas"])
|
||||
return env
|
||||
|
||||
|
||||
def run_once(profile: dict, repetition: int, args) -> dict:
|
||||
apply_profile(profile)
|
||||
EVIDENCE.mkdir(parents=True, exist_ok=True)
|
||||
tag = f"{profile['name']}_r{repetition}"
|
||||
bench_output = EVIDENCE / f"bench_{tag}.json"
|
||||
metrics_output = EVIDENCE / f"metrics_{tag}.json"
|
||||
sampler = subprocess.Popen(
|
||||
[
|
||||
sys.executable,
|
||||
str(ROOT / "student-tests" / "sample_metrics.py"),
|
||||
"--duration",
|
||||
str(args.duration + args.warmup),
|
||||
"--interval",
|
||||
"2",
|
||||
"--output",
|
||||
str(metrics_output),
|
||||
],
|
||||
cwd=ROOT,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
bench = subprocess.run(
|
||||
[
|
||||
sys.executable,
|
||||
str(ROOT / "student-tests" / "track1_bench.py"),
|
||||
"--base-url",
|
||||
args.base_url,
|
||||
"--duration",
|
||||
str(args.duration),
|
||||
"--warmup",
|
||||
str(args.warmup),
|
||||
"--concurrency",
|
||||
str(profile["concurrency"]),
|
||||
"--label",
|
||||
tag,
|
||||
"--output",
|
||||
str(bench_output),
|
||||
],
|
||||
cwd=ROOT,
|
||||
text=True,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
)
|
||||
sampler.wait(timeout=30)
|
||||
if bench.returncode != 0:
|
||||
raise RuntimeError(bench.stdout)
|
||||
result = json.loads(bench_output.read_text(encoding="utf-8"))
|
||||
result["profile"] = profile
|
||||
result["repetition"] = repetition
|
||||
result["metrics_file"] = str(metrics_output.relative_to(ROOT))
|
||||
return result
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
parser.add_argument("--duration", type=float, default=20.0)
|
||||
parser.add_argument("--warmup", type=float, default=2.0)
|
||||
parser.add_argument("--repetitions", type=int, default=2)
|
||||
parser.add_argument("--concurrency", type=int, default=24)
|
||||
parser.add_argument("--output", default="evidence/track1_summary.json")
|
||||
args = parser.parse_args()
|
||||
|
||||
scaling = [
|
||||
{"name": "1x2.0cpu_1g", "replicas": 1, "cpu": "2.0", "mem": "1G", "concurrency": args.concurrency},
|
||||
{"name": "2x1.0cpu_512m", "replicas": 2, "cpu": "1.0", "mem": "512M", "concurrency": args.concurrency},
|
||||
{"name": "4x0.5cpu_256m", "replicas": 4, "cpu": "0.5", "mem": "256M", "concurrency": args.concurrency},
|
||||
]
|
||||
growth = [
|
||||
{"name": "4x0.5cpu_256m", "replicas": 4, "cpu": "0.5", "mem": "256M", "concurrency": args.concurrency},
|
||||
{"name": "4x1.0cpu_512m", "replicas": 4, "cpu": "1.0", "mem": "512M", "concurrency": args.concurrency},
|
||||
{"name": "4x2.0cpu_1g", "replicas": 4, "cpu": "2.0", "mem": "1G", "concurrency": args.concurrency},
|
||||
]
|
||||
|
||||
results = {"scaling_fixed_total": [], "growth_four_replicas": []}
|
||||
try:
|
||||
for profile in scaling:
|
||||
for repetition in range(1, args.repetitions + 1):
|
||||
print(f"RUN scaling {profile['name']} repetition {repetition}", flush=True)
|
||||
results["scaling_fixed_total"].append(run_once(profile, repetition, args))
|
||||
for profile in growth:
|
||||
for repetition in range(1, args.repetitions + 1):
|
||||
print(f"RUN growth {profile['name']} repetition {repetition}", flush=True)
|
||||
results["growth_four_replicas"].append(run_once(profile, repetition, args))
|
||||
finally:
|
||||
# Restore the normal profile even if an experiment fails.
|
||||
restore_env = os.environ.copy()
|
||||
restore_env.update(
|
||||
{"API_REPLICAS": "2", "API_CPU_LIMIT": "1.0", "API_MEM_LIMIT": "512M"}
|
||||
)
|
||||
compose(
|
||||
"up",
|
||||
"-d",
|
||||
"--no-deps",
|
||||
"--scale",
|
||||
"api=2",
|
||||
"api",
|
||||
env=restore_env,
|
||||
)
|
||||
wait_healthy(2)
|
||||
|
||||
output = ROOT / args.output
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
output.write_text(json.dumps(results, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print("PASS: track-1 matrix complete; evidence:", output)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user