Files
mtusi2026lab3/scripts/track1_scaling.py
T

103 lines
3.9 KiB
Python

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()