forked from mtusi2026/mtusi2026lab4
feat: add s3 readiness and orphan object reconciler
This commit is contained in:
Executable
+39
@@ -0,0 +1,39 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
bucket="${S3_BUCKET:-messenger-attachments}"
|
||||
key="attachments/orphan-$(date +%s)"
|
||||
|
||||
mc_api() {
|
||||
docker compose run --rm --no-deps -T -e BUCKET="$bucket" -e KEY="$key" --entrypoint sh s3-init -c "
|
||||
cd /run/secrets
|
||||
export MC_HOST_api=\"http://\$(cat s3_access_key_id):\$(cat s3_secret_access_key)@s3:9000\"
|
||||
$1"
|
||||
}
|
||||
|
||||
run() {
|
||||
docker compose run --rm --no-deps -T reconciler node dist/reconcile.js "$@"
|
||||
}
|
||||
|
||||
echo "## Отказ между S3 и БД: объект есть, строки нет"
|
||||
mc_api 'echo orphan > /tmp/o && mc cp -q /tmp/o "api/$BUCKET/$KEY" >/dev/null && mc stat "api/$BUCKET/$KEY" | head -1'
|
||||
|
||||
echo
|
||||
echo "## Свежий объект, grace 3600 с, --apply: не удалён"
|
||||
run --apply --grace-seconds=3600
|
||||
mc_api 'mc stat "api/$BUCKET/$KEY" >/dev/null && echo "объект на месте"'
|
||||
|
||||
sleep 3
|
||||
echo
|
||||
echo "## Dry-run, grace 1 с: найден, не удалён"
|
||||
run --grace-seconds=1
|
||||
mc_api 'mc stat "api/$BUCKET/$KEY" >/dev/null && echo "объект на месте"'
|
||||
|
||||
echo
|
||||
echo "## --apply, grace 1 с: удалён только он"
|
||||
run --apply --grace-seconds=1
|
||||
mc_api 'mc stat "api/$BUCKET/$KEY" >/dev/null 2>&1 && echo "объект всё ещё есть" || echo "объект удалён"'
|
||||
|
||||
echo
|
||||
echo "## Повторный запуск: удалять нечего"
|
||||
run --apply --grace-seconds=1
|
||||
Executable
+79
@@ -0,0 +1,79 @@
|
||||
#!/usr/bin/env python3
|
||||
import hashlib
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client
|
||||
|
||||
STATE = Path(os.environ.get('S3_OUTAGE_STATE', '/tmp/s3-outage-state.json'))
|
||||
SAMPLE = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
HOST = os.environ.get('LB_HOST', 'lb')
|
||||
PORT = int(os.environ.get('LB_PORT', '8080'))
|
||||
|
||||
|
||||
def request(method, path, token=None, body=None, content_type=None, extra=None):
|
||||
headers = dict(extra or {})
|
||||
if token:
|
||||
headers['Authorization'] = 'Bearer ' + token
|
||||
if content_type:
|
||||
headers['Content-Type'] = content_type
|
||||
conn = http.client.HTTPConnection(HOST, PORT, timeout=30)
|
||||
started = time.monotonic()
|
||||
conn.request(method, path, body=body, headers=headers)
|
||||
response = conn.getresponse()
|
||||
data = response.read()
|
||||
elapsed = time.monotonic() - started
|
||||
conn.close()
|
||||
return response, data, elapsed
|
||||
|
||||
|
||||
def show(label, response, data, elapsed):
|
||||
code = ''
|
||||
if response.status >= 400:
|
||||
code = json.loads(data)['error']['code']
|
||||
print('%-32s -> %s %-12s %5.2fs X-Instance-Id=%s' % (label, response.status, code, elapsed, 'yes' if response.getheader('X-Instance-Id') else 'no'))
|
||||
|
||||
|
||||
def prepare():
|
||||
client = Client('http://%s:%d' % (HOST, PORT))
|
||||
alice = client.user('alice')
|
||||
chat = client.call('POST', '/api/v1/chats', 201, actor=alice, body={'title': 'outage', 'member_ids': [alice['id']]}, schema='Chat')['json']
|
||||
attachment, _ = client.attachment(alice, chat)
|
||||
STATE.write_text(json.dumps({'token': alice['token'], 'chat': chat['id'], 'attachment': attachment['id']}))
|
||||
|
||||
|
||||
def during():
|
||||
state = json.loads(STATE.read_text())
|
||||
token, chat, attachment = state['token'], state['chat'], state['attachment']
|
||||
show('GET /health/live', *request('GET', '/health/live'))
|
||||
show('GET /health/ready', *request('GET', '/health/ready'))
|
||||
show('GET /attachments/{id}', *request('GET', '/api/v1/attachments/' + attachment, token))
|
||||
show('GET /attachments/{id}/content', *request('GET', '/api/v1/attachments/' + attachment + '/content', token))
|
||||
show('POST /attachments', *request('POST', '/api/v1/chats/' + chat + '/attachments?filename=down.png', token, SAMPLE, 'image/png'))
|
||||
show('POST /messages (текст)', *request('POST', '/api/v1/chats/' + chat + '/messages', token, json.dumps({'text': 'пока S3 недоступен'}), 'application/json', {'Idempotency-Key': uuid.uuid4().hex}))
|
||||
|
||||
|
||||
def after():
|
||||
state = json.loads(STATE.read_text())
|
||||
token, attachment = state['token'], state['attachment']
|
||||
deadline = time.monotonic() + 30
|
||||
while True:
|
||||
response, data, elapsed = request('GET', '/health/ready')
|
||||
if response.status == 200 or time.monotonic() > deadline:
|
||||
break
|
||||
time.sleep(0.5)
|
||||
show('GET /health/ready', response, data, elapsed)
|
||||
response, data, elapsed = request('GET', '/api/v1/attachments/' + attachment + '/content', token)
|
||||
show('GET /attachments/{id}/content', response, data, elapsed)
|
||||
print('sha256 совпадает:', hashlib.sha256(data).hexdigest() == hashlib.sha256(SAMPLE).hexdigest())
|
||||
STATE.unlink()
|
||||
|
||||
|
||||
{'prepare': prepare, 'during': during, 'after': after}[sys.argv[1]]()
|
||||
Executable
+18
@@ -0,0 +1,18 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
mode="${1:-stop}"
|
||||
python3 scripts/s3-outage.py prepare
|
||||
case "$mode" in
|
||||
stop) docker compose stop s3 2>&1 | grep -v Container || true ;;
|
||||
pause) docker compose pause s3 2>&1 | grep -v Container || true ;;
|
||||
*) echo "usage: s3-outage.sh stop|pause" >&2; exit 2 ;;
|
||||
esac
|
||||
echo "## S3: $mode"
|
||||
python3 scripts/s3-outage.py during
|
||||
case "$mode" in
|
||||
stop) docker compose start s3 2>&1 | grep -v Container || true ;;
|
||||
pause) docker compose unpause s3 2>&1 | grep -v Container || true ;;
|
||||
esac
|
||||
echo "## S3 восстановлен"
|
||||
python3 scripts/s3-outage.py after
|
||||
Reference in New Issue
Block a user