Files
mtusi2026lab5/research/worker_limits.py
T
celis a4a7b9d41a Реализовать лабораторную 5: очередь RabbitMQ, worker и outbox
- upload возвращает 202 после записи оригинала в staging/ и одной
  транзакции attachments + jobs + outbox
- relay outbox → RabbitMQ (quorum-очередь, publisher confirms) в каждой
  реплике API; sweeper возвращает работу с истёкшей арендой
- worker: аренда с fencing-токеном, варианты thumbnail/crop/optimized
  (sharp), retry с backoff и jitter, реестр failed, replay с аудитом,
  reprocess новой версией pipeline
- reconciler дочищает staging/ и variants/
- сценарии уровней 3–4, fault-injection трека 2 (14 сценариев,
  инварианты I1–I6), evidence и REPORT.md
2026-10-31 00:31:54 +03:00

78 lines
4.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Уровень 4: ресурсы worker на худших допустимых входах (не больше MAX_UPLOAD_BYTES и MAX_IMAGE_PIXELS).
Методика: перед каждым файлом worker перезапускается (сбрасывается memory.peak cgroup v2 контейнера), файл грузится
через API, измеряются время от 202 до ready и пик памяти контейнеров worker. Затем тот же render внутри контейнера
worker с timeout 1 с (как при JOB_TIMEOUT_SECONDS=1) должен закончиться постоянной ошибкой processing_timeout.
Запуск: python3 research/worker_limits.py --base-url http://localhost:8080"""
from pathlib import Path
import struct
import subprocess
import sys
import time
import zlib
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'student-tests'))
from attachments import chunk, gray1, noise_png # noqa: E402
from failures import ROOT, compose # noqa: E402
from client import Client, arguments, check, run # noqa: E402
MiB = 1024 * 1024
RENDER = """
import { render } from './src/jobs/render.ts';
const chunks = []; for await (const c of process.stdin) chunks.push(c);
const t = performance.now();
try { await render(Buffer.concat(chunks), 1, 40000000, Number(process.argv[1])); console.log('ok', Math.round(performance.now() - t)); }
catch (e) { console.log(e.code, Math.round(performance.now() - t)); }
"""
def rgba16(width, height):
"""RGBA 16 бит: 8 байт на пиксель, 40 Мп = 320 МБ распакованных данных; повторяющиеся строки сжимаются до ~1 МБ."""
row = b'\0' + bytes(range(256)) * (width * 8 // 256)
z = zlib.compressobj(9)
data = b''.join(z.compress(row) for _ in range(height)) + z.flush()
return (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', width, height, 16, 6, 0, 0, 0))
+ chunk(b'IDAT', data) + chunk(b'IEND', b''))
def workers():
return compose('ps', '-q', 'worker', capture=True).split()
def cgroup(container, name):
r = subprocess.run(['docker', 'exec', container, 'cat', '/sys/fs/cgroup/' + name], capture_output=True, text=True)
check(r.returncode == 0, 'cgroup v2 %s unavailable' % name)
return int(r.stdout) / MiB
def main():
args = arguments('Worker resource limits on worst-case accepted images')
c = Client(args.base_url, args.ca_file, timeout=60)
alice, bob, _, chat = c.bootstrap()
limit = compose('exec', '-T', 'worker', 'sh', '-c', 'cat /sys/fs/cgroup/memory.max', capture=True).strip()
print('worker: лимит памяти контейнера %d MiB, WORKER_CONCURRENCY=2, libvips concurrency 1, cache off' % (int(limit) / MiB))
print('%-34s %9s %8s %10s %13s %13s' % ('вход', 'файл', 'пикс.', 'до ready', 'пик worker', 'timeout 1 с'))
for label, data, pixels in (('PNG RGB-шум 1860×1860 (макс. байт)', noise_png(1860), 1860 * 1860),
('PNG 1 бит 6400×6250', gray1(6400, 6250), 40_000_000),
('PNG RGBA 16 бит 6400×6250', rgba16(6400, 6250), 40_000_000)):
check(len(data) <= 10 * MiB, 'input over upload limit')
compose('restart', 'worker')
time.sleep(3)
att = c.call('POST', '/api/v1/chats/%s/attachments?filename=limits.png' % chat['id'], 202, actor=alice, raw=data,
headers={'Content-Type': 'image/png'}, schema='Attachment')['json']
start = time.monotonic()
ready = c.wait_ready(bob, att, 120)
took = time.monotonic() - start
check(len(ready['variants']) == 3, 'variants')
peak = max(cgroup(w, 'memory.peak') for w in workers())
r = subprocess.run(['docker', 'compose', 'exec', '-T', 'worker', 'node', '--input-type=module', '-e', RENDER, '1'],
cwd=ROOT, input=data, capture_output=True)
code, ms = r.stdout.decode().split()
print('%-34s %7.2f MB %6.0f M %8.1f с %9.0f MiB %13s' % (label, len(data) / 1e6, pixels / 1e6, took, peak,
'%s (%s мс)' % (code, ms)))
print('PASS: worst-case accepted images processed within worker limits')
if __name__ == '__main__':
run(main)