lab5: очередь RabbitMQ, outbox, worker, варианты, fault-injection
This commit is contained in:
Executable
+143
@@ -0,0 +1,143 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Негативные и граничные сценарии вложений (уровень 4).
|
||||
|
||||
Покрывает: слишком большой файл (по Content-Length и по пикселям), «бомбу»,
|
||||
повреждённое изображение, подмену MIME, чужой формат, опасные filename,
|
||||
чужое attachment_id, вложение другого чата, правила text/attachment_ids,
|
||||
идемпотентность с вложениями, варианты. Любой 500 — провал (Client проверяет код).
|
||||
"""
|
||||
import hashlib
|
||||
import uuid
|
||||
from labutil import bomb_png, fixture, noise_png, png, raw_post, wait_status
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
MAX = 10 * 1024 * 1024
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Attachment negative suite (lab4 level 4)')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
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 = '/api/v1/chats/' + chat['id'] + '/attachments?filename='
|
||||
results = []
|
||||
|
||||
def up(name, data, ctype, expected, chat_path=path, actor=alice):
|
||||
r = c.call('POST', chat_path + name, expected, actor=actor, raw=data, headers={'Content-Type': ctype},
|
||||
schema='Attachment' if expected == 202 else None)
|
||||
results.append((name[:40], ctype, len(data), r['status']))
|
||||
return r
|
||||
|
||||
small_png, small_jpg = fixture('small.png'), fixture('small.jpg')
|
||||
|
||||
# --- корректные файлы ---
|
||||
a_png = up('ok.png', small_png, 'image/png', 202)['json']
|
||||
a_jpg = up('ok.jpg', small_jpg, 'image/jpeg', 202)['json']
|
||||
check(a_jpg['content_type'] == 'image/jpeg' and a_jpg['sha256'] == hashlib.sha256(small_jpg).hexdigest(), 'jpeg metadata')
|
||||
uni = up('%D1%84%D0%BE%D1%82%D0%BE%20%F0%9F%98%80.png', small_png, 'image/png', 202)['json']
|
||||
check(uni['filename'] == 'фото 😀.png', 'unicode filename not preserved')
|
||||
up('params.png', small_png, 'image/png; charset=binary', 202)
|
||||
near = noise_png(MAX - 200_000)
|
||||
check(len(near) <= MAX, 'generator produced too large file')
|
||||
big_ok = up('near-limit.png', near, 'image/png', 202)['json']
|
||||
wait_status(c, bob, big_ok['id'], ('ready',), timeout=180)
|
||||
got = c.call('GET', '/api/v1/attachments/' + big_ok['id'] + '/content', actor=bob)
|
||||
check(got['bytes'] == near, 'near-limit file changed on download')
|
||||
|
||||
# --- размер и пиксели ---
|
||||
# Content-Length больше лимита: 413 сразу, без чтения тела.
|
||||
hdr = {'Authorization': 'Bearer ' + alice['token'], 'Content-Type': 'image/png'}
|
||||
st, _ = raw_post(c.base, path + 'too-big.png', dict(hdr, **{'Content-Length': str(MAX + 1)}),
|
||||
(b'\x89PNG\r\n\x1a\n' + b'\0' * 65528 for _ in range(1)))
|
||||
check(st == 413, 'Content-Length > limit: expected 413, got %s' % st)
|
||||
results.append(('too-big.png (Content-Length)', 'image/png', MAX + 1, st))
|
||||
# Без Content-Length (chunked), реально 11 MiB: сервер читает не больше лимита + 1 байт.
|
||||
def chunked(total=11 * 1024 * 1024, part=256 * 1024):
|
||||
yield b'%x\r\n\x89PNG\r\n\x1a\n\r\n' % 8
|
||||
sent = 8
|
||||
while sent < total:
|
||||
yield b'%x\r\n' % part + b'\0' * part + b'\r\n'
|
||||
sent += part
|
||||
yield b'0\r\n\r\n'
|
||||
st, _ = raw_post(c.base, path + 'too-big-chunked.png', dict(hdr, **{'Transfer-Encoding': 'chunked'}), chunked())
|
||||
check(st == 413, 'chunked > limit: expected 413, got %s' % st)
|
||||
results.append(('too-big-chunked.png (no Content-Length)', 'image/png', 11 * 1024 * 1024, st))
|
||||
up('bomb.png', bomb_png(), 'image/png', 413)
|
||||
up('over-pixels.png', bomb_png(8000, 5001), 'image/png', 413)
|
||||
|
||||
# --- содержимое и MIME ---
|
||||
up('truncated.png', small_png[:len(small_png) // 2], 'image/png', 415)
|
||||
broken = bytearray(small_png)
|
||||
broken[len(broken) // 2] ^= 0xFF
|
||||
up('corrupt.png', bytes(broken), 'image/png', 415)
|
||||
up('truncated.jpg', small_jpg[:len(small_jpg) - 2], 'image/jpeg', 415)
|
||||
up('mime-swap.png', small_png, 'image/jpeg', 415) # PNG, объявлен как JPEG
|
||||
up('mime-swap.jpg', small_jpg, 'image/png', 415)
|
||||
up('text.png', b'definitely not an image', 'image/png', 415)
|
||||
up('gif.gif', b'GIF89a\x01\x00\x01\x00\x00\x00\x00;', 'image/gif', 415)
|
||||
up('ctype-missing.png', small_png, 'application/octet-stream', 415)
|
||||
up('empty.png', b'', 'image/png', 415)
|
||||
up('short-data.png', png(8, 8, raw=b'\x00' * 10), 'image/png', 415)
|
||||
|
||||
# --- filename ---
|
||||
for bad in ('..%2Fetc%2Fpasswd', 'a%5Cb.png', 'nul%00.png', 'bell%07.png', '%20%20%20', 'x' * 256, ''):
|
||||
up(bad, small_png, 'image/png', 400)
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments', 400, actor=alice, raw=small_png,
|
||||
headers={'Content-Type': 'image/png'})
|
||||
c.call('POST', path + 'a.png&filename=b.png', 400, actor=alice, raw=small_png, headers={'Content-Type': 'image/png'})
|
||||
|
||||
# --- доступ ---
|
||||
up('eve.png', small_png, 'image/png', 404, actor=eve)
|
||||
c.call('POST', path + 'anon.png', 401, raw=small_png, headers={'Content-Type': 'image/png'})
|
||||
for suffix in ('', '/content'):
|
||||
c.call('GET', '/api/v1/attachments/' + a_png['id'] + suffix, 404, actor=eve)
|
||||
c.call('GET', '/api/v1/attachments/' + str(uuid.uuid4()) + suffix, 404, actor=alice)
|
||||
c.call('GET', '/api/v1/attachments/not-a-uuid' + suffix, 400, actor=alice)
|
||||
wait_status(c, bob, a_png['id'], ('ready',))
|
||||
wait_status(c, bob, a_jpg['id'], ('ready',))
|
||||
th = c.call('GET', '/api/v1/attachments/' + a_png['id'] + '/content?variant=thumbnail', actor=bob)
|
||||
check(th['headers'].get_content_type() == 'image/jpeg', 'thumbnail of small png')
|
||||
c.call('GET', '/api/v1/attachments/' + a_png['id'] + '/content?variant=bogus', 400, actor=bob)
|
||||
orig = c.call('GET', '/api/v1/attachments/' + a_png['id'] + '/content?variant=original', actor=bob)
|
||||
check(orig['bytes'] == small_png and orig['headers'].get_content_type() == 'image/png', 'original variant')
|
||||
|
||||
# --- сообщения с вложениями ---
|
||||
foreign = up('foreign.png', small_png, 'image/png', 202,
|
||||
chat_path='/api/v1/chats/' + other['id'] + '/attachments?filename=')['json']
|
||||
mpath = '/api/v1/chats/' + chat['id'] + '/messages'
|
||||
|
||||
def msg(body, expected, key=None, actor=alice):
|
||||
return c.call('POST', mpath, expected, actor=actor, body=body,
|
||||
headers={'Idempotency-Key': key or uuid.uuid4().hex},
|
||||
schema='Message' if expected == 201 else None)
|
||||
|
||||
msg({'text': '', 'attachment_ids': [foreign['id']]}, 404) # вложение другого чата
|
||||
msg({'text': '', 'attachment_ids': [str(uuid.uuid4())]}, 404) # неизвестное
|
||||
msg({'text': 'x', 'attachment_ids': ['nope']}, 400)
|
||||
msg({'text': 'x', 'attachment_ids': [a_png['id'], a_png['id']]}, 400)
|
||||
msg({'text': 'x', 'attachment_ids': [str(uuid.uuid4()) for _ in range(11)]}, 400)
|
||||
msg({'text': ''}, 400)
|
||||
msg({'text': ' ', 'attachment_ids': []}, 400)
|
||||
msg({'attachment_ids': [a_png['id']]}, 400) # text обязателен
|
||||
msg({'text': '', 'attachment_ids': [a_png['id']]}, 404, actor=eve)
|
||||
key = uuid.uuid4().hex
|
||||
m1 = msg({'text': '', 'attachment_ids': [a_png['id'], a_jpg['id']]}, 201, key=key)['json']
|
||||
check(m1['attachment_ids'] == [a_png['id'], a_jpg['id']] and m1['text'] == '', 'attachment order/text')
|
||||
m2 = msg({'attachment_ids': [a_png['id'], a_jpg['id']], 'text': ''}, 201, key=key)['json']
|
||||
check(m2 == m1, 'idempotent replay with attachments differs')
|
||||
msg({'text': '', 'attachment_ids': [a_jpg['id'], a_png['id']]}, 409, key=key) # другой порядок = другое тело
|
||||
plain = msg({'text': 'без вложений'}, 201)['json']
|
||||
check(plain['attachment_ids'] == [], 'missing attachment_ids must be []')
|
||||
hist = c.call('GET', mpath + '?limit=100', actor=bob, schema='MessagePage')['json']['items']
|
||||
check(any(m == m1 for m in hist), 'message with attachments not in history')
|
||||
# Bob (участник) прикрепляет вложение Alice — допустимо.
|
||||
msg({'text': 'и я', 'attachment_ids': [a_png['id']]}, 201, actor=bob)
|
||||
|
||||
for row in results:
|
||||
print('%-42s %-28s %9d -> %d' % row)
|
||||
print('PASS: attachment negative suite (%d upload cases, no 5xx)' % len(results))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Executable
+282
@@ -0,0 +1,282 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Операционные сценарии вложений на Docker-стенде (уровни 3–4).
|
||||
|
||||
failover upload → остановить обслужившую реплику → download через другую
|
||||
s3-outage остановить S3: загрузка/скачивание 503, текстовый чат и readiness работают
|
||||
interrupt обрыв клиента посреди тела: ни ready-вложения, ни намерения, ни объекта
|
||||
db-gap PUT в S3 прошёл, PostgreSQL недоступен на MarkReady: объект удалён
|
||||
компенсацией, намерение осталось → убирает reconciler
|
||||
security bucket приватен (анонимно 403), у API-ключа нет прав вне bucket,
|
||||
bootstrap идемпотентен, консоль/порты S3 не опубликованы
|
||||
memory N одновременных загрузок ~9.8 MiB: пик памяти (cgroup memory.peak) реплик
|
||||
|
||||
Каждый сценарий печатает JSON-итог и PASS/FAIL.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from labutil import (BUCKET, api_container, bucket_count, compose, fixture, mc, noise_png, object_key, psql,
|
||||
raw_post, sh, wait_status)
|
||||
from client import Client, Failure, arguments, check, run
|
||||
|
||||
|
||||
def upload(c, actor, chat, data, name='f.png', ctype='image/png', expected=202):
|
||||
return c.call('POST', '/api/v1/chats/%s/attachments?filename=%s' % (chat['id'], name), expected,
|
||||
actor=actor, raw=data, headers={'Content-Type': ctype},
|
||||
schema='Attachment' if expected == 202 else None)
|
||||
|
||||
|
||||
def wait_ready(c, timeout=90):
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
try:
|
||||
c.call('GET', '/health/ready')
|
||||
return
|
||||
except Failure:
|
||||
time.sleep(1)
|
||||
raise Failure('stack not ready')
|
||||
|
||||
|
||||
def scenario_failover(c):
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
data = noise_png(2 * 1024 * 1024)
|
||||
r = upload(c, alice, chat, data)
|
||||
att, served_by = r['json'], r['headers']['X-Instance-Id']
|
||||
wait_status(c, bob, att['id'], ('ready',))
|
||||
cid = api_container(served_by)
|
||||
sh('docker', 'stop', '-t', '15', cid)
|
||||
try:
|
||||
seen = set()
|
||||
for _ in range(6):
|
||||
d = c.call('GET', '/api/v1/attachments/%s/content' % att['id'], actor=bob)
|
||||
check(d['bytes'] == data, 'downloaded bytes differ after failover')
|
||||
seen.add(d['headers']['X-Instance-Id'])
|
||||
check(served_by not in seen, 'stopped replica still serving')
|
||||
finally:
|
||||
sh('docker', 'start', cid)
|
||||
sh('sh', 'scripts/restore.sh')
|
||||
return {'uploaded_by': served_by, 'downloaded_by': sorted(seen), 'sha256': hashlib.sha256(data).hexdigest(),
|
||||
'stopped_container': cid[:12]}
|
||||
|
||||
|
||||
def scenario_s3_outage(c):
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
small = fixture('small.png')
|
||||
att = upload(c, alice, chat, small)['json']
|
||||
wait_status(c, bob, att['id'], ('ready',))
|
||||
compose('stop', 's3')
|
||||
try:
|
||||
t0 = time.time()
|
||||
up = upload(c, alice, chat, small, expected=503)
|
||||
up_s = time.time() - t0
|
||||
c.call('GET', '/api/v1/attachments/%s/content' % att['id'], 503, actor=bob)
|
||||
meta = c.call('GET', '/api/v1/attachments/%s' % att['id'], actor=bob, schema='Attachment')['json']
|
||||
msg = c.message(alice, chat, 'S3 лежит, а чат работает')['json']
|
||||
c.call('GET', '/health/ready', schema='Health')
|
||||
leftovers = psql("SELECT count(*) FROM attachments WHERE chat_id = '%s' AND status = 'uploading'" % chat['id'])
|
||||
finally:
|
||||
compose('start', 's3')
|
||||
compose('run', '--rm', 's3-init')
|
||||
for _ in range(30):
|
||||
try:
|
||||
again = upload(c, alice, chat, small)['json']
|
||||
break
|
||||
except Failure:
|
||||
time.sleep(1)
|
||||
else:
|
||||
raise Failure('upload did not recover after S3 start')
|
||||
d = c.call('GET', '/api/v1/attachments/%s/content' % att['id'], actor=bob)
|
||||
check(d['bytes'] == small, 'old attachment changed after S3 restart')
|
||||
check(leftovers == '0', 'intent rows left after failed upload: ' + leftovers)
|
||||
return {'upload_status_during_outage': up['status'], 'upload_error_seconds': round(up_s, 2),
|
||||
'download_status_during_outage': 503, 'metadata_during_outage': meta['status'],
|
||||
'text_message_during_outage': 201, 'readiness_during_outage': 200,
|
||||
'intents_left': int(leftovers), 'upload_after_recovery': again['status']}
|
||||
|
||||
|
||||
def scenario_interrupt(c):
|
||||
alice, _, _, chat = c.bootstrap()
|
||||
data = noise_png(4 * 1024 * 1024)
|
||||
hdr = {'Authorization': 'Bearer ' + alice['token'], 'Content-Type': 'image/png',
|
||||
'Content-Length': str(len(data))}
|
||||
# Отправляем 1 MiB из 4 и обрываем соединение.
|
||||
import socket
|
||||
from urllib.parse import urlsplit
|
||||
u = urlsplit(c.base)
|
||||
s = socket.create_connection((u.hostname, u.port or 80))
|
||||
head = 'POST /api/v1/chats/%s/attachments?filename=cut.png HTTP/1.1\r\nHost: %s\r\n' % (chat['id'], u.netloc)
|
||||
s.sendall((head + ''.join('%s: %s\r\n' % kv for kv in hdr.items()) + '\r\n').encode())
|
||||
s.sendall(data[:1024 * 1024])
|
||||
time.sleep(1)
|
||||
s.close()
|
||||
time.sleep(3)
|
||||
rows = psql("SELECT status FROM attachments WHERE chat_id = '%s'" % chat['id'])
|
||||
objs = str(sum(bucket_count(p + chat['id'] + '/') for p in ('s/', 'o/', 'v/')))
|
||||
check(rows == '', 'rows left after interrupted upload: %r' % rows)
|
||||
check(objs == '0', 'objects left after interrupted upload: ' + objs)
|
||||
return {'sent_bytes': 1024 * 1024, 'declared_bytes': len(data), 'rows_after': 0, 'objects_after': 0}
|
||||
|
||||
|
||||
def scenario_db_gap(c):
|
||||
"""PUT прошёл, а PostgreSQL «пропал» до MarkReady (docker pause)."""
|
||||
alice, _, _, chat = c.bootstrap()
|
||||
data = noise_png(3 * 1024 * 1024)
|
||||
hdr = {'Authorization': 'Bearer ' + alice['token'], 'Content-Type': 'image/png', 'Content-Length': str(len(data))}
|
||||
state = {}
|
||||
|
||||
def body():
|
||||
yield data[:512 * 1024] # намерение уже записано, PUT идёт
|
||||
time.sleep(2)
|
||||
compose('pause', 'postgres') # БД «пропала» до MarkReady
|
||||
state['paused_at'] = time.time()
|
||||
yield data[512 * 1024:]
|
||||
t0 = time.time()
|
||||
try:
|
||||
st, _ = raw_post(c.base, '/api/v1/chats/%s/attachments?filename=gap.png' % chat['id'], hdr, body(), read_timeout=60)
|
||||
finally:
|
||||
# Дольше таймаута запроса (30 s) и компенсации (10 s): DeleteIntent тоже не пройдёт.
|
||||
time.sleep(max(0, 45 - (time.time() - state.get('paused_at', time.time()))))
|
||||
compose('unpause', 'postgres')
|
||||
wait_ready(c)
|
||||
time.sleep(3) # отложенный UPDATE (если был) успевает закоммититься после unpause
|
||||
rows = psql("SELECT id || ' ' || status FROM attachments WHERE chat_id = '%s'" % chat['id'])
|
||||
staged = bucket_count('s/' + chat['id'] + '/')
|
||||
status_after = rows.split()[-1] if rows else 'none'
|
||||
check(st != 202, 'upload must not report success when the job was not committed (got %s)' % st)
|
||||
# Инвариант: нет строки queued/ready без исходника.
|
||||
check(not (status_after in ('queued', 'processing') and staged == 0 and bucket_count('o/' + chat['id'] + '/') == 0),
|
||||
'job without source: %r' % rows)
|
||||
if status_after in ('queued', 'processing', 'ready'):
|
||||
# COMMIT всё-таки прошёл: pipeline доводит работу до ready.
|
||||
aid = rows.split()[0]
|
||||
for _ in range(120):
|
||||
if psql("SELECT status FROM attachments WHERE id='%s'" % aid) == 'ready':
|
||||
break
|
||||
time.sleep(1)
|
||||
else:
|
||||
psql("UPDATE attachments SET updated_at = now() - interval '30 minutes' WHERE chat_id = '%s'" % chat['id'])
|
||||
for _ in range(10):
|
||||
r = compose('run', '--rm', '--no-deps', '-T', '--entrypoint', '/app/reconcile', 'reconciler',
|
||||
'--apply', '--grace', '10m', check=False)
|
||||
if r.returncode != 3:
|
||||
break
|
||||
time.sleep(2)
|
||||
check(r.returncode in (0, 4), 'reconcile failed: ' + r.stderr[-300:])
|
||||
final = psql("SELECT status FROM attachments WHERE chat_id = '%s'" % chat['id'])
|
||||
check(final in ('ready', ''), 'inconsistent final state: %r' % final)
|
||||
return {'client_status': st, 'seconds': round(time.time() - t0, 1),
|
||||
'after_gap': {'row_status': status_after, 'staging_objects': staged},
|
||||
'final': {'row_status': final or 'none'}}
|
||||
|
||||
|
||||
def scenario_security(c):
|
||||
alice, _, _, chat = c.bootstrap()
|
||||
att = upload(c, alice, chat, fixture('small.png'))['json']
|
||||
key = object_key(att['id'])
|
||||
url = 'http://s3:9000/%s/%s' % (BUCKET, key)
|
||||
# Анонимно изнутри сети стенда (из контейнера API): объект и листинг закрыты.
|
||||
anon_get = compose('exec', '-T', 'api', 'wget', '-q', '-S', '-O', '/dev/null', url, check=False)
|
||||
anon_list = compose('exec', '-T', 'api', 'wget', '-q', '-S', '-O', '/dev/null',
|
||||
'http://s3:9000/%s?list-type=2' % BUCKET, check=False)
|
||||
check(anon_get.returncode != 0 and '403' in anon_get.stderr, 'anonymous GET must be 403')
|
||||
check(anon_list.returncode != 0 and '403' in anon_list.stderr, 'anonymous LIST must be 403')
|
||||
# Ключ API: свой bucket — да, остальное — нет.
|
||||
own = mc('mc stat s3/%s/%s >/dev/null && echo ok' % (BUCKET, key), as_user='api').stdout.strip()
|
||||
mb = mc('mc mb s3/evil-bucket-%s' % uuid.uuid4().hex[:6], check=False, as_user='api')
|
||||
admin = mc('mc admin user list s3', check=False, as_user='api')
|
||||
buckets = mc('mc ls s3', check=False, as_user='api')
|
||||
check(own == 'ok', 'api key cannot read own bucket')
|
||||
check(mb.returncode != 0, 'api key must not create buckets')
|
||||
check(admin.returncode != 0, 'api key must not use admin API')
|
||||
check(buckets.returncode != 0 or 'evil' not in buckets.stdout, 'api key sees a bucket it created?!')
|
||||
# Bootstrap идемпотентен: повторный запуск успешен, объект на месте.
|
||||
before = mc('mc ls --recursive s3/%s | wc -l' % BUCKET).stdout.strip()
|
||||
r1 = compose('run', '--rm', 's3-init')
|
||||
r2 = compose('run', '--rm', 's3-init')
|
||||
after = mc('mc ls --recursive s3/%s | wc -l' % BUCKET).stdout.strip()
|
||||
check(before == after, 'bootstrap changed objects')
|
||||
ports = compose('ps', 's3', '--format', '{{.Ports}}').stdout.strip()
|
||||
check('0.0.0.0' not in ports and '127.0.0.1' not in ports, 's3 port is published: ' + ports)
|
||||
return {'anonymous_get': '403', 'anonymous_list': '403', 'api_key_own_bucket': 'allowed',
|
||||
'api_key_make_bucket': 'denied', 'api_key_admin': 'denied',
|
||||
'api_key_visible_buckets': sorted(l.split()[-1].rstrip('/') for l in buckets.stdout.splitlines() if l.strip())
|
||||
if buckets.returncode == 0 else 'denied',
|
||||
'bootstrap_runs': [r1.returncode, r2.returncode], 'objects_before_after': [int(before), int(after)],
|
||||
's3_published_ports': ports or 'none'}
|
||||
|
||||
|
||||
def read_peak(cid):
|
||||
r = sh('docker', 'exec', cid, 'cat', '/sys/fs/cgroup/memory.peak', check=False)
|
||||
return int(r.stdout.strip()) if r.returncode == 0 and r.stdout.strip().isdigit() else None
|
||||
|
||||
|
||||
def read_current(cid):
|
||||
r = sh('docker', 'exec', cid, 'cat', '/sys/fs/cgroup/memory.current', check=False)
|
||||
return int(r.stdout.strip()) if r.returncode == 0 and r.stdout.strip().isdigit() else None
|
||||
|
||||
|
||||
def scenario_memory(c, parallel_levels=(10, 20)):
|
||||
alice, _, _, chat = c.bootstrap()
|
||||
data = noise_png(10 * 1024 * 1024 - 300_000)
|
||||
out = {'file_bytes': len(data), 'runs': []}
|
||||
for n in parallel_levels:
|
||||
compose('restart', 'api') # новый cgroup → memory.peak с нуля
|
||||
sh('sh', 'scripts/restore.sh')
|
||||
wait_ready(c)
|
||||
cids = compose('ps', '-q', 'api').stdout.split()
|
||||
upload(c, alice, chat, fixture('small.png')) # прогрев пулов/соединений
|
||||
base = {cid[:12]: read_peak(cid) for cid in cids}
|
||||
barrier = threading.Barrier(n)
|
||||
res = []
|
||||
|
||||
def worker():
|
||||
local = Client(c.base, timeout=60)
|
||||
barrier.wait()
|
||||
t0 = time.time()
|
||||
try:
|
||||
upload(local, alice, chat, data, name='mem.png')
|
||||
res.append(('ok', time.time() - t0))
|
||||
except Failure as e:
|
||||
res.append(('fail:' + str(e)[:60], time.time() - t0))
|
||||
ths = [threading.Thread(target=worker) for _ in range(n)]
|
||||
for t in ths:
|
||||
t.start()
|
||||
for t in ths:
|
||||
t.join()
|
||||
peak = {cid[:12]: read_peak(cid) for cid in cids}
|
||||
ok = sum(1 for r in res if r[0] == 'ok')
|
||||
mib = lambda v: round(v / 1048576, 1) if v else None
|
||||
run = {'parallel': n, 'ok': ok, 'failed': [r[0] for r in res if r[0] != 'ok'],
|
||||
'max_seconds': round(max(r[1] for r in res), 2),
|
||||
'baseline_peak_mib': {k: mib(v) for k, v in base.items()},
|
||||
'peak_mib': {k: mib(v) for k, v in peak.items()},
|
||||
'payload_total_mib': round(n * len(data) / 1048576, 1)}
|
||||
growth = [peak[k] - base[k] for k in peak if peak[k] and base[k]]
|
||||
run['max_peak_growth_mib'] = mib(max(growth)) if growth else None
|
||||
out['runs'].append(run)
|
||||
check(ok == n, '%d of %d concurrent uploads failed: %s' % (n - ok, n, run['failed'][:3]))
|
||||
return out
|
||||
|
||||
|
||||
SCENARIOS = {'failover': scenario_failover, 's3-outage': scenario_s3_outage, 'interrupt': scenario_interrupt,
|
||||
'db-gap': scenario_db_gap, 'security': scenario_security, 'memory': scenario_memory}
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('scenario', choices=sorted(SCENARIOS))
|
||||
p.add_argument('--output', default=None)
|
||||
args = arguments('Docker-level attachment scenarios (lab4)', configure)
|
||||
c = Client(args.base_url, args.ca_file, timeout=60)
|
||||
result = SCENARIOS[args.scenario](c)
|
||||
text = json.dumps({'scenario': args.scenario, 'result': result}, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
open(args.output, 'w', encoding='utf-8').write(text + '\n')
|
||||
print(text)
|
||||
print('PASS: ' + args.scenario)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Executable
+174
@@ -0,0 +1,174 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Серия отказов под нагрузкой (уровень 4): поочерёдно останавливает КАЖДУЮ
|
||||
API-реплику (docker stop → SIGTERM → drain), восстанавливает её и переходит
|
||||
к следующей. Во время всей серии идёт closed-loop нагрузка через LB:
|
||||
POST сообщения (при ошибке повтор с тем же Idempotency-Key) и GET истории.
|
||||
|
||||
Измеряется на каждую реплику: RPS до/во время/после, число ошибок, время от
|
||||
начала остановки до последней ошибки (recovery), время до исчезновения реплики
|
||||
из ответов LB и время восстановления реплики после docker start.
|
||||
В конце проверяется: все подтверждённые сообщения на месте, дублей нет.
|
||||
|
||||
Скрипт сам вызывает docker CLI (это не публичный тест), запускать из корня репозитория.
|
||||
"""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
import sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests')) # публичный client.py
|
||||
from client import Client, Failure, arguments, check, run
|
||||
from resilience import history
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def docker(*args):
|
||||
return subprocess.run(['docker', *args], cwd=ROOT, check=True, capture_output=True, text=True).stdout.strip()
|
||||
|
||||
|
||||
def api_containers():
|
||||
return docker('compose', 'ps', '-q', 'api').split()
|
||||
|
||||
|
||||
def health(cid):
|
||||
return docker('inspect', '-f', '{{.State.Health.Status}}', cid)
|
||||
|
||||
|
||||
class Load:
|
||||
def __init__(self, args, actor, reader, chat, concurrency):
|
||||
self.args, self.actor, self.reader, self.chat = args, actor, reader, chat
|
||||
self.concurrency = concurrency
|
||||
self.events = [] # (t, kind, ok, instance)
|
||||
self.confirmed = [] # подтверждённые Message
|
||||
self.lock = threading.Lock()
|
||||
self.stop = threading.Event()
|
||||
|
||||
def record(self, kind, ok, instance=None):
|
||||
with self.lock:
|
||||
self.events.append((time.monotonic(), kind, ok, instance))
|
||||
|
||||
def worker(self, n):
|
||||
c = Client(self.args.base_url, self.args.ca_file, timeout=3)
|
||||
path = '/api/v1/chats/' + self.chat['id'] + '/messages?limit=20'
|
||||
key, text, i = None, None, 0
|
||||
while not self.stop.is_set():
|
||||
if key is None:
|
||||
key = uuid.uuid4().hex
|
||||
text = 'series-%d-%d-%s' % (n, i, key)
|
||||
i += 1
|
||||
try:
|
||||
r = c.message(self.actor, self.chat, text, key=key)
|
||||
self.record('write', True, r['headers'].get('X-Instance-Id'))
|
||||
with self.lock:
|
||||
self.confirmed.append(r['json'])
|
||||
key = None
|
||||
except Failure:
|
||||
self.record('write', False) # неопределённый результат: тот же ключ
|
||||
try:
|
||||
r = c.call('GET', path, actor=self.reader, schema='MessagePage')
|
||||
self.record('read', True, r['headers'].get('X-Instance-Id'))
|
||||
except Failure:
|
||||
self.record('read', False)
|
||||
|
||||
def __enter__(self):
|
||||
self.pool = ThreadPoolExecutor(max_workers=self.concurrency)
|
||||
self.futures = [self.pool.submit(self.worker, n) for n in range(self.concurrency)]
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
self.stop.set()
|
||||
for f in self.futures:
|
||||
f.result()
|
||||
self.pool.shutdown()
|
||||
|
||||
def window(self, a, b):
|
||||
with self.lock:
|
||||
ev = [e for e in self.events if a <= e[0] < b]
|
||||
ok = sum(1 for e in ev if e[2])
|
||||
return {'seconds': round(b - a, 2), 'ok': ok, 'errors': len(ev) - ok,
|
||||
'ok_rps': round(ok / (b - a), 1) if b > a else None}
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--concurrency', type=int, default=4)
|
||||
p.add_argument('--warmup', type=float, default=5)
|
||||
p.add_argument('--observe', type=float, default=15)
|
||||
p.add_argument('--output', default=None)
|
||||
args = arguments('Stop each API replica in turn under load; collect RPS/errors/recovery', configure)
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
replicas = api_containers()
|
||||
check(len(replicas) >= 2, 'need at least 2 api containers')
|
||||
results = []
|
||||
with Load(args, alice, bob, chat, args.concurrency) as load:
|
||||
time.sleep(args.warmup)
|
||||
for cid in replicas:
|
||||
target = cid[:12]
|
||||
before_start = time.monotonic() - args.warmup
|
||||
t0 = time.monotonic()
|
||||
docker('stop', '-t', '15', cid)
|
||||
stop_seconds = time.monotonic() - t0
|
||||
time.sleep(max(0.0, args.observe - stop_seconds))
|
||||
t_end = time.monotonic()
|
||||
with load.lock:
|
||||
after = [e for e in load.events if e[0] >= t0]
|
||||
errs = [e[0] for e in after if not e[2]]
|
||||
served = [e[0] for e in after if e[2] and e[3] == target]
|
||||
row = {
|
||||
'target_instance': target,
|
||||
'docker_stop_seconds': round(stop_seconds, 2),
|
||||
'before': load.window(before_start, t0),
|
||||
'during_stop_and_observe': load.window(t0, t_end),
|
||||
'errors_after_stop': len(errs),
|
||||
'recovery_seconds': round(max(errs) - t0, 2) if errs else 0.0,
|
||||
'target_last_served_after_stop_seconds': round(max(served) - t0, 2) if served else None,
|
||||
'other_instances_after': sorted({e[3] for e in after if e[2] and e[3] != target}),
|
||||
}
|
||||
# Восстановление реплики и её возврат в балансировку.
|
||||
r0 = time.monotonic()
|
||||
docker('start', cid)
|
||||
while health(cid) != 'healthy':
|
||||
check(time.monotonic() - r0 < 60, 'replica did not become healthy')
|
||||
time.sleep(0.5)
|
||||
healthy_at = time.monotonic() - r0
|
||||
while True:
|
||||
with load.lock:
|
||||
seen = any(e[0] > r0 and e[2] and e[3] == target for e in load.events)
|
||||
if seen:
|
||||
break
|
||||
check(time.monotonic() - r0 < 60, 'replica not seen behind LB after restore')
|
||||
time.sleep(0.2)
|
||||
row['restore_healthy_seconds'] = round(healthy_at, 2)
|
||||
row['restore_serving_via_lb_seconds'] = round(time.monotonic() - r0, 2)
|
||||
results.append(row)
|
||||
print(json.dumps(row, ensure_ascii=False))
|
||||
time.sleep(3)
|
||||
total = load.window(load.events[0][0], time.monotonic())
|
||||
confirmed = list(load.confirmed)
|
||||
|
||||
messages = history(c, bob, chat)
|
||||
ids = [m['id'] for m in messages]
|
||||
texts = [m['text'] for m in messages]
|
||||
check(len(ids) == len(set(ids)), 'duplicated message IDs')
|
||||
check(len(texts) == len(set(texts)), 'retry with same key created a duplicate')
|
||||
by_id = {m['id']: m for m in messages}
|
||||
lost = [m for m in confirmed if by_id.get(m['id']) != m]
|
||||
check(not lost, '%d confirmed messages lost/changed' % len(lost))
|
||||
summary = {'concurrency': args.concurrency, 'replicas': len(replicas), 'total': total,
|
||||
'confirmed_writes': len(confirmed), 'stored_messages': len(messages),
|
||||
'duplicates': 0, 'lost_confirmed': 0, 'per_replica': results}
|
||||
text = json.dumps(summary, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
Path(args.output).write_text(text + '\n', encoding='utf-8')
|
||||
print(text)
|
||||
print('PASS: every replica stopped and restored under load; no lost or duplicated messages.')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 900 B |
Binary file not shown.
|
After Width: | Height: | Size: 106 B |
@@ -0,0 +1,47 @@
|
||||
// Command genfixtures пишет маленькие синтетические изображения для собственных
|
||||
// тестов (student-tests/fixtures). Большие и вредоносные файлы тесты генерируют
|
||||
// сами в памяти — в Git они не хранятся.
|
||||
//
|
||||
// go run ./student-tests/genfixtures
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
func img(w, h int) *image.RGBA {
|
||||
m := image.NewRGBA(image.Rect(0, 0, w, h))
|
||||
for y := 0; y < h; y++ {
|
||||
for x := 0; x < w; x++ {
|
||||
m.Set(x, y, color.RGBA{uint8(x * 4), uint8(y * 4), 128, 255})
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func main() {
|
||||
dir := filepath.Join("student-tests", "fixtures")
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
var j bytes.Buffer
|
||||
if err := jpeg.Encode(&j, img(64, 48), &jpeg.Options{Quality: 85}); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
var p bytes.Buffer
|
||||
if err := png.Encode(&p, img(40, 30)); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
for name, data := range map[string][]byte{"small.jpg": j.Bytes(), "small.png": p.Bytes()} {
|
||||
if err := os.WriteFile(filepath.Join(dir, name), data, 0o644); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
Executable
+92
@@ -0,0 +1,92 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Конкурентный повтор POST сообщения с одним Idempotency-Key через LB (lab3).
|
||||
|
||||
Каждый раунд: N потоков (каждый со своим соединением) по барьеру одновременно
|
||||
отправляют одинаковый body с одинаковым ключом. Ожидаем: все ответы 201 с одним
|
||||
и тем же Message, запросы обслужены ≥2 репликами, в истории ровно одно сообщение.
|
||||
Затем тот же ключ с другим body — 409; тот же ключ в другом чате — новое сообщение.
|
||||
"""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import threading
|
||||
import uuid
|
||||
import sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests')) # публичный client.py
|
||||
from client import Client, Failure, arguments, check, run
|
||||
from resilience import history
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--rounds', type=int, default=10)
|
||||
p.add_argument('--parallel', type=int, default=16)
|
||||
p.add_argument('--output', default=None)
|
||||
args = arguments('Concurrent Idempotency-Key replay across replicas', configure)
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
other = c.call('POST', '/api/v1/chats', 201, actor=alice,
|
||||
body={'title': 'Второй чат', 'member_ids': [alice['id'], bob['id']]}, schema='Chat')['json']
|
||||
|
||||
rounds = []
|
||||
all_instances = set()
|
||||
for r in range(args.rounds):
|
||||
key = 'conc-' + uuid.uuid4().hex
|
||||
text = 'Конкурентный повтор %d %s' % (r, key)
|
||||
barrier = threading.Barrier(args.parallel)
|
||||
|
||||
def worker(_):
|
||||
local = Client(args.base_url, args.ca_file, timeout=10)
|
||||
barrier.wait()
|
||||
try:
|
||||
resp = local.message(alice, chat, text, key=key)
|
||||
return resp['status'], resp['json'], resp['headers'].get('X-Instance-Id')
|
||||
except Failure as exc:
|
||||
return 'fail', str(exc), None
|
||||
|
||||
with ThreadPoolExecutor(max_workers=args.parallel) as pool:
|
||||
results = list(pool.map(worker, range(args.parallel)))
|
||||
statuses = [s for s, _, _ in results]
|
||||
check(all(s == 201 for s in statuses), 'round %d: not all 201: %s' % (r, statuses))
|
||||
bodies = {json.dumps(b, sort_keys=True) for _, b, _ in results}
|
||||
check(len(bodies) == 1, 'round %d: replays returned different messages' % r)
|
||||
instances = {i for _, _, i in results}
|
||||
all_instances |= instances
|
||||
stored = [m for m in history(c, bob, chat) if m['text'] == text]
|
||||
check(len(stored) == 1, 'round %d: %d messages stored for one key' % (r, len(stored)))
|
||||
# Другой body с тем же ключом — 409, не новое сообщение.
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice,
|
||||
body={'text': text + ' (изменён)'}, headers={'Idempotency-Key': key})
|
||||
rounds.append({'round': r, 'requests': args.parallel, 'status_201': statuses.count(201),
|
||||
'distinct_messages': len(bodies), 'stored': len(stored), 'instances': len(instances)})
|
||||
|
||||
# Ключ уникален в пределах чата: тот же ключ в другом чате создаёт своё сообщение.
|
||||
key = 'scope-' + uuid.uuid4().hex
|
||||
a = c.message(alice, chat, 'scope', key=key)['json']
|
||||
b = c.message(alice, other, 'scope', key=key)['json']
|
||||
check(a['id'] != b['id'], 'key leaked across chats')
|
||||
# Другой пользователь с тем же ключом — тоже независим.
|
||||
d = c.message(bob, chat, 'scope', key=key)['json']
|
||||
check(d['id'] != a['id'], 'key leaked across users')
|
||||
# Без ключа и с неверным ключом — 400.
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages'
|
||||
c.call('POST', path, 400, actor=alice, body={'text': 'x'})
|
||||
c.call('POST', path, 400, actor=alice, body={'text': 'x'}, headers={'Idempotency-Key': 'bad key!'})
|
||||
c.call('POST', path, 400, actor=alice, body={'text': 'x'}, headers={'Idempotency-Key': 'k' * 129})
|
||||
# Повтор проверяет доступ: посторонний с тем же ключом получает 404.
|
||||
c.call('POST', path, 404, actor=eve, body={'text': 'scope'}, headers={'Idempotency-Key': key})
|
||||
|
||||
check(len(all_instances) >= 2, 'concurrent requests were served by fewer than 2 replicas')
|
||||
summary = {'rounds': args.rounds, 'parallel_per_round': args.parallel,
|
||||
'distinct_instances_seen': len(all_instances),
|
||||
'duplicates_found': sum(x['stored'] - 1 for x in rounds), 'per_round': rounds}
|
||||
text = json.dumps(summary, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
with open(args.output, 'w', encoding='utf-8') as f:
|
||||
f.write(text + '\n')
|
||||
print(text)
|
||||
print('PASS: concurrent Idempotency-Key replay produced exactly one message per key.')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Executable
+156
@@ -0,0 +1,156 @@
|
||||
"""Общие помощники собственных тестов lab4: изображения, docker compose, psql, mc.
|
||||
|
||||
Только stdlib. Секреты не печатаются: mc получает их внутри контейнера из /run/secrets.
|
||||
"""
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests')) # публичный client.py
|
||||
FIXTURES = Path(__file__).resolve().parent / 'fixtures'
|
||||
BUCKET = 'messenger-attachments'
|
||||
|
||||
|
||||
def chunk(typ, data):
|
||||
return struct.pack('>I', len(data)) + typ + data + struct.pack('>I', zlib.crc32(typ + data) & 0xffffffff)
|
||||
|
||||
|
||||
def png(w, h, raw=None, color_type=2, interlace=0, level=6):
|
||||
"""PNG из сырых строк; по умолчанию RGB 8 bit, все пиксели чёрные."""
|
||||
if raw is None:
|
||||
raw = (b'\x00' + b'\x00' * (w * 3)) * h
|
||||
ihdr = struct.pack('>IIBBBBB', w, h, 8, color_type, 0, 0, interlace)
|
||||
return (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', ihdr) + chunk(b'IDAT', zlib.compress(raw, level))
|
||||
+ chunk(b'IEND', b''))
|
||||
|
||||
|
||||
def noise_png(target_bytes):
|
||||
"""Почти несжимаемый PNG размером около target_bytes (шум из детерминированного PRNG)."""
|
||||
w = 1024
|
||||
h = max(1, target_bytes // (w * 3 + 1))
|
||||
seed = 0x2545F491
|
||||
rows = bytearray()
|
||||
for _ in range(h):
|
||||
rows.append(0)
|
||||
row = bytearray(w * 3)
|
||||
for i in range(0, w * 3, 4):
|
||||
seed = (seed * 1103515245 + 12345) & 0xffffffff
|
||||
row[i:i + 4] = seed.to_bytes(4, 'little')[:len(row) - i]
|
||||
rows += row
|
||||
return png(w, h, bytes(rows), level=1)
|
||||
|
||||
|
||||
def bomb_png(w=100_000, h=100_000):
|
||||
"""Маленький файл, огромные размеры в IHDR."""
|
||||
return png(w, h, raw=b'\x00')
|
||||
|
||||
|
||||
def raw_post(base_url, path, headers, body_iter, read_timeout=30):
|
||||
"""POST на сыром сокете: тело отправляется в фоне, ответ читается параллельно.
|
||||
|
||||
Нужен, когда сервер отвечает (413) до чтения тела и закрывает соединение:
|
||||
urllib в этом случае падает на отправке, не увидев ответа.
|
||||
Возвращает (status, body_bytes) или (None, b'') если ответа не было.
|
||||
"""
|
||||
import socket
|
||||
import threading
|
||||
from urllib.parse import urlsplit
|
||||
u = urlsplit(base_url)
|
||||
s = socket.create_connection((u.hostname, u.port or 80), timeout=read_timeout)
|
||||
head = 'POST %s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n' % (path, u.netloc)
|
||||
head += ''.join('%s: %s\r\n' % kv for kv in headers.items()) + '\r\n'
|
||||
s.sendall(head.encode())
|
||||
|
||||
def send():
|
||||
try:
|
||||
for part in body_iter:
|
||||
s.sendall(part)
|
||||
except OSError:
|
||||
pass # сервер уже ответил и закрыл соединение — ожидаемо
|
||||
t = threading.Thread(target=send, daemon=True)
|
||||
t.start()
|
||||
data = b''
|
||||
try:
|
||||
while True:
|
||||
b = s.recv(65536)
|
||||
if not b:
|
||||
break
|
||||
data += b
|
||||
if b'\r\n\r\n' in data and len(data) > 4096:
|
||||
break
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
s.close()
|
||||
if not data.startswith(b'HTTP/1.'):
|
||||
return None, b''
|
||||
status = int(data.split(b' ', 2)[1])
|
||||
return status, data.split(b'\r\n\r\n', 1)[-1]
|
||||
|
||||
|
||||
def fixture(name):
|
||||
return (FIXTURES / name).read_bytes()
|
||||
|
||||
|
||||
def sh(*args, check=True, timeout=300, input=None, env=None):
|
||||
full_env = None
|
||||
if env:
|
||||
import os
|
||||
full_env = dict(os.environ, **env)
|
||||
r = subprocess.run(list(args), cwd=ROOT, capture_output=True, text=True, timeout=timeout, input=input, env=full_env)
|
||||
if check and r.returncode != 0:
|
||||
raise RuntimeError('%s failed (%d): %s' % (' '.join(args[:4]), r.returncode, (r.stderr or r.stdout)[-800:]))
|
||||
return r
|
||||
|
||||
|
||||
def compose(*args, **kw):
|
||||
return sh('docker', 'compose', *args, **kw)
|
||||
|
||||
|
||||
def psql(sql):
|
||||
"""Одно значение/таблица из PostgreSQL стенда (через docker compose exec)."""
|
||||
return compose('exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger',
|
||||
'-v', 'ON_ERROR_STOP=1', '-tAc', sql).stdout.strip()
|
||||
|
||||
|
||||
def mc(script, check=True, as_user='root'):
|
||||
"""Скрипт mc в одноразовом контейнере s3-init. Алиас `s3` — root или API-пользователь."""
|
||||
creds = {'root': ('s3_root_user', 's3_root_password'),
|
||||
'api': ('s3_access_key_id', 's3_secret_access_key')}[as_user]
|
||||
prelude = ('mc alias set s3 http://s3:9000 "$(cat /run/secrets/%s)" "$(cat /run/secrets/%s)" >/dev/null; '
|
||||
% creds)
|
||||
return compose('run', '--rm', '--no-deps', '-T', '--entrypoint', 'sh', 's3-init', '-c', prelude + script,
|
||||
check=check)
|
||||
|
||||
|
||||
def api_container(instance_id):
|
||||
for cid in compose('ps', '-q', 'api').stdout.split():
|
||||
if cid.startswith(instance_id):
|
||||
return cid
|
||||
raise RuntimeError('no api container for ' + instance_id)
|
||||
|
||||
|
||||
def object_key(attachment_id):
|
||||
return psql("SELECT object_key FROM attachments WHERE id = '%s'" % attachment_id)
|
||||
|
||||
|
||||
def wait_status(c, actor, att_id, statuses=('ready',), timeout=90):
|
||||
"""Опрос GET метаданных до одного из статусов; возвращает метаданные."""
|
||||
import time
|
||||
from client import Failure
|
||||
end = time.time() + timeout
|
||||
last = None
|
||||
while time.time() < end:
|
||||
last = c.call('GET', '/api/v1/attachments/' + att_id, actor=actor, schema='Attachment')['json']
|
||||
if last['status'] in statuses:
|
||||
return last
|
||||
time.sleep(0.5)
|
||||
raise Failure('attachment %s did not reach %s, last=%s' % (att_id, statuses, last and last['status']))
|
||||
|
||||
|
||||
def bucket_count(prefix):
|
||||
"""Число объектов под префиксом bucket (s/, o/, v/, a/ + chat)."""
|
||||
return int(mc('mc ls --recursive s3/%s/%s 2>/dev/null | wc -l' % (BUCKET, prefix)).stdout.strip() or 0)
|
||||
Executable
+58
@@ -0,0 +1,58 @@
|
||||
import base64
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
|
||||
BASE = (sys.argv[sys.argv.index("--base-url") + 1] if "--base-url" in sys.argv else "http://localhost:8080").rstrip("/")
|
||||
PASSWORD = "Example-only-not-a-real-secret-123"
|
||||
|
||||
def post(path, body, headers=None):
|
||||
req = urllib.request.Request(BASE + path, method="POST",
|
||||
data=json.dumps(body).encode(),
|
||||
headers={"Content-Type": "application/json", **(headers or {})})
|
||||
try:
|
||||
with urllib.request.urlopen(req) as r:
|
||||
return r.status, json.loads(r.read())
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, json.loads(e.read())
|
||||
|
||||
def get(path, headers=None):
|
||||
req = urllib.request.Request(BASE + path, headers=headers or {})
|
||||
try:
|
||||
with urllib.request.urlopen(req) as r:
|
||||
return r.status, json.loads(r.read())
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, json.loads(e.read())
|
||||
|
||||
def main():
|
||||
failures = []
|
||||
|
||||
# 1. Неверный JSON → 400
|
||||
status, _ = post("/api/v1/users", "not-json")
|
||||
if status != 400:
|
||||
failures.append(f"invalid JSON: expected 400, got {status}")
|
||||
|
||||
# 2. Невалидный username → 400
|
||||
status, _ = post("/api/v1/users", {"username": "AB", "display_name": "Test", "password": PASSWORD})
|
||||
if status != 400:
|
||||
failures.append(f"invalid username: expected 400, got {status}")
|
||||
|
||||
# 3. Отсутствие Bearer на /users/me → 401
|
||||
status, _ = get("/api/v1/users/me")
|
||||
if status != 401:
|
||||
failures.append(f"no auth: expected 401, got {status}")
|
||||
|
||||
# 4. X-User-Id не даёт доступ → 401
|
||||
status, _ = get("/api/v1/users/me", {"X-User-Id": "00000000-0000-0000-0000-000000000000"})
|
||||
if status != 401:
|
||||
failures.append(f"X-User-Id bypass: expected 401, got {status}")
|
||||
|
||||
if failures:
|
||||
for f in failures:
|
||||
print(f"FAIL: {f}")
|
||||
sys.exit(1)
|
||||
print("PASS: negative checks")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+397
@@ -0,0 +1,397 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Сценарии асинхронной обработки lab5 на Docker-стенде.
|
||||
|
||||
demo уровень 3: worker остановлен → upload 202 → сообщение с вложением →
|
||||
content 409, чат работает → рестарт API и broker (volume) → worker → ready
|
||||
outbox-gap relay остановлен (разрыв COMMIT↔publish) → upload → relay → ready;
|
||||
relay падает после confirm до отметки outbox → повторная публикация → один результат
|
||||
crash-effect worker падает после записи объектов до COMMIT → lease истекает → повтор → тот же результат
|
||||
crash-commit worker падает после COMMIT до ack → повторная доставка → no-op
|
||||
broker-restart принятая задача в quorum-очереди переживает рестарт RabbitMQ с volume
|
||||
transient S3 недоступен во время обработки → retry с backoff и jitter → ready
|
||||
failed-replay постоянная ошибка → failed (error_code), реестр, явный replay, повтор успешной запрещён;
|
||||
невалидное сообщение → DLQ
|
||||
limits изображение 36 Мпикс и параллельная обработка: пик памяти worker, время
|
||||
versions трек 5: reprocess v2, устаревший дубль v1 и повтор v2 после публикации не меняют результат
|
||||
|
||||
Каждый сценарий печатает JSON-итог и PASS/FAIL; ID вложений и задания — без токенов.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import struct
|
||||
import time
|
||||
import zlib
|
||||
from labutil import (BUCKET, bucket_count, compose, fixture, mc, psql, sh, wait_status)
|
||||
from client import Client, Failure, arguments, check, run
|
||||
from image_probe import jpeg_size
|
||||
|
||||
SAMPLE = None
|
||||
|
||||
|
||||
def sample():
|
||||
global SAMPLE
|
||||
if SAMPLE is None:
|
||||
from pathlib import Path
|
||||
SAMPLE = (Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png').read_bytes()
|
||||
return SAMPLE
|
||||
|
||||
|
||||
def upload(c, actor, chat, data, name='p.png', ctype='image/png'):
|
||||
r = c.call('POST', '/api/v1/chats/%s/attachments?filename=%s' % (chat['id'], name), 202, actor=actor,
|
||||
raw=data, headers={'Content-Type': ctype}, schema='Attachment')
|
||||
check(r['json']['status'] == 'queued', 'upload snapshot must be queued')
|
||||
return r['json']
|
||||
|
||||
|
||||
def wait_ready_api(c, timeout=90):
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
try:
|
||||
c.call('GET', '/health/ready')
|
||||
return
|
||||
except Failure:
|
||||
time.sleep(1)
|
||||
raise Failure('API not ready')
|
||||
|
||||
|
||||
def job_of(att_id, version=1):
|
||||
row = psql("SELECT job_id || '|' || state || '|' || attempt FROM jobs WHERE attachment_id = '%s' AND pipeline_version = %d"
|
||||
% (att_id, version))
|
||||
jid, state, attempt = row.split('|')
|
||||
return jid, state, int(attempt)
|
||||
|
||||
|
||||
def events(job_id):
|
||||
return psql("SELECT string_agg(event, ',' ORDER BY id) FROM job_events WHERE job_id = '%s'" % job_id)
|
||||
|
||||
|
||||
def invariants(att_id, chat_id):
|
||||
"""I1 ≤1 варианта на (версия, имя); I2 ready ⇒ 3 варианта опубликованной версии с объектами;
|
||||
I3 объектов v/ ровно 3 на каждую версию с вариантами (повторы не размножают)."""
|
||||
dup = psql("SELECT count(*) FROM (SELECT 1 FROM attachment_variants WHERE attachment_id='%s' "
|
||||
"GROUP BY pipeline_version, name HAVING count(*) > 1) d" % att_id)
|
||||
check(dup == '0', 'I1 duplicated variants')
|
||||
st, ver = psql("SELECT status || '|' || pipeline_version FROM attachments WHERE id='%s'" % att_id).split('|')
|
||||
out = {'status': st, 'published_version': int(ver)}
|
||||
if st == 'ready':
|
||||
n = psql("SELECT count(*) FROM attachment_variants WHERE attachment_id='%s' AND pipeline_version=%s" % (att_id, ver))
|
||||
check(n == '3', 'I2 ready with %s variants' % n)
|
||||
versions = psql("SELECT string_agg(DISTINCT pipeline_version::text, ',') FROM attachment_variants WHERE attachment_id='%s'" % att_id)
|
||||
for v in versions.split(','):
|
||||
objs = bucket_count('v/%s/%s/p%s/' % (chat_id, att_id, v))
|
||||
check(objs == 3, 'I3 version %s has %d objects' % (v, objs))
|
||||
out['objects_per_version'] = {v: 3 for v in versions.split(',')}
|
||||
return out
|
||||
|
||||
|
||||
def check_variants(c, actor, meta, original):
|
||||
vs = {v['name']: v for v in meta['variants']}
|
||||
check(set(vs) == {'thumbnail', 'crop', 'optimized'}, 'variants: %s' % sorted(vs))
|
||||
th = c.call('GET', '/api/v1/attachments/%s/content?variant=thumbnail' % meta['id'], actor=actor)
|
||||
check(th['headers'].get_content_type() == 'image/jpeg', 'thumbnail type')
|
||||
check(hashlib.sha256(th['bytes']).hexdigest() == vs['thumbnail']['sha256'], 'thumbnail sha')
|
||||
tw, thh = jpeg_size(th['bytes'])
|
||||
cr = c.call('GET', '/api/v1/attachments/%s/content?variant=crop' % meta['id'], actor=actor)
|
||||
check(jpeg_size(cr['bytes']) == (128, 128), 'crop size')
|
||||
op = c.call('GET', '/api/v1/attachments/%s/content?variant=optimized' % meta['id'], actor=actor)
|
||||
check(op['bytes'][:4] == b'RIFF' and op['bytes'][8:12] == b'WEBP', 'optimized is not WebP')
|
||||
check(hashlib.sha256(op['bytes']).hexdigest() == vs['optimized']['sha256'], 'optimized sha')
|
||||
orig = c.call('GET', '/api/v1/attachments/%s/content' % meta['id'], actor=actor)
|
||||
check(orig['bytes'] == original, 'original changed')
|
||||
return {'thumbnail': [tw, thh], 'crop': [128, 128],
|
||||
'optimized': [vs['optimized']['width'], vs['optimized']['height']],
|
||||
'optimized_bytes': vs['optimized']['size_bytes'], 'original_bytes': len(original)}
|
||||
|
||||
|
||||
def recreate(service, **env):
|
||||
"""Пересоздать сервис с переменными окружения (точки сбоя, таймауты)."""
|
||||
compose('up', '-d', '--no-deps', '--wait', service, env=env, timeout=180)
|
||||
|
||||
|
||||
# ---------------- уровень 3 ----------------
|
||||
|
||||
def scenario_demo(c):
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
timeline = []
|
||||
compose('stop', 'worker')
|
||||
timeline.append('worker stopped')
|
||||
att = upload(c, alice, chat, sample(), name='demo.png')
|
||||
timeline.append('upload 202 queued id=%s' % att['id'])
|
||||
msg = c.message(alice, chat, 'с вложением в очереди', attachments=[att['id']])['json']
|
||||
check(msg['attachment_ids'] == [att['id']], 'message attachment')
|
||||
timeline.append('message 201 with queued attachment')
|
||||
c.call('GET', '/api/v1/attachments/%s/content' % att['id'], 409, actor=bob)
|
||||
c.message(bob, chat, 'чат работает без worker')
|
||||
timeline.append('content 409, other messages OK')
|
||||
time.sleep(2)
|
||||
published = psql("SELECT count(*) FROM outbox o JOIN jobs j USING (job_id) WHERE j.attachment_id='%s' AND o.published_at IS NOT NULL" % att['id'])
|
||||
compose('restart', 'api')
|
||||
compose('restart', 'rabbitmq')
|
||||
sh('sh', 'scripts/restore.sh')
|
||||
wait_ready_api(c)
|
||||
timeline.append('api and rabbitmq restarted (volumes kept), outbox published=%s' % published)
|
||||
queued = compose('exec', '-T', 'rabbitmq', 'rabbitmqctl', '-q', 'list_queues', 'name', 'messages').stdout
|
||||
timeline.append('rabbitmq queues after restart: ' + ' '.join(queued.split()))
|
||||
t0 = time.time()
|
||||
compose('start', 'worker')
|
||||
meta = wait_status(c, bob, att['id'], ('ready',), timeout=90)
|
||||
timeline.append('worker started → ready in %.1f s' % (time.time() - t0))
|
||||
res = check_variants(c, bob, meta, sample())
|
||||
check(res['thumbnail'] == [256, 160], 'fixture thumbnail must be 256x160')
|
||||
jid, state, attempt = job_of(att['id'])
|
||||
return {'attachment_id': att['id'], 'job_id': jid, 'job_state': state, 'attempt': attempt,
|
||||
'timeline': timeline, 'variants': res, 'invariants': invariants(att['id'], chat['id']),
|
||||
'events': events(jid)}
|
||||
|
||||
|
||||
# ---------------- уровень 4 ----------------
|
||||
|
||||
def scenario_outbox_gap(c):
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
compose('stop', 'relay')
|
||||
att = upload(c, alice, chat, sample(), name='gap.png')
|
||||
time.sleep(3)
|
||||
jid, state, _ = job_of(att['id'])
|
||||
unpublished = psql("SELECT count(*) FROM outbox WHERE job_id='%s' AND published_at IS NULL" % jid)
|
||||
check(state == 'queued' and unpublished == '1', 'job must wait in outbox: %s %s' % (state, unpublished))
|
||||
compose('restart', 'api') # «падение» после COMMIT, publish ещё не было
|
||||
wait_ready_api(c)
|
||||
compose('start', 'relay')
|
||||
meta = wait_status(c, bob, att['id'], ('ready',))
|
||||
part1 = {'attachment_id': att['id'], 'unpublished_while_relay_down': 1, 'then': meta['status']}
|
||||
|
||||
# Relay падает ПОСЛЕ publisher confirm, ДО отметки published_at → повторная публикация.
|
||||
recreate('relay', RELAY_FAULT_POINTS='relay.after_publish')
|
||||
att2 = upload(c, alice, chat, sample(), name='dup.png')
|
||||
meta2 = wait_status(c, bob, att2['id'], ('ready',), timeout=120)
|
||||
jid2, _, attempt2 = job_of(att2['id'])
|
||||
attempts = psql("SELECT publish_attempts FROM outbox WHERE job_id='%s'" % jid2)
|
||||
restarts = sh('docker', 'inspect', '-f', '{{.RestartCount}}', compose('ps', '-q', 'relay').stdout.strip()).stdout.strip()
|
||||
recreate('relay')
|
||||
worker_log = compose('logs', '--no-color', 'worker').stdout
|
||||
dup_seen = worker_log.count(jid2) >= 2
|
||||
check(attempt2 == 1, 'duplicate publish must not create a second attempt')
|
||||
part2 = {'attachment_id': att2['id'], 'relay_restarts': int(restarts), 'outbox_publish_attempts': int(attempts or 0),
|
||||
'worker_saw_message_twice': dup_seen, 'job_attempt': attempt2, 'invariants': invariants(att2['id'], chat['id'])}
|
||||
return {'relay_down_then_up': part1, 'relay_crash_after_confirm': part2, 'events': events(jid2)}
|
||||
|
||||
|
||||
def scenario_crash_effect(c):
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
recreate('worker', WORKER_FAULT_POINTS='worker.after_side_effect', JOB_TIMEOUT_SECONDS='15')
|
||||
t0 = time.time()
|
||||
att = upload(c, alice, chat, sample(), name='crash.png')
|
||||
meta = wait_status(c, bob, att['id'], ('ready',), timeout=120)
|
||||
took = time.time() - t0
|
||||
jid, state, attempt = job_of(att['id'])
|
||||
cid = compose('ps', '-q', 'worker').stdout.split()[0]
|
||||
restarts = sh('docker', 'inspect', '-f', '{{.RestartCount}}', cid).stdout.strip()
|
||||
recreate('worker')
|
||||
check(attempt == 2, 'expected recovery on attempt 2, got %d' % attempt)
|
||||
ev = events(jid)
|
||||
check('lease_expired_requeued' in ev, 'lease expiry recovery missing: ' + ev)
|
||||
return {'attachment_id': att['id'], 'job_id': jid, 'worker_restarts': int(restarts), 'attempt': attempt,
|
||||
'seconds_to_ready': round(took, 1), 'events': ev, 'invariants': invariants(att['id'], chat['id']),
|
||||
'variants': check_variants(c, bob, meta, sample())}
|
||||
|
||||
|
||||
def scenario_crash_commit(c):
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
recreate('worker', WORKER_FAULT_POINTS='worker.after_commit')
|
||||
att = upload(c, alice, chat, sample(), name='commit.png')
|
||||
wait_status(c, bob, att['id'], ('ready',))
|
||||
time.sleep(8) # контейнер перезапускается, broker доставляет неподтверждённое сообщение повторно
|
||||
jid, state, attempt = job_of(att['id'])
|
||||
cid = compose('ps', '-q', 'worker').stdout.split()[0]
|
||||
restarts = sh('docker', 'inspect', '-f', '{{.RestartCount}}', cid).stdout.strip()
|
||||
log = compose('logs', '--no-color', 'worker').stdout
|
||||
noop = any(jid in l and 'duplicate delivery of finished job' in l for l in log.splitlines())
|
||||
recreate('worker')
|
||||
check(attempt == 1 and state == 'done', 'redelivery after commit must be a no-op: %s %d' % (state, attempt))
|
||||
return {'attachment_id': att['id'], 'job_id': jid, 'worker_restarts': int(restarts), 'attempt': attempt,
|
||||
'redelivery_acked_as_noop': noop, 'invariants': invariants(att['id'], chat['id'])}
|
||||
|
||||
|
||||
def scenario_broker_restart(c):
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
compose('stop', 'worker')
|
||||
att = upload(c, alice, chat, sample(), name='broker.png')
|
||||
jid, _, _ = job_of(att['id'])
|
||||
for _ in range(30):
|
||||
if psql("SELECT count(*) FROM outbox WHERE job_id='%s' AND published_at IS NOT NULL" % jid) == '1':
|
||||
break
|
||||
time.sleep(0.5)
|
||||
before = compose('exec', '-T', 'rabbitmq', 'rabbitmqctl', '-q', 'list_queues', 'name', 'messages').stdout
|
||||
compose('restart', 'rabbitmq')
|
||||
for _ in range(60):
|
||||
st = sh('docker', 'inspect', '-f', '{{.State.Health.Status}}', compose('ps', '-q', 'rabbitmq').stdout.strip()).stdout.strip()
|
||||
if st == 'healthy':
|
||||
break
|
||||
time.sleep(1)
|
||||
after = compose('exec', '-T', 'rabbitmq', 'rabbitmqctl', '-q', 'list_queues', 'name', 'messages').stdout
|
||||
compose('start', 'worker')
|
||||
wait_status(c, bob, att['id'], ('ready',))
|
||||
q = lambda out: {l.split()[0]: int(l.split()[1]) for l in out.splitlines() if len(l.split()) == 2}
|
||||
check(q(after).get('attachment.process', 0) >= 1, 'message lost on broker restart: %s' % after)
|
||||
return {'attachment_id': att['id'], 'queue_before_restart': q(before), 'queue_after_restart': q(after),
|
||||
'invariants': invariants(att['id'], chat['id'])}
|
||||
|
||||
|
||||
def scenario_transient(c):
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
compose('stop', 'worker')
|
||||
att = upload(c, alice, chat, sample(), name='retry.png')
|
||||
jid, _, _ = job_of(att['id'])
|
||||
compose('stop', 's3')
|
||||
compose('start', 'worker')
|
||||
seen = []
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < 25:
|
||||
ev = events(jid) or ''
|
||||
seen = ev.split(',')
|
||||
if seen.count('retry_scheduled') >= 2:
|
||||
break
|
||||
time.sleep(1)
|
||||
compose('start', 's3')
|
||||
meta = wait_status(c, bob, att['id'], ('ready',), timeout=150)
|
||||
_, state, attempt = job_of(att['id'])
|
||||
details = psql("SELECT string_agg(detail, ' | ' ORDER BY id) FROM job_events WHERE job_id='%s' AND event='retry_scheduled'" % jid)
|
||||
check(attempt >= 2 and state == 'done', 'expected retries then success')
|
||||
return {'attachment_id': att['id'], 'attempts': attempt, 'final_status': meta['status'],
|
||||
'retry_details': details, 'events': events(jid), 'invariants': invariants(att['id'], chat['id'])}
|
||||
|
||||
|
||||
def scenario_failed_replay(c):
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
compose('stop', 'worker')
|
||||
att = upload(c, alice, chat, sample(), name='bad.png')
|
||||
key = psql("SELECT staging_key FROM attachments WHERE id='%s'" % att['id'])
|
||||
mc('printf garbage > /tmp/g && mc cp -q /tmp/g s3/%s/%s >/dev/null' % (BUCKET, key)) # порча staging
|
||||
compose('start', 'worker')
|
||||
meta = wait_status(c, bob, att['id'], ('failed',))
|
||||
check(meta['error_code'] == 'checksum_mismatch', 'error_code %s' % meta['error_code'])
|
||||
c.call('GET', '/api/v1/attachments/%s/content' % att['id'], 409, actor=bob)
|
||||
c.call('POST', '/api/v1/chats/%s/messages' % chat['id'], 409, actor=alice,
|
||||
body={'text': '', 'attachment_ids': [att['id']]}, headers={'Idempotency-Key': 'f-' + att['id']})
|
||||
registry = compose('run', '--rm', '--no-deps', '-T', '--entrypoint', '/app/pipeline', 'relay', 'failed').stdout
|
||||
check(att['id'] in registry, 'failed registry must list the job')
|
||||
# Восстанавливаем исходник и делаем явный replay.
|
||||
import subprocess
|
||||
p = subprocess.run(['docker', 'compose', 'run', '--rm', '--no-deps', '-T', '--entrypoint', 'sh', 's3-init', '-c',
|
||||
'mc alias set s3 http://s3:9000 "$(cat /run/secrets/s3_root_user)" "$(cat /run/secrets/s3_root_password)" >/dev/null; '
|
||||
'cat > /tmp/o && mc cp -q /tmp/o s3/%s/%s >/dev/null' % (BUCKET, key)], input=sample(), capture_output=True)
|
||||
check(p.returncode == 0, 'restore staging failed')
|
||||
rp = compose('run', '--rm', '--no-deps', '-T', '--entrypoint', '/app/pipeline', 'relay', 'replay', att['id'],
|
||||
'--actor', 'lab5-test', check=False)
|
||||
check(rp.returncode == 0, 'replay failed: ' + rp.stdout + rp.stderr[-200:])
|
||||
ready = wait_status(c, bob, att['id'], ('ready',))
|
||||
again = compose('run', '--rm', '--no-deps', '-T', '--entrypoint', '/app/pipeline', 'relay', 'replay', att['id'],
|
||||
'--actor', 'lab5-test', check=False)
|
||||
check(again.returncode != 0, 'replay of a finished job must be refused')
|
||||
jid, _, attempt = job_of(att['id'])
|
||||
# Невалидное сообщение → DLQ (не крутится вечно, не теряется молча).
|
||||
psql("INSERT INTO outbox (job_id, payload) VALUES ('%s', '{\"schema_version\": 99}'::jsonb)" % jid)
|
||||
dead = 0
|
||||
for _ in range(30):
|
||||
out = compose('exec', '-T', 'rabbitmq', 'rabbitmqctl', '-q', 'list_queues', 'name', 'messages').stdout
|
||||
dead = {l.split()[0]: int(l.split()[1]) for l in out.splitlines() if len(l.split()) == 2}.get('attachment.dead', 0)
|
||||
if dead >= 1:
|
||||
break
|
||||
time.sleep(1)
|
||||
check(dead >= 1, 'invalid message did not reach DLQ')
|
||||
return {'attachment_id': att['id'], 'failed_error_code': meta['error_code'], 'content_while_failed': 409,
|
||||
'attach_failed_to_message': 409, 'registry_listed': True, 'replay': json.loads(rp.stdout.strip().splitlines()[-1]),
|
||||
'replay_after_success': json.loads(again.stdout.strip().splitlines()[-1]),
|
||||
'final_status': ready['status'], 'events': events(jid), 'dlq_messages': dead,
|
||||
'invariants': invariants(att['id'], chat['id'])}
|
||||
|
||||
|
||||
def solid_png(w, h, rgb=(40, 120, 200)):
|
||||
row = b'\x00' + bytes(rgb) * w
|
||||
raw = row * h
|
||||
ihdr = struct.pack('>IIBBBBB', w, h, 8, 2, 0, 0, 0)
|
||||
ch = lambda t, d: struct.pack('>I', len(d)) + t + d + struct.pack('>I', zlib.crc32(t + d) & 0xffffffff)
|
||||
return b'\x89PNG\r\n\x1a\n' + ch(b'IHDR', ihdr) + ch(b'IDAT', zlib.compress(raw, 9)) + ch(b'IEND', b'')
|
||||
|
||||
|
||||
def scenario_limits(c):
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
big = solid_png(6000, 6000) # 36 Мпикс, сжатый файл маленький
|
||||
check(len(big) < 10 * 1024 * 1024, 'test image too big')
|
||||
compose('restart', 'worker') # новый cgroup → memory.peak с нуля
|
||||
time.sleep(3)
|
||||
cid = compose('ps', '-q', 'worker').stdout.split()[0]
|
||||
t0 = time.time()
|
||||
ids = [upload(c, alice, chat, big, name='big%d.png' % i)['id'] for i in range(3)]
|
||||
done = [wait_status(c, bob, i, ('ready', 'failed'), timeout=240) for i in ids]
|
||||
took = time.time() - t0
|
||||
peak = sh('docker', 'exec', cid, 'cat', '/sys/fs/cgroup/memory.peak', check=False).stdout.strip()
|
||||
limit = sh('docker', 'exec', cid, 'cat', '/sys/fs/cgroup/memory.max', check=False).stdout.strip()
|
||||
check(all(d['status'] == 'ready' for d in done), 'big images failed: %s' % [d['error_code'] for d in done])
|
||||
th = {v['name']: (v['width'], v['height']) for v in done[0]['variants']}
|
||||
check(th['thumbnail'] == (256, 256) and th['optimized'] == (1280, 1280), 'variant sizes %s' % th)
|
||||
return {'image': '6000x6000 PNG (%d bytes)' % len(big), 'parallel_uploads': 3, 'seconds_all_ready': round(took, 1),
|
||||
'worker_memory_peak_mib': round(int(peak) / 1048576, 1) if peak.isdigit() else peak,
|
||||
'worker_memory_limit_mib': round(int(limit) / 1048576, 1) if limit.isdigit() else limit,
|
||||
'pixel_budget': 60_000_000, 'decoded_rgba_per_image_mib': round(6000 * 6000 * 4 / 1048576, 1),
|
||||
'variant_sizes': th}
|
||||
|
||||
|
||||
# ---------------- трек 5: версии и устаревшие задания ----------------
|
||||
|
||||
def scenario_versions(c):
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
att = upload(c, alice, chat, sample(), name='ver.png')
|
||||
v1 = wait_status(c, bob, att['id'], ('ready',))
|
||||
th1 = {v['name']: v['sha256'] for v in v1['variants']}['thumbnail']
|
||||
jid1, _, _ = job_of(att['id'], 1)
|
||||
rp = compose('run', '--rm', '--no-deps', '-T', '--entrypoint', '/app/pipeline', 'relay', 'reprocess', att['id'], '--version', '2')
|
||||
jid2 = json.loads(rp.stdout.strip().splitlines()[-1])['job_id']
|
||||
for _ in range(120):
|
||||
if psql("SELECT pipeline_version FROM attachments WHERE id='%s'" % att['id']) == '2':
|
||||
break
|
||||
time.sleep(0.5)
|
||||
v2 = c.call('GET', '/api/v1/attachments/' + att['id'], actor=bob, schema='Attachment')['json']
|
||||
th2 = {v['name']: v['sha256'] for v in v2['variants']}['thumbnail']
|
||||
check(v2['status'] == 'ready' and th2 != th1, 'v2 must be published with a different thumbnail')
|
||||
# Устаревший дубль v1 и повтор v2 после публикации v2.
|
||||
psql("INSERT INTO outbox (job_id, payload) SELECT job_id, payload FROM outbox WHERE job_id='%s' ORDER BY id LIMIT 1" % jid1)
|
||||
psql("INSERT INTO outbox (job_id, payload) SELECT job_id, payload FROM outbox WHERE job_id='%s' ORDER BY id LIMIT 1" % jid2)
|
||||
time.sleep(6)
|
||||
after = c.call('GET', '/api/v1/attachments/' + att['id'], actor=bob, schema='Attachment')['json']
|
||||
th_after = {v['name']: v['sha256'] for v in after['variants']}['thumbnail']
|
||||
got = c.call('GET', '/api/v1/attachments/%s/content?variant=thumbnail' % att['id'], actor=bob)['bytes']
|
||||
check(th_after == th2 and hashlib.sha256(got).hexdigest() == th2, 'stale v1 overwrote v2')
|
||||
check(psql("SELECT pipeline_version FROM attachments WHERE id='%s'" % att['id']) == '2', 'version went back')
|
||||
_, s1, a1 = job_of(att['id'], 1)
|
||||
_, s2, a2 = job_of(att['id'], 2)
|
||||
check(a1 == 1 and a2 == 1, 'duplicates must not start new attempts')
|
||||
return {'attachment_id': att['id'], 'v1_thumbnail_sha': th1, 'v2_thumbnail_sha': th2,
|
||||
'after_stale_v1_and_dup_v2': th_after, 'published_version': 2,
|
||||
'jobs': {'v1': {'state': s1, 'attempt': a1, 'events': events(jid1)},
|
||||
'v2': {'state': s2, 'attempt': a2, 'events': events(jid2)}},
|
||||
'invariants': invariants(att['id'], chat['id'])}
|
||||
|
||||
|
||||
SCENARIOS = {'demo': scenario_demo, 'outbox-gap': scenario_outbox_gap, 'crash-effect': scenario_crash_effect,
|
||||
'crash-commit': scenario_crash_commit, 'broker-restart': scenario_broker_restart,
|
||||
'transient': scenario_transient, 'failed-replay': scenario_failed_replay,
|
||||
'limits': scenario_limits, 'versions': scenario_versions}
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('scenario', choices=sorted(SCENARIOS))
|
||||
p.add_argument('--output', default=None)
|
||||
args = arguments('Lab5 pipeline scenarios on the Docker stand', configure)
|
||||
c = Client(args.base_url, args.ca_file, timeout=60)
|
||||
result = SCENARIOS[args.scenario](c)
|
||||
text = json.dumps({'scenario': args.scenario, 'result': result}, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
open(args.output, 'w', encoding='utf-8').write(text + '\n')
|
||||
print(text)
|
||||
print('PASS: ' + args.scenario)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Executable
+89
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Трек 2: стоимость обхода reconciler в зависимости от числа вложений.
|
||||
|
||||
Для каждого N: досеиваем согласованные пары (строка в PostgreSQL + объект в S3)
|
||||
под отдельным префиксом чата-стенда, затем 3 раза запускаем dry-run и берём
|
||||
медиану duration_ms. Фиксируем число строк/объектов, LIST-страниц, Stat-вызовов
|
||||
и heap процесса reconciler. Дополнительно — прогон с 1% внедрённых расхождений.
|
||||
|
||||
Объекты — 1 KiB случайных байт (размер не влияет на обход: LIST возвращает
|
||||
метаданные, тела объектов не читаются).
|
||||
"""
|
||||
import json
|
||||
import statistics
|
||||
import time
|
||||
import uuid
|
||||
from labutil import BUCKET, compose, mc, psql
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def reconcile_dry():
|
||||
for _ in range(10):
|
||||
r = compose('run', '--rm', '--no-deps', '-T', '--entrypoint', '/app/reconcile', 'reconciler',
|
||||
'--grace', '1h', check=False, timeout=900)
|
||||
if r.returncode == 3:
|
||||
time.sleep(2)
|
||||
continue
|
||||
check(r.returncode in (0, 4), 'reconcile failed: ' + r.stderr[-300:])
|
||||
return json.loads(r.stdout.strip().splitlines()[-1])
|
||||
raise RuntimeError('lock busy')
|
||||
|
||||
|
||||
def seed(chat_id, owner_id, start, count):
|
||||
"""count согласованных пар с ключами a/<chat>/bench-<номер>."""
|
||||
# Объекты: генерируем count файлов в контейнере mc и заливаем одним mirror.
|
||||
mc('mkdir -p /tmp/b && head -c 1024 /dev/urandom > /tmp/one && i=%d; while [ $i -lt %d ]; do '
|
||||
'cp /tmp/one /tmp/b/bench-$(printf %%07d $i); i=$((i+1)); done && '
|
||||
'mc mirror -q --overwrite /tmp/b s3/%s/a/%s/ >/dev/null' % (start, start + count, BUCKET, chat_id))
|
||||
psql("INSERT INTO attachments (id, chat_id, owner_id, filename, object_key, status, content_type, size_bytes, sha256) "
|
||||
"SELECT gen_random_uuid(), '%s', '%s', 'b.png', 'a/%s/bench-' || lpad(g::text, 7, '0'), 'ready', "
|
||||
"'image/png', 1024, repeat('a', 64) FROM generate_series(%d, %d) g"
|
||||
% (chat_id, owner_id, chat_id, start, start + count - 1))
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--sizes', default='1000,10000,30000')
|
||||
p.add_argument('--output', default=None)
|
||||
args = arguments('Reconciler traversal cost (lab4 track 2)', configure)
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, _, _, chat = c.bootstrap()
|
||||
total_existing = int(psql('SELECT count(*) FROM attachments'))
|
||||
sizes = [int(x) for x in args.sizes.split(',')]
|
||||
seeded, runs = 0, []
|
||||
for n in sizes:
|
||||
t0 = time.time()
|
||||
seed(chat['id'], alice['id'], seeded, n - seeded)
|
||||
seed_s = time.time() - t0
|
||||
seeded = n
|
||||
reps = [reconcile_dry() for _ in range(3)]
|
||||
ms = [r['duration_ms'] for r in reps]
|
||||
r = reps[-1]
|
||||
runs.append({'bench_pairs': n, 'rows_scanned': r['rows_scanned'], 'objects_scanned': r['objects_scanned'],
|
||||
'duration_ms_runs': ms, 'duration_ms_median': statistics.median(ms),
|
||||
'us_per_pair': round(1000 * statistics.median(ms) / max(1, r['rows_scanned']), 1),
|
||||
'calls': r['calls'], 'heap_alloc_mb': r['heap_alloc_mb'], 'found': r['found'],
|
||||
'wait_ms_runs': [x.get('wait_ms') for x in reps],
|
||||
'seed_seconds': round(seed_s, 1)})
|
||||
print(json.dumps(runs[-1], ensure_ascii=False))
|
||||
# 1% расхождений на самом большом наборе: удалённые объекты и сироты.
|
||||
k = max(1, sizes[-1] // 100)
|
||||
mc('i=0; while [ $i -lt %d ]; do mc rm -q s3/%s/a/%s/bench-$(printf %%07d $((i*97 %% %d))) >/dev/null 2>&1; i=$((i+1)); done'
|
||||
% (k // 2, BUCKET, chat['id'], sizes[-1]))
|
||||
mc('head -c 512 /dev/urandom > /tmp/o && i=0; while [ $i -lt %d ]; do mc cp -q /tmp/o s3/%s/a/%s/zz-orphan-$i >/dev/null; i=$((i+1)); done'
|
||||
% (k - k // 2, BUCKET, chat['id']))
|
||||
faulty = reconcile_dry()
|
||||
out = {'preexisting_rows': total_existing, 'object_size_bytes': 1024, 'runs': runs,
|
||||
'with_1pct_faults': {'injected_missing': k // 2, 'injected_orphans': k - k // 2,
|
||||
'duration_ms': faulty['duration_ms'], 'found': faulty['found'],
|
||||
'skipped': faulty['skipped'], 'calls': faulty['calls']},
|
||||
'note': 'dry-run, grace 1h: свежие сироты учитываются как skipped.fresh_object, а не удаляются'}
|
||||
text = json.dumps(out, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
open(args.output, 'w', encoding='utf-8').write(text + '\n')
|
||||
print(text)
|
||||
print('PASS: reconciler cost measured for %s pairs' % sizes)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Executable
+175
@@ -0,0 +1,175 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Трек 2: внедрение расхождений PostgreSQL↔S3 и проверка reconciler.
|
||||
|
||||
Сценарий (Docker-стенд, reconciler запускается одноразово через docker compose run):
|
||||
1. Через API: чат, 6 вложений, два из них прикреплены к сообщениям.
|
||||
2. Внедряем ошибки с обеих сторон:
|
||||
S3: сирота (объект без строки, старый), сирота свежая (моложе grace),
|
||||
удалённый объект используемого и неиспользуемого вложения,
|
||||
объект с подменённым размером;
|
||||
БД: брошенное намерение с объектом и без, свежее намерение (загрузка «идёт»).
|
||||
3. dry-run: всё найдено, ничего не изменено (снимки БД и S3 совпадают).
|
||||
4. apply: исправлено; свежие и используемые не тронуты; API: здоровые вложения
|
||||
скачиваются байт-в-байт, потерянные отвечают 503, сообщение сохраняет attachment_ids.
|
||||
5. Повторный apply — ничего не исправляет (идемпотентность).
|
||||
6. Объект «восстановлен из бэкапа» → apply снимает карантин, скачивание снова работает.
|
||||
7. После grace: неиспользуемая запись карантина удаляется, используемая остаётся;
|
||||
свежая сирота, ставшая старой, удаляется.
|
||||
|
||||
Grace в тесте — 8 s (--unsafe-short-grace); «старые» строки сдвинуты на 30 минут
|
||||
назад, поэтому фоновый reconciler стенда (grace 1h) их не трогает.
|
||||
"""
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
from labutil import BUCKET, compose, fixture, mc, noise_png, object_key, psql, wait_status
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
GRACE = '8s'
|
||||
|
||||
|
||||
def reconcile(*flags):
|
||||
for _ in range(10):
|
||||
r = compose('run', '--rm', '--no-deps', '-T', '--entrypoint', '/app/reconcile', 'reconciler',
|
||||
'--grace', GRACE, '--unsafe-short-grace', *flags, check=False)
|
||||
if r.returncode == 3: # фоновый reconciler держит advisory lock
|
||||
time.sleep(2)
|
||||
continue
|
||||
check(r.returncode in (0, 4), 'reconcile failed: ' + r.stderr[-400:])
|
||||
return json.loads(r.stdout.strip().splitlines()[-1])
|
||||
raise RuntimeError('reconciler lock busy')
|
||||
|
||||
|
||||
def snapshot(chat_id):
|
||||
rows = psql("SELECT id || ':' || status || ':' || COALESCE(size_bytes, 0) FROM attachments "
|
||||
"WHERE chat_id = '%s' ORDER BY id" % chat_id)
|
||||
objs = mc('mc ls --recursive --json s3/%s/a/%s/' % (BUCKET, chat_id)).stdout
|
||||
# mc ls --json отдаёт key относительно листинга — дополняем до полного ключа.
|
||||
keys = sorted(('a/%s/%s' % (chat_id, json.loads(l)['key']), json.loads(l)['size'])
|
||||
for l in objs.splitlines() if l.strip() and 'key' in json.loads(l))
|
||||
return rows, keys
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--output', default=None)
|
||||
args = arguments('Reconciler fault injection (lab4 track 2)', configure)
|
||||
c = Client(args.base_url, args.ca_file, timeout=30)
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
cid = chat['id']
|
||||
def up(data):
|
||||
a = c.call('POST', '/api/v1/chats/%s/attachments?filename=r.png' % cid, 202, actor=alice,
|
||||
raw=data, headers={'Content-Type': 'image/png'}, schema='Attachment')['json']
|
||||
return wait_status(c, alice, a['id'], ('ready',))
|
||||
datas = [noise_png(20_000 + i * 1000) for i in range(6)]
|
||||
ok, lost_used, lost_free, resized, keep_used, restore_me = [up(d) for d in datas]
|
||||
for att in (lost_used, keep_used, restore_me):
|
||||
c.message(alice, chat, 'с вложением', attachments=[att['id']])
|
||||
|
||||
# --- внедрение ошибок ---
|
||||
tmp = '/tmp/f.bin'
|
||||
put = 'head -c %d /dev/urandom > ' + tmp + ' && mc cp -q ' + tmp + ' s3/' + BUCKET + '/%s >/dev/null'
|
||||
orphan_old = 'a/%s/%s' % (cid, uuid.uuid4())
|
||||
orphan_fresh = 'a/%s/%s' % (cid, uuid.uuid4())
|
||||
stale_with = str(uuid.uuid4())
|
||||
stale_without = str(uuid.uuid4())
|
||||
inflight = str(uuid.uuid4())
|
||||
mc(' && '.join([
|
||||
put % (5000, orphan_old),
|
||||
'mc rm -q s3/%s/%s' % (BUCKET, object_key(lost_used['id'])),
|
||||
'mc rm -q s3/%s/%s' % (BUCKET, object_key(lost_free['id'])),
|
||||
'mc rm -q s3/%s/%s' % (BUCKET, object_key(restore_me['id'])),
|
||||
put % (777, object_key(resized['id'])),
|
||||
put % (4000, 'a/%s/%s' % (cid, stale_with)),
|
||||
put % (4000, 'a/%s/%s' % (cid, inflight)),
|
||||
]))
|
||||
for aid, age in ((stale_with, "now() - interval '30 minutes'"), (stale_without, "now() - interval '30 minutes'"),
|
||||
(inflight, 'now()')):
|
||||
psql("INSERT INTO attachments (id, chat_id, owner_id, filename, object_key, status, created_at, updated_at) "
|
||||
"VALUES ('%s', '%s', '%s', 'x.png', 'a/%s/%s', 'uploading', %s, %s)" % (aid, cid, alice['id'], cid, aid, age, age))
|
||||
time.sleep(9) # «старые» объекты стали старше grace
|
||||
mc(put % (3000, orphan_fresh)) # а эта сирота — свежая
|
||||
psql("UPDATE attachments SET updated_at = now() WHERE id = '%s'" % inflight) # загрузка «продолжается»
|
||||
|
||||
# --- dry-run ---
|
||||
before = snapshot(cid)
|
||||
dry = reconcile()
|
||||
check(snapshot(cid) == before, 'dry-run changed state')
|
||||
mine = lambda rep, kind: [i for i in rep['items'] if i['kind'] == kind and cid in i['key']]
|
||||
expect = {'orphan_object': 1, 'stale_intent': 2, 'missing_object': 3, 'size_mismatch': 1}
|
||||
for kind, n in expect.items():
|
||||
check(len(mine(dry, kind)) == n, 'dry-run %s: %d, want %d' % (kind, len(mine(dry, kind)), n))
|
||||
check(all(i['action'].startswith('would_') for i in dry['items'] if cid in i['key']), 'dry-run planned real actions')
|
||||
|
||||
# --- apply ---
|
||||
applied = reconcile('--apply')
|
||||
rows, keys = snapshot(cid)
|
||||
status = {r.split(':')[0]: r.split(':')[1] for r in rows.splitlines()}
|
||||
key_set = {k for k, _ in keys}
|
||||
check(stale_with not in status and stale_without not in status, 'stale intents not removed')
|
||||
check('a/%s/%s' % (cid, stale_with) not in key_set, 'stale intent object not removed')
|
||||
check(orphan_old not in key_set, 'old orphan not removed')
|
||||
check(orphan_fresh in key_set, 'FRESH orphan was deleted')
|
||||
check(status.get(inflight) == 'uploading' and 'a/%s/%s' % (cid, inflight) in key_set, 'IN-FLIGHT upload touched')
|
||||
for att in (lost_used, lost_free, restore_me, resized):
|
||||
check(status.get(att['id']) == 'missing', '%s not quarantined' % att['id'])
|
||||
check(status.get(ok['id']) == 'ready' and status.get(keep_used['id']) == 'ready', 'healthy rows touched')
|
||||
# API после исправления
|
||||
for att, data in ((ok, datas[0]), (keep_used, datas[4])):
|
||||
d = c.call('GET', '/api/v1/attachments/%s/content' % att['id'], actor=bob)
|
||||
check(d['bytes'] == data, 'healthy attachment changed')
|
||||
c.call('GET', '/api/v1/attachments/%s' % lost_used['id'], 503, actor=bob)
|
||||
c.call('GET', '/api/v1/attachments/%s/content' % lost_used['id'], 503, actor=bob)
|
||||
hist = c.call('GET', '/api/v1/chats/%s/messages?limit=100' % cid, actor=bob, schema='MessagePage')['json']['items']
|
||||
check(any(lost_used['id'] in m['attachment_ids'] for m in hist), 'message lost its attachment reference')
|
||||
c.call('POST', '/api/v1/chats/%s/messages' % cid, 409, actor=alice, body={'text': '', 'attachment_ids': [lost_free['id']]},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
|
||||
# --- идемпотентность ---
|
||||
again = reconcile('--apply')
|
||||
check(not [i for i in again['items'] if cid in i['key']], 'second apply changed something: %s' % [i for i in again['items'] if cid in i['key']])
|
||||
|
||||
# --- восстановление объекта ---
|
||||
with_data = datas[5]
|
||||
open_key = object_key(restore_me['id'])
|
||||
# Восстанавливаем исходные байты («из бэкапа») через stdin контейнера mc.
|
||||
import subprocess
|
||||
p = subprocess.run(['docker', 'compose', 'run', '--rm', '--no-deps', '-T', '--entrypoint', 'sh', 's3-init', '-c',
|
||||
'mc alias set s3 http://s3:9000 "$(cat /run/secrets/s3_root_user)" "$(cat /run/secrets/s3_root_password)" >/dev/null; '
|
||||
'cat > /tmp/r.png && mc cp -q /tmp/r.png s3/%s/%s >/dev/null' % (BUCKET, open_key)],
|
||||
input=with_data, capture_output=True)
|
||||
check(p.returncode == 0, 'restore put failed')
|
||||
restored = reconcile('--apply')
|
||||
check(len(mine(restored, 'restored')) == 1, 'restore not detected')
|
||||
d = c.call('GET', '/api/v1/attachments/%s/content' % restore_me['id'], actor=bob)
|
||||
check(d['bytes'] == with_data, 'restored attachment bytes differ')
|
||||
|
||||
# --- после grace ---
|
||||
time.sleep(9)
|
||||
late = reconcile('--apply')
|
||||
rows, keys = snapshot(cid)
|
||||
status = {r.split(':')[0]: r.split(':')[1] for r in rows.splitlines()}
|
||||
check(lost_free['id'] not in status, 'unreferenced quarantined row not purged after grace')
|
||||
check(resized['id'] not in status or status[resized['id']] == 'missing', 'resized row state')
|
||||
check(status.get(lost_used['id']) == 'missing', 'REFERENCED quarantined row deleted')
|
||||
check(orphan_fresh not in {k for k, _ in keys}, 'orphan not removed after grace')
|
||||
|
||||
summary = {
|
||||
'injected': {'orphan_old': 1, 'orphan_fresh': 1, 'deleted_objects': 3, 'resized_object': 1,
|
||||
'stale_intents': 2, 'inflight_intent': 1},
|
||||
'dry_run_found': {k: len(mine(dry, k)) for k in expect}, 'dry_run_state_changed': False,
|
||||
'apply_found': {k: len(mine(applied, k)) for k in expect},
|
||||
'second_apply_actions': 0, 'restored': 1,
|
||||
'after_grace': {k: len(mine(late, k)) for k in ('purge_missing', 'orphan_object')},
|
||||
'never_deleted': ['fresh orphan (until grace)', 'in-flight intent', 'referenced quarantined row', 'healthy rows'],
|
||||
'reports': {'dry_run': dry, 'apply': applied, 'second_apply': again, 'restore': restored, 'after_grace': late},
|
||||
}
|
||||
text = json.dumps(summary, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
open(args.output, 'w', encoding='utf-8').write(text + '\n')
|
||||
print(json.dumps({k: v for k, v in summary.items() if k != 'reports'}, ensure_ascii=False, indent=2))
|
||||
print('PASS: reconciler detected and safely fixed faults on both sides; dry-run and repeat are safe')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Executable
+81
@@ -0,0 +1,81 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Регрессии по замечаниям проверки lab3.
|
||||
|
||||
1. Видимость подтверждённой записи при отказе Redis в командах инвалидации:
|
||||
чат с двумя сообщениями → закэшировать историю → в Redis запретить команды
|
||||
через ACL (сначала только INCR, затем INCR+DEL+UNLINK+SCAN) → отправить
|
||||
третье сообщение → каждое следующее чтение через LB обязано вернуть его.
|
||||
2. Пароль из одних пробельных символов при регистрации → 400.
|
||||
|
||||
Нужен запущенный Docker-стенд (redis-cli вызывается через docker compose exec).
|
||||
ACL всегда восстанавливается в finally. --only cache|password запускает одну часть.
|
||||
"""
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests')) # публичный client.py
|
||||
from client import Client, arguments, check, run
|
||||
from resilience import history
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
WHITESPACE_PASSWORDS = (' ' * 12, '\t' * 12, ' ' * 8)
|
||||
|
||||
|
||||
def redis_cli(*args):
|
||||
r = subprocess.run(['docker', 'compose', 'exec', '-T', 'redis', 'redis-cli', *args],
|
||||
cwd=ROOT, capture_output=True, text=True, timeout=30)
|
||||
check(r.returncode == 0, 'redis-cli failed: ' + r.stderr.strip())
|
||||
return r.stdout.strip()
|
||||
|
||||
|
||||
def visibility_case(c, alice, bob, chat, denied):
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages?limit=50'
|
||||
before = [m['id'] for m in history(c, bob, chat)]
|
||||
# Прогреваем кэш на обеих репликах.
|
||||
for _ in range(4):
|
||||
c.call('GET', path, actor=bob, schema='MessagePage')
|
||||
redis_cli('ACL', 'SETUSER', 'default', *('-' + cmd for cmd in denied))
|
||||
try:
|
||||
sent = c.message(alice, chat, 'после запрета ' + '+'.join(denied))['json']
|
||||
# Каждое следующее чтение (через любую реплику) видит подтверждённую запись.
|
||||
for i in range(6):
|
||||
page = c.call('GET', path, actor=bob, schema='MessagePage')
|
||||
ids = [m['id'] for m in page['json']['items']]
|
||||
check(sent['id'] in ids, 'read %d after 201 misses confirmed message (denied: %s)' % (i, denied))
|
||||
# Порядок (created_at до секунды, id): новое сообщение той же секунды может
|
||||
# встать раньше старых, поэтому проверяем наличие, а не префикс.
|
||||
check(set(before) <= set(ids), 'previously confirmed messages missing')
|
||||
finally:
|
||||
# reset — чтобы снять и точечные запреты, независимо от порядка правил.
|
||||
redis_cli('ACL', 'SETUSER', 'default', 'reset', 'on', 'nopass', '~*', '&*', '+@all')
|
||||
return len(before) + 1
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--only', choices=['password', 'cache'], default=None)
|
||||
args = arguments('Regression checks for lab3 review findings', configure)
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
|
||||
# 2. Пароль из пробельных символов (пробелы, табуляции, неразрывные пробелы).
|
||||
if args.only in (None, 'password'):
|
||||
for pw in WHITESPACE_PASSWORDS:
|
||||
c.call('POST', '/api/v1/users', 400,
|
||||
body={'username': 'ws_' + uuid.uuid4().hex[:10], 'display_name': 'WS', 'password': pw})
|
||||
print('PASS: whitespace-only password rejected with 400 (3 variants)')
|
||||
if args.only == 'password':
|
||||
return
|
||||
|
||||
# 1. Видимость записи при отказе Redis.
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
c.message(alice, chat, 'первое')
|
||||
c.message(bob, chat, 'второе')
|
||||
n = visibility_case(c, alice, bob, chat, ['incr'])
|
||||
print('PASS: Redis ACL -incr: message visible on every next read (%d in history)' % n)
|
||||
n = visibility_case(c, alice, bob, chat, ['incr', 'del', 'unlink', 'scan'])
|
||||
print('PASS: Redis ACL -incr -del -unlink -scan: message visible on every next read (%d in history)' % n)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Reference in New Issue
Block a user