feat(lab4): implement S3 attachments with fault tolerance
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
"""Stop exactly the API that returned upload 201, download via survivor; repeat both."""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, check
|
||||
from faults import compose, ready
|
||||
|
||||
|
||||
def mappings():
|
||||
result = {}
|
||||
for container in compose('ps', '-q', 'api').split():
|
||||
identity = subprocess.check_output(['docker', 'exec', container, 'python', '-c', 'import urllib.request;print(urllib.request.urlopen("http://localhost:8080/health/live").headers["X-Instance-Id"])'], text=True).strip()
|
||||
result[identity] = container
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
c = Client(os.getenv('BASE_URL', 'http://localhost:8084'), timeout=20)
|
||||
alice,bob,eve,chat = c.bootstrap()
|
||||
image=(Path(__file__).resolve().parents[1]/'tests/fixtures/sample.png').read_bytes()
|
||||
results=[]
|
||||
stopped=set()
|
||||
try:
|
||||
for _ in range(2):
|
||||
mapping=mappings()
|
||||
for attempt in range(20):
|
||||
response=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=failover.png',201,actor=alice,raw=image,headers={'Content-Type':'image/png'},schema='Attachment')
|
||||
instance=response['headers']['X-Instance-Id']
|
||||
container=mapping[instance]
|
||||
if container not in stopped:
|
||||
break
|
||||
else:
|
||||
raise RuntimeError('could not reach other uploader')
|
||||
att=response['json']
|
||||
env=dict(os.environ,TARGET_INSTANCE_ID=instance)
|
||||
subprocess.run(['scripts/stop-one.sh'],env=env,check=True)
|
||||
status=subprocess.check_output(['docker','inspect','--format','{{.State.Running}}',container],text=True).strip()
|
||||
check(status=='false','uploader still running')
|
||||
deadline=time.monotonic()+10
|
||||
while True:
|
||||
try:
|
||||
download=c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)
|
||||
break
|
||||
except AssertionError:
|
||||
if time.monotonic()>deadline:
|
||||
raise
|
||||
time.sleep(.2)
|
||||
check(download['headers']['X-Instance-Id']!=instance,'served by stopped uploader')
|
||||
check(download['bytes']==image,'original changed after uploader stop')
|
||||
results.append({'uploader_instance':instance,'stopped_container':container[:12],'survivor_instance':download['headers']['X-Instance-Id'],'sha256':hashlib.sha256(download['bytes']).hexdigest(),'original_identical':True})
|
||||
stopped.add(container)
|
||||
compose('start','api')
|
||||
time.sleep(4)
|
||||
ready(c)
|
||||
print(json.dumps({'passed':True,'both_uploaders_tested':len(stopped),'scenarios':results},indent=2))
|
||||
finally:
|
||||
compose('start','api')
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Verify every committed original against PostgreSQL, without printing keys/tokens."""
|
||||
import json
|
||||
from faults import remote
|
||||
|
||||
code = '''from src.database import open_database,get_connection
|
||||
from src.storage import s3,BUCKET
|
||||
import hashlib,json
|
||||
open_database()
|
||||
with get_connection() as conn:
|
||||
rows=conn.execute('SELECT object_key,size_bytes,sha256 FROM attachments').fetchall()
|
||||
checked=total=0
|
||||
for row in rows:
|
||||
body=s3.get_object(Bucket=BUCKET,Key=row['object_key'])['Body']
|
||||
digest=hashlib.sha256(); size=0
|
||||
try:
|
||||
for chunk in body.iter_chunks(65536):
|
||||
size+=len(chunk); digest.update(chunk)
|
||||
finally:
|
||||
body.close()
|
||||
assert size==row['size_bytes'] and digest.hexdigest()==row['sha256'], 'original mismatch'
|
||||
checked+=1; total+=size
|
||||
print(json.dumps({'verified_originals':checked,'verified_bytes':total,'all_checksums_match':True}))'''
|
||||
print(json.dumps(json.loads(remote(code)),indent=2))
|
||||
@@ -0,0 +1,209 @@
|
||||
"""Real lab4-only fault injection. Restores services/triggers in finally.
|
||||
Operator invokes explicitly; never removes volumes or user objects.
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, check
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
COMPOSE = ['docker', 'compose', '--env-file', str(ROOT / '.env')]
|
||||
|
||||
|
||||
def compose(*args, data=None):
|
||||
result = subprocess.run(COMPOSE + list(args), input=data, text=True, capture_output=True, cwd=ROOT)
|
||||
if result.returncode:
|
||||
raise RuntimeError('compose action failed: ' + ' '.join(args[:2]))
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def sql(statement):
|
||||
return compose('exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-v', 'ON_ERROR_STOP=1', '-At', data=statement)
|
||||
|
||||
|
||||
def remote(code, data=None):
|
||||
return compose('exec', '-T', 'api', 'python', '-c', code, data=data)
|
||||
|
||||
|
||||
def ready(c):
|
||||
deadline = time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
c.call('GET', '/health/ready')
|
||||
return
|
||||
except AssertionError:
|
||||
time.sleep(.5)
|
||||
raise RuntimeError('readiness timeout')
|
||||
|
||||
|
||||
S3_SUMMARY = '''from src.storage import s3, BUCKET
|
||||
import json
|
||||
objects = [o['Key'] for p in s3.get_paginator('list_objects_v2').paginate(Bucket=BUCKET, Prefix='originals/') for o in p.get('Contents', [])]
|
||||
print(json.dumps(objects))'''
|
||||
|
||||
|
||||
def main():
|
||||
c = Client(os.getenv('BASE_URL', 'http://localhost:8084'), timeout=40)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
attachment, image = c.attachment(alice, chat)
|
||||
passed = []
|
||||
# Only our unique filename will trigger a database failure AFTER a real S3 PUT.
|
||||
filename = 'fault-' + chat['id'] + '.png'
|
||||
trigger = f'''CREATE OR REPLACE FUNCTION student_fail_attachment() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN IF NEW.filename = '{filename}' THEN RAISE EXCEPTION 'synthetic attachment failure'; END IF; RETURN NEW; END $$;
|
||||
CREATE TRIGGER student_fail_attachment BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION student_fail_attachment();'''
|
||||
try:
|
||||
before = set(json.loads(remote(S3_SUMMARY)))
|
||||
referenced = set(json.loads(remote('''from src.database import open_database, get_connection
|
||||
open_database()
|
||||
import json
|
||||
with get_connection() as conn:
|
||||
print(json.dumps([r['object_key'] for r in conn.execute('SELECT object_key FROM attachments').fetchall()]))''')))
|
||||
sql(trigger)
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + filename, 503, actor=alice, raw=image, headers={'Content-Type': 'image/png'})
|
||||
sql('DROP TRIGGER IF EXISTS student_fail_attachment ON attachments; DROP FUNCTION IF EXISTS student_fail_attachment();')
|
||||
after = set(json.loads(remote(S3_SUMMARY)))
|
||||
orphan = after - before
|
||||
check(len(orphan) == 1, 'did not observe a real orphan after DB rollback')
|
||||
passed.append('S3_PUT_then_DB_failure_returns_503_with_real_orphan')
|
||||
# Fresh objects survive a real cleanup. Clock advance is confined to this test
|
||||
# process: production grace period and object timestamps are not changed.
|
||||
result = json.loads(remote('''from src.database import open_database
|
||||
open_database()
|
||||
from src.cleanup import cleanup
|
||||
import json
|
||||
print(json.dumps(cleanup()))'''))
|
||||
check(result['deleted'] == 0 and result['fresh'] > 0, 'fresh object deleted')
|
||||
passed.append('fresh_orphan_survives_one_hour_grace')
|
||||
result = json.loads(remote('''from src.database import open_database
|
||||
open_database()
|
||||
import src.cleanup as cleaner
|
||||
from datetime import datetime, timezone, timedelta
|
||||
class Future(datetime):
|
||||
@classmethod
|
||||
def now(cls, tz=None):
|
||||
return datetime.now(timezone.utc) + timedelta(hours=2)
|
||||
cleaner.datetime = Future
|
||||
import json
|
||||
print(json.dumps(cleaner.cleanup()))'''))
|
||||
check(result['deleted'] >= 1 and result['referenced'] > 0, 'cleanup failed to preserve references / delete orphan')
|
||||
final = set(json.loads(remote(S3_SUMMARY)))
|
||||
check(not orphan & final and referenced <= final, 'cleanup lost used data')
|
||||
passed.append('expired_orphan_deleted_referenced_objects_preserved_test_clock')
|
||||
repeat = json.loads(remote('''from src.database import open_database
|
||||
open_database()
|
||||
from src.cleanup import cleanup
|
||||
import json
|
||||
print(json.dumps(cleanup()))'''))
|
||||
check(repeat['deleted'] == 0, 'cleanup not repeatable')
|
||||
passed.append('cleanup_repeatable')
|
||||
# API credentials: anonymous GET/list denied, bucket policy/admin denied.
|
||||
privacy = json.loads(remote('''from src.storage import s3, BUCKET
|
||||
from botocore import UNSIGNED
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import ClientError
|
||||
import boto3, json, urllib.request, urllib.error
|
||||
key=s3.list_objects_v2(Bucket=BUCKET,Prefix='originals/',MaxKeys=1)['Contents'][0]['Key']
|
||||
result=[]
|
||||
for suffix in ('/'+BUCKET+'/'+key, '/'+BUCKET+'?list-type=2'):
|
||||
try:
|
||||
urllib.request.urlopen('http://s3:9000'+suffix,timeout=3)
|
||||
result.append(200)
|
||||
except urllib.error.HTTPError as e:
|
||||
result.append(e.code)
|
||||
try:
|
||||
s3.get_bucket_policy(Bucket=BUCKET)
|
||||
result.append(200)
|
||||
except ClientError as e:
|
||||
result.append(e.response['ResponseMetadata']['HTTPStatusCode'])
|
||||
print(json.dumps(result))'''))
|
||||
check(privacy == [403, 403, 403], 'bucket or API credentials overexposed')
|
||||
passed.append('anonymous_GET_and_LIST_denied_API_cannot_read_policy')
|
||||
# Probe API itself, not a load-balancer-generated failure.
|
||||
request = json.dumps({'token': alice['token'], 'chat': chat['id'], 'image': base64.b64encode(image).decode()})
|
||||
probe = '''import sys,json,base64,urllib.request,urllib.error
|
||||
x=json.load(sys.stdin)
|
||||
r=urllib.request.Request('http://127.0.0.1:8080/api/v1/chats/'+x['chat']+'/attachments?filename=outage.png',data=base64.b64decode(x['image']),headers={'Authorization':'Bearer '+x['token'],'Content-Type':'image/png'},method='POST')
|
||||
try:
|
||||
response=urllib.request.urlopen(r,timeout=20)
|
||||
except urllib.error.HTTPError as e:
|
||||
response=e
|
||||
print(json.dumps({'status':response.code,'body':json.loads(response.read()),'request_id':bool(response.headers.get('X-Request-Id')),'instance_id':bool(response.headers.get('X-Instance-Id'))}))'''
|
||||
for service in ('s3', 'postgres'):
|
||||
compose('stop', service)
|
||||
try:
|
||||
failure = json.loads(remote(probe, data=request))
|
||||
check(failure['status'] == 503 and failure['request_id'] and failure['instance_id'], service + ' outage mishandled')
|
||||
check(failure['body']['error']['code'] == 'unavailable', 'wrong error format')
|
||||
finally:
|
||||
compose('start', service)
|
||||
ready(c)
|
||||
passed.append(service + '_outage_API_503')
|
||||
# An actual disconnect cannot create an object because PUT follows full validation.
|
||||
before = set(json.loads(remote(S3_SUMMARY)))
|
||||
import socket
|
||||
from urllib.parse import urlsplit
|
||||
url = urlsplit(c.base)
|
||||
con = socket.create_connection((url.hostname, url.port))
|
||||
con.sendall((f'POST /api/v1/chats/{chat["id"]}/attachments?filename=aborted.png HTTP/1.1\r\nHost: localhost\r\nAuthorization: Bearer {alice["token"]}\r\nContent-Type: image/png\r\nContent-Length: {len(image)}\r\n\r\n').encode() + image[:100])
|
||||
con.close()
|
||||
time.sleep(2)
|
||||
check(before == set(json.loads(remote(S3_SUMMARY))), 'aborted upload left an S3 object')
|
||||
passed.append('interrupted_upload_no_S3_object')
|
||||
# Kill the process while the metadata INSERT sleeps after PUT.
|
||||
sql(f'''CREATE OR REPLACE FUNCTION student_fail_attachment() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN IF NEW.filename = '{filename}' THEN PERFORM pg_sleep(20); END IF; RETURN NEW; END $$;
|
||||
CREATE TRIGGER student_fail_attachment BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION student_fail_attachment();''')
|
||||
before = set(json.loads(remote(S3_SUMMARY)))
|
||||
with ThreadPoolExecutor(max_workers=1) as pool:
|
||||
future = pool.submit(c.call, 'POST', '/api/v1/chats/'+chat['id']+'/attachments?filename='+filename, 201, actor=alice, raw=image, headers={'Content-Type':'image/png'})
|
||||
deadline = time.monotonic() + 15
|
||||
while time.monotonic() < deadline:
|
||||
observed = set(json.loads(remote(S3_SUMMARY))) - before
|
||||
if observed:
|
||||
break
|
||||
time.sleep(.2)
|
||||
check(len(observed) == 1, 'PUT not observed before crash')
|
||||
compose('kill', '-s', 'SIGKILL', 'api')
|
||||
try:
|
||||
future.result()
|
||||
raise RuntimeError('crashed request unexpectedly completed')
|
||||
except AssertionError:
|
||||
pass
|
||||
compose('up', '-d', '--no-deps', 'api')
|
||||
sql('DROP TRIGGER IF EXISTS student_fail_attachment ON attachments; DROP FUNCTION IF EXISTS student_fail_attachment();')
|
||||
ready(c)
|
||||
check(int(sql("SELECT count(*) FROM attachments WHERE filename='"+filename+"';")) == 0, 'crash committed metadata')
|
||||
check(observed <= set(json.loads(remote(S3_SUMMARY))), 'crash orphan not observed')
|
||||
passed.append('API_SIGKILL_after_PUT_before_COMMIT_orphan_recoverable')
|
||||
crash_cleanup = json.loads(remote('''from src.database import open_database
|
||||
open_database()
|
||||
import src.cleanup as cleaner
|
||||
from datetime import datetime, timezone, timedelta
|
||||
class Future(datetime):
|
||||
@classmethod
|
||||
def now(cls, tz=None):
|
||||
return datetime.now(timezone.utc) + timedelta(hours=2)
|
||||
cleaner.datetime = Future
|
||||
import json
|
||||
print(json.dumps(cleaner.cleanup()))'''))
|
||||
check(crash_cleanup['deleted'] >= 1, 'crash orphan cleanup did not run')
|
||||
check(not observed & set(json.loads(remote(S3_SUMMARY))), 'crash orphan not removed')
|
||||
passed.append('API_crash_orphan_actually_cleaned_after_test_clock_grace')
|
||||
got = c.call('GET', '/api/v1/attachments/'+attachment['id']+'/content', actor=bob)['bytes']
|
||||
check(got == image, 'confirmed attachment lost during failures')
|
||||
passed.append('confirmed_original_survives_faults')
|
||||
print(json.dumps({'passed': passed, 'count': len(passed), 'privacy_status_codes': privacy, 'cleanup_expired_result': result, 'grace_test': 'test process clock +2h; production grace remains 1h'}, indent=2))
|
||||
finally:
|
||||
compose('start', 'postgres', 's3')
|
||||
compose('up', '-d', '--no-deps', 'api')
|
||||
sql('DROP TRIGGER IF EXISTS student_fail_attachment ON attachments; DROP FUNCTION IF EXISTS student_fail_attachment();')
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,3 @@
|
||||
sample.jpg — синтетический RGB JPEG 32×24, однотонный, создан Pillow 11.2.1
|
||||
в контейнере lab4. Без персональных данных; проверяет второй разрешённый формат.
|
||||
Публичный PNG fixture не изменён.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 643 B |
@@ -0,0 +1,104 @@
|
||||
"""Black-box grade 4 checks; public tests stay untouched. Standard library only."""
|
||||
import hashlib
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
import zlib
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from urllib.parse import quote, urlsplit
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, check
|
||||
|
||||
|
||||
def png(width, height, pixels=None):
|
||||
def chunk(kind, data):
|
||||
return struct.pack('!I', len(data)) + kind + data + struct.pack('!I', zlib.crc32(kind + data))
|
||||
raw = pixels if pixels is not None else b'\0' * ((width * 3 + 1) * height)
|
||||
return b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('!IIBBBBB', width, height, 8, 2, 0, 0, 0)) + chunk(b'IDAT', zlib.compress(raw)) + chunk(b'IEND', b'')
|
||||
|
||||
|
||||
def main():
|
||||
c = Client(os.getenv('BASE_URL', 'http://localhost:8084'), timeout=45)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
base = '/api/v1/chats/' + chat['id']
|
||||
path = base + '/attachments?filename='
|
||||
image = (Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png').read_bytes()
|
||||
passed = []
|
||||
def upload(name, data, status, mime='image/png'):
|
||||
return c.call('POST', path + quote(name, safe=''), status, actor=alice, raw=data, headers={'Content-Type': mime}, schema='Attachment' if status == 201 else None)
|
||||
cases = [('bytes_over_10MiB', 'large.png', b'x' * (10485760 + 1), 413, 'image/png'),
|
||||
('pixels_over_40M', 'bomb.png', png(40000001, 1, b'\0'), 413, 'image/png'),
|
||||
('broken_png', 'broken.png', image[:70], 415, 'image/png'),
|
||||
('broken_jpeg', 'broken.jpg', b'\xff\xd8\xff\xe0truncated', 415, 'image/jpeg'),
|
||||
('mime_mismatch', 'wrong.jpg', image, 415, 'image/jpeg'),
|
||||
('invalid_format', 'bad.png', b'plain text', 415, 'image/png'),
|
||||
('multipart_rejected', 'bad.png', image, 415, 'multipart/form-data')]
|
||||
for name, filename, data, status, mime in cases:
|
||||
upload(filename, data, status, mime)
|
||||
passed.append(name)
|
||||
for filename in ('../x.png', 'x\\y.png', 'x\0.png', 'x\n.png', '\x7f.png', '', 'x' * 256):
|
||||
upload(filename, image, 400)
|
||||
passed.append('dangerous_filenames')
|
||||
att, data = c.attachment(alice, chat)
|
||||
for actor in (alice, bob):
|
||||
got = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=actor)['bytes']
|
||||
check(hashlib.sha256(got).hexdigest() == att['sha256'] and got == data, 'checksum mismatch')
|
||||
passed.append('original_checksum_and_shared_access')
|
||||
jpeg = (Path(__file__).resolve().parent / 'fixtures/sample.jpg').read_bytes()
|
||||
jpeg_att = upload('original.jpg', jpeg, 201, 'image/jpeg')['json']
|
||||
downloaded = c.call('GET', '/api/v1/attachments/' + jpeg_att['id'] + '/content', actor=bob)
|
||||
check(downloaded['bytes'] == jpeg and downloaded['headers'].get_content_type() == 'image/jpeg', 'JPEG original changed')
|
||||
check(jpeg_att['sha256'] == hashlib.sha256(jpeg).hexdigest(), 'JPEG checksum mismatch')
|
||||
passed.append('JPEG_success_and_checksum')
|
||||
for suffix in ('', '/content'):
|
||||
c.call('GET', '/api/v1/attachments/' + att['id'] + suffix, 401)
|
||||
c.call('GET', '/api/v1/attachments/' + att['id'] + suffix, 404, actor=eve)
|
||||
c.call('GET', '/api/v1/attachments/' + str(uuid.uuid4()) + suffix, 404, actor=alice)
|
||||
passed.append('download_auth_and_acl')
|
||||
other = c.call('POST', '/api/v1/chats', 201, actor=alice, body={'title': 'other', 'member_ids': [alice['id']]}, schema='Chat')['json']
|
||||
foreign = c.call('POST', '/api/v1/chats', 201, actor=eve, body={'title': 'private', 'member_ids': [eve['id']]}, schema='Chat')['json']
|
||||
foreign_att, _ = c.attachment(eve, foreign)
|
||||
for ids in ([str(uuid.uuid4())], [foreign_att['id']]):
|
||||
c.call('POST', base + '/messages', 404, actor=alice, body={'text': '', 'attachment_ids': ids}, headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
c.call('POST', '/api/v1/chats/' + other['id'] + '/messages', 404, actor=alice, body={'text': '', 'attachment_ids': [att['id']]}, headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
passed.append('unknown_foreign_and_other_chat_attachment')
|
||||
for ids in ([att['id']] * 2, [str(uuid.uuid4()) for _ in range(11)], 'invalid', [None]):
|
||||
c.call('POST', base + '/messages', 400, actor=alice, body={'text': '', 'attachment_ids': ids}, headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
passed.append('attachment_id_validation')
|
||||
key = uuid.uuid4().hex
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
messages = list(pool.map(lambda _: Client(c.base, timeout=30).message(alice, chat, '', key=key, attachments=[att['id']])['json'], range(10)))
|
||||
check(all(x == messages[0] for x in messages), 'concurrent replay differs')
|
||||
c.call('POST', base + '/messages', 409, actor=alice, body={'text': 'changed', 'attachment_ids': [att['id']]}, headers={'Idempotency-Key': key})
|
||||
key = uuid.uuid4().hex
|
||||
first = c.message(alice, chat, 'old text', key=key)['json']
|
||||
check(first == c.message(alice, chat, 'old text', key=key, attachments=[])['json'], 'default [] differs')
|
||||
passed.append('attachment_idempotency_across_replicas')
|
||||
# Actual chunked request without Content-Length exercises incremental byte limit.
|
||||
url = urlsplit(c.base)
|
||||
con = http.client.HTTPConnection(url.hostname, url.port, timeout=30)
|
||||
con.request('POST', path + 'chunked.png', body=iter([b'x' * 65536] * 161), headers={'Authorization': 'Bearer ' + alice['token'], 'Content-Type': 'image/png'}, encode_chunked=True)
|
||||
response = con.getresponse()
|
||||
check(response.status == 413, 'chunked limit failed')
|
||||
response.read()
|
||||
con.close()
|
||||
passed.append('chunked_body_limit')
|
||||
# Close mid-body before image validation / S3 PUT.
|
||||
con = socket.create_connection((url.hostname, url.port))
|
||||
headers = f'POST {path}interrupted.png HTTP/1.1\r\nHost: localhost\r\nAuthorization: Bearer {alice["token"]}\r\nContent-Type: image/png\r\nContent-Length: {len(image)}\r\n\r\n'.encode()
|
||||
con.sendall(headers + image[:100])
|
||||
con.close()
|
||||
time.sleep(1)
|
||||
c.call('GET', '/health/ready', schema='Health')
|
||||
passed.append('client_disconnect_server_survives')
|
||||
output = {'passed': passed, 'count': len(passed), 'note': 'Fault/orphan checks are separate in faults.py'}
|
||||
print(json.dumps(output, ensure_ascii=False, indent=2))
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Ten barrier-synchronized uploads + cgroup v2 memory/CPU sampling, lab4 only."""
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from negative import png
|
||||
from client import Client
|
||||
|
||||
|
||||
def main():
|
||||
c = Client(os.getenv('BASE_URL', 'http://localhost:8084'), timeout=45)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
# Random RGB is poorly compressible; ~7.3 MiB per original, no fixture in Git.
|
||||
width = height = 1600
|
||||
raw = b''.join(b'\0' + os.urandom(width * 3) for _ in range(height))
|
||||
image = png(width, height, raw)
|
||||
del raw
|
||||
compose = ['docker', 'compose', '--env-file', '.env']
|
||||
containers = subprocess.check_output(compose + ['ps', '-q', 'api'], text=True).split()
|
||||
code = '''import json,time
|
||||
from pathlib import Path
|
||||
root=Path('/sys/fs/cgroup')
|
||||
def cpu():
|
||||
return int(dict(line.split() for line in (root/'cpu.stat').read_text().splitlines())['usage_usec'])
|
||||
start=time.monotonic(); first=cpu(); values=[]
|
||||
while time.monotonic()-start < 20:
|
||||
values.append(int((root/'memory.current').read_text()))
|
||||
time.sleep(.02)
|
||||
print(json.dumps({'sample_count':len(values),'sampled_baseline_bytes':values[0],'sampled_peak_bytes':max(values),'cgroup_lifetime_peak_bytes':int((root/'memory.peak').read_text()),'elapsed_seconds':time.monotonic()-start,'cpu_usage_seconds':(cpu()-first)/1e6}))'''
|
||||
samplers = [subprocess.Popen(['docker', 'exec', name, 'python', '-c', code], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) for name in containers]
|
||||
time.sleep(1)
|
||||
barrier = threading.Barrier(10)
|
||||
def worker(index):
|
||||
local = Client(c.base, timeout=45)
|
||||
barrier.wait()
|
||||
started = time.monotonic()
|
||||
try:
|
||||
response = local.call('POST', '/api/v1/chats/'+chat['id']+'/attachments?filename=load-'+str(index)+'.png', 201, actor=alice, raw=image, headers={'Content-Type':'image/png'}, schema='Attachment')
|
||||
return {'ok': True, 'seconds': time.monotonic()-started, 'instance': response['headers']['X-Instance-Id']}
|
||||
except Exception as exc:
|
||||
return {'ok': False, 'seconds': time.monotonic()-started, 'error': type(exc).__name__}
|
||||
started = time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
results = list(pool.map(worker, range(10)))
|
||||
elapsed = time.monotonic() - started
|
||||
metrics = []
|
||||
for name, proc in zip(containers, samplers):
|
||||
out, err = proc.communicate(timeout=30)
|
||||
if proc.returncode:
|
||||
raise RuntimeError('cgroup sampler failed')
|
||||
record = json.loads(out)
|
||||
record['container'] = name[:12]
|
||||
record['average_cpu_percent_one_core'] = 100 * record['cpu_usage_seconds'] / record['elapsed_seconds']
|
||||
metrics.append(record)
|
||||
latencies = sorted(x['seconds'] for x in results if x['ok'])
|
||||
successes = len(latencies)
|
||||
report = {'utc': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()), 'concurrency': 10, 'requests': 10,
|
||||
'original_bytes': len(image), 'dimensions': [width,height], 'successful_requests': successes,
|
||||
'failed_requests': 10-successes, 'elapsed_seconds': elapsed, 'successful_rps': successes/elapsed,
|
||||
'latency_success_seconds': {p: latencies[max(0, math.ceil(q*len(latencies))-1)] if latencies else None for p,q in [('p50',.5),('p95',.95),('p99',.99)]},
|
||||
'api_cgroups': metrics, 'requests_detail': results,
|
||||
'limitations': 'One local closed-loop batch; client overhead; no capacity claim. cgroup memory.current sampled every 20ms includes decoder and tmpfs/page cache; may miss shorter peaks. memory.peak is lifetime, includes earlier work. CPU averaged over 20s sampling window includes idle time. Per-API peaks need not be simultaneous.',
|
||||
'docker_host': subprocess.check_output(['docker','info','--format','{{.Architecture}} CPUs={{.NCPU}} RAM={{.MemTotal}}'],text=True).strip()}
|
||||
text=json.dumps(report,indent=2)
|
||||
Path('evidence/upload-load.json').write_text(text+'\n')
|
||||
print(text)
|
||||
if successes != 10:
|
||||
raise SystemExit(1)
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user