lab 3 done
This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
# Собственные проверки lab3
|
||||
|
||||
Публичные 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 и 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 текущей работы.
|
||||
@@ -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)
|
||||
@@ -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-lab3')
|
||||
|
||||
|
||||
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)
|
||||
Reference in New Issue
Block a user