222 lines
8.0 KiB
Python
222 lines
8.0 KiB
Python
"""Уровень 4: отказ между S3 PUT и COMMIT не оставляет вечных объектов.
|
|
|
|
1. db_error_after_s3_put — процесс API (FAULT_INJECTION, порт 8091 внутри
|
|
контейнера реплики) теряет БД после PUT -> 503, фоновая компенсация
|
|
сама удаляет объект и intent;
|
|
2. crash_after_s3_put — процесс (порт 8090) умирает после PUT до COMMIT ->
|
|
остаются intent и объект; janitor после grace удаляет оба;
|
|
3. свежий intent (моложе grace, «загрузка в процессе») janitor не трогает;
|
|
готовое вложение после janitor скачивается побайтно.
|
|
|
|
docker compose --profile tools run --rm tester python3 student-tests/upload_compensation.py
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
import uuid
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parent.parent
|
|
BASE = os.environ.get('BASE_URL', 'http://lb:8080').rstrip('/')
|
|
PROJECT = os.environ.get('COMPOSE_PROJECT', 'messenger-lab4')
|
|
SAMPLE = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
|
GRACE = 20
|
|
|
|
failed = 0
|
|
|
|
|
|
def check(label, ok, detail=''):
|
|
global failed
|
|
failed += not ok
|
|
print(f"{'OK ' if ok else 'FAIL'} {label} {detail}".rstrip(), flush=True)
|
|
|
|
|
|
def docker(*args, stdin=None) -> str:
|
|
r = subprocess.run(['docker', *args], capture_output=True, text=True, input=stdin)
|
|
if r.returncode:
|
|
raise RuntimeError(f'docker {args[0]} failed: {r.stderr.strip()[-300:]}')
|
|
return r.stdout.strip()
|
|
|
|
|
|
def container(service: str) -> str:
|
|
return docker('ps', '-q', '--filter', f'label=com.docker.compose.project={PROJECT}',
|
|
'--filter', f'label=com.docker.compose.service={service}').split()[0]
|
|
|
|
|
|
API = DB = ''
|
|
|
|
|
|
def psql(sql: str) -> str:
|
|
return docker('exec', DB, 'psql', '-U', 'messenger', '-d', 'messenger', '-tAc', sql)
|
|
|
|
|
|
def intents() -> set[str]:
|
|
return set(filter(None, psql('SELECT object_key FROM upload_intents').splitlines()))
|
|
|
|
|
|
def s3_exists(*keys: str) -> list:
|
|
code = """
|
|
import asyncio, json, sys
|
|
from app.storage import storage
|
|
async def main():
|
|
await storage.start()
|
|
out = [await storage.exists(k) for k in json.load(sys.stdin)]
|
|
await storage.close()
|
|
print(json.dumps(out))
|
|
asyncio.run(main())
|
|
"""
|
|
return json.loads(docker('exec', '-i', API, 'python', '-c', code, stdin=json.dumps(list(keys))))
|
|
|
|
|
|
def run_janitor(grace: int) -> int:
|
|
code = f"""
|
|
import asyncio
|
|
from app.attachments import cleanup_stale_uploads
|
|
from app.storage import storage
|
|
async def main():
|
|
await storage.start()
|
|
print(await cleanup_stale_uploads({grace}))
|
|
await storage.close()
|
|
asyncio.run(main())
|
|
"""
|
|
return int(docker('exec', API, 'python', '-c', code).splitlines()[-1])
|
|
|
|
|
|
def http(method, url, data=None, headers=None, timeout=30):
|
|
req = urllib.request.Request(url, data=data, headers=headers or {}, method=method)
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
return r.status, r.read()
|
|
except urllib.error.HTTPError as e:
|
|
return e.code, e.read()
|
|
|
|
|
|
class Client:
|
|
def __init__(self, base):
|
|
self.base = base
|
|
|
|
def call(self, method, path, body=None, auth=None, raw=None, ctype=None):
|
|
h = {}
|
|
if auth:
|
|
h['Authorization'] = auth
|
|
if body is not None:
|
|
raw, ctype = json.dumps(body).encode(), 'application/json'
|
|
if ctype:
|
|
h['Content-Type'] = ctype
|
|
s, data = http(method, self.base + '/api/v1' + path, raw, h)
|
|
try:
|
|
return s, json.loads(data)
|
|
except ValueError:
|
|
return s, data
|
|
|
|
def upload(self, auth, chat_id):
|
|
return self.call('POST', f'/chats/{chat_id}/attachments?filename=c.png',
|
|
auth=auth, raw=SAMPLE, ctype='image/png')
|
|
|
|
|
|
def start_faulty(mode: str, port: int) -> Client:
|
|
docker('exec', '-d', '-e', f'FAULT_INJECTION={mode}', '-e', f'APP_PORT={port}',
|
|
'-e', 'JANITOR_INTERVAL_SECONDS=3600', API, 'python', '-m', 'app.server')
|
|
name = docker('inspect', '-f', '{{.Name}}', API).lstrip('/')
|
|
base = f'http://{name}:{port}'
|
|
for _ in range(60):
|
|
try:
|
|
if http('GET', base + '/health/ready', timeout=2)[0] == 200:
|
|
return Client(base)
|
|
except OSError:
|
|
pass
|
|
time.sleep(0.5)
|
|
raise RuntimeError(f'faulty process {mode} did not start')
|
|
|
|
|
|
def stop_faulty() -> None:
|
|
"""Kill the extra app.server processes (not PID 1, the real replica)."""
|
|
code = """
|
|
import os, signal
|
|
for p in filter(str.isdigit, os.listdir('/proc')):
|
|
if int(p) in (1, os.getpid()):
|
|
continue
|
|
try:
|
|
cmd = open(f'/proc/{p}/cmdline', 'rb').read()
|
|
except OSError:
|
|
continue
|
|
if b'app.server' in cmd:
|
|
os.kill(int(p), signal.SIGKILL)
|
|
"""
|
|
docker('exec', API, 'python', '-c', code)
|
|
|
|
|
|
def main() -> int:
|
|
global API, DB
|
|
API, DB = container('api'), container('db')
|
|
lb = Client(BASE)
|
|
|
|
name = 'comp' + uuid.uuid4().hex[:12]
|
|
password = 'compensation-password-1'
|
|
lb.call('POST', '/users', {'username': name, 'display_name': 'Comp', 'password': password})
|
|
basic = 'Basic ' + base64.b64encode(f'{name}:{password}'.encode()).decode()
|
|
auth = 'Bearer ' + lb.call('POST', '/auth/sessions', auth=basic)[1]['token']
|
|
me = lb.call('GET', '/users/me', auth=auth)[1]
|
|
chat = lb.call('POST', '/chats', {'title': 'compensation', 'member_ids': [me['id']]}, auth=auth)[1]
|
|
ready = lb.upload(auth, chat['id'])[1]
|
|
|
|
try:
|
|
# 1. DB lost after PUT -> 503 + background compensation
|
|
before = intents()
|
|
s, _ = start_faulty('db_error_after_s3_put', 8091).upload(auth, chat['id'])
|
|
time.sleep(2)
|
|
check('db_error_after_s3_put: 503', s == 503, f'({s})')
|
|
check('db_error_after_s3_put: компенсация убрала intent', intents() - before == set())
|
|
|
|
# 2. crash after PUT -> intent + object stay
|
|
before = intents()
|
|
try:
|
|
s, _ = start_faulty('crash_after_s3_put', 8090).upload(auth, chat['id'])
|
|
result = f'HTTP {s}'
|
|
except OSError as exc:
|
|
result = type(exc).__name__
|
|
crash_keys = sorted(intents() - before)
|
|
check('crash_after_s3_put: клиент не получил 201', '201' not in result, f'({result})')
|
|
check('crash_after_s3_put: остались intent и объект',
|
|
len(crash_keys) == 1 and s3_exists(*crash_keys) == [True])
|
|
finally:
|
|
stop_faulty()
|
|
|
|
check('janitor до grace ничего не удаляет',
|
|
run_janitor(GRACE) == 0 and set(crash_keys) <= intents())
|
|
|
|
print(f'-- ждём grace {GRACE + 1} s', flush=True)
|
|
time.sleep(GRACE + 1)
|
|
|
|
# 3. fresh in-flight upload (younger than grace) must survive
|
|
inflight = f'originals/{uuid.uuid4().hex}'
|
|
psql(f"INSERT INTO upload_intents (object_key, attachment_id, chat_id) "
|
|
f"VALUES ('{inflight}', '{uuid.uuid4()}', '{chat['id']}')")
|
|
|
|
cleaned = run_janitor(GRACE)
|
|
left = intents()
|
|
check('janitor после grace удалил intent от crash', cleaned >= 1 and not set(crash_keys) & left,
|
|
f'(cleaned={cleaned})')
|
|
check('janitor удалил объект от crash', s3_exists(*crash_keys) == [False])
|
|
check('свежий intent не тронут', inflight in left)
|
|
psql(f"DELETE FROM upload_intents WHERE object_key = '{inflight}'")
|
|
|
|
s, body = lb.call('GET', f"/attachments/{ready['id']}/content", auth=auth)
|
|
check('готовое вложение цело', s == 200 and hashlib.sha256(body).hexdigest() == ready['sha256'])
|
|
|
|
print('PASS: компенсация и janitor не оставляют вечных объектов' if not failed
|
|
else f'FAIL: {failed} проверок не прошли')
|
|
return 1 if failed else 0
|
|
|
|
|
|
if __name__ == '__main__':
|
|
sys.exit(main())
|