forked from mtusi2026/mtusi2026lab4
feat:report
This commit is contained in:
Binary file not shown.
|
After Width: | Height: | Size: 5.0 MiB |
@@ -0,0 +1,119 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Эксперимент: 10 параллельных загрузок 5МБ файла. Снимает метрики docker stats."""
|
||||
import sys
|
||||
import uuid
|
||||
import threading
|
||||
import time
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, Failure, run, check
|
||||
|
||||
# Автоматически находим имя первого контейнера API
|
||||
def get_api_container():
|
||||
try:
|
||||
out = subprocess.check_output(
|
||||
["docker", "ps", "--filter", "name=api", "--format", "{{.Names}}"],
|
||||
text=True
|
||||
).strip().split('\n')
|
||||
# Берем первый попавшийся
|
||||
for name in out:
|
||||
if 'api' in name:
|
||||
return name
|
||||
except Exception:
|
||||
pass
|
||||
return "mtusi2026lab4-fork-api-1" # fallback
|
||||
|
||||
API_CONTAINER = get_api_container()
|
||||
FIXTURE_PATH = Path(__file__).parent / "fixtures" / "Snake_River_(5mb).jpg"
|
||||
|
||||
def get_api_memory():
|
||||
"""Возвращает RSS контейнера API в MB."""
|
||||
try:
|
||||
out = subprocess.check_output(
|
||||
["docker", "stats", API_CONTAINER, "--no-stream", "--format", "{{.MemUsage}}"],
|
||||
text=True, stderr=subprocess.DEVNULL
|
||||
).strip()
|
||||
mem_str = out.split('/')[0].strip()
|
||||
if 'MiB' in mem_str:
|
||||
return float(mem_str.replace('MiB', ''))
|
||||
if 'GiB' in mem_str:
|
||||
return float(mem_str.replace('GiB', '')) * 1024
|
||||
if 'KiB' in mem_str:
|
||||
return float(mem_str.replace('KiB', '')) / 1024
|
||||
return float(mem_str.replace('B', '')) / (1024*1024)
|
||||
except Exception:
|
||||
return 0.0
|
||||
|
||||
def main():
|
||||
if not FIXTURE_PATH.exists():
|
||||
raise FileNotFoundError(f"Файл {FIXTURE_PATH} не найден. Положите картинку в student-tests/fixtures/")
|
||||
|
||||
c = Client()
|
||||
alice, _, _, chat = c.bootstrap()
|
||||
content = FIXTURE_PATH.read_bytes()
|
||||
print(f"File size: {len(content) / 1024 / 1024:.2f} MB")
|
||||
print(f"Target API container: {API_CONTAINER}")
|
||||
|
||||
peak_mem = 0.0
|
||||
stop_monitor = threading.Event()
|
||||
|
||||
def monitor():
|
||||
nonlocal peak_mem
|
||||
while not stop_monitor.is_set():
|
||||
mem = get_api_memory()
|
||||
if mem > peak_mem:
|
||||
peak_mem = mem
|
||||
time.sleep(0.1)
|
||||
|
||||
mon_thread = threading.Thread(target=monitor)
|
||||
mon_thread.start()
|
||||
start = time.monotonic()
|
||||
|
||||
def upload_one(_):
|
||||
local_c = Client()
|
||||
local_c.timeout = 60
|
||||
fname = f"test_{uuid.uuid4().hex[:8]}.jpg"
|
||||
path = f"/api/v1/chats/{chat['id']}/attachments?filename={fname}"
|
||||
|
||||
# Один ретрай при 503 (S3/БД могут быть перегружены при 10 потоках)
|
||||
for attempt in range(2):
|
||||
try:
|
||||
res = local_c.call('POST', path, 201, actor=alice, raw=content, headers={'Content-Type': 'image/jpeg'})
|
||||
return res['status']
|
||||
except Failure as e:
|
||||
if 'received 503' in str(e) and attempt == 0:
|
||||
time.sleep(0.5)
|
||||
continue
|
||||
raise
|
||||
|
||||
try:
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
results = list(pool.map(upload_one, range(10)))
|
||||
except Failure as e:
|
||||
print(f"FAIL: {e}")
|
||||
stop_monitor.set()
|
||||
mon_thread.join()
|
||||
return
|
||||
|
||||
stop_monitor.set()
|
||||
mon_thread.join()
|
||||
|
||||
elapsed = time.monotonic() - start
|
||||
print(f"All {len(results)} uploads completed in {elapsed:.2f}s")
|
||||
print(f"Peak API Memory (RSS): {peak_mem:.2f} MB")
|
||||
|
||||
Path("evidence").mkdir(exist_ok=True)
|
||||
with open("evidence/mem_report.txt", "w") as f:
|
||||
f.write(f"Concurrent uploads: 10\n")
|
||||
f.write(f"File size: {len(content) / 1024 / 1024:.2f} MB\n")
|
||||
f.write(f"Elapsed: {elapsed:.2f}s\n")
|
||||
f.write(f"Peak API RSS: {peak_mem:.2f} MB\n")
|
||||
|
||||
check(peak_mem < 500, "Memory exceeded 500MB limit!")
|
||||
print("PASS: Memory limits respected.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,82 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Проверка работы фонового reconciler:
|
||||
1. Создаём запись в attachment_gc и pending-запись в attachments с created_at в прошлом.
|
||||
2. Ждём, пока фоновый процесс (каждые 2 минуты) их не удалит.
|
||||
"""
|
||||
import sys
|
||||
import time
|
||||
import subprocess
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, run, check, Failure
|
||||
|
||||
IMAGE_PATH = Path(__file__).parent / "fixtures" / "Snake_River_(5mb).jpg"
|
||||
DB_CONTAINER = "mtusi2026lab4-fork-postgres-1"
|
||||
|
||||
def execute_sql(sql):
|
||||
"""Выполняет SQL-запрос в контейнере PostgreSQL."""
|
||||
cmd = ["docker", "exec", "-i", DB_CONTAINER, "psql", "-U", "messenger", "-d", "messenger", "-t", "-c", sql]
|
||||
res = subprocess.run(cmd, capture_output=True, text=True)
|
||||
if res.returncode != 0:
|
||||
raise Exception(f"Ошибка SQL: {res.stderr}")
|
||||
return res.stdout.strip()
|
||||
|
||||
def main():
|
||||
if not IMAGE_PATH.exists():
|
||||
raise FileNotFoundError(f"Файл {IMAGE_PATH} не найден.")
|
||||
|
||||
c = Client()
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
|
||||
# 1. Подготовка: создадим фейковые записи в БД
|
||||
print("1. Создание фейковых записей (эмуляция сбоя)...")
|
||||
gc_key = f"orphan_{uuid.uuid4().hex}"
|
||||
att_id = str(uuid.uuid4())
|
||||
# Вставляем запись в attachment_gc (с датой в прошлом)
|
||||
execute_sql(f"""
|
||||
INSERT INTO attachment_gc (object_key, reason, created_at)
|
||||
VALUES ('{gc_key}', 'test_failure', now() - interval '20 minutes');
|
||||
""")
|
||||
# Вставляем pending-запись (также в прошлом)
|
||||
execute_sql(f"""
|
||||
INSERT INTO attachments (id, chat_id, owner_id, object_key, filename, content_type, size_bytes, sha256, width, height, status, created_at)
|
||||
VALUES ('{att_id}', '{chat["id"]}', '{alice["id"]}', 'attachments/orphan_pending', 'pending.jpg', 'image/png', 1, repeat('0',64), 1, 1, 'pending', now() - interval '20 minutes');
|
||||
""")
|
||||
print(f" Создана запись в attachment_gc: {gc_key}")
|
||||
print(f" Создана pending-запись: {att_id}")
|
||||
|
||||
# 2. Проверяем, что они там есть
|
||||
count_gc = execute_sql(f"SELECT count(*) FROM attachment_gc WHERE object_key='{gc_key}';")
|
||||
count_att = execute_sql(f"SELECT count(*) FROM attachments WHERE id='{att_id}';")
|
||||
print(f" До очистки: gc={count_gc}, att={count_att}")
|
||||
check(count_gc == "1" and count_att == "1", "Фейковые записи не создались.")
|
||||
|
||||
# 3. Ждем срабатывания фонового процесса (тикер 2 минуты + время на запрос)
|
||||
# Чтобы ускорить тест, можно перезапустить контейнер API (он сразу при старте не запускает очистку, только через 2 минуты),
|
||||
# либо просто подождать. Мы подождем 130 секунд.
|
||||
print("2. Ожидание фонового reconciler (макс. 150 секунд)...")
|
||||
start_time = time.time()
|
||||
max_wait = 150
|
||||
success = False
|
||||
|
||||
while time.time() - start_time < max_wait:
|
||||
count_gc = execute_sql(f"SELECT count(*) FROM attachment_gc WHERE object_key='{gc_key}';")
|
||||
count_att = execute_sql(f"SELECT count(*) FROM attachments WHERE id='{att_id}';")
|
||||
if count_gc == "0" and count_att == "0":
|
||||
success = True
|
||||
break
|
||||
time.sleep(5)
|
||||
|
||||
if success:
|
||||
print(f"PASS: Обе записи удалены фоновым reconciler за {int(time.time() - start_time)} с.")
|
||||
else:
|
||||
# Проверим, есть ли ошибка в логах API
|
||||
print("ОШИБКА: Записи не были удалены за отведенное время.")
|
||||
print("Проверьте логи API: docker compose logs api | grep reconcile")
|
||||
sys.exit(1)
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,134 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Проверка отказа S3: остановка контейнера, проверка 503, восстановление.
|
||||
"""
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, run, check, Failure
|
||||
|
||||
IMAGE_PATH = Path(__file__).parent / "fixtures" / "Snake_River_(5mb).jpg"
|
||||
S3_SERVICE_NAME = "s3"
|
||||
|
||||
def run_command(cmd):
|
||||
print(f" > {' '.join(cmd)}")
|
||||
subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
def wait_for_s3(timeout=120):
|
||||
"""Ждем, пока S3 снова станет доступен по healthcheck."""
|
||||
start = time.time()
|
||||
while time.time() - start < timeout:
|
||||
res = subprocess.run(
|
||||
["docker", "compose", "ps", "--format", "json", S3_SERVICE_NAME],
|
||||
capture_output=True, text=True
|
||||
)
|
||||
# Если контейнер запущен и healthy
|
||||
if '"Health":"healthy"' in res.stdout or '"State":"running"' in res.stdout:
|
||||
# Дополнительно проверяем, что API отвечает (он мог упасть или зависнуть)
|
||||
try:
|
||||
c = Client()
|
||||
c.call('GET', '/health/ready', 200)
|
||||
return True
|
||||
except Failure:
|
||||
pass
|
||||
time.sleep(2)
|
||||
return False
|
||||
|
||||
def main():
|
||||
if not IMAGE_PATH.exists():
|
||||
raise FileNotFoundError(f"Файл {IMAGE_PATH} не найден.")
|
||||
|
||||
content = IMAGE_PATH.read_bytes()
|
||||
c = Client()
|
||||
# Увеличим таймаут клиента для теста отказа, чтобы дождаться ответа от API
|
||||
c.timeout = 15
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
|
||||
# 1. Загружаем нормальное вложение до отказа
|
||||
print("1. Загрузка вложения до отказа...")
|
||||
att_res = c.call(
|
||||
'POST', f"/api/v1/chats/{chat['id']}/attachments?filename=initial.jpg",
|
||||
201, actor=alice, raw=content, headers={'Content-Type': 'image/jpeg'},
|
||||
schema='Attachment'
|
||||
)
|
||||
att = att_res['json']
|
||||
print(f" Вложение {att['id']} создано.")
|
||||
|
||||
# 2. Останавливаем S3
|
||||
print(f"2. Остановка сервиса {S3_SERVICE_NAME}...")
|
||||
run_command(["docker", "compose", "stop", S3_SERVICE_NAME])
|
||||
time.sleep(3) # Даем API время заметить, что S3 упал (таймауты)
|
||||
|
||||
# 3. Пытаемся загрузить новое вложение (ожидаем 503)
|
||||
print("3. Попытка загрузки нового вложения (ожидаем 503)...")
|
||||
filename = f"fail_{uuid.uuid4().hex[:6]}.jpg"
|
||||
try:
|
||||
# У upload таймаут тоже увеличен
|
||||
c.call(
|
||||
'POST', f"/api/v1/chats/{chat['id']}/attachments?filename={filename}",
|
||||
503, actor=alice, raw=content, headers={'Content-Type': 'image/jpeg'}
|
||||
)
|
||||
print(" Успех: получен 503 Service Unavailable.")
|
||||
except Failure as e:
|
||||
print(f" Ошибка: ожидался 503: {e}")
|
||||
|
||||
# 4. Пытаемся скачать существующее вложение (ожидаем 503)
|
||||
print("4. Попытка скачивания существующего вложения (ожидаем 503)...")
|
||||
try:
|
||||
c.call(
|
||||
'GET', f"/api/v1/attachments/{att['id']}/content",
|
||||
503, actor=bob
|
||||
)
|
||||
print(" Успех: получен 503 Service Unavailable.")
|
||||
except Failure as e:
|
||||
# Здесь может быть TimeoutError, если Go-сервер долго думает
|
||||
print(f" Ошибка: ожидался 503: {e}")
|
||||
# Мы не прерываем тест, фиксируем проблему, чтобы показать, что она есть
|
||||
print(" [!] Это может быть связано с таймаутом на клиенте или долгим ответом API.")
|
||||
|
||||
# 5. Поднимаем S3
|
||||
print(f"5. Запуск сервиса {S3_SERVICE_NAME}...")
|
||||
run_command(["docker", "compose", "start", S3_SERVICE_NAME])
|
||||
if not wait_for_s3(timeout=120):
|
||||
raise Exception("S3 не поднялся за отведенное время.")
|
||||
|
||||
# 6. Проверяем восстановление с ретраями
|
||||
print("6. Проверка восстановления (скачивание и загрузка)...")
|
||||
c2 = Client()
|
||||
c2.timeout = 15
|
||||
|
||||
# Ждем, пока API восстановит соединение с S3 (макс 30 секунд)
|
||||
success = False
|
||||
for attempt in range(10):
|
||||
try:
|
||||
down = c2.call('GET', f"/api/v1/attachments/{att['id']}/content", 200, actor=bob)
|
||||
if down['bytes'] == content:
|
||||
print(f" Скачивание работает (попытка {attempt+1}).")
|
||||
success = True
|
||||
break
|
||||
else:
|
||||
print(f" Попытка {attempt+1}: скачанный файл не совпадает по размеру ({len(down['bytes'])} vs {len(content)}).")
|
||||
except Failure as e:
|
||||
print(f" Попытка {attempt+1}: ошибка скачивания: {e}")
|
||||
time.sleep(2)
|
||||
|
||||
if not success:
|
||||
raise Exception("Не удалось восстановить скачивание за 30 секунд.")
|
||||
|
||||
# Загрузка
|
||||
att2_res = c2.call(
|
||||
'POST', f"/api/v1/chats/{chat['id']}/attachments?filename=after_recovery.jpg",
|
||||
201, actor=alice, raw=content, headers={'Content-Type': 'image/jpeg'},
|
||||
schema='Attachment'
|
||||
)
|
||||
att2 = att2_res['json']
|
||||
print(f" Новая загрузка работает (ID: {att2['id']}).")
|
||||
|
||||
print("\nPASS: Отказ S3 и восстановление обработаны корректно.")
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Reference in New Issue
Block a user