- приватный bucket SeaweedFS за S3-шлюзом, отдельные identities admin/api/reconciler, анонимный доступ запрещён - потоковый upload с проверкой PNG/JPEG (CRC, распаковка со сверкой объёма, лимит пикселей до распаковки) без буферизации тела - скачивание через авторизованный API; компенсация неудачной загрузки: сначала pending-строка, затем объект - reconciler БД ↔ S3 с grace period: stale_pending, orphan_object, missing_object, size/checksum mismatch, обратимый карантин lost - сценарии отказов S3, замер памяти загрузок, трек 2, evidence и REPORT.md
168 lines
9.3 KiB
Python
168 lines
9.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Отказы вокруг S3 и перезапуск всего стенда (уровни 3–4). Управляет Docker Compose этого каталога:
|
|
0. клиент обрывает загрузку на середине тела: компенсация убирает строку, объект не появляется;
|
|
1. S3 остановлен: upload/download → 503 быстро, метаданные и текст работают, readiness = 200;
|
|
2. S3 «завис» (docker pause): ответ 503 по таймауту API раньше таймаута LB;
|
|
3. после возврата S3 всё работает, неудачные загрузки не оставили ни строк, ни объектов; «воскресший» PUT убирает reconciler;
|
|
4. docker compose down (без -v) + up: метаданные, оригинал и прежний токен сохранены.
|
|
Запуск: python3 student-tests/failures.py --base-url http://localhost:8080"""
|
|
import hashlib
|
|
import http.client
|
|
import json
|
|
from pathlib import Path
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import urllib.parse
|
|
import uuid
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
|
from client import Client, ROOT, arguments, check, run # noqa: E402
|
|
|
|
PNG = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
|
|
|
|
|
def compose(*args, capture=False):
|
|
r = subprocess.run(['docker', 'compose', *args], cwd=ROOT, text=True, capture_output=True)
|
|
check(r.returncode == 0, 'docker compose %s: %s' % (args[0], r.stderr.strip().splitlines()[-1:]))
|
|
return r.stdout if capture else None
|
|
|
|
|
|
def sql(query):
|
|
return compose('exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-tAc', query, capture=True).strip()
|
|
|
|
|
|
def reconcile(*flags):
|
|
for _ in range(3): # фоновый reconciler держит advisory lock — подождать и повторить
|
|
out = compose('run', '--rm', '--no-deps', '-T', 'reconciler', 'node', 'src/main.ts', 'reconcile', *flags, capture=True)
|
|
summary = json.loads(out.strip().splitlines()[-1])
|
|
if 'skipped' not in summary:
|
|
return summary
|
|
time.sleep(2)
|
|
raise AssertionError('reconciler lock is busy')
|
|
|
|
|
|
def abort_upload(base, token, chat):
|
|
"""Отправить заголовки и половину тела, затем закрыть соединение."""
|
|
url = urllib.parse.urlsplit(base)
|
|
conn = http.client.HTTPConnection(url.hostname, url.port, timeout=10)
|
|
conn.putrequest('POST', '/api/v1/chats/' + chat + '/attachments?filename=abort.png')
|
|
conn.putheader('Authorization', 'Bearer ' + token)
|
|
conn.putheader('Content-Type', 'image/png')
|
|
conn.putheader('Content-Length', str(len(PNG)))
|
|
conn.endheaders()
|
|
conn.send(PNG[:len(PNG) // 2])
|
|
time.sleep(0.5) # строка pending и S3 PUT уже начаты
|
|
conn.close()
|
|
return len(PNG) // 2
|
|
|
|
|
|
def wait_ready(c, seconds=90):
|
|
deadline = time.monotonic() + seconds
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
if c.call('GET', '/health/ready', [200, 503])['status'] == 200:
|
|
return
|
|
except AssertionError:
|
|
pass
|
|
time.sleep(1)
|
|
raise AssertionError('stand not ready')
|
|
|
|
|
|
def recover(c, path, actor, seconds=60):
|
|
"""Время до первого успешного скачивания после возврата S3."""
|
|
start = time.monotonic()
|
|
while c.call('GET', path, [200, 503], actor=actor)['status'] != 200:
|
|
check(time.monotonic() - start < seconds, 'S3 path did not recover')
|
|
time.sleep(0.5)
|
|
return time.monotonic() - start
|
|
|
|
|
|
def main():
|
|
args = arguments('S3 outage, S3 hang and full stand restart')
|
|
c = Client(args.base_url, args.ca_file, timeout=30)
|
|
alice, bob, _, chat = c.bootstrap()
|
|
up = '/api/v1/chats/' + chat['id'] + '/attachments?filename=outage.png'
|
|
send = '/api/v1/chats/' + chat['id'] + '/messages'
|
|
hdr = {'Content-Type': 'image/png'}
|
|
att = c.call('POST', up, 201, actor=alice, raw=PNG, headers=hdr, schema='Attachment')['json']
|
|
content = '/api/v1/attachments/' + att['id'] + '/content'
|
|
pending_before = int(sql("SELECT count(*) FROM attachments WHERE state = 'pending'"))
|
|
log = []
|
|
|
|
def step(name, r):
|
|
log.append('%-52s %d %5d ms' % (name, r['status'], r['elapsed'] * 1000))
|
|
|
|
# 0. Обрыв загрузки клиентом. Перед этим --apply с grace 0 (кроме теста никто не пишет): чистая база для сравнения.
|
|
reconcile('--grace=0', '--apply')
|
|
sent = abort_upload(c.base, alice['token'], chat['id'])
|
|
time.sleep(1.5)
|
|
left = sql("SELECT count(*) FROM attachments WHERE chat_id = '%s' AND filename = 'abort.png'" % chat['id'])
|
|
after = reconcile('--grace=0')
|
|
log.append('client abort после %d из %d байт: строк abort.png %s, сверка: %s' % (sent, len(PNG), left, json.dumps(after['findings'])))
|
|
check(left == '0' and not after['findings'], 'aborted upload left a row or an object')
|
|
|
|
# 1. S3 остановлен.
|
|
compose('stop', 's3')
|
|
try:
|
|
step('S3 stopped: /health/ready (S3 не критичен)', c.call('GET', '/health/ready', 200))
|
|
for i in range(3):
|
|
step('S3 stopped: upload #%d' % (i + 1), c.call('POST', up, 503, actor=alice, raw=PNG, headers=hdr))
|
|
step('S3 stopped: download', c.call('GET', content, 503, actor=bob))
|
|
step('S3 stopped: metadata (только БД)', c.call('GET', '/api/v1/attachments/' + att['id'], 200, actor=bob, schema='Attachment'))
|
|
step('S3 stopped: text message', c.call('POST', send, 201, actor=alice, body={'text': 'S3 недоступен'},
|
|
headers={'Idempotency-Key': uuid.uuid4().hex}, schema='Message'))
|
|
step('S3 stopped: message with ready attachment', c.call('POST', send, 201, actor=alice, body={'text': '', 'attachment_ids': [att['id']]},
|
|
headers={'Idempotency-Key': uuid.uuid4().hex}, schema='Message'))
|
|
finally:
|
|
compose('start', 's3')
|
|
# Компенсация сначала удаляет pending-строку (БД доступна), затем объект: S3 недоступен, но объекта и нет — PUT не прошёл.
|
|
leftover = int(sql("SELECT count(*) FROM attachments WHERE state = 'pending'")) - pending_before
|
|
log.append('pending-строк после 3 неудачных загрузок: %d' % leftover)
|
|
check(leftover == 0, 'compensation left pending rows')
|
|
|
|
log.append('S3 started: download снова 200 через %.1f s' % recover(c, content, bob))
|
|
|
|
# 2. S3 завис: TCP-соединения не отвечают.
|
|
c.call('GET', content, 200, actor=bob) # прогреть keep-alive соединения API → S3
|
|
compose('pause', 's3')
|
|
try:
|
|
step('S3 paused: download (таймаут сокета S3 8 с)', c.call('GET', content, 503, actor=bob))
|
|
step('S3 paused: upload', c.call('POST', up, 503, actor=alice, raw=PNG, headers=hdr))
|
|
step('S3 paused: text message', c.call('POST', send, 201, actor=alice, body={'text': 'S3 завис'},
|
|
headers={'Idempotency-Key': uuid.uuid4().hex}, schema='Message'))
|
|
finally:
|
|
compose('unpause', 's3')
|
|
|
|
# 3. S3 вернулся.
|
|
log.append('S3 unpaused: download снова 200 через %.1f s' % recover(c, content, bob))
|
|
step('S3 back: upload', c.call('POST', up, 201, actor=alice, raw=PNG, headers=hdr, schema='Attachment'))
|
|
r = c.call('GET', content, 200, actor=bob)
|
|
check(r['bytes'] == PNG, 'original changed')
|
|
step('S3 back: download old attachment', r)
|
|
# Ожидаемо: пусто или orphan_object — PUT, который S3 буферизовал во время pause и выполнил после того,
|
|
# как API сдался и компенсация уже удалила строку и объект (объект «воскрес»).
|
|
dry = reconcile('--grace=0')
|
|
log.append('reconcile dry-run --grace=0: %s' % json.dumps(dry['findings'], ensure_ascii=False))
|
|
check(set(dry['findings']) <= {'orphan_object'}, 'unexpected findings')
|
|
fixed = reconcile('--grace=0', '--apply')
|
|
again = reconcile('--grace=0')
|
|
log.append('reconcile --apply: applied=%d; повтор: %s' % (fixed['applied'], json.dumps(again['findings'])))
|
|
check(not again['findings'], 'reconciler left inconsistencies')
|
|
|
|
# 4. Полный перезапуск стенда с сохранением volumes: down удаляет контейнеры и сети, не volumes.
|
|
compose('down')
|
|
compose('up', '-d', '--wait')
|
|
wait_ready(c)
|
|
r = c.call('GET', content, 200, actor=bob) # прежний токен
|
|
check(r['bytes'] == PNG and hashlib.sha256(r['bytes']).hexdigest() == att['sha256'], 'original lost after down/up')
|
|
step('down + up -d: download with old token', r)
|
|
meta = c.call('GET', '/api/v1/attachments/' + att['id'], 200, actor=bob, schema='Attachment')['json']
|
|
check(meta == att, 'metadata changed after restart')
|
|
print('\n'.join(log))
|
|
print('PASS: S3 outage/hang degrade only attachments (503), compensation + reconciler clean up, full restart keeps data')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
run(main)
|