Apply completed lab 4 implementation
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
@@ -0,0 +1,220 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Собственные проверки вложений lab4 (уровень 4), только стандартная библиотека.
|
||||
|
||||
Покрывают: слишком большой файл, повреждённые PNG/JPEG, подмену MIME, decompression bomb,
|
||||
опасные filename, чужое/неизвестное attachment_id, вложение другого чата, постороннего пользователя,
|
||||
идемпотентность с вложениями. Ни одна пользовательская ошибка не должна давать 500.
|
||||
|
||||
--with-docker дополнительно (через docker compose из корня репозитория):
|
||||
* останавливает S3: загрузка/скачивание -> 503, текстовые сообщения и /health/ready работают,
|
||||
после неудачной загрузки не остаётся строк 'uploading' (компенсация);
|
||||
* останавливает 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=201, 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 == 201 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 = upload(PNG)['json']
|
||||
att_jpg = 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)')
|
||||
|
||||
# Варианты: в lab4 есть только original.
|
||||
c.call('GET', '/api/v1/attachments/%s/content?variant=original' % att_png['id'], actor=bob)
|
||||
c.call('GET', '/api/v1/attachments/%s/content?variant=thumbnail' % att_png['id'], 404, actor=bob)
|
||||
c.call('GET', '/api/v1/attachments/%s/content?variant=../../etc' % att_png['id'], 400, actor=bob)
|
||||
ok('variant: original 200, absent thumbnail 404, garbage 400')
|
||||
|
||||
if args.with_docker:
|
||||
# Недоступный S3: вложения 503, текстовый путь живёт, после сбоя нет зависших строк.
|
||||
compose('stop', 's3')
|
||||
try:
|
||||
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 where state='uploading'") == '0', 'failed upload left an uploading 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 uploading rows; recovered after start')
|
||||
|
||||
# Остановка реплики, принявшей загрузку: другая скачивает тот же файл.
|
||||
r = upload(PNG)
|
||||
served = r['headers']['X-Instance-Id']
|
||||
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,180 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Трек 2: внедрение рассинхронизации БД и S3 и проверка сверки (dry-run -> apply -> повтор).
|
||||
|
||||
Гипотеза: сверка находит все виды расхождений, dry-run ничего не меняет, apply исправляет только
|
||||
безопасное (старше grace и не используемое), повторный запуск ничего не находит, а свежие
|
||||
и используемые вложения остаются доступны. --cost N1,N2 дополнительно меряет стоимость обхода.
|
||||
|
||||
Сбои вносятся мимо API: в S3 через сервис s3-probe (ключи API), в БД через psql в контейнере postgres.
|
||||
Запуск из корня репозитория при работающем стенде: python3 tests/reconcile_experiment.py --output evidence/reconcile_experiment.json
|
||||
"""
|
||||
import json
|
||||
import struct
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
import zlib
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from client import ROOT, Client, arguments, check, run
|
||||
|
||||
PNG = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
# Запас на цепочку из ~5 запусков сверки (JVM ≈ 10 с каждый) после появления «свежих» объектов.
|
||||
GRACE = 90
|
||||
BUCKET = 'messenger-attachments'
|
||||
|
||||
|
||||
def tiny_png(seed):
|
||||
# 1×1 PNG с уникальным пикселем: тысячи разных маленьких файлов для замера стоимости обхода.
|
||||
def chunk(kind, data):
|
||||
return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data))
|
||||
pixel = b'\x00' + seed.to_bytes(3, 'big')
|
||||
return (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 1, 1, 8, 2, 0, 0, 0))
|
||||
+ chunk(b'IDAT', zlib.compress(pixel)) + chunk(b'IEND', b''))
|
||||
|
||||
|
||||
def compose(*args, stdin=None):
|
||||
p = subprocess.run(['docker', 'compose', *args], cwd=ROOT, input=stdin, capture_output=True, text=True)
|
||||
check(p.returncode in (0, 3), 'docker compose %s failed: %s' % (args[0], p.stderr[-300:]))
|
||||
return p.stdout
|
||||
|
||||
|
||||
def sql(query):
|
||||
return compose('exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-At', '-c', query).strip()
|
||||
|
||||
|
||||
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)"; }
|
||||
url=http://s3:8333/''' + BUCKET + '\n' + '\n'.join(commands) + '\n'
|
||||
return compose('run', '--rm', '-T', 's3-probe', stdin=script)
|
||||
|
||||
|
||||
def put(key, data):
|
||||
# data — строка или @файл внутри s3-probe.
|
||||
return 'sign | curl -K - -s -o /dev/null -w "PUT %%{http_code}\\n" --aws-sigv4 aws:amz:us-east-1:s3 -X PUT --data-binary "%s" "$url/%s"' % (data, key)
|
||||
|
||||
|
||||
def delete(key):
|
||||
return 'sign | curl -K - -s -o /dev/null -w "DELETE %%{http_code}\\n" --aws-sigv4 aws:amz:us-east-1:s3 -X DELETE "$url/%s"' % key
|
||||
|
||||
|
||||
def reconcile(*flags):
|
||||
out = compose('run', '--rm', '-T', 'reconciler', *flags)
|
||||
return json.loads(out[out.index('{'):])
|
||||
|
||||
|
||||
def snapshot():
|
||||
# Один листинг S3 (до 1000 ключей хватает до замера стоимости) и счётчики строк по состояниям.
|
||||
listing = s3(['sign | curl -K - -s --aws-sigv4 aws:amz:us-east-1:s3 "$url?list-type=2&prefix=originals/"'])
|
||||
return {'rows': sql("select state || ':' || count(*) from attachments group by state order by state").split('\n'),
|
||||
'objects': listing.count('<Key>')}
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--cost', default='', help='comma-separated object counts for traversal cost, e.g. 1000,10000')
|
||||
p.add_argument('--output', default=None)
|
||||
args = arguments('Reconciler fault-injection experiment (track 2)', configure)
|
||||
c = Client(args.base_url, args.ca_file, timeout=20)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
path = '/api/v1/chats/%s/messages' % chat['id']
|
||||
|
||||
def upload(data=PNG):
|
||||
return c.call('POST', '/api/v1/chats/%s/attachments?filename=x.png' % chat['id'], 201, actor=alice, raw=data,
|
||||
headers={'Content-Type': 'image/png'}, schema='Attachment')['json']
|
||||
|
||||
def attach(att):
|
||||
return c.call('POST', path, 201, actor=alice, body={'text': 'с вложением', 'attachment_ids': [att['id']]},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex}, schema='Message')['json']
|
||||
|
||||
key = lambda att: 'originals/' + att['id']
|
||||
# Исходные данные: используемое и неиспользуемое вложение, оба корректные.
|
||||
used_ok = upload(); used_msg = attach(used_ok)
|
||||
used_missing = upload(); attach(used_missing)
|
||||
unref_missing, size_bad, checksum_bad, row_deleted, lost_back = (upload() for _ in range(5))
|
||||
# Сбои со стороны S3 и со стороны БД.
|
||||
orphan_old = ['originals/' + str(uuid.uuid4()) for _ in range(3)]
|
||||
stale_with_object, stale_no_object = str(uuid.uuid4()), str(uuid.uuid4())
|
||||
s3([delete(key(used_missing)), delete(key(unref_missing)),
|
||||
put(key(size_bad), 'short'), # другой размер
|
||||
'head -c %d /dev/zero > /tmp/same' % len(PNG),
|
||||
put(key(checksum_bad), '@/tmp/same'), # тот же размер, другие байты
|
||||
put('originals/' + stale_with_object, 'partial')]
|
||||
+ [put(k, 'orphan') for k in orphan_old])
|
||||
sql("delete from attachments where id='%s'" % row_deleted['id']) # объект без метаданных
|
||||
sql("update attachments set state='lost' where id='%s'" % lost_back['id']) # ложная пометка lost
|
||||
for aid, k in ((stale_with_object, 'originals/' + stale_with_object), (stale_no_object, 'originals/' + stale_no_object)):
|
||||
# PUT прошёл/не прошёл, а ready не записан: «зависшая» загрузка.
|
||||
sql("insert into attachments values('%s','%s','%s','x.png','image/png',%d,'%s',1,1,'uploading','%s',now(),now())"
|
||||
% (aid, chat['id'], alice['id'], len(PNG), '0' * 64, k))
|
||||
print('faults injected; waiting %d s so they are older than grace' % (GRACE + 2))
|
||||
time.sleep(GRACE + 2)
|
||||
# Свежие объекты (моложе grace) появляются после ожидания и должны уцелеть.
|
||||
orphan_fresh = 'originals/' + str(uuid.uuid4())
|
||||
inflight = str(uuid.uuid4())
|
||||
s3([put(orphan_fresh, 'fresh')])
|
||||
sql("insert into attachments values('%s','%s','%s','x.png','image/png',1,'%s',1,1,'uploading','originals/%s',now(),now())"
|
||||
% (inflight, chat['id'], alice['id'], '0' * 64, inflight))
|
||||
fresh_used = upload(); attach(fresh_used)
|
||||
|
||||
before = snapshot()
|
||||
dry = reconcile('--dry-run', '--grace-seconds=%d' % GRACE)
|
||||
after_dry = snapshot()
|
||||
check(before == after_dry, 'dry-run changed state')
|
||||
apply1 = reconcile('--apply', '--grace-seconds=%d' % GRACE)
|
||||
apply2 = reconcile('--apply', '--grace-seconds=%d' % GRACE)
|
||||
verify = reconcile('--apply', '--grace-seconds=%d' % GRACE, '--verify-checksums')
|
||||
verify2 = reconcile('--apply', '--grace-seconds=%d' % GRACE, '--verify-checksums')
|
||||
|
||||
f = dry['findings']
|
||||
check(f.get('orphan_object') == len(orphan_old) + 1, 'orphan objects (3 injected + deleted row) not found: %s' % f)
|
||||
check(f.get('orphan_object_fresh_kept') == 1 and f.get('upload_in_progress_kept') == 1, 'fresh items not reported as kept: %s' % f)
|
||||
check(f.get('stale_upload') == 1 and f.get('stale_upload_with_object') == 1, 'stale uploads not found: %s' % f)
|
||||
check(f.get('missing_object_used') == 1 and f.get('missing_object') == 1, 'missing objects not found: %s' % f)
|
||||
check(f.get('size_mismatch') == 1 and f.get('lost_object_back_unverified') == 1, 'size mismatch / lost-back not found: %s' % f)
|
||||
check(not dry['actions'], 'dry-run reported actions')
|
||||
a = apply1['actions']
|
||||
check(a == {'objects_deleted': len(orphan_old) + 2, 'rows_deleted': 2, 'marked_lost': 3}, 'unexpected apply actions: %s' % a)
|
||||
check(not apply2['actions'], 'second apply is not idempotent: %s' % apply2['actions'])
|
||||
va = verify['actions']
|
||||
check(verify['findings'].get('checksum_mismatch') == 1 and va == {'marked_lost': 1, 'restored': 1}, 'unexpected verify run: %s %s' % (verify['findings'], va))
|
||||
check(not verify2['actions'], 'second verify run is not idempotent: %s' % verify2['actions'])
|
||||
|
||||
# Свежие и используемые вложения не тронуты и доступны; найденные потери скрыты (404), а не 500.
|
||||
for att in (used_ok, fresh_used, lost_back):
|
||||
check(c.call('GET', '/api/v1/attachments/%s/content' % att['id'], actor=bob)['bytes'] == PNG, 'healthy attachment lost')
|
||||
for att in (used_missing, unref_missing, size_bad, checksum_bad):
|
||||
c.call('GET', '/api/v1/attachments/%s/content' % att['id'], 404, actor=bob)
|
||||
check(sql("select count(*) from attachments where id in ('%s','%s')" % (used_missing['id'], inflight)) == '2', 'used or in-flight row deleted')
|
||||
history = c.call('GET', path + '?limit=100', actor=bob, schema='MessagePage')['json']['items']
|
||||
check(any(m == used_msg for m in history), 'message with attachment changed')
|
||||
check('orphan_object_fresh_kept' in apply2['findings'], 'fresh orphan was deleted')
|
||||
print('PASS: dry-run read-only, apply fixed %s, repeated apply/verify found nothing new' % json.dumps(a))
|
||||
|
||||
cost = []
|
||||
for n in [int(x) for x in args.cost.split(',') if x]:
|
||||
have = int(sql('select count(*) from attachments'))
|
||||
with ThreadPoolExecutor(max_workers=16) as pool:
|
||||
list(pool.map(lambda i: upload(tiny_png(have + i)), range(max(0, n - have))))
|
||||
total = int(sql('select count(*) from attachments'))
|
||||
plain = reconcile('--dry-run', '--grace-seconds=0')
|
||||
checks = reconcile('--dry-run', '--grace-seconds=0', '--verify-checksums')
|
||||
cost.append({'rows': total, 'dry_run': {'duration_ms': plain['duration_ms'], **plain['cost']},
|
||||
'verify_checksums': {'duration_ms': checks['duration_ms'], **checks['cost']}})
|
||||
print(json.dumps(cost[-1]))
|
||||
|
||||
report = {'experiment': 'reconciler fault injection (track 2)', 'grace_seconds': GRACE,
|
||||
'injected': {'orphan_objects_old': len(orphan_old), 'object_without_row': 1, 'orphan_object_fresh': 1,
|
||||
'stale_upload_with_object': 1, 'stale_upload_without_object': 1, 'upload_in_progress': 1,
|
||||
'missing_object_used': 1, 'missing_object_unreferenced': 1, 'size_mismatch': 1,
|
||||
'checksum_mismatch': 1, 'false_lost': 1},
|
||||
'state_before': before, 'state_after_dry_run': after_dry, 'dry_run': dry, 'apply': apply1,
|
||||
'apply_again': apply2, 'verify_checksums': verify, 'verify_again': verify2, 'state_after': snapshot(), 'cost': cost}
|
||||
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'], [201, 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