174 lines
8.4 KiB
Python
174 lines
8.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Grade 4 only: each process failure and sequential replacement under one fixed load."""
|
|
import argparse
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from datetime import datetime, timezone
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import sys
|
|
import threading
|
|
import time
|
|
import uuid
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path[:0] = [str(ROOT / 'tests'), str(ROOT / 'scripts')]
|
|
from client import Client, Failure, check
|
|
from resilience import history
|
|
from labctl import command, compose, containers, replace_one, save, wait_api
|
|
|
|
# IPv4-only published LB: avoid slow localhost IPv6 fallback on Windows.
|
|
os.environ.setdefault('BASE_URL', 'http://127.0.0.1:8080')
|
|
|
|
|
|
def quantile(values, q):
|
|
ordered = sorted(values)
|
|
return round(ordered[min(len(ordered) - 1, int((len(ordered) - 1) * q))] * 1000, 3) if values else None
|
|
|
|
|
|
def scenario(mode, target=None, seconds=32):
|
|
c = Client(timeout=2)
|
|
alice, bob, eve, chat = c.bootstrap()
|
|
original_key = uuid.uuid4().hex
|
|
original = c.message(alice, chat, 'Подтверждено до воздействия', key=original_key)['json']
|
|
instances_before = {c.call('GET', '/api/v1/users/me', actor=alice, schema='User')['headers']['X-Instance-Id']
|
|
for _ in range(20)}
|
|
check(len(instances_before) == 2, 'Need two distinct processes before experiment')
|
|
samples, confirmations, resources, action = [], [], [], {}
|
|
stop = threading.Event()
|
|
start = time.monotonic()
|
|
|
|
def worker(n):
|
|
client = Client(timeout=2)
|
|
key = uuid.uuid4().hex
|
|
text = 'load-' + key
|
|
while not stop.is_set():
|
|
for operation in ('write', 'read'):
|
|
at = time.monotonic()
|
|
try:
|
|
if operation == 'write':
|
|
result = client.message(alice, chat, text, key=key)
|
|
confirmations.append(result['json'])
|
|
key = uuid.uuid4().hex
|
|
text = 'load-' + key
|
|
else:
|
|
result = client.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=100',
|
|
actor=bob, schema='MessagePage')
|
|
check(original in result['json']['items'], 'Confirmed data missing during action')
|
|
samples.append(dict(at=round(at - start, 5), end=round(time.monotonic() - start, 5),
|
|
elapsed=time.monotonic() - at, operation=operation,
|
|
ok=True, status=result['status'], instance=result['headers']['X-Instance-Id']))
|
|
except Failure as exc:
|
|
# Failure only contains sanitized method/path/status or transport type.
|
|
samples.append(dict(at=round(at - start, 5), end=round(time.monotonic() - start, 5),
|
|
elapsed=time.monotonic() - at, operation=operation,
|
|
ok=False, error=str(exc)))
|
|
stop.wait(.03)
|
|
|
|
def affect():
|
|
stop.wait(5)
|
|
action['start'] = time.monotonic() - start
|
|
try:
|
|
if mode == 'stop':
|
|
before = containers('api')
|
|
command('docker', 'stop', '--time', '8', target['id'])
|
|
action['stop_completed'] = time.monotonic() - start
|
|
after = containers('api', all_states=True)
|
|
check(next(x for x in after if x['id'] == target['id'])['status'] == 'exited', 'Target still running')
|
|
action.update(before=before, after_stop=after)
|
|
stop.wait(10)
|
|
compose('up', '-d', '--no-deps', '--no-recreate', 'api')
|
|
wait_api()
|
|
else:
|
|
initial = containers('api')
|
|
changes = []
|
|
for item in initial:
|
|
changes.append(replace_one(item['id']))
|
|
action['replacements'] = changes
|
|
save('rolling-processes.json', dict(before=initial, replacements=changes, after=containers('api')))
|
|
action['end'] = time.monotonic() - start
|
|
except Exception as exc:
|
|
action['error'] = type(exc).__name__
|
|
stop.set()
|
|
|
|
def monitor():
|
|
while not stop.is_set():
|
|
ids = [x['id'] for x in containers()]
|
|
rows = command('docker', 'stats', '--no-stream', '--format', '{{json .}}', *ids)
|
|
resources.append(dict(at=round(time.monotonic() - start, 3),
|
|
containers=[json.loads(x) for x in rows.splitlines()]))
|
|
stop.wait(5)
|
|
|
|
with ThreadPoolExecutor(max_workers=6) as pool:
|
|
workers = [pool.submit(worker, n) for n in range(4)]
|
|
impact = pool.submit(affect)
|
|
monitor_job = pool.submit(monitor)
|
|
stop.wait(seconds)
|
|
stop.set()
|
|
impact.result()
|
|
monitor_job.result()
|
|
for job in workers:
|
|
job.result()
|
|
check('error' not in action, 'Action failed: ' + action.get('error', ''))
|
|
wait_api()
|
|
all_messages = history(c, bob, chat)
|
|
by_id = {x['id']: x for x in all_messages}
|
|
check(len(by_id) == len(all_messages), 'Duplicate IDs')
|
|
check(len({x['text'] for x in all_messages}) == len(all_messages), 'Uncertain retry duplicated a message')
|
|
check(all(by_id.get(x['id']) == x for x in [original, *confirmations]), 'Confirmed data lost')
|
|
check(c.message(alice, chat, original['text'], key=original_key)['json'] == original,
|
|
'Pre-action idempotency result changed after replacement')
|
|
elapsed = max(x['end'] for x in samples)
|
|
errors = [x for x in samples if not x['ok']]
|
|
successful = [x for x in samples if x['ok']]
|
|
latencies = [x['elapsed'] for x in successful]
|
|
result = dict(mode=mode, target=target['name'] if target else None,
|
|
at_utc=datetime.now(timezone.utc).isoformat(), duration_seconds=round(elapsed, 3),
|
|
warmup_seconds=5, concurrency=4, profile='each worker: POST + GET, then 30ms pause; closed loop',
|
|
initial_messages=1, final_messages=len(all_messages), confirmations=len(confirmations),
|
|
operations=len(samples), successful_operations=len(successful), errors=len(errors),
|
|
error_percent=round(100 * len(errors) / len(samples), 3),
|
|
successful_rps=round(len(successful) / elapsed, 3),
|
|
latency_success_ms=dict(p50=quantile(latencies, .5), p95=quantile(latencies, .95), p99=quantile(latencies, .99)),
|
|
instances_before=sorted(instances_before), action=action, resources=resources,
|
|
confirmed_data_lost=0, duplicate_messages=0)
|
|
if mode == 'stop':
|
|
done = action['stop_completed']
|
|
post = [x for x in samples if done <= x['at'] < done + 8]
|
|
recovery = {}
|
|
for op in ('read', 'write'):
|
|
valid = [x for x in post if x['ok'] and x['operation'] == op]
|
|
check(bool(valid), op + ' did not continue after stop')
|
|
recovery[op] = round(min(x['end'] for x in valid) - action['start'], 3)
|
|
check(recovery[op] <= 10, 'Recovery exceeded 10 seconds')
|
|
relevant_errors = [x for x in errors if action['start'] <= x['at'] < done + 8]
|
|
result['first_success_after_stop_seconds_from_action_start'] = recovery
|
|
result['last_error_seconds_from_action_start'] = round(
|
|
max((x['end'] - action['start'] for x in relevant_errors), default=0), 3)
|
|
result['successful_rps_8s_after_stop'] = round(sum(x['ok'] for x in post) / 8, 3)
|
|
else:
|
|
check(len(action['replacements']) == 2, 'Both containers must be replaced')
|
|
check(len(errors) / len(samples) < .2, 'Too many errors during sequential replacement')
|
|
filename = 'load-' + (target['name'] if target else 'rolling') + '.json'
|
|
result['samples'] = samples
|
|
save(filename, result)
|
|
print(json.dumps({k: v for k, v in result.items() if k not in ('samples', 'resources', 'action')}, ensure_ascii=False))
|
|
print('Evidence:', 'evidence/' + filename, flush=True)
|
|
|
|
|
|
def main():
|
|
p = argparse.ArgumentParser()
|
|
p.add_argument('--mode', choices=['failures', 'rolling', 'all'], default='all')
|
|
args = p.parse_args()
|
|
wait_api()
|
|
if args.mode in ('failures', 'all'):
|
|
for target in containers('api'):
|
|
scenario('stop', target)
|
|
if args.mode in ('rolling', 'all'):
|
|
scenario('rolling')
|
|
print('PASS: grade 4 load scenarios; no scale or multi-node research track.')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|