#!/usr/bin/env python3 """Dependency-outage checks for lab2. Stops and starts the real lab2 containers with `docker stop` / `docker start`. Volumes are never removed. It verifies the level-4 requirement that loss of Valkey or PostgreSQL produces a bounded 503 and never turns an anonymous request into a trusted one, and that recovery keeps the existing session and confirmed data. The operator is expected to run this against the local teaching stand only. """ import base64 import datetime as dt import json import subprocess import sys import time import urllib.error import urllib.request import uuid from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / 'tests')) from client import Client, Failure, arguments, check # noqa: E402 POSTGRES = 'mtusi-lab2-melnikov-postgres' VALKEY = 'mtusi-lab2-melnikov-valkey' VOLUMES = ['mtusi-lab2-melnikov-pgdata', 'mtusi-lab2-melnikov-valkeydata'] def docker(*args, quiet=False): result = subprocess.run(['docker'] + list(args), capture_output=True, text=True) if result.returncode != 0: raise Failure('docker ' + ' '.join(args) + ' failed: ' + result.stderr.strip()[:200]) return result.stdout.strip() def inspect_state(name): raw = docker('inspect', name) return json.loads(raw)[0] def http(base, method, path, token=None, body=None, timeout=10, extra_headers=None): headers = {'Accept': 'application/json'} data = None if token: headers['Authorization'] = 'Bearer ' + token if extra_headers: headers.update(extra_headers) if body is not None: data = json.dumps(body).encode('utf-8') headers['Content-Type'] = 'application/json' request = urllib.request.Request(base + path, data=data, headers=headers, method=method) try: with urllib.request.urlopen(request, timeout=timeout) as response: raw = response.read() return response.status, dict(response.headers), json.loads(raw) if raw else None except urllib.error.HTTPError as error: raw = error.read() return error.code, dict(error.headers), json.loads(raw) if raw else None except Exception: # noqa: BLE001 - a refused connection is an expected observation return None, {}, None def wait_status(base, path, expected, timeout=45): deadline = time.monotonic() + timeout last = None while time.monotonic() < deadline: status, _, _ = http(base, 'GET', path) last = status if status == expected: return time.sleep(0.5) raise Failure('%s did not reach %s within %ss (last %r)' % (path, expected, timeout, last)) def expect_unavailable(base, path, token=None): status, headers, payload = http(base, 'GET', path, token=token) check(status == 503, path + ' expected 503, got %r' % (status,)) check(payload and payload.get('error', {}).get('code') == 'unavailable', path + ' error code') check(payload['error']['request_id'] == headers.get('X-Request-Id'), path + ' request id mismatch') return {'path': path, 'status': status, 'code': payload['error']['code']} def main(): def configure(parser): parser.add_argument('--output', default=None, help='optional JSON evidence path') args = arguments('Stop/start Valkey and PostgreSQL; volumes are preserved', configure) c = Client(args.base_url, args.ca_file) actor = c.user('failure') chat = c.call('POST', '/api/v1/chats', 201, actor=actor, body={'title': 'Отказ зависимости', 'member_ids': [actor['id']]}, schema='Chat')['json'] probe = 'failure-probe-' + uuid.uuid4().hex message = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=actor, body={'text': probe}, schema='Message')['json'] volume_before = {name: inspect_state(name)['Mountpoint'] for name in VOLUMES} states_before = {name: inspect_state(name)['State']['StartedAt'] for name in (POSTGRES, VALKEY)} observations = {'probe_message_id': message['id'], 'volumes_before': volume_before, 'containers_started_before': states_before} try: # ---- Valkey outage ------------------------------------------------- docker('stop', '--time', '20', VALKEY) stopped = time.monotonic() wait_status(args.base_url, '/health/ready', 503) valkey = {} status, headers, payload = http(args.base_url, 'GET', '/health/live') check(status == 200 and payload == {'status': 'ok'}, 'liveness must stay 200 without Valkey') valkey['liveness'] = {'status': status, 'body': payload} valkey['readiness'] = {'status': 503} valkey['authenticated_request'] = expect_unavailable(args.base_url, '/api/v1/users/me', actor['token']) status, headers, payload = http(args.base_url, 'GET', '/api/v1/users/me') check(status == 401 and payload['error']['code'] == 'unauthorized', 'anonymous request without Valkey must stay 401') valkey['anonymous_request'] = {'status': status, 'code': payload['error']['code']} credential = 'Basic ' + base64.b64encode( (actor['registration']['username'] + ':' + actor['registration']['password']).encode('utf-8')).decode('ascii') status, headers, payload = http(args.base_url, 'POST', '/api/v1/auth/sessions', extra_headers={'Authorization': credential}) check(status == 503 and payload['error']['code'] == 'unavailable', 'login with valid credentials must be a bounded 503 without Valkey') valkey['login'] = {'status': status, 'code': payload['error']['code']} # Registration only needs PostgreSQL; it is allowed to work while the # session store is down, and proves the outage is bounded to sessions. outage_user = 'outage_' + uuid.uuid4().hex[:10] status, headers, payload = http(args.base_url, 'POST', '/api/v1/users', body={ 'username': outage_user, 'display_name': 'Во время отказа Valkey', 'password': 'Outage-password-123', }) check(status == 201 and payload['username'] == outage_user, 'registration should be independent of the session store') valkey['registration_while_down'] = {'status': status} # ---- Valkey recovery ---------------------------------------------- docker('start', VALKEY) wait_status(args.base_url, '/health/ready', 200) valkey['recovery_seconds'] = round(time.monotonic() - stopped, 3) status, _, payload = http(args.base_url, 'GET', '/api/v1/users/me', token=actor['token']) check(status == 200 and payload['id'] == actor['id'], 'existing session did not survive the Valkey stop/start') valkey['session_after_recovery'] = {'status': status} observations['valkey_outage'] = valkey # ---- PostgreSQL outage -------------------------------------------- docker('stop', '--time', '20', POSTGRES) stopped = time.monotonic() wait_status(args.base_url, '/health/ready', 503) postgres = {} status, _, payload = http(args.base_url, 'GET', '/health/live') check(status == 200 and payload == {'status': 'ok'}, 'liveness must stay 200 without PostgreSQL') postgres['liveness'] = {'status': status, 'body': payload} postgres['readiness'] = {'status': http(args.base_url, 'GET', '/health/ready')[0]} postgres['authenticated_request'] = expect_unavailable(args.base_url, '/api/v1/users/me', actor['token']) status, _, payload = http(args.base_url, 'GET', '/api/v1/users/me') check(status == 401, 'anonymous request without PostgreSQL must stay 401') postgres['anonymous_request'] = {'status': status, 'code': payload['error']['code']} status, _, payload = http(args.base_url, 'POST', '/api/v1/users', body={ 'username': 'unreachable_' + uuid.uuid4().hex[:8], 'display_name': 'Не должно создаться', 'password': 'Outage-password-123', }) check(status == 503 and payload['error']['code'] == 'unavailable', 'registration must be a bounded 503 without PostgreSQL') postgres['registration'] = {'status': status, 'code': payload['error']['code']} # ---- PostgreSQL recovery ------------------------------------------ docker('start', POSTGRES) wait_status(args.base_url, '/health/ready', 200) postgres['recovery_seconds'] = round(time.monotonic() - stopped, 3) status, _, payload = http(args.base_url, 'GET', '/api/v1/users/me', token=actor['token']) check(status == 200 and payload['id'] == actor['id'], 'existing session did not survive the PostgreSQL stop/start') postgres['session_after_recovery'] = {'status': status} status, _, payload = http( args.base_url, 'GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=100', token=actor['token']) check(status == 200 and any(item['id'] == message['id'] for item in payload['items']), 'confirmed message was lost across the PostgreSQL stop/start') postgres['message_after_recovery'] = {'status': status, 'found': True} observations['postgres_outage'] = postgres finally: for name in (POSTGRES, VALKEY): state = inspect_state(name)['State'] if not state['Running']: docker('start', name) try: wait_status(args.base_url, '/health/ready', 200) except Failure: pass volume_after = {name: inspect_state(name)['Mountpoint'] for name in VOLUMES} states_after = {name: inspect_state(name)['State']['StartedAt'] for name in (POSTGRES, VALKEY)} check(volume_after == volume_before, 'named volumes changed or were removed during the outage test') check(all(states_after[name] != states_before[name] for name in states_before), 'containers were not really restarted') observations['volumes_after'] = volume_after observations['containers_started_after'] = states_after observations['finished_at'] = dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00', 'Z') if args.output: destination = Path(args.output) destination.parent.mkdir(parents=True, exist_ok=True) destination.write_text(json.dumps(observations, indent=2, ensure_ascii=False) + '\n') print(json.dumps({'valkey_recovery_seconds': observations['valkey_outage']['recovery_seconds'], 'postgres_recovery_seconds': observations['postgres_outage']['recovery_seconds'], 'volumes_kept': sorted(volume_after), 'workers_really_restarted': True}, ensure_ascii=False, sort_keys=True)) print('PASS: bounded 503 on Valkey/PostgreSQL outage; session and data survive recovery; volumes kept') if __name__ == '__main__': try: main() except AssertionError as exc: print('FAIL:', exc) raise SystemExit(1)