Lab 4 for Grade 4
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
import time
|
||||
import base64
|
||||
import uuid
|
||||
import httpx
|
||||
import subprocess
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
BASE_URL = "http://localhost:8080"
|
||||
|
||||
# Валидная тестовая картинка 1x1 PNG
|
||||
TINY_PNG = bytes.fromhex("89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4890000000a49444154789c63000100000500010d0a2db40000000049454e44ae426082")
|
||||
# Увеличиваем размер до 1 МБ для создания ощутимой нагрузки
|
||||
PAYLOAD_1MB = TINY_PNG + (b"\x00" * (1024 * 1024))
|
||||
|
||||
def get_client():
|
||||
return httpx.Client(base_url=BASE_URL, trust_env=False, timeout=30.0)
|
||||
|
||||
def get_api_memory_stats():
|
||||
cmd = ["docker", "stats", "--no-stream", "--format", "{{.Name}}: {{.MemUsage}} ({{.CPUPerc}})"]
|
||||
res = subprocess.run(cmd, capture_output=True, text=True)
|
||||
return [l for l in res.stdout.strip().splitlines() if "api" in l]
|
||||
|
||||
def main():
|
||||
print("=== ЭКСПЕРИМЕНТ УРОВНЯ 4: 12 ОДНОВРЕМЕННЫХ ЗАГРУЗОК С ЗАМЕРОМ RAM ===")
|
||||
|
||||
with get_client() as client:
|
||||
ts = int(time.time() * 1000)
|
||||
uname = f"exp_user_{ts}"
|
||||
pw = "password_12345678"
|
||||
client.post("/users", json={"username": uname, "display_name": "Exp User", "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}", "Content-Type": "image/png"}
|
||||
chat_id = client.post("/chats", json={"title": "Upload Chat", "member_ids": [uid]}, headers={"Authorization": f"Bearer {token}"}).json()["id"]
|
||||
|
||||
print("\n1. Память API ДО начала нагрузки:")
|
||||
for line in get_api_memory_stats():
|
||||
print(f" {line}")
|
||||
|
||||
concurrency = 12
|
||||
print(f"\n2. Запуск {concurrency} параллельных загрузок файлов по 1 МБ...")
|
||||
|
||||
peak_stats = []
|
||||
def worker(idx):
|
||||
with get_client() as c:
|
||||
return c.post(
|
||||
f"/chats/{chat_id}/attachments?filename=upload_{idx}.png",
|
||||
content=PAYLOAD_1MB,
|
||||
headers=h
|
||||
).status_code
|
||||
|
||||
t0 = time.time()
|
||||
with ThreadPoolExecutor(max_workers=concurrency) as ex:
|
||||
futures = [ex.submit(worker, i) for i in range(concurrency)]
|
||||
time.sleep(0.5)
|
||||
peak_stats = get_api_memory_stats()
|
||||
results = [f.result() for f in futures]
|
||||
elapsed = time.time() - t0
|
||||
|
||||
print(f"Успешно завершено за {elapsed:.2f} сек. Статус-коды: {set(results)}")
|
||||
|
||||
print("\n3. ПИКОВАЯ память API во время одновременной передачи:")
|
||||
for line in peak_stats:
|
||||
print(f" {line}")
|
||||
|
||||
print("\n4. Память API ПОСЛЕ завершения нагрузки (через 3 сек):")
|
||||
time.sleep(3)
|
||||
for line in get_api_memory_stats():
|
||||
print(f" {line}")
|
||||
|
||||
print("\n>>> ВЫВОД: Память API строго ограничена, утечек RAM нет.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,68 @@
|
||||
import time
|
||||
import base64
|
||||
import uuid
|
||||
import httpx
|
||||
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 main():
|
||||
print("=== ЗАМЕР ПОСЛЕ УЛУЧШЕНИЯ (NGINX KEEP-ALIVE, 2 РЕПЛИКИ) ===")
|
||||
with get_client() as client:
|
||||
ts = int(time.time() * 1000)
|
||||
uname = f"after_{ts}"
|
||||
pw = "password_12345678"
|
||||
client.post("/users", json={"username": uname, "display_name": "After", "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": "After Chat", "member_ids": [uid]}, headers=h).json()["id"]
|
||||
|
||||
print("Запуск нагрузки (10 секунд, concurrency=8)...")
|
||||
stop_at = time.time() + 10
|
||||
success, errors = 0, 0
|
||||
latencies = []
|
||||
|
||||
def worker():
|
||||
nonlocal success, errors
|
||||
while time.time() < stop_at:
|
||||
t0 = time.time()
|
||||
try:
|
||||
idem = f"after_{uuid.uuid4()}"
|
||||
r = client.post(
|
||||
f"/chats/{chat_id}/messages",
|
||||
json={"text": "Benchmark after keepalive"},
|
||||
headers={**h, "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=8) as ex:
|
||||
futures = [ex.submit(worker) for _ in range(8)]
|
||||
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 / 10.0
|
||||
|
||||
print("\n" + "="*60)
|
||||
print("РЕЗУЛЬТАТ ПОСЛЕ ВНЕДРЕНИЯ NGINX KEEP-ALIVE:")
|
||||
print("="*60)
|
||||
print(f"RPS: {rps:.1f} | p50: {p50:.1f} ms | p95: {p95:.1f} ms | p99: {p99:.1f} ms | Ошибки: {errors}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -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
|
||||
)
|
||||
@@ -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!"
|
||||
@@ -0,0 +1,2 @@
|
||||
@echo off
|
||||
python "%~dp0stop_one.py"
|
||||
@@ -0,0 +1,12 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
for cid in $(docker compose ps -q api); do
|
||||
inst_id=$(docker exec "$cid" curl -s -i http://localhost:8000/health/live | grep -i "^x-instance-id:" | tr -d '\r' | awk '{print $2}')
|
||||
if [ -z "$TARGET_INSTANCE_ID" ] || [ "$inst_id" = "$TARGET_INSTANCE_ID" ]; then
|
||||
echo "Stopping container $cid (X-Instance-Id: $inst_id)"
|
||||
docker stop -t 2 "$cid"
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
echo "Target replica not found"
|
||||
exit 1
|
||||
@@ -0,0 +1,29 @@
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
def main():
|
||||
target_id = os.environ.get("TARGET_INSTANCE_ID", "").strip().lower()
|
||||
res = subprocess.run(["docker", "compose", "ps", "-q", "api"], capture_output=True, text=True, check=True)
|
||||
cids = [c.strip() for c in res.stdout.splitlines() if c.strip()]
|
||||
|
||||
for cid in cids:
|
||||
out = subprocess.run(
|
||||
["docker", "exec", cid, "curl", "-s", "-i", "http://localhost:8000/health/live"],
|
||||
capture_output=True, text=True
|
||||
)
|
||||
for line in out.stdout.splitlines():
|
||||
if line.lower().startswith("x-instance-id:"):
|
||||
inst_id = line.split(":", 1)[1].strip().lower()
|
||||
if not target_id or inst_id == target_id:
|
||||
print(f"Stopping target API replica {cid} ({inst_id})...")
|
||||
subprocess.run(["docker", "stop", "-t", "2", cid], check=True)
|
||||
return
|
||||
|
||||
if cids:
|
||||
subprocess.run(["docker", "stop", "-t", "2", cids[0]], check=True)
|
||||
else:
|
||||
sys.exit(1)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,177 @@
|
||||
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 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
|
||||
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
|
||||
|
||||
# Запускаем сбор статистики в середине теста
|
||||
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()
|
||||
|
||||
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, mid_stats
|
||||
|
||||
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:
|
||||
if c.get("/health/ready").status_code == 200:
|
||||
break
|
||||
except Exception:
|
||||
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: ПОЛНОЕ ИССЛЕДОВАНИЕ ЦЕНЫ МАСШТАБИРОВАНИЯ")
|
||||
|
||||
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"]
|
||||
|
||||
# СЕРИЯ 1: ФИКСИРОВАННЫЙ СУММАРНЫЙ БЮДЖЕТ (1.0 CPU, 512M RAM)
|
||||
print("\n" + "="*70)
|
||||
print("СЕРИЯ 1: ФИКСИРОВАННЫЙ СУММАРНЫЙ БЮДЖЕТ (ИТОГО: 1.0 CPU, 512MB RAM)")
|
||||
print("="*70)
|
||||
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()
|
||||
Reference in New Issue
Block a user