"""Публичные resilience и отдельный принудительный отказ каждой API-реплики.""" import json from pathlib import Path import subprocess import sys import time ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / 'tests')) from client import Client, Failure, check COMPOSE = ['docker', 'compose', '-p', 'lyakhonov-lab5'] def docker(*args): return subprocess.check_output(['docker', *args], cwd=ROOT, text=True, encoding='utf-8') def snapshot(): ids = docker('compose', '-p', 'lyakhonov-lab5', 'ps', '-a', '-q').split() raw = json.loads(docker('inspect', *ids)) return [dict(id=x['Id'], name=x['Name'], started_at=x['State']['StartedAt'], running=x['State']['Running']) for x in raw] def public(mode): before = snapshot() script = ROOT / 'scripts' / (('restart' if mode == 'persistence' else 'stop-one') + ('.cmd' if sys.platform == 'win32' else '.sh')) result = subprocess.run([sys.executable, '-X', 'utf8', 'tests/resilience.py', '--mode', mode, '--base-url', 'http://127.0.0.1:8085', '--action-script', str(script)], cwd=ROOT, text=True, encoding='utf-8', capture_output=True) after = snapshot() (ROOT / f'evidence/{mode}.json').write_text(json.dumps(dict(command=result.args, exit_code=result.returncode, output=result.stdout + result.stderr, before=before, after=after), ensure_ascii=False, indent=2), encoding='utf-8') print(result.stdout, flush=True) check(result.returncode == 0, result.stderr) subprocess.check_call([*COMPOSE, 'start', 'api'], cwd=ROOT) def targeted(): c = Client('http://127.0.0.1:8085', timeout=2) alice, _, _, chat = c.bootstrap() ids = docker('compose', '-p', 'lyakhonov-lab5', 'ps', '-q', 'api').split() evidence = [] for index, target in enumerate(ids): before = snapshot() responses, errors = [], [] first = None begin = time.monotonic() subprocess.check_call(['docker', 'stop', '-t', '2', target], stdout=subprocess.DEVNULL) try: while time.monotonic() - begin < 15: key = f'explicit-{index}-{len(responses)}' try: response = c.message(alice, chat, 'replica failure', key=key) first = first or time.monotonic()-begin responses.append(response['json']) except Failure as exc: errors.append(str(exc)) time.sleep(.05) check(first is not None and first <= 10, 'slow API failover') page = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=100', actor=alice)['json'] messages = list(page['items']) while page['next_cursor']: from urllib.parse import quote page = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=100&cursor=' + quote(page['next_cursor'], safe=''), actor=alice)['json'] messages.extend(page['items']) found = {m['id'] for m in messages} check(all(m['id'] in found for m in responses), 'acknowledged message lost') check(len(found) == len(messages), 'duplicate messages') evidence.append(dict(target=target, before=before, after=snapshot(), successes=len(responses), errors=errors, recovery_seconds=round(first, 3))) finally: subprocess.check_call(['docker', 'start', target], stdout=subprocess.DEVNULL) time.sleep(3) (ROOT / 'evidence/failover-each.json').write_text(json.dumps(evidence, ensure_ascii=False, indent=2), encoding='utf-8') print('PASS: both real API containers independently stopped and restored') if __name__ == '__main__': public('persistence') public('failover') targeted()