ЛР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
+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()
|
||||
Reference in New Issue
Block a user