ЛР5 БВТ2304 Запорожец на 5
RabbitMQ (quorum queue, publisher confirms, manual ack, DLX) + отдельный worker: staging в S3 + вложение/job/outbox одной транзакцией -> 202 queued; relay outbox, lease с heartbeat и fencing (worker_id, attempt), retry с backoff+jitter, failed-реестр, безопасный replay с audit; thumbnail/crop/WebP в изолированном процессе с лимитами. Тесты окон отказа (fault injection), трек 1 «Очередь под перегрузкой» с backpressure. Перенесено исправление замечания lab3 PR #99 (U+0000 в тексте). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Executable
+312
@@ -0,0 +1,312 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Серии отказов под нагрузкой (уровень 4): RPS, ошибки, время обнаружения и восстановления.
|
||||
|
||||
Запускается на ХОСТЕ из корня репозитория (нужны docker CLI и, для rolling, compose с bind-путями):
|
||||
python student-tests/failover_series.py --scenario stop # graceful stop каждой реплики по очереди
|
||||
python student-tests/failover_series.py --scenario kill # SIGKILL каждой реплики по очереди
|
||||
python student-tests/failover_series.py --scenario rolling # scripts/rolling-update.sh под нагрузкой
|
||||
|
||||
Нагрузка closed-loop: W писателей (POST сообщения; неопределённый результат повторяется с ТЕМ ЖЕ ключом,
|
||||
как в tests/resilience.py) и R читателей (GET истории). Параллельно раз в 200 мс опрашивается
|
||||
CSV-статистика HAProxy: когда слот целевой реплики перестал быть UP — это время обнаружения отказа LB.
|
||||
После серии проверяется, что все подтверждённые сообщения на месте и нет дублей.
|
||||
Токены остаются в памяти процесса; в отчёт попадают только агрегаты.
|
||||
"""
|
||||
import argparse
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, Failure, check # noqa: E402
|
||||
|
||||
PROJECT = 'mtusi-lab5'
|
||||
EDGE_NETWORK = PROJECT + '_edge'
|
||||
API_FILTER = ['--filter', f'label=com.docker.compose.project={PROJECT}',
|
||||
'--filter', 'label=com.docker.compose.service=api']
|
||||
|
||||
|
||||
def docker(*args: str) -> str:
|
||||
return subprocess.run(['docker', *args], check=True, text=True, capture_output=True).stdout.strip()
|
||||
|
||||
|
||||
def api_containers() -> list[str]:
|
||||
names = docker('ps', *API_FILTER, '--format', '{{.Names}}').split()
|
||||
return sorted(names)
|
||||
|
||||
|
||||
def container_info(name: str) -> dict:
|
||||
fmt = ('{{.Config.Hostname}}|{{index .Config.Labels "org.opencontainers.image.revision"}}|'
|
||||
'{{(index .NetworkSettings.Networks "%s").IPAddress}}') % EDGE_NETWORK
|
||||
hostname, revision, ip = docker('inspect', '-f', fmt, name).split('|')
|
||||
return {'name': name, 'hostname': hostname, 'revision': revision, 'ip': ip}
|
||||
|
||||
|
||||
def percentile(values: list[float], p: float):
|
||||
values = sorted(values)
|
||||
return round(1000 * values[max(0, math.ceil(p * len(values)) - 1)], 1) if values else None
|
||||
|
||||
|
||||
class LbWatcher(threading.Thread):
|
||||
"""Опрос /stats;csv: состояние слотов backend `api` и счётчики retry/redispatch."""
|
||||
|
||||
def __init__(self, stats_url: str, t0: float):
|
||||
super().__init__(daemon=True)
|
||||
self.url = stats_url.rstrip('/') + ';csv'
|
||||
self.t0 = t0
|
||||
self.stop_flag = threading.Event()
|
||||
self.samples = [] # (t, {addr: status})
|
||||
self.first = self.last = None
|
||||
|
||||
def snapshot(self):
|
||||
with urllib.request.urlopen(self.url, timeout=1) as r:
|
||||
rows = list(csv.DictReader(io.StringIO(r.read().decode().lstrip('# '))))
|
||||
servers = {row['addr']: row['status'] for row in rows
|
||||
if row['pxname'] == 'api' and row['svname'] not in ('FRONTEND', 'BACKEND') and row.get('addr')}
|
||||
backend = next(row for row in rows if row['pxname'] == 'api' and row['svname'] == 'BACKEND')
|
||||
return servers, {'retries': int(backend['wretr'] or 0), 'redispatches': int(backend['wredis'] or 0)}
|
||||
|
||||
def run(self):
|
||||
while not self.stop_flag.is_set():
|
||||
try:
|
||||
servers, counters = self.snapshot()
|
||||
self.samples.append((time.monotonic() - self.t0, servers))
|
||||
self.first = self.first or counters
|
||||
self.last = counters
|
||||
except Exception: # LB-статистика — вспомогательная, не влияет на результат серии
|
||||
pass
|
||||
time.sleep(0.2)
|
||||
|
||||
def first_not_up(self, ip: str, after: float):
|
||||
"""Первый момент после `after`, когда слот с этим IP не UP (DOWN/MAINT/исчез из DNS)."""
|
||||
addr = ip + ':8080'
|
||||
for t, servers in self.samples:
|
||||
if t >= after and not servers.get(addr, 'MISSING').startswith('UP'):
|
||||
return round(t - after, 3), servers.get(addr, 'removed from DNS')
|
||||
return None, None
|
||||
|
||||
|
||||
def run_probe(base_url: str, stats_url: str, action, targets: list[dict], duration: float,
|
||||
action_at: float, writers: int, readers: int) -> dict:
|
||||
c = Client(base_url)
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
events = [] # (t, kind, ok, instance, latency)
|
||||
confirmed = [] # подтверждённые сообщения
|
||||
lock = threading.Lock()
|
||||
retries_with_same_key = [0]
|
||||
t0 = time.monotonic()
|
||||
deadline = t0 + duration
|
||||
watcher = LbWatcher(stats_url, t0)
|
||||
watcher.start()
|
||||
|
||||
def record(kind, ok, instance, latency):
|
||||
with lock:
|
||||
events.append((time.monotonic() - t0, kind, ok, instance, latency))
|
||||
|
||||
def writer(i):
|
||||
local = Client(base_url, timeout=3)
|
||||
key, n = uuid.uuid4().hex, 0
|
||||
text = f'probe-{i}-{n}'
|
||||
while time.monotonic() < deadline:
|
||||
start = time.monotonic()
|
||||
try:
|
||||
r = local.message(alice, chat, text, key=key)
|
||||
record('write', True, r['headers'].get('X-Instance-Id', ''), time.monotonic() - start)
|
||||
with lock:
|
||||
confirmed.append(r['json'])
|
||||
n += 1
|
||||
key, text = uuid.uuid4().hex, f'probe-{i}-{n}'
|
||||
except Failure:
|
||||
record('write', False, '', time.monotonic() - start)
|
||||
with lock:
|
||||
retries_with_same_key[0] += 1
|
||||
time.sleep(0.05) # тот же key и тот же body при следующей попытке
|
||||
|
||||
def reader(_i):
|
||||
local = Client(base_url, timeout=3)
|
||||
path = f"/api/v1/chats/{chat['id']}/messages?limit=20"
|
||||
while time.monotonic() < deadline:
|
||||
start = time.monotonic()
|
||||
try:
|
||||
r = local.call('GET', path, actor=bob, schema='MessagePage')
|
||||
record('read', True, r['headers'].get('X-Instance-Id', ''), time.monotonic() - start)
|
||||
except Failure:
|
||||
record('read', False, '', time.monotonic() - start)
|
||||
time.sleep(0.05)
|
||||
|
||||
threads = [threading.Thread(target=writer, args=(i,)) for i in range(writers)]
|
||||
threads += [threading.Thread(target=reader, args=(i,)) for i in range(readers)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
time.sleep(max(0.0, t0 + action_at - time.monotonic()))
|
||||
a_start = time.monotonic() - t0
|
||||
action_output = action()
|
||||
a_end = time.monotonic() - t0
|
||||
for t in threads:
|
||||
t.join()
|
||||
watcher.stop_flag.set()
|
||||
watcher.join()
|
||||
|
||||
# Сохранность: тот же токен, полная история через LB, без дублей.
|
||||
history, cursor = [], None
|
||||
while True:
|
||||
path = f"/api/v1/chats/{chat['id']}/messages?limit=100" + (f'&cursor={urllib.parse.quote(cursor, safe="")}' if cursor else '')
|
||||
page = c.call('GET', path, actor=bob, schema='MessagePage')['json']
|
||||
history += page['items']
|
||||
cursor = page['next_cursor']
|
||||
if cursor is None:
|
||||
break
|
||||
ids = {m['id'] for m in history}
|
||||
texts = [m['text'] for m in history]
|
||||
lost = sum(1 for m in confirmed if m['id'] not in ids)
|
||||
check(len(ids) == len(history), 'duplicated message id in history')
|
||||
check(len(texts) == len(set(texts)), 'retry with same key produced a duplicate message')
|
||||
check(lost == 0, f'{lost} confirmed messages lost')
|
||||
|
||||
def window(lo, hi):
|
||||
sel = [e for e in events if lo <= e[0] < hi]
|
||||
ok = [e for e in sel if e[2]]
|
||||
span = max(hi - lo, 1e-9)
|
||||
return {'seconds': round(span, 2), 'ok_rps': round(len(ok) / span, 1),
|
||||
'write_rps': round(sum(1 for e in ok if e[1] == 'write') / span, 1),
|
||||
'read_rps': round(sum(1 for e in ok if e[1] == 'read') / span, 1),
|
||||
'errors': len(sel) - len(ok),
|
||||
'p50_ms': percentile([e[4] for e in ok], .50), 'p95_ms': percentile([e[4] for e in ok], .95),
|
||||
'p99_ms': percentile([e[4] for e in ok], .99), 'max_ms': percentile([e[4] for e in ok], 1.0)}
|
||||
|
||||
errors = [e for e in events if not e[2]]
|
||||
target_prefixes = tuple(t['hostname'] + '-' for t in targets)
|
||||
served_by_target = [e[0] for e in events if e[2] and e[3].startswith(target_prefixes)]
|
||||
per_second = []
|
||||
for s in range(int(duration)):
|
||||
sel = [e for e in events if s <= e[0] < s + 1]
|
||||
per_second.append({'t': s, 'ok': sum(1 for e in sel if e[2]), 'err': sum(1 for e in sel if not e[2]),
|
||||
'instances': len({e[3] for e in sel if e[2]})})
|
||||
detection = {}
|
||||
for t in targets:
|
||||
seconds, state = watcher.first_not_up(t['ip'], a_start)
|
||||
detection[t['name']] = {'lb_marked_not_up_after_s': seconds, 'lb_state': state}
|
||||
lb_counters = None
|
||||
if watcher.first and watcher.last:
|
||||
lb_counters = {k: watcher.last[k] - watcher.first[k] for k in watcher.last}
|
||||
return {
|
||||
'targets': [{k: t[k] for k in ('name', 'hostname', 'revision')} for t in targets],
|
||||
'action_started_s': round(a_start, 3), 'action_duration_s': round(a_end - a_start, 3),
|
||||
'action_output': action_output,
|
||||
'before': window(1, a_start), 'during_action_plus_5s': window(a_start, a_end + 5),
|
||||
'after': window(a_end + 5, duration),
|
||||
'errors_total': len(errors),
|
||||
'write_attempts_retried_same_key': retries_with_same_key[0],
|
||||
'error_window_s': ([round(errors[0][0] - a_start, 3), round(errors[-1][0] - a_start, 3)] if errors else None),
|
||||
'recovery_s': round(errors[-1][0] - a_start, 3) if errors else 0.0,
|
||||
'target_last_served_after_action_s': (round(max(served_by_target) - a_start, 3)
|
||||
if served_by_target and max(served_by_target) >= a_start else None),
|
||||
'lb_detection': detection,
|
||||
'lb_retries_redispatches': lb_counters,
|
||||
'instances_after': sorted({e[3] for e in events if e[2] and e[0] > a_end + 5}),
|
||||
'confirmed_writes': len(confirmed), 'history_messages': len(history),
|
||||
'duplicates': 0, 'lost_confirmed': lost,
|
||||
'timeline_per_second': per_second,
|
||||
}
|
||||
|
||||
|
||||
def wait_lb_up(stats_url: str, ip: str, seconds: float = 60) -> None:
|
||||
deadline = time.monotonic() + seconds
|
||||
url = stats_url.rstrip('/') + ';csv'
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=1) as r:
|
||||
rows = csv.DictReader(io.StringIO(r.read().decode().lstrip('# ')))
|
||||
if any(row['pxname'] == 'api' and row.get('addr') == ip + ':8080' and row['status'].startswith('UP')
|
||||
for row in rows):
|
||||
return
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
raise Failure('replica did not return to LB rotation')
|
||||
|
||||
|
||||
def restore(stats_url: str) -> None:
|
||||
subprocess.run(['sh', str(ROOT / 'scripts/restore.sh')], check=True, capture_output=True)
|
||||
for name in api_containers():
|
||||
wait_lb_up(stats_url, container_info(name)['ip'])
|
||||
|
||||
|
||||
def main() -> int:
|
||||
p = argparse.ArgumentParser(description=__doc__.split('\n')[0])
|
||||
p.add_argument('--scenario', choices=['stop', 'kill', 'rolling'], required=True)
|
||||
p.add_argument('--base-url', default=os.environ.get('BASE_URL', 'http://localhost:8080'))
|
||||
p.add_argument('--stats-url', default=os.environ.get('LB_STATS_URL', 'http://localhost:8404/stats'))
|
||||
p.add_argument('--duration', type=float, default=None)
|
||||
p.add_argument('--action-at', type=float, default=8)
|
||||
p.add_argument('--writers', type=int, default=4)
|
||||
p.add_argument('--readers', type=int, default=2)
|
||||
p.add_argument('--output', default=None)
|
||||
args = p.parse_args()
|
||||
duration = args.duration or (45 if args.scenario == 'rolling' else 25)
|
||||
|
||||
runs = []
|
||||
if args.scenario == 'rolling':
|
||||
targets = [container_info(n) for n in api_containers()]
|
||||
|
||||
def action():
|
||||
r = subprocess.run(['sh', str(ROOT / 'scripts/rolling-update.sh')], text=True, capture_output=True)
|
||||
check(r.returncode == 0, 'rolling-update.sh failed: ' + r.stderr[-500:])
|
||||
return r.stdout.strip().splitlines()
|
||||
result = run_probe(args.base_url, args.stats_url, action, targets, duration, args.action_at,
|
||||
args.writers, args.readers)
|
||||
result['replicas_after'] = [container_info(n) for n in api_containers()]
|
||||
runs.append(result)
|
||||
else:
|
||||
for name in api_containers(): # по очереди каждую реплику, восстанавливая предыдущую
|
||||
restore(args.stats_url)
|
||||
target = container_info(name)
|
||||
|
||||
def action(name=name):
|
||||
started = time.monotonic()
|
||||
if args.scenario == 'kill':
|
||||
docker('kill', name)
|
||||
else:
|
||||
docker('stop', '-t', '20', name)
|
||||
state = docker('inspect', '-f', '{{.State.Status}} exit={{.State.ExitCode}}', name)
|
||||
return [f'{args.scenario} {name}: {state} in {time.monotonic() - started:.2f}s']
|
||||
result = run_probe(args.base_url, args.stats_url, action, [target], duration, args.action_at,
|
||||
args.writers, args.readers)
|
||||
runs.append(result)
|
||||
print(f"{args.scenario} {name}: errors={result['errors_total']} recovery={result['recovery_s']}s "
|
||||
f"lb_detection={result['lb_detection'][name]['lb_marked_not_up_after_s']}s "
|
||||
f"rps before/after={result['before']['ok_rps']}/{result['after']['ok_rps']}", flush=True)
|
||||
restore(args.stats_url)
|
||||
|
||||
report = {
|
||||
'scenario': args.scenario, 'date_utc': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
|
||||
'profile': {'duration_s': duration, 'action_at_s': args.action_at, 'writers': args.writers,
|
||||
'readers': args.readers, 'client_timeout_s': 3,
|
||||
'workload': 'closed-loop: POST message (retry same key on failure) + GET history limit=20'},
|
||||
'runs': runs,
|
||||
}
|
||||
text = json.dumps(report, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
Path(args.output).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(args.output).write_text(text + '\n', encoding='utf-8')
|
||||
summary = [{k: r[k] for k in ('targets', 'errors_total', 'recovery_s', 'lb_detection', 'action_duration_s',
|
||||
'target_last_served_after_action_s', 'lb_retries_redispatches')}
|
||||
| {'rps_before': r['before']['ok_rps'], 'rps_after': r['after']['ok_rps'],
|
||||
'p99_during_ms': r['during_action_plus_5s']['p99_ms']} for r in runs]
|
||||
print(json.dumps(summary, ensure_ascii=False, indent=1))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.9 KiB |
Executable
+207
@@ -0,0 +1,207 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Трек 1: нагрузка на очередь обработки изображений (запуск внутри сервиса tester; драйвер — scripts/track1.sh).
|
||||
|
||||
Методика:
|
||||
- OPEN-LOOP поступление: upload отправляются по расписанию (rate/s) независимо от скорости ответа, поэтому
|
||||
нет coordinated omission генератора; задержки отправки (если пул потоков не успел) фиксируются отдельно;
|
||||
- время до ready считается по серверным меткам PostgreSQL: attachments.created_at (момент COMMIT приёма) ->
|
||||
updated_at перехода в ready; это то, что видит клиент, опрашивая метаданные (без шума опроса);
|
||||
- queue lag: каждые 0.5 с — число незавершённых заданий (queued + processing) из attachment_jobs и
|
||||
глубина очереди RabbitMQ (messages_ready + unacked) — раз в 2 с;
|
||||
- память worker: docker stats контейнера worker (процесс + дочерние процессы обработки), раз в ~1 с;
|
||||
- throughput: число ready / (последний ready - первый принятый upload).
|
||||
Результат — JSON в evidence/track1/<label>.json (без токенов и ID пользователей).
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client # noqa: E402
|
||||
|
||||
BASE = os.environ.get('BASE_URL', 'http://lb:8080')
|
||||
PROJECT = 'mtusi-lab5'
|
||||
IMAGES = {
|
||||
'small': (ROOT / 'tests/fixtures/sample.png', 'image/png'), # 320x200, 112 KB
|
||||
'large': (ROOT / 'student-tests/.generated/large.jpg', 'image/jpeg'), # 4000x3000, ~3 MB
|
||||
}
|
||||
|
||||
|
||||
def sh(*args: str) -> str:
|
||||
return subprocess.run(args, check=True, text=True, capture_output=True).stdout.strip()
|
||||
|
||||
|
||||
def sql(query: str) -> str:
|
||||
return sh('docker', 'compose', '--env-file', str(ROOT / '.env'), 'exec', '-T', 'postgres',
|
||||
'psql', '-U', 'app', '-d', 'messenger', '-tAc', query)
|
||||
|
||||
|
||||
def worker_ids() -> list[str]:
|
||||
return sh('docker', 'ps', '-q', '--filter', f'label=com.docker.compose.project={PROJECT}',
|
||||
'--filter', 'label=com.docker.compose.service=worker').split()
|
||||
|
||||
|
||||
def mem_mib(value: str) -> float:
|
||||
number = float(''.join(ch for ch in value if ch.isdigit() or ch == '.'))
|
||||
unit = value.lstrip('0123456789.').strip().lower()
|
||||
return number * {'b': 1 / 2**20, 'kib': 1 / 1024, 'mib': 1, 'gib': 1024, 'kb': 1 / 1024, 'mb': 1, 'gb': 1024}.get(unit, 1)
|
||||
|
||||
|
||||
def pct(values: list[float], p: float) -> float | None:
|
||||
if not values:
|
||||
return None
|
||||
ordered = sorted(values)
|
||||
k = max(0, min(len(ordered) - 1, round(p / 100 * len(ordered) + 0.5) - 1))
|
||||
return round(ordered[k], 3)
|
||||
|
||||
|
||||
class Sampler(threading.Thread):
|
||||
def __init__(self, since: str):
|
||||
super().__init__(daemon=True)
|
||||
self.since = since
|
||||
self.stop = threading.Event()
|
||||
self.pending: list[tuple[float, int]] = []
|
||||
self.broker: list[tuple[float, int]] = []
|
||||
self.memory: list[tuple[float, float]] = []
|
||||
self.t0 = time.monotonic()
|
||||
|
||||
def run(self):
|
||||
tick = 0
|
||||
while not self.stop.is_set():
|
||||
t = round(time.monotonic() - self.t0, 2)
|
||||
try:
|
||||
n = int(sql("SELECT count(*) FROM attachment_jobs WHERE status IN ('queued','processing') "
|
||||
f"AND created_at >= '{self.since}'"))
|
||||
self.pending.append((t, n))
|
||||
if tick % 2 == 0:
|
||||
stats = sh('docker', 'stats', '--no-stream', '--format', '{{.MemUsage}}', *worker_ids())
|
||||
self.memory.append((t, round(sum(mem_mib(line.split('/')[0]) for line in stats.splitlines()), 1)))
|
||||
if tick % 4 == 0:
|
||||
out = sh('docker', 'compose', '--env-file', str(ROOT / '.env'), 'exec', '-T', 'rabbitmq',
|
||||
'rabbitmqctl', '-q', 'list_queues', 'name', 'messages')
|
||||
for line in out.splitlines():
|
||||
parts = line.split()
|
||||
if parts and parts[0] == 'attachment.process.v1':
|
||||
self.broker.append((t, int(parts[1])))
|
||||
except (subprocess.CalledProcessError, ValueError):
|
||||
pass
|
||||
tick += 1
|
||||
self.stop.wait(0.5)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument('--label', required=True)
|
||||
p.add_argument('--size', choices=IMAGES, required=True)
|
||||
p.add_argument('--count', type=int, required=True)
|
||||
p.add_argument('--rate', type=float, required=True, help='uploads per second (open loop)')
|
||||
p.add_argument('--timeout', type=float, default=600)
|
||||
args = p.parse_args()
|
||||
|
||||
path, ctype = IMAGES[args.size]
|
||||
data = path.read_bytes()
|
||||
c = Client(BASE, timeout=60)
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
url = f"{BASE}/api/v1/chats/{chat['id']}/attachments?filename=load.{'png' if ctype == 'image/png' else 'jpg'}"
|
||||
config = {k: sh('docker', 'inspect', '-f', '{{range .Config.Env}}{{println .}}{{end}}', worker_ids()[0])
|
||||
for k in ['env']}['env']
|
||||
env = dict(line.split('=', 1) for line in config.splitlines() if '=' in line)
|
||||
api = sh('docker', 'ps', '-q', '--filter', f'label=com.docker.compose.project={PROJECT}',
|
||||
'--filter', 'label=com.docker.compose.service=api').split()[0]
|
||||
api_env = dict(line.split('=', 1) for line in sh('docker', 'inspect', '-f',
|
||||
'{{range .Config.Env}}{{println .}}{{end}}', api).splitlines() if '=' in line)
|
||||
since = sql('SELECT clock_timestamp()')
|
||||
|
||||
results, lock = [], threading.Lock()
|
||||
|
||||
def send(i: int, planned: float) -> None:
|
||||
late = time.monotonic() - planned
|
||||
req = urllib.request.Request(url, data=data, method='POST', headers={
|
||||
'Content-Type': ctype, 'Authorization': 'Bearer ' + alice['token']})
|
||||
started = time.monotonic()
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=60) as r:
|
||||
status, body = r.status, json.loads(r.read())
|
||||
except urllib.error.HTTPError as e:
|
||||
status, body = e.code, None
|
||||
e.read()
|
||||
except OSError:
|
||||
status, body = 'error', None
|
||||
with lock:
|
||||
results.append({'status': status, 'id': body['id'] if body else None,
|
||||
'upload_s': time.monotonic() - started, 'late_s': late})
|
||||
|
||||
sampler = Sampler(since)
|
||||
sampler.start()
|
||||
t0 = time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=48) as pool:
|
||||
for i in range(args.count):
|
||||
planned = t0 + i / args.rate
|
||||
delay = planned - time.monotonic()
|
||||
if delay > 0:
|
||||
time.sleep(delay)
|
||||
pool.submit(send, i, planned)
|
||||
submit_done = time.monotonic() - t0
|
||||
accepted = [r['id'] for r in results if r['status'] == 202]
|
||||
deadline = time.monotonic() + args.timeout
|
||||
while time.monotonic() < deadline:
|
||||
left = int(sql("SELECT count(*) FROM attachment_jobs WHERE status IN ('queued','processing') "
|
||||
f"AND created_at >= '{since}'"))
|
||||
if left == 0:
|
||||
break
|
||||
time.sleep(1)
|
||||
drained_at = time.monotonic() - t0
|
||||
sampler.stop.set()
|
||||
sampler.join(5)
|
||||
|
||||
rows = sql("SELECT a.status, extract(epoch FROM a.updated_at - a.created_at), "
|
||||
"extract(epoch FROM a.created_at), extract(epoch FROM a.updated_at) FROM attachments a "
|
||||
f"WHERE a.chat_id = '{chat['id']}'").splitlines()
|
||||
ready = [list(map(float, r.split('|')[1:])) for r in rows if r.startswith('ready|')]
|
||||
lat = [x[0] for x in ready]
|
||||
statuses = {}
|
||||
for r in results:
|
||||
statuses[str(r['status'])] = statuses.get(str(r['status']), 0) + 1
|
||||
span = (max(x[2] for x in ready) - min(x[1] for x in ready)) if ready else 0
|
||||
summary = {
|
||||
'label': args.label, 'size': args.size, 'bytes': len(data), 'count': args.count, 'rate_per_s': args.rate,
|
||||
'worker': {k: env.get(k) for k in ('WORKER_CONCURRENCY', 'WORKER_PREFETCH', 'WORKER_TASK_MEMORY_MB')},
|
||||
'worker_replicas': len(worker_ids()), 'max_pending_jobs': api_env.get('MAX_PENDING_JOBS'),
|
||||
'upload_status': statuses, 'accepted': len(accepted),
|
||||
'ready': len(ready), 'failed': sum(1 for r in rows if r.startswith('failed|')),
|
||||
'lost_accepted': len(accepted) - len(rows),
|
||||
'submit_seconds': round(submit_done, 2), 'drain_seconds': round(drained_at, 2),
|
||||
'throughput_ready_per_s': round(len(ready) / span, 3) if span else None,
|
||||
'time_to_ready_s': {'p50': pct(lat, 50), 'p95': pct(lat, 95), 'p99': pct(lat, 99),
|
||||
'max': round(max(lat), 3) if lat else None,
|
||||
'mean': round(statistics.mean(lat), 3) if lat else None},
|
||||
'upload_latency_s': {'p50': pct([r['upload_s'] for r in results], 50),
|
||||
'p95': pct([r['upload_s'] for r in results], 95)},
|
||||
'generator_max_late_s': round(max(r['late_s'] for r in results), 3),
|
||||
'queue_lag': {'max_pending_jobs': max((n for _, n in sampler.pending), default=0),
|
||||
'max_broker_messages': max((n for _, n in sampler.broker), default=0)},
|
||||
'worker_memory_mib': {'peak': max((m for _, m in sampler.memory), default=None),
|
||||
'idle_first': sampler.memory[0][1] if sampler.memory else None},
|
||||
'timeline': {'pending': sampler.pending, 'broker': sampler.broker, 'memory': sampler.memory},
|
||||
}
|
||||
out = ROOT / 'evidence/track1' / f'{args.label}.json'
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_text(json.dumps(summary, ensure_ascii=False, indent=1), encoding='utf-8')
|
||||
short = {k: summary[k] for k in ('label', 'upload_status', 'ready', 'failed', 'lost_accepted',
|
||||
'throughput_ready_per_s', 'time_to_ready_s', 'queue_lag', 'worker_memory_mib',
|
||||
'drain_seconds')}
|
||||
print(json.dumps(short, ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Executable
+15
@@ -0,0 +1,15 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Один вход (одна сессия) -> 10 запросов через LB: какие реплики обслужили. Токен не печатается."""
|
||||
import os
|
||||
import sys
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client # noqa: E402
|
||||
|
||||
c = Client(os.environ.get('BASE_URL', 'http://lb:8080'))
|
||||
alice = c.user('instances')
|
||||
served = [c.call('GET', '/api/v1/users/me', actor=alice, schema='User')['headers']['X-Instance-Id'] for _ in range(10)]
|
||||
print('X-Instance-Id sequence:', ' '.join(served))
|
||||
print('distinct replicas for one session without re-login:', dict(Counter(served)))
|
||||
Executable
+256
@@ -0,0 +1,256 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Регрессия: собственные проверки уровня 4 из lab2, перенесённые на стенд lab3 (через LB).
|
||||
Запуск: sh scripts/test-lab3.sh (внутри сервиса tester).
|
||||
|
||||
Требуют запущенный стенд и доступ к docker (останавливают/ставят на паузу valkey и postgres,
|
||||
затем возвращают их). Используют только синтетические данные.
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, Failure, check # noqa: E402
|
||||
|
||||
BASE_URL = os.environ.get('BASE_URL', 'http://lb:8080')
|
||||
TTL_BASE_URL = os.environ.get('TTL_BASE_URL', 'http://api-ttl:8080')
|
||||
VALKEY_CLI = 'valkey-cli --no-auth-warning -a "$(sed -n "s/^requirepass //p" /run/secrets/valkey_conf)" '
|
||||
|
||||
|
||||
def compose(*args: str, capture: bool = False) -> str:
|
||||
result = subprocess.run(['docker', 'compose', '--env-file', str(ROOT / '.env'), *args],
|
||||
cwd=ROOT, check=True, text=True,
|
||||
stdout=subprocess.PIPE if capture else subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL)
|
||||
return (result.stdout or '').strip()
|
||||
|
||||
|
||||
def sql(query: str) -> str:
|
||||
return compose('exec', '-T', 'postgres', 'psql', '-U', 'app', '-d', 'messenger', '-tAc', query, capture=True)
|
||||
|
||||
|
||||
def valkey(command: str) -> str:
|
||||
return compose('exec', '-T', 'valkey', 'sh', '-c', VALKEY_CLI + command, capture=True)
|
||||
|
||||
|
||||
def basic(username: str, password: str) -> dict:
|
||||
return {'Authorization': 'Basic ' + base64.b64encode(f'{username}:{password}'.encode()).decode()}
|
||||
|
||||
|
||||
def wait_ready(c: Client, seconds: float = 60) -> None:
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
try:
|
||||
c.call('GET', '/health/ready', schema='Health')
|
||||
return
|
||||
except Failure:
|
||||
check(time.monotonic() < deadline, 'API did not become ready')
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def wait_healthy(service: str, seconds: float = 60) -> None:
|
||||
deadline = time.monotonic() + seconds
|
||||
container = compose('ps', '-q', service, capture=True)
|
||||
while subprocess.run(['docker', 'inspect', '-f', '{{.State.Health.Status}}', container],
|
||||
text=True, capture_output=True).stdout.strip() != 'healthy':
|
||||
check(time.monotonic() < deadline, service + ' did not become healthy')
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def cache_key(actor: dict) -> str:
|
||||
return 'session:' + hashlib.sha256(actor['token'].encode()).hexdigest()
|
||||
|
||||
|
||||
def wait_cache_used(c: Client, actor: dict, seconds: float = 75) -> None:
|
||||
"""После недавнего сбоя Valkey API законно не доверяет кэшу SESSION_CACHE_TTL_SECONDS — ждём конца окна."""
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
c.call('GET', '/api/v1/users/me', actor=actor, schema='User')
|
||||
if valkey('EXISTS ' + cache_key(actor)) == '1':
|
||||
return
|
||||
check(time.monotonic() < deadline, 'session was never cached in Valkey')
|
||||
time.sleep(2)
|
||||
|
||||
|
||||
def bearer(token: str) -> dict:
|
||||
return {'Authorization': 'Bearer ' + token}
|
||||
|
||||
# ---------------------------------------------------------------- тесты
|
||||
|
||||
|
||||
def test_wrong_password(c: Client):
|
||||
alice = c.user('wrongpw')
|
||||
username = alice['registration']['username']
|
||||
wrong = c.call('POST', '/api/v1/auth/sessions', 401, headers=basic(username, 'definitely-wrong-password'))
|
||||
unknown = c.call('POST', '/api/v1/auth/sessions', 401, headers=basic('no_such_' + uuid.uuid4().hex[:8], 'whatever-password-123'))
|
||||
# Одинаковый ответ: по нему нельзя узнать, существует ли username.
|
||||
check(wrong['json']['error']['message'] == unknown['json']['error']['message'], 'different 401 for unknown user')
|
||||
check(wrong['headers']['WWW-Authenticate'] == 'Basic realm="messenger", charset="UTF-8"', 'wrong Basic challenge')
|
||||
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': 'Basic !!!not-base64'})
|
||||
c.call('POST', '/api/v1/auth/sessions', 401, headers=bearer(alice['token'])) # Bearer на входе не принимается
|
||||
|
||||
|
||||
def test_logout(c: Client):
|
||||
alice = c.user('logout')
|
||||
c.call('GET', '/api/v1/users/me', actor=alice, schema='User')
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
|
||||
r = c.call('GET', '/api/v1/users/me', 401, actor=alice)
|
||||
check(r['headers']['WWW-Authenticate'] == 'Bearer realm="messenger"', 'wrong Bearer challenge')
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 401, actor=alice)
|
||||
revoked = sql("SELECT count(*) FROM sessions s JOIN users u ON u.id = s.user_id "
|
||||
f"WHERE u.username = '{alice['registration']['username']}' AND s.revoked_at IS NOT NULL")
|
||||
check(revoked == '1', 'revocation not recorded in PostgreSQL')
|
||||
|
||||
|
||||
def test_short_ttl(_c: Client):
|
||||
# Отдельная реплика api-ttl с SESSION_TTL_SECONDS=2, общая БД и кэш.
|
||||
c = Client(TTL_BASE_URL)
|
||||
wait_ready(c)
|
||||
alice = c.user('ttl')
|
||||
c.call('GET', '/api/v1/users/me', actor=alice, schema='User')
|
||||
time.sleep(3)
|
||||
c.call('GET', '/api/v1/users/me', 401, actor=alice)
|
||||
|
||||
|
||||
def test_username_race(c: Client):
|
||||
username = 'race_' + uuid.uuid4().hex[:12]
|
||||
body = {'username': username, 'display_name': 'Гонка', 'password': 'Race-password-' + uuid.uuid4().hex}
|
||||
statuses, barrier = [], threading.Barrier(16)
|
||||
|
||||
def register():
|
||||
barrier.wait()
|
||||
statuses.append(Client(BASE_URL, timeout=30).call('POST', '/api/v1/users', [201, 409], body=body)['status'])
|
||||
|
||||
threads = [threading.Thread(target=register) for _ in range(16)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
check(sorted(statuses) == [201] + [409] * 15, f'race result {sorted(statuses)}')
|
||||
check(sql(f"SELECT count(*) FROM users WHERE username = '{username}'") == '1', 'duplicate username row')
|
||||
|
||||
|
||||
def test_chat_rollback(c: Client):
|
||||
alice = c.user('rollback')
|
||||
before = sql('SELECT (SELECT count(*) FROM chats) || \' \' || (SELECT count(*) FROM chat_members)')
|
||||
# Второй участник не существует: INSERT chats уже выполнен, INSERT chat_members вставит 1 из 2 -> ROLLBACK.
|
||||
c.call('POST', '/api/v1/chats', 400, actor=alice,
|
||||
body={'title': 'Откат', 'member_ids': [alice['id'], str(uuid.uuid4())]})
|
||||
after = sql('SELECT (SELECT count(*) FROM chats) || \' \' || (SELECT count(*) FROM chat_members)')
|
||||
check(before == after, f'partial chat left after failure: {before} -> {after}')
|
||||
listed = c.call('GET', '/api/v1/chats', actor=alice, schema='ChatPage')['json']
|
||||
check(listed['items'] == [], 'failed chat is visible')
|
||||
|
||||
|
||||
def test_cursor_rules(c: Client):
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
other = c.call('POST', '/api/v1/chats', 201, actor=alice, body={'title': 'Другой', 'member_ids': [alice['id']]},
|
||||
schema='Chat')['json']
|
||||
for i in range(3):
|
||||
c.message(alice, chat, f'm{i}')
|
||||
c.message(alice, other, f'o{i}')
|
||||
page = c.call('GET', f'/api/v1/chats/{chat["id"]}/messages?limit=1', actor=alice, schema='MessagePage')['json']
|
||||
from urllib.parse import quote
|
||||
cursor = quote(page['next_cursor'], safe='')
|
||||
c.call('GET', f'/api/v1/chats/{other["id"]}/messages?cursor={cursor}', 400, actor=alice) # курсор чужого чата
|
||||
c.call('GET', f'/api/v1/chats/{chat["id"]}/messages?cursor=garbage', 400, actor=alice)
|
||||
c.call('GET', f'/api/v1/chats/{chat["id"]}/messages?limit=101', 400, actor=alice)
|
||||
c.call('POST', '/api/v1/chats', 400, actor=alice, body={'title': 'x', 'member_ids': [alice['id']], 'extra': 1})
|
||||
c.call('POST', f'/api/v1/chats/{chat["id"]}/messages', 400, actor=bob, body={'text': 'x', 'sender_id': alice['id']})
|
||||
|
||||
|
||||
def test_valkey_cache_role(c: Client):
|
||||
alice = c.user('cache')
|
||||
wait_cache_used(c, alice)
|
||||
ttl = int(valkey('TTL ' + cache_key(alice)))
|
||||
check(0 < ttl <= 60, f'unexpected cache TTL {ttl}')
|
||||
valkey('FLUSHALL') # потеря всего кэша
|
||||
c.call('GET', '/api/v1/users/me', actor=alice, schema='User') # источник истины — PostgreSQL
|
||||
check(valkey('EXISTS ' + cache_key(alice)) == '1', 'cache was not refilled on miss')
|
||||
|
||||
|
||||
def test_valkey_down(c: Client):
|
||||
alice = c.user('vkdown')
|
||||
try:
|
||||
compose('stop', 'valkey')
|
||||
c.call('GET', '/api/v1/users/me', actor=alice, schema='User') # обход кэша через PostgreSQL
|
||||
c.call('GET', '/api/v1/users/me', 401, headers=bearer('A' * 43)) # неизвестный токен — не доверяем
|
||||
c.call('GET', '/api/v1/users/me', 401) # аноним — 401
|
||||
bob = c.user('vkdown_login') # вход работает без кэша
|
||||
c.call('GET', '/health/ready', schema='Health') # Valkey не критичен
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=bob)
|
||||
c.call('GET', '/api/v1/users/me', 401, actor=bob)
|
||||
finally:
|
||||
compose('start', 'valkey')
|
||||
wait_healthy('valkey')
|
||||
|
||||
|
||||
def test_revoke_during_cache_partition(c: Client):
|
||||
# Худший случай инвалидации: logout во время разрыва API <-> Valkey, DEL потерян, а копия отозванной
|
||||
# сессии в Valkey пережила разрыв. Окно недоверия к кэшу (SESSION_CACHE_TTL_SECONDS после ошибки)
|
||||
# не даёт её использовать. TCP может доставить DEL повторной передачей после восстановления сети,
|
||||
# поэтому потерю DEL моделируем явно: возвращаем сохранённую до разрыва копию записи.
|
||||
alice = c.user('partition')
|
||||
wait_cache_used(c, alice)
|
||||
key = cache_key(alice)
|
||||
stale_value = valkey('GET ' + key)
|
||||
container = compose('ps', '-q', 'valkey', capture=True)
|
||||
network = 'mtusi-lab5_data' # Valkey в lab3 только во внутренней сети data
|
||||
subprocess.run(['docker', 'network', 'disconnect', network, container], check=True)
|
||||
try:
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice) # COMMIT в PostgreSQL прошёл
|
||||
finally:
|
||||
subprocess.run(['docker', 'network', 'connect', '--alias', 'valkey', network, container], check=True)
|
||||
valkey(f"SET {key} '{stale_value}' EX 60")
|
||||
c.call('GET', '/api/v1/users/me', 401, actor=alice)
|
||||
|
||||
|
||||
def test_postgres_down(c: Client):
|
||||
alice = c.user('pgdown')
|
||||
c.call('GET', '/api/v1/users/me', actor=alice, schema='User')
|
||||
try:
|
||||
compose('stop', 'postgres')
|
||||
c.call('GET', '/health/live', schema='Health')
|
||||
c.call('GET', '/health/ready', 503)
|
||||
r = c.call('GET', '/api/v1/users/me', 503, actor=alice) # ограниченная ошибка, не 500/200
|
||||
check(r['json']['error']['code'] == 'unavailable', 'expected unavailable')
|
||||
c.call('GET', '/api/v1/users/me', 503, headers=bearer('B' * 43)) # неизвестный токен не проходит
|
||||
c.call('GET', '/api/v1/chats', 401) # аноним не пропускается
|
||||
c.call('POST', '/api/v1/users', 503, body={'username': 'pg_' + uuid.uuid4().hex[:8],
|
||||
'display_name': 'x', 'password': 'Password-123456'})
|
||||
finally:
|
||||
compose('start', 'postgres')
|
||||
wait_ready(c)
|
||||
c.call('GET', '/api/v1/users/me', actor=alice, schema='User') # та же сессия жива после рестарта БД
|
||||
|
||||
|
||||
TESTS = [test_wrong_password, test_logout, test_short_ttl, test_username_race, test_chat_rollback,
|
||||
test_cursor_rules, test_valkey_cache_role, test_revoke_during_cache_partition, test_valkey_down,
|
||||
test_postgres_down]
|
||||
|
||||
|
||||
def main() -> int:
|
||||
c = Client(BASE_URL)
|
||||
wait_ready(c)
|
||||
failed = 0
|
||||
for test in TESTS:
|
||||
started = time.monotonic()
|
||||
try:
|
||||
test(c)
|
||||
print(f'PASS {test.__name__} ({time.monotonic() - started:.1f}s)')
|
||||
except (Failure, subprocess.CalledProcessError, OSError) as exc:
|
||||
failed += 1
|
||||
print(f'FAIL {test.__name__}: {exc}')
|
||||
print(f'{len(TESTS) - failed}/{len(TESTS)} passed')
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
Executable
+308
@@ -0,0 +1,308 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Собственные проверки lab3 (уровни 3–4), в lab4 — регрессия. Запуск: sh scripts/test-lab4.sh (внутри сервиса tester).
|
||||
|
||||
Обращаются к репликам и НАПРЯМУЮ (по IP из DNS Docker внутри сети edge), чтобы гарантировать, что
|
||||
конкурентные повторы действительно приходят в разные процессы, а не полагаться на round-robin LB.
|
||||
Требуют доступ к docker (останавливают postgres, шлют SIGTERM реплике и возвращают всё обратно).
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, Failure, check # noqa: E402
|
||||
|
||||
BASE_URL = os.environ.get('BASE_URL', 'http://lb:8080')
|
||||
PROJECT = 'mtusi-lab5'
|
||||
API_FILTER = ['--filter', f'label=com.docker.compose.project={PROJECT}',
|
||||
'--filter', 'label=com.docker.compose.service=api']
|
||||
|
||||
|
||||
def compose(*args: str, capture: bool = False) -> str:
|
||||
result = subprocess.run(['docker', 'compose', '--env-file', str(ROOT / '.env'), *args],
|
||||
cwd=ROOT, check=True, text=True,
|
||||
stdout=subprocess.PIPE if capture else subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL)
|
||||
return (result.stdout or '').strip()
|
||||
|
||||
|
||||
def docker(*args: str) -> str:
|
||||
return subprocess.run(['docker', *args], check=True, text=True, capture_output=True).stdout.strip()
|
||||
|
||||
|
||||
def sql(query: str) -> str:
|
||||
return compose('exec', '-T', 'postgres', 'psql', '-U', 'app', '-d', 'messenger', '-tAc', query, capture=True)
|
||||
|
||||
|
||||
def replica_urls() -> list[str]:
|
||||
"""Все IP сервиса api из DNS Docker -> прямые адреса реплик (порты наружу не опубликованы)."""
|
||||
ips = sorted({info[4][0] for info in socket.getaddrinfo('api', 8080, socket.AF_INET, socket.SOCK_STREAM)})
|
||||
check(len(ips) >= 2, f'expected >= 2 api replicas in DNS, got {len(ips)}')
|
||||
return [f'http://{ip}:8080' for ip in ips]
|
||||
|
||||
|
||||
def wait_ready(c: Client, seconds: float = 60) -> None:
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
try:
|
||||
c.call('GET', '/health/ready', schema='Health')
|
||||
return
|
||||
except Failure:
|
||||
check(time.monotonic() < deadline, 'API did not become ready')
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def raw_post(base: str, path: str, actor: dict, raw: bytes, key: str | None):
|
||||
"""POST с заданными байтами тела (для проверки семантического равенства JSON)."""
|
||||
headers = {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + actor['token']}
|
||||
if key is not None:
|
||||
headers['Idempotency-Key'] = key
|
||||
return Client(base).call('POST', path, [201, 400, 409], raw=raw, headers=headers, schema='Message')
|
||||
|
||||
|
||||
def concurrent(calls: list) -> list:
|
||||
"""Запускает функции одновременно (barrier) и возвращает результаты в исходном порядке."""
|
||||
results = [None] * len(calls)
|
||||
barrier = threading.Barrier(len(calls))
|
||||
|
||||
def run(i):
|
||||
barrier.wait()
|
||||
try:
|
||||
results[i] = calls[i]()
|
||||
except Exception as exc: # результат проверяет вызывающий тест
|
||||
results[i] = exc
|
||||
|
||||
threads = [threading.Thread(target=run, args=(i,)) for i in range(len(calls))]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
return results
|
||||
|
||||
|
||||
def count_messages(chat: dict) -> int:
|
||||
return int(sql(f"SELECT count(*) FROM messages WHERE chat_id = '{chat['id']}'"))
|
||||
|
||||
# ---------------------------------------------------------------- тесты
|
||||
|
||||
|
||||
def test_session_across_replicas(c: Client):
|
||||
alice = c.user('xrepl') # вход через LB (обслужила какая-то одна реплика)
|
||||
seen = {c.call('GET', '/api/v1/users/me', actor=alice, schema='User')['headers']['X-Instance-Id']
|
||||
for _ in range(20)}
|
||||
check(len(seen) >= 2, f'one session must be served by >= 2 replicas, saw {seen}')
|
||||
urls = replica_urls()
|
||||
for url in urls: # каждая реплика напрямую принимает тот же токен
|
||||
me = Client(url).call('GET', '/api/v1/users/me', actor=alice, schema='User')['json']
|
||||
check(me['id'] == alice['id'], 'replica resolved another user')
|
||||
Client(urls[0]).call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
|
||||
for url in urls: # logout на одной реплике виден всем (общий store)
|
||||
Client(url).call('GET', '/api/v1/users/me', 401, actor=alice)
|
||||
|
||||
|
||||
def test_same_key_concurrent_across_replicas(c: Client):
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
urls, key = replica_urls(), uuid.uuid4().hex
|
||||
calls = [lambda u=urls[i % len(urls)]: Client(u, timeout=15).message(alice, chat, 'один раз', key=key)
|
||||
for i in range(24)]
|
||||
results = concurrent(calls)
|
||||
failures = [r for r in results if isinstance(r, Exception)]
|
||||
check(not failures, f'concurrent retry failed: {failures[:1]}')
|
||||
bodies = {json.dumps(r['json'], sort_keys=True) for r in results}
|
||||
instances = {r['headers']['X-Instance-Id'] for r in results}
|
||||
check(len(bodies) == 1, f'{len(bodies)} different messages returned for one key')
|
||||
check(len(instances) >= 2, 'retries did not hit different replicas')
|
||||
check(count_messages(chat) == 1, f'{count_messages(chat)} messages stored for one key')
|
||||
via_lb = c.message(alice, chat, 'один раз', key=key)['json'] # и позже через LB — тот же ответ
|
||||
check(json.dumps(via_lb, sort_keys=True) in bodies, 'later replay differs')
|
||||
|
||||
|
||||
def test_same_key_concurrent_different_bodies(c: Client):
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
urls, key = replica_urls(), uuid.uuid4().hex
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
|
||||
def send(url, text):
|
||||
return Client(url, timeout=15).call('POST', path, [201, 409], actor=alice, body={'text': text},
|
||||
headers={'Idempotency-Key': key}, schema='Message')
|
||||
calls = [lambda u=urls[i % len(urls)], t=('A' if i % 2 else 'B'): send(u, t) for i in range(20)]
|
||||
results = concurrent(calls)
|
||||
check(not any(isinstance(r, Exception) for r in results), 'unexpected status in conflicting retries')
|
||||
winners = {r['json']['text'] for r in results if r['status'] == 201}
|
||||
check(len(winners) == 1, f'both bodies accepted for one key: {winners}')
|
||||
loser_statuses = {r['status'] for r in results if r['status'] != 201}
|
||||
check(loser_statuses <= {409}, 'different body must be 409')
|
||||
check(sum(r['status'] == 409 for r in results) == 10, 'every other-body request must get 409')
|
||||
check(count_messages(chat) == 1, 'conflicting retries stored more than one message')
|
||||
|
||||
|
||||
def test_key_scope_and_format(c: Client):
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
other = c.call('POST', '/api/v1/chats', 201, actor=alice, body={'title': 'Другой', 'member_ids': [alice['id']]},
|
||||
schema='Chat')['json']
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
key = 'scope.' + uuid.uuid4().hex + ':1-x_y' # все допустимые символы
|
||||
first = c.message(alice, chat, 'область', key=key)['json']
|
||||
check(c.message(bob, chat, 'область', key=key)['json']['id'] != first['id'], 'key shared between users')
|
||||
check(c.message(alice, other, 'область', key=key)['json']['id'] != first['id'], 'key shared between chats')
|
||||
# Семантически тот же JSON другими байтами (пробелы, \u-экранирование) — тот же ответ.
|
||||
same = raw_post(BASE_URL, path, alice, b'{ "text" : "\\u043e\\u0431\\u043b\\u0430\\u0441\\u0442\\u044c" }', key)
|
||||
check(same['status'] == 201 and same['json'] == first, 'semantically equal JSON was not a replay')
|
||||
conflict = raw_post(BASE_URL, path, alice, json.dumps({'text': 'иначе'}).encode(), key)
|
||||
check(conflict['status'] == 409 and conflict['json']['error']['code'] == 'conflict', 'expected 409 conflict')
|
||||
check(c.message(alice, chat, 'область', key=key)['json'] == first, '409 must not replace stored result')
|
||||
for bad in (None, '', 'has space', 'café', 'x' * 129, 'a/b'):
|
||||
r = raw_post(BASE_URL, path, alice, b'{"text":"bad key"}', bad)
|
||||
check(r['status'] == 400, f'invalid key {bad!r} accepted')
|
||||
check(len(c.message(alice, chat, 'max', key='k' * 128)['json']['id']) == 36, '128-char key rejected')
|
||||
check(count_messages(chat) == 3, 'unexpected number of messages in scope test') # alice x2, bob x1
|
||||
|
||||
|
||||
def test_replay_rechecks_session(c: Client):
|
||||
alice, _bob, eve, chat = c.bootstrap()
|
||||
key = uuid.uuid4().hex
|
||||
c.message(alice, chat, 'до выхода', key=key)
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
# Посторонний с тем же ключом не получает чужой результат.
|
||||
c.call('POST', path, 404, actor=eve, body={'text': 'до выхода'}, headers={'Idempotency-Key': key})
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
|
||||
c.call('POST', path, 401, actor=alice, body={'text': 'до выхода'}, headers={'Idempotency-Key': key})
|
||||
|
||||
|
||||
def test_transient_failure_not_recorded(c: Client):
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
key = uuid.uuid4().hex
|
||||
try:
|
||||
compose('stop', 'postgres')
|
||||
r = c.call('POST', f"/api/v1/chats/{chat['id']}/messages", 503, actor=alice,
|
||||
body={'text': 'после сбоя'}, headers={'Idempotency-Key': key})
|
||||
check(r['json']['error']['code'] == 'unavailable', 'expected unavailable')
|
||||
check(bool(r['headers'].get('X-Instance-Id')), '503 must come from API (fallback backend), not LB')
|
||||
c.call('GET', '/health/live', schema='Health')
|
||||
finally:
|
||||
compose('start', 'postgres')
|
||||
wait_ready(c)
|
||||
first = c.message(alice, chat, 'после сбоя', key=key)['json'] # повтор с тем же ключом создаёт запись
|
||||
check(c.message(alice, chat, 'после сбоя', key=key)['json'] == first, 'replay after recovery differs')
|
||||
check(count_messages(chat) == 1, 'transient failure produced extra message')
|
||||
|
||||
|
||||
def test_sigterm_drain(c: Client):
|
||||
"""SIGTERM: реплика сначала отвечает ready=503, но ещё обслуживает запросы, затем завершается с кодом 0."""
|
||||
alice = c.user('drain')
|
||||
names = docker('ps', *API_FILTER, '--format', '{{.Names}}').split()
|
||||
name = sorted(names)[0]
|
||||
ip = docker('inspect', '-f', '{{(index .NetworkSettings.Networks "%s_edge").IPAddress}}' % PROJECT, name)
|
||||
direct = Client(f'http://{ip}:8080', timeout=2)
|
||||
docker('kill', '-s', 'TERM', name)
|
||||
signalled = time.monotonic()
|
||||
try:
|
||||
time.sleep(0.3)
|
||||
direct.call('GET', '/health/ready', 503)
|
||||
direct.call('GET', '/health/live', schema='Health')
|
||||
r = direct.call('GET', '/api/v1/users/me', actor=alice, schema='User')
|
||||
check(r['headers'].get('Connection', '').lower() == 'close', 'draining replica must close keep-alive')
|
||||
time.sleep(max(0.0, signalled + 2.0 - time.monotonic())) # окно обнаружения LB: fall 2 x 0.5-1 с
|
||||
served = {c.call('GET', '/api/v1/users/me', actor=alice, schema='User')['headers']['X-Instance-Id']
|
||||
for _ in range(10)} # LB уже не отправляет на неё запросы
|
||||
deadline = time.monotonic() + 20
|
||||
while docker('inspect', '-f', '{{.State.Status}}', name) != 'exited':
|
||||
check(time.monotonic() < deadline, 'replica did not exit after drain')
|
||||
time.sleep(0.2)
|
||||
code = docker('inspect', '-f', '{{.State.ExitCode}}', name)
|
||||
check(code in ('0', '143'), f'unclean exit code {code}')
|
||||
hostname = docker('inspect', '-f', '{{.Config.Hostname}}', name)
|
||||
check(not any(i.startswith(hostname) for i in served), 'LB still routes to the draining replica')
|
||||
finally:
|
||||
subprocess.run(['sh', str(ROOT / 'scripts/restore.sh')], check=True, capture_output=True)
|
||||
deadline = time.monotonic() + 30
|
||||
while len({c.call('GET', '/health/live', schema='Health')['headers']['X-Instance-Id'] for _ in range(10)}) < 2:
|
||||
check(time.monotonic() < deadline, 'restored replica did not return to LB')
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def test_infrastructure_rules(_c: Client):
|
||||
containers = docker('ps', '--filter', f'label=com.docker.compose.project={PROJECT}', '--format', '{{.Names}}').split()
|
||||
for name in containers:
|
||||
cfg = json.loads(docker('inspect', name))[0]
|
||||
service = cfg['Config']['Labels']['com.docker.compose.service']
|
||||
if service == 'tester':
|
||||
continue
|
||||
host = cfg['HostConfig']
|
||||
check(host['NanoCpus'] > 0 and host['Memory'] > 0, f'{name}: no CPU/RAM limit')
|
||||
check(name.startswith(f'{PROJECT}-{service}-'), f'{name}: fixed container_name prevents scaling')
|
||||
bindings = host.get('PortBindings') or {}
|
||||
if service == 'lb':
|
||||
check(all(b['HostIp'] == '127.0.0.1' for v in bindings.values() for b in v), 'LB published beyond loopback')
|
||||
else:
|
||||
check(not bindings, f'{name} publishes ports in bypass of LB')
|
||||
if service == 'api':
|
||||
check(cfg['HostConfig']['ReadonlyRootfs'], 'api root fs must be read-only (no local state)')
|
||||
mounts = {m['Destination'] for m in cfg['Mounts']}
|
||||
check(mounts <= {'/run/secrets/database_url', '/run/secrets/cache_url', '/run/secrets/s3_access_key_id',
|
||||
'/run/secrets/s3_secret_access_key', '/run/secrets/broker_url'},
|
||||
f'api has unexpected mounts {mounts}') # lab4: + S3, lab5: + broker
|
||||
check(sql('SELECT count(*) FROM schema_migrations') == '6', 'unexpected migration count') # lab4: + 0004_attachments, 0005_nul_safe_text; lab5: + 0006_jobs
|
||||
with urllib.request.urlopen(os.environ.get('LB_STATS_URL', 'http://lb:8404/stats') + ';csv', timeout=2) as r:
|
||||
text = r.read().decode()
|
||||
check(',UP,' in text or ',UP ' in text, 'LB stats show no UP backend')
|
||||
|
||||
|
||||
def test_nul_in_text_roundtrip(c: Client):
|
||||
"""Замечание к PR #99: {"text":"abc\\u0000def"} давал 500. Строка с U+0000 сохраняется точно."""
|
||||
alice, bob, _eve, _chat = c.bootstrap()
|
||||
text = 'abc\u0000def'
|
||||
chat = c.call('POST', '/api/v1/chats', 201, actor=alice,
|
||||
body={'title': 'чат\u0000NUL', 'member_ids': [alice['id'], bob['id']]}, schema='Chat')['json']
|
||||
check(chat['title'] == 'чат\u0000NUL', 'title with NUL changed in response')
|
||||
got = c.call('GET', '/api/v1/chats/' + chat['id'], actor=bob, schema='Chat')['json']
|
||||
check(got['title'] == 'чат\u0000NUL', 'title with NUL changed on read')
|
||||
key = uuid.uuid4().hex
|
||||
first = c.message(alice, chat, text, key=key)['json']
|
||||
check(first['text'] == text, 'response text differs')
|
||||
replay = c.message(alice, chat, text, key=key)['json']
|
||||
check(replay == first, 'idempotent replay differs')
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice,
|
||||
body={'text': 'abc\ufffddef'}, headers={'Idempotency-Key': key}) # U+FFFD — другой текст
|
||||
c.message(alice, chat, '\u0000') # только NUL — не пробел, допустим
|
||||
history = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages', actor=bob,
|
||||
schema='MessagePage')['json']['items']
|
||||
check([m['text'] for m in history] == [text, '\u0000'], 'history lost NUL')
|
||||
name = 'Имя\u0000Фамилия'
|
||||
user = c.call('POST', '/api/v1/users', 201, body={'username': 'nul_' + uuid.uuid4().hex[:12],
|
||||
'display_name': name, 'password': 'T3st-' + uuid.uuid4().hex}, schema='User')['json']
|
||||
check(user['display_name'] == name, 'display_name with NUL changed')
|
||||
|
||||
|
||||
TESTS = [test_session_across_replicas, test_same_key_concurrent_across_replicas,
|
||||
test_same_key_concurrent_different_bodies, test_key_scope_and_format, test_replay_rechecks_session,
|
||||
test_transient_failure_not_recorded, test_sigterm_drain, test_infrastructure_rules,
|
||||
test_nul_in_text_roundtrip]
|
||||
|
||||
|
||||
def main() -> int:
|
||||
c = Client(BASE_URL)
|
||||
wait_ready(c)
|
||||
failed = 0
|
||||
for test in TESTS:
|
||||
started = time.monotonic()
|
||||
try:
|
||||
test(c)
|
||||
print(f'PASS {test.__name__} ({time.monotonic() - started:.1f}s)', flush=True)
|
||||
except (Failure, subprocess.CalledProcessError, OSError) as exc:
|
||||
failed += 1
|
||||
print(f'FAIL {test.__name__}: {exc}', flush=True)
|
||||
print(f'{len(TESTS) - failed}/{len(TESTS)} passed')
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
Executable
+284
@@ -0,0 +1,284 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Собственные проверки lab4 (уровень 3), в lab5 — регрессия с переходом 201 -> 202 (после upload ждём ready).
|
||||
Запуск: sh scripts/test-lab5.sh (внутри сервиса tester).
|
||||
|
||||
Покрывают критерии README «3»: PNG/JPEG upload -> 201 ready, побайтный download с SHA-256, доступ только
|
||||
участникам, сообщение с attachment_ids, лимиты (10 MiB, 40 Мпикс до декодирования), MIME по содержимому,
|
||||
опасные filename, failover загрузившей реплики, недоступность S3, приватность bucket вне API и отсутствие
|
||||
локальной копии файла на API. Требуют доступ к docker: останавливают реплику и S3, затем возвращают.
|
||||
"""
|
||||
import hashlib
|
||||
import os
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, Failure, check # noqa: E402
|
||||
|
||||
BASE_URL = os.environ.get('BASE_URL', 'http://lb:8080')
|
||||
PROJECT = 'mtusi-lab5'
|
||||
PNG = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
JPEG = (ROOT / 'student-tests/fixtures/sample.jpg').read_bytes()
|
||||
|
||||
|
||||
def docker(*args: str) -> str:
|
||||
return subprocess.run(['docker', *args], check=True, text=True, capture_output=True).stdout.strip()
|
||||
|
||||
|
||||
def service_containers(service: str, running_only: bool = True) -> list[str]:
|
||||
args = ['ps', '-q', '--filter', f'label=com.docker.compose.project={PROJECT}',
|
||||
'--filter', f'label=com.docker.compose.service={service}']
|
||||
if not running_only:
|
||||
args.insert(1, '-a')
|
||||
return docker(*args).split()
|
||||
|
||||
|
||||
def wait_ready(c: Client, seconds: float = 60) -> None:
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
try:
|
||||
c.call('GET', '/health/ready', schema='Health')
|
||||
return
|
||||
except Failure:
|
||||
check(time.monotonic() < deadline, 'API did not become ready')
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def upload(c: Client, actor: dict, chat: dict, data: bytes, ctype: str, filename: str = 'photo.png',
|
||||
expected=202, wait=True) -> dict:
|
||||
path = f"/api/v1/chats/{chat['id']}/attachments?filename={quote(filename, safe='')}"
|
||||
response = c.call('POST', path, expected, actor=actor, raw=data, headers={'Content-Type': ctype},
|
||||
schema='Attachment' if expected == 202 else None)
|
||||
if expected == 202:
|
||||
check(response['json']['status'] == 'queued', 'lab5 upload must return queued snapshot')
|
||||
if wait: # lab5: готовность — через опрос метаданных (заголовки ответа upload сохраняем)
|
||||
response['json'] = c.wait_ready(actor, response['json'])
|
||||
return response
|
||||
|
||||
|
||||
def download(c: Client, actor: dict, att_id: str, expected=200) -> dict:
|
||||
return c.call('GET', f'/api/v1/attachments/{att_id}/content', expected, actor=actor)
|
||||
|
||||
|
||||
def png_chunk(kind: bytes, data: bytes) -> bytes:
|
||||
return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data) & 0xffffffff)
|
||||
|
||||
|
||||
def png_header_only(width: int, height: int) -> bytes:
|
||||
"""Валидная сигнатура и IHDR (с верным CRC) огромного изображения, без пиксельных данных."""
|
||||
ihdr = struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0)
|
||||
idat = zlib.compress(b'\x00' * 64) # заведомо меньше, чем нужно: декодировать сервер не должен
|
||||
return b'\x89PNG\r\n\x1a\n' + png_chunk(b'IHDR', ihdr) + png_chunk(b'IDAT', idat) + png_chunk(b'IEND', b'')
|
||||
|
||||
|
||||
# ---------- тесты ----------
|
||||
|
||||
def test_png_and_jpeg_roundtrip(c: Client):
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
for data, ctype, name in ((PNG, 'image/png', 'Фото 1.png'), (JPEG, 'image/jpeg', 'кадр.jpg')):
|
||||
att = upload(c, alice, chat, data, ctype, name)['json']
|
||||
check(att['status'] == 'ready' and len(att['variants']) == 3 and att['error_code'] is None, 'not ready')
|
||||
check(att['filename'] == name and att['content_type'] == ctype, 'metadata mismatch')
|
||||
check(att['sha256'] == hashlib.sha256(data).hexdigest() and att['size_bytes'] == len(data), 'checksum')
|
||||
meta = c.call('GET', f"/api/v1/attachments/{att['id']}", actor=bob, schema='Attachment')['json']
|
||||
check(meta == att, 'metadata via GET differs from upload response')
|
||||
got = download(c, bob, att['id'])
|
||||
check(got['bytes'] == data, 'downloaded bytes differ')
|
||||
check(got['headers'].get_content_type() == ctype, 'wrong Content-Type on download')
|
||||
check(hashlib.sha256(got['bytes']).hexdigest() == att['sha256'], 'sha256 mismatch')
|
||||
for suffix in ('', '/content'):
|
||||
c.call('GET', f"/api/v1/attachments/{att['id']}{suffix}", 404, actor=eve)
|
||||
c.call('GET', f"/api/v1/attachments/{att['id']}/content", 401)
|
||||
|
||||
|
||||
def test_message_with_attachments(c: Client):
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
a1 = upload(c, alice, chat, PNG, 'image/png')['json']
|
||||
a2 = upload(c, bob, chat, JPEG, 'image/jpeg', 'b.jpg')['json']
|
||||
key = uuid.uuid4().hex
|
||||
msg = c.message(bob, chat, '', key=key, attachments=[a2['id'], a1['id']])['json'] # любой участник
|
||||
check(msg['attachment_ids'] == [a2['id'], a1['id']] and msg['text'] == '', 'attachment order lost')
|
||||
replay = c.message(bob, chat, '', key=key, attachments=[a2['id'], a1['id']])['json']
|
||||
check(replay == msg, 'idempotent replay with attachments differs')
|
||||
plain = c.message(alice, chat, 'только текст')['json']
|
||||
check(plain['attachment_ids'] == [], 'text message must have attachment_ids=[]')
|
||||
history = c.call('GET', f"/api/v1/chats/{chat['id']}/messages?limit=100", actor=alice,
|
||||
schema='MessagePage')['json']['items']
|
||||
check([m['attachment_ids'] for m in history] == [[a2['id'], a1['id']], []], 'history lost attachments')
|
||||
h = {'Idempotency-Key': uuid.uuid4().hex}
|
||||
c.call('POST', f"/api/v1/chats/{chat['id']}/messages", 400, actor=alice, body={'text': ' '}, headers=h)
|
||||
c.call('POST', f"/api/v1/chats/{chat['id']}/messages", 400, actor=alice,
|
||||
body={'text': '', 'attachment_ids': [a1['id'], a1['id']]}, headers=h)
|
||||
|
||||
|
||||
def test_foreign_attachment_rejected(c: Client):
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
other = c.call('POST', '/api/v1/chats', 201, actor=eve, body={'title': 'чужой', 'member_ids': [eve['id']]},
|
||||
schema='Chat')['json']
|
||||
foreign = upload(c, eve, other, PNG, 'image/png')['json']
|
||||
h = {'Idempotency-Key': uuid.uuid4().hex}
|
||||
# Вложение другого чата и несуществующее — 404, сообщение не создаётся.
|
||||
for ids in ([foreign['id']], [str(uuid.uuid4())]):
|
||||
c.call('POST', f"/api/v1/chats/{chat['id']}/messages", 404, actor=alice,
|
||||
body={'text': 'x', 'attachment_ids': ids}, headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
items = c.call('GET', f"/api/v1/chats/{chat['id']}/messages", actor=alice, schema='MessagePage')['json']['items']
|
||||
check(items == [], 'message with foreign attachment was created')
|
||||
# Посторонний не может загрузить файл в чужой чат.
|
||||
upload(c, eve, chat, PNG, 'image/png', expected=404)
|
||||
c.call('POST', f"/api/v1/chats/{chat['id']}/messages", 404, actor=eve,
|
||||
body={'text': 'x'}, headers=h)
|
||||
|
||||
|
||||
def test_limits_and_mime(c: Client):
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
# 10 MiB + 1 байт: 413 (тело дальше лимита сервер не читает).
|
||||
upload(c, alice, chat, PNG[:8] + b'\0' * (10 * 1024 * 1024 - 7), 'image/png', expected=413)
|
||||
# Ровно 10 MiB проходит проверку размера (а затем отклоняется как повреждённый PNG — 415, не 413).
|
||||
upload(c, alice, chat, PNG[:8] + b'\0' * (10 * 1024 * 1024 - 8), 'image/png', expected=415)
|
||||
# 10000 x 5000 = 50 Мпикс по заголовку -> 413 до декодирования (файл всего ~100 байт).
|
||||
upload(c, alice, chat, png_header_only(10000, 5000), 'image/png', expected=413)
|
||||
# 6000 x 6000 = 36 Мпикс укладывается в лимит, но пикселей нет -> повреждённый -> 415.
|
||||
upload(c, alice, chat, png_header_only(6000, 6000), 'image/png', expected=415)
|
||||
# MIME по содержимому: PNG с Content-Type image/jpeg и наоборот -> 415.
|
||||
upload(c, alice, chat, PNG, 'image/jpeg', expected=415)
|
||||
upload(c, alice, chat, JPEG, 'image/png', expected=415)
|
||||
# Не изображение, обрезанные файлы, пустое тело, чужие Content-Type.
|
||||
upload(c, alice, chat, b'GIF89a' + b'\0' * 100, 'image/png', expected=415)
|
||||
upload(c, alice, chat, PNG[:len(PNG) // 2], 'image/png', expected=415)
|
||||
upload(c, alice, chat, JPEG[:len(JPEG) // 2], 'image/jpeg', expected=415)
|
||||
upload(c, alice, chat, b'', 'image/png', expected=415)
|
||||
upload(c, alice, chat, PNG, 'text/plain', expected=415)
|
||||
upload(c, alice, chat, PNG, 'multipart/form-data; boundary=x', expected=415)
|
||||
|
||||
|
||||
def test_dangerous_filenames(c: Client):
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
for name in ('../etc/passwd', 'a/b.png', 'a\\b.png', 'nul\x00.png', 'tab\t.png', 'new\nline.png',
|
||||
'\x7f.png', '', ' ', '..', 'x' * 256):
|
||||
upload(c, alice, chat, PNG, 'image/png', name, expected=400)
|
||||
c.call('POST', f"/api/v1/chats/{chat['id']}/attachments", 400, actor=alice, raw=PNG,
|
||||
headers={'Content-Type': 'image/png'}) # без filename
|
||||
ok = upload(c, alice, chat, PNG, 'image/png', 'отчёт (финал) ✓.png')['json']
|
||||
check(ok['filename'] == 'отчёт (финал) ✓.png', 'unicode filename changed')
|
||||
upload(c, alice, chat, PNG, 'image/png', 'x' * 255)
|
||||
|
||||
|
||||
def test_failover_of_uploading_replica(c: Client):
|
||||
"""Upload -> остановить реплику, которая его обслужила -> download через другую = тот же файл."""
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
response = upload(c, alice, chat, PNG, 'image/png')
|
||||
att = response['json']
|
||||
served_by = response['headers']['X-Instance-Id']
|
||||
cid = served_by.rsplit('-', 1)[0]
|
||||
check(cid in [x[:12] for x in service_containers('api')], 'uploader replica not found among containers')
|
||||
docker('stop', '-t', '20', cid)
|
||||
try:
|
||||
time.sleep(2)
|
||||
got = download(c, bob, att['id'])
|
||||
check(got['headers']['X-Instance-Id'] != served_by, 'download served by stopped replica')
|
||||
check(got['bytes'] == PNG and hashlib.sha256(got['bytes']).hexdigest() == att['sha256'],
|
||||
'file differs after uploader replica stopped')
|
||||
print(f' uploaded via {served_by}, downloaded via {got["headers"]["X-Instance-Id"]}')
|
||||
finally:
|
||||
docker('start', cid)
|
||||
wait_ready(c)
|
||||
|
||||
|
||||
def test_s3_unavailable(c: Client):
|
||||
"""S3 остановлен: upload/download -> 503 без 500, текстовые сообщения работают, после старта — всё снова."""
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
att = upload(c, alice, chat, PNG, 'image/png')['json']
|
||||
s3 = service_containers('s3')
|
||||
check(len(s3) == 1, 'expected one s3 container')
|
||||
docker('stop', s3[0])
|
||||
try:
|
||||
started = time.monotonic()
|
||||
upload(c, alice, chat, PNG, 'image/png', expected=503)
|
||||
download(c, bob, att['id'], expected=503)
|
||||
check(time.monotonic() - started < 15, 'S3 failure is not bounded by timeouts')
|
||||
c.message(alice, chat, 'S3 недоступен, а текст отправляется')
|
||||
c.call('GET', f"/api/v1/attachments/{att['id']}", actor=bob, schema='Attachment') # метаданные в БД
|
||||
c.call('GET', '/health/ready', schema='Health')
|
||||
finally:
|
||||
docker('start', s3[0])
|
||||
deadline = time.monotonic() + 60
|
||||
while True:
|
||||
try:
|
||||
check(download(c, bob, att['id'])['bytes'] == PNG, 'file changed after S3 restart')
|
||||
break
|
||||
except Failure:
|
||||
check(time.monotonic() < deadline, 'S3 did not come back')
|
||||
time.sleep(1)
|
||||
upload(c, alice, chat, JPEG, 'image/jpeg', 'after.jpg')
|
||||
|
||||
|
||||
def test_bucket_private_outside_api(c: Client):
|
||||
"""Прямой анонимный GET объекта в S3 (в обход API) отклоняется; ключ в API не раскрывается."""
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
att = upload(c, alice, chat, PNG, 'image/png')['json']
|
||||
check('object_key' not in att and 'originals/' not in str(att) and 'staging/' not in str(att), 'object key leaked to API')
|
||||
api = service_containers('api')[0]
|
||||
code = docker('exec', api, 'python', '-c',
|
||||
'import urllib.request,urllib.error,sys\n'
|
||||
'try:\n'
|
||||
f' urllib.request.urlopen("http://s3:9000/messenger-attachments/originals/{att["id"]}", timeout=5)\n'
|
||||
' print(200)\n'
|
||||
'except urllib.error.HTTPError as e:\n'
|
||||
' print(e.code)\n')
|
||||
check(code in ('401', '403'), f'anonymous S3 GET returned {code}')
|
||||
# Листинг bucket анонимно тоже запрещён.
|
||||
code = docker('exec', api, 'python', '-c',
|
||||
'import urllib.request,urllib.error\n'
|
||||
'try:\n'
|
||||
' urllib.request.urlopen("http://s3:9000/messenger-attachments", timeout=5); print(200)\n'
|
||||
'except urllib.error.HTTPError as e:\n'
|
||||
' print(e.code)\n')
|
||||
check(code in ('401', '403'), f'anonymous S3 list returned {code}')
|
||||
print(f' anonymous GET object/list -> {code}')
|
||||
|
||||
|
||||
def test_no_local_copy_on_api(c: Client):
|
||||
"""У API read-only корневая ФС и пустой tmpfs: оригинал не хранится локально."""
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
upload(c, alice, chat, PNG, 'image/png')
|
||||
for cid in service_containers('api'):
|
||||
check(docker('inspect', '-f', '{{.HostConfig.ReadonlyRootfs}}', cid) == 'true', 'api rootfs is writable')
|
||||
# Допустимы только read-only секреты compose (/run/secrets/*); volume и записываемых bind нет.
|
||||
mounts = docker('inspect', '-f', '{{range .Mounts}}{{.Type}}:{{.Destination}}:{{.RW}} {{end}}', cid).split()
|
||||
writable = [m for m in mounts if m.startswith('volume:') or
|
||||
(m.startswith('bind:') and not (m.startswith('bind:/run/secrets/') and m.endswith(':false')))]
|
||||
check(not writable, f'api has persistent/writable mounts: {writable}')
|
||||
files = docker('exec', cid, 'find', '/tmp', '-type', 'f')
|
||||
check(files == '', f'unexpected files in api /tmp: {files}')
|
||||
|
||||
|
||||
TESTS = [test_png_and_jpeg_roundtrip, test_message_with_attachments, test_foreign_attachment_rejected,
|
||||
test_limits_and_mime, test_dangerous_filenames, test_bucket_private_outside_api,
|
||||
test_no_local_copy_on_api, test_failover_of_uploading_replica, test_s3_unavailable]
|
||||
|
||||
|
||||
def main() -> int:
|
||||
c = Client(BASE_URL, timeout=30)
|
||||
wait_ready(c)
|
||||
failed = 0
|
||||
for test in TESTS:
|
||||
started = time.monotonic()
|
||||
try:
|
||||
test(c)
|
||||
print(f'PASS {test.__name__} ({time.monotonic() - started:.1f}s)', flush=True)
|
||||
except (Failure, subprocess.CalledProcessError, OSError) as exc:
|
||||
failed += 1
|
||||
print(f'FAIL {test.__name__}: {exc}', flush=True)
|
||||
print(f'{len(TESTS) - failed}/{len(TESTS)} passed')
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
Executable
+515
@@ -0,0 +1,515 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Собственные проверки lab5 (уровни 3–4). Запуск: sh scripts/test-lab5.sh (внутри сервиса tester).
|
||||
|
||||
Управляют стендом через docker (останавливают worker/S3/RabbitMQ, внедряют отказы файлами /tmp/fault-*),
|
||||
читают состояние из PostgreSQL и RabbitMQ, чтобы проверять не только HTTP-ответы, но и инварианты:
|
||||
нет второго набора вариантов, попытки ограничены, принятая работа не теряется.
|
||||
"""
|
||||
import hashlib
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, Failure, check # noqa: E402
|
||||
from image_probe import jpeg_size # noqa: E402
|
||||
|
||||
BASE_URL = os.environ.get('BASE_URL', 'http://lb:8080')
|
||||
PROJECT = 'mtusi-lab5'
|
||||
PNG = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
JPEG = (ROOT / 'student-tests/fixtures/sample.jpg').read_bytes()
|
||||
|
||||
|
||||
# ---------- инфраструктура ----------
|
||||
|
||||
def docker(*args: str, stdin: str | None = None) -> str:
|
||||
return subprocess.run(['docker', *args], check=True, text=True, capture_output=True, input=stdin).stdout.strip()
|
||||
|
||||
|
||||
def compose(*args: str) -> str:
|
||||
return subprocess.run(['docker', 'compose', '--env-file', str(ROOT / '.env'), *args], cwd=ROOT, check=True,
|
||||
text=True, capture_output=True).stdout.strip()
|
||||
|
||||
|
||||
def containers(service: str) -> list[str]:
|
||||
return docker('ps', '-q', '--filter', f'label=com.docker.compose.project={PROJECT}',
|
||||
'--filter', f'label=com.docker.compose.service={service}').split()
|
||||
|
||||
|
||||
def sql(query: str) -> str:
|
||||
return compose('exec', '-T', 'postgres', 'psql', '-U', 'app', '-d', 'messenger', '-tAc', query)
|
||||
|
||||
|
||||
def in_container(service: str, script: str) -> str:
|
||||
"""Python-скрипт внутри контейнера сервиса (там есть minio/aio-pika/Pillow и секреты).
|
||||
|
||||
Скрипт пишется в /tmp (tmpfs) и запускается файлом: multiprocessing forkserver не умеет стартовать
|
||||
из stdin. Код с побочными эффектами в скриптах — под if __name__ == '__main__'.
|
||||
"""
|
||||
return docker('exec', '-i', containers(service)[0], 'sh', '-c', 'cat > /tmp/_t.py && PYTHONPATH=/srv python /tmp/_t.py; rc=$?; rm -f /tmp/_t.py; exit $rc',
|
||||
stdin=script)
|
||||
|
||||
|
||||
def logs(container: str, since: str | None = None) -> str:
|
||||
"""docker logs: приложение пишет logging в stderr, поэтому склеиваем оба потока."""
|
||||
args = ['docker', 'logs'] + (['--since', since] if since else []) + [container]
|
||||
return subprocess.run(args, check=True, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).stdout
|
||||
|
||||
|
||||
def start_worker() -> None:
|
||||
"""docker start, а не compose start: compose поднял бы и намеренно остановленные зависимости (S3)."""
|
||||
ids = docker('ps', '-aq', '--filter', f'label=com.docker.compose.project={PROJECT}',
|
||||
'--filter', 'label=com.docker.compose.service=worker').split()
|
||||
docker('start', *ids)
|
||||
|
||||
|
||||
S3_PRELUDE = '''
|
||||
from minio import Minio
|
||||
import io
|
||||
k=open('/run/secrets/s3_access_key_id').read().strip(); s=open('/run/secrets/s3_secret_access_key').read().strip()
|
||||
m=Minio('s3:9000', access_key=k, secret_key=s, secure=False, region='us-east-1')
|
||||
B='messenger-attachments'
|
||||
def exists(key):
|
||||
try:
|
||||
m.stat_object(B, key); return True
|
||||
except Exception:
|
||||
return False
|
||||
'''
|
||||
|
||||
|
||||
def queue_counts() -> dict:
|
||||
out = compose('exec', '-T', 'rabbitmq', 'rabbitmqctl', '-q', 'list_queues', 'name', 'messages')
|
||||
counts = {}
|
||||
for line in out.splitlines():
|
||||
parts = line.split()
|
||||
if len(parts) == 2 and parts[1].isdigit():
|
||||
counts[parts[0]] = int(parts[1])
|
||||
return counts
|
||||
|
||||
|
||||
def wait_queue(name: str, minimum: int, seconds: float = 20) -> int:
|
||||
"""Счётчики list_queues у quorum queue обновляются периодически (метрики) — опрашиваем."""
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
n = queue_counts().get(name, 0)
|
||||
if n >= minimum or time.monotonic() > deadline:
|
||||
return n
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def wait_healthy(service: str, seconds: float = 90) -> None:
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
ids = containers(service)
|
||||
if ids and all(docker('inspect', '-f', '{{.State.Health.Status}}', i) == 'healthy' for i in ids):
|
||||
return
|
||||
time.sleep(1)
|
||||
raise Failure(f'{service} did not become healthy')
|
||||
|
||||
|
||||
def wait_ready_api(c: Client, seconds: float = 90) -> None:
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
try:
|
||||
c.call('GET', '/health/ready', schema='Health')
|
||||
return
|
||||
except Failure:
|
||||
check(time.monotonic() < deadline, 'API did not become ready')
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def touch_fault(service: str, name: str) -> list[str]:
|
||||
ids = containers(service)
|
||||
for i in ids:
|
||||
docker('exec', '-u', '10001', i, 'touch', f'/tmp/fault-{name}')
|
||||
return ids
|
||||
|
||||
|
||||
def clear_fault(service: str, name: str) -> None:
|
||||
for i in containers(service):
|
||||
docker('exec', '-u', '10001', i, 'rm', '-f', f'/tmp/fault-{name}')
|
||||
|
||||
|
||||
# ---------- API ----------
|
||||
|
||||
def upload(c: Client, actor: dict, chat: dict, data: bytes = PNG, ctype: str = 'image/png') -> dict:
|
||||
att = c.call('POST', f"/api/v1/chats/{chat['id']}/attachments?filename=photo.png", 202, actor=actor, raw=data,
|
||||
headers={'Content-Type': ctype}, schema='Attachment')['json']
|
||||
check(att['status'] == 'queued' and att['variants'] == [] and att['error_code'] is None, 'bad queued snapshot')
|
||||
return att
|
||||
|
||||
|
||||
def meta(c: Client, actor: dict, att_id: str) -> dict:
|
||||
return c.call('GET', f'/api/v1/attachments/{att_id}', actor=actor, schema='Attachment')['json']
|
||||
|
||||
|
||||
def wait_status(c: Client, actor: dict, att_id: str, wanted: set, seconds: float = 90) -> dict:
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
m = meta(c, actor, att_id)
|
||||
if m['status'] in wanted:
|
||||
return m
|
||||
check(time.monotonic() < deadline, f'attachment stayed {m["status"]}, wanted {wanted}')
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def content(c: Client, actor: dict, att_id: str, variant: str = 'original', expected=200) -> dict:
|
||||
return c.call('GET', f'/api/v1/attachments/{att_id}/content?variant={variant}', expected, actor=actor)
|
||||
|
||||
|
||||
def job(att_id: str) -> dict:
|
||||
row = sql(f"SELECT status, attempt, coalesce(error_code,''), "
|
||||
f"(SELECT count(*) FROM attachment_variants v WHERE v.attachment_id = j.attachment_id) "
|
||||
f"FROM attachment_jobs j WHERE attachment_id = '{att_id}'").split('|')
|
||||
return {'status': row[0], 'attempt': int(row[1]), 'error_code': row[2], 'variants': int(row[3])}
|
||||
|
||||
|
||||
def wait_published(att_id: str, seconds: float = 30) -> None:
|
||||
deadline = time.monotonic() + seconds
|
||||
while sql(f"SELECT count(*) FROM outbox o JOIN attachment_jobs j USING (job_id) "
|
||||
f"WHERE j.attachment_id = '{att_id}' AND o.published_at IS NULL") != '0':
|
||||
check(time.monotonic() < deadline, 'outbox row not published')
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def webp_size(b: bytes) -> tuple[int, int]:
|
||||
check(b[:4] == b'RIFF' and b[8:12] == b'WEBP', 'not a WebP file')
|
||||
kind = b[12:16]
|
||||
if kind == b'VP8 ':
|
||||
return int.from_bytes(b[26:28], 'little') & 0x3fff, int.from_bytes(b[28:30], 'little') & 0x3fff
|
||||
if kind == b'VP8L':
|
||||
bits = int.from_bytes(b[21:25], 'little')
|
||||
return (bits & 0x3fff) + 1, ((bits >> 14) & 0x3fff) + 1
|
||||
return int.from_bytes(b[24:27], 'little') + 1, int.from_bytes(b[27:30], 'little') + 1
|
||||
|
||||
|
||||
# ---------- уровень 3 ----------
|
||||
|
||||
def test_variants_contract(c: Client):
|
||||
"""Оригинал неизменен; thumbnail 256x160 JPEG, crop 128x128 JPEG, optimized WebP; checksums и реальные размеры."""
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
att = upload(c, alice, chat)
|
||||
ready = wait_status(c, bob, att['id'], {'ready'})
|
||||
check(ready['error_code'] is None, 'ready with error_code')
|
||||
variants = {v['name']: v for v in ready['variants']}
|
||||
check(sorted(variants) == ['crop', 'optimized', 'thumbnail'], f'variants: {sorted(variants)}')
|
||||
expect = {'thumbnail': ('image/jpeg', (256, 160)), 'crop': ('image/jpeg', (128, 128)),
|
||||
'optimized': ('image/webp', (320, 200))}
|
||||
for name, (ctype, size) in expect.items():
|
||||
v = variants[name]
|
||||
got = content(c, bob, att['id'], name)
|
||||
check(got['headers'].get_content_type() == ctype, f'{name}: content type')
|
||||
check(len(got['bytes']) == v['size_bytes'] and hashlib.sha256(got['bytes']).hexdigest() == v['sha256'],
|
||||
f'{name}: checksum')
|
||||
real = jpeg_size(got['bytes']) if ctype == 'image/jpeg' else webp_size(got['bytes'])
|
||||
check(real == size == (v['width'], v['height']), f'{name}: real size {real}, metadata {v["width"]}x{v["height"]}')
|
||||
original = content(c, bob, att['id'])
|
||||
check(original['bytes'] == PNG and original['headers'].get_content_type() == 'image/png', 'original changed')
|
||||
jpg = upload(c, alice, chat, JPEG, 'image/jpeg')
|
||||
r = wait_status(c, alice, jpg['id'], {'ready'})
|
||||
thumb = {v['name']: v for v in r['variants']}['thumbnail']
|
||||
check((thumb['width'], thumb['height']) == (160, 100), 'small image must not be upscaled')
|
||||
|
||||
|
||||
def test_worker_down_demo(c: Client):
|
||||
"""Сценарий защиты: worker остановлен -> 202 -> 409 -> сообщение создано -> рестарт API и RabbitMQ -> worker -> ready."""
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
compose('stop', 'worker')
|
||||
try:
|
||||
att = upload(c, alice, chat)
|
||||
print(f' worker stopped; upload 202 attachment={att["id"]}')
|
||||
check(meta(c, bob, att['id'])['status'] == 'queued', 'must stay queued without worker')
|
||||
for variant in ('original', 'thumbnail'):
|
||||
content(c, bob, att['id'], variant, 409)
|
||||
msg = c.message(alice, chat, 'фото без worker', attachments=[att['id']])['json']
|
||||
check(msg['attachment_ids'] == [att['id']], 'message lost attachment')
|
||||
c.message(bob, chat, 'другие сообщения работают')
|
||||
wait_published(att['id'])
|
||||
before = wait_queue('attachment.process.v1', 1)
|
||||
check(before >= 1, 'job is not in the broker queue')
|
||||
compose('restart', 'api')
|
||||
wait_ready_api(c)
|
||||
compose('restart', 'rabbitmq')
|
||||
wait_healthy('rabbitmq')
|
||||
after = wait_queue('attachment.process.v1', 1)
|
||||
check(after >= 1, 'job lost on broker restart')
|
||||
print(f' api and rabbitmq restarted; queue depth before/after broker restart: {before}/{after}')
|
||||
check(meta(c, bob, att['id'])['status'] == 'queued', 'state changed without worker')
|
||||
finally:
|
||||
start_worker()
|
||||
started = time.monotonic()
|
||||
ready = wait_status(c, bob, att['id'], {'ready'}, 60)
|
||||
thumb = content(c, bob, att['id'], 'thumbnail')
|
||||
check(jpeg_size(thumb['bytes']) == (256, 160), 'thumbnail after restart is wrong')
|
||||
check(len(ready['variants']) == 3, 'variants missing')
|
||||
print(f' worker started -> ready in {time.monotonic() - started:.1f}s, thumbnail OK')
|
||||
|
||||
|
||||
def test_failed_state_and_409(c: Client):
|
||||
"""Постоянная ошибка (staging подменён в S3, sha256 не совпал) -> failed с безопасным кодом; 409 на content и attach."""
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
compose('stop', 'worker')
|
||||
try:
|
||||
att = upload(c, alice, chat)
|
||||
in_container('api', S3_PRELUDE + f"m.put_object(B, 'staging/{att['id']}', io.BytesIO(b'garbage'), 7)\n")
|
||||
finally:
|
||||
start_worker()
|
||||
failed = wait_status(c, bob, att['id'], {'failed', 'ready'}, 60)
|
||||
check(failed['status'] == 'failed' and failed['error_code'] == 'source_corrupted', f'got {failed}')
|
||||
check(failed['variants'] == [], 'failed must have no variants')
|
||||
content(c, bob, att['id'], 'original', 409)
|
||||
c.call('POST', f"/api/v1/chats/{chat['id']}/messages", 409, actor=alice,
|
||||
body={'text': '', 'attachment_ids': [att['id']]}, headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
j = job(att['id'])
|
||||
check(j['status'] == 'failed' and j['attempt'] == 1, f'permanent error must not be retried: {j}')
|
||||
|
||||
|
||||
def test_retry_bounded_then_replay(c: Client):
|
||||
"""Временная ошибка (S3 недоступен) -> ограниченные повторы с backoff -> failed retry_exhausted -> replay -> ready."""
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
compose('stop', 'worker')
|
||||
s3 = containers('s3')[0]
|
||||
try:
|
||||
att = upload(c, alice, chat)
|
||||
docker('stop', s3)
|
||||
start_worker()
|
||||
started = time.monotonic()
|
||||
failed = wait_status(c, bob, att['id'], {'failed', 'ready'}, 150)
|
||||
check(failed['status'] == 'failed' and failed['error_code'] == 'retry_exhausted', f'got {failed}')
|
||||
max_attempts = int(sql("SELECT max_attempts FROM attachment_jobs WHERE attachment_id = '%s'" % att['id']))
|
||||
j = job(att['id'])
|
||||
check(j['attempt'] == max_attempts, f'attempts {j["attempt"]} != JOB_MAX_ATTEMPTS {max_attempts}')
|
||||
print(f' S3 down: failed retry_exhausted after {j["attempt"]} attempts, {time.monotonic() - started:.0f}s')
|
||||
worker_logs = logs(containers('worker')[0])
|
||||
job_id = att_job_id(att['id']) # один запрос, не на каждую строку лога
|
||||
delays = [line.split('retry in ')[1].split('s')[0] for line in worker_logs.splitlines()
|
||||
if job_id in line and 'retry in' in line]
|
||||
print(f' backoff delays (s): {", ".join(delays)}')
|
||||
check(len(delays) == max_attempts - 1, 'expected a retry delay per non-final attempt')
|
||||
finally:
|
||||
docker('start', s3)
|
||||
wait_healthy('s3')
|
||||
out = compose('exec', '-T', 'worker', 'python', '-m', 'app.replay', 'replay', '--attachment', att['id'],
|
||||
'--reason', 'S3 restored', '--dry-run')
|
||||
check('would replay' in out and meta(c, bob, att['id'])['status'] == 'failed', 'dry-run changed state')
|
||||
compose('exec', '-T', '-e', 'REPLAY_ACTOR=test', 'worker', 'python', '-m', 'app.replay', 'replay',
|
||||
'--attachment', att['id'], '--reason', 'S3 restored')
|
||||
ready = wait_status(c, bob, att['id'], {'ready'}, 60)
|
||||
check(len(ready['variants']) == 3, 'replay did not produce variants')
|
||||
out = compose('exec', '-T', 'worker', 'python', '-m', 'app.replay', 'replay', '--attachment', att['id'],
|
||||
'--reason', 'again')
|
||||
check('replay only for failed' in out, 'replay of a done job must be refused')
|
||||
audit = sql(f"SELECT count(*) FROM job_audit a JOIN attachment_jobs j USING (job_id) WHERE j.attachment_id = '{att['id']}'")
|
||||
check(audit == '1' and job(att['id'])['variants'] == 3, 'audit/variants after replay')
|
||||
|
||||
|
||||
def att_job_id(att_id: str) -> str:
|
||||
return sql(f"SELECT job_id FROM attachment_jobs WHERE attachment_id = '{att_id}'")
|
||||
|
||||
|
||||
def test_duplicate_delivery_is_noop(c: Client):
|
||||
"""Повторная доставка завершённой job: no-op + ack, без второго набора вариантов и без изменения updated_at."""
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
att = upload(c, alice, chat)
|
||||
ready = wait_status(c, alice, att['id'], {'ready'})
|
||||
job_id = att_job_id(att['id'])
|
||||
for _ in range(3):
|
||||
sql(f"INSERT INTO outbox (job_id, payload) SELECT job_id, payload FROM outbox WHERE job_id = '{job_id}' LIMIT 1")
|
||||
wait_published(att['id'])
|
||||
time.sleep(3)
|
||||
check(meta(c, alice, att['id'])['updated_at'] == ready['updated_at'], 'duplicate changed ready attachment')
|
||||
j = job(att['id'])
|
||||
check(j['attempt'] == 1 and j['variants'] == 3, f'duplicate created extra work: {j}')
|
||||
check(f'job {job_id}: no-op, already done' in logs(containers('worker')[0], '60s'), 'worker did not report no-op')
|
||||
|
||||
|
||||
# ---------- уровень 4 ----------
|
||||
|
||||
def test_crash_between_commit_and_publish(c: Client):
|
||||
"""API падает сразу после COMMIT (до 202 и publish): outbox восстанавливает намерение, файл доходит до ready."""
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
touch_fault('api', 'api_crash_after_commit')
|
||||
try:
|
||||
req = urllib.request.Request(f"{BASE_URL}/api/v1/chats/{chat['id']}/attachments?filename=crash.png", data=PNG,
|
||||
method='POST', headers={'Content-Type': 'image/png',
|
||||
'Authorization': 'Bearer ' + alice['token']})
|
||||
try:
|
||||
status = urllib.request.urlopen(req, timeout=30).status
|
||||
except urllib.error.HTTPError as exc:
|
||||
status = exc.code
|
||||
except (urllib.error.URLError, OSError):
|
||||
status = 'connection error'
|
||||
check(status != 202, f'API should have crashed before 202, got {status}')
|
||||
print(f' client saw: {status} (API process exited after COMMIT)')
|
||||
finally:
|
||||
clear_fault('api', 'api_crash_after_commit')
|
||||
att_id = sql(f"SELECT id FROM attachments WHERE chat_id = '{chat['id']}'")
|
||||
check(len(att_id) == 36, 'attachment row must be committed')
|
||||
wait_ready_api(c)
|
||||
ready = wait_status(c, bob, att_id, {'ready'}, 60)
|
||||
check(len(ready['variants']) == 3, 'variants missing')
|
||||
print(f' attachment {att_id} reached ready via outbox relay')
|
||||
|
||||
|
||||
def test_worker_crash_after_s3_before_commit(c: Client):
|
||||
"""Worker умирает после записи объектов в S3, до COMMIT: аренда истекает, повтор даёт тот же результат."""
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
worker = touch_fault('worker', 'worker_crash_after_s3')[0]
|
||||
restarts = int(docker('inspect', '-f', '{{.RestartCount}}', worker))
|
||||
att = upload(c, alice, chat)
|
||||
started = time.monotonic()
|
||||
ready = wait_status(c, bob, att['id'], {'ready'}, 90)
|
||||
check(int(docker('inspect', '-f', '{{.RestartCount}}', worker)) == restarts + 1, 'worker did not crash')
|
||||
j = job(att['id'])
|
||||
check(j['attempt'] == 2 and j['variants'] == 3, f'expected second attempt with one variant set: {j}')
|
||||
keys = in_container('api', S3_PRELUDE + f"print(len(list(m.list_objects(B, prefix='variants/{att['id']}/', recursive=True))))\n")
|
||||
check(keys == '3', f'S3 has {keys} variant objects, expected 3 (same keys overwritten)')
|
||||
check(len(ready['variants']) == 3, 'variants missing')
|
||||
print(f' crash after S3 writes -> ready on attempt 2 in {time.monotonic() - started:.1f}s, 3 objects in S3')
|
||||
wait_healthy('worker')
|
||||
|
||||
|
||||
def test_worker_crash_after_commit_before_ack(c: Client):
|
||||
"""Worker умирает после COMMIT результата, до ack: redelivery видит done и подтверждает без повторной работы."""
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
worker = touch_fault('worker', 'worker_crash_after_commit')[0]
|
||||
att = upload(c, alice, chat)
|
||||
wait_status(c, bob, att['id'], {'ready'}, 60)
|
||||
wait_healthy('worker')
|
||||
job_id = att_job_id(att['id'])
|
||||
deadline = time.monotonic() + 30
|
||||
while f'job {job_id}: no-op, already done' not in logs(containers('worker')[0]):
|
||||
check(time.monotonic() < deadline, 'redelivered message was not acknowledged as no-op')
|
||||
time.sleep(1)
|
||||
j = job(att['id'])
|
||||
check(j['attempt'] == 1 and j['variants'] == 3, f'work was repeated: {j}')
|
||||
deadline = time.monotonic() + 20
|
||||
while queue_counts().get('attachment.process.v1', 0) != 0:
|
||||
check(time.monotonic() < deadline, 'message left in queue')
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def test_expired_lease_takeover(c: Client):
|
||||
"""Зависшая processing-задача (аренда истекла, владельца нет) перехватывается новой попыткой."""
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
compose('stop', 'worker')
|
||||
try:
|
||||
att = upload(c, alice, chat)
|
||||
wait_published(att['id'])
|
||||
job_id = att_job_id(att['id'])
|
||||
sql(f"UPDATE attachment_jobs SET status='processing', attempt=1, worker_id='ghost-dead', "
|
||||
f"lease_until=clock_timestamp() - interval '1 second' WHERE job_id='{job_id}'")
|
||||
sql(f"UPDATE attachments SET status='processing' WHERE id='{att['id']}'")
|
||||
check(meta(c, bob, att['id'])['status'] == 'processing', 'processing state not visible in API')
|
||||
finally:
|
||||
start_worker()
|
||||
wait_status(c, bob, att['id'], {'ready'}, 60)
|
||||
j = job(att['id'])
|
||||
check(j['attempt'] == 2 and j['variants'] == 3, f'takeover result: {j}')
|
||||
|
||||
|
||||
def test_staging_cleanup_after_commit(c: Client):
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
att = upload(c, alice, chat)
|
||||
wait_status(c, alice, att['id'], {'ready'})
|
||||
out = in_container('api', S3_PRELUDE + f"print(exists('staging/{att['id']}'), exists('originals/{att['id']}'))\n")
|
||||
check(out == 'False True', f'staging/originals after ready: {out}')
|
||||
|
||||
|
||||
def test_poison_message_to_dlq(c: Client):
|
||||
before = queue_counts().get('attachment.process.v1.dlq', 0)
|
||||
in_container('api', '''
|
||||
import asyncio, aio_pika
|
||||
async def main():
|
||||
url = open('/run/secrets/broker_url').read().strip()
|
||||
conn = await aio_pika.connect(url)
|
||||
ch = await conn.channel(publisher_confirms=True)
|
||||
ex = await ch.get_exchange('attachments')
|
||||
await ex.publish(aio_pika.Message(b'{"not":"a job"}', delivery_mode=2), routing_key='attachment.process.v1')
|
||||
await conn.close()
|
||||
asyncio.run(main())
|
||||
''')
|
||||
deadline = time.monotonic() + 15
|
||||
while queue_counts().get('attachment.process.v1.dlq', 0) != before + 1:
|
||||
check(time.monotonic() < deadline, 'invalid message did not reach DLQ')
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def test_prefetch_limited(c: Client):
|
||||
out = compose('exec', '-T', 'rabbitmq', 'rabbitmqctl', '-q', 'list_consumers', 'queue_name', 'prefetch_count')
|
||||
rows = [l.split() for l in out.splitlines() if l.startswith('attachment.process.v1')]
|
||||
expected = os.environ.get('WORKER_PREFETCH_EXPECTED', '2')
|
||||
check(rows and all(r[1] == expected for r in rows), f'consumers/prefetch: {rows}')
|
||||
|
||||
|
||||
def test_worker_resource_limits(c: Client):
|
||||
"""Лимиты worker: бомба памяти -> resource_limit (permanent), долгая обработка -> timeout (transient)."""
|
||||
out = in_container('worker', '''
|
||||
import asyncio, io, struct, zlib
|
||||
from PIL import Image
|
||||
from app import imaging
|
||||
def ch(k, d): return struct.pack('>I', len(d)) + k + d + struct.pack('>I', zlib.crc32(k + d) & 0xffffffff)
|
||||
async def main():
|
||||
w = h = 6000 # 36 Мпикс: проходит лимит пикселей, но RGB-декодирование ~108 MiB
|
||||
raw = zlib.compress(b''.join(b'\\0' + b'\\0' * (3 * w) for _ in range(h)), 1)
|
||||
big = b'\\x89PNG\\r\\n\\x1a\\n' + ch(b'IHDR', struct.pack('>IIBBBBB', w, h, 8, 2, 0, 0, 0)) + ch(b'IDAT', raw) + ch(b'IEND', b'')
|
||||
try:
|
||||
await imaging.run_isolated(big, 40_000_000, 96, 60); print('mem: no error')
|
||||
except imaging.PermanentImageError as e:
|
||||
print('mem:', e.code)
|
||||
try:
|
||||
await imaging.run_isolated(big, 40_000_000, 1024, 0.2); print('time: no error')
|
||||
except imaging.TransientImageError as e:
|
||||
print('time:', e.code)
|
||||
rgba = Image.new('RGBA', (300, 200), (255, 0, 0, 0)); b = io.BytesIO(); rgba.save(b, 'PNG')
|
||||
v = await imaging.run_isolated(b.getvalue(), 40_000_000, 512, 30)
|
||||
print('alpha:', Image.open(io.BytesIO(v[0]['data'])).convert('RGB').getpixel((10, 10)))
|
||||
im = Image.new('RGB', (300, 100)); ex = im.getexif(); ex[0x0112] = 6; b = io.BytesIO(); im.save(b, 'JPEG', exif=ex)
|
||||
v = await imaging.run_isolated(b.getvalue(), 40_000_000, 512, 30)
|
||||
t = Image.open(io.BytesIO(v[0]['data']))
|
||||
print('exif:', t.size, t.getexif().get(0x0112))
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
''')
|
||||
print(' ' + out.replace('\n', '; '))
|
||||
check('mem: resource_limit' in out, 'memory limit not enforced')
|
||||
check('time: processing_timeout' in out, 'timeout not enforced')
|
||||
alpha = out.split('alpha: (')[1].split(')')[0].split(', ')
|
||||
check(all(int(x) >= 250 for x in alpha), 'alpha not composited on white')
|
||||
check('exif: (85, 256) None' in out, 'EXIF orientation not applied or metadata not stripped')
|
||||
|
||||
|
||||
TESTS = [test_variants_contract, test_worker_down_demo, test_failed_state_and_409, test_duplicate_delivery_is_noop,
|
||||
test_retry_bounded_then_replay, test_crash_between_commit_and_publish,
|
||||
test_worker_crash_after_s3_before_commit, test_worker_crash_after_commit_before_ack,
|
||||
test_expired_lease_takeover, test_staging_cleanup_after_commit, test_poison_message_to_dlq,
|
||||
test_prefetch_limited, test_worker_resource_limits]
|
||||
|
||||
|
||||
def main() -> int:
|
||||
c = Client(BASE_URL, timeout=30)
|
||||
wait_ready_api(c)
|
||||
only = set(sys.argv[1:])
|
||||
failed = 0
|
||||
selected = [t for t in TESTS if not only or t.__name__ in only]
|
||||
for test in selected:
|
||||
started = time.monotonic()
|
||||
try:
|
||||
test(c)
|
||||
print(f'PASS {test.__name__} ({time.monotonic() - started:.1f}s)', flush=True)
|
||||
except (Failure, subprocess.CalledProcessError, OSError) as exc:
|
||||
failed += 1
|
||||
detail = getattr(exc, 'stderr', '') or ''
|
||||
print(f'FAIL {test.__name__}: {exc} {detail.strip()[-300:]}', flush=True)
|
||||
print(f'{len(selected) - failed}/{len(selected)} passed')
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
Executable
+64
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Сводка трека 1: evidence/track1/*.json -> markdown-таблицы (stdout и evidence/track1/report.md).
|
||||
|
||||
Запуск (Python 3.9+, без зависимостей): python student-tests/track1_report.py [каталог, по умолчанию evidence/track1]
|
||||
Повторы одной конфигурации показываются как среднее и диапазон [min..max], чтобы был виден разброс.
|
||||
"""
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DIR = Path(sys.argv[1]) if len(sys.argv) > 1 else ROOT / 'evidence/track1'
|
||||
|
||||
|
||||
def rng(values, fmt='{:.2f}'):
|
||||
values = [v for v in values if v is not None]
|
||||
if not values:
|
||||
return '—'
|
||||
mean = sum(values) / len(values)
|
||||
if len(values) == 1 or max(values) == min(values):
|
||||
return fmt.format(mean)
|
||||
return f"{fmt.format(mean)} [{fmt.format(min(values))}..{fmt.format(max(values))}]"
|
||||
|
||||
|
||||
def main() -> None:
|
||||
runs = [json.loads(p.read_text(encoding='utf-8')) for p in sorted(DIR.glob('*.json'))]
|
||||
matrix = defaultdict(list)
|
||||
for r in runs:
|
||||
m = re.fullmatch(r'c(\d+)-p(\d+)-(small|large)-r\d+', r['label'])
|
||||
if m:
|
||||
matrix[(int(m[1]), int(m[2]), m[3])].append(r)
|
||||
lines = ['## Матрица concurrency/prefetch', '',
|
||||
'| Размер | concurrency / prefetch | Повторов | Принято / ready / failed / потеряно | Throughput, ready/s | '
|
||||
'p50 до ready, с | p95 до ready, с | p99 до ready, с | Макс. незавершённых | Пик памяти worker, MiB | Разгрузка, с |',
|
||||
'| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |']
|
||||
for (c, p, size), rs in sorted(matrix.items(), key=lambda kv: (kv[0][2] != 'small', kv[0][0], kv[0][1])):
|
||||
lines.append(
|
||||
f"| {size} | {c} / {p} | {len(rs)} | "
|
||||
f"{sum(r['accepted'] for r in rs)} / {sum(r['ready'] for r in rs)} / {sum(r['failed'] for r in rs)} / "
|
||||
f"{sum(r['lost_accepted'] for r in rs)} | "
|
||||
f"{rng([r['throughput_ready_per_s'] for r in rs])} | {rng([r['time_to_ready_s']['p50'] for r in rs])} | "
|
||||
f"{rng([r['time_to_ready_s']['p95'] for r in rs])} | {rng([r['time_to_ready_s']['p99'] for r in rs])} | "
|
||||
f"{rng([r['queue_lag']['max_pending_jobs'] for r in rs], '{:.0f}')} | "
|
||||
f"{rng([r['worker_memory_mib']['peak'] for r in rs], '{:.0f}')} | {rng([r['drain_seconds'] for r in rs], '{:.1f}')} |")
|
||||
lines += ['', '## Backpressure и восстановление', '',
|
||||
'| Прогон | MAX_PENDING_JOBS | Поток | Ответы upload | Ready / failed / потеряно | Макс. незавершённых | '
|
||||
'p95 до ready, с | Throughput, ready/s | Пик памяти, MiB |',
|
||||
'| --- | --- | --- | --- | --- | --- | --- | --- | --- |']
|
||||
for r in runs:
|
||||
if r['label'].startswith(('baseline', 'backpressure', 'recovery')):
|
||||
lines.append(
|
||||
f"| {r['label']} | {r['max_pending_jobs']} | {r['count']} x {r['size']} @ {r['rate_per_s']}/s | "
|
||||
f"{', '.join(f'{k}: {v}' for k, v in sorted(r['upload_status'].items()))} | "
|
||||
f"{r['ready']} / {r['failed']} / {r['lost_accepted']} | {r['queue_lag']['max_pending_jobs']} | "
|
||||
f"{r['time_to_ready_s']['p95']} | {r['throughput_ready_per_s']} | {r['worker_memory_mib']['peak']} |")
|
||||
text = '\n'.join(lines) + '\n'
|
||||
(DIR / 'report.md').write_text(text, encoding='utf-8')
|
||||
print(text)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user