This commit is contained in:
paflove
2026-11-06 14:48:35 +03:00
parent 67ac1497dc
commit 04be9e0311
4 changed files with 256 additions and 48 deletions
+98 -24
View File
@@ -12,6 +12,21 @@ BASE_URL = "http://localhost:8080"
def get_client():
return httpx.Client(base_url=BASE_URL, trust_env=False, timeout=10.0)
def get_container_ids():
res = subprocess.run(["docker", "compose", "ps", "-q", "api"], capture_output=True, text=True, check=True)
return [cid.strip() for cid in res.stdout.strip().splitlines() if cid.strip()]
def get_docker_stats():
# Собираем реальную загрузку CPU и памяти контейнеров
cmd = ["docker", "stats", "--no-stream", "--format", "{{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}"]
res = subprocess.run(cmd, capture_output=True, text=True)
stats = {}
for line in res.stdout.strip().splitlines():
parts = line.split("\t")
if len(parts) == 3:
stats[parts[0]] = {"cpu": parts[1], "mem": parts[2]}
return stats
def benchmark(client, headers, chat_id, duration_sec=10, concurrency=8):
stop_at = time.time() + duration_sec
success = 0
@@ -38,8 +53,12 @@ def benchmark(client, headers, chat_id, duration_sec=10, concurrency=8):
except Exception:
errors += 1
# Запускаем сбор статистики в середине теста
mid_stats = {}
with ThreadPoolExecutor(max_workers=concurrency) as ex:
futures = [ex.submit(worker) for _ in range(concurrency)]
time.sleep(duration_sec / 2)
mid_stats = get_docker_stats()
for f in futures:
f.result()
@@ -49,14 +68,17 @@ def benchmark(client, headers, chat_id, duration_sec=10, concurrency=8):
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
return rps, p50, p95, p99, errors, mid_stats
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)
def set_replicas_and_limits(replicas, cpus_per_rep, mem_per_rep):
print(f"\n>>> Масштабирование: {replicas} реплик (по {cpus_per_rep} CPU, {mem_per_rep} RAM каждая)...")
subprocess.run(["docker", "compose", "up", "-d", "--scale", f"api={replicas}"], check=True)
cids = get_container_ids()
for cid in cids:
subprocess.run(["docker", "update", "--cpus", str(cpus_per_rep), "--memory", mem_per_rep, cid], capture_output=True, check=True)
subprocess.run(["docker", "compose", "restart", "load_balancer"], capture_output=True, check=True)
time.sleep(4)
with get_client() as c:
for _ in range(15):
try:
@@ -66,11 +88,18 @@ def set_replicas(n):
pass
time.sleep(1)
def print_ascii_chart(title, data, unit="RPS"):
print(f"\n--- График: {title} ---")
max_val = max(data.values()) if data else 1
for k, v in data.items():
bar_len = int((v / max_val) * 30)
bar = "█" * bar_len
print(f"{k:<12} | {bar:<30} {v:.1f} {unit}")
def main():
print("ТРЕК 1: ИССЛЕДОВАНИЕ ЦЕНЫ МАСШТАБИРОВАНИЯ (1, 2, 4 РЕПЛИКИ)")
print("ТРЕК 1: ПОЛНОЕ ИССЛЕДОВАНИЕ ЦЕНЫ МАСШТАБИРОВАНИЯ")
with get_client() as client:
# Регистрация пользователя и чата
ts = int(time.time() * 1000)
uname = f"perf_{ts}"
pw = "password_12345678"
@@ -81,23 +110,68 @@ def main():
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)
# СЕРИЯ 1: ФИКСИРОВАННЫЙ СУММАРНЫЙ БЮДЖЕТ (1.0 CPU, 512M RAM)
print("\n" + "="*70)
print("ИТОГОВАЯ СВОДКА МАСШТАБИРОВАНИЯ:")
print("СЕРИЯ 1: ФИКСИРОВАННЫЙ СУММАРНЫЙ БЮДЖЕТ (ИТОГО: 1.0 CPU, 512MB RAM)")
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}")
fixed_plan = [
(1, 1.00, "512m"),
(2, 0.50, "256m"),
(4, 0.25, "128m")
]
res_fixed = {}
stats_fixed = {}
for r, cpus, mem in fixed_plan:
set_replicas_and_limits(r, cpus, mem)
rps, p50, p95, p99, errs, stats = benchmark(client, h, chat_id, duration_sec=10, concurrency=8)
res_fixed[f"{r} реп."] = rps
stats_fixed[r] = (rps, p50, p95, p99, errs, stats)
print(f"[{r} реп. по {cpus} CPU]: {rps:.1f} RPS | p50={p50:.1f}ms | p99={p99:.1f}ms | err={errs}")
# СЕРИЯ 2: РОСТ РЕСУРСОВ (ПО 0.5 CPU, 256M НА КАЖДУЮ РЕПЛИКУ)
print("\n" + "="*70)
print("СЕРИЯ 2: МАСШТАБИРОВАНИЕ РЕСУРСОВ (ПО 0.5 CPU, 256MB НА РЕПЛИКУ)")
print("="*70)
scaled_plan = [
(1, 0.50, "256m"),
(2, 0.50, "256m"),
(4, 0.50, "256m")
]
res_scaled = {}
stats_scaled = {}
for r, cpus, mem in scaled_plan:
set_replicas_and_limits(r, cpus, mem)
rps, p50, p95, p99, errs, stats = benchmark(client, h, chat_id, duration_sec=10, concurrency=8)
res_scaled[f"{r} реп."] = rps
stats_scaled[r] = (rps, p50, p95, p99, errs, stats)
print(f"[{r} реп. (суммарно {r*0.5:.1f} CPU)]: {rps:.1f} RPS | p50={p50:.1f}ms | p99={p99:.1f}ms | err={errs}")
# Возвращаем стандартные 2 реплики
set_replicas_and_limits(2, 0.50, "256m")
print("\n" + "#"*70)
print("ИТОГОВЫЕ ТАБЛИЦЫ ДЛЯ REPORT.MD")
print("#"*70)
print("\n1. СЕРИЯ 1 (ФИКСИРОВАННЫЙ БЮДЖЕТ 1.0 CPU, 512MB RAM):")
print(f"{'Реплики':<10} | {'CPU на реп.':<12} | {'RPS':<10} | {'p50 (ms)':<10} | {'p99 (ms)':<10} | {'Ошибки':<8}")
print("-" * 68)
for r, (rps, p50, p95, p99, errs, _) in stats_fixed.items():
print(f"{r:<10} | {1.0/r:<12.2f} | {rps:<10.1f} | {p50:<10.1f} | {p99:<10.1f} | {errs:<8}")
print_ascii_chart("RPS при фиксированном суммарном бюджете (1.0 CPU)", res_fixed)
print("\n2. СЕРИЯ 2 (РОСТ РЕСУРСОВ: ПО 0.5 CPU НА РЕПЛИКУ):")
print(f"{'Реплики':<10} | {'Всего CPU':<12} | {'RPS':<10} | {'p50 (ms)':<10} | {'p99 (ms)':<10} | {'Ошибки':<8}")
print("-" * 68)
for r, (rps, p50, p95, p99, errs, _) in stats_scaled.items():
print(f"{r:<10} | {r*0.5:<12.1f} | {rps:<10.1f} | {p50:<10.1f} | {p99:<10.1f} | {errs:<8}")
print_ascii_chart("RPS при масштабировании ресурсов (+0.5 CPU на реплику)", res_scaled)
print("\n3. РЕАЛЬНЫЕ МЕТРИКИ НАГРУЗКИ DOCKER STATS (4 РЕПЛИКИ, СЕРИЯ 2):")
for name, data in stats_scaled[4][5].items():
print(f" - {name}: CPU = {data['cpu']}, Память = {data['mem']}")
if __name__ == "__main__":
main()