Files
mtusi2026lab3/tools/lab3/chaos_load.py
T

291 lines
14 KiB
Python

#!/usr/bin/env python3
"""Нагрузка + управляемое воздействие на стенд (уровень 4).
Сценарии:
sequential-stop поочерёдно останавливает КАЖДУЮ API-реплику (scripts/stop-one.sh), наблюдает, восстанавливает
(scripts/restore-replicas.sh) и наблюдает ещё раз;
rolling-update выполняет scripts/rolling-update.sh под нагрузкой;
baseline только нагрузка (контроль без воздействия).
Нагрузка: WORKERS потоков, замкнутый цикл, 50% GET истории (limit=20) и 50% POST сообщения с уникальным
Idempotency-Key. Неопределённый POST (ошибка/таймаут/5xx) повторяется с ТЕМ ЖЕ ключом до RETRIES раз.
В конце проверяется история: ни одно подтверждённое сообщение не потеряно, ни одно не задублировано.
Результат: JSON-сводка (по фазам: RPS, ошибки, p50/p95/p99, время восстановления) и CSV по секундам.
"""
import argparse
import csv
import json
import os
import subprocess
import sys
import threading
import time
import uuid
from collections import Counter, defaultdict
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from common import Api, create_chat, percentile, read_history, register_user # noqa: E402
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
class Recorder:
def __init__(self):
self.lock = threading.Lock()
self.samples = [] # (t_end, latency_ms, ok, op, instance)
self.confirmed = {} # key -> message id (подтверждённые POST)
self.attempted = set() # все использованные ключи
self.retried = 0
def add(self, t_end, latency_ms, ok, op, instance):
with self.lock:
self.samples.append((t_end, latency_ms, ok, op, instance))
def worker(idx, args, api, users, recorder, stop, t0):
user, chat_id = users[idx % len(users)]
n = 0
while not stop.is_set():
n += 1
if n % 2:
do_get(api, user, chat_id, recorder, t0)
else:
do_post(api, user, chat_id, recorder, t0, args.retries)
if args.think > 0:
time.sleep(args.think)
def do_get(api, user, chat_id, recorder, t0):
start = time.monotonic()
ok, instance = False, None
try:
status, headers, _ = api.request('GET', '/api/v1/chats/%s/messages?limit=20' % chat_id, token=user['token'])
ok, instance = status == 200, headers.get('x-instance-id')
except Exception:
pass
end = time.monotonic()
recorder.add(end - t0, (end - start) * 1000, ok, 'get', instance)
def do_post(api, user, chat_id, recorder, t0, retries):
key = uuid.uuid4().hex
body = {'text': 'нагрузка ' + key}
with recorder.lock:
recorder.attempted.add(key)
for attempt in range(retries + 1):
start = time.monotonic()
ok, instance, message_id = False, None, None
try:
status, headers, payload = api.request('POST', '/api/v1/chats/%s/messages' % chat_id, body,
token=user['token'], headers={'Idempotency-Key': key})
instance = headers.get('x-instance-id')
if status == 201:
ok, message_id = True, payload['id']
except Exception:
pass
end = time.monotonic()
recorder.add(end - t0, (end - start) * 1000, ok, 'post', instance)
if ok:
with recorder.lock:
recorder.confirmed[key] = message_id
return
with recorder.lock:
recorder.retried += 1
time.sleep(0.05) # тот же ключ и то же тело: повтор безопасен благодаря идемпотентности
def run_script(name, env_extra=None, args=()):
env = dict(os.environ)
env.update(env_extra or {})
started = time.monotonic()
proc = subprocess.run([os.path.join(ROOT, 'scripts', name), *args], env=env, cwd=ROOT,
capture_output=True, text=True)
return proc, time.monotonic() - started
def discover_instances(api, user, chat_id, probes=40):
seen = set()
for _ in range(probes):
_, headers, _ = api.request('GET', '/health/live')
seen.add(headers.get('x-instance-id'))
return sorted(i for i in seen if i)
def phase_stats(samples, t_from, t_to):
window = [s for s in samples if t_from <= s[0] < t_to]
ok_lat = sorted(s[1] for s in window if s[2])
errors = sum(1 for s in window if not s[2])
duration = max(t_to - t_from, 1e-9)
return {
'from_s': round(t_from, 1), 'to_s': round(t_to, 1), 'requests': len(window), 'errors': errors,
'rps_ok': round(len(ok_lat) / duration, 1),
'error_rate_pct': round(100.0 * errors / len(window), 2) if window else None,
'p50_ms': percentile(ok_lat, 0.50) and round(percentile(ok_lat, 0.50), 1),
'p95_ms': percentile(ok_lat, 0.95) and round(percentile(ok_lat, 0.95), 1),
'p99_ms': percentile(ok_lat, 0.99) and round(percentile(ok_lat, 0.99), 1),
'instances': dict(Counter(s[4] for s in window if s[2])),
}
def recovery_window(samples, t_action):
"""Окно ошибок после воздействия: первая/последняя ошибка и «время восстановления» = последняя ошибка - начало."""
errors = sorted(s[0] for s in samples if not s[2] and s[0] >= t_action)
if not errors:
return {'errors_after_action': 0, 'recovery_seconds': 0.0}
# Ошибки считаются относящимися к воздействию, пока между ними пауза < 2 с.
cluster = [errors[0]]
for t in errors[1:]:
if t - cluster[-1] < 2.0:
cluster.append(t)
else:
break
return {'errors_after_action': len(errors), 'errors_in_first_cluster': len(cluster),
'first_error_after_s': round(cluster[0] - t_action, 2),
'recovery_seconds': round(cluster[-1] - t_action, 2)}
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--base-url', default='http://localhost:8080')
parser.add_argument('--scenario', choices=['sequential-stop', 'rolling-update', 'baseline'], required=True)
parser.add_argument('--workers', type=int, default=8)
parser.add_argument('--users', type=int, default=4)
parser.add_argument('--think', type=float, default=0.02, help='пауза между запросами потока, с')
parser.add_argument('--retries', type=int, default=20)
parser.add_argument('--warmup', type=float, default=5)
parser.add_argument('--observe', type=float, default=10, help='наблюдение после каждого воздействия, с')
parser.add_argument('--baseline-seconds', type=float, default=15)
parser.add_argument('--output-prefix', required=True, help='например evidence/level4/sequential-stop')
args = parser.parse_args()
api = Api(args.base_url, timeout=5)
users = []
for i in range(args.users):
user = register_user(api, 'chaos%d' % i)
users.append((user, create_chat(api, user)))
instances = discover_instances(api, users[0][0], users[0][1])
print('replicas before:', instances, flush=True)
recorder, stop, t0 = Recorder(), threading.Event(), time.monotonic()
threads = [threading.Thread(target=worker, args=(i, args, Api(args.base_url, 5), users, recorder, stop, t0))
for i in range(args.workers)]
for t in threads:
t.start()
events = [] # (t, text)
def mark(text):
events.append((time.monotonic() - t0, text))
print('[%6.1fs] %s' % (events[-1][0], text), flush=True)
phases = [] # (name, t_from, t_to, action_t)
action_results = []
try:
time.sleep(args.warmup)
t_base = time.monotonic() - t0
if args.scenario == 'baseline':
time.sleep(args.baseline_seconds)
phases.append(('baseline', t_base, time.monotonic() - t0, None))
elif args.scenario == 'sequential-stop':
time.sleep(args.baseline_seconds)
phases.append(('baseline', t_base, time.monotonic() - t0, None))
for target in instances:
t_from = time.monotonic() - t0
mark('STOP replica %s' % target)
proc, took = run_script('stop-one.sh', {'TARGET_INSTANCE_ID': target})
action_results.append({'action': 'stop', 'target': target, 'exit_code': proc.returncode,
'hook_seconds': round(took, 2), 'at_s': round(t_from, 1)})
mark('stop-one.sh exit=%d in %.1fs' % (proc.returncode, took))
if proc.returncode != 0:
raise SystemExit('stop-one.sh failed: ' + proc.stderr.strip())
time.sleep(args.observe)
t_down_end = time.monotonic() - t0
phases.append(('replica %s stopped' % target, t_from, t_down_end, t_from))
mark('RESTORE replicas')
proc, took = run_script('restore-replicas.sh')
action_results.append({'action': 'restore', 'exit_code': proc.returncode,
'restore_seconds': round(took, 2), 'at_s': round(t_down_end, 1)})
mark('restore-replicas.sh exit=%d in %.1fs: %s' % (proc.returncode, took, proc.stdout.strip().splitlines()[-1:]))
if proc.returncode != 0:
raise SystemExit('restore failed: ' + proc.stderr.strip())
time.sleep(args.observe)
phases.append(('after restore of %s' % target, t_down_end, time.monotonic() - t0, t_down_end))
elif args.scenario == 'rolling-update':
time.sleep(args.baseline_seconds)
phases.append(('baseline', t_base, time.monotonic() - t0, None))
t_from = time.monotonic() - t0
mark('ROLLING UPDATE start')
proc, took = run_script('rolling-update.sh', args=(str(int(time.time())),))
action_results.append({'action': 'rolling-update', 'exit_code': proc.returncode,
'seconds': round(took, 2), 'at_s': round(t_from, 1), 'log': proc.stdout.strip().splitlines()})
mark('rolling-update.sh exit=%d in %.1fs' % (proc.returncode, took))
if proc.returncode != 0:
raise SystemExit('rolling-update failed: ' + proc.stderr.strip())
phases.append(('rolling update', t_from, time.monotonic() - t0, t_from))
time.sleep(args.observe)
phases.append(('after update', phases[-1][2], time.monotonic() - t0, None))
finally:
stop.set()
for t in threads:
t.join()
total_s = time.monotonic() - t0
samples = recorder.samples
# Проверка данных: подтверждённые сообщения на месте, дублей нет.
problems = []
texts = Counter()
ids = Counter()
for user, chat_id in users:
for m in read_history(api, user, chat_id):
texts[m['text']] += 1
ids[m['id']] += 1
lost = [k for k, mid in recorder.confirmed.items() if ids.get(mid, 0) != 1]
duplicated = [k for k in recorder.attempted if texts.get('нагрузка ' + k, 0) > 1]
if lost:
problems.append('confirmed messages lost or duplicated by id: %d' % len(lost))
if duplicated:
problems.append('keys that produced more than one message: %d' % len(duplicated))
unconfirmed_but_present = [k for k in recorder.attempted if k not in recorder.confirmed and texts.get('нагрузка ' + k, 0) == 1]
summary = {
'scenario': args.scenario, 'base_url': args.base_url, 'workers': args.workers, 'users_and_chats': args.users,
'think_time_s': args.think, 'replicas_before': instances, 'total_seconds': round(total_s, 1),
'overall': phase_stats(samples, args.warmup, total_s),
'phases': [],
'actions': action_results,
'events': [{'t_s': round(t, 1), 'event': e} for t, e in events],
'data_check': {
'post_keys_used': len(recorder.attempted), 'post_confirmed': len(recorder.confirmed),
'post_retries_with_same_key': recorder.retried,
'confirmed_missing_or_duplicated': len(lost), 'keys_with_duplicate_messages': len(duplicated),
'unconfirmed_but_written_once': len(unconfirmed_but_present),
'result': 'PASS' if not problems else 'FAIL', 'problems': problems,
},
}
for name, t_from, t_to, action_t in phases:
stats = phase_stats(samples, t_from, t_to)
stats['name'] = name
if action_t is not None:
stats.update(recovery_window(samples, action_t))
summary['phases'].append(stats)
os.makedirs(os.path.dirname(os.path.abspath(args.output_prefix)), exist_ok=True)
with open(args.output_prefix + '.json', 'w', encoding='utf-8') as f:
json.dump(summary, f, ensure_ascii=False, indent=2)
per_second = defaultdict(lambda: [0, 0])
for s in samples:
per_second[int(s[0])][0 if s[2] else 1] += 1
with open(args.output_prefix + '.csv', 'w', newline='', encoding='utf-8') as f:
w = csv.writer(f)
w.writerow(['second', 'ok', 'errors'])
for sec in sorted(per_second):
w.writerow([sec, per_second[sec][0], per_second[sec][1]])
print(json.dumps({k: summary[k] for k in ('overall', 'phases', 'data_check')}, ensure_ascii=False, indent=2))
return 1 if problems else 0
if __name__ == '__main__':
raise SystemExit(main())