lab4 done

This commit is contained in:
Khakimov Dmitrij
2026-11-10 20:42:03 +03:00
parent 276dbdad8a
commit b2bd7501d3
129 changed files with 9319 additions and 109 deletions
+20
View File
@@ -0,0 +1,20 @@
# Собственные проверки lab4
`make test-lab4` проверяет реальные PNG/JPEG, лимиты, MIME, повреждения, права, приватность bucket и отказы.
Тест останавливает именно API-реплику, которая приняла файл, и проверяет скачивание через другую.
`make measure-uploads` запускает десять клиентов на двух размерах PNG и сохраняет замеры cgroup memory.
`make test-reconcile` внедряет ошибки S3/БД и проверяет grace, блокировки, dry-run, повторное исправление и стоимость обхода.
Эти сценарии используют реальный MinIO. Запускайте их последовательно на учебном Swarm-стенде.
Результаты находятся в `evidence/lab4-*`. Подробная методика приведена в [REPORT.md](../../REPORT.md).
Публичные tests/*.py и обязательный контракт сохранены.
- `make test-own`: Go tests с race detector. Без INTEGRATION_TESTS=1 PostgreSQL-сценарий пропускается.
- `make test-integration`: отдельный Swarm job, Go 1.26.4 и goose. Временная схема, миграции с нуля/повторно/legacy/reset/up, регистрационная гонка, rollback, 10 000 сообщений с одинаковыми timestamps, EXPLAIN и 16 конкурентных запросов одного ключа.
- `make test-grade4`: `swarm_grade4.py`, ровно две API tasks. Проверяет общий ключ через LB, одинаковый результат, 409, границы ключа, область пользователя/чата, права и logout. По очереди останавливает обе исходные tasks с восстановлением, затем выполняет rolling update под нагрузкой. Проверяет историю, отсутствие дублей и повтор исходного ключа после воздействия. Сохраняет `evidence/swarm-grade4.json`.
- `make test-persistence`: перезапуск всех API, PostgreSQL, Redis, MinIO и LB; volumes/secrets сохраняются.
- `make test-failover ACTION_SCRIPT=scripts/stop-one.sh`: публичный сценарий отказа; `make wait` дожидается восстановления двух реплик.
- `make measure-load`: 3s прогрева + 30s, concurrency 4, метрики и Docker stats в `evidence/swarm-*`.
Сценарии отказов, persistence и rolling update выполняйте **последовательно**, на локальном учебном стенде. Все данные синтетические; пароль и токены в результаты не записываются. Старый `grade4.py` относится к Compose-стенду lab2 и не является entrypoint текущей работы.
+120
View File
@@ -0,0 +1,120 @@
#!/usr/bin/env python3
"""Additional lab2 acceptance checks. Never print credentials or session tokens."""
import base64
from concurrent.futures import ThreadPoolExecutor
import os
from pathlib import Path
import subprocess
import sys
import time
import uuid
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from client import Client, Failure, check, run
ROOT = Path(__file__).resolve().parents[2]
def compose(*args, ttl=None):
env = dict(os.environ)
if ttl is not None:
env['SESSION_TTL_SECONDS'] = str(ttl)
result = subprocess.run([str(ROOT / 'scripts/compose.sh'), *args], env=env,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=180)
check(result.returncode == 0, 'compose operation failed: ' + args[0])
def login(c, username, password, expected=201):
basic = base64.b64encode((username + ':' + password).encode()).decode()
return c.call('POST', '/api/v1/auth/sessions', expected,
headers={'Authorization': 'Basic ' + basic}, schema='Session' if expected == 201 else None)
def main():
c = Client(timeout=5)
alice, bob, eve, chat = c.bootstrap()
credentials = alice['registration']
login(c, credentials['username'], 'incorrect-password', 401)
login(c, 'unknown_' + uuid.uuid4().hex[:12], 'incorrect-password', 401)
c.call('GET', '/api/v1/users/me', 401, headers={'X-User-Id': alice['id']})
basic = base64.b64encode((credentials['username'] + ':' + credentials['password']).encode()).decode()
c.call('GET', '/api/v1/users/me', 401, headers={'Authorization': 'Basic ' + basic})
response = c.call('GET', '/api/v1/users/me', actor=alice, headers={'X-User-Id': bob['id']}, schema='User')
check(response['json']['id'] == alice['id'], 'X-User-Id changed session owner')
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
c.call('GET', '/api/v1/users/me', 401, actor=alice)
c.call('DELETE', '/api/v1/auth/sessions/current', 401, actor=alice)
print('PASS: wrong password, unknown user, Bearer-only access, X-User-Id ignored, logout')
# Maximum UTF-8 password length and a colon are supported without truncation.
username = 'unicode_' + uuid.uuid4().hex[:12]
password = '🔑' * 127 + ':'
c.call('POST', '/api/v1/users', 201, body={'username': username, 'display_name': 'Unicode', 'password': password}, schema='User')
login(c, username, password)
login(c, username, '🔑' * 127 + 'x', 401)
print('PASS: 128-code-point Unicode password including colon; suffix verified')
username = 'race_' + uuid.uuid4().hex[:12]
def register(_):
return Client().call('POST', '/api/v1/users', [201, 409], body={
'username': username, 'display_name': 'Concurrent', 'password': 'synthetic-password-123'
})['status']
with ThreadPoolExecutor(max_workers=8) as pool:
statuses = list(pool.map(register, range(8)))
check(statuses.count(201) == 1 and statuses.count(409) == 7, 'registration race broken')
print('PASS: HTTP registration race: one 201, seven 409')
# Revoke before restart: absence must also survive AOF recovery.
for service in ('redis', 'postgres'):
compose('stop', service)
try:
c.call('GET', '/health/live', schema='Health')
start = time.monotonic()
c.call('GET', '/health/ready', 503)
check(time.monotonic() - start < 4, 'readiness error exceeded timeout budget')
c.call('GET', '/api/v1/users/me', 503, actor=bob)
c.call('GET', '/api/v1/users/me', 401, headers={'X-User-Id': bob['id']})
login(c, bob['registration']['username'], bob['registration']['password'], 503)
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 503, actor=bob, body={'text': 'must fail'})
finally:
compose('up', '-d', '--wait', service)
c.call('GET', '/health/ready', schema='Health')
c.call('GET', '/api/v1/users/me', actor=bob, schema='User')
c.call('GET', '/api/v1/users/me', 401, actor=alice)
print('PASS: ' + service + ' outage bounded; live=200, ready=503, protected=503, anonymous=401; session recovered, logout retained')
# The same signed cursor remains valid across an API process restart.
c.message(bob, chat, 'cursor before restart 1')
c.message(bob, chat, 'cursor before restart 2')
page = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=1', actor=bob, schema='MessagePage')['json']
check(page['next_cursor'] is not None, 'missing cursor')
compose('restart', 'api')
deadline = time.monotonic() + 30
while True:
try:
c.call('GET', '/health/ready', schema='Health')
break
except Failure:
check(time.monotonic() < deadline, 'API did not recover')
time.sleep(.2)
from urllib.parse import quote
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?cursor=' + quote(page['next_cursor']), actor=bob, schema='MessagePage')
print('PASS: cursor and existing session survive API restart')
try:
compose('up', '-d', '--wait', '--force-recreate', 'api', ttl=2)
short = c.user('expiry')
c.call('GET', '/api/v1/users/me', actor=short, schema='User')
time.sleep(2.2)
c.call('GET', '/api/v1/users/me', 401, actor=short)
compose('restart', 'redis')
compose('up', '-d', '--wait', 'redis')
c.call('GET', '/api/v1/users/me', 401, actor=short)
print('PASS: SESSION_TTL_SECONDS=2 expires; Redis restart does not revive expired session')
finally:
compose('up', '-d', '--wait', '--force-recreate', 'api', ttl=3600)
print('PASS: all grade-4 HTTP checks; normal TTL restored to 3600')
if __name__ == '__main__':
run(main)
+116
View File
@@ -0,0 +1,116 @@
"""Local lab4 experiment helpers. Never print credentials or session tokens."""
import json
import os
from pathlib import Path
import random
import struct
import subprocess
import sys
import time
import uuid
import zlib
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, check
STACK = os.environ.get('STACK_NAME', 'mtusi-lab4')
MC = os.environ.get('S3_CLIENT_IMAGE', 'mtusi-mc:RELEASE.2025-08-13T08-35-41Z')
def docker(*args, data=None, check_result=True):
return subprocess.run(['docker', *args], input=data, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, check=check_result)
def containers(service):
ids = docker('ps', '--filter', 'label=com.docker.swarm.service.name='+STACK+'_'+service,
'--format', '{{.ID}}').stdout.decode().split()
check(bool(ids), 'no container for '+service)
return ids
def sql(statement):
result = docker('exec', '-i', containers('postgres')[0], 'psql', '-U', 'messenger',
'-d', 'messenger', '-At', '-v', 'ON_ERROR_STOP=1', data=statement.encode())
return result.stdout.decode().strip()
def reconcile(apply=False, grace='90s'):
args = ['exec', containers('api')[0], '/usr/local/bin/reconcile', '--grace='+grace]
if apply:
args.append('--apply')
return json.loads(docker(*args).stdout)
def upload(c, actor, chat, content, filename='sample.png', mime='image/png', expected=201):
from urllib.parse import quote
return c.call('POST', '/api/v1/chats/'+chat['id']+'/attachments?filename='+quote(filename, safe=''),
expected, actor=actor, raw=content, headers={'Content-Type': mime},
schema='Attachment' if expected == 201 else None)
def png(width=320, height=200, noisy=False):
def chunk(kind, body):
return struct.pack('>I', len(body))+kind+body+struct.pack('>I', zlib.crc32(kind+body))
rng = random.Random(419)
lines = b''.join(b'\0'+(rng.randbytes(width*3) if noisy else b'\x18\x60\xc0'*width)
for _ in range(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(lines))+chunk(b'IEND', b''))
def oversized_dimensions():
body = struct.pack('>IIBBBBB', 10000, 4001, 8, 2, 0, 0, 0)
return b'\x89PNG\r\n\x1a\n'+struct.pack('>I', len(body))+b'IHDR'+body+struct.pack('>I', zlib.crc32(b'IHDR'+body))
def save(name, result):
(ROOT / 'evidence').mkdir(exist_ok=True)
(ROOT / 'evidence' / name).write_text(json.dumps(result, indent=2, ensure_ascii=False)+'\n')
def wait_ready(timeout=90):
deadline = time.monotonic()+timeout
while time.monotonic() < deadline:
try:
Client(timeout=2).call('GET', '/health/ready', schema='Health')
return
except AssertionError:
time.sleep(.5)
raise AssertionError('readiness did not recover')
class Probe:
"""Short-lived mc service; root secrets remain inside Docker secrets."""
def __enter__(self):
self.name = STACK+'_probe_'+uuid.uuid4().hex[:8]
args = ['service', 'create', '--detach', '--no-resolve-image', '--name', self.name, '--network', STACK+'_data',
'--restart-condition', 'none', '--limit-memory', '512m', '--limit-cpu', '0.5',
'--entrypoint', '/bin/sh']
for secret in ('s3_root_access_key', 's3_root_secret_key', 's3_access_key', 's3_secret_key'):
args += ['--secret', 'source='+STACK+'_'+secret+',target='+secret]
docker(*args, MC, '-c', 'sleep 3600')
deadline = time.monotonic()+45
while time.monotonic() < deadline:
ids = docker('ps', '--filter', 'label=com.docker.swarm.service.name='+self.name, '-q').stdout.decode().split()
if ids:
self.container = ids[0]
return self
time.sleep(.3)
docker('service', 'rm', self.name, check_result=False)
raise AssertionError('probe did not start')
def mc(self, *args, data=None, admin=False, expected=0):
access = 's3_root_access_key' if admin else 's3_access_key'
secret = 's3_root_secret_key' if admin else 's3_secret_key'
script = ('set -eu; export MC_CONFIG_DIR=/tmp/mc; '
'mc alias set local http://minio:9000 "$(cat /run/secrets/'+access+')" '
'"$(cat /run/secrets/'+secret+')" >/dev/null; exec mc "$@"')
result = docker('exec', '-i', self.container, '/bin/sh', '-c', script, 'sh', *args,
data=data, check_result=False)
check((result.returncode == 0) == (expected == 0), 'unexpected mc outcome: '+args[0])
return result
def __exit__(self, *args):
docker('service', 'rm', self.name, check_result=False)
+154
View File
@@ -0,0 +1,154 @@
#!/usr/bin/env python3
"""Real S3/API negative cases and failures; only synthetic lab data."""
import hashlib
import http.client
import json
import os
from pathlib import Path
import subprocess
import time
import uuid
from urllib.parse import urlsplit
from helpers import Client, Probe, ROOT, STACK, check, containers, docker, png, oversized_dimensions, save, sql, upload, wait_ready
def main():
c = Client(timeout=55)
alice, bob, eve, chat = c.bootstrap()
data = png()
result = {'negative_cases': [], 'failures': {}, 'checksums': {}}
for name, body, mime, filename, status in (
('oversized_bytes', b'x'*(10*1024*1024+1), 'image/png', 'large.png', 413),
('damaged_png', data[:50], 'image/png', 'broken.png', 415),
('corrupt_crc', data[:-16]+b'\xff'*16, 'image/png', 'crc.png', 415),
('mime_spoof', data, 'image/jpeg', 'fake.jpg', 415),
('not_image', b'plain text', 'image/png', 'fake.png', 415),
('unsupported_mime', data, 'application/octet-stream', 'file.png', 415),
('pixel_budget', oversized_dimensions(), 'image/png', 'large-dimensions.png', 413),
('unsafe_slash', data, 'image/png', '../file.png', 400),
('unsafe_backslash', data, 'image/png', 'x\\y.png', 400),
('unsafe_control', data, 'image/png', 'x\x00.png', 400),
('empty_filename', data, 'image/png', '', 400),
):
upload(c, alice, chat, body, filename, mime, status)
result['negative_cases'].append({'case': name, 'status': status})
for content, filename, mime in ((data, 'изображение.png', 'image/png'),
((ROOT/'tests/own/fixtures/sample.jpg').read_bytes(), 'photo.jpg', 'image/jpeg')):
att = upload(c, alice, chat, content, filename, mime)['json']
downloaded = c.call('GET', '/api/v1/attachments/'+att['id']+'/content', actor=bob)
check(downloaded['bytes'] == content, 'original bytes changed')
check(att['sha256'] == hashlib.sha256(content).hexdigest(), 'incorrect SHA256')
check(downloaded['headers'].get_content_type() == mime, 'incorrect content MIME')
result['checksums'][mime] = att['sha256']
att = upload(c, alice, chat, data)['json']
for suffix in ('', '/content'):
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)
c.call('GET', '/api/v1/attachments/'+att['id']+suffix, 401)
upload(c, eve, chat, data, expected=404)
c.call('GET', '/api/v1/attachments/'+att['id']+'/content?variant=thumbnail', 404, actor=bob)
other = c.call('POST', '/api/v1/chats', 201, actor=alice,
body={'title':'other chat', 'member_ids':[alice['id'], bob['id']]}, schema='Chat')['json']
path = '/api/v1/chats/'+other['id']+'/messages'
for ids, status in (([att['id']], 404), ([str(uuid.uuid4())], 404), ([att['id'],att['id']], 400)):
c.call('POST', path, status, actor=alice, body={'text':'', 'attachment_ids':ids},
headers={'Idempotency-Key':uuid.uuid4().hex})
result['negative_cases'] += [{'case': x, 'status': s} for x,s in (
('foreign_attachment',404), ('foreign_chat_link',404), ('unknown_attachment',404),
('duplicate_ids',400), ('missing_authentication',401), ('unknown_variant',404))]
# The proxy must stop oversized chunked bodies even without Content-Length.
address = urlsplit(c.base)
conn = http.client.HTTPConnection(address.hostname, address.port, timeout=55)
conn.request('POST', '/api/v1/chats/'+chat['id']+'/attachments?filename=chunked.png',
body=iter([b'x'*65536]*161), encode_chunked=True,
headers={'Authorization':'Bearer '+alice['token'], 'Content-Type':'image/png'})
response = conn.getresponse()
check(response.status == 413, 'chunked upload bypassed byte limit')
response.read(); conn.close()
result['negative_cases'].append({'case':'chunked_oversized', 'status':413})
# Disconnect halfway through the declared body. No object/metadata can be published.
before = int(sql('SELECT count(*) FROM attachments;'))
conn = http.client.HTTPConnection(address.hostname, address.port, timeout=5)
conn.putrequest('POST', '/api/v1/chats/'+chat['id']+'/attachments?filename=aborted.png')
conn.putheader('Authorization', 'Bearer '+alice['token'])
conn.putheader('Content-Type', 'image/png')
conn.putheader('Content-Length', str(len(data)+10000))
conn.endheaders(); conn.send(data[:40]); conn.close()
time.sleep(1)
check(int(sql('SELECT count(*) FROM attachments;')) == before, 'aborted upload published metadata')
leftovers = [docker('exec', container, 'find', '/tmp', '-maxdepth', '1', '-name', 'messenger-upload-*').stdout.decode()
for container in containers('api')]
check(not any(leftovers), 'aborted upload left spool files')
result['failures']['client_disconnect'] = {'metadata_added':0, 'spool_files_remaining':0}
with Probe() as probe:
key = sql("SELECT object_key FROM attachments WHERE id='"+att['id']+"';")
raw = docker('exec', containers('minio')[0], 'wget', '-S', '-O', '/dev/null',
'http://127.0.0.1:9000/attachments/'+key, check_result=False)
check(b'403' in raw.stderr, 'unauthenticated direct S3 GET was not forbidden')
probe.mc('stat', 'local/attachments/'+key)
probe.mc('mb', 'local/forbidden-'+uuid.uuid4().hex[:8], expected=1)
probe.mc('pipe', 'local/attachments/outside-prefix', data=b'x', expected=1)
result['bucket_security'] = {'anonymous_get_status':403, 'create_bucket_denied':True,
'write_outside_prefix_denied':True, 'console_published':False}
service = json.loads(docker('service', 'inspect', STACK+'_minio').stdout)[0]
check(not service['Spec'].get('EndpointSpec', {}).get('Ports'), 'MinIO publishes an external port')
for _ in range(2):
subprocess.run(['python3', str(ROOT/'scripts/swarm.py'), 'bootstrap-s3'], check=True,
stdout=subprocess.DEVNULL)
check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)['bytes']==data,
'repeated bucket bootstrap changed data')
result['bucket_security']['bootstrap_repeats'] = 2
# Stop the replica that accepted THIS upload, then read through another one.
accepted = upload(c,alice,chat,data)
source = accepted['headers']['X-Instance-Id']
env = dict(os.environ, TARGET_INSTANCE_ID=source)
started = time.monotonic()
subprocess.run(['python3',str(ROOT/'scripts/swarm.py'),'stop-one'],env=env,check=True,
stdout=subprocess.DEVNULL)
deadline = time.monotonic()+10
while True:
try:
downloaded = Client(timeout=2).call('GET','/api/v1/attachments/'+accepted['json']['id']+'/content',actor=bob)
check(downloaded['headers']['X-Instance-Id']!=source,'stopped upload replica still serves bytes')
check(downloaded['bytes']==data,'cross-replica original changed')
break
except AssertionError:
check(time.monotonic()<deadline,'cross-replica download did not recover in10s')
time.sleep(.2)
result['failures']['upload_replica_failure'] = {'upload_instance':source,
'download_instance':downloaded['headers']['X-Instance-Id'],
'recovery_seconds':round(time.monotonic()-started,3), 'sha256':hashlib.sha256(data).hexdigest()}
subprocess.run(['python3',str(ROOT/'scripts/swarm.py'),'wait'],check=True,stdout=subprocess.DEVNULL)
# Stop only this stack's S3; /live still works, direct /ready reports503.
started = time.monotonic()
try:
docker('service','scale','--detach',STACK+'_minio=0')
deadline = time.monotonic()+30
while time.monotonic()<deadline:
stopped = docker('ps','--filter','label=com.docker.swarm.service.name='+STACK+'_minio','-q').stdout.strip()
if not stopped:
break
time.sleep(.3)
live = docker('exec',containers('api')[0],'wget','-q','-O','-','http://127.0.0.1:8080/health/live')
check(json.loads(live.stdout)['status']=='ok','S3 outage broke liveness')
ready = docker('exec',containers('api')[0],'wget','-S','-O','-','http://127.0.0.1:8080/health/ready',check_result=False)
check(b'503' in ready.stderr,'readiness ignored S3 outage')
result['failures']['s3_outage'] = {'liveness':200, 'readiness':503}
finally:
docker('service','scale','--detach',STACK+'_minio=1')
wait_ready()
check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)['bytes']==data,
'S3 outage lost original')
result['failures']['s3_outage']['recovery_seconds'] = round(time.monotonic()-started,3)
save('lab4-acceptance.json', result)
print('PASS: PNG/JPEG, bounded uploads, MIME/damage/ACL/link errors, disconnect, private S3, repeat bootstrap, S3 outage.')
if __name__ == '__main__':
main()
+137
View File
@@ -0,0 +1,137 @@
#!/usr/bin/env python3
"""Track2: actual DB/S3 failures, grace, locking, repeat repairs and scan cost."""
import json
import subprocess
import time
import uuid
from helpers import Client, Probe, ROOT, STACK, check, containers, docker, png, reconcile, save, sql, upload, wait_ready
def objects(probe):
raw = probe.mc('ls','--recursive','--json','local/attachments',admin=True).stdout.decode()
return {json.loads(line)['key'] for line in raw.splitlines() if json.loads(line).get('type')=='file'}
def main():
c = Client(timeout=55)
alice,bob,_,chat = c.bootstrap()
data = png()
experiment = uuid.uuid4().hex
result = {'hypothesis':'fixed grace plus per-object transaction lock permits repeatable repair without deleting fresh or linked data',
'grace_seconds':90, 'faults':{}, 'cost':[]}
with Probe() as probe:
# Inject a failure exactly between successful S3 PUT and PostgreSQL INSERT.
before = objects(probe)
filename = 'db-fault-'+experiment+'.png'
sql("CREATE FUNCTION lab4_inject_failure() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.filename='"+filename+"' THEN RAISE EXCEPTION 'lab4 injected DB failure'; END IF; RETURN NEW; END; $$; CREATE TRIGGER lab4_inject_failure BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION lab4_inject_failure();")
try:
upload(c,alice,chat,data,filename=filename,expected=503)
finally:
sql('DROP TRIGGER lab4_inject_failure ON attachments; DROP FUNCTION lab4_inject_failure();')
orphans = objects(probe)-before
check(len(orphans)==1,'DB failure did not leave the expected one unconfirmed S3 object')
orphan = next(iter(orphans))
check(sql("SELECT count(*) FROM attachments WHERE filename='"+filename+"';")=='0','failed metadata INSERT published a row')
born = time.monotonic()
result['faults']['s3_put_db_insert_failure'] = {'upload_status':503, 'objects_without_metadata':1}
fresh = reconcile(apply=True)
check(orphan in objects(probe),'fresh orphan removed before grace')
result['fresh_orphan_preserved'] = fresh['fresh_skipped']>0
# Keep one old linked object and remove a second original behind PostgreSQL.
live = upload(c,alice,chat,data)['json']
c.message(alice,chat,'keep live original',attachments=[live['id']])
missing = upload(c,alice,chat,data)['json']
message = c.message(alice,chat,'keep missing reference',attachments=[missing['id']])['json']
missing_key = sql("SELECT object_key FROM attachments WHERE id='"+missing['id']+"';")
probe.mc('rm','local/attachments/'+missing_key,admin=True)
current = reconcile(apply=True)
check(sql("SELECT status FROM attachments WHERE id='"+missing['id']+"';")=='ready','fresh metadata changed before grace')
result['fresh_metadata_preserved'] = current['fresh_skipped']>0
# Measure a real scan at two bucket sizes, crossing an S3 page boundary.
cost_prefix = 'original/cost-'+experiment+'/'
try:
for group,count,total in (('small',100,100),('extra',1000,1100)):
script = ('mkdir -p /tmp/cost/"$1"; i=1; while [ "$i" -le "$2" ]; do '
'printf x > /tmp/cost/"$1"/"$i"; i=$((i+1)); done')
docker('exec',probe.container,'/bin/sh','-c',script,'sh',group,str(count))
probe.mc('mirror','--quiet','/tmp/cost/'+group,'local/attachments/'+cost_prefix+group,admin=True)
summary = reconcile()
check(summary['objects_scanned']>=total,'scan skipped S3 objects')
result['cost'].append({'phase':'fresh', 'synthetic_objects':total, **summary})
print('Fresh scan cost:',json.dumps({k:summary[k] for k in ('objects_scanned','metadata_scanned','list_requests_estimate','stat_requests','db_queries','duration_ms')}),flush=True)
print('Waiting92s for actual S3 timestamps: measuring aged-object locking, DB and HEAD cost next.',flush=True)
time.sleep(92)
for total in (1100,100):
summary = reconcile()
check(summary['orphans']>=total,'aged scan did not inspect all orphan fixtures')
result['cost'].append({'phase':'aged', 'synthetic_objects':total, **summary})
print('Aged scan cost:',json.dumps({k:summary[k] for k in ('objects_scanned','metadata_scanned','list_requests_estimate','stat_requests','db_queries','duration_ms')}),flush=True)
if total==1100:
probe.mc('rm','--recursive','--force','local/attachments/'+cost_prefix+'extra/',admin=True)
finally:
probe.mc('rm','--recursive','--force','local/attachments/'+cost_prefix,admin=True)
# S3/DB unavailability must stop reconciliation without destructive guesses.
for service in ('minio','postgres'):
try:
docker('service','scale','--detach',STACK+'_'+service+'=0')
deadline=time.monotonic()+30
while time.monotonic()<deadline:
if not docker('ps','--filter','label=com.docker.swarm.service.name='+STACK+'_'+service,'-q').stdout.strip():
break
time.sleep(.3)
failed = docker('exec',containers('api')[0],'/usr/local/bin/reconcile','--apply','--grace=90s','--timeout=10s',check_result=False)
check(failed.returncode!=0,'reconciler succeeded with unavailable '+service)
result['faults'][service+'_unavailable'] = {'exit_nonzero':True, 'summary':json.loads(failed.stdout)}
finally:
docker('service','scale','--detach',STACK+'_'+service+'=1')
wait_ready()
check(orphan in objects(probe),'reconciler removed orphan while a store was unavailable')
remaining=92-(time.monotonic()-born)
if remaining>0:
print('Waiting for actual S3 object age to exceed90s grace:',round(remaining,1),'seconds',flush=True)
time.sleep(remaining)
sql("UPDATE attachments SET created_at=clock_timestamp()-interval '10 minutes' WHERE id IN ('"+live['id']+"','"+missing['id']+"');")
# A second process holds the upload lock: even an old orphan is protected.
lock_script = "BEGIN; SELECT pg_advisory_xact_lock(hashtextextended('"+orphan+"',0));\n"
lock = subprocess.Popen(['docker','exec','-i',containers('postgres')[0],'psql','-U','messenger','-d','messenger','-At','-v','ON_ERROR_STOP=1'],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
lock.stdin.write(lock_script.encode()); lock.stdin.flush()
try:
deadline = time.monotonic()+10
while sql("SELECT pg_try_advisory_xact_lock(hashtextextended('"+orphan+"',0));") != 'f':
check(time.monotonic()<deadline,'lock fixture did not acquire advisory lock')
time.sleep(.1)
locked = reconcile(apply=True)
check(locked['locked_skipped']>=1 and orphan in objects(probe),'upload lock did not protect orphan')
finally:
lock.stdin.write(b'ROLLBACK;\n'); lock.stdin.close()
lock.wait(timeout=15)
result['locked_candidate_preserved'] = True
# The apply above may mark the aged missing row; restore only its internal state
# to compare the following dry-run with an unchanged, well-defined fixture.
sql("UPDATE attachments SET status='ready',error_code=NULL WHERE id='"+missing['id']+"';")
dry = reconcile()
check(dry['orphans']>=1 and dry['missing']>=1,'dry-run did not detect injected inconsistencies')
check(orphan in objects(probe),'dry-run deleted an object')
check(sql("SELECT status FROM attachments WHERE id='"+missing['id']+"';")=='ready','dry-run modified metadata')
applied = reconcile(apply=True)
check(orphan not in objects(probe),'apply did not delete old orphan')
check(sql("SELECT status FROM attachments WHERE id='"+missing['id']+"';")=='failed','missing original not marked failed')
check(sql("SELECT count(*) FROM messages WHERE id='"+message['id']+"' AND '"+missing['id']+"'::uuid=ANY(attachment_ids);")=='1','repair deleted linked metadata or reference')
c.call('GET','/api/v1/attachments/'+missing['id'],409,actor=alice)
check(c.call('GET','/api/v1/attachments/'+live['id']+'/content',actor=bob)['bytes']==data,'repair deleted a live linked original')
repeated = reconcile(apply=True)
check(repeated['deleted']==0 and repeated['marked_failed']==0,'repeat apply was not idempotent')
result.update({'dry_run':dry, 'apply':applied, 'repeat_apply':repeated,
'live_linked_preserved':True, 'missing_linked_reference_preserved':True})
save('lab4-reconciliation.json',result)
print('PASS: real two-store faults, grace, lock, dry-run/apply/repeat, linked data preserved and paginated scan cost.')
if __name__=='__main__':
main()
+165
View File
@@ -0,0 +1,165 @@
#!/usr/bin/env python3
"""Grade-4 acceptance through the public LB; writes only synthetic test data."""
from concurrent.futures import ThreadPoolExecutor
import json
import os
from pathlib import Path
import subprocess
import sys
import threading
import time
import uuid
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT/'tests'))
from client import Client, Failure, check, run
from resilience import history
STACK = os.environ.get('STACK_NAME', 'mtusi-lab4')
def docker_json(*args):
return json.loads(subprocess.check_output(['docker', *args], text=True))
def task_ids():
ids = subprocess.check_output(['docker','service','ps','--filter','desired-state=running','-q',STACK+'_api'], text=True).split()
return {i for i in ids if docker_json('inspect',i)[0]['Status']['State']=='running'}
def wait_ready():
subprocess.run([sys.executable, str(ROOT/'scripts/swarm.py'), 'wait'], check=True, stdout=subprocess.DEVNULL)
time.sleep(3) # DNS and HAProxy rise interval
def idempotency(c, alice, bob, eve, chat):
key = uuid.uuid4().hex
barrier = threading.Barrier(16)
def send(_):
local = Client(timeout=5)
barrier.wait()
return local.message(alice, chat, 'one concurrent effect', key=key)
with ThreadPoolExecutor(max_workers=16) as pool:
results = list(pool.map(send, range(16)))
expected = results[0]['json']
check(all(r['json']==expected and r['status']==201 for r in results), 'concurrent replay changed result')
instances = {r['headers']['X-Instance-Id'] for r in results}
check(len(instances)>=2, 'same-key race did not reach two replicas')
path = '/api/v1/chats/'+chat['id']+'/messages'
c.call('POST', path, 409, actor=alice, body={'text':'changed'}, headers={'Idempotency-Key':key})
c.call('POST', path, 404, actor=eve, body={'text':expected['text']}, headers={'Idempotency-Key':key})
other = c.message(bob, chat, expected['text'], key=key)['json']
check(other['id']!=expected['id'], 'key leaked across users')
second_chat = c.call('POST','/api/v1/chats',201,actor=alice,body={'title':'Key scope','member_ids':[alice['id'],bob['id']]},schema='Chat')['json']
separate = c.message(alice,second_chat,expected['text'],key=key)['json']
check(separate['id']!=expected['id'], 'key leaked across chats')
for bad in ['', 'x'*129, 'bad key', 'bad,key', 'bad/key']:
c.call('POST', path, 400, actor=alice, body={'text':'invalid key'}, headers={'Idempotency-Key':bad})
c.message(alice,chat,'128 ASCII characters',key='x'*128)
retry = uuid.uuid4().hex
c.call('POST',path,400,actor=alice,body={'text':''},headers={'Idempotency-Key':retry})
c.message(alice,chat,'valid after invalid',key=retry)
check(sum(m['id']==expected['id'] for m in history(c,bob,chat))==1, 'race created duplicate')
# Revocation must be rechecked even for an already committed key.
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=alice)
c.call('POST',path,401,actor=alice,body={'text':expected['text']},headers={'Idempotency-Key':key})
print('PASS: shared-key race on two replicas; replay/conflict/scope/validation/access/logout', flush=True)
return {'parallel_requests':16, 'instances':sorted(instances), 'unique_message_ids':1}
def exercise(action, target=None):
c = Client(timeout=2)
alice,bob,eve,chat = c.bootstrap()
original_key = uuid.uuid4().hex
original = c.message(alice,chat,'confirmed before '+action,key=original_key)['json']
before = task_ids()
stop = threading.Event()
events = []
confirmations = []
lock = threading.Lock()
def worker(number):
local = Client(timeout=2)
key = uuid.uuid4().hex
body = 'load-'+key
while not stop.is_set():
started = time.monotonic()
try:
result = local.message(alice,chat,body,key=key)
with lock:
confirmations.append(result['json'])
local.call('GET','/api/v1/users/me',actor=bob,schema='User')
event = (started,time.monotonic(),result['json'],result['headers']['X-Instance-Id'],None)
key = uuid.uuid4().hex
body = 'load-'+key
except Failure as exc:
event = (started,time.monotonic(),None,None,str(exc))
with lock:
events.append(event)
time.sleep(.03)
threads = [threading.Thread(target=worker,args=(i,)) for i in range(4)]
for thread in threads: thread.start()
time.sleep(2)
env = dict(os.environ)
if target: env['TARGET_INSTANCE_ID'] = target
started = time.monotonic()
proc = subprocess.Popen([sys.executable,str(ROOT/'scripts/swarm.py'),action],env=env,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
try:
code = proc.wait(timeout=180)
check(code==0, action+' command failed')
completed = time.monotonic()
time.sleep(15 if target else 5)
finally:
stop.set()
for thread in threads: thread.join(timeout=10)
if proc.poll() is None:
proc.kill(); proc.wait()
ended = time.monotonic()
wait_ready()
window = [e for e in events if e[0]>=started]
successes = [e for e in window if e[2] is not None]
failures = [e for e in window if e[2] is None]
check(bool(successes), 'no writes during '+action)
recovery = min(e[1] for e in successes if e[0]>=completed)-started if target else None
if target:
check(recovery<=10, 'failure recovery exceeded 10 seconds')
check(target not in [e[3] for e in successes[-20:]], 'stopped instance returned')
check(target not in task_ids(), 'old task still running')
else:
check(before.isdisjoint(task_ids()), 'rolling update did not replace every replica')
replay = c.message(alice,chat,original['text'],key=original_key)['json']
check(replay==original, 'committed idempotency result lost after '+action)
all_messages = history(c,bob,chat)
by_id = {m['id']:m for m in all_messages}
check(by_id.get(original['id'])==original, 'pre-action confirmation lost')
check(all(by_id.get(m['id'])==m for m in confirmations), 'confirmation lost/changed')
texts = [m['text'] for m in all_messages]
check(len(texts)==len(set(texts)), 'uncertain retry created duplicate')
times = [started]+sorted(e[1] for e in successes)+[ended]
max_gap = max(b-a for a,b in zip(times,times[1:]))
check(max_gap<=10, 'writes stalled for more than 10 seconds')
report = {'action':action,'target':target,'duration_seconds':round(ended-started,3),
'successful_writes':len(successes),'failed_attempts':len(failures),
'successful_rps':round(len(successes)/(ended-started),3),
'first_recovery_seconds':round(recovery,3) if recovery is not None else None,
'max_success_gap_seconds':round(max_gap,3),
'instances_before':sorted(before),'instances_after':sorted(task_ids()),
'confirmed_messages_checked':len(confirmations)+1,
'duplicate_bodies':0}
print(json.dumps(report),flush=True)
return report
def main():
wait_ready()
c = Client()
results = {'idempotency':idempotency(c,*c.bootstrap())}
originals = sorted(task_ids())
check(len(originals)==2,'grade4 scenario expects exactly two API replicas')
results['failovers'] = [exercise('stop-one',target) for target in originals]
results['rolling_update'] = exercise('update')
(ROOT/'evidence/swarm-grade4.json').write_text(json.dumps(results,indent=2)+'\n')
print('PASS: each original replica stopped and replaced; rolling update under load; confirmations and sessions preserved')
if __name__=='__main__':
run(main)