forked from mtusi2026/mtusi2026lab4
238 lines
12 KiB
Python
238 lines
12 KiB
Python
"""Настоящие fault injection в PostgreSQL и S3, затем dry-run/apply/повтор."""
|
||
import argparse
|
||
import base64
|
||
from datetime import datetime, timezone
|
||
import hashlib
|
||
import http.client
|
||
import io
|
||
import json
|
||
import os
|
||
from pathlib import Path
|
||
import sys
|
||
import time
|
||
import urllib.request
|
||
import urllib.error
|
||
import uuid
|
||
|
||
import psycopg
|
||
from psycopg.rows import dict_row
|
||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||
from client import Client
|
||
from src.config import DATABASE_URL, S3_ENDPOINT, S3_BUCKET
|
||
from src.storage import ObjectStore, PREFIX, lock_attachment, unlock_attachment
|
||
from src.reconcile import run
|
||
|
||
|
||
def main():
|
||
p = argparse.ArgumentParser()
|
||
p.add_argument('mode', choices=['privacy', 'interrupted', 's3-failure', 'reconcile', 'cost'])
|
||
p.add_argument('--sizes', nargs='+', type=int, default=[100, 500, 1000])
|
||
p.add_argument('--failed-chat-id', type=uuid.UUID)
|
||
args = p.parse_args()
|
||
c = Client(os.getenv('BASE_URL', 'http://localhost:8080'), timeout=30)
|
||
alice, bob, _, chat = c.bootstrap()
|
||
data = (Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png').read_bytes()
|
||
digest = hashlib.sha256(data).hexdigest()
|
||
md5 = base64.b64encode(hashlib.md5(data).digest()).decode()
|
||
storage = ObjectStore()
|
||
records = {}
|
||
|
||
def scan(grace=20, apply=False):
|
||
return run(grace, apply, chat['id'])
|
||
|
||
def put(key):
|
||
storage.put(io.BytesIO(data), key, len(data), 'image/png', digest, md5)
|
||
|
||
def upload(name, code=201):
|
||
return c.call('POST', '/api/v1/chats/'+chat['id']+'/attachments?filename='+name,
|
||
code, actor=alice, raw=data, headers={'Content-Type': 'image/png'},
|
||
schema='Attachment' if code == 201 else None)
|
||
|
||
def row(identifier):
|
||
with psycopg.connect(DATABASE_URL, row_factory=dict_row) as db:
|
||
return db.execute('SELECT * FROM attachments WHERE id=%s', (identifier,)).fetchone()
|
||
|
||
def seed(status='ready', active=False):
|
||
identifier = uuid.uuid4()
|
||
key = PREFIX + chat['id'] + '/' + str(identifier)
|
||
put(key)
|
||
with psycopg.connect(DATABASE_URL) as db:
|
||
db.execute("INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,"
|
||
"object_key,status,lease_until,created_at) VALUES (%s,%s,%s,'synthetic.png','image/png',"
|
||
"%s,%s,%s,%s,clock_timestamp()+%s*interval '1 second',clock_timestamp()-interval '15 minutes')",
|
||
(identifier, chat['id'], alice['id'], len(data), digest, key, status, 120 if active else -900))
|
||
return dict(id=identifier, key=key)
|
||
|
||
if args.mode == 'interrupted':
|
||
from urllib.parse import urlsplit
|
||
base = urlsplit(c.base)
|
||
connection = http.client.HTTPConnection(base.hostname, base.port or 80, timeout=5)
|
||
connection.putrequest('POST', '/api/v1/chats/'+chat['id']+'/attachments?filename=interrupted.png')
|
||
connection.putheader('Authorization', 'Bearer '+alice['token'])
|
||
connection.putheader('Content-Type', 'image/png')
|
||
connection.putheader('Content-Length', '4096')
|
||
connection.endheaders()
|
||
connection.send(data[:16])
|
||
connection.close() # Не отправляем остаток и не завершаем корректный HTTP body.
|
||
time.sleep(.5)
|
||
with psycopg.connect(DATABASE_URL) as db:
|
||
count = db.execute('SELECT count(*) FROM attachments WHERE chat_id=%s', (chat['id'],)).fetchone()[0]
|
||
objects = list(storage.objects(PREFIX+chat['id']+'/'))
|
||
assert count == 0 and not objects
|
||
print(json.dumps(dict(status='PASS', sent_bytes=16, declared_bytes=4096, metadata=0, objects=0)))
|
||
return
|
||
|
||
if args.mode == 'privacy':
|
||
original = upload('private.png')['json']
|
||
key = row(original['id'])['object_key']
|
||
try:
|
||
urllib.request.urlopen(S3_ENDPOINT+'/'+S3_BUCKET+'/'+key, timeout=5)
|
||
except urllib.error.HTTPError as exc:
|
||
assert exc.code == 403
|
||
else:
|
||
raise AssertionError('Anonymous object GET succeeded')
|
||
buckets = storage.client.list_buckets().get('Buckets', [])
|
||
assert all(bucket['Name'] == S3_BUCKET for bucket in buckets), 'Foreign bucket listed'
|
||
# MinIO может вернуть отфильтрованный ListBuckets, а не AccessDenied.
|
||
try:
|
||
storage.client.create_bucket(Bucket='forbidden-'+uuid.uuid4().hex)
|
||
except Exception as exc:
|
||
assert getattr(exc, 'response', {}).get('Error', {}).get('Code') == 'AccessDenied'
|
||
else:
|
||
raise AssertionError('API credential has bucket administration rights')
|
||
from urllib.parse import urlsplit
|
||
endpoint = urlsplit(S3_ENDPOINT)
|
||
console = f'{endpoint.scheme}://{endpoint.hostname}:9001/'
|
||
try:
|
||
urllib.request.urlopen(console, timeout=2)
|
||
except urllib.error.URLError:
|
||
pass
|
||
else:
|
||
raise AssertionError('Admin console is reachable from another container')
|
||
print(json.dumps(dict(status='PASS', anonymous_get=403, bucket_list='filtered', create_bucket='AccessDenied',
|
||
console='not reachable', attachment_id=original['id'])))
|
||
return
|
||
|
||
if args.mode == 's3-failure':
|
||
# Оператор временно установил deny PUT policy; GET/LIST/readiness доступны.
|
||
upload('fault-s3.png', 503)
|
||
with psycopg.connect(DATABASE_URL, row_factory=dict_row) as db:
|
||
failed = db.execute("SELECT * FROM attachments WHERE chat_id=%s AND filename='fault-s3.png'",
|
||
(chat['id'],)).fetchone()
|
||
assert failed and failed['status'] == 'uploading'
|
||
assert storage.head(failed['object_key']) is None
|
||
print(json.dumps(dict(status='PASS', http_status=503, metadata='uploading', object='absent',
|
||
chat_id=chat['id'], attachment_id=str(failed['id']))))
|
||
return
|
||
|
||
if args.mode == 'cost':
|
||
results, made = [], 0
|
||
for size in args.sizes:
|
||
while made < size:
|
||
seed()
|
||
made += 1
|
||
scan(600, False) # Прогрев обхода.
|
||
for repeat in range(3):
|
||
report = scan(600, False)
|
||
report.update(dataset_added=size, repetition=repeat+1)
|
||
results.append(report)
|
||
print(json.dumps(dict(status='PASS', scans=results)))
|
||
return
|
||
|
||
# Используемое вложение: сообщение и готовый объект должны пережить очистку.
|
||
if args.failed_chat_id:
|
||
with psycopg.connect(DATABASE_URL, row_factory=dict_row) as db:
|
||
failure = db.execute("SELECT * FROM attachments WHERE chat_id=%s AND filename='fault-s3.png'",
|
||
(args.failed_chat_id,)).fetchone()
|
||
assert failure and failure['status'] == 'uploading'
|
||
db.execute("UPDATE attachments SET created_at=clock_timestamp()-interval '15 minutes',"
|
||
"lease_until=clock_timestamp()-interval '15 minutes' WHERE id=%s", (failure['id'],))
|
||
dry_failure = run(20, False, args.failed_chat_id)
|
||
assert row(failure['id'])
|
||
fixed_failure = run(20, True, args.failed_chat_id)
|
||
assert row(failure['id']) is None and storage.head(failure['object_key']) is None
|
||
records['s3_failure_compensation'] = dict(dry_run=dry_failure, apply=fixed_failure, metadata_removed=True)
|
||
used = upload('used.png')['json']
|
||
message = c.message(bob, chat, '', attachments=[used['id']])['json']
|
||
used_row = row(used['id'])
|
||
with psycopg.connect(DATABASE_URL) as db:
|
||
db.execute("UPDATE attachments SET created_at=clock_timestamp()-interval '15 minutes' WHERE id=%s",
|
||
(used['id'],))
|
||
|
||
# Ошибка UPDATE ready ПОСЛЕ успешного S3 PUT. Только тестовое имя файла.
|
||
with psycopg.connect(DATABASE_URL) as db:
|
||
db.execute("CREATE OR REPLACE FUNCTION lab4_fail_ready() RETURNS trigger LANGUAGE plpgsql AS $$ "
|
||
"BEGIN IF NEW.filename='fault-db.png' AND NEW.status='ready' THEN "
|
||
"RAISE EXCEPTION 'synthetic DB failure'; END IF; RETURN NEW; END; $$")
|
||
db.execute('CREATE TRIGGER lab4_test_fail BEFORE UPDATE ON attachments '
|
||
'FOR EACH ROW EXECUTE FUNCTION lab4_fail_ready()')
|
||
try:
|
||
upload('fault-db.png', 503)
|
||
with psycopg.connect(DATABASE_URL, row_factory=dict_row) as db:
|
||
failed = db.execute("SELECT * FROM attachments WHERE chat_id=%s AND filename='fault-db.png'",
|
||
(chat['id'],)).fetchone()
|
||
assert failed and failed['status'] == 'uploading' and storage.head(failed['object_key'])
|
||
immediate = scan(20, True)
|
||
assert row(failed['id']) and storage.head(failed['object_key'])
|
||
records['after_put_db_failure'] = dict(http_status=503, metadata='uploading', object='present',
|
||
immediate_cleanup=immediate)
|
||
with psycopg.connect(DATABASE_URL) as db:
|
||
db.execute("UPDATE attachments SET lease_until=clock_timestamp()-interval '15 minutes',"
|
||
"created_at=clock_timestamp()-interval '15 minutes' WHERE id=%s", (failed['id'],))
|
||
finally:
|
||
with psycopg.connect(DATABASE_URL) as db:
|
||
db.execute('DROP TRIGGER IF EXISTS lab4_test_fail ON attachments')
|
||
db.execute('DROP FUNCTION IF EXISTS lab4_fail_ready()')
|
||
|
||
missing = upload('missing.png')['json']
|
||
missing_message = c.message(alice, chat, '', attachments=[missing['id']])['json']
|
||
missing_row = row(missing['id'])
|
||
storage.delete(missing_row['object_key'])
|
||
with psycopg.connect(DATABASE_URL) as db:
|
||
db.execute("UPDATE attachments SET created_at=clock_timestamp()-interval '15 minutes' WHERE id=%s",
|
||
(missing['id'],))
|
||
|
||
orphan_key = PREFIX + chat['id'] + '/' + str(uuid.uuid4())
|
||
put(orphan_key)
|
||
active = seed('uploading', active=True)
|
||
locked = seed('uploading')
|
||
time.sleep(20.2) # Настоящий возраст объекта S3, не фиктивный LastModified.
|
||
fresh_key = PREFIX + chat['id'] + '/' + str(uuid.uuid4())
|
||
put(fresh_key)
|
||
fresh = upload('fresh.png')['json']
|
||
with psycopg.connect(DATABASE_URL, row_factory=dict_row) as guard:
|
||
lock_attachment(guard, locked['id']); guard.commit()
|
||
try:
|
||
dry = scan(20, False)
|
||
assert storage.head(orphan_key) and row(failed['id'])
|
||
assert row(missing['id'])['status'] == 'ready'
|
||
applied = scan(20, True)
|
||
assert storage.head(orphan_key) is None
|
||
assert row(failed['id']) is None and storage.head(failed['object_key']) is None
|
||
assert row(missing['id'])['status'] == 'missing'
|
||
assert row(used['id']) and storage.head(used_row['object_key'])
|
||
assert row(active['id']) and storage.head(active['key'])
|
||
assert row(locked['id']) and storage.head(locked['key'])
|
||
assert storage.head(fresh_key) and row(fresh['id'])
|
||
c.call('GET', '/api/v1/attachments/'+missing['id']+'/content', 503, actor=bob)
|
||
# После возврата именно исходных bytes reconciler может вернуть ready.
|
||
put(missing_row['object_key'])
|
||
repaired = scan(20, True)
|
||
assert row(missing['id'])['status'] == 'ready'
|
||
assert c.call('GET', '/api/v1/attachments/'+missing['id']+'/content', actor=bob)['bytes'] == data
|
||
repeated = scan(20, True)
|
||
assert not repeated['actions'], 'Repeat still changes already corrected state'
|
||
page = c.call('GET', '/api/v1/chats/'+chat['id']+'/messages', actor=bob, schema='MessagePage')['json']
|
||
assert message in page['items'] and missing_message in page['items']
|
||
finally:
|
||
unlock_attachment(guard, locked['id']); guard.commit()
|
||
records.update(status='PASS', dry_run=dry, apply=applied, restore=repaired, repeat=repeated,
|
||
used_and_fresh_preserved=True, active_lease_and_lock_preserved=True,
|
||
missing_original_restored_by_operator=True)
|
||
print(json.dumps(records))
|
||
|
||
|
||
if __name__ == '__main__':
|
||
main()
|