Files
mtusi2026lab4/student-tests/failover_series.py
T
RainakandClaude Opus 5.5 2dca5c114b ЛР4 БВТ2304 Запорожец на 3
Вложения: приватный S3-bucket (RustFS 1.0.4) + метаданные в PostgreSQL, upload PNG/JPEG
с лимитами до декодирования, авторизованный download, attachment_ids в сообщениях,
идемпотентный bootstrap bucket, failover/persistence/S3-down тесты и REPORT.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 18:49:12 +03:00

313 lines
15 KiB
Python
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Серии отказов под нагрузкой (уровень 4): RPS, ошибки, время обнаружения и восстановления.
Запускается на ХОСТЕ из корня репозитория (нужны docker CLI и, для rolling, compose с bind-путями):
python student-tests/failover_series.py --scenario stop # graceful stop каждой реплики по очереди
python student-tests/failover_series.py --scenario kill # SIGKILL каждой реплики по очереди
python student-tests/failover_series.py --scenario rolling # scripts/rolling-update.sh под нагрузкой
Нагрузка closed-loop: W писателей (POST сообщения; неопределённый результат повторяется с ТЕМ ЖЕ ключом,
как в tests/resilience.py) и R читателей (GET истории). Параллельно раз в 200 мс опрашивается
CSV-статистика HAProxy: когда слот целевой реплики перестал быть UP — это время обнаружения отказа LB.
После серии проверяется, что все подтверждённые сообщения на месте и нет дублей.
Токены остаются в памяти процесса; в отчёт попадают только агрегаты.
"""
import argparse
import csv
import io
import json
import math
import os
import subprocess
import sys
import threading
import time
import urllib.parse
import urllib.request
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, check # noqa: E402
PROJECT = 'mtusi-lab4'
EDGE_NETWORK = PROJECT + '_edge'
API_FILTER = ['--filter', f'label=com.docker.compose.project={PROJECT}',
'--filter', 'label=com.docker.compose.service=api']
def docker(*args: str) -> str:
return subprocess.run(['docker', *args], check=True, text=True, capture_output=True).stdout.strip()
def api_containers() -> list[str]:
names = docker('ps', *API_FILTER, '--format', '{{.Names}}').split()
return sorted(names)
def container_info(name: str) -> dict:
fmt = ('{{.Config.Hostname}}|{{index .Config.Labels "org.opencontainers.image.revision"}}|'
'{{(index .NetworkSettings.Networks "%s").IPAddress}}') % EDGE_NETWORK
hostname, revision, ip = docker('inspect', '-f', fmt, name).split('|')
return {'name': name, 'hostname': hostname, 'revision': revision, 'ip': ip}
def percentile(values: list[float], p: float):
values = sorted(values)
return round(1000 * values[max(0, math.ceil(p * len(values)) - 1)], 1) if values else None
class LbWatcher(threading.Thread):
"""Опрос /stats;csv: состояние слотов backend `api` и счётчики retry/redispatch."""
def __init__(self, stats_url: str, t0: float):
super().__init__(daemon=True)
self.url = stats_url.rstrip('/') + ';csv'
self.t0 = t0
self.stop_flag = threading.Event()
self.samples = [] # (t, {addr: status})
self.first = self.last = None
def snapshot(self):
with urllib.request.urlopen(self.url, timeout=1) as r:
rows = list(csv.DictReader(io.StringIO(r.read().decode().lstrip('# '))))
servers = {row['addr']: row['status'] for row in rows
if row['pxname'] == 'api' and row['svname'] not in ('FRONTEND', 'BACKEND') and row.get('addr')}
backend = next(row for row in rows if row['pxname'] == 'api' and row['svname'] == 'BACKEND')
return servers, {'retries': int(backend['wretr'] or 0), 'redispatches': int(backend['wredis'] or 0)}
def run(self):
while not self.stop_flag.is_set():
try:
servers, counters = self.snapshot()
self.samples.append((time.monotonic() - self.t0, servers))
self.first = self.first or counters
self.last = counters
except Exception: # LB-статистика — вспомогательная, не влияет на результат серии
pass
time.sleep(0.2)
def first_not_up(self, ip: str, after: float):
"""Первый момент после `after`, когда слот с этим IP не UP (DOWN/MAINT/исчез из DNS)."""
addr = ip + ':8080'
for t, servers in self.samples:
if t >= after and not servers.get(addr, 'MISSING').startswith('UP'):
return round(t - after, 3), servers.get(addr, 'removed from DNS')
return None, None
def run_probe(base_url: str, stats_url: str, action, targets: list[dict], duration: float,
action_at: float, writers: int, readers: int) -> dict:
c = Client(base_url)
alice, bob, _eve, chat = c.bootstrap()
events = [] # (t, kind, ok, instance, latency)
confirmed = [] # подтверждённые сообщения
lock = threading.Lock()
retries_with_same_key = [0]
t0 = time.monotonic()
deadline = t0 + duration
watcher = LbWatcher(stats_url, t0)
watcher.start()
def record(kind, ok, instance, latency):
with lock:
events.append((time.monotonic() - t0, kind, ok, instance, latency))
def writer(i):
local = Client(base_url, timeout=3)
key, n = uuid.uuid4().hex, 0
text = f'probe-{i}-{n}'
while time.monotonic() < deadline:
start = time.monotonic()
try:
r = local.message(alice, chat, text, key=key)
record('write', True, r['headers'].get('X-Instance-Id', ''), time.monotonic() - start)
with lock:
confirmed.append(r['json'])
n += 1
key, text = uuid.uuid4().hex, f'probe-{i}-{n}'
except Failure:
record('write', False, '', time.monotonic() - start)
with lock:
retries_with_same_key[0] += 1
time.sleep(0.05) # тот же key и тот же body при следующей попытке
def reader(_i):
local = Client(base_url, timeout=3)
path = f"/api/v1/chats/{chat['id']}/messages?limit=20"
while time.monotonic() < deadline:
start = time.monotonic()
try:
r = local.call('GET', path, actor=bob, schema='MessagePage')
record('read', True, r['headers'].get('X-Instance-Id', ''), time.monotonic() - start)
except Failure:
record('read', False, '', time.monotonic() - start)
time.sleep(0.05)
threads = [threading.Thread(target=writer, args=(i,)) for i in range(writers)]
threads += [threading.Thread(target=reader, args=(i,)) for i in range(readers)]
for t in threads:
t.start()
time.sleep(max(0.0, t0 + action_at - time.monotonic()))
a_start = time.monotonic() - t0
action_output = action()
a_end = time.monotonic() - t0
for t in threads:
t.join()
watcher.stop_flag.set()
watcher.join()
# Сохранность: тот же токен, полная история через LB, без дублей.
history, cursor = [], None
while True:
path = f"/api/v1/chats/{chat['id']}/messages?limit=100" + (f'&cursor={urllib.parse.quote(cursor, safe="")}' if cursor else '')
page = c.call('GET', path, actor=bob, schema='MessagePage')['json']
history += page['items']
cursor = page['next_cursor']
if cursor is None:
break
ids = {m['id'] for m in history}
texts = [m['text'] for m in history]
lost = sum(1 for m in confirmed if m['id'] not in ids)
check(len(ids) == len(history), 'duplicated message id in history')
check(len(texts) == len(set(texts)), 'retry with same key produced a duplicate message')
check(lost == 0, f'{lost} confirmed messages lost')
def window(lo, hi):
sel = [e for e in events if lo <= e[0] < hi]
ok = [e for e in sel if e[2]]
span = max(hi - lo, 1e-9)
return {'seconds': round(span, 2), 'ok_rps': round(len(ok) / span, 1),
'write_rps': round(sum(1 for e in ok if e[1] == 'write') / span, 1),
'read_rps': round(sum(1 for e in ok if e[1] == 'read') / span, 1),
'errors': len(sel) - len(ok),
'p50_ms': percentile([e[4] for e in ok], .50), 'p95_ms': percentile([e[4] for e in ok], .95),
'p99_ms': percentile([e[4] for e in ok], .99), 'max_ms': percentile([e[4] for e in ok], 1.0)}
errors = [e for e in events if not e[2]]
target_prefixes = tuple(t['hostname'] + '-' for t in targets)
served_by_target = [e[0] for e in events if e[2] and e[3].startswith(target_prefixes)]
per_second = []
for s in range(int(duration)):
sel = [e for e in events if s <= e[0] < s + 1]
per_second.append({'t': s, 'ok': sum(1 for e in sel if e[2]), 'err': sum(1 for e in sel if not e[2]),
'instances': len({e[3] for e in sel if e[2]})})
detection = {}
for t in targets:
seconds, state = watcher.first_not_up(t['ip'], a_start)
detection[t['name']] = {'lb_marked_not_up_after_s': seconds, 'lb_state': state}
lb_counters = None
if watcher.first and watcher.last:
lb_counters = {k: watcher.last[k] - watcher.first[k] for k in watcher.last}
return {
'targets': [{k: t[k] for k in ('name', 'hostname', 'revision')} for t in targets],
'action_started_s': round(a_start, 3), 'action_duration_s': round(a_end - a_start, 3),
'action_output': action_output,
'before': window(1, a_start), 'during_action_plus_5s': window(a_start, a_end + 5),
'after': window(a_end + 5, duration),
'errors_total': len(errors),
'write_attempts_retried_same_key': retries_with_same_key[0],
'error_window_s': ([round(errors[0][0] - a_start, 3), round(errors[-1][0] - a_start, 3)] if errors else None),
'recovery_s': round(errors[-1][0] - a_start, 3) if errors else 0.0,
'target_last_served_after_action_s': (round(max(served_by_target) - a_start, 3)
if served_by_target and max(served_by_target) >= a_start else None),
'lb_detection': detection,
'lb_retries_redispatches': lb_counters,
'instances_after': sorted({e[3] for e in events if e[2] and e[0] > a_end + 5}),
'confirmed_writes': len(confirmed), 'history_messages': len(history),
'duplicates': 0, 'lost_confirmed': lost,
'timeline_per_second': per_second,
}
def wait_lb_up(stats_url: str, ip: str, seconds: float = 60) -> None:
deadline = time.monotonic() + seconds
url = stats_url.rstrip('/') + ';csv'
while time.monotonic() < deadline:
try:
with urllib.request.urlopen(url, timeout=1) as r:
rows = csv.DictReader(io.StringIO(r.read().decode().lstrip('# ')))
if any(row['pxname'] == 'api' and row.get('addr') == ip + ':8080' and row['status'].startswith('UP')
for row in rows):
return
except OSError:
pass
time.sleep(0.5)
raise Failure('replica did not return to LB rotation')
def restore(stats_url: str) -> None:
subprocess.run(['sh', str(ROOT / 'scripts/restore.sh')], check=True, capture_output=True)
for name in api_containers():
wait_lb_up(stats_url, container_info(name)['ip'])
def main() -> int:
p = argparse.ArgumentParser(description=__doc__.split('\n')[0])
p.add_argument('--scenario', choices=['stop', 'kill', 'rolling'], required=True)
p.add_argument('--base-url', default=os.environ.get('BASE_URL', 'http://localhost:8080'))
p.add_argument('--stats-url', default=os.environ.get('LB_STATS_URL', 'http://localhost:8404/stats'))
p.add_argument('--duration', type=float, default=None)
p.add_argument('--action-at', type=float, default=8)
p.add_argument('--writers', type=int, default=4)
p.add_argument('--readers', type=int, default=2)
p.add_argument('--output', default=None)
args = p.parse_args()
duration = args.duration or (45 if args.scenario == 'rolling' else 25)
runs = []
if args.scenario == 'rolling':
targets = [container_info(n) for n in api_containers()]
def action():
r = subprocess.run(['sh', str(ROOT / 'scripts/rolling-update.sh')], text=True, capture_output=True)
check(r.returncode == 0, 'rolling-update.sh failed: ' + r.stderr[-500:])
return r.stdout.strip().splitlines()
result = run_probe(args.base_url, args.stats_url, action, targets, duration, args.action_at,
args.writers, args.readers)
result['replicas_after'] = [container_info(n) for n in api_containers()]
runs.append(result)
else:
for name in api_containers(): # по очереди каждую реплику, восстанавливая предыдущую
restore(args.stats_url)
target = container_info(name)
def action(name=name):
started = time.monotonic()
if args.scenario == 'kill':
docker('kill', name)
else:
docker('stop', '-t', '20', name)
state = docker('inspect', '-f', '{{.State.Status}} exit={{.State.ExitCode}}', name)
return [f'{args.scenario} {name}: {state} in {time.monotonic() - started:.2f}s']
result = run_probe(args.base_url, args.stats_url, action, [target], duration, args.action_at,
args.writers, args.readers)
runs.append(result)
print(f"{args.scenario} {name}: errors={result['errors_total']} recovery={result['recovery_s']}s "
f"lb_detection={result['lb_detection'][name]['lb_marked_not_up_after_s']}s "
f"rps before/after={result['before']['ok_rps']}/{result['after']['ok_rps']}", flush=True)
restore(args.stats_url)
report = {
'scenario': args.scenario, 'date_utc': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
'profile': {'duration_s': duration, 'action_at_s': args.action_at, 'writers': args.writers,
'readers': args.readers, 'client_timeout_s': 3,
'workload': 'closed-loop: POST message (retry same key on failure) + GET history limit=20'},
'runs': runs,
}
text = json.dumps(report, ensure_ascii=False, indent=2)
if args.output:
Path(args.output).parent.mkdir(parents=True, exist_ok=True)
Path(args.output).write_text(text + '\n', encoding='utf-8')
summary = [{k: r[k] for k in ('targets', 'errors_total', 'recovery_s', 'lb_detection', 'action_duration_s',
'target_last_served_after_action_s', 'lb_retries_redispatches')}
| {'rps_before': r['before']['ok_rps'], 'rps_after': r['after']['ok_rps'],
'p99_during_ms': r['during_action_plus_5s']['p99_ms']} for r in runs]
print(json.dumps(summary, ensure_ascii=False, indent=1))
return 0
if __name__ == '__main__':
sys.exit(main())