forked from mtusi2026/mtusi2026lab3
87 lines
3.2 KiB
Python
87 lines
3.2 KiB
Python
#!/usr/bin/env python3
|
|
"""Останавливает КАЖДУЮ реплику по очереди и проверяет восстановление."""
|
|
import json
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
|
|
from common import (
|
|
BASE_URL, Client, Failure, check, compose, observe_instances, print_pass,
|
|
wait_ready,
|
|
)
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
|
|
def stop_one(instance_alias):
|
|
env = {'TARGET_INSTANCE_ID': instance_alias, 'PATH': __import__('os').environ['PATH']}
|
|
proc = subprocess.run(
|
|
[str(ROOT / 'scripts/stop-one.sh')],
|
|
cwd=str(ROOT), env={**__import__('os').environ, **env},
|
|
capture_output=True, text=True, timeout=30)
|
|
check(proc.returncode == 0,
|
|
'stop-one.sh для %s упал rc=%d\nstderr=%s'
|
|
% (instance_alias, proc.returncode, proc.stderr[-1000:]))
|
|
|
|
|
|
def restore_all():
|
|
"""Возвращает все реплики в running."""
|
|
for svc in ('api1', 'api2'):
|
|
compose('start', svc, check_rc=False)
|
|
wait_ready(90)
|
|
|
|
|
|
def main():
|
|
c = Client(BASE_URL)
|
|
alice, bob, eve, chat = c.bootstrap()
|
|
seen = observe_instances(c, alice, n=40)
|
|
check(len(seen) >= 2, 'видна одна реплика: %r' % seen)
|
|
print(' instances:', seen)
|
|
|
|
for alias in sorted(seen):
|
|
print('--- failover test for %s' % alias)
|
|
target_alias = alias
|
|
stop_one(target_alias)
|
|
time.sleep(1)
|
|
|
|
# Ни одна последующая успешная запись не должна обслуживаться target.
|
|
first_ok = None
|
|
after = []
|
|
deadline = time.monotonic() + 15
|
|
key = 'fo-' + __import__('uuid').uuid4().hex
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
r = c.message(alice, chat, 'after-stop-' + key, key=key)
|
|
if first_ok is None:
|
|
first_ok = time.monotonic()
|
|
after.append(r['headers']['X-Instance-Id'])
|
|
key = 'fo-' + __import__('uuid').uuid4().hex
|
|
except Failure:
|
|
pass
|
|
time.sleep(0.2)
|
|
check(first_ok is not None, 'запись не восстановилась за 15с')
|
|
check(len(after) >= 5, 'слишком мало успешных записей после отказа: %d' % len(after))
|
|
check(target_alias not in after[-5:],
|
|
'остановленная реплика %s всё ещё отвечает' % target_alias)
|
|
print(' after stop %s: %d writes, последние instances=%r'
|
|
% (target_alias, len(after), after[-3:]))
|
|
|
|
# Восстановить и подождать, пока LB снова начнёт её использовать.
|
|
restore_all()
|
|
time.sleep(2)
|
|
seen2 = observe_instances(c, alice, n=60)
|
|
print(' после restore видно:', seen2)
|
|
|
|
# В конце — обе реплики снова живы.
|
|
seen3 = observe_instances(c, alice, n=60)
|
|
check(len(seen3) >= 2, 'после restore видна одна реплика: %r' % seen3)
|
|
print_pass('failover both replicas')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
try:
|
|
main()
|
|
except Failure as e:
|
|
print('FAIL:', e)
|
|
raise SystemExit(1) |