Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
181 lines
11 KiB
Python
181 lines
11 KiB
Python
#!/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)
|