forked from mtusi2026/mtusi2026lab3
145 lines
6.2 KiB
Python
Executable File
145 lines
6.2 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Level-3/4 shared-dependency outage evidence.
|
|
|
|
Stops the real PostgreSQL container, then the real Valkey container, while
|
|
HAProxy and both API processes keep running. Verifies bounded 503 responses,
|
|
liveness, recovery through the LB, the same still-valid session token and
|
|
untouched named volumes. Never removes volumes. Python 3.9+.
|
|
"""
|
|
import argparse
|
|
import datetime as dt
|
|
import json
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / 'tests'))
|
|
sys.path.insert(0, str(ROOT / 'scripts'))
|
|
from client import Client # noqa: E402
|
|
import lab3_metrics as M # noqa: E402
|
|
|
|
OUT = ROOT / 'evidence/failure-checks.json'
|
|
|
|
|
|
def now():
|
|
return dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00', 'Z')
|
|
|
|
|
|
def wait_healthy(container, timeout=60):
|
|
deadline = time.monotonic() + timeout
|
|
while time.monotonic() < deadline:
|
|
status = M.run(['docker', 'inspect', '-f', '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}',
|
|
container]).stdout.strip()
|
|
if status in ('healthy', 'running'):
|
|
return True
|
|
time.sleep(0.25)
|
|
return False
|
|
|
|
|
|
def service_container(name):
|
|
return M.containers(name)[0]
|
|
|
|
|
|
def volumes():
|
|
names = set()
|
|
for name in ('postgres', 'valkey'):
|
|
data = json.loads(M.run(['docker', 'inspect', service_container(name)['container_id']]).stdout)[0]
|
|
for mount in data.get('Mounts', []):
|
|
if mount.get('Type') == 'volume':
|
|
names.add(mount.get('Name'))
|
|
return sorted(names)
|
|
|
|
|
|
def outage(c, actor, chat, dependency):
|
|
container = service_container(dependency)['container_id']
|
|
before_volumes = volumes()
|
|
before_counts = M.db_snapshot()['datasets'] if dependency == 'valkey' else None
|
|
stop_started = time.monotonic()
|
|
M.run(['docker', 'stop', container])
|
|
stop_seconds = time.monotonic() - stop_started
|
|
time.sleep(1.0)
|
|
observed = {'dependency': dependency, 'container': container,
|
|
'stopped_at': now(), 'stop_seconds': round(stop_seconds, 3)}
|
|
live = c.call('GET', '/health/live', schema='Health')
|
|
observed['live_status'] = live['status']
|
|
observed['live_has_instance'] = bool(live['headers'].get('X-Instance-Id'))
|
|
ready = c.call('GET', '/health/ready', 503)
|
|
observed['ready_status'] = ready['status']
|
|
observed['ready_code'] = ready['json']['error']['code']
|
|
protected = c.call('GET', '/api/v1/users/me', 503, actor=actor)
|
|
observed['protected_status'] = protected['status']
|
|
observed['protected_code'] = protected['json']['error']['code']
|
|
anonymous = c.call('GET', '/api/v1/users/me', 401)
|
|
observed['anonymous_status'] = anonymous['status']
|
|
login_error = c.call('POST', '/api/v1/auth/sessions', 503,
|
|
headers={'Authorization': 'Basic ' + __import__('base64').b64encode(
|
|
(actor['registration']['username'] + ':' + actor['registration']['password']).encode()).decode()})
|
|
observed['login_status'] = login_error['status']
|
|
write_error = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 503,
|
|
actor=actor, body={'text': 'во время отказа'},
|
|
headers={'Idempotency-Key': 'fail-' + dt.datetime.now().strftime('%H%M%S%f')})
|
|
observed['write_status'] = write_error['status']
|
|
|
|
restore_started = time.monotonic()
|
|
M.run(['docker', 'start', container])
|
|
if not wait_healthy(container):
|
|
raise RuntimeError('dependency did not become healthy after start')
|
|
ready_deadline = time.monotonic() + 30
|
|
while time.monotonic() < ready_deadline:
|
|
response = c.call('GET', '/health/ready', (200, 503))
|
|
if response['status'] == 200:
|
|
break
|
|
time.sleep(0.1)
|
|
else:
|
|
raise RuntimeError('LB readiness did not recover')
|
|
recovery_seconds = time.monotonic() - restore_started
|
|
observed['recovery_seconds_to_ready'] = round(recovery_seconds, 3)
|
|
observed['restored_at'] = now()
|
|
me = c.call('GET', '/api/v1/users/me', actor=actor, schema='User')['json']
|
|
observed['same_token_user_id'] = me['id']
|
|
observed['same_token'] = me['id'] == actor['id']
|
|
history = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=100',
|
|
actor=actor, schema='MessagePage')['json']
|
|
observed['history_items'] = len(history['items'])
|
|
after_volumes = volumes()
|
|
observed['volumes_before'] = before_volumes
|
|
observed['volumes_after'] = after_volumes
|
|
observed['volumes_preserved'] = before_volumes == after_volumes
|
|
if before_counts is not None:
|
|
observed['counts_unchanged'] = before_counts == M.db_snapshot()['datasets']
|
|
return observed
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description='Stop PostgreSQL and Valkey under the lab3 LB')
|
|
parser.add_argument('--base-url', default='http://127.0.0.1:8083')
|
|
parser.add_argument('--output', default='evidence/failure-checks.json')
|
|
args = parser.parse_args()
|
|
global OUT
|
|
OUT = (ROOT / args.output).resolve()
|
|
c = Client(args.base_url)
|
|
alice, bob, eve, chat = c.bootstrap()
|
|
message = c.message(alice, chat, 'до отказа зависимостей')['json']
|
|
result = {'checked_at': now(), 'base_url': args.base_url, 'initial_message': message['id'],
|
|
'outages': []}
|
|
for dependency in ('postgres', 'valkey'):
|
|
observed = outage(c, alice, chat, dependency)
|
|
result['outages'].append(observed)
|
|
print('%s: ready=%d protected=%d login=%d write=%d, recovery %.3fs, volumes preserved=%s' % (
|
|
dependency, observed['ready_status'], observed['protected_status'],
|
|
observed['login_status'], observed['write_status'],
|
|
observed['recovery_seconds_to_ready'], observed['volumes_preserved']))
|
|
result['result'] = 'PASS'
|
|
OUT.parent.mkdir(parents=True, exist_ok=True)
|
|
OUT.write_text(json.dumps(result, indent=2, ensure_ascii=False) + '\n')
|
|
print('PASS: dependency outages produced bounded 503, then recovered with the same token')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
try:
|
|
main()
|
|
except Exception as exc: # noqa: BLE001
|
|
print('FAIL:', exc)
|
|
raise SystemExit(1)
|