Complete Lab 3 for Grade 5 (Track 1)

This commit is contained in:
paflove
2026-11-03 13:37:17 +03:00
parent 0ab3a341aa
commit 67ac1497dc
16 changed files with 1143 additions and 15 deletions
+8
View File
@@ -0,0 +1,8 @@
@echo off
docker compose restart
:wait_loop
curl -s -f http://localhost:8080/health/ready >nul 2>&1
if errorlevel 1 (
timeout /t 1 /nobreak >nul
goto wait_loop
)
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
set -e
echo "Restarting stack while preserving volumes..."
docker compose restart
echo "Waiting for API readiness..."
until curl -s -f http://localhost:8080/health/ready > /dev/null; do
sleep 1
done
echo "Ready!"
+7
View File
@@ -0,0 +1,7 @@
@echo off
for /f "tokens=*" %%i in ('docker compose ps -q api') do (
echo Stopping API replica %%i...
docker stop %%i
goto :done
)
:done
+10
View File
@@ -0,0 +1,10 @@
#!/bin/sh
set -e
TARGET=$(docker compose ps -q api | head -n 1)
if [ -n "$TARGET" ]; then
echo "Остановка реплики $TARGET..."
docker stop "$TARGET"
else
echo "Нет запущенных API-контейнеров"
exit 1
fi
+103
View File
@@ -0,0 +1,103 @@
import os
import sys
import time
import base64
import uuid
import httpx
import subprocess
from concurrent.futures import ThreadPoolExecutor
BASE_URL = "http://localhost:8080"
def get_client():
return httpx.Client(base_url=BASE_URL, trust_env=False, timeout=10.0)
def benchmark(client, headers, chat_id, duration_sec=10, concurrency=8):
stop_at = time.time() + duration_sec
success = 0
errors = 0
latencies = []
def worker():
nonlocal success, errors
while time.time() < stop_at:
t0 = time.time()
try:
idem = f"bench_{uuid.uuid4()}"
r = client.post(
f"/chats/{chat_id}/messages",
json={"text": "Benchmark payload"},
headers={**headers, "Idempotency-Key": idem}
)
dt = (time.time() - t0) * 1000
if r.status_code == 201:
success += 1
latencies.append(dt)
else:
errors += 1
except Exception:
errors += 1
with ThreadPoolExecutor(max_workers=concurrency) as ex:
futures = [ex.submit(worker) for _ in range(concurrency)]
for f in futures:
f.result()
latencies.sort()
n = len(latencies)
p50 = latencies[int(n * 0.50)] if n else 0
p95 = latencies[int(n * 0.95)] if n else 0
p99 = latencies[int(n * 0.99)] if n else 0
rps = success / duration_sec
return rps, p50, p95, p99, errors
def set_replicas(n):
print(f"\n>>> Масштабирование до {n} реплик API...")
subprocess.run(["docker", "compose", "up", "-d", "--scale", f"api={n}"], check=True)
subprocess.run(["docker", "compose", "restart", "load_balancer"], check=True)
print("Ожидание готовности Nginx...")
time.sleep(5)
with get_client() as c:
for _ in range(15):
try:
if c.get("/health/ready").status_code == 200:
break
except Exception:
pass
time.sleep(1)
def main():
print("ТРЕК 1: ИССЛЕДОВАНИЕ ЦЕНЫ МАСШТАБИРОВАНИЯ (1, 2, 4 РЕПЛИКИ)")
with get_client() as client:
# Регистрация пользователя и чата
ts = int(time.time() * 1000)
uname = f"perf_{ts}"
pw = "password_12345678"
client.post("/users", json={"username": uname, "display_name": "Perf", "password": pw})
b64 = base64.b64encode(f"{uname}:{pw}".encode()).decode()
token = client.post("/auth/sessions", headers={"Authorization": f"Basic {b64}"}).json()["token"]
uid = client.get("/users/me", headers={"Authorization": f"Bearer {token}"}).json()["id"]
h = {"Authorization": f"Bearer {token}"}
chat_id = client.post("/chats", json={"title": "Perf Chat", "member_ids": [uid]}, headers=h).json()["id"]
results = {}
for replicas in [1, 2, 4]:
set_replicas(replicas)
print(f"Запуск нагрузки для {replicas} реплик (10 секунд, concurrency=8)...")
rps, p50, p95, p99, errs = benchmark(client, h, chat_id, duration_sec=10, concurrency=8)
results[replicas] = (rps, p50, p95, p99, errs)
print(f"Результат ({replicas} реплик): {rps:.1f} RPS, p50={p50:.1f}ms, p95={p95:.1f}ms, p99={p99:.1f}ms, errors={errs}")
set_replicas(2)
print("\n" + "="*70)
print("ИТОГОВАЯ СВОДКА МАСШТАБИРОВАНИЯ:")
print("="*70)
print(f"{'Реплики':<10} | {'RPS':<10} | {'p50 (ms)':<10} | {'p95 (ms)':<10} | {'p99 (ms)':<10} | {'Ошибки':<8}")
print("-" * 70)
for r, (rps, p50, p95, p99, errs) in results.items():
print(f"{r:<10} | {rps:<10.1f} | {p50:<10.1f} | {p95:<10.1f} | {p99:<10.1f} | {errs:<8}")
if __name__ == "__main__":
main()