forked from mtusi2026/mtusi2026lab5
ЛР5: брокер RabbitMQ, worker, outbox, retry/DLQ/replay, трек 1
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/env python3
|
||||
import json
|
||||
import secrets
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SECRETS = ROOT / 'secrets'
|
||||
|
||||
|
||||
def write(name, value):
|
||||
path = SECRETS / name
|
||||
if path.exists():
|
||||
print('keep secrets/' + name)
|
||||
return path.read_text().strip()
|
||||
path.write_bytes((value + '\n').encode('utf-8'))
|
||||
print('created secrets/' + name)
|
||||
return value
|
||||
|
||||
|
||||
def main():
|
||||
SECRETS.mkdir(exist_ok=True)
|
||||
pg = write('pg_password', secrets.token_urlsafe(24))
|
||||
write('database_url', 'postgres://messenger:%s@postgres:5432/messenger?sslmode=disable' % pg)
|
||||
vk_conf = SECRETS / 'valkey_auth.conf'
|
||||
if vk_conf.exists():
|
||||
vk = vk_conf.read_text().split()[-1]
|
||||
print('keep secrets/valkey_auth.conf')
|
||||
else:
|
||||
vk = secrets.token_urlsafe(24)
|
||||
write('valkey_auth.conf', 'requirepass ' + vk)
|
||||
write('cache_url', 'redis://:%s@valkey:6379/0' % vk)
|
||||
admin_id = write('s3_admin_access_key_id', 'admin' + secrets.token_hex(8))
|
||||
admin_secret = write('s3_admin_secret_access_key', secrets.token_urlsafe(30))
|
||||
api_id = write('s3_access_key_id', 'api' + secrets.token_hex(8))
|
||||
api_secret = write('s3_secret_access_key', secrets.token_urlsafe(30))
|
||||
bucket = 'messenger-attachments'
|
||||
identities = {'identities': [
|
||||
{'name': 'bootstrap-admin',
|
||||
'credentials': [{'accessKey': admin_id, 'secretKey': admin_secret}],
|
||||
'actions': ['Admin', 'Read', 'Write', 'List', 'Tagging']},
|
||||
{'name': 'messenger-api',
|
||||
'credentials': [{'accessKey': api_id, 'secretKey': api_secret}],
|
||||
'actions': ['Read:' + bucket, 'Write:' + bucket, 'List:' + bucket]},
|
||||
]}
|
||||
write('s3_identities.json', json.dumps(identities, indent=2))
|
||||
mq_conf = SECRETS / 'rabbitmq_auth.conf'
|
||||
if mq_conf.exists():
|
||||
mq = [l.split('=', 1)[1].strip() for l in mq_conf.read_text().splitlines() if l.startswith('default_pass')][0]
|
||||
print('keep secrets/rabbitmq_auth.conf')
|
||||
else:
|
||||
mq = secrets.token_urlsafe(24)
|
||||
write('rabbitmq_auth.conf', 'default_user = messenger\ndefault_pass = %s\ndefault_vhost = /' % mq)
|
||||
write('broker_url', 'amqp://messenger:%s@rabbitmq:5672/' % mq)
|
||||
env = ROOT / '.env'
|
||||
if not env.exists():
|
||||
shutil.copy(ROOT / '.env.example', env)
|
||||
print('created .env from .env.example')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,428 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import zlib
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
sys.path.insert(0, str(ROOT / 'student-tests'))
|
||||
sys.path.insert(0, str(ROOT / 'scripts'))
|
||||
from client import Client, Failure, check
|
||||
from image_probe import jpeg_size
|
||||
import imagegen
|
||||
from lablib import sh
|
||||
|
||||
PNG = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
NETWORK = 'mtusi-lab5_data'
|
||||
TOOL_IMAGE = 'python:3.12.8-alpine3.21'
|
||||
|
||||
|
||||
def s3tool(*args):
|
||||
cmd = ['docker', 'run', '--rm', '--network', NETWORK,
|
||||
'-v', str(ROOT / 'secrets').replace('\\', '/') + ':/secrets:ro',
|
||||
'-v', str(ROOT / 'scripts').replace('\\', '/') + ':/tool:ro',
|
||||
TOOL_IMAGE, 'python', '-I', '/tool/s3tool.py', *args]
|
||||
r = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8')
|
||||
if r.returncode != 0:
|
||||
raise RuntimeError('s3tool failed: ' + (r.stdout + r.stderr).strip()[-300:])
|
||||
return json.loads(r.stdout.strip().splitlines()[-1])
|
||||
|
||||
|
||||
def psql(sql):
|
||||
return sh('docker', 'compose', 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger',
|
||||
'-At', '-F', '|', '-v', 'ON_ERROR_STOP=1', '-c', sql)
|
||||
|
||||
|
||||
def queues():
|
||||
out = sh('docker', 'compose', 'exec', '-T', 'rabbitmq', 'rabbitmqctl', '-q', 'list_queues',
|
||||
'name', 'messages_ready', 'messages_unacknowledged', 'consumers', '--formatter', 'json')
|
||||
return {q['name']: {'ready': q['messages_ready'], 'unacked': q['messages_unacknowledged'],
|
||||
'consumers': q['consumers']} for q in json.loads(out)}
|
||||
|
||||
|
||||
def restarts(service):
|
||||
out = sh('docker', 'compose', 'ps', '-a', '-q', service)
|
||||
return {cid[:12]: int(sh('docker', 'inspect', '-f', '{{.RestartCount}}', cid)) for cid in out.split()}
|
||||
|
||||
|
||||
def events(att_id):
|
||||
rows = psql("SELECT e.attempt, e.event, COALESCE(e.error_code,''), "
|
||||
"to_char(e.created_at AT TIME ZONE 'UTC','HH24:MI:SS.MS') "
|
||||
"FROM job_events e JOIN attachment_jobs j USING (job_id) "
|
||||
"WHERE j.attachment_id = '%s' ORDER BY e.id" % att_id)
|
||||
return [dict(zip(('attempt', 'event', 'error_code', 'at'), r.split('|'))) for r in rows.splitlines()]
|
||||
|
||||
|
||||
def event_times(att_id):
|
||||
rows = psql("SELECT e.event, extract(epoch FROM e.created_at) FROM job_events e JOIN attachment_jobs j USING (job_id) "
|
||||
"WHERE j.attachment_id = '%s' ORDER BY e.id" % att_id)
|
||||
return [(r.split('|')[0], float(r.split('|')[1])) for r in rows.splitlines()]
|
||||
|
||||
|
||||
def job_row(att_id):
|
||||
r = psql("SELECT j.job_id, j.status, j.attempt, j.max_attempts, COALESCE(j.error_code,''), "
|
||||
"(SELECT count(*) FROM attachment_variants v WHERE v.attachment_id = j.attachment_id), "
|
||||
"(SELECT count(*) FROM job_outbox o WHERE o.job_id = j.job_id), "
|
||||
"(SELECT count(*) FROM job_outbox o WHERE o.job_id = j.job_id AND o.published_at IS NULL), "
|
||||
"a.staging_key IS NULL "
|
||||
"FROM attachment_jobs j JOIN attachments a ON a.id = j.attachment_id WHERE j.attachment_id = '%s'" % att_id)
|
||||
k = ('job_id', 'status', 'attempt', 'max_attempts', 'error_code', 'variant_rows', 'outbox_rows',
|
||||
'outbox_unpublished', 'staging_removed')
|
||||
v = r.split('|')
|
||||
d = dict(zip(k, v))
|
||||
for f in ('attempt', 'max_attempts', 'variant_rows', 'outbox_rows', 'outbox_unpublished'):
|
||||
d[f] = int(d[f])
|
||||
d['staging_removed'] = d['staging_removed'] == 't'
|
||||
return d
|
||||
|
||||
|
||||
def s3_counts(chat_id, att_id):
|
||||
return {'variants_objects': s3tool('count', 'variants/%s/%s/' % (chat_id, att_id))['count'],
|
||||
'final_original': s3tool('count', 'attachments/%s/%s' % (chat_id, att_id))['count'],
|
||||
'staging_objects': s3tool('count', 'staging/' + att_id)['count']}
|
||||
|
||||
|
||||
def upload(c, actor, chat, data=PNG, name='sample.png', ctype='image/png', expected=202):
|
||||
return c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + name, expected,
|
||||
actor=actor, raw=data, headers={'Content-Type': ctype},
|
||||
schema='Attachment' if expected == 202 else None)
|
||||
|
||||
|
||||
def wait_status(c, actor, att_id, want, timeout=120):
|
||||
deadline = time.monotonic() + timeout
|
||||
seen = []
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
a = c.call('GET', '/api/v1/attachments/' + att_id, actor=actor, schema='Attachment')['json']
|
||||
except Failure:
|
||||
time.sleep(0.5)
|
||||
continue
|
||||
if not seen or seen[-1] != a['status']:
|
||||
seen.append(a['status'])
|
||||
if a['status'] in want:
|
||||
return a, seen
|
||||
time.sleep(0.3)
|
||||
raise Failure('attachment did not reach %s in %ss (seen %s)' % (want, timeout, seen))
|
||||
|
||||
|
||||
def wait_api(c, timeout=90):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
c.call('GET', '/health/ready', schema='Health')
|
||||
return
|
||||
except Failure:
|
||||
time.sleep(0.5)
|
||||
raise Failure('API not ready')
|
||||
|
||||
|
||||
def check_ready(c, actor, att):
|
||||
names = sorted(v['name'] for v in att['variants'])
|
||||
check(names == ['crop', 'optimized', 'thumbnail'], 'variants: %s' % names)
|
||||
orig = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=actor)
|
||||
check(hashlib.sha256(orig['bytes']).hexdigest() == att['sha256'], 'original changed')
|
||||
out = {'variants': {}}
|
||||
for v in att['variants']:
|
||||
r = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=' + v['name'], actor=actor)
|
||||
check(hashlib.sha256(r['bytes']).hexdigest() == v['sha256'], v['name'] + ' checksum')
|
||||
check(r['headers'].get_content_type() == v['content_type'], v['name'] + ' content type')
|
||||
out['variants'][v['name']] = '%s %dx%d %dB' % (v['content_type'], v['width'], v['height'], v['size_bytes'])
|
||||
thumb = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=thumbnail', actor=actor)['bytes']
|
||||
out['thumbnail_real_jpeg_size'] = list(jpeg_size(thumb))
|
||||
out['original_sha256_ok'] = True
|
||||
return out
|
||||
|
||||
|
||||
def fault_upload(c, actor, chat, point):
|
||||
name = 'fault-%s-%d.png' % (point, int(time.time() * 1000))
|
||||
try:
|
||||
att = upload(c, actor, chat, name=name)['json']
|
||||
return att['id'], name, 202
|
||||
except Failure as exc:
|
||||
att_id = psql("SELECT id FROM attachments WHERE chat_id = '%s' AND filename = '%s'" % (chat['id'], name))
|
||||
return att_id, name, 'client saw failure: ' + str(exc)[-60:]
|
||||
|
||||
|
||||
def cmd_worker_down(a):
|
||||
c = Client(a.base_url, timeout=30)
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
steps = []
|
||||
sh('docker', 'compose', 'stop', 'worker')
|
||||
steps.append('docker compose stop worker')
|
||||
t0 = time.monotonic()
|
||||
r = upload(c, alice, chat)
|
||||
att = r['json']
|
||||
upload_ms = round((time.monotonic() - t0) * 1000)
|
||||
steps.append('upload -> %d %s' % (r['status'], att['status']))
|
||||
msg = c.message(alice, chat, '', attachments=[att['id']])['json']
|
||||
steps.append('message with queued attachment -> 201')
|
||||
c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', 409, actor=bob)
|
||||
steps.append('content while queued -> 409')
|
||||
c.message(bob, chat, 'текст работает без worker')
|
||||
steps.append('plain text message -> 201')
|
||||
time.sleep(2)
|
||||
q_before = queues()
|
||||
job_before = job_row(att['id'])
|
||||
sh('docker', 'compose', 'restart', 'api')
|
||||
sh('docker', 'compose', 'restart', 'rabbitmq')
|
||||
sh('docker', 'compose', 'up', '-d', '--no-recreate', '--wait', 'rabbitmq', 'api', 'lb')
|
||||
wait_api(c)
|
||||
steps.append('docker compose restart api rabbitmq (volumes kept)')
|
||||
q_after = queues()
|
||||
still = c.call('GET', '/api/v1/attachments/' + att['id'], actor=bob, schema='Attachment')['json']['status']
|
||||
sh('docker', 'compose', 'start', 'worker')
|
||||
steps.append('docker compose start worker')
|
||||
t1 = time.monotonic()
|
||||
ready, seen = wait_status(c, bob, att['id'], ('ready', 'failed'))
|
||||
check(ready['status'] == 'ready', 'did not become ready')
|
||||
res = {
|
||||
'attachment_id': att['id'], 'message_id': msg['id'],
|
||||
'upload_status': r['status'], 'upload_ms_worker_down': upload_ms,
|
||||
'queue_before_restart': q_before.get('attachment.process.v1'),
|
||||
'job_before_restart': job_before,
|
||||
'queue_after_api_and_broker_restart': q_after.get('attachment.process.v1'),
|
||||
'status_after_restart_before_worker': still,
|
||||
'seconds_to_ready_after_worker_start': round(time.monotonic() - t1, 2),
|
||||
'statuses_seen': seen, 'steps': steps,
|
||||
'ready_check': check_ready(c, bob, ready),
|
||||
'job_after': job_row(att['id']), 's3': s3_counts(chat['id'], att['id']),
|
||||
}
|
||||
return res
|
||||
|
||||
|
||||
def cmd_api_crash(a):
|
||||
c = Client(a.base_url, timeout=30)
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
before = restarts('api')
|
||||
att_id, name, client_view = fault_upload(c, alice, chat, 'api-after-commit')
|
||||
check(att_id, 'attachment row not found')
|
||||
row = job_row(att_id)
|
||||
ready, seen = wait_status(c, bob, att_id, ('ready', 'failed'))
|
||||
check(ready['status'] == 'ready', 'not ready')
|
||||
time.sleep(3)
|
||||
return {'fault': 'API os.Exit right after COMMIT(queued+job+outbox), before publish and before HTTP response',
|
||||
'attachment_id': att_id, 'client_view': client_view,
|
||||
'job_right_after_crash': row, 'api_restart_counts_before': before, 'api_restart_counts_after': restarts('api'),
|
||||
'statuses_seen': seen, 'events': events(att_id), 'job_after': job_row(att_id),
|
||||
'ready_check': check_ready(c, bob, ready)}
|
||||
|
||||
|
||||
def _worker_crash(a, point, desc):
|
||||
c = Client(a.base_url, timeout=30)
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
before = restarts('worker')
|
||||
att_id, name, client_view = fault_upload(c, alice, chat, point)
|
||||
ready, seen = wait_status(c, bob, att_id, ('ready', 'failed'))
|
||||
check(ready['status'] == 'ready', 'not ready')
|
||||
time.sleep(5)
|
||||
job = job_row(att_id)
|
||||
s3 = s3_counts(chat['id'], att_id)
|
||||
check(job['variant_rows'] == 3 and s3['variants_objects'] == 3, 'duplicated or missing variants')
|
||||
logs = sh('docker', 'compose', 'logs', 'worker', '--no-log-prefix', '--since', '3m')
|
||||
noop = [json.loads(l) for l in logs.splitlines() if att_id in l and 'no-op' in l]
|
||||
return {'fault': desc, 'attachment_id': att_id, 'upload': client_view,
|
||||
'worker_restart_counts_before': before, 'worker_restart_counts_after': restarts('worker'),
|
||||
'statuses_seen': seen, 'events': events(att_id), 'job_after': job, 's3': s3,
|
||||
'redelivery_noop_log': [{'result': n.get('result'), 'redelivered': n.get('redelivered')} for n in noop],
|
||||
'ready_check': check_ready(c, bob, ready)}
|
||||
|
||||
|
||||
def cmd_effect_crash(a):
|
||||
return _worker_crash(a, 'worker-after-effect',
|
||||
'worker os.Exit after writing original+variants to S3, before result COMMIT and ack')
|
||||
|
||||
|
||||
def cmd_ack_crash(a):
|
||||
return _worker_crash(a, 'worker-before-ack', 'worker os.Exit after result COMMIT + staging cleanup, before ack')
|
||||
|
||||
|
||||
def cmd_retry(a):
|
||||
c = Client(a.base_url, timeout=30)
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
att_id, _, _ = fault_upload(c, alice, chat, 'transient')
|
||||
ready, seen = wait_status(c, bob, att_id, ('ready', 'failed'))
|
||||
check(ready['status'] == 'ready', 'not ready')
|
||||
t = event_times(att_id)
|
||||
fails = [x for x in t if x[0] == 'retry_scheduled']
|
||||
starts = [x for x in t if x[0] == 'started']
|
||||
gaps = [round(starts[i + 1][1] - fails[i][1], 2) for i in range(len(fails))]
|
||||
return {'fault': 'attempts 1 and 2 raise a transient error (injected_transient)',
|
||||
'attachment_id': att_id, 'statuses_seen': seen, 'events': events(att_id),
|
||||
'retry_gaps_seconds': gaps,
|
||||
'expected_gap_ranges': ['attempt1: backoff [0.5, 1.0] s + relay poll <= 1 s',
|
||||
'attempt2: backoff [1.0, 2.0] s + relay poll <= 1 s'],
|
||||
'job_after': job_row(att_id), 'ready_check': check_ready(c, bob, ready)}
|
||||
|
||||
|
||||
def cmd_replay(a):
|
||||
c = Client(a.base_url, timeout=30)
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
att_id, _, _ = fault_upload(c, alice, chat, 'flaky')
|
||||
failed, seen = wait_status(c, bob, att_id, ('ready', 'failed'), timeout=180)
|
||||
check(failed['status'] == 'failed', 'expected failed')
|
||||
res = {'fault': 'transient error on every attempt <= JOB_MAX_ATTEMPTS', 'attachment_id': att_id,
|
||||
'statuses_seen': seen, 'failed_metadata': {k: failed[k] for k in ('status', 'error_code', 'variants')},
|
||||
'content_when_failed': c.call('GET', '/api/v1/attachments/' + att_id + '/content', 409, actor=bob)['status'],
|
||||
'attach_failed_to_message': c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice,
|
||||
body={'text': 'x', 'attachment_ids': [att_id]},
|
||||
headers={'Idempotency-Key': 'replay-' + att_id})['status'],
|
||||
'job_failed': job_row(att_id)}
|
||||
res['dlq_registry_query'] = psql("SELECT count(*) FROM attachment_jobs WHERE status = 'failed' AND attachment_id = '%s'" % att_id)
|
||||
replay = lambda: json.loads(sh('docker', 'compose', 'exec', '-T', 'worker', '/app/server', 'replay', att_id,
|
||||
'--actor', 'lab5ops'))
|
||||
res['replay_1'] = replay()
|
||||
ready, seen2 = wait_status(c, bob, att_id, ('ready', 'failed'))
|
||||
check(ready['status'] == 'ready', 'replay did not finish')
|
||||
res['replay_2_after_ready'] = replay()
|
||||
res['statuses_after_replay'] = seen2
|
||||
res['events'] = events(att_id)
|
||||
res['job_after'] = job_row(att_id)
|
||||
res['ready_check'] = check_ready(c, bob, ready)
|
||||
return res
|
||||
|
||||
|
||||
def corrupt_png():
|
||||
good = imagegen.png(64, 64)
|
||||
return (b'\x89PNG\r\n\x1a\n' + imagegen.chunk(b'IHDR', good[16:29]) +
|
||||
imagegen.chunk(b'IDAT', b'not-a-zlib-stream' * 10) + imagegen.chunk(b'IEND', b''))
|
||||
|
||||
|
||||
def cmd_invalid(a):
|
||||
c = Client(a.base_url, timeout=60)
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
att = upload(c, alice, chat, data=corrupt_png(), name='corrupt.png')['json']
|
||||
failed, seen = wait_status(c, bob, att['id'], ('ready', 'failed'))
|
||||
check(failed['status'] == 'failed' and failed['error_code'] == 'invalid_image', 'expected invalid_image')
|
||||
return {
|
||||
'corrupt_png': {'upload': 202, 'statuses_seen': seen, 'error_code': failed['error_code'],
|
||||
'events': events(att['id']), 'job': job_row(att['id'])},
|
||||
'api_rejects_before_queue': {
|
||||
'pixel_bomb_20000x20000': upload(c, alice, chat, data=imagegen.bomb_png(), name='bomb.png', expected=413)['status'],
|
||||
'not_an_image': upload(c, alice, chat, data=b'GIF89a' + b'\0' * 100, name='x.png', expected=415)['status'],
|
||||
'over_10MiB': upload(c, alice, chat, data=b'\x89PNG\r\n\x1a\n' + b'\0' * (10 * 1024 * 1024 + 1),
|
||||
name='big.png', expected=413)['status'],
|
||||
'path_in_filename': upload(c, alice, chat, name='..%2Fetc.png', expected=400)['status'],
|
||||
}}
|
||||
|
||||
|
||||
def cmd_hang(a):
|
||||
c = Client(a.base_url, timeout=30)
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
att_id, _, _ = fault_upload(c, alice, chat, 'hang')
|
||||
t0 = time.monotonic()
|
||||
ready, seen = wait_status(c, bob, att_id, ('ready', 'failed'), timeout=150)
|
||||
check(ready['status'] == 'ready', 'not ready')
|
||||
took = round(time.monotonic() - t0, 1)
|
||||
time.sleep(70)
|
||||
logs = sh('docker', 'compose', 'logs', 'worker', '--no-log-prefix', '--since', '5m')
|
||||
stale = [l for l in logs.splitlines() if att_id in l and ('stale attempt' in l or 'no-op' in l)]
|
||||
return {'fault': 'attempt 1 freezes for 3x lease without heartbeat (simulated hung worker)',
|
||||
'attachment_id': att_id, 'seconds_to_ready': took, 'statuses_seen': seen,
|
||||
'events': events(att_id), 'job_after': job_row(att_id), 's3': s3_counts(chat['id'], att_id),
|
||||
'stale_attempt_logs': [json.loads(l).get('msg') for l in stale],
|
||||
'ready_check': check_ready(c, bob, ready)}
|
||||
|
||||
|
||||
def cmd_dlq(a):
|
||||
before = queues()
|
||||
script = ('U=$(sed -n "s/^default_user = //p" /etc/rabbitmq/conf.d/20-auth.conf); '
|
||||
'P=$(sed -n "s/^default_pass = //p" /etc/rabbitmq/conf.d/20-auth.conf); '
|
||||
'wget -q -O- --header "Content-Type: application/json" --post-data '
|
||||
'\'{"properties":{"delivery_mode":2},"routing_key":"attachment.process.v1",'
|
||||
'"payload":"{\\"not\\":\\"a job\\"}","payload_encoding":"string"}\' '
|
||||
'"http://$U:$P@127.0.0.1:15672/api/exchanges/%2F/attachments/publish"')
|
||||
routed = sh('docker', 'compose', 'exec', '-T', 'rabbitmq', 'sh', '-c', script)
|
||||
time.sleep(3)
|
||||
after = queues()
|
||||
logs = sh('docker', 'compose', 'logs', 'worker', '--no-log-prefix', '--since', '1m')
|
||||
return {'published': json.loads(routed), 'dlq_before': before.get('attachment.process.dlq'),
|
||||
'dlq_after': after.get('attachment.process.dlq'),
|
||||
'worker_log': [json.loads(l)['msg'] for l in logs.splitlines() if 'DLQ' in l][-1:]}
|
||||
|
||||
|
||||
def gradient_png(w, h):
|
||||
row = b'\x02' + bytes(3 * w)
|
||||
first = b'\x00' + bytes((x * 255 // max(1, w - 1)) for x in range(w) for _ in range(3))
|
||||
raw = first + row * (h - 1)
|
||||
return imagegen.png(w, h, raw=raw, level=9)
|
||||
|
||||
|
||||
class MemSampler:
|
||||
def __init__(self, service):
|
||||
self.cids = sh('docker', 'compose', 'ps', '-q', service).split()
|
||||
self.peak = 0.0
|
||||
self._stop = threading.Event()
|
||||
self.t = threading.Thread(target=self.run, daemon=True)
|
||||
|
||||
def run(self):
|
||||
while not self._stop.is_set():
|
||||
out = sh('docker', 'stats', '--no-stream', '--format', '{{.MemUsage}}', *self.cids, check=False)
|
||||
for line in out.splitlines():
|
||||
used = line.split('/')[0].strip()
|
||||
num = float(''.join(ch for ch in used if ch.isdigit() or ch == '.') or 0)
|
||||
mib = num * 1024 if used.endswith('GiB') else num / 1024 if used.endswith('KiB') else num
|
||||
self.peak = max(self.peak, mib)
|
||||
|
||||
def __enter__(self):
|
||||
self.t.start()
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
self._stop.set()
|
||||
self.t.join(timeout=10)
|
||||
|
||||
|
||||
def cmd_limits(a):
|
||||
c = Client(a.base_url, timeout=60)
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
data = gradient_png(6000, 6000)
|
||||
limit = sh('docker', 'inspect', '-f', '{{.HostConfig.Memory}}', sh('docker', 'compose', 'ps', '-q', 'worker').split()[0])
|
||||
with MemSampler('worker') as m:
|
||||
t0 = time.monotonic()
|
||||
att = upload(c, alice, chat, data=data, name='big-6000x6000.png')['json']
|
||||
ready, seen = wait_status(c, bob, att['id'], ('ready', 'failed'), timeout=120)
|
||||
took = round(time.monotonic() - t0, 1)
|
||||
time.sleep(2)
|
||||
check(ready['status'] == 'ready', 'big image failed: %s' % ready['error_code'])
|
||||
return {'image': '6000x6000 PNG (36 MPx, %d bytes)' % len(data), 'seconds_to_ready': took,
|
||||
'worker_peak_mem_mib': round(m.peak, 1), 'worker_mem_limit_mib': int(limit) // (1 << 20),
|
||||
'variants': {v['name']: '%dx%d' % (v['width'], v['height']) for v in ready['variants']},
|
||||
'statuses_seen': seen, 'job': job_row(att['id'])}
|
||||
|
||||
|
||||
COMMANDS = {
|
||||
'worker-down': cmd_worker_down, 'api-crash': cmd_api_crash, 'effect-crash': cmd_effect_crash,
|
||||
'ack-crash': cmd_ack_crash, 'retry': cmd_retry, 'replay': cmd_replay, 'invalid': cmd_invalid,
|
||||
'hang': cmd_hang, 'dlq': cmd_dlq, 'limits': cmd_limits,
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
p.add_argument('command', choices=sorted(COMMANDS))
|
||||
p.add_argument('--base-url', default='http://localhost:8080')
|
||||
p.add_argument('--output')
|
||||
a = p.parse_args()
|
||||
started = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
|
||||
try:
|
||||
res = COMMANDS[a.command](a)
|
||||
res = {'scenario': a.command, 'result': 'PASS', 'started_at': started, **res}
|
||||
except (Failure, RuntimeError) as exc:
|
||||
res = {'scenario': a.command, 'result': 'FAIL', 'started_at': started, 'error': str(exc)}
|
||||
text = json.dumps(res, ensure_ascii=False, indent=2)
|
||||
print(text)
|
||||
if a.output:
|
||||
Path(ROOT / a.output).parent.mkdir(parents=True, exist_ok=True)
|
||||
(ROOT / a.output).write_text(text + '\n', encoding='utf-8')
|
||||
if res['result'] != 'PASS':
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,130 @@
|
||||
import json
|
||||
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
|
||||
|
||||
PROJECT = 'mtusi-lab5'
|
||||
|
||||
|
||||
def sh(*args, check=True):
|
||||
r = subprocess.run(list(args), cwd=ROOT, capture_output=True, text=True, encoding='utf-8')
|
||||
if check and r.returncode != 0:
|
||||
raise RuntimeError('%s failed: %s' % (' '.join(args[:3]), r.stderr.strip()[:300]))
|
||||
return r.stdout.strip()
|
||||
|
||||
|
||||
def api_containers(all_states=False):
|
||||
out = sh('docker', 'ps', *(['-a'] if all_states else []), '--no-trunc',
|
||||
'--filter', 'label=com.docker.compose.project=' + PROJECT,
|
||||
'--filter', 'label=com.docker.compose.service=api',
|
||||
'--format', '{{json .}}')
|
||||
rows = []
|
||||
for line in out.splitlines():
|
||||
d = json.loads(line)
|
||||
rows.append({'id': d['ID'][:12], 'name': d['Names'], 'state': d['State'], 'status': d['Status']})
|
||||
return sorted(rows, key=lambda r: r['name'])
|
||||
|
||||
|
||||
def health(cid):
|
||||
return sh('docker', 'inspect', '-f', '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}', cid)
|
||||
|
||||
|
||||
def wait_healthy(cid, timeout=60):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
if health(cid) == 'healthy':
|
||||
return True
|
||||
time.sleep(0.25)
|
||||
return False
|
||||
|
||||
|
||||
def ps_snapshot():
|
||||
return sh('docker', 'compose', 'ps', '-a', '--format', '{{.Name}}\t{{.State}}\t{{.Status}}')
|
||||
|
||||
|
||||
class WriteLoad:
|
||||
|
||||
def __init__(self, base_url, workers=8, timeout=2.0, pause=0.0):
|
||||
self.base = base_url
|
||||
self.workers = workers
|
||||
self.timeout = timeout
|
||||
self.pause = pause
|
||||
self.events = []
|
||||
self.confirmed = []
|
||||
self.retries = 0
|
||||
self._lock = threading.Lock()
|
||||
self._stop = threading.Event()
|
||||
self._threads = []
|
||||
c = Client(base_url, timeout=10)
|
||||
self.alice, self.bob, _eve, self.chat = c.bootstrap()
|
||||
self.reader = c
|
||||
|
||||
def _worker(self, wid):
|
||||
c = Client(self.base, timeout=self.timeout)
|
||||
key = text = None
|
||||
n = 0
|
||||
while not self._stop.is_set():
|
||||
if key is None:
|
||||
key = uuid.uuid4().hex
|
||||
text = 'load-%d-%d-%s' % (wid, n, key[:8])
|
||||
start = time.monotonic()
|
||||
try:
|
||||
r = c.message(self.alice, self.chat, text, key=key)
|
||||
with self._lock:
|
||||
self.events.append((start, True, r['headers']['X-Instance-Id'], time.monotonic() - start))
|
||||
self.confirmed.append(r['json'])
|
||||
key = None
|
||||
n += 1
|
||||
except Failure as exc:
|
||||
with self._lock:
|
||||
self.events.append((start, False, str(exc)[-60:], time.monotonic() - start))
|
||||
self.retries += 1
|
||||
time.sleep(0.05)
|
||||
if self.pause:
|
||||
time.sleep(self.pause)
|
||||
|
||||
def start(self):
|
||||
for i in range(self.workers):
|
||||
t = threading.Thread(target=self._worker, args=(i,), daemon=True)
|
||||
t.start()
|
||||
self._threads.append(t)
|
||||
self.t0 = time.monotonic()
|
||||
|
||||
def stop(self):
|
||||
self._stop.set()
|
||||
for t in self._threads:
|
||||
t.join(timeout=15)
|
||||
|
||||
def window(self, a, b):
|
||||
ev = [e for e in self.events if a <= e[0] < b]
|
||||
ok = [e for e in ev if e[1]]
|
||||
lat = sorted(e[3] for e in ok)
|
||||
pct = lambda p: round(1000 * lat[min(len(lat) - 1, int(p * len(lat)))], 1) if lat else None
|
||||
return {'seconds': round(b - a, 2), 'ok': len(ok), 'errors': len(ev) - len(ok),
|
||||
'ok_rps': round(len(ok) / (b - a), 1) if b > a else None,
|
||||
'p50_ms': pct(.5), 'p95_ms': pct(.95), 'p99_ms': pct(.99)}
|
||||
|
||||
def verify_history(self):
|
||||
items, cursor = [], None
|
||||
path = '/api/v1/chats/' + self.chat['id'] + '/messages?limit=100'
|
||||
while True:
|
||||
page = self.reader.call('GET', path + ('&cursor=' + cursor if cursor else ''),
|
||||
actor=self.bob, schema='MessagePage')['json']
|
||||
items += page['items']
|
||||
cursor = page['next_cursor']
|
||||
if not cursor:
|
||||
break
|
||||
by_id = {m['id']: m for m in items}
|
||||
texts = [m['text'] for m in items]
|
||||
lost = [m for m in self.confirmed if by_id.get(m['id']) != m]
|
||||
return {'stored_messages': len(items), 'confirmed_201': len(self.confirmed),
|
||||
'lost_confirmed': len(lost), 'duplicate_ids': len(items) - len(by_id),
|
||||
'duplicate_texts': len(texts) - len(set(texts)),
|
||||
'unique_confirmed': len({m['id'] for m in self.confirmed})}
|
||||
@@ -0,0 +1,6 @@
|
||||
@echo off
|
||||
cd /d "%~dp0.."
|
||||
docker compose stop lb api worker || exit /b 1
|
||||
docker compose restart postgres valkey s3 rabbitmq || exit /b 1
|
||||
docker compose up -d --no-recreate --wait postgres valkey s3 rabbitmq || exit /b 1
|
||||
docker compose start api worker lb || exit /b 1
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose stop lb api worker
|
||||
docker compose restart postgres valkey s3 rabbitmq
|
||||
docker compose up -d --no-recreate --wait postgres valkey s3 rabbitmq
|
||||
docker compose start api worker lb
|
||||
@@ -0,0 +1,137 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import hmac
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
from urllib.parse import quote
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
HOST = os.environ.get('S3_HOST', 's3:8333')
|
||||
REGION = os.environ.get('S3_REGION', 'us-east-1')
|
||||
BUCKET = os.environ.get('S3_BUCKET', 'messenger-attachments')
|
||||
SECRETS = os.environ.get('SECRETS_DIR', '/secrets')
|
||||
NS = '{http://s3.amazonaws.com/doc/2006-03-01/}'
|
||||
|
||||
|
||||
def creds(identity):
|
||||
if identity == 'anonymous':
|
||||
return None
|
||||
prefix = 's3_admin_' if identity == 'admin' else 's3_'
|
||||
read = lambda n: open(os.path.join(SECRETS, prefix + n)).read().strip()
|
||||
return read('access_key_id'), read('secret_access_key')
|
||||
|
||||
|
||||
def _h(key, msg):
|
||||
return hmac.new(key, msg.encode(), hashlib.sha256).digest()
|
||||
|
||||
|
||||
_local = threading.local()
|
||||
|
||||
|
||||
def request(method, path, identity='api', body=b'', query=None):
|
||||
query = query or {}
|
||||
headers = {'host': HOST}
|
||||
payload_hash = hashlib.sha256(body).hexdigest()
|
||||
c = creds(identity)
|
||||
if c:
|
||||
now = dt.datetime.now(dt.timezone.utc)
|
||||
amzdate, date = now.strftime('%Y%m%dT%H%M%SZ'), now.strftime('%Y%m%d')
|
||||
headers.update({'x-amz-content-sha256': payload_hash, 'x-amz-date': amzdate})
|
||||
signed = ';'.join(sorted(headers))
|
||||
cq = '&'.join('%s=%s' % (quote(k, safe='-_.~'), quote(v, safe='-_.~')) for k, v in sorted(query.items()))
|
||||
creq = '\n'.join([method, quote(path, safe='/-_.~'), cq,
|
||||
''.join('%s:%s\n' % (k, headers[k]) for k in sorted(headers)), signed, payload_hash])
|
||||
scope = '%s/%s/s3/aws4_request' % (date, REGION)
|
||||
sts = '\n'.join(['AWS4-HMAC-SHA256', amzdate, scope, hashlib.sha256(creq.encode()).hexdigest()])
|
||||
k = _h(_h(_h(_h(('AWS4' + c[1]).encode(), date), REGION), 's3'), 'aws4_request')
|
||||
sig = hmac.new(k, sts.encode(), hashlib.sha256).hexdigest()
|
||||
headers['authorization'] = 'AWS4-HMAC-SHA256 Credential=%s/%s, SignedHeaders=%s, Signature=%s' % (
|
||||
c[0], scope, signed, sig)
|
||||
url = quote(path, safe='/-_.~')
|
||||
if query:
|
||||
url += '?' + '&'.join('%s=%s' % (quote(k, safe='-_.~'), quote(v, safe='-_.~')) for k, v in sorted(query.items()))
|
||||
conn = getattr(_local, 'conn', None)
|
||||
if conn is None:
|
||||
conn = _local.conn = http.client.HTTPConnection(HOST, timeout=30)
|
||||
try:
|
||||
conn.request(method, url, body=body or None, headers=headers)
|
||||
r = conn.getresponse()
|
||||
return r.status, r.read()
|
||||
except (OSError, http.client.HTTPException):
|
||||
_local.conn = None
|
||||
raise
|
||||
|
||||
|
||||
def obj(key):
|
||||
return '/' + BUCKET + '/' + key
|
||||
|
||||
|
||||
def list_keys(prefix, identity='api'):
|
||||
keys, token = [], None
|
||||
while True:
|
||||
q = {'list-type': '2', 'prefix': prefix, 'max-keys': '1000'}
|
||||
if token:
|
||||
q['continuation-token'] = token
|
||||
st, body = request('GET', '/' + BUCKET, identity, query=q)
|
||||
if st != 200:
|
||||
raise SystemExit('list failed: HTTP %d' % st)
|
||||
root = ET.fromstring(body)
|
||||
keys += [e.find(NS + 'Key').text for e in root.findall(NS + 'Contents')]
|
||||
if root.findtext(NS + 'IsTruncated') != 'true':
|
||||
return keys
|
||||
token = root.findtext(NS + 'NextContinuationToken')
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument('cmd', choices=['get', 'put', 'delete', 'create-bucket', 'list', 'count', 'bulk-put', 'bulk-delete'])
|
||||
p.add_argument('arg', nargs='?', default='')
|
||||
p.add_argument('--as', dest='identity', default='api', choices=['api', 'admin', 'anonymous'])
|
||||
p.add_argument('--size', type=int, default=100)
|
||||
p.add_argument('--workers', type=int, default=32)
|
||||
p.add_argument('--stdin', action='store_true', help='put: body from stdin instead of random bytes')
|
||||
a = p.parse_args()
|
||||
out = {'cmd': a.cmd, 'as': a.identity}
|
||||
if a.cmd == 'get':
|
||||
st, body = request('GET', obj(a.arg), a.identity)
|
||||
out.update(status=st, bytes=len(body) if st == 200 else 0,
|
||||
sha256=hashlib.sha256(body).hexdigest() if st == 200 else None)
|
||||
elif a.cmd == 'put':
|
||||
body = sys.stdin.buffer.read() if a.stdin else os.urandom(a.size)
|
||||
st, _ = request('PUT', obj(a.arg), a.identity, body=body)
|
||||
out.update(status=st)
|
||||
elif a.cmd == 'delete':
|
||||
st, _ = request('DELETE', obj(a.arg), a.identity)
|
||||
out.update(status=st)
|
||||
elif a.cmd == 'create-bucket':
|
||||
st, _ = request('PUT', '/' + a.arg, a.identity)
|
||||
out.update(status=st)
|
||||
elif a.cmd == 'list':
|
||||
out.update(keys=list_keys(a.arg, a.identity))
|
||||
elif a.cmd == 'count':
|
||||
out.update(count=len(list_keys(a.arg, a.identity)))
|
||||
elif a.cmd in ('bulk-put', 'bulk-delete'):
|
||||
keys = [k.strip() for k in sys.stdin if k.strip()]
|
||||
data = b'x' * a.size
|
||||
|
||||
def one(k):
|
||||
if a.cmd == 'bulk-put':
|
||||
return request('PUT', obj(k), a.identity, body=data)[0]
|
||||
return request('DELETE', obj(k), a.identity)[0]
|
||||
|
||||
start = dt.datetime.now()
|
||||
with ThreadPoolExecutor(a.workers) as pool:
|
||||
codes = list(pool.map(one, keys))
|
||||
out.update(count=len(keys), ok=sum(1 for c in codes if c in (200, 204)),
|
||||
seconds=round((dt.datetime.now() - start).total_seconds(), 2))
|
||||
print(json.dumps(out))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
cd /d "%~dp0.."
|
||||
docker compose start worker
|
||||
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose start worker
|
||||
@@ -0,0 +1,10 @@
|
||||
@echo off
|
||||
setlocal
|
||||
cd /d "%~dp0.."
|
||||
if "%TARGET_INSTANCE_ID%"=="" exit /b 2
|
||||
echo %TARGET_INSTANCE_ID%| findstr /r /x "[0-9a-f][0-9a-f]*" >nul || exit /b 2
|
||||
set CID=
|
||||
for /f %%i in ('docker ps -q --filter "id=%TARGET_INSTANCE_ID%" --filter "label=com.docker.compose.project=mtusi-lab5" --filter "label=com.docker.compose.service=api"') do set CID=%%i
|
||||
if "%CID%"=="" exit /b 3
|
||||
docker stop -t 15 %CID% >nul || exit /b 1
|
||||
echo stopped api container %CID%
|
||||
@@ -0,0 +1,14 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
case "$TARGET_INSTANCE_ID" in
|
||||
*[!0-9a-f]*) echo "unexpected instance id format" >&2; exit 2 ;;
|
||||
esac
|
||||
cid=$(docker ps -q --filter "id=$TARGET_INSTANCE_ID" \
|
||||
--filter "label=com.docker.compose.project=mtusi-lab5" \
|
||||
--filter "label=com.docker.compose.service=api")
|
||||
[ -n "$cid" ] || { echo "no running api replica matches" >&2; exit 3; }
|
||||
[ "$(printf '%s\n' "$cid" | wc -l)" -eq 1 ] || { echo "ambiguous id" >&2; exit 3; }
|
||||
docker stop -t 15 "$cid" >/dev/null
|
||||
echo "stopped api container $cid"
|
||||
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
cd /d "%~dp0.."
|
||||
docker compose stop worker
|
||||
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose stop worker
|
||||
@@ -0,0 +1,230 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
sys.path.insert(0, str(ROOT / 'scripts'))
|
||||
sys.path.insert(0, str(ROOT / 'student-tests'))
|
||||
from client import Client, Failure
|
||||
from lab5ops import MemSampler, gradient_png, psql, queues
|
||||
import imagegen
|
||||
|
||||
|
||||
def compose(*args, env=None):
|
||||
e = dict(os.environ)
|
||||
e.update(env or {})
|
||||
r = subprocess.run(['docker', 'compose', '--env-file', '.env', *args], cwd=ROOT, env=e,
|
||||
capture_output=True, text=True, encoding='utf-8')
|
||||
if r.returncode != 0:
|
||||
raise RuntimeError('compose %s: %s' % (args[:2], r.stderr[-300:]))
|
||||
|
||||
|
||||
def noisy_png(w, h):
|
||||
row_noise = lambda: b'\x00' + os.urandom(3 * w)
|
||||
row_same = b'\x02' + bytes(3 * w)
|
||||
raw = b''.join(row_noise() if y % 8 == 0 else row_same for y in range(h))
|
||||
return imagegen.png(w, h, raw=raw, level=6)
|
||||
|
||||
|
||||
SIZES = {
|
||||
'S_320x200': lambda: (ROOT / 'tests/fixtures/sample.png').read_bytes(),
|
||||
'M_2000x1500': lambda: noisy_png(2000, 1500),
|
||||
'L_5000x4000': lambda: gradient_png(5000, 4000),
|
||||
}
|
||||
COUNTS = {'S_320x200': 120, 'M_2000x1500': 40, 'L_5000x4000': 16}
|
||||
CONCURRENCY = [1, 2, 4]
|
||||
|
||||
|
||||
def pct(values, p):
|
||||
if not values:
|
||||
return None
|
||||
s = sorted(values)
|
||||
return round(s[min(len(s) - 1, int(p * len(s)))], 3)
|
||||
|
||||
|
||||
class LagSampler(threading.Thread):
|
||||
def __init__(self, chat_id):
|
||||
super().__init__(daemon=True)
|
||||
self.chat_id = chat_id
|
||||
self.samples = []
|
||||
self.stop = threading.Event()
|
||||
|
||||
def run(self):
|
||||
t0 = time.monotonic()
|
||||
while not self.stop.is_set():
|
||||
try:
|
||||
r = psql("SELECT count(*) FILTER (WHERE j.status IN ('queued','processing')), "
|
||||
"COALESCE(extract(epoch FROM now() - min(j.created_at) FILTER (WHERE j.status IN ('queued','processing'))), 0) "
|
||||
"FROM attachment_jobs j JOIN attachments a ON a.id = j.attachment_id WHERE a.chat_id = '%s'" % self.chat_id)
|
||||
active, oldest = r.split('|')
|
||||
q = queues().get('attachment.process.v1', {})
|
||||
self.samples.append({'t': round(time.monotonic() - t0, 1), 'active': int(active),
|
||||
'mq_ready': q.get('ready'), 'mq_unacked': q.get('unacked'),
|
||||
'oldest_age_s': round(float(oldest), 2)})
|
||||
except Exception:
|
||||
pass
|
||||
self.stop.wait(0.5)
|
||||
|
||||
|
||||
def burst(c, actor, chat, data, n, threads=8):
|
||||
codes = []
|
||||
lock = threading.Lock()
|
||||
|
||||
def one(i):
|
||||
try:
|
||||
r = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=t1-%d.png' % i, [202, 503],
|
||||
actor=actor, raw=data, headers={'Content-Type': 'image/png'})
|
||||
code = r['status']
|
||||
ra = r['headers'].get('Retry-After')
|
||||
except Failure as exc:
|
||||
code, ra = 'error:' + str(exc)[-40:], None
|
||||
with lock:
|
||||
codes.append((code, ra))
|
||||
|
||||
t0 = time.monotonic()
|
||||
with ThreadPoolExecutor(threads) as pool:
|
||||
list(pool.map(one, range(n)))
|
||||
return codes, time.monotonic() - t0
|
||||
|
||||
|
||||
def wait_drained(chat_id, timeout=900):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
n = int(psql("SELECT count(*) FROM attachment_jobs j JOIN attachments a ON a.id = j.attachment_id "
|
||||
"WHERE a.chat_id = '%s' AND j.status IN ('queued','processing')" % chat_id))
|
||||
if n == 0:
|
||||
return True
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
def job_stats(chat_id):
|
||||
rows = psql("SELECT j.status, extract(epoch FROM j.created_at), extract(epoch FROM j.finished_at), j.attempt "
|
||||
"FROM attachment_jobs j JOIN attachments a ON a.id = j.attachment_id WHERE a.chat_id = '%s'" % chat_id)
|
||||
jobs = [r.split('|') for r in rows.splitlines()]
|
||||
ready = [(float(c), float(f)) for s, c, f, _ in jobs if s == 'ready']
|
||||
ttr = [f - c for c, f in ready]
|
||||
span = (max(f for _, f in ready) - min(c for c, _ in ready)) if ready else 0
|
||||
return {'jobs': len(jobs), 'ready': len(ready), 'failed': sum(1 for j in jobs if j[0] == 'failed'),
|
||||
'retried_jobs': sum(1 for j in jobs if int(j[3]) > 1),
|
||||
'throughput_jobs_per_s': round(len(ready) / span, 2) if span else None,
|
||||
'pipeline_span_s': round(span, 2),
|
||||
'time_to_ready_s': {'p50': pct(ttr, .5), 'p95': pct(ttr, .95), 'max': round(max(ttr), 3) if ttr else None}}
|
||||
|
||||
|
||||
def set_worker(concurrency):
|
||||
compose('up', '-d', '--no-deps', '--wait', 'worker', env={'WORKER_CONCURRENCY': str(concurrency)})
|
||||
time.sleep(2)
|
||||
|
||||
|
||||
def one_run(base_url, size, conc):
|
||||
c = Client(base_url, timeout=60)
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
data = SIZES[size]()
|
||||
n = COUNTS[size]
|
||||
lag = LagSampler(chat['id'])
|
||||
with MemSampler('worker') as mem:
|
||||
lag.start()
|
||||
codes, upload_s = burst(c, alice, chat, data, n)
|
||||
drained = wait_drained(chat['id'])
|
||||
time.sleep(1)
|
||||
lag.stop.set()
|
||||
lag.join()
|
||||
st = job_stats(chat['id'])
|
||||
s = lag.samples
|
||||
return {'size': size, 'image_bytes': len(data), 'worker_concurrency_prefetch': conc, 'uploads': n,
|
||||
'accepted_202': sum(1 for x, _ in codes if x == 202),
|
||||
'rejected': sum(1 for x, _ in codes if x != 202),
|
||||
'upload_burst_s': round(upload_s, 2), 'drained': drained, **st,
|
||||
'queue_lag': {'max_active_jobs': max((x['active'] for x in s), default=None),
|
||||
'max_mq_ready': max((x['mq_ready'] or 0 for x in s), default=None),
|
||||
'max_oldest_job_age_s': max((x['oldest_age_s'] for x in s), default=None)},
|
||||
'worker_peak_rss_mib': round(mem.peak, 1),
|
||||
'lag_timeline': s[::max(1, len(s) // 40)]}
|
||||
|
||||
|
||||
def cmd_matrix(a):
|
||||
runs = []
|
||||
try:
|
||||
for conc in CONCURRENCY:
|
||||
set_worker(conc)
|
||||
for size in SIZES:
|
||||
r = one_run(a.base_url, size, conc)
|
||||
print(json.dumps({k: r[k] for k in ('size', 'worker_concurrency_prefetch', 'throughput_jobs_per_s',
|
||||
'time_to_ready_s', 'worker_peak_rss_mib', 'queue_lag')}), flush=True)
|
||||
runs.append(r)
|
||||
finally:
|
||||
set_worker(2)
|
||||
return {'runs': runs}
|
||||
|
||||
|
||||
def cmd_backpressure(a):
|
||||
bound = 20
|
||||
compose('up', '-d', '--no-deps', '--wait', 'api', env={'MAX_ACTIVE_JOBS': str(bound)})
|
||||
set_worker(1)
|
||||
try:
|
||||
c = Client(a.base_url, timeout=60)
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
data = SIZES['M_2000x1500']()
|
||||
lag = LagSampler(chat['id'])
|
||||
lag.start()
|
||||
t0 = time.monotonic()
|
||||
codes, upload_s = burst(c, alice, chat, data, 80)
|
||||
drained = wait_drained(chat['id'])
|
||||
drain_s = time.monotonic() - t0
|
||||
t1 = time.monotonic()
|
||||
att = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=after.png', 202, actor=alice,
|
||||
raw=(ROOT / 'tests/fixtures/sample.png').read_bytes(), headers={'Content-Type': 'image/png'}, schema='Attachment')['json']
|
||||
while True:
|
||||
st = c.call('GET', '/api/v1/attachments/' + att['id'], actor=alice, schema='Attachment')['json']['status']
|
||||
if st in ('ready', 'failed'):
|
||||
break
|
||||
time.sleep(0.2)
|
||||
recovery_ready_s = time.monotonic() - t1
|
||||
time.sleep(1)
|
||||
lag.stop.set()
|
||||
lag.join()
|
||||
s = lag.samples
|
||||
return {'max_active_jobs_bound': bound, 'worker_concurrency': 1, 'uploads': 80,
|
||||
'accepted_202': sum(1 for x, _ in codes if x == 202),
|
||||
'rejected_503': sum(1 for x, _ in codes if x == 503),
|
||||
'retry_after_header': sorted({ra for x, ra in codes if x == 503}),
|
||||
'other': [x for x, _ in codes if x not in (202, 503)],
|
||||
'upload_burst_s': round(upload_s, 2), 'drained': drained, 'drain_s': round(drain_s, 1),
|
||||
'max_active_observed': max((x['active'] for x in s), default=None),
|
||||
'jobs': job_stats(chat['id']), 'after_overload_upload_status': st,
|
||||
'after_overload_seconds_to_ready': round(recovery_ready_s, 2),
|
||||
'lag_timeline': s[::max(1, len(s) // 40)]}
|
||||
finally:
|
||||
compose('up', '-d', '--no-deps', '--wait', 'api')
|
||||
set_worker(2)
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
p.add_argument('command', choices=['matrix', 'backpressure'])
|
||||
p.add_argument('--base-url', default='http://localhost:8080')
|
||||
p.add_argument('--output')
|
||||
a = p.parse_args()
|
||||
env = {'started_at': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
|
||||
'worker_limits': 'cpus=2.0 memory=768M GOMEMLIMIT=600MiB decode budget 384MiB',
|
||||
'host': 'Windows 11, Docker Desktop 29.7.2 (WSL2)'}
|
||||
res = {'experiment': a.command, **env, **(cmd_matrix(a) if a.command == 'matrix' else cmd_backpressure(a))}
|
||||
text = json.dumps(res, ensure_ascii=False, indent=1)
|
||||
if a.output:
|
||||
(ROOT / a.output).parent.mkdir(parents=True, exist_ok=True)
|
||||
(ROOT / a.output).write_text(text + '\n', encoding='utf-8')
|
||||
print(text[:3000])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user