forked from mtusi2026/mtusi2026lab3
ЛР 3 — БВТ2303 — Брезгунова — на 5
This commit is contained in:
@@ -0,0 +1,139 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Stop EVERY replica sequentially, SIGKILL, rolling replacement and cache loss.
|
||||
Runs reads and writes through LB, retains original keys on uncertain writes,
|
||||
verifies every acknowledged message and measures errors/recovery.
|
||||
"""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
sys.path.insert(0, str(ROOT / 'scripts'))
|
||||
from client import Client, Failure
|
||||
from resilience import history
|
||||
from actions import base_url, command, containers, record, restore, rolling, stop, wait_instances
|
||||
|
||||
|
||||
def scenario(label, action, duration=20):
|
||||
c = Client(base_url(), timeout=2)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
sentinel_key = uuid.uuid4().hex
|
||||
sentinel = c.message(alice, chat, 'Before ' + label, key=sentinel_key)['json']
|
||||
start = time.monotonic()
|
||||
attempts, confirmations, action_data = [], {}, {}
|
||||
lock = threading.Lock()
|
||||
|
||||
def worker(index):
|
||||
local = Client(base_url(), timeout=2)
|
||||
key = uuid.uuid4().hex
|
||||
while time.monotonic()-start < duration:
|
||||
for method in ('POST', 'GET'):
|
||||
at = time.monotonic()
|
||||
try:
|
||||
if method == 'POST':
|
||||
response = local.message(alice, chat, 'resilience-' + key, key=key)
|
||||
with lock:
|
||||
confirmations[response['json']['id']] = response['json']
|
||||
key = uuid.uuid4().hex
|
||||
else:
|
||||
response = local.call('GET', '/api/v1/users/me', actor=alice, schema='User')
|
||||
event = {'at': at-start, 'end': time.monotonic()-start, 'method': method,
|
||||
'success': True, 'instance': response['headers']['X-Instance-Id']}
|
||||
except Failure as exc:
|
||||
event = {'at': at-start, 'end': time.monotonic()-start, 'method': method, 'success': False, 'error': str(exc)}
|
||||
with lock:
|
||||
attempts.append(event)
|
||||
time.sleep(.05)
|
||||
|
||||
def mutate():
|
||||
time.sleep(3)
|
||||
action_data['started'] = time.monotonic()-start
|
||||
try:
|
||||
action_data['result'] = action()
|
||||
except Exception as exc:
|
||||
action_data['error'] = str(exc)
|
||||
action_data['completed'] = time.monotonic()-start
|
||||
|
||||
mutator = threading.Thread(target=mutate)
|
||||
mutator.start()
|
||||
with ThreadPoolExecutor(max_workers=4) as pool:
|
||||
list(pool.map(worker, range(4)))
|
||||
mutator.join()
|
||||
assert 'error' not in action_data, action_data
|
||||
items = history(c, bob, chat)
|
||||
indexed = {item['id']: item for item in items}
|
||||
assert indexed.get(sentinel['id']) == sentinel
|
||||
assert all(indexed.get(ident) == msg for ident, msg in confirmations.items())
|
||||
assert len({msg['text'] for msg in items}) == len(items), 'retry duplicate detected'
|
||||
assert c.message(alice, chat, 'Before ' + label, key=sentinel_key)['json'] == sentinel
|
||||
recoveries = {}
|
||||
for method in ('GET', 'POST'):
|
||||
recovered = [event for event in attempts if event['success'] and event['method'] == method
|
||||
and event['at'] >= action_data['completed']]
|
||||
assert recovered, 'no operations after completed action'
|
||||
recoveries[method] = min(event['end'] for event in recovered) - action_data['completed']
|
||||
assert recoveries[method] <= 10
|
||||
if label.startswith('stop-replica') or label == 'hard-kill':
|
||||
assert recoveries[method] + action_data['completed'] - action_data['started'] <= 10
|
||||
stopped_target = action_data.get('result', {}).get('target') if isinstance(action_data.get('result'), dict) else None
|
||||
if stopped_target:
|
||||
assert all(event.get('instance') != stopped_target for event in attempts
|
||||
if event['success'] and event['at'] > action_data['completed']+2)
|
||||
latencies = sorted((event['end'] - event['at'])*1000 for event in attempts)
|
||||
report = {'label': label, 'pass': True, 'duration_seconds': duration, 'workers': 4,
|
||||
'successful_rps': sum(event['success'] for event in attempts)/duration,
|
||||
'all_attempt_latency_ms': {name: latencies[math.ceil(len(latencies)*percent)-1]
|
||||
for name,percent in [('p50',.5),('p95',.95),('p99',.99)]},
|
||||
'error_ratio': sum(not event['success'] for event in attempts)/len(attempts),
|
||||
'failed_requests': sum(not event['success'] for event in attempts),
|
||||
'successful_requests': sum(event['success'] for event in attempts),
|
||||
'confirmed_messages': len(confirmations), 'all_confirmed_preserved': True,
|
||||
'no_duplicate_texts': True, 'existing_token_and_idempotency_preserved': True,
|
||||
'first_success_after_action_completed_seconds': recoveries, 'action': action_data,
|
||||
'first_success_after_action_started_seconds': {method: value+action_data['completed']-action_data['started']
|
||||
for method,value in recoveries.items()},
|
||||
'attempts': attempts}
|
||||
(ROOT / 'evidence' / (label + '.json')).write_text(json.dumps(report, indent=2) + '\n')
|
||||
print(f"{label}: PASS; {report['successful_rps']:.1f} RPS, errors={report['failed_requests']}, recovery={recoveries}", flush=True)
|
||||
return {key: value for key, value in report.items() if key != 'attempts'}
|
||||
|
||||
|
||||
def main():
|
||||
restore()
|
||||
originals = containers('api', running=True)
|
||||
results = []
|
||||
try:
|
||||
for index, victim in enumerate(originals):
|
||||
results.append(scenario('stop-replica-' + str(index+1), lambda target=victim['instance']: stop(target)))
|
||||
command(['docker', 'start', victim['id']])
|
||||
wait_instances(2, required=victim['instance'])
|
||||
victim = containers('api', running=True)[0]
|
||||
results.append(scenario('hard-kill', lambda: stop(victim['instance'], hard=True)))
|
||||
command(['docker', 'start', victim['id']])
|
||||
wait_instances(2, required=victim['instance'])
|
||||
results.append(scenario('rolling-update', rolling, duration=30))
|
||||
redis = containers('redis', running=True)[0]
|
||||
|
||||
def cache_loss():
|
||||
before = containers('redis')
|
||||
command(['docker', 'stop', redis['id']])
|
||||
result = record('cache-loss', before, containers('redis'))
|
||||
time.sleep(5)
|
||||
command(['docker', 'start', redis['id']])
|
||||
return result
|
||||
|
||||
results.append(scenario('cache-loss', cache_loss))
|
||||
finally:
|
||||
command(['docker', 'start'] + [x['id'] for x in containers('redis')])
|
||||
restore()
|
||||
(ROOT / 'evidence' / 'resilience-summary.json').write_text(json.dumps(results, indent=2) + '\n')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user