200 lines
8.7 KiB
Python
Executable File
200 lines
8.7 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 base64
|
|
import datetime as dt
|
|
import json
|
|
import re
|
|
import sys
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
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 direct(api_container, path, headers=None, body=None):
|
|
"""Call an API process on its container loopback, bypassing the LB.
|
|
|
|
During a shared-dependency outage HAProxy correctly removes every unready
|
|
backend, so the LB itself answers 503 and cannot show the API's JSON error.
|
|
The process-level contract is therefore checked directly, while the LB
|
|
outage status is recorded separately.
|
|
"""
|
|
command = ['docker', 'exec', api_container, 'wget', '-S', '-O', '-',
|
|
'-T', '3']
|
|
if body is not None:
|
|
command.extend(['--post-data', body])
|
|
for key, value in (headers or {}).items():
|
|
command.extend(['--header', key + ': ' + value])
|
|
command.append('http://127.0.0.1:8080' + path)
|
|
result = M.run(command, check=False)
|
|
match = re.search(r'HTTP/\d\.\d (\d{3})', result.stderr)
|
|
status = int(match.group(1)) if match else 0
|
|
payload = None
|
|
try:
|
|
payload = json.loads(result.stdout)
|
|
except ValueError:
|
|
pass
|
|
return status, payload
|
|
|
|
|
|
def lb_status(path, headers=None):
|
|
request = urllib.request.Request('http://127.0.0.1:8083' + path, headers=headers or {})
|
|
try:
|
|
with urllib.request.urlopen(request, timeout=3) as response:
|
|
return response.status, response.headers.get('X-Instance-Id'), response.read(4096)
|
|
except urllib.error.HTTPError as error:
|
|
return error.code, error.headers.get('X-Instance-Id'), error.read(4096)
|
|
|
|
|
|
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']
|
|
api_container = M.containers('api')[0]['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_status, live = direct(api_container, '/health/live')
|
|
observed['direct_live_status'] = live_status
|
|
observed['direct_live_body'] = live
|
|
ready_status, ready = direct(api_container, '/health/ready')
|
|
observed['direct_ready_status'] = ready_status
|
|
observed['direct_ready_code'] = (ready or {}).get('error', {}).get('code')
|
|
bearer = {'Authorization': 'Bearer ' + actor['token']}
|
|
protected_status, protected = direct(api_container, '/api/v1/users/me', bearer)
|
|
observed['direct_protected_status'] = protected_status
|
|
observed['direct_protected_code'] = (protected or {}).get('error', {}).get('code')
|
|
anonymous_status, anonymous = direct(api_container, '/api/v1/users/me')
|
|
observed['direct_anonymous_status'] = anonymous_status
|
|
credential = base64.b64encode((actor['registration']['username'] + ':' +
|
|
actor['registration']['password']).encode()).decode()
|
|
login_status, login_error = direct(api_container, '/api/v1/auth/sessions',
|
|
{'Authorization': 'Basic ' + credential}, '')
|
|
observed['direct_login_status'] = login_status
|
|
observed['direct_login_code'] = (login_error or {}).get('error', {}).get('code')
|
|
write_status, write_error = direct(
|
|
api_container, '/api/v1/chats/' + chat['id'] + '/messages',
|
|
dict(bearer, **{'Content-Type': 'application/json',
|
|
'Idempotency-Key': 'fail-' + dt.datetime.now().strftime('%H%M%S%f')}),
|
|
'{"text":"во время отказа"}')
|
|
observed['direct_write_status'] = write_status
|
|
observed['direct_write_code'] = (write_error or {}).get('error', {}).get('code')
|
|
|
|
lb_live_status, lb_instance, _ = lb_status('/health/live')
|
|
observed['lb_live_status_during_outage'] = lb_live_status
|
|
observed['lb_live_instance_header'] = lb_instance
|
|
lb_ready_status, lb_ready_instance, _ = lb_status('/health/ready')
|
|
observed['lb_ready_status_during_outage'] = lb_ready_status
|
|
observed['lb_ready_instance_header'] = lb_ready_instance
|
|
|
|
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: direct live=%d ready=%d protected=%d login=%d write=%d; LB live=%d ready=%d; recovery %.3fs; volumes preserved=%s' % (
|
|
dependency, observed['direct_live_status'], observed['direct_ready_status'],
|
|
observed['direct_protected_status'], observed['direct_login_status'],
|
|
observed['direct_write_status'], observed['lb_live_status_during_outage'],
|
|
observed['lb_ready_status_during_outage'], 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)
|