Files
mtusi2026lab6-fork/student-tests/broker_resilience.py
T

99 lines
4.1 KiB
Python

"""Exercise broker persistence and kill a worker after S3 writes, before SQL commit/ACK."""
from pathlib import Path
import subprocess
import sys
import time
from uuid import uuid4
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, arguments, check, run
def cmd(*args, capture=False):
return subprocess.run(args, cwd=ROOT, text=True, check=True, timeout=100,
stdout=subprocess.PIPE if capture else None).stdout
def compose(*args, capture=False):
return cmd('docker', 'compose', *args, capture=capture)
def wait_for(probe, timeout, label):
until = time.monotonic() + timeout
while time.monotonic() < until:
if probe():
return
time.sleep(.25)
raise RuntimeError(label)
def confirmed(aid):
count = compose('exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger',
'-At', '-c', f"SELECT count(*) FROM attachment_outbox o JOIN attachment_jobs j "
f"ON j.id=o.job_id WHERE j.attachment_id='{aid}' AND o.published_at IS NOT NULL",
capture=True)
return int(count.strip()) > 0
def main():
args = arguments(__doc__)
client = Client(args.base_url, args.ca_file)
marker = 'AFTER_S3_BEFORE_COMMIT'
fault_worker = 'lab5-fault-' + uuid4().hex[:10]
compose('stop', 'worker')
try:
alice, bob, _, chat = client.bootstrap()
attachment, original = client.attachment(alice, chat)
client.message(alice, chat, '', attachments=[attachment['id']])
path = '/api/v1/attachments/' + attachment['id']
client.call('GET', path + '/content', 409, actor=bob)
wait_for(lambda: confirmed(attachment['id']), 30, 'no publisher confirm')
compose('restart', 'rabbitmq', 'api-a', 'api-b')
compose('up', '-d', '--no-build', '--no-deps', '--wait', 'api-a', 'api-b')
queued = client.call('GET', path, actor=bob, schema='Attachment')['json']
check(queued['status'] == 'queued', 'job lost during restart')
compose('start', 'worker')
client.wait_ready(bob, attachment)
check(client.call('GET', path + '/content', actor=bob)['bytes'] == original, 'original lost')
print('PASS: worker stopped; after API and RabbitMQ restart the same attachment became ready', flush=True)
compose('stop', 'worker')
attachment, original = client.attachment(alice, chat)
path = '/api/v1/attachments/' + attachment['id']
code = """
import sys,time
from messenger import worker
commit = worker.complete
def pause(db, job, result=None, error_code=None):
if job['attachment_id'] == sys.argv[1] and result is not None:
print('AFTER_S3_BEFORE_COMMIT', flush=True)
time.sleep(120)
return commit(db, job, result, error_code)
worker.complete = pause
worker.main()
"""
compose('run', '-d', '--no-deps', '--name', fault_worker, 'worker',
'python', '-c', code, attachment['id'])
wait_for(lambda: marker in cmd('docker', 'logs', fault_worker, capture=True),
40, 'worker did not reach fault point')
cmd('docker', 'kill', fault_worker)
compose('start', 'worker')
start = time.monotonic()
def is_ready():
state = client.call('GET', path, actor=bob, schema='Attachment')['json']
check(state['status'] != 'failed', 'processing failed after crash')
return state if state['status'] == 'ready' else None
wait_for(is_ready, 90, 'expired processing lease did not recover')
ready = is_ready()
check(len(ready['variants']) == 3, 'expected exactly one set of variants')
check(client.call('GET', path + '/content', actor=bob)['bytes'] == original, 'original changed')
print(f'PASS: worker killed after S3 write before COMMIT/ACK; recovered in {time.monotonic()-start:.2f}s')
finally:
subprocess.run(['docker', 'rm', '-f', fault_worker], cwd=ROOT, capture_output=True, timeout=15)
compose('start', 'worker')
if __name__ == '__main__':
run(main)