ЛР 4 — БВТ2303 — Брезгунова — на 5

This commit is contained in:
2026-10-29 13:02:56 +03:00
parent ec540a1a72
commit b78cadb893
73 changed files with 2076 additions and 36 deletions
+119
View File
@@ -0,0 +1,119 @@
"""Extra black-box, failure and reconciliation checks; no public tests modified."""
import concurrent.futures as cf
import hashlib
import io
import json
import os
from pathlib import Path
import socket
import struct
import sys
import time
import urllib.error
import urllib.request
import uuid
import zlib
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
from client import Client, check
from PIL import Image
from botocore.exceptions import ClientError
from src.storage import BUCKET, PREFIX, STORAGE_LOCK, db, s3, setting
from src.reconcile import reconcile
def png(width,height):
def chunk(kind,content):
return struct.pack('!I',len(content))+kind+content+struct.pack('!I',zlib.crc32(kind+content))
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(b'\0\0\0\0'))+chunk(b'IEND',b'')
def main():
c = Client('http://lb:8080',timeout=40)
a,b,e,chat = c.bootstrap()
content = (Path('tests/fixtures/sample.png')).read_bytes()
path = '/api/v1/chats/'+chat['id']+'/attachments?filename=sample.png'
def upload(raw=content,mime='image/png',expected=201,actor=a,url=path,client=c):
return client.call('POST',url,expected,actor=actor,raw=raw,
headers={'Content-Type':mime},schema='Attachment' if expected==201 else None)
for label,raw,mime,expected in (
('oversize',b'x'*(10485760+1),'image/png',413),
('corrupt',b'not an image','image/png',415),
('truncated_png',content[:70],'image/png',415),
('mime_mismatch',content,'image/jpeg',415),
('pixel_limit',png(10000,5000),'image/png',413)):
upload(raw,mime,expected)
for name in ('..%2Fx.png','..%5Cx.png','a%00.png','a%0A.png'):
upload(expected=400,url=path.split('?')[0]+'?filename='+name)
# No Content-Length: the limit is enforced while receiving chunked transfer.
upload(raw=(b'x'*65536 for _ in range(161)),expected=413)
jpeg = io.BytesIO()
Image.new('RGB',(64,48),(10,30,80)).save(jpeg,format='JPEG')
jpeg_bytes = jpeg.getvalue()
jpeg_att = upload(jpeg_bytes,'image/jpeg')['json']
check(c.call('GET','/api/v1/attachments/'+jpeg_att['id']+'/content',actor=b)['bytes']==jpeg_bytes,'JPEG byte mismatch')
upload(jpeg_bytes[:-20],'image/jpeg',415)
att = upload()['json']
upload(actor=e,expected=404)
other = c.call('POST','/api/v1/chats',201,actor=a,body={'title':'Other','member_ids':[a['id']]},schema='Chat')['json']
c.call('POST','/api/v1/chats/'+other['id']+'/messages',404,actor=a,
body={'text':'','attachment_ids':[att['id']]},headers={'Idempotency-Key':uuid.uuid4().hex})
c.call('POST','/api/v1/chats/'+chat['id']+'/messages',404,actor=a,
body={'text':'','attachment_ids':[str(uuid.uuid4())]},headers={'Idempotency-Key':uuid.uuid4().hex})
c.call('POST','/api/v1/chats/'+chat['id']+'/messages',404,actor=e,
body={'text':'','attachment_ids':[att['id']]},headers={'Idempotency-Key':uuid.uuid4().hex})
# Concurrent same-key requests distributed across two real API processes.
key = uuid.uuid4().hex
with cf.ThreadPoolExecutor(max_workers=12) as executor:
replies = list(executor.map(lambda _: c.message(a,chat,'race',key=key),range(12)))
check(len({r['json']['id'] for r in replies})==1,'idempotency race duplicated message')
check(len({r['headers']['X-Instance-Id'] for r in replies})==2,'race did not cross replicas')
cid = replies[0]['json']['id']
c.call('POST','/api/v1/chats/'+chat['id']+'/messages',201,actor=a,
body={'attachment_ids':[],'text':'race'},headers={'Idempotency-Key':key},schema='Message')
for value in ({'text':123},{'text':'a','sender_id':a['id']},
{'text':'a','attachment_ids':[att['id'],att['id']]}):
c.call('POST','/api/v1/chats/'+chat['id']+'/messages',400,actor=a,
body=value,headers={'Idempotency-Key':uuid.uuid4().hex})
c.call('POST','/api/v1/chats/'+chat['id']+'/messages',400,actor=a,
raw=b'{"text":"\\ud800"}',headers={'Content-Type':'application/json','Idempotency-Key':uuid.uuid4().hex})
c.call('GET','/api/v1/attachments/invalid-uuid',400,actor=a)
c.call('GET','/api/v1/attachments/invalid-uuid',401)
# Private bucket and application IAM tested from inside isolated network.
with db() as conn:
row = conn.execute('SELECT * FROM attachments WHERE id=%s',(att['id'],)).fetchone()
url = 'http://s3:9000/'+BUCKET+'/'+row['object_key']
try:
urllib.request.urlopen(url)
raise AssertionError('Anonymous bucket access succeeded')
except urllib.error.HTTPError as exc:
check(exc.code==403,'private bucket must deny anonymous GET')
try:
s3().delete_object(Bucket=BUCKET,Key=row['object_key'])
raise AssertionError('API user can delete objects')
except ClientError as exc:
check(exc.response['Error']['Code']=='AccessDenied','unexpected IAM error')
try:
s3().put_object(Bucket=BUCKET,Key='outside-prefix',Body=b'no')
raise AssertionError('API user can write outside prefix')
except ClientError as exc:
check(exc.response['Error']['Code']=='AccessDenied','prefix IAM denial expected')
# Disconnect before completing body: no object or metadata is persisted.
with db() as conn:
before = conn.execute('SELECT count(*) AS n FROM attachments').fetchone()['n']
sock = socket.create_connection(('api1',8080))
req = ('POST '+path+' HTTP/1.1\r\nHost: api1\r\nAuthorization: Bearer '+a['token']+
'\r\nContent-Type: image/png\r\nContent-Length: 100000\r\n\r\n').encode()+content[:20]
sock.sendall(req)
sock.close()
time.sleep(.5)
with db() as conn:
check(conn.execute('SELECT count(*) AS n FROM attachments').fetchone()['n']==before,'disconnect persisted attachment')
print(json.dumps({'status':'PASS','negative_cases':21,'jpeg_roundtrip':True,
'idempotency_concurrency':12,'idempotency_instances':2,'private_bucket':True,
'api_delete_denied':True,'prefix_write_denied':True,'interrupted_upload':True}))
if __name__ == '__main__':
main()
+18
View File
@@ -0,0 +1,18 @@
"""Called while the operator has explicitly stopped one dependency."""
import json
from pathlib import Path
import sys
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
from client import Client
c = Client('http://api1:8080',timeout=40)
c.call('GET','/health/live',schema='Health')
c.call('GET','/health/ready',503)
if sys.argv[1]=='postgres':
c.call('POST','/api/v1/users',503,body={'username':'outage','display_name':'Test','password':'test-password-123'})
else:
a = c.user('outage')
chat = c.call('POST','/api/v1/chats',201,actor=a,body={'title':'S3 outage','member_ids':[a['id']]},schema='Chat')['json']
c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=outage.png',503,actor=a,
raw=Path('tests/fixtures/sample.png').read_bytes(),headers={'Content-Type':'image/png'})
print(json.dumps({'status':'PASS','dependency':sys.argv[1],'live':200,'ready':503,'mutation':503}))
+101
View File
@@ -0,0 +1,101 @@
"""Inject real orphan/missing failures using a dedicated operator-only test container."""
import concurrent.futures as cf
import hashlib
import json
import os
from pathlib import Path
import sys
import time
import uuid
import boto3
from botocore.exceptions import ClientError
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
from client import Client, check
from src.storage import BUCKET, PREFIX, db, setting
from src.reconcile import reconcile
def main():
os.environ['S3_ACCESS_KEY_ID_FILE'] = '/run/secrets/reconcile_access_key_id'
os.environ['S3_SECRET_ACCESS_KEY_FILE'] = '/run/secrets/reconcile_secret_access_key'
c = Client('http://lb:8080',timeout=40)
a,b,e,chat = c.bootstrap()
content = Path('tests/fixtures/sample.png').read_bytes()
att,_ = c.attachment(a,chat)
c.message(a,chat,'used attachment',attachments=[att['id']])
with db() as conn:
used = conn.execute('SELECT * FROM attachments WHERE id=%s',(att['id'],)).fetchone()
# Only the tests profile has root credentials; normal API/reconciler do not.
admin = boto3.client('s3',endpoint_url='http://s3:9000',region_name='us-east-1',
aws_access_key_id=setting('MINIO_ROOT_USER'),aws_secret_access_key=setting('MINIO_ROOT_PASSWORD'))
old_key = PREFIX+str(uuid.uuid4())
admin.put_object(Bucket=BUCKET,Key=old_key,Body=content)
# Real API error after PUT and before INSERT/COMMIT, through a test-only process.
fault = Client('http://fault-api:8080')
fault.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=fault.png',503,
actor=a,raw=content,headers={'Content-Type':'image/png'})
# A deferred PostgreSQL trigger raises a real error at COMMIT, after S3 PUT.
with db() as conn:
conn.execute("""CREATE OR REPLACE FUNCTION test_commit_fault() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN IF NEW.filename='commit-fault.png' THEN RAISE EXCEPTION 'test commit failure'; END IF; RETURN NEW; END $$""")
conn.execute('DROP TRIGGER IF EXISTS test_commit_fault ON attachments')
conn.execute('CREATE CONSTRAINT TRIGGER test_commit_fault AFTER INSERT ON attachments DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION test_commit_fault()')
try:
c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=commit-fault.png',503,
actor=a,raw=content,headers={'Content-Type':'image/png'})
finally:
with db() as conn:
conn.execute('DROP TRIGGER IF EXISTS test_commit_fault ON attachments')
conn.execute('DROP FUNCTION IF EXISTS test_commit_fault()')
time.sleep(3)
fresh_key = PREFIX+str(uuid.uuid4())
admin.put_object(Bucket=BUCKET,Key=fresh_key,Body=content)
dry = reconcile(False,2,7)
check(dry['orphan_candidates']>=3 and dry['deleted']==0,'dry-run did not find failures safely')
admin.head_object(Bucket=BUCKET,Key=old_key)
applied = reconcile(True,2,7)
check(applied['deleted']>=3,'old orphans not removed')
admin.head_object(Bucket=BUCKET,Key=fresh_key)
admin.head_object(Bucket=BUCKET,Key=used['object_key'])
repeat = reconcile(True,2,7)
check(repeat['deleted']==0,'repeat immediately deleted fresh object')
# S3 loss: metadata + message link are retained, grace observations precede quarantine.
admin.delete_object(Bucket=BUCKET,Key=used['object_key'])
missing_dry = reconcile(False,2,7)
check(missing_dry['missing']>=1 and missing_dry['observation_started']==0,'dry-run changed DB')
first = reconcile(True,2,7)
check(first['observation_started']>=1 and first['quarantined']==0,'fresh absence quarantined too early')
time.sleep(3)
second = reconcile(True,2,7)
check(second['quarantined']>=1,'persistent missing object not quarantined')
c.call('GET','/api/v1/attachments/'+att['id']+'/content',503,actor=b)
with db() as conn:
check(conn.execute('SELECT 1 FROM message_attachments WHERE attachment_id=%s',(att['id'],)).fetchone(),'used metadata lost')
admin.put_object(Bucket=BUCKET,Key=used['object_key'],Body=content,
ContentType='image/png',Metadata={'sha256':used['sha256']})
restored = reconcile(True,2,7)
check(restored['recovered']>=1,'restored bytes not verified/recovered')
check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=b)['bytes']==content,'restored content mismatch')
# Reconciliation concurrent with PUT/COMMIT cannot collect valid attachments.
def uploading(_):
return c.attachment(a,chat)[0]
with cf.ThreadPoolExecutor(max_workers=11) as executor:
futures = [executor.submit(uploading,i) for i in range(10)]
scan = executor.submit(reconcile,True,2,7)
uploaded = [f.result() for f in futures]
concurrent = scan.result()
for item in uploaded:
check(c.call('GET','/api/v1/attachments/'+item['id']+'/content',actor=b)['bytes']==content,'concurrent sweep lost fresh upload')
# A cost sweep over > one page of objects/rows.
cost = [reconcile(False,3600,7) for _ in range(3)]
print(json.dumps({'status':'PASS','grace_for_test_seconds':2,'dry_run':dry,
'apply':applied,'repeat':repeat,'missing_dry_run':missing_dry,
'first_missing_observation':first,'quarantine':second,'restore':restored,
'concurrent_scan':concurrent,'concurrent_uploads_preserved':len(uploaded),
'cost_repeats':cost},sort_keys=True))
if __name__ == '__main__':
main()
+88
View File
@@ -0,0 +1,88 @@
"""Barrier-started >=10 upload clients and sampled RSS of both API processes."""
import concurrent.futures as cf
import io
import json
from pathlib import Path
import statistics
import sys
import threading
import time
import urllib.request
from PIL import Image
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
from client import Client, check
def rss():
return [json.load(urllib.request.urlopen('http://'+host+':8080/internal-test/memory',timeout=2))
for host in ('api1','api2')]
def main():
c = Client('http://lb:8080',timeout=40)
a,b,e,chat = c.bootstrap()
summaries = []
for edge in (512,1536):
# Uncompressible RGB is a genuine PNG; ~0.75 and ~6.76 MiB.
import random
image = Image.frombytes('RGB',(edge,edge),random.Random(42).randbytes(edge*edge*3))
output = io.BytesIO()
image.save(output,format='PNG')
content = output.getvalue()
del image,output
path = '/api/v1/chats/'+chat['id']+'/attachments?filename=load.png'
c.call('POST',path,201,actor=a,raw=content,headers={'Content-Type':'image/png'},schema='Attachment')
baseline = rss()
barrier = threading.Barrier(12)
latencies = []
errors = []
samples = []
done = threading.Event()
def observe():
while not done.is_set():
samples.append(rss())
done.wait(.025)
observer = threading.Thread(target=observe)
observer.start()
def upload(_):
barrier.wait()
for __ in range(3):
started = time.monotonic()
try:
result = c.call('POST',path,201,actor=a,raw=content,headers={'Content-Type':'image/png'},schema='Attachment')
latencies.append(time.monotonic()-started)
except Exception as exc:
errors.append(type(exc).__name__)
started = time.monotonic()
try:
with cf.ThreadPoolExecutor(max_workers=12) as pool:
list(pool.map(upload,range(12)))
finally:
done.set()
observer.join()
elapsed = time.monotonic()-started
check(not errors and len(latencies)==36,'concurrent uploads failed')
ordered = sorted(latencies)
peaks = [max(sample[i]['rss_bytes'] for sample in samples) for i in (0,1)]
cpu_end = rss()
cpu_delta = sum(cpu_end[i]['cpu_seconds']-baseline[i]['cpu_seconds'] for i in (0,1))
summaries.append({'size_bytes':len(content),'dimensions':[edge,edge],
'concurrency':12,'uploads':36,'successful_rps':round(36/elapsed,3),
'duration_seconds':round(elapsed,3),'errors':0,
'p50_seconds':round(statistics.median(ordered),4),
'p95_seconds':round(ordered[int((len(ordered)-1)*.95)],4),
'p99_seconds':round(ordered[int((len(ordered)-1)*.99)],4),
'baseline_rss_bytes':[x['rss_bytes'] for x in baseline],
'peak_rss_bytes':peaks,'cpu_seconds_total':round(cpu_delta,3),
'baseline_container_memory_bytes':[x['container_memory_bytes'] for x in baseline],
'sampled_peak_container_memory_bytes':[max(s[i]['container_memory_bytes'] for s in samples) for i in (0,1)],
'kernel_container_peak_before_bytes':[x['container_peak_bytes'] for x in baseline],
'kernel_container_peak_after_bytes':[x['container_peak_bytes'] for x in cpu_end],
'cpu_average_percent_total':round(100*cpu_delta/elapsed,2),
'memory_samples':len(samples)})
print(json.dumps({'status':'PASS','profiles':summaries}))
if __name__ == '__main__':
main()