Apply completed lab 5 implementation
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
@@ -0,0 +1,224 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Собственные проверки вложений (с lab4; в lab5 upload → 202 queued), только стандартная библиотека.
|
||||
|
||||
Покрывают: слишком большой файл, повреждённые PNG/JPEG, подмену MIME, decompression bomb,
|
||||
опасные filename, чужое/неизвестное attachment_id, вложение другого чата, постороннего пользователя,
|
||||
идемпотентность с вложениями. Ни одна пользовательская ошибка не должна давать 500.
|
||||
|
||||
--with-docker дополнительно (через docker compose из корня репозитория):
|
||||
* останавливает S3: загрузка/скачивание -> 503, текстовые сообщения и /health/ready работают,
|
||||
неудачная загрузка не оставляет строк в БД;
|
||||
* останавливает API-реплику, принявшую загрузку, и скачивает файл через другую.
|
||||
Синтетический fixture tests/fixtures/sample.jpg получен из sample.png (sips, quality 85).
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
import zlib
|
||||
from urllib.parse import quote
|
||||
from client import ROOT, Client, arguments, check, run
|
||||
|
||||
PNG = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
JPEG = (ROOT / 'tests/fixtures/sample.jpg').read_bytes()
|
||||
MIB = 1024 * 1024
|
||||
|
||||
|
||||
def png(width, height, idat=None, depth=8, color=2):
|
||||
def chunk(kind, data):
|
||||
return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data))
|
||||
if idat is None:
|
||||
row = b'\x00' + bytes(width * 3)
|
||||
idat = zlib.compress(row * height, 9)
|
||||
return (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', width, height, depth, color, 0, 0, 0))
|
||||
+ chunk(b'IDAT', idat) + chunk(b'IEND', b''))
|
||||
|
||||
|
||||
def flip(data, at):
|
||||
return data[:at] + bytes([data[at] ^ 0xff]) + data[at + 1:]
|
||||
|
||||
|
||||
def compose(*args, check_rc=True):
|
||||
return subprocess.run(['docker', 'compose', *args], cwd=ROOT, check=check_rc, capture_output=True, text=True).stdout
|
||||
|
||||
|
||||
def sql(query):
|
||||
return compose('exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-At', '-c', query).strip()
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--with-docker', action='store_true', help='also stop S3 and the uploading replica via docker compose')
|
||||
args = arguments('Negative attachment checks for lab4; creates synthetic data', configure)
|
||||
c = Client(args.base_url, args.ca_file, timeout=20)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
other = c.call('POST', '/api/v1/chats', 201, actor=alice, body={'title': 'Другой чат', 'member_ids': [alice['id'], eve['id']]}, schema='Chat')['json']
|
||||
passed = []
|
||||
|
||||
def upload(data, ctype='image/png', expected=202, actor=alice, target=chat, name='file.png'):
|
||||
r = c.call('POST', '/api/v1/chats/%s/attachments?filename=%s' % (target['id'], quote(name, safe='')), expected,
|
||||
actor=actor, raw=data, headers={'Content-Type': ctype}, schema='Attachment' if expected == 202 else None)
|
||||
if expected >= 400:
|
||||
check(r['json']['error']['code'] != 'internal_error', 'user error turned into 500')
|
||||
return r
|
||||
|
||||
def ok(name):
|
||||
passed.append(name)
|
||||
print('PASS', name)
|
||||
|
||||
# Валидные форматы и побайтовое скачивание.
|
||||
att_png = c.wait_ready(bob, upload(PNG)['json'])
|
||||
att_jpg = c.wait_ready(bob, upload(JPEG, 'image/jpeg', name='photo.jpg')['json'])
|
||||
check(att_jpg['content_type'] == 'image/jpeg' and att_jpg['status'] == 'ready', 'jpeg metadata')
|
||||
for att, data, ctype in ((att_png, PNG, 'image/png'), (att_jpg, JPEG, 'image/jpeg')):
|
||||
got = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)
|
||||
check(got['bytes'] == data and got['headers'].get_content_type() == ctype, 'download differs')
|
||||
ok('valid PNG and JPEG upload/download byte-for-byte')
|
||||
|
||||
# Размер: API отклоняет 10 MiB + 1 байт, nginx — всё больше 11 MiB, оба JSON 413.
|
||||
upload(PNG[:8] + bytes(10 * MIB + 1 - 8), expected=413)
|
||||
req = urllib.request.Request(c.base + '/api/v1/chats/%s/attachments?filename=big.png' % chat['id'], data=bytes(12 * MIB), method='POST',
|
||||
headers={'Authorization': 'Bearer ' + alice['token'], 'Content-Type': 'image/png'})
|
||||
try:
|
||||
urllib.request.urlopen(req, timeout=20)
|
||||
check(False, 'oversized body accepted')
|
||||
except urllib.error.HTTPError as e:
|
||||
body = json.loads(e.read())
|
||||
check(e.code == 413 and body['error']['code'] == 'payload_too_large' and e.headers.get('X-Request-Id'), 'nginx 413 must be contract JSON')
|
||||
# Почти 10 MiB: случайные пиксели не сжимаются; у каждой строки байт фильтра 0.
|
||||
big = png(1800, 1900, idat=zlib.compress(b''.join(b'\x00' + os.urandom(1800 * 3) for _ in range(1900)), 1))
|
||||
check(len(big) <= 10 * MIB, 'fixture too large')
|
||||
upload(big)
|
||||
ok('10 MiB + 1 byte -> 413 (API), 12 MiB -> 413 JSON (nginx), valid %.1f MiB accepted' % (len(big) / MIB))
|
||||
|
||||
# Повреждённые изображения.
|
||||
idat_at = PNG.find(b'IDAT') + 8
|
||||
for broken in (flip(PNG, idat_at), PNG[:len(PNG) // 2], PNG + b'trailing', PNG[:8] + b'garbage' * 10):
|
||||
upload(broken, expected=415)
|
||||
for broken in (JPEG[:len(JPEG) // 2], JPEG[:4] + b'\x00' * 100, JPEG[:2] + b'\xff\xda\x00\x02' + JPEG[2:]):
|
||||
upload(broken, 'image/jpeg', expected=415)
|
||||
ok('corrupted/truncated PNG and JPEG -> 415')
|
||||
|
||||
# Подмена MIME: проверяется содержимое, а не заголовок.
|
||||
upload(PNG, 'image/jpeg', expected=415)
|
||||
upload(JPEG, 'image/png', expected=415)
|
||||
upload(b'GIF89a' + bytes(100), 'image/png', expected=415)
|
||||
upload(b'<svg xmlns="http://www.w3.org/2000/svg"/>', 'image/png', expected=415)
|
||||
upload(PNG, 'text/plain', expected=415)
|
||||
upload(PNG, 'image/gif', expected=415)
|
||||
ok('MIME spoofing (content vs Content-Type) -> 415')
|
||||
|
||||
# Decompression bomb: заголовок > 40 Мпикс -> 413 до распаковки; ложный маленький заголовок -> 415;
|
||||
# честные 36 Мпикс (≈108 МБ пикселей) принимаются без декодирования в RAM.
|
||||
upload(png(10000, 10000, idat=zlib.compress(bytes(1000))), expected=413)
|
||||
upload(png(100, 100, idat=zlib.compress(bytes(50 * MIB), 9)), expected=415)
|
||||
upload(png(6000, 6000))
|
||||
ok('decompression bomb: >40 MP -> 413, lying header -> 415, honest 36 MP accepted')
|
||||
|
||||
# filename: только отображение; пути, NUL, управляющие символы и длина — 400.
|
||||
for name in ('../evil.png', 'a/b.png', 'a\\b.png', 'a\x00b.png', 'a\x07b.png', 'line\nbreak.png', ' ', '..', 'x' * 256):
|
||||
upload(PNG, name=name, expected=400)
|
||||
c.call('POST', '/api/v1/chats/%s/attachments' % chat['id'], 400, actor=alice, raw=PNG, headers={'Content-Type': 'image/png'})
|
||||
for name in ('фото 😀.png', '😀' * 255):
|
||||
got = upload(PNG, name=name)['json']
|
||||
check(got['filename'] == name, 'filename changed')
|
||||
ok('dangerous filenames -> 400, Unicode up to 255 code points preserved')
|
||||
|
||||
# Доступ: посторонний не загружает и не читает, без сессии — 401, неизвестный id — 404.
|
||||
upload(PNG, actor=eve, expected=404)
|
||||
for suffix in ('', '/content'):
|
||||
c.call('GET', '/api/v1/attachments/' + att_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', 400, actor=alice)
|
||||
c.call('POST', '/api/v1/chats/%s/attachments?filename=a.png' % chat['id'], 401, raw=PNG, headers={'Content-Type': 'image/png'})
|
||||
ok('outsider/unknown attachment -> 404, no session -> 401')
|
||||
|
||||
# attachment_ids в сообщении.
|
||||
path = '/api/v1/chats/%s/messages' % chat['id']
|
||||
foreign = upload(PNG, target=other)['json']
|
||||
|
||||
def send(body, expected=201, key=None):
|
||||
return c.call('POST', path, expected, actor=alice, body=body, headers={'Idempotency-Key': key or uuid.uuid4().hex},
|
||||
schema='Message' if expected == 201 else None)
|
||||
send({'text': 'чужое', 'attachment_ids': [foreign['id']]}, 404)
|
||||
send({'text': 'неизвестное', 'attachment_ids': [str(uuid.uuid4())]}, 404)
|
||||
send({'text': 'смесь', 'attachment_ids': [att_png['id'], foreign['id']]}, 404)
|
||||
for bad in (['not-a-uuid'], [att_png['id'], att_png['id']], [str(uuid.uuid4()) for _ in range(11)], None, att_png['id'], [1]):
|
||||
send({'text': 'x', 'attachment_ids': bad}, 400)
|
||||
send({'text': ''}, 400)
|
||||
send({'text': '', 'attachment_ids': []}, 400)
|
||||
send({'text': ' ', 'attachment_ids': [att_png['id']]}, 400)
|
||||
two = send({'text': '', 'attachment_ids': [att_jpg['id'], att_png['id']]})['json']
|
||||
check(two['attachment_ids'] == [att_jpg['id'], att_png['id']] and two['text'] == '', 'attachment order or text changed')
|
||||
history = c.call('GET', path + '?limit=100', actor=bob, schema='MessagePage')['json']['items']
|
||||
check(any(m == two for m in history), 'history lost attachment_ids')
|
||||
ok('foreign/unknown attachment -> 404, malformed attachment_ids -> 400, order preserved')
|
||||
|
||||
# Идемпотентность: отсутствующий attachment_ids == [], другой набор с тем же ключом — 409.
|
||||
key = uuid.uuid4().hex
|
||||
first = send({'text': 'ключ'}, key=key)['json']
|
||||
check(send({'attachment_ids': [], 'text': 'ключ'}, key=key)['json'] == first, 'missing vs [] must be equal')
|
||||
send({'text': 'ключ', 'attachment_ids': [att_png['id']]}, 409, key=key)
|
||||
key = uuid.uuid4().hex
|
||||
first = send({'text': 'с файлом', 'attachment_ids': [att_png['id']]}, key=key)['json']
|
||||
check(send({'text': 'с файлом', 'attachment_ids': [att_png['id']]}, key=key)['json'] == first, 'replay with attachment differs')
|
||||
send({'text': 'с файлом', 'attachment_ids': [att_jpg['id']]}, 409, key=key)
|
||||
ok('idempotency with attachment_ids (missing == [], different set -> 409)')
|
||||
|
||||
# Варианты lab5: thumbnail/crop JPEG, optimized WebP; мусорное имя — 400.
|
||||
types = {'original': 'image/png', 'thumbnail': 'image/jpeg', 'crop': 'image/jpeg', 'optimized': 'image/webp'}
|
||||
for name, ctype in types.items():
|
||||
got = c.call('GET', '/api/v1/attachments/%s/content?variant=%s' % (att_png['id'], name), actor=bob)
|
||||
check(got['headers'].get_content_type() == ctype, 'variant %s has wrong content type' % name)
|
||||
c.call('GET', '/api/v1/attachments/%s/content?variant=../../etc' % att_png['id'], 400, actor=bob)
|
||||
ok('variants: original/thumbnail/crop/optimized 200 with own types, garbage 400')
|
||||
|
||||
if args.with_docker:
|
||||
# Недоступный S3: вложения 503, текстовый путь живёт, после сбоя нет зависших строк.
|
||||
compose('stop', 's3')
|
||||
try:
|
||||
rows_before = sql('select count(*) from attachments')
|
||||
r = upload(PNG, expected=503)
|
||||
check(r['json']['error']['code'] == 'unavailable', 'S3 outage must be 503 unavailable')
|
||||
c.call('GET', '/api/v1/attachments/' + att_png['id'] + '/content', 503, actor=bob)
|
||||
c.call('GET', '/api/v1/attachments/' + att_png['id'], actor=bob, schema='Attachment')
|
||||
send({'text': 'S3 лежит, текст идёт'})
|
||||
c.call('GET', '/health/ready', schema='Health')
|
||||
check(sql('select count(*) from attachments') == rows_before, 'failed upload left a row')
|
||||
finally:
|
||||
compose('start', 's3')
|
||||
deadline = time.monotonic() + 60
|
||||
while True:
|
||||
try:
|
||||
got = c.call('GET', '/api/v1/attachments/' + att_png['id'] + '/content', actor=bob)
|
||||
break
|
||||
except AssertionError:
|
||||
check(time.monotonic() < deadline, 'downloads did not recover after S3 start')
|
||||
time.sleep(1)
|
||||
check(got['bytes'] == PNG, 'download after S3 recovery differs')
|
||||
ok('S3 down: attachments 503, messages/ready OK, no rows left; recovered after start')
|
||||
|
||||
# Остановка реплики, принявшей загрузку: другая скачивает тот же файл.
|
||||
r = upload(PNG)
|
||||
served = r['headers']['X-Instance-Id']
|
||||
c.wait_ready(bob, r['json'])
|
||||
cid = [x for x in compose('ps', '-q', 'api-1', 'api-2').split() if x.startswith(served)]
|
||||
check(len(cid) == 1, 'cannot map X-Instance-Id to a container')
|
||||
subprocess.run(['docker', 'stop', cid[0]], check=True, capture_output=True)
|
||||
try:
|
||||
for _ in range(5):
|
||||
got = c.call('GET', '/api/v1/attachments/' + r['json']['id'] + '/content', actor=bob)
|
||||
check(got['bytes'] == PNG and got['headers']['X-Instance-Id'] != served, 'download through other replica failed')
|
||||
finally:
|
||||
subprocess.run(['docker', 'start', cid[0]], check=True, capture_output=True)
|
||||
ok('upload replica %s stopped: other replica serves identical bytes' % served)
|
||||
|
||||
print('PASS: %d attachment checks' % len(passed))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Vendored
BIN
Binary file not shown.
|
After Width: | Height: | Size: 10 KiB |
@@ -0,0 +1,285 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Сквозная проверка pipeline lab5 (уровни 3–4) и эксперимент трека 2 «доказанная идемпотентность».
|
||||
|
||||
Гипотеза: при at-least-once доставке, дублях, перестановке сообщений, падениях до/после побочного
|
||||
эффекта и устаревшей job после новой версии ни одна принятая (202) работа не теряется, на ключ эффекта
|
||||
(attachment_id, pipeline_version, variant) приходится ровно один результат, а указатель версии не откатывается.
|
||||
|
||||
Сценарии (FAULT_INJECTION=1 включает точки сбоя по префиксу имени файла fault-<point>, каждая — один раз):
|
||||
A worker остановлен → upload 202, content 409, сообщение с вложением 201 → рестарт API и брокера → worker → ready;
|
||||
B падения: relay до publish (разрыв COMMIT/publish), relay после publish до удаления outbox (дубль),
|
||||
worker после захвата (до эффекта), после записи в S3 до COMMIT, после COMMIT до ack; временная ошибка до
|
||||
исчерпания попыток (backoff+jitter → failed) и replay; постоянная ошибка (arithmetic JPEG);
|
||||
C устаревшая job: v1 медленная (40 с перед COMMIT), v2 (jobctl reprocess) фиксируется раньше; дубли v1 во время и после обработки;
|
||||
затем инварианты по БД, S3 и API.
|
||||
|
||||
Запуск из корня репозитория при работающем стенде (docker compose из этого каталога; для другого проекта —
|
||||
COMPOSE_PROJECT_NAME/COMPOSE_FILE):
|
||||
python3 tests/pipeline_experiment.py --output evidence/pipeline_experiment.json
|
||||
Скрипт пересоздаёт api-1, api-2 и worker с FAULT_INJECTION=1 и арендой 6 с, в конце возвращает обычный режим.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
from client import ROOT, Client, arguments, check, run
|
||||
from image_probe import jpeg_size
|
||||
|
||||
PNG = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
BUCKET = 'messenger-attachments'
|
||||
LEASE = 6
|
||||
FAULT_ENV = {'FAULT_INJECTION': '1', 'JOB_LEASE_SECONDS': str(LEASE)}
|
||||
CRASHES = ['crash-before-publish', 'crash-after-publish', 'crash-after-claim', 'crash-after-s3', 'crash-after-commit']
|
||||
|
||||
|
||||
def compose(*args, env=None, stdin=None):
|
||||
p = subprocess.run(['docker', 'compose', *args], cwd=ROOT, input=stdin, capture_output=True, text=True, env={**os.environ, **(env or {})})
|
||||
check(p.returncode == 0, 'docker compose %s failed: %s' % (' '.join(args[:2]), p.stderr[-400:]))
|
||||
return p.stdout
|
||||
|
||||
|
||||
def sql(query):
|
||||
return compose('exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-At', '-F', '|', '-c', query).strip()
|
||||
|
||||
|
||||
def rows(query):
|
||||
out = sql(query)
|
||||
return [line.split('|') for line in out.split('\n')] if out else []
|
||||
|
||||
|
||||
def queue():
|
||||
out = compose('exec', '-T', 'rabbitmq', 'rabbitmqctl', '-q', 'list_queues', 'name', 'messages')
|
||||
return {k: int(v) for k, v in (line.split('\t') for line in out.strip().split('\n') if '\t' in line and not line.startswith('name'))}
|
||||
|
||||
|
||||
def s3(commands):
|
||||
# Подписанные запросы ключами API из контейнера s3-probe; ключи передаются curl через stdin.
|
||||
script = ('sign() { printf \'user = "%s:%s"\\n\' "$(cat /run/secrets/s3.access-key)" "$(cat /run/secrets/s3.secret-key)"; }\n'
|
||||
'url=http://s3:8333/' + BUCKET + '\n' + '\n'.join(commands) + '\n')
|
||||
return compose('run', '--rm', '-T', 's3-probe', stdin=script)
|
||||
|
||||
|
||||
def s3_keys(prefix):
|
||||
return re.findall(r'<Key>([^<]+)</Key>', s3(['sign | curl -K - -s --aws-sigv4 aws:amz:us-east-1:s3 "$url?list-type=2&prefix=%s"' % prefix]))
|
||||
|
||||
|
||||
def s3_sha256(keys):
|
||||
out = s3(['echo "%s $(sign | curl -K - -s --aws-sigv4 aws:amz:us-east-1:s3 "$url/%s" | sha256sum | cut -d" " -f1)"' % (k, k) for k in keys])
|
||||
return dict(line.split(' ') for line in out.strip().split('\n') if line)
|
||||
|
||||
|
||||
def jobctl(*args):
|
||||
out = compose('run', '--rm', '-T', 'jobctl', *args)
|
||||
return json.loads(out[out.index('{'):])
|
||||
|
||||
|
||||
def arithmetic_jpeg():
|
||||
# Структурно корректный JPEG (SOF9, arithmetic coding): API принимает, ImageIO декодировать не умеет.
|
||||
seg = lambda marker, body: b'\xff' + bytes([marker]) + struct.pack('>H', len(body) + 2) + body
|
||||
return (b'\xff\xd8' + seg(0xC9, struct.pack('>BHHB', 8, 16, 16, 1) + b'\x01\x11\x00')
|
||||
+ seg(0xDA, b'\x01\x01\x00\x00\x3f\x00') + b'\x00' * 32 + b'\xff\xd9')
|
||||
|
||||
|
||||
def wait_until(what, condition, timeout):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
value = condition()
|
||||
if value:
|
||||
return value
|
||||
except Exception:
|
||||
pass # API-реплика или брокер перезапускаются после внедрённого падения
|
||||
time.sleep(0.5)
|
||||
check(False, 'timeout waiting for ' + what)
|
||||
|
||||
|
||||
def events(job):
|
||||
return [(int(a), e, d) for a, e, d in rows("select attempt,event,coalesce(detail,'') from job_audit where job_id='%s' order by id" % job)]
|
||||
|
||||
|
||||
def invariants(ids, invalid_id):
|
||||
in_list = ','.join("'%s'" % i for i in ids)
|
||||
jobs_of = 'select job_id from jobs where attachment_id in (%s)' % in_list
|
||||
states = dict(rows('select id,state from attachments where id in (%s)' % in_list))
|
||||
check(all(states[i] == 'ready' for i in ids if i != invalid_id) and states[invalid_id] == 'failed', 'I1: accepted work lost or stuck: %s' % states)
|
||||
effects = rows('select attachment_id,pipeline_version,count(*) from attachment_variants where attachment_id in (%s) group by 1,2' % in_list)
|
||||
check(all(int(n) == 3 for _, _, n in effects), 'I2: effect key has not exactly 3 variants')
|
||||
db_sha = dict(rows('select object_key,sha256 from attachment_variants where attachment_id in (%s)' % in_list))
|
||||
s3_variants = sorted(k for i in ids for k in s3_keys('variants/' + i + '/'))
|
||||
check(s3_variants == sorted(db_sha), 'I2: S3 variant objects differ from DB rows')
|
||||
s3_sha = s3_sha256(sorted(db_sha))
|
||||
check(s3_sha == db_sha, 'I3: S3 bytes differ from committed checksums')
|
||||
# I4: каждое done-задание зафиксировано ровно один раз, failed — ни разу; после done захватов нет.
|
||||
commits = rows("select j.state,count(a.*) filter (where a.event='done') from jobs j left join job_audit a on a.job_id=j.job_id where j.job_id in (%s) group by j.job_id,j.state" % jobs_of)
|
||||
check(all(int(n) == (1 if s == 'done' else 0) for s, n in commits), 'I4: a job was committed more than once (or failed job committed): %s' % commits)
|
||||
after_done = sql("select count(*) from job_audit a join job_audit d on d.job_id=a.job_id and d.event='done' and a.event='claimed' and a.id>d.id where a.job_id in (%s)" % jobs_of)
|
||||
check(after_done == '0', 'I4: a done job was claimed again')
|
||||
# I5: staging ready-вложений удалён (сразу после COMMIT или sweepStaging), failed хранится до retention.
|
||||
ready_ids = {i for i in ids if states[i] == 'ready'}
|
||||
staging = wait_until('staging cleanup', lambda: (lambda left: {'staging_left_for_run': sorted(left & set(ids))} if not left & ready_ids else None)(
|
||||
{k.split('/')[1] for k in s3_keys('staging/')}), 90)
|
||||
duplicates = dict(rows("select event,count(*) from job_audit where event in ('duplicate_done','duplicate_in_progress','stale_attempt') and job_id in (%s) group by 1" % jobs_of))
|
||||
result = {'I1_no_lost_accepted_work': states, 'I2_variants_per_effect_key': {'%s/v%s' % (a, v): int(n) for a, v, n in effects},
|
||||
'I2_s3_variant_objects': len(s3_variants), 'I3_checksums_equal': len(s3_sha),
|
||||
'I4_commits_per_job': sorted(int(n) for _, n in commits), 'I5_staging': staging,
|
||||
'duplicates_dropped': {k: int(v) for k, v in duplicates.items()}, 'result': 'PASS'}
|
||||
print('PASS invariants: %d attachments final, %d variant objects = DB rows, checksums equal, every done job committed once, dropped %s'
|
||||
% (len(ids), len(s3_variants), result['duplicates_dropped']))
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--output', default=None)
|
||||
args = arguments('Lab5 pipeline end-to-end checks and track-2 idempotency experiment', configure)
|
||||
c = Client(args.base_url, args.ca_file, timeout=20)
|
||||
started = time.monotonic()
|
||||
compose('up', '-d', '--wait', 'api-1', 'api-2', 'worker', env=FAULT_ENV)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
report = {'experiment': 'lab5 pipeline: grade 3/4 scenarios and track 2 idempotency', 'lease_seconds': LEASE, 'scenarios': {}}
|
||||
|
||||
def upload(name, data=PNG, ctype='image/png'):
|
||||
att = c.call('POST', '/api/v1/chats/%s/attachments?filename=%s' % (chat['id'], name), 202, actor=alice, raw=data,
|
||||
headers={'Content-Type': ctype}, schema='Attachment')['json']
|
||||
check(att['status'] == 'queued' and att['variants'] == [] and att['error_code'] is None, 'upload must return a queued snapshot')
|
||||
return att
|
||||
|
||||
def meta(att):
|
||||
return c.call('GET', '/api/v1/attachments/' + att['id'], actor=bob, schema='Attachment')['json']
|
||||
|
||||
def final(att, timeout=120):
|
||||
return wait_until('final state of ' + att['filename'], lambda: (lambda m: m if m['status'] in ('ready', 'failed') else None)(meta(att)), timeout)
|
||||
|
||||
def job_of(att, version=1):
|
||||
return sql("select job_id from jobs where attachment_id='%s' and pipeline_version=%d" % (att['id'], version))
|
||||
|
||||
# A. Worker остановлен: приём не зависит от worker, задание переживает рестарт API и брокера.
|
||||
t0 = time.monotonic()
|
||||
# Сначала очередь пуста (worker разобрал прежнее); счётчик list_queues у quorum-очереди обновляется
|
||||
# с задержкой до ~5 с, поэтому пустоту подтверждаем двумя чтениями с паузой.
|
||||
empty = lambda: queue().get('attachments.process', 1) == 0
|
||||
wait_until('queue drained', lambda: empty() and (time.sleep(6) or empty()), 120)
|
||||
compose('stop', 'worker')
|
||||
demo = upload('demo.png')
|
||||
for suffix in ('/content', '/content?variant=thumbnail'):
|
||||
c.call('GET', '/api/v1/attachments/%s%s' % (demo['id'], suffix), 409, actor=bob)
|
||||
linked = c.message(alice, chat, '', attachments=[demo['id']])['json']
|
||||
c.message(bob, chat, 'worker остановлен, текст идёт')
|
||||
depth = lambda least: (lambda q: q if q.get('attachments.process', 0) >= least else None)(queue())
|
||||
depth_before = wait_until('job message in broker', lambda: depth(1), 30)
|
||||
compose('restart', 'api-1', 'api-2', 'rabbitmq')
|
||||
# После рестарта quorum-очередь сначала выбирает лидера; ждём, пока она снова покажет сообщение.
|
||||
depth_after = wait_until('queued job after broker restart', lambda: depth(1), 90)
|
||||
wait_until('API after restart', lambda: c.call('GET', '/health/ready', schema='Health'), 90)
|
||||
check(meta(demo)['status'] == 'queued', 'attachment must stay queued while worker is down')
|
||||
compose('start', 'worker')
|
||||
ready = final(demo)
|
||||
check(ready['status'] == 'ready' and ready['error_code'] is None, 'demo attachment did not become ready')
|
||||
got = {v: c.call('GET', '/api/v1/attachments/%s/content?variant=%s' % (demo['id'], v), actor=bob) for v in ('original', 'thumbnail', 'crop', 'optimized')}
|
||||
check(got['original']['bytes'] == PNG, 'original changed')
|
||||
variants = {v['name']: v for v in ready['variants']}
|
||||
check(sorted(variants) == ['crop', 'optimized', 'thumbnail'], 'expected thumbnail, crop, optimized')
|
||||
check(jpeg_size(got['thumbnail']['bytes']) == (256, 160) and jpeg_size(got['crop']['bytes']) == (128, 128), 'JPEG variant dimensions')
|
||||
check(got['optimized']['bytes'][:4] == b'RIFF' and got['optimized']['bytes'][8:12] == b'WEBP', 'optimized is not WebP')
|
||||
check((variants['optimized']['width'], variants['optimized']['height']) == (320, 200), 'optimized must not upscale 320x200')
|
||||
for v in ('thumbnail', 'crop', 'optimized'):
|
||||
check(hashlib.sha256(got[v]['bytes']).hexdigest() == variants[v]['sha256'], 'variant checksum mismatch: ' + v)
|
||||
report['scenarios']['A_worker_down_restart'] = {
|
||||
'attachment_id': demo['id'], 'job_id': job_of(demo), 'message_id': linked['id'],
|
||||
'queue_before_restart': depth_before, 'queue_after_restart': depth_after,
|
||||
'content_while_queued': 409, 'seconds': round(time.monotonic() - t0, 1), 'result': 'PASS'}
|
||||
print('PASS A: worker down -> 202/409/message 201 -> API+broker restart keeps job -> worker -> ready')
|
||||
|
||||
# B. Падения в окнах отказа, временная и постоянная ошибки. Relay работает и в API-репликах:
|
||||
# его падение роняет реплику, поэтому эти два сценария идут по одному, остальные — параллельно.
|
||||
t0 = time.monotonic()
|
||||
crash = {}
|
||||
for p in CRASHES[:2]:
|
||||
crash[p] = upload('fault-%s.png' % p)
|
||||
final(crash[p], 180)
|
||||
wait_until('API after relay crash', lambda: c.call('GET', '/health/ready', schema='Health'), 90)
|
||||
crash.update({p: upload('fault-%s.png' % p) for p in CRASHES[2:]})
|
||||
transient = upload('fault-transient.png')
|
||||
invalid = upload('arith.jpg', arithmetic_jpeg(), 'image/jpeg')
|
||||
# Перестановка: устаревшее сообщение attempt=1, когда задание уже на attempt≥2.
|
||||
tjob = job_of(transient)
|
||||
wait_until('transient job retry', lambda: int(sql("select attempt from jobs where job_id='%s'" % tjob)) >= 2, 240)
|
||||
sql("insert into outbox(job_id,attempt) values('%s',1)" % tjob)
|
||||
results = {p: final(a, 300) for p, a in crash.items()}
|
||||
bad = final(invalid)
|
||||
exhausted = final(transient, 300)
|
||||
check(all(r['status'] == 'ready' for r in results.values()), 'crash scenario did not reach ready: %s' % {p: r['status'] for p, r in results.items()})
|
||||
check(bad['status'] == 'failed' and bad['error_code'] == 'invalid_image', 'arithmetic JPEG must fail with invalid_image')
|
||||
check(exhausted['status'] == 'failed' and exhausted['error_code'] == 'retry_exhausted', 'transient job must end with retry_exhausted')
|
||||
c.call('GET', '/api/v1/attachments/%s/content' % bad['id'], 409, actor=bob)
|
||||
c.call('POST', '/api/v1/chats/%s/messages' % chat['id'], 409, actor=alice, body={'text': '', 'attachment_ids': [bad['id']]},
|
||||
headers={'Idempotency-Key': 'failed-' + bad['id']})
|
||||
fired = sorted(r[0] for r in rows('select point from fault_marks'))
|
||||
check(all(p in fired for p in CRASHES), 'not all crash points fired: %s' % fired)
|
||||
per = {p: events(job_of(a)) for p, a in crash.items()}
|
||||
check(any(e == 'lease_expired' for _, e, _ in per['crash-after-claim']), 'crash before effect: lease did not expire')
|
||||
check(any(e == 'lease_expired' for _, e, _ in per['crash-after-s3']), 'crash after S3 write: lease did not expire')
|
||||
check([a for a, e, _ in per['crash-after-commit'] if e == 'done'] == [1] and any(e == 'duplicate_done' for _, e, _ in per['crash-after-commit']),
|
||||
'crash after commit: redelivery must be a no-op')
|
||||
check(any(e.startswith('duplicate') or e == 'stale_attempt' for _, e, _ in per['crash-after-publish']), 'duplicate publish not observed')
|
||||
tev = events(tjob)
|
||||
delays = [int(re.search(r'delay_ms=(\d+)', d).group(1)) for _, e, d in tev if e == 'retry_scheduled']
|
||||
check(len(delays) == 4 and [a for a, e, _ in tev if e == 'claimed'] == [1, 2, 3, 4, 5], 'transient job: expected 5 attempts, 4 backoffs')
|
||||
check(any(e == 'stale_attempt' for _, e, _ in tev), 'stale attempt=1 message was not dropped')
|
||||
check(sum(e == 'failed' for _, e, _ in events(job_of(invalid))) == 1 and not any(e == 'retry_scheduled' for _, e, _ in events(job_of(invalid))),
|
||||
'permanent error must not be retried')
|
||||
# Replay: failed → queued (новая попытка того же job_id); повтор replay и replay done-задания — no-op.
|
||||
replay = jobctl('replay', tjob, job_of(crash['crash-after-commit']))
|
||||
replayed = final(transient, 60)
|
||||
check(replayed['status'] == 'ready', 'replayed job did not become ready')
|
||||
again = jobctl('replay', tjob)
|
||||
check(again[tjob].startswith('skipped') and replay[job_of(crash['crash-after-commit'])].startswith('skipped'), 'replay of done job must be skipped')
|
||||
report['scenarios']['B_faults'] = {
|
||||
'fired_points': fired,
|
||||
'audit': {p: [list(e) for e in v] for p, v in per.items()},
|
||||
'transient': {'job_id': tjob, 'backoff_delays_ms': delays, 'audit': [list(e) for e in events(tjob)], 'replay': replay, 'replay_again': again},
|
||||
'invalid_image': {'job_id': job_of(invalid), 'audit': [list(e) for e in events(job_of(invalid))]},
|
||||
'seconds': round(time.monotonic() - t0, 1), 'result': 'PASS'}
|
||||
print('PASS B: crash windows recovered, duplicates dropped, backoff %s ms -> retry_exhausted -> replay -> ready, invalid_image not retried' % delays)
|
||||
|
||||
# C. Устаревшая job после новой версии + дубли во время и после обработки.
|
||||
t0 = time.monotonic()
|
||||
slow = upload('fault-slow.png')
|
||||
v1 = job_of(slow)
|
||||
wait_until('v1 claimed', lambda: sql("select state from jobs where job_id='%s'" % v1) == 'processing', 30)
|
||||
created = jobctl('reprocess', '--pipeline-version=2', slow['id'])
|
||||
for _ in range(3):
|
||||
sql("insert into outbox(job_id,attempt) values('%s',1)" % v1)
|
||||
wait_until('v1 done', lambda: sql("select state from jobs where job_id='%s'" % v1) == 'done', 90)
|
||||
for _ in range(2):
|
||||
sql("insert into outbox(job_id,attempt) values('%s',1)" % v1)
|
||||
time.sleep(3)
|
||||
m = meta(slow)
|
||||
v2 = job_of(slow, 2)
|
||||
v1_events, v2_events = events(v1), events(v2)
|
||||
check(sql("select pipeline_version from attachments where id='%s'" % slow['id']) == '2', 'stale v1 job rolled back the version pointer')
|
||||
check(('superseded' in [d for _, e, d in v1_events if e == 'done']), 'v1 must be committed as superseded after v2')
|
||||
v2_rows = {r[0]: r[1] for r in rows("select name,sha256 from attachment_variants where attachment_id='%s' and pipeline_version=2" % slow['id'])}
|
||||
check({v['name']: v['sha256'] for v in m['variants']} == v2_rows and len(v2_rows) == 3, 'API must serve v2 variants')
|
||||
check(sum(e == 'duplicate_in_progress' for _, e, _ in v1_events) >= 1 and sum(e == 'duplicate_done' for _, e, _ in v1_events) >= 2, 'duplicates of v1 were not dropped')
|
||||
report['scenarios']['C_stale_version'] = {'attachment_id': slow['id'], 'v1_job': v1, 'v2_job': v2, 'reprocess': created,
|
||||
'v1_audit': [list(e) for e in v1_events], 'v2_audit': [list(e) for e in v2_events],
|
||||
'pointer': 2, 'seconds': round(time.monotonic() - t0, 1), 'result': 'PASS'}
|
||||
print('PASS C: v2 committed first, late v1 committed as superseded, pointer stays 2, duplicates dropped')
|
||||
|
||||
# Инварианты по всем вложениям прогона.
|
||||
ids = [demo['id'], slow['id'], transient['id'], invalid['id']] + [a['id'] for a in crash.values()]
|
||||
report['invariants'] = invariants(ids, invalid['id'])
|
||||
report['seconds_total'] = round(time.monotonic() - started, 1)
|
||||
compose('up', '-d', '--wait', 'api-1', 'api-2', 'worker')
|
||||
if args.output:
|
||||
Path(args.output).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(args.output).write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,107 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Эксперимент уровня 4: N одновременных загрузок ~10 MiB и пик памяти контейнеров.
|
||||
|
||||
Память читается из cgroup v2 внутри контейнеров (memory.current и anon из memory.stat) каждые 0.2 с
|
||||
через docker compose exec, пока идут загрузки. anon — память процессов (heap JVM и native),
|
||||
memory.current дополнительно включает page cache временных файлов.
|
||||
Пример: python3 tests/upload_memory.py --runs 1,10,20 --output evidence/upload_memory.json
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import zlib
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from client import ROOT, Client, Failure, arguments, check, run
|
||||
|
||||
SERVICES = ('api-1', 'api-2', 'nginx', 's3')
|
||||
# Свой дедлайн: docker exec не завершает процесс в контейнере, когда клиент отключается.
|
||||
SAMPLER = ('end=$(($(date +%s)+180)); while [ $(date +%s) -lt $end ]; do '
|
||||
'echo $(cat /sys/fs/cgroup/memory.current) $(grep "^anon " /sys/fs/cgroup/memory.stat | cut -d" " -f2) || exit; sleep 0.2; done')
|
||||
|
||||
|
||||
def big_png():
|
||||
# 1800×1900 RGB из случайных байтов не сжимается: файл ≈9.8 MiB, чуть меньше лимита 10 MiB.
|
||||
def chunk(kind, data):
|
||||
return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data))
|
||||
raw = b''.join(b'\x00' + os.urandom(1800 * 3) for _ in range(1900))
|
||||
return (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 1800, 1900, 8, 2, 0, 0, 0))
|
||||
+ chunk(b'IDAT', zlib.compress(raw, 1)) + chunk(b'IEND', b''))
|
||||
|
||||
|
||||
class Sampler:
|
||||
"""Фоновое чтение памяти одного контейнера; хранит максимум за время измерения."""
|
||||
def __init__(self, service):
|
||||
self.service, self.peak_current, self.peak_anon, self.base = service, 0, 0, None
|
||||
self.proc = subprocess.Popen(['docker', 'compose', 'exec', '-T', service, 'sh', '-c', SAMPLER], cwd=ROOT,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
|
||||
threading.Thread(target=self.read, daemon=True).start()
|
||||
|
||||
def read(self):
|
||||
for line in self.proc.stdout:
|
||||
parts = line.split()
|
||||
if len(parts) != 2:
|
||||
continue
|
||||
current, anon = map(int, parts)
|
||||
if self.base is None:
|
||||
self.base = (current, anon)
|
||||
self.peak_current, self.peak_anon = max(self.peak_current, current), max(self.peak_anon, anon)
|
||||
|
||||
def stop(self):
|
||||
self.proc.terminate()
|
||||
mib = lambda v: round(v / 2**20, 1)
|
||||
return {'baseline_current_mib': mib(self.base[0]), 'baseline_anon_mib': mib(self.base[1]),
|
||||
'peak_current_mib': mib(self.peak_current), 'peak_anon_mib': mib(self.peak_anon)}
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--runs', default='1,10,20', help='comma-separated concurrency levels')
|
||||
p.add_argument('--output', default=None)
|
||||
args = arguments('Concurrent ~10 MiB uploads with peak container memory', configure)
|
||||
c = Client(args.base_url, args.ca_file, timeout=120)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
data = big_png()
|
||||
check(len(data) <= 10 * 2**20, 'fixture exceeds 10 MiB')
|
||||
results = []
|
||||
for n in [int(x) for x in args.runs.split(',')]:
|
||||
samplers = [Sampler(s) for s in SERVICES]
|
||||
time.sleep(1.5)
|
||||
|
||||
def one(_):
|
||||
local = Client(args.base_url, args.ca_file, timeout=120)
|
||||
started = time.monotonic()
|
||||
try:
|
||||
r = local.call('POST', '/api/v1/chats/%s/attachments?filename=big.png' % chat['id'], [202, 503], actor=alice,
|
||||
raw=data, headers={'Content-Type': 'image/png'})
|
||||
return r['status'], time.monotonic() - started, r['headers'].get('X-Instance-Id')
|
||||
except Failure as e:
|
||||
return str(e), time.monotonic() - started, None
|
||||
started = time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=n) as pool:
|
||||
done = list(pool.map(one, range(n)))
|
||||
wall = time.monotonic() - started
|
||||
time.sleep(1)
|
||||
memory = {s.service: s.stop() for s in samplers}
|
||||
statuses = {}
|
||||
for status, _, _ in done:
|
||||
statuses[str(status)] = statuses.get(str(status), 0) + 1
|
||||
latencies = sorted(d for _, d, _ in done)
|
||||
result = {'concurrent_uploads': n, 'file_mib': round(len(data) / 2**20, 2), 'statuses': statuses,
|
||||
'replicas_used': len({i for _, _, i in done if i}), 'wall_seconds': round(wall, 2),
|
||||
'latency_seconds': {'p50': round(latencies[len(latencies) // 2], 2), 'max': round(latencies[-1], 2)},
|
||||
'memory': memory}
|
||||
print(json.dumps(result, ensure_ascii=False))
|
||||
results.append(result)
|
||||
report = {'experiment': 'concurrent ~10 MiB PNG uploads through nginx', 'api_memory_limit': '512M per replica, JVM heap max 128 MiB',
|
||||
'max_concurrent_uploads_per_replica': 8, 'results': results}
|
||||
if args.output:
|
||||
Path(args.output).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(args.output).write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Reference in New Issue
Block a user