Files
mtusi2026lab4/student-tests/attachment_resilience.py
T

217 lines
10 KiB
Python

"""Explicit local failures; preserves volumes and restores API/S3 in finally."""
import datetime as dt
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
import time
import urllib.error
import urllib.request
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, arguments, check, run
def docker(*args, check_code=True):
result = subprocess.run(['docker', *args], cwd=ROOT, text=True, capture_output=True, timeout=120)
if check_code:
check(result.returncode == 0, 'Docker operation failed: ' + args[0])
return result
def compose(*args, **kwargs):
return docker('compose', '--env-file', '.env', *args, **kwargs)
def snapshot(label):
ids = compose('ps', '-a', '-q').stdout.split()
template = ('{"id":{{json .Id}},"name":{{json .Name}},'
'"service":{{json (index .Config.Labels "com.docker.compose.service")}},'
'"status":{{json .State.Status}},"started_at":{{json .State.StartedAt}},'
'"pid":{{json .State.Pid}},"image_id":{{json .Image}},"mounts":{{json .Mounts}}}')
records = []
for container in ids:
item = json.loads(docker('inspect', '--format', template, container).stdout)
item['volumes'] = [{'name': m['Name'], 'destination': m['Destination']}
for m in item.pop('mounts') if m['Type'] == 'volume']
records.append(item)
record = {'stage': label, 'utc': dt.datetime.now(dt.timezone.utc).isoformat(), 'containers': records}
with (ROOT / 'evidence' / 'attachment-resilience-containers.jsonl').open('a', encoding='utf-8') as out:
out.write(json.dumps(record, ensure_ascii=False) + '\n')
return records
def wait_ready(c, seconds=60):
deadline = time.monotonic() + seconds
while True:
try:
c.call('GET', '/health/ready', schema='Health')
return
except Failure:
check(time.monotonic() < deadline, 'readiness did not recover')
time.sleep(0.3)
def restore(c):
# Compose start also visits depends_on (bootstrap/migrate). Restore only
# the stopped processes, without reapplying credentials during the test.
for container in compose('ps', '-a', '-q', 's3', 'api').stdout.split():
if docker('inspect', '--format', '{{.State.Running}}', container).stdout.strip() != 'true':
docker('start', container)
deadline = time.monotonic() + 60
observed, consecutive = set(), 0
while True:
try:
response = c.call('GET', '/health/ready', schema='Health')
observed.add(response['headers']['X-Instance-Id'])
consecutive += 1
if len(observed) == 2 and consecutive >= 8:
return
except Failure:
observed, consecutive = set(), 0
check(time.monotonic() < deadline, 'two API replicas did not return to stable LB rotation')
time.sleep(0.2)
def download(c, actor, attachment, original):
response = c.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=actor)
check(response['bytes'] == original, 'original bytes changed')
check(hashlib.sha256(response['bytes']).hexdigest() == attachment['sha256'], 'checksum changed')
return response
def public_test(c, mode):
env = dict(os.environ, LAB_PYTHON=sys.executable)
hook = 'scripts/restart.cmd' if mode == 'persistence' else 'scripts/stop-one.cmd'
before = snapshot('before-public-' + mode)
result = subprocess.run([sys.executable, '-X', 'utf8', 'tests/resilience.py', '--mode', mode,
'--action-script', hook, '--base-url', c.base],
cwd=ROOT, env=env, text=True, capture_output=True, timeout=200)
(ROOT / 'evidence' / ('lab4-' + mode + '.txt')).write_text(result.stdout + result.stderr, encoding='utf-8')
after = snapshot('after-public-' + mode)
check(result.returncode == 0, 'public ' + mode + ' failed; inspect its evidence file')
if mode == 'persistence':
previous = {item['name']: item for item in before}
for item in after:
if item['service'] in ('api', 'lb', 'postgres', 'redis', 's3'):
check(item['started_at'] != previous[item['name']]['started_at'], 'component was not restarted: ' + item['service'])
check(item['volumes'] == previous[item['name']]['volumes'], 'persistent volume changed')
print('PASS: public persistence; API/LB/PostgreSQL/Redis/S3 restarted, named volumes unchanged')
else:
check(sum(item['service'] == 'api' and item['status'] == 'exited' for item in after) == 1,
'failover hook did not leave exactly one API stopped')
print('PASS: public failover; one API stopped, in-flight messages/session/original preserved')
restore(c)
def uploader_failovers(c):
alice, bob, _, chat = c.bootstrap()
data = (ROOT / 'tests/fixtures/sample.png').read_bytes()
containers = compose('ps', '-q', 'api').stdout.split()
check(len(containers) == 2, 'expected exactly two running API replicas')
aliases = {container: docker('exec', container, '/server', 'instance-id').stdout.strip() for container in containers}
for index, target in enumerate(containers, 1):
expected = aliases[target]
uploaded = None
for _ in range(40):
response = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=failover.png',
201, actor=alice, raw=data, headers={'Content-Type': 'image/png'}, schema='Attachment')
if response['headers']['X-Instance-Id'] == expected:
uploaded = response['json']
break
check(uploaded is not None, 'target API did not receive upload')
c.message(alice, chat, '', attachments=[uploaded['id']])
snapshot('before-uploader-stop-' + str(index))
docker('stop', '--time', '1', target)
snapshot('after-uploader-stop-' + str(index))
started = time.monotonic()
failures = 0
while True:
try:
response = download(c, bob, uploaded, data)
check(response['headers']['X-Instance-Id'] != expected, 'stopped uploader still served download')
break
except Failure:
failures += 1
check(time.monotonic() - started < 10, 'download did not recover within 10 seconds')
time.sleep(0.2)
print(json.dumps({'scenario': 'uploader-failover', 'replica': index,
'recovery_seconds_after_stop': round(time.monotonic()-started, 3),
'transient_failures': failures, 'checksum_match': True}))
restore(c)
# Ensure the restored process is ready before selecting it as the next target.
deadline = time.monotonic() + 30
while True:
result = docker('exec', target, '/server', 'healthcheck', check_code=False)
if result.returncode == 0:
break
check(time.monotonic() < deadline, 'restored API did not become ready')
time.sleep(0.2)
aliases[target] = docker('exec', target, '/server', 'instance-id').stdout.strip()
print('PASS: upload -> stop exact uploader -> other API downloads identical original, for both replicas')
def s3_outage(c):
alice, bob, _, chat = c.bootstrap()
attachment, data = c.attachment(alice, chat)
original_message = c.message(alice, chat, 'survive S3 outage', attachments=[attachment['id']])['json']
before = snapshot('before-s3-outage')
compose('stop', '--timeout', '1', 's3')
snapshot('during-s3-outage')
try:
api_containers = compose('ps', '-q', 'api').stdout.split()
for container in api_containers:
probe = docker('exec', container, '/server', 'healthcheck', check_code=False)
check(probe.returncode != 0 and 'status=503' in probe.stderr, 'API readiness did not return 503')
live = compose('run', '--rm', '--no-deps', '--entrypoint', '/bin/sh', 's3-bootstrap',
'-c', 'wget -qO- http://api:8080/health/live').stdout
check(json.loads(live)['status'] == 'ok', 'API liveness failed during S3 outage')
# LB may withdraw all API after readiness failure and generate its own 503.
req = urllib.request.Request(c.base + '/api/v1/attachments/' + attachment['id'] + '/content',
headers={'Authorization': 'Bearer ' + bob['token']})
try:
response = c.opener.open(req, timeout=10)
except urllib.error.HTTPError as error:
response = error
with response:
check(response.code == 503, 'download did not fail with 503 during S3 outage')
print('PASS: real S3 stop; both API ready=503, live=200, public download=503 (API or LB)')
finally:
compose('start', 's3')
wait_ready(c)
download(c, bob, attachment, data)
page = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages', actor=bob, schema='MessagePage')['json']
check(original_message in page['items'], 'message lost during S3 outage')
c.attachment(alice, chat)
after = snapshot('after-s3-outage')
previous = {item['name']: item for item in before}
for item in after:
if item['service'] == 'api':
check(item['started_at'] == previous[item['name']]['started_at'], 'API restarted during S3 outage')
print('PASS: S3 restored; original/message/session preserved, new upload works, API processes did not restart')
def main():
args = arguments('Explicit attachment failover, restart and S3 outage')
c = Client(args.base_url or 'http://127.0.0.1:8084', args.ca_file, timeout=3)
evidence = ROOT / 'evidence/attachment-resilience-containers.jsonl'
evidence.write_text('', encoding='utf-8')
try:
restore(c)
snapshot('initial')
public_test(c, 'failover')
uploader_failovers(c)
public_test(c, 'persistence')
s3_outage(c)
print('PASS: attachment resilience checks completed')
finally:
restore(c)
snapshot('final-restored')
if __name__ == '__main__':
run(main)