forked from mtusi2026/mtusi2026lab7
feat: core func lab7
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Останавливает API-реплики по очереди и проверяет сохранность данных."""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def docker_output(*args):
|
||||
return subprocess.check_output(["docker", *args], cwd=ROOT, text=True).strip()
|
||||
|
||||
|
||||
def call_during_failover(client, deadline, method, path, status=200, **kwargs):
|
||||
while True:
|
||||
result = client.call(method, path, [status, 503], **kwargs)
|
||||
if result["status"] == status:
|
||||
return result
|
||||
check(result["headers"]["X-Instance-Id"] == "nginx", "API вернул 503 при живой реплике")
|
||||
check(time.monotonic() < deadline, "Балансировщик не восстановил запросы за 10 с")
|
||||
time.sleep(0.2)
|
||||
|
||||
|
||||
def check_replicas(client):
|
||||
containers = docker_output("compose", "ps", "-q", "api").splitlines()
|
||||
check(len(containers) >= 2, "Для проверки должны работать минимум две реплики")
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
original = client.message(alice, chat, "Сообщение до остановки реплик")["json"]
|
||||
attachment, content = client.attachment(alice, chat)
|
||||
client.wait_ready(alice, attachment)
|
||||
content_path = f"/api/v1/attachments/{attachment['id']}/content"
|
||||
confirmed = [original]
|
||||
|
||||
for index, container in enumerate(containers, start=1):
|
||||
instance = docker_output("exec", container, "cat", "/tmp/instance-id")
|
||||
check(bool(instance), "Реплика не сообщила X-Instance-Id")
|
||||
key = uuid.uuid4().hex
|
||||
text = f"Запись при остановке реплики {index}"
|
||||
started = time.monotonic()
|
||||
try:
|
||||
subprocess.run(
|
||||
["./scripts/stop-one.sh"],
|
||||
cwd=ROOT,
|
||||
env={**os.environ, "TARGET_INSTANCE_ID": instance},
|
||||
check=True,
|
||||
timeout=10,
|
||||
)
|
||||
running = docker_output("inspect", "--format", "{{.State.Running}}", container)
|
||||
check(running == "false", "Выбранный контейнер остался запущен")
|
||||
deadline = started + 10
|
||||
messages_path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
result = call_during_failover(
|
||||
client, deadline, "POST", messages_path, 201, actor=alice,
|
||||
body={"text": text}, headers={"Idempotency-Key": key}, schema="Message",
|
||||
)
|
||||
elapsed = time.monotonic() - started
|
||||
check(elapsed <= 10, "Запись восстановилась позже 10 с")
|
||||
check(result["headers"]["X-Instance-Id"] != instance, "Ответ от остановленной реплики")
|
||||
confirmed.append(result["json"])
|
||||
call_during_failover(client, deadline, "GET", "/api/v1/users/me", actor=bob, schema="User")
|
||||
downloaded = call_during_failover(client, deadline, "GET", content_path, actor=bob)
|
||||
check(downloaded["bytes"] == content, "Вложение изменилось или пропало")
|
||||
page = call_during_failover(
|
||||
client, deadline, "GET", messages_path + "?limit=100", actor=bob, schema="MessagePage"
|
||||
)
|
||||
messages = page["json"]["items"]
|
||||
check(all(item in messages for item in confirmed), "Подтверждённое сообщение потеряно")
|
||||
check(len({item["id"] for item in messages}) == len(messages), "Повтор записи")
|
||||
print(f"PASS: остановлена реплика {index}/{len(containers)}, запись через "
|
||||
f"{elapsed:.2f} с, сессия и вложение сохранены", flush=True)
|
||||
finally:
|
||||
subprocess.run(["./scripts/restore.sh"], cwd=ROOT, check=True, timeout=70)
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments(__doc__)
|
||||
check_replicas(Client(args.base_url, args.ca_file, timeout=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user