Выполнение 3 лабораторной работы
This commit is contained in:
@@ -0,0 +1,290 @@
|
||||
#!/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())
|
||||
@@ -0,0 +1,100 @@
|
||||
"""Общие функции инструментов lab3: минимальный HTTP-клиент (stdlib) и подготовка синтетических данных."""
|
||||
import base64
|
||||
import http.client
|
||||
import json
|
||||
import threading
|
||||
import urllib.parse
|
||||
import uuid
|
||||
|
||||
|
||||
class Api:
|
||||
"""Клиент с keep-alive соединением на поток. Сетевые ошибки пробрасываются, соединение пересоздаётся."""
|
||||
|
||||
def __init__(self, base_url, timeout=5.0):
|
||||
self.base_url = base_url
|
||||
parsed = urllib.parse.urlparse(base_url)
|
||||
self.host, self.port, self.timeout = parsed.hostname, parsed.port or 80, timeout
|
||||
self._local = threading.local()
|
||||
|
||||
def _connection(self):
|
||||
conn = getattr(self._local, 'conn', None)
|
||||
if conn is None:
|
||||
conn = http.client.HTTPConnection(self.host, self.port, timeout=self.timeout)
|
||||
self._local.conn = conn
|
||||
return conn
|
||||
|
||||
def request(self, method, path, body=None, token=None, headers=None):
|
||||
"""Возвращает (status, headers, json|None). Исключение = нет ответа (обрыв, таймаут)."""
|
||||
h = {'Accept': 'application/json'}
|
||||
data = None
|
||||
if body is not None:
|
||||
data = json.dumps(body, ensure_ascii=False).encode('utf-8')
|
||||
h['Content-Type'] = 'application/json'
|
||||
if token:
|
||||
h['Authorization'] = 'Bearer ' + token
|
||||
h.update(headers or {})
|
||||
# Для GET один раз прозрачно повторяем запрос, если сервер/LB закрыл простаивавшее keep-alive соединение
|
||||
# (timeout http-keep-alive в HAProxy). POST так не повторяется: его повтор решает вызывающий с тем же ключом.
|
||||
attempts = 2 if method == 'GET' else 1
|
||||
for attempt in range(attempts):
|
||||
conn = self._connection()
|
||||
reused = conn.sock is not None
|
||||
try:
|
||||
conn.request(method, path, body=data, headers=h)
|
||||
response = conn.getresponse()
|
||||
raw = response.read()
|
||||
if response.getheader('Connection', '').lower() == 'close':
|
||||
conn.close()
|
||||
self._local.conn = None
|
||||
break
|
||||
except (OSError, http.client.HTTPException):
|
||||
conn.close()
|
||||
self._local.conn = None
|
||||
if attempt + 1 >= attempts or not reused:
|
||||
raise
|
||||
payload = None
|
||||
if raw and response.getheader('Content-Type', '').startswith('application/json'):
|
||||
payload = json.loads(raw)
|
||||
return response.status, {k.lower(): v for k, v in response.getheaders()}, payload
|
||||
|
||||
|
||||
def register_user(api, label):
|
||||
"""Создаёт пользователя и сессию. Возвращает {'id', 'token'}."""
|
||||
username = 'l3_%s_%s' % (label, uuid.uuid4().hex[:10])
|
||||
password = 'T3st-' + uuid.uuid4().hex
|
||||
status, _, user = api.request('POST', '/api/v1/users',
|
||||
{'username': username, 'display_name': 'Нагрузка ' + label, 'password': password})
|
||||
assert status == 201, 'register failed: %s' % status
|
||||
credential = base64.b64encode((username + ':' + password).encode()).decode()
|
||||
status, _, session = api.request('POST', '/api/v1/auth/sessions', headers={'Authorization': 'Basic ' + credential})
|
||||
assert status == 201, 'login failed: %s' % status
|
||||
return {'id': user['id'], 'token': session['token']}
|
||||
|
||||
|
||||
def create_chat(api, owner, others=()):
|
||||
members = [owner['id']] + [o['id'] for o in others]
|
||||
status, _, chat = api.request('POST', '/api/v1/chats', {'title': 'Нагрузка', 'member_ids': members}, token=owner['token'])
|
||||
assert status == 201, 'create chat failed: %s' % status
|
||||
return chat['id']
|
||||
|
||||
|
||||
def read_history(api, user, chat_id):
|
||||
"""Вся история чата постранично (cursor), для проверки дублей и потерь."""
|
||||
items, cursor = [], None
|
||||
while True:
|
||||
path = '/api/v1/chats/%s/messages?limit=100' % chat_id
|
||||
if cursor:
|
||||
path += '&cursor=' + urllib.parse.quote(cursor, safe='')
|
||||
status, _, page = api.request('GET', path, token=user['token'])
|
||||
assert status == 200, 'history failed: %s' % status
|
||||
items.extend(page['items'])
|
||||
cursor = page['next_cursor']
|
||||
if cursor is None:
|
||||
return items
|
||||
|
||||
|
||||
def percentile(sorted_values, p):
|
||||
if not sorted_values:
|
||||
return None
|
||||
index = max(0, min(len(sorted_values) - 1, int(-(-p * len(sorted_values) // 1)) - 1))
|
||||
return sorted_values[index]
|
||||
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Параллельные POST с одним Idempotency-Key через балансировщик (разные реплики).
|
||||
|
||||
Проверяет: в каждом раунде создаётся ровно одно сообщение, все ответы 201 и совпадают побайтно,
|
||||
запросы реально обслужили ≥2 реплики. Отдельный раунд: один ключ с РАЗНЫМИ телами → один победитель, остальные 409.
|
||||
|
||||
Запуск: python3 tools/lab3/idempotency_race.py --base-url http://localhost:8080 --rounds 20 --parallel 40
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import uuid
|
||||
from collections import Counter
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from common import Api, create_chat, read_history, register_user # noqa: E402
|
||||
|
||||
|
||||
def fire(api, user, chat_id, key, bodies):
|
||||
"""Одновременно отправляет len(bodies) запросов (старт по барьеру). Возвращает [(status, instance, json)]."""
|
||||
barrier = threading.Barrier(len(bodies))
|
||||
results = [None] * len(bodies)
|
||||
|
||||
def worker(i):
|
||||
local = Api(api.base_url, timeout=15) # своё соединение на поток: настоящий параллелизм
|
||||
barrier.wait()
|
||||
status, headers, payload = local.request(
|
||||
'POST', '/api/v1/chats/%s/messages' % chat_id, {'text': bodies[i]}, token=user['token'],
|
||||
headers={'Idempotency-Key': key})
|
||||
results[i] = (status, headers.get('x-instance-id'), payload)
|
||||
|
||||
threads = [threading.Thread(target=worker, args=(i,)) for i in range(len(bodies))]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
return results
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--base-url', default='http://localhost:8080')
|
||||
parser.add_argument('--rounds', type=int, default=20)
|
||||
parser.add_argument('--parallel', type=int, default=40)
|
||||
parser.add_argument('--output', default=None)
|
||||
args = parser.parse_args()
|
||||
|
||||
api = Api(args.base_url)
|
||||
user = register_user(api, 'idem')
|
||||
chat_id = create_chat(api, user)
|
||||
|
||||
instances = Counter()
|
||||
failures = []
|
||||
for round_no in range(args.rounds):
|
||||
key = 'race-%d-%s' % (round_no, uuid.uuid4().hex[:12])
|
||||
results = fire(api, user, chat_id, key, ['гонка %d' % round_no] * args.parallel)
|
||||
statuses = Counter(r[0] for r in results)
|
||||
bodies = {json.dumps(r[2], sort_keys=True) for r in results}
|
||||
instances.update(r[1] for r in results)
|
||||
if statuses != Counter({201: args.parallel}) or len(bodies) != 1:
|
||||
failures.append('round %d: statuses=%s distinct_bodies=%d' % (round_no, dict(statuses), len(bodies)))
|
||||
|
||||
# Один ключ, разные тела: ровно один 201, остальные 409.
|
||||
key = 'race-diff-' + uuid.uuid4().hex[:12]
|
||||
results = fire(api, user, chat_id, key, ['вариант %d' % i for i in range(args.parallel)])
|
||||
statuses = Counter(r[0] for r in results)
|
||||
if statuses != Counter({201: 1, 409: args.parallel - 1}):
|
||||
failures.append('different bodies: statuses=%s' % dict(statuses))
|
||||
|
||||
history = read_history(api, user, chat_id)
|
||||
expected = args.rounds + 1
|
||||
if len(history) != expected:
|
||||
failures.append('history has %d messages, expected %d' % (len(history), expected))
|
||||
if len({m['id'] for m in history}) != len(history):
|
||||
failures.append('duplicate message ids in history')
|
||||
if len(instances) < 2:
|
||||
failures.append('only %d replica(s) served the race: %s' % (len(instances), dict(instances)))
|
||||
|
||||
summary = {
|
||||
'rounds': args.rounds, 'parallel_requests_per_round': args.parallel,
|
||||
'requests_total': args.rounds * args.parallel + args.parallel,
|
||||
'messages_in_history': len(history), 'messages_expected': expected,
|
||||
'replicas_that_served_requests': len(instances), 'requests_per_replica': dict(instances),
|
||||
'result': 'FAIL' if failures else 'PASS', 'failures': failures,
|
||||
}
|
||||
print(json.dumps(summary, ensure_ascii=False, indent=2))
|
||||
if args.output:
|
||||
with open(args.output, 'w', encoding='utf-8') as f:
|
||||
json.dump(summary, f, ensure_ascii=False, indent=2)
|
||||
return 1 if failures else 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,29 @@
|
||||
#!/bin/sh
|
||||
# Измеряет, за сколько HAProxy помечает DOWN замороженный (docker pause) backend: время от заморозки до статуса DOWN.
|
||||
# Выполнять из WSL/Linux при поднятом стенде. Реплика после измерения размораживается.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/../.."
|
||||
|
||||
down_count() {
|
||||
docker compose exec -T lb wget -qO- 'http://127.0.0.1:8404/stats;csv' \
|
||||
| awk -F, '$1=="api" && $2!="BACKEND" && $18 ~ /^DOWN/ {n++} END {print n+0}'
|
||||
}
|
||||
|
||||
container=$(docker compose ps -q api | head -n 1)
|
||||
[ -n "$container" ] || { echo "no running api container" >&2; exit 1; }
|
||||
[ "$(down_count)" = "0" ] || { echo "some replica is already DOWN" >&2; exit 1; }
|
||||
|
||||
echo "freezing $(docker inspect -f '{{.Name}}' "$container")"
|
||||
start=$(date +%s.%N)
|
||||
docker pause "$container" >/dev/null
|
||||
trap 'docker unpause "$container" >/dev/null 2>&1 || true' EXIT
|
||||
for _ in $(seq 1 400); do
|
||||
if [ "$(down_count)" -ge 1 ]; then
|
||||
now=$(date +%s.%N)
|
||||
echo "DOWN detected after $(echo "$now - $start" | bc) s"
|
||||
exit 0
|
||||
fi
|
||||
sleep 0.1
|
||||
done
|
||||
echo "not detected within 40 s" >&2
|
||||
exit 1
|
||||
Reference in New Issue
Block a user