forked from mtusi2026/mtusi2026lab5
Complete Lab 5 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,2 @@
|
||||
@echo off
|
||||
docker compose stop worker
|
||||
@@ -0,0 +1,2 @@
|
||||
#!/bin/sh
|
||||
docker compose stop worker
|
||||
@@ -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()
|
||||
@@ -0,0 +1,104 @@
|
||||
import base64
|
||||
import io
|
||||
import time
|
||||
import subprocess
|
||||
import uuid
|
||||
import httpx
|
||||
from PIL import Image
|
||||
|
||||
BASE_URL = "http://localhost:8080"
|
||||
|
||||
def get_client():
|
||||
return httpx.Client(base_url=BASE_URL, trust_env=False, timeout=20.0)
|
||||
|
||||
def auth_user(client, username):
|
||||
pw = "super_password_12345"
|
||||
client.post("/users", json={"username": username, "display_name": "Fault Test", "password": pw})
|
||||
b64 = base64.b64encode(f"{username}:{pw}".encode()).decode()
|
||||
res = client.post("/auth/sessions", headers={"Authorization": f"Basic {b64}"})
|
||||
return res.json()["token"], res.json()["user"]["id"]
|
||||
|
||||
def make_png():
|
||||
img = Image.new("RGB", (320, 200), (50, 100, 150))
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, format="PNG")
|
||||
return buf.getvalue()
|
||||
|
||||
def wait_for_api():
|
||||
with get_client() as c:
|
||||
for _ in range(30):
|
||||
try:
|
||||
if c.get("/health/ready").status_code == 200:
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
|
||||
def wait_for_ready(client, h, att_id, timeout=30):
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
r = client.get(f"/attachments/{att_id}", headers=h)
|
||||
if r.status_code == 200 and r.json()["status"] == "ready":
|
||||
return r.json()
|
||||
time.sleep(0.5)
|
||||
raise AssertionError(f"Attachment {att_id} did not reach ready in {timeout}s")
|
||||
|
||||
def main():
|
||||
print("=== ПРОВЕРКА СЦЕНАРИЕВ ОТКАЗОВ УРОВНЯ 4 ===")
|
||||
with get_client() as client:
|
||||
ts = int(time.time() * 1000)
|
||||
token, uid = auth_user(client, f"u_fault_{ts}")
|
||||
h = {"Authorization": f"Bearer {token}"}
|
||||
chat_id = client.post("/chats", json={"title": "Fault Chat", "member_ids": [uid]}, headers=h).json()["id"]
|
||||
png_data = make_png()
|
||||
|
||||
# --- СЦЕНАРИЙ 1: Остановка worker + 409 на content + рестарт API/broker ---
|
||||
print("\n[Сценарий 1] Остановка worker...")
|
||||
subprocess.run(["docker", "compose", "stop", "worker"], check=True)
|
||||
|
||||
up1 = client.post(f"/chats/{chat_id}/attachments?filename=stopped_w.png", content=png_data, headers={**h, "Content-Type": "image/png"})
|
||||
assert up1.status_code == 202
|
||||
att1_id = up1.json()["id"]
|
||||
print(f" Загрузка при мёртвом worker -> 202 queued (ID: {att1_id})")
|
||||
|
||||
# Контент должен отвечать 409 Conflict
|
||||
cont = client.get(f"/attachments/{att1_id}/content", headers=h)
|
||||
assert cont.status_code == 409, f"Ожидался 409, получен {cont.status_code}"
|
||||
print(f" GET /content при queued -> {cont.status_code} Conflict (верно!)")
|
||||
|
||||
# Сообщения продолжают работать
|
||||
msg = client.post(f"/chats/{chat_id}/messages", json={"text": "Работаем без worker", "attachment_ids": [att1_id]}, headers={**h, "Idempotency-Key": str(uuid.uuid4())})
|
||||
assert msg.status_code == 201
|
||||
print(" Отправка сообщения с queued-вложением -> 201 Created (верно!)")
|
||||
|
||||
# Рестарт API и брокера, затем запуск worker
|
||||
print(" Перезапуск API и RabbitMQ broker...")
|
||||
subprocess.run(["docker", "compose", "restart", "api", "broker"], check=True)
|
||||
wait_for_api()
|
||||
print(" Запуск worker...")
|
||||
subprocess.run(["docker", "compose", "start", "worker"], check=True)
|
||||
|
||||
ready1 = wait_for_ready(client, h, att1_id)
|
||||
print(f" УСПЕХ! Вложение {att1_id} перешло в статус '{ready1['status']}' с {len(ready1['variants'])} вариантами!")
|
||||
|
||||
# --- СЦЕНАРИЙ 2: Разрыв COMMIT и publish (Outbox при недоступном брокере) ---
|
||||
print("\n[Сценарий 2] Симуляция разрыва COMMIT -> publish (остановка broker)...")
|
||||
subprocess.run(["docker", "compose", "stop", "broker"], check=True)
|
||||
|
||||
up2 = client.post(f"/chats/{chat_id}/attachments?filename=outbox_test.png", content=png_data, headers={**h, "Content-Type": "image/png"})
|
||||
assert up2.status_code == 202
|
||||
att2_id = up2.json()["id"]
|
||||
print(f" Загрузка при упавшем брокере -> 202 queued (ID: {att2_id}, сохранено в Outbox!)")
|
||||
|
||||
print(" Восстановление RabbitMQ broker и перезапуск worker...")
|
||||
subprocess.run(["docker", "compose", "start", "broker"], check=True)
|
||||
time.sleep(5)
|
||||
subprocess.run(["docker", "compose", "restart", "worker"], check=True)
|
||||
|
||||
ready2 = wait_for_ready(client, h, att2_id, timeout=30)
|
||||
print(f" УСПЕХ! Outbox Relay доставил задачу, вложение {att2_id} стало '{ready2['status']}'!")
|
||||
|
||||
print("\n>>> ВСЕ СЦЕНАРИИ СБОЕВ УРОВНЯ 4 ПРОЙДЕНЫ БЕЗ ЕДИНОЙ ПОТЕРИ!")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,81 @@
|
||||
import asyncio
|
||||
import base64
|
||||
import io
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
import asyncpg
|
||||
import httpx
|
||||
from PIL import Image
|
||||
|
||||
DB_URL = open("/run/secrets/database_url").read().strip() if os.path.exists("/run/secrets/database_url") else "postgresql://appuser:apppassword@postgres:5432/messenger_db"
|
||||
BASE_URL = "http://load_balancer:8080"
|
||||
|
||||
def make_png():
|
||||
img = Image.new("RGB", (320, 200), (80, 120, 200))
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, format="PNG")
|
||||
return buf.getvalue()
|
||||
|
||||
async def wait_ready(client, h, att_id, timeout=20):
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
r = await client.get(f"/attachments/{att_id}", headers=h)
|
||||
if r.status_code == 200 and r.json()["status"] == "ready":
|
||||
return r.json()
|
||||
await asyncio.sleep(0.5)
|
||||
raise AssertionError("Did not become ready")
|
||||
|
||||
async def main():
|
||||
print("=== ПРОВЕРКА REPLAY FAILED И LEASE RECOVERY (CRASH ДО ACK) ===")
|
||||
conn = await asyncpg.connect(DB_URL)
|
||||
|
||||
async with httpx.AsyncClient(base_url=BASE_URL, timeout=15.0) as client:
|
||||
ts = int(time.time() * 1000)
|
||||
uname = f"u_rep_{ts}"
|
||||
pw = "super_password_12345"
|
||||
await client.post("/users", json={"username": uname, "display_name": "Replay", "password": pw})
|
||||
b64 = base64.b64encode(f"{uname}:{pw}".encode()).decode()
|
||||
login = (await client.post("/auth/sessions", headers={"Authorization": f"Basic {b64}"})).json()
|
||||
token, uid = login["token"], login["user"]["id"]
|
||||
h = {"Authorization": f"Bearer {token}"}
|
||||
chat_id = (await client.post("/chats", json={"title": "Replay Chat", "member_ids": [uid]}, headers=h)).json()["id"]
|
||||
|
||||
# Загружаем вложение и ждём первичного ready
|
||||
up = await client.post(f"/chats/{chat_id}/attachments?filename=rep.png", content=make_png(), headers={**h, "Content-Type": "image/png"})
|
||||
att_id = up.json()["id"]
|
||||
await wait_ready(client, h, att_id)
|
||||
print(f"Подготовлено вложение: {att_id}")
|
||||
|
||||
# 1. Тест REPLAY FAILED
|
||||
print("\n[Тест 1] Имитация failed -> операторский replay -> ready...")
|
||||
await conn.execute("UPDATE attachments SET status='failed', error_code='processing_failed' WHERE id=$1", uuid.UUID(att_id))
|
||||
await conn.execute("UPDATE attachment_jobs SET status='failed', last_error_code='processing_failed' WHERE attachment_id=$1", uuid.UUID(att_id))
|
||||
|
||||
rep_res = await client.post(f"/internal/attachments/{att_id}/replay")
|
||||
assert rep_res.status_code == 200 and rep_res.json()["replayed"] is True
|
||||
print(f" Вызов /replay вернул: {rep_res.json()}")
|
||||
|
||||
ready1 = await wait_ready(client, h, att_id)
|
||||
assert len(ready1["variants"]) == 3
|
||||
print(f" УСПЕХ! После replay статус снова 'ready', вариантов ровно {len(ready1['variants'])}.")
|
||||
|
||||
# 2. Тест CRASH ПОСЛЕ S3 ДО ACK / LEASE RECOVERY
|
||||
print("\n[Тест 2] Имитация зависшего processing (объекты в S3 уже есть, lease истек)...")
|
||||
await conn.execute("UPDATE attachments SET status='processing' WHERE id=$1", uuid.UUID(att_id))
|
||||
await conn.execute(
|
||||
"UPDATE attachment_jobs SET status='processing', locked_until = NOW() - interval '5 seconds', outbox_published = TRUE WHERE attachment_id=$1",
|
||||
uuid.UUID(att_id)
|
||||
)
|
||||
print(" Lease просрочен -> ожидаем автоматический возврат в очередь и идемпотентную обработку...")
|
||||
ready2 = await wait_ready(client, h, att_id)
|
||||
assert len(ready2["variants"]) == 3
|
||||
v_count = await conn.fetchval("SELECT count(*) FROM attachment_variants WHERE attachment_id=$1", uuid.UUID(att_id))
|
||||
assert v_count == 3, f"Найдены дубликаты вариантов: {v_count}"
|
||||
print(f" УСПЕХ! Lease восстановлен, повторная доставка завершилась 'ready', вариантов в БД ровно {v_count} (дубликатов нет!).")
|
||||
|
||||
await conn.close()
|
||||
print("\n>>> ВСЕ ПРОВЕРКИ УРОВНЯ 4 ЗАВЕРШЕНЫ!")
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
Reference in New Issue
Block a user