81 lines
2.7 KiB
Python
Executable File
81 lines
2.7 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Upload through one API replica, stop it, download through another.
|
|
|
|
Run against a live stand:
|
|
python3 student-tests/attachment_failover.py --base-url http://localhost:8080
|
|
"""
|
|
import hashlib
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
from urllib.parse import quote
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
|
|
from client import Client, Failure, arguments, check, run # noqa: E402
|
|
from tests_helpers import ROOT, compose # noqa: E402
|
|
|
|
FIXTURE = Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png'
|
|
|
|
|
|
def main():
|
|
args = arguments('Attachment failover across API replicas (lab4)')
|
|
client = Client(args.base_url, args.ca_file)
|
|
alice, bob, _, chat = client.bootstrap()
|
|
content = FIXTURE.read_bytes()
|
|
|
|
response = client.call(
|
|
'POST',
|
|
'/api/v1/chats/' + chat['id'] + '/attachments?filename=' + quote('failover.png'),
|
|
201,
|
|
actor=alice,
|
|
raw=content,
|
|
headers={'Content-Type': 'image/png'},
|
|
schema='Attachment',
|
|
)
|
|
attachment = response['json']
|
|
instance = response['headers'].get('X-Instance-Id')
|
|
check(bool(instance), 'upload response has no X-Instance-Id')
|
|
check(attachment['sha256'] == hashlib.sha256(content).hexdigest(), 'upload checksum mismatch')
|
|
|
|
stop = subprocess.run(
|
|
[str(ROOT / 'scripts/stop-one.sh')],
|
|
cwd=ROOT,
|
|
env={**os.environ, 'TARGET_INSTANCE_ID': instance},
|
|
capture_output=True,
|
|
text=True,
|
|
)
|
|
check(stop.returncode == 0, 'stop-one.sh failed: ' + stop.stderr.strip())
|
|
|
|
deadline = time.monotonic() + 30
|
|
last_error = None
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
download = client.call(
|
|
'GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=bob,
|
|
)
|
|
if download['bytes'] == content:
|
|
metadata = client.call(
|
|
'GET', '/api/v1/attachments/' + attachment['id'], actor=bob, schema='Attachment',
|
|
)['json']
|
|
check(metadata['sha256'] == attachment['sha256'], 'metadata changed after failover')
|
|
print('PASS: lab4 attachment failover; served by', instance)
|
|
return
|
|
last_error = 'downloaded bytes differ from the original'
|
|
except Failure as error:
|
|
last_error = str(error)
|
|
|
|
time.sleep(1)
|
|
|
|
raise Failure('download did not recover within 30s: ' + str(last_error))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
try:
|
|
run(main)
|
|
finally:
|
|
compose('up', '-d', '--no-deps', 'api', check=False)
|