ЛР3 — БВТ2302 — Никитина — на 5

This commit is contained in:
Yuliiiaaaa
2026-11-03 12:37:56 +03:00
parent 0ab3a341aa
commit dacbdd8b29
21 changed files with 1138 additions and 48 deletions
+93
View File
@@ -0,0 +1,93 @@
#!/usr/bin/env python3
"""Failover test for lab3: hits API concurrently, kills one replica, checks survival."""
import argparse
import subprocess
import sys
import threading
import time
import uuid
from client import Client, Failure, run, check
def main():
ap = argparse.ArgumentParser()
ap.add_argument('--base-url', default='http://localhost:8080')
ap.add_argument('--action-script', required=True)
args = ap.parse_args()
c = Client(args.base_url)
alice, bob, eve, chat = c.bootstrap()
path = '/api/v1/chats/' + chat['id']
instances = set()
messages = []
errors = 0
# 1. Собираем имена реплик (X-Instance-Id)
for _ in range(10):
r = c.call('GET', '/health/live')
instances.add(r['headers'].get('X-Instance-Id'))
time.sleep(0.05)
check(len(instances) >= 2, 'Expected at least 2 API replicas, got: ' + str(instances))
print('Observed replicas:', instances)
# 2. Запускаем фоновую нагрузку
stop_event = threading.Event()
def sender(thread_id):
nonlocal errors
local_c = Client(args.base_url, timeout=5)
i = 0
while not stop_event.is_set():
key = uuid.uuid4().hex
text = f'msg_{thread_id}_{i}'
try:
r = local_c.message(alice, chat, text, key=key)
messages.append(r['json']['id'])
instances.add(r['headers'].get('X-Instance-Id'))
except Failure:
# Во время отказа запросы могут падать. Повторяем с тем же ключом.
try:
time.sleep(0.1)
r = local_c.message(alice, chat, text, key=key)
messages.append(r['json']['id'])
except Failure:
errors += 1
i += 1
time.sleep(0.02)
threads = [threading.Thread(target=sender, args=(t,)) for t in range(4)]
for t in threads: t.start()
time.sleep(1) # Даем нагрузке раскрутиться
# 3. Запускаем скрипт остановки реплики
print(f'Running action script: {args.action_script}')
subprocess.run(args.action_script, shell=True, check=True)
# 4. Ждем восстановления и останавливаем нагрузку
time.sleep(4)
stop_event.set()
for t in threads: t.join()
# 5. Проверяем, что история не потерялась и нет дублей
history_ids = []
cursor = None
while True:
q = path + '/messages?limit=100'
if cursor: q += '&cursor=' + cursor
page = c.call('GET', q, actor=alice, schema='MessagePage')['json']
for m in page['items']:
history_ids.append(m['id'])
cursor = page['next_cursor']
if not cursor: break
check(len(set(history_ids)) == len(history_ids), 'Duplicate messages found!')
check(len(messages) > 0, 'No messages were successfully sent')
print(f'Success! Replicas used: {len(instances)}, Messages sent: {len(messages)}, Network errors (retried safely): {errors}')
print('PASS: failover verified')
if __name__ == '__main__':
run(main)
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env python3
import http.client
import json
import threading
import time
import uuid
BASE_URL = "127.0.0.1"
PORT = 8080
def worker(token, chat_id, duration, stats):
# Каждый поток открывает ОДНО соединение и шлет по нему много запросов
conn = http.client.HTTPConnection(BASE_URL, PORT)
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
end_time = time.time() + duration
while time.time() < end_time:
headers["Idempotency-Key"] = uuid.uuid4().hex
body = json.dumps({"text": "load-test"})
try:
conn.request("POST", f"/api/v1/chats/{chat_id}/messages", body=body, headers=headers)
resp = conn.getresponse()
resp.read()
if resp.status == 201:
stats['success'] += 1
else:
stats['error'] += 1
except Exception:
stats['error'] += 1
conn = http.client.HTTPConnection(BASE_URL, PORT) # Переподключение при ошибке
def main():
# 1. Подготовка (регистрация, логин, создание чата)
# Для простоты используем готовый tests/client.py
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from client import Client
c = Client("http://127.0.0.1:8080")
alice, bob, eve, chat = c.bootstrap()
token = alice['token']
# 2. Запуск нагрузки
duration = 20
num_threads = 20
stats = {'success': 0, 'error': 0}
threads = [threading.Thread(target=worker, args=(token, chat['id'], duration, stats)) for _ in range(num_threads)]
print(f"Starting load: {num_threads} threads for {duration}s...")
start_time = time.time()
for t in threads: t.start()
for t in threads: t.join()
elapsed = time.time() - start_time
rps = stats['success'] / elapsed
print(f"RESULT: RPS={rps:.2f}, Success={stats['success']}, Errors={stats['error']}")
if __name__ == '__main__':
main()