Выполнение lab4 на 4
This commit is contained in:
@@ -0,0 +1,144 @@
|
||||
"""Explicit local fault injection. Ages only its own synthetic upload intent."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def compose(*args, input=None):
|
||||
result = subprocess.run(['docker', 'compose', '--env-file', '.env', *args], cwd=ROOT,
|
||||
input=input, text=True, capture_output=True, timeout=90)
|
||||
check(result.returncode == 0, 'Compose operation failed: ' + args[0])
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def sql(query):
|
||||
return compose('exec', '-T', 'postgres', 'psql', '-X', '-qAt', '-v', 'ON_ERROR_STOP=1',
|
||||
'-U', 'messenger', '-d', 'messenger', input=query)
|
||||
|
||||
|
||||
def s3_exists(object_id):
|
||||
# Shell text contains no credential values; they are read inside the container.
|
||||
script = ('mc alias set api http://s3:9000 "$(cat /run/secrets/s3_access_key_id)" '
|
||||
'"$(cat /run/secrets/s3_secret_access_key)" >/dev/null 2>&1; '
|
||||
'mc --json stat "api/$S3_BUCKET/attachments/' + object_id + '"')
|
||||
result = subprocess.run(['docker', 'compose', '--env-file', '.env', 'run', '--rm',
|
||||
'--entrypoint', '/bin/sh', 's3-bootstrap', '-c', script],
|
||||
cwd=ROOT, text=True, capture_output=True, timeout=30)
|
||||
lines = [json.loads(line) for line in result.stdout.splitlines() if line.startswith('{')]
|
||||
check(bool(lines), 'S3 stat returned no JSON')
|
||||
item = lines[-1]
|
||||
if item.get('status') == 'success':
|
||||
return True
|
||||
# Missing and authorization/network errors must not be confused.
|
||||
message = json.dumps(item).lower()
|
||||
check('does not exist' in message or 'specified key' in message or 'nosuchkey' in message,
|
||||
'unexpected S3 stat error')
|
||||
return False
|
||||
|
||||
|
||||
def age(object_id):
|
||||
sql("UPDATE upload_intents SET created_at=clock_timestamp()-INTERVAL '11 minutes', "
|
||||
"expires_at=clock_timestamp()-INTERVAL '1 minute', next_cleanup_at=clock_timestamp()-INTERVAL '1 minute' "
|
||||
"WHERE id='" + object_id + "';")
|
||||
|
||||
|
||||
def cleanup(dry=False):
|
||||
options = ('--dry-run',) if dry else ()
|
||||
return json.loads(compose('exec', '-T', 'api', '/server', 'cleanup', *options))
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Upload compensation / grace period checks')
|
||||
c = Client(args.base_url or 'http://127.0.0.1:8084', args.ca_file)
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
ready, data = c.attachment(alice, chat)
|
||||
c.message(alice, chat, '', attachments=[ready['id']])
|
||||
check(sql("SELECT count(*) FROM upload_intents WHERE id='" + ready['id'] + "';") == '0',
|
||||
'successful publication left an intent')
|
||||
marker = 'cleanup_test_' + uuid.uuid4().hex
|
||||
filename = marker + '.png'
|
||||
create_trigger = f"""
|
||||
CREATE FUNCTION {marker}() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF NEW.filename='{filename}' THEN RAISE EXCEPTION 'synthetic metadata failure'; END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
CREATE TRIGGER {marker} BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION {marker}();
|
||||
"""
|
||||
sql(create_trigger)
|
||||
failed_id = None
|
||||
try:
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + filename,
|
||||
503, actor=alice, raw=data, headers={'Content-Type': 'image/png'})
|
||||
failed_id = sql("SELECT id::text FROM upload_intents WHERE owner_id='" + alice['id'] + "';")
|
||||
uuid.UUID(failed_id)
|
||||
check(sql("SELECT count(*) FROM attachments WHERE id='" + failed_id + "';") == '0', 'failed publication committed metadata')
|
||||
check(s3_exists(failed_id), 'fault was not injected after successful S3 PUT')
|
||||
print('PASS: real S3 PUT followed by injected INSERT failure returns 503; durable intent remains')
|
||||
cleanup()
|
||||
check(s3_exists(failed_id), 'fresh upload removed before grace period')
|
||||
print('PASS: cleanup preserves fresh failed upload during 10-minute grace period')
|
||||
age(failed_id)
|
||||
preview = cleanup(True)
|
||||
check(preview['would_delete'] >= 1 and s3_exists(failed_id), 'dry-run modified object or missed intent')
|
||||
unavailable = subprocess.run(['docker', 'compose', '--env-file', '.env', 'exec', '-T',
|
||||
'-e', 'S3_ENDPOINT=http://127.0.0.1:1', 'api', '/server', 'cleanup'],
|
||||
cwd=ROOT, text=True, capture_output=True, timeout=30)
|
||||
check(unavailable.returncode != 0 and json.loads(unavailable.stdout)['errors'] >= 1,
|
||||
'cleanup failed to report unavailable S3')
|
||||
check(sql("SELECT state FROM upload_intents WHERE id='" + failed_id + "';") == 'pending',
|
||||
'failed deletion discarded pending intent')
|
||||
print('PASS: unavailable cleanup endpoint reports error and preserves intent for retry')
|
||||
cleanup()
|
||||
check(not s3_exists(failed_id), 'expired failed upload remains in S3')
|
||||
check(sql("SELECT state FROM upload_intents WHERE id='" + failed_id + "';") == 'abandoned', 'tombstone missing')
|
||||
print('PASS: aged intent detected; dry-run preserves object; cleanup removes it and retains tombstone')
|
||||
# Simulate a late PUT arriving after the first deletion.
|
||||
script = ('mc alias set api http://s3:9000 "$(cat /run/secrets/s3_access_key_id)" '
|
||||
'"$(cat /run/secrets/s3_secret_access_key)" >/dev/null 2>&1; '
|
||||
'printf late | mc pipe "api/$S3_BUCKET/attachments/' + failed_id + '" >/dev/null')
|
||||
compose('run', '--rm', '--entrypoint', '/bin/sh', 's3-bootstrap', '-c', script)
|
||||
age(failed_id)
|
||||
cleanup()
|
||||
check(not s3_exists(failed_id), 'late PUT not cleaned')
|
||||
age(failed_id)
|
||||
cleanup()
|
||||
print('PASS: late PUT removed on retry; repeat DELETE of absent object succeeds')
|
||||
check(c.call('GET', '/api/v1/attachments/' + ready['id'] + '/content', actor=bob)['bytes'] == data,
|
||||
'cleanup damaged published attachment')
|
||||
sql("INSERT INTO upload_intents(id,chat_id,owner_id) VALUES('" + ready['id'] + "','" + chat['id'] + "','" + alice['id'] + "');")
|
||||
age(ready['id'])
|
||||
cleanup()
|
||||
check(sql("SELECT count(*) FROM upload_intents WHERE id='" + ready['id'] + "';") == '0', 'stale ready intent not removed')
|
||||
check(c.call('GET', '/api/v1/attachments/' + ready['id'] + '/content', actor=bob)['bytes'] == data,
|
||||
'stale intent caused published object deletion')
|
||||
print('PASS: published attachment referenced by message remains byte-identical')
|
||||
# A client disconnects before a complete image is received: no S3 PUT starts.
|
||||
target = urlsplit(c.base)
|
||||
check(target.scheme == 'http', 'disconnect check is local HTTP only')
|
||||
request = (f'POST /api/v1/chats/{chat["id"]}/attachments?filename=interrupted.png HTTP/1.1\r\n'
|
||||
f'Host: {target.netloc}\r\nAuthorization: Bearer {alice["token"]}\r\n'
|
||||
'Content-Type: image/png\r\nContent-Length: 100000\r\n\r\n').encode() + data[:20]
|
||||
with socket.create_connection((target.hostname, target.port or 80), timeout=5) as sock:
|
||||
sock.sendall(request)
|
||||
sock.shutdown(socket.SHUT_WR)
|
||||
while sock.recv(4096):
|
||||
pass
|
||||
check(sql("SELECT count(*) FROM upload_intents WHERE owner_id='" + alice['id'] + "' AND state='pending';") == '0',
|
||||
'interrupted client created a pending S3 upload')
|
||||
print('PASS: disconnected partial HTTP upload never reaches S3 intent stage')
|
||||
finally:
|
||||
sql(f'DROP TRIGGER IF EXISTS {marker} ON attachments; DROP FUNCTION IF EXISTS {marker}();')
|
||||
print('PASS: upload compensation checks completed; grace aging was explicit SQL simulation')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Reference in New Issue
Block a user