Лабораторная 3: реализован стенд с балансировщиком и идемпотентностью

This commit is contained in:
2026-11-22 16:11:18 +03:00
parent 0ab3a341aa
commit 752995515f
31 changed files with 1576 additions and 23 deletions
+80
View File
@@ -0,0 +1,80 @@
#!/usr/bin/env python3
"""Repeatable closed-loop scaling experiment for lab3 grade 5."""
import argparse
import json
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
OUTPUT = ROOT / "evidence" / "scale"
def run(command):
return subprocess.run(command, cwd=ROOT, check=True)
def wait_ready():
deadline = time.monotonic() + 60
while time.monotonic() < deadline:
result = subprocess.run(
["python", "-c", "import urllib.request; print(urllib.request.urlopen('http://localhost:8080/health/ready', timeout=2).status)"],
cwd=ROOT,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
if result.returncode == 0:
return
time.sleep(1)
raise RuntimeError("API did not become ready")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--duration", type=float, default=15)
parser.add_argument("--concurrency", type=int, default=8)
args = parser.parse_args()
OUTPUT.mkdir(parents=True, exist_ok=True)
metadata = {
"hypothesis": "With a fixed API budget, two replicas should improve tail and throughput versus one; four replicas will converge toward PostgreSQL/LB limits.",
"duration_seconds": args.duration,
"concurrency": args.concurrency,
"fixed_budget": {"cpu": 2.0, "memory_mb": 1024},
}
(OUTPUT / "experiment.json").write_text(json.dumps(metadata, ensure_ascii=False, indent=2) + "\n")
fixed_runs = []
for count in (1, 2, 4):
run([sys.executable, str(ROOT / "scripts" / "scale_topology.py"), str(count),
"--total-cpus", "2", "--total-memory-mb", "1024"])
wait_ready()
dest = OUTPUT / f"fixed-{count}-replicas.json"
run([sys.executable, str(ROOT / "tests" / "load.py"),
"--duration", str(args.duration), "--concurrency", str(args.concurrency),
"--output", str(dest)])
fixed_runs.append(dest.name)
resource_runs = []
for total_cpus, memory_mb in ((1.0, 512), (2.0, 1024), (4.0, 2048)):
run([sys.executable, str(ROOT / "scripts" / "scale_topology.py"), "2",
"--total-cpus", str(total_cpus), "--total-memory-mb", str(memory_mb)])
wait_ready()
dest = OUTPUT / f"resources-{int(total_cpus)}cpu-{memory_mb}mb.json"
run([sys.executable, str(ROOT / "tests" / "load.py"),
"--duration", str(args.duration), "--concurrency", str(args.concurrency),
"--output", str(dest)])
resource_runs.append(dest.name)
summary = {
"fixed_budget_runs": fixed_runs,
"resource_growth_runs": resource_runs,
"raw_outputs": "Each JSON is the public load-test summary.",
}
(OUTPUT / "runs.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n")
print("Benchmark complete:", OUTPUT)
if __name__ == "__main__":
main()
+6
View File
@@ -0,0 +1,6 @@
@echo off
REM Restart API and all used state stores (DB, sessions). Preserves volumes.
cd /d "%~dp0.."
docker compose restart --timeout 15
docker compose up -d
exit /b 0
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env python3
"""Restart all services preserving volumes — called by resilience.py persistence test."""
import subprocess
import sys
import os
def main():
# Change to repo root
repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.chdir(repo_root)
# Restart running services; up -d brings any stopped replica back up
result = subprocess.run(["docker", "compose", "restart", "--timeout", "15"], capture_output=True)
if result.returncode != 0:
print(f"docker compose restart failed: {result.stderr.decode()}", file=sys.stderr)
return 1
result = subprocess.run(["docker", "compose", "up", "-d"], capture_output=True)
if result.returncode != 0:
print(f"docker compose up -d failed: {result.stderr.decode()}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
# Restart the API and all used state stores, preserving persistent volumes.
# Never use `down -v`, never flush/re-seed the database.
set -eu
cd "$(dirname "$0")/.."
# Restart running services; up -d brings any stopped replica back up.
docker compose restart --timeout 15
docker compose up -d
exit 0
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env python3
"""Restart API replicas one at a time while the public load continues."""
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def compose(*args):
subprocess.run(["docker", "compose", *args], cwd=ROOT, check=True)
def wait_ready(timeout=60):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
result = subprocess.run(
["python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8080/health/ready', timeout=2)"],
cwd=ROOT,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
if result.returncode == 0:
return
time.sleep(0.5)
raise RuntimeError("LB never recovered readiness")
def main():
for service in ("api-1", "api-2"):
compose("stop", "--timeout", "5", service)
time.sleep(2)
compose("start", service)
wait_ready()
print(f"rolling restart recovered: {service}")
if __name__ == "__main__":
try:
main()
except subprocess.CalledProcessError as exc:
print(f"rolling update failed: {exc}", file=sys.stderr)
sys.exit(1)
+65
View File
@@ -0,0 +1,65 @@
#!/usr/bin/env python3
"""Scale the lab API topology and apply a fixed aggregate CPU/RAM budget."""
import argparse
import shutil
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
SERVICES = ("api-1", "api-2", "api-3", "api-4")
def compose(*args):
return subprocess.run(
["docker", "compose", *args],
cwd=ROOT,
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
).stdout
def main():
parser = argparse.ArgumentParser()
parser.add_argument("count", choices=(1, 2, 4), type=int)
parser.add_argument("--total-cpus", type=float, default=2.0)
parser.add_argument("--total-memory-mb", type=int, default=1024)
args = parser.parse_args()
if shutil.which("docker") is None:
print("Docker CLI is unavailable", file=sys.stderr)
return 2
active = set(SERVICES[: args.count])
for service in active:
compose("start", service)
for service in set(SERVICES) - active:
compose("stop", "--timeout", "5", service)
for service in active:
container_id = compose("ps", "-q", service).strip()
if not container_id:
print(f"{service} is not running", file=sys.stderr)
return 1
cpus = args.total_cpus / args.count
memory_mb = max(128, args.total_memory_mb // args.count)
subprocess.run(
[
"docker", "update",
"--cpus", str(cpus),
"--memory", f"{memory_mb}m",
"--memory-swap", f"{memory_mb}m",
container_id,
],
check=True,
stdout=subprocess.DEVNULL,
)
print(f"active replicas={args.count}; total CPU={args.total_cpus}; RAM={args.total_memory_mb}MB")
return 0
if __name__ == "__main__":
sys.exit(main())
+9
View File
@@ -0,0 +1,9 @@
@echo off
REM Stop exactly ONE API replica selected by TARGET_INSTANCE_ID. Leave it stopped.
if "%TARGET_INSTANCE_ID%"=="" (
echo TARGET_INSTANCE_ID not set
exit /b 2
)
cd /d "%~dp0.."
docker compose stop --timeout 5 %TARGET_INSTANCE_ID%
exit /b 0
+25
View File
@@ -0,0 +1,25 @@
#!/usr/bin/env python3
"""Stop exactly ONE API replica selected by TARGET_INSTANCE_ID — called by resilience.py failover test."""
import subprocess
import sys
import os
def main():
target = os.environ.get("TARGET_INSTANCE_ID")
if not target:
print("TARGET_INSTANCE_ID not set", file=sys.stderr)
return 2
# Change to repo root
repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.chdir(repo_root)
# Stop the specific API service by its compose service name
result = subprocess.run(["docker", "compose", "stop", "--timeout", "5", target], capture_output=True)
if result.returncode != 0:
print(f"docker compose stop {target} failed: {result.stderr.decode()}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
# Stop exactly ONE API replica selected by TARGET_INSTANCE_ID and leave it stopped.
# Used by tests/resilience.py failover scenario.
set -eu
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
# Resolve compose project directory regardless of invocation cwd.
cd "$(dirname "$0")/.."
# INSTANCE_ID values are the compose service names (api-1, api-2, ...).
exec docker compose stop --timeout 5 "$TARGET_INSTANCE_ID"