diff --git a/compose.yaml b/compose.yaml index f6ffc8f1..b062c46a 100644 --- a/compose.yaml +++ b/compose.yaml @@ -10,7 +10,7 @@ # Stop: make stop (processes stopped, named volumes and data preserved) # Remove: make down (containers removed, volumes preserved) # Purge: make purge (containers AND named volumes removed; explicit data loss) -name: mtusi-lab3-melnikov +name: ${COMPOSE_PROJECT_NAME:-mtusi-lab3-melnikov} x-api-build: &api-build context: . @@ -217,10 +217,10 @@ services: volumes: pgdata: - name: mtusi-lab3-melnikov-pgdata + name: ${COMPOSE_PROJECT_NAME:-mtusi-lab3-melnikov}-pgdata valkeydata: - name: mtusi-lab3-melnikov-valkeydata + name: ${COMPOSE_PROJECT_NAME:-mtusi-lab3-melnikov}-valkeydata networks: backend: - name: mtusi-lab3-melnikov-net + name: ${COMPOSE_PROJECT_NAME:-mtusi-lab3-melnikov}-net diff --git a/evidence/track1/raw/fixed-r1-rep1.json b/evidence/track1/raw/fixed-r1-rep1.json deleted file mode 100644 index 7bd70a0a..00000000 --- a/evidence/track1/raw/fixed-r1-rep1.json +++ /dev/null @@ -1,209 +0,0 @@ -{ - "tool": "mtusi-lab3-loadgen", - "version": "dev", - "started_at": "2026-12-02T15:26:05.520383Z", - "finished_at": "2026-12-02T15:26:25.525989Z", - "measured_seconds": 20.006, - "warmup_seconds": 5, - "concurrency": 32, - "rate_limit_per_second": 0, - "read_ratio": 0, - "retry_uncertain": false, - "profile": "closed-loop", - "successful_requests": 50081, - "failed_requests": 0, - "error_ratio": 0, - "successful_rps": 2503.305, - "offered_rps": 2503.305, - "successful_latency_ms": { - "p50": 9.898, - "p95": 30.124, - "p99": 45.284, - "max": 101.78, - "mean": 12.772 - }, - "status_counts": { - "201": 50081 - }, - "instances": { - "c98d67f83aff": 50081 - }, - "app_versions": { - "1.0.0": 50081 - }, - "kinds": { - "write": 50081 - }, - "series": [ - { - "second": 1796225165, - "success": 1248, - "errors": 0, - "p50_ms": 9.678, - "p95_ms": 28.221, - "p99_ms": 30.453 - }, - { - "second": 1796225166, - "success": 2789, - "errors": 0, - "p50_ms": 9.535, - "p95_ms": 24.788, - "p99_ms": 31.637 - }, - { - "second": 1796225167, - "success": 2730, - "errors": 0, - "p50_ms": 9.585, - "p95_ms": 26.788, - "p99_ms": 33.782 - }, - { - "second": 1796225168, - "success": 2402, - "errors": 0, - "p50_ms": 9.654, - "p95_ms": 34.211, - "p99_ms": 52.39 - }, - { - "second": 1796225169, - "success": 2067, - "errors": 0, - "p50_ms": 11.633, - "p95_ms": 35.307, - "p99_ms": 46.827 - }, - { - "second": 1796225170, - "success": 2741, - "errors": 0, - "p50_ms": 9.431, - "p95_ms": 26.111, - "p99_ms": 38.947 - }, - { - "second": 1796225171, - "success": 2678, - "errors": 0, - "p50_ms": 9.413, - "p95_ms": 28.329, - "p99_ms": 42.157 - }, - { - "second": 1796225172, - "success": 2368, - "errors": 0, - "p50_ms": 10.828, - "p95_ms": 29.231, - "p99_ms": 38.489 - }, - { - "second": 1796225173, - "success": 2294, - "errors": 0, - "p50_ms": 10.463, - "p95_ms": 34.586, - "p99_ms": 44.744 - }, - { - "second": 1796225174, - "success": 2759, - "errors": 0, - "p50_ms": 9.349, - "p95_ms": 26.482, - "p99_ms": 40.701 - }, - { - "second": 1796225175, - "success": 2839, - "errors": 0, - "p50_ms": 9.222, - "p95_ms": 27.333, - "p99_ms": 36.243 - }, - { - "second": 1796225176, - "success": 2696, - "errors": 0, - "p50_ms": 9.674, - "p95_ms": 29.684, - "p99_ms": 35.313 - }, - { - "second": 1796225177, - "success": 2787, - "errors": 0, - "p50_ms": 9.386, - "p95_ms": 25.722, - "p99_ms": 48.056 - }, - { - "second": 1796225178, - "success": 2305, - "errors": 0, - "p50_ms": 10.919, - "p95_ms": 31.339, - "p99_ms": 40.262 - }, - { - "second": 1796225179, - "success": 1493, - "errors": 0, - "p50_ms": 11.568, - "p95_ms": 61.363, - "p99_ms": 68.795 - }, - { - "second": 1796225180, - "success": 2075, - "errors": 0, - "p50_ms": 11.519, - "p95_ms": 40.011, - "p99_ms": 55.483 - }, - { - "second": 1796225181, - "success": 2757, - "errors": 0, - "p50_ms": 9.601, - "p95_ms": 29.591, - "p99_ms": 34.011 - }, - { - "second": 1796225182, - "success": 2689, - "errors": 0, - "p50_ms": 9.915, - "p95_ms": 26.276, - "p99_ms": 35.526 - }, - { - "second": 1796225183, - "success": 2323, - "errors": 0, - "p50_ms": 10.359, - "p95_ms": 30.561, - "p99_ms": 73.07 - }, - { - "second": 1796225184, - "success": 2711, - "errors": 0, - "p50_ms": 9.542, - "p95_ms": 28.308, - "p99_ms": 32.276 - }, - { - "second": 1796225185, - "success": 1330, - "errors": 0, - "p50_ms": 10.098, - "p95_ms": 26.991, - "p99_ms": 37.346 - } - ], - "uncertain_retries": 0, - "note": "track1 fixed-r1-rep1; replicas=1 cpu_per=0.8 mem_per=512M; synthetic messages created by loadgen, no retries unless -retry-uncertain" -} diff --git a/scripts/container-checks.py b/scripts/container-checks.py new file mode 100755 index 00000000..103e41ac --- /dev/null +++ b/scripts/container-checks.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python3 +"""Level-3/4 infrastructure evidence for the lab3 Compose stand. + +Checks actual Docker state, not just compose.yaml: distinct API processes, +no published API port, LB as the only entrypoint, CPU/RAM limits, non-root +read-only API, named volumes and a session shared across replicas. +Python 3.9+, standard library only. +""" +import argparse +import datetime as dt +import json +import subprocess +import sys +import uuid +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, check # noqa: E402 +import lab3_metrics as M # noqa: E402 + +OUT = ROOT / 'evidence/container-checks.json' + + +def now(): + return dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00', 'Z') + + +def inspect(container): + return json.loads(M.run(['docker', 'inspect', container]).stdout)[0] + + +def main(): + parser = argparse.ArgumentParser(description='Lab3 container/infrastructure checks') + parser.add_argument('--base-url', default='http://127.0.0.1:8083') + parser.add_argument('--image', default='mtusi-messenger-lab3-melnikov:local') + parser.add_argument('--output', default='evidence/container-checks.json') + args = parser.parse_args() + global OUT + OUT = (ROOT / args.output).resolve() + checks = {} + + compose_text = (ROOT / 'compose.yaml').read_text() + checks['no_container_name_in_compose'] = 'container_name:' not in compose_text + + api = M.containers('api') + lb = M.containers('lb') + postgres = M.containers('postgres') + valkey = M.containers('valkey') + check(len(api) >= 2, 'expected at least two running API containers') + check(len(lb) == 1 and len(postgres) == 1 and len(valkey) == 1, 'expected one shared LB/DB/session container') + + checks['api_replica_count'] = len(api) + checks['api_container_ids_distinct'] = len({item['container_id'] for item in api}) == len(api) + checks['api_instance_ids_distinct'] = len({item['hostname'] for item in api}) == len(api) + checks['api_images'] = sorted({item['image_id'] for item in api}) + checks['api_image_matches_expected_tag'] = all('lab3' in item['image_ref'] for item in api) + + api_ports = {} + for item in api: + ports = M.run(['docker', 'port', item['container_id']]).stdout.strip() + api_ports[item['name']] = ports + checks['api_has_no_published_ports'] = all(value == '' for value in api_ports.values()) + checks['api_ports'] = api_ports + lb_ports = M.run(['docker', 'port', lb[0]['container_id']]).stdout.strip() + checks['lb_published_loopback_only'] = lb_ports.startswith('127.0.0.1:8083->8080/tcp') + checks['lb_ports'] = lb_ports + + limits = {} + for service, items in (('api', api), ('postgres', postgres), ('valkey', valkey), ('lb', lb)): + limits[service] = [{'name': item['name'], 'nano_cpus': item['cpu_limit_nano'], + 'memory_bytes': item['memory_limit_bytes'], + 'cpu_max': item['cpu_max'], 'memory_max': item['memory_max']} + for item in items] + checks['all_services_have_cpu_and_memory_limits'] = all( + item['nano_cpus'] > 0 and item['memory_limit_bytes'] > 0 + for values in limits.values() for item in values) + checks['limits'] = limits + + api_security = [] + for item in api: + data = inspect(item['container_id']) + api_security.append({ + 'name': item['name'], + 'user': data['Config'].get('User'), + 'read_only_rootfs': data['HostConfig'].get('ReadonlyRootfs'), + 'cap_drop': data['HostConfig'].get('CapDrop'), + 'security_opt': data['HostConfig'].get('SecurityOpt'), + 'restart_policy': data['HostConfig'].get('RestartPolicy', {}).get('Name'), + 'stop_grace_period_ns': data['Config'].get('StopTimeout'), + 'networks': sorted((data.get('NetworkSettings') or {}).get('Networks', {}).keys()), + 'mounts': [mount.get('Name') or mount.get('Source') for mount in data.get('Mounts', [])], + }) + checks['api_security'] = api_security + checks['api_non_root'] = all(item['user'] and item['user'].startswith('10001') for item in api_security) + checks['api_read_only_rootfs'] = all(item['read_only_rootfs'] for item in api_security) + checks['api_cap_drop_all'] = all(item['cap_drop'] == ['ALL'] for item in api_security) + checks['api_no_new_privileges'] = all( + any('no-new-privileges' in value for value in (item['security_opt'] or [])) + for item in api_security) + checks['api_has_no_state_volume'] = all(not item['mounts'] for item in api_security) + checks['all_on_same_backend_network'] = all( + item['networks'] == ['mtusi-lab3-melnikov-net'] for item in api_security) + + volume_names = set() + for container in (postgres[0]['container_id'], valkey[0]['container_id']): + data = inspect(container) + for mount in data.get('Mounts', []): + if mount.get('Type') == 'volume': + volume_names.add(mount.get('Name')) + checks['named_volumes'] = sorted(volume_names) + checks['volumes_have_prefix'] = all(name.startswith('mtusi-lab3-melnikov-') for name in volume_names) + + c = Client(args.base_url) + alice, bob, eve, chat = c.bootstrap() + observed = set() + for _ in range(30): + response = c.call('GET', '/api/v1/users/me', actor=alice, schema='User') + observed.add(response['headers']['X-Instance-Id']) + checks['observed_instances'] = sorted(observed) + checks['session_crosses_replicas'] = len(observed) >= 2 + checks['session_instances_are_api_hostnames'] = observed.issubset({item['hostname'] for item in api}) + health = c.call('GET', '/health/ready', schema='Health') + checks['health_ready_via_lb'] = health['status'] == 200 + checks['health_instance_is_api'] = health['headers']['X-Instance-Id'] in observed + + # The API never publishes a host port; a direct connection to a container + # IP is still possible from the host on Linux, but compose exposes none. + checks['public_entrypoint_is_lb'] = lb_ports.startswith('127.0.0.1:8083') + + failed = [key for key, value in checks.items() if isinstance(value, bool) and not value] + checks['result'] = 'PASS' if not failed else 'FAIL' + checks['failed'] = failed + checks['checked_at'] = now() + checks['base_url'] = args.base_url + OUT.parent.mkdir(parents=True, exist_ok=True) + OUT.write_text(json.dumps(checks, indent=2, ensure_ascii=False) + '\n') + lines = ['lab3 container checks at ' + checks['checked_at'], + 'result: ' + checks['result'], + 'API replicas: %d (%s)' % (len(api), ', '.join(item['hostname'] for item in api)), + 'API ports published: %r' % api_ports, + 'LB ports: ' + lb_ports, + 'volumes: ' + ', '.join(checks['named_volumes']), + 'limits: ' + json.dumps(limits, separators=(',', ':')), + 'observed session instances: ' + ', '.join(sorted(observed))] + (ROOT / 'evidence/container-checks.txt').write_text('\n'.join(lines) + '\n') + print('\n'.join(lines)) + if failed: + raise SystemExit('FAILED checks: ' + ', '.join(failed)) + print('PASS: container and infrastructure checks') + + +if __name__ == '__main__': + try: + main() + except Exception as exc: # noqa: BLE001 + print('FAIL:', exc) + raise SystemExit(1) diff --git a/scripts/db-checks.py b/scripts/db-checks.py new file mode 100755 index 00000000..695109cb --- /dev/null +++ b/scripts/db-checks.py @@ -0,0 +1,166 @@ +#!/usr/bin/env python3 +"""SQL-level lab3 evidence: schema, constraints, idempotency records, +migration idempotence and password-hash shape. Python 3.9+. + +All SQL runs inside the lab3 PostgreSQL container with ON_ERROR_STOP=1. The +script creates only synthetic users/messages through the public API. +""" +import argparse +import datetime as dt +import json +import sys +import uuid +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, check # noqa: E402 +import lab3_metrics as M # noqa: E402 + +OUT = ROOT / 'evidence/db-checks.json' + + +def now(): + return dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00', 'Z') + + +def sql_json(sql): + return M.psql_json(sql) + + +def sql_text(sql): + container = M.containers('postgres')[0]['container_id'] + result = M.run(['docker', 'exec', '-i', container, 'psql', '-X', '-A', '-t', + '-v', 'ON_ERROR_STOP=1', '-U', M.ENV['POSTGRES_USER'], + '-d', M.ENV['POSTGRES_DB'], '-c', sql]) + return result.stdout.strip() + + +def main(): + parser = argparse.ArgumentParser(description='Lab3 SQL checks') + parser.add_argument('--base-url', default='http://127.0.0.1:8083') + parser.add_argument('--output', default='evidence/db-checks.json') + args = parser.parse_args() + global OUT + OUT = (ROOT / args.output).resolve() + checks = {} + + versions = sql_text("SELECT string_agg(version::text, ',' ORDER BY version) FROM schema_migrations;") + checks['migration_versions'] = versions + checks['migration_versions_expected'] = versions == '1,2,3' + tables = sql_text("SELECT string_agg(tablename, ',' ORDER BY tablename) FROM pg_tables WHERE schemaname='public';") + checks['tables'] = tables + required_tables = {'users', 'chats', 'chat_members', 'messages', 'schema_migrations', 'message_idempotency'} + checks['required_tables_present'] = required_tables.issubset(set(tables.split(','))) + constraints = sql_text(""" + SELECT string_agg(conname, ',' ORDER BY conname) + FROM pg_constraint WHERE connamespace = 'public'::regnamespace;""") + checks['constraints'] = constraints + for required in ('users_pkey', 'users_username_format', 'chats_title_length', + 'chat_members_pkey', 'messages_sender_membership_fk', + 'message_idempotency_pkey'): + checks['constraint_' + required] = required in constraints.split(',') + indexes = sql_text("SELECT string_agg(indexname, ',' ORDER BY indexname) FROM pg_indexes WHERE schemaname='public';") + checks['indexes'] = indexes + checks['messages_index_present'] = 'messages_chat_created_id_idx' in indexes.split(',') + checks['idempotency_created_index_present'] = 'message_idempotency_created_at_idx' in indexes.split(',') + + state = sql_json(""" + SELECT json_build_object( + 'messages', (SELECT count(*) FROM messages), + 'idempotency', (SELECT count(*) FROM message_idempotency), + 'duplicate_scopes', (SELECT count(*) FROM ( + SELECT user_id, method, path, key FROM message_idempotency + GROUP BY 1,2,3,4 HAVING count(*) > 1) duplicated), + 'orphan_records', (SELECT count(*) FROM message_idempotency i + LEFT JOIN messages m ON m.id = i.message_id WHERE m.id IS NULL), + 'old_records', (SELECT count(*) FROM message_idempotency + WHERE created_at < now() - interval '24 hours'), + 'hash_lengths', (SELECT coalesce(json_agg(DISTINCT octet_length(request_hash)), '[]') FROM message_idempotency)));""") + checks['data_state'] = state + checks['scopes_unique'] = state['duplicate_scopes'] == 0 + checks['records_reference_messages'] = state['orphan_records'] == 0 + checks['retention_not_expired'] = state['old_records'] == 0 + checks['hashes_are_sha256'] = state['hash_lengths'] in ([32], []) + checks['messages_have_idempotency_records'] = state['messages'] == state['idempotency'] + + hashes = sql_json(""" + SELECT json_build_object( + 'total', count(*), + 'argon2id', count(*) FILTER (WHERE password_hash LIKE '$argon2id$%'), + 'plaintext_like', count(*) FILTER (WHERE password_hash NOT LIKE '$argon2id$%')) FROM users;""") + checks['password_hashes'] = hashes + checks['all_passwords_argon2id'] = hashes['total'] == hashes['argon2id'] + + settings = sql_json(""" + SELECT json_build_object( + 'max_connections', current_setting('max_connections'), + 'shared_buffers', current_setting('shared_buffers'), + 'synchronous_commit', current_setting('synchronous_commit'), + 'max_wal_size', current_setting('max_wal_size'));""") + checks['settings'] = settings + checks['max_connections_sane'] = int(settings['max_connections']) >= 100 + checks['synchronous_commit_on'] = settings['synchronous_commit'] == 'on' + + # API-level increment: one new key creates exactly one message and one + # idempotency row; replay creates neither. + c = Client(args.base_url) + alice, bob, eve, chat = c.bootstrap() + before = sql_json("SELECT json_build_object('messages',(SELECT count(*) FROM messages)," + "'idempotency',(SELECT count(*) FROM message_idempotency));") + key = uuid.uuid4().hex + first = c.message(alice, chat, 'db-check ' + key, key=key)['json'] + replay = c.message(alice, chat, 'db-check ' + key, key=key)['json'] + check(first == replay, 'idempotent replay differed in DB check') + after = sql_json("SELECT json_build_object('messages',(SELECT count(*) FROM messages)," + "'idempotency',(SELECT count(*) FROM message_idempotency));") + delta_messages = after['messages'] - before['messages'] + delta_records = after['idempotency'] - before['idempotency'] + checks['api_write_delta'] = {'messages': delta_messages, 'idempotency': delta_records} + checks['one_message_one_record'] = delta_messages == 1 and delta_records == 1 + + # A one-shot migrate run while API replicas are serving must be a no-op. + revision = M.run(['git', 'rev-parse', 'HEAD']).stdout.strip() + env = {'API_IMAGE': 'mtusi-messenger-lab3-melnikov:local', 'GIT_REVISION': revision, + 'API_REPLICAS': '2', 'API_CPU_LIMIT': '0.4', 'API_MEM_LIMIT': '256M'} + migrate = M.compose('run', '--rm', 'migrate', env_extra=env, check=False) + versions_after = sql_text("SELECT string_agg(version::text, ',' ORDER BY version) FROM schema_migrations;") + checks['migrate_run'] = { + 'exit_code': migrate.returncode, + 'stdout_tail': migrate.stdout.strip().splitlines()[-3:], + 'versions_after': versions_after, + } + checks['migrate_idempotent'] = migrate.returncode == 0 and versions_after == versions + checks['migrate_output_up_to_date'] = 'migrations: up-to-date' in migrate.stdout + + failed = [key for key, value in checks.items() if isinstance(value, bool) and not value] + checks['result'] = 'PASS' if not failed else 'FAIL' + checks['failed'] = failed + checks['checked_at'] = now() + OUT.parent.mkdir(parents=True, exist_ok=True) + OUT.write_text(json.dumps(checks, indent=2, ensure_ascii=False) + '\n') + text = [ + 'lab3 database checks at ' + checks['checked_at'], + 'result: ' + checks['result'], + 'migrations: ' + versions + '; tables: ' + tables, + 'messages=%d idempotency=%d; duplicate scopes=%d; orphans=%d; old>24h=%d' % ( + state['messages'], state['idempotency'], state['duplicate_scopes'], + state['orphan_records'], state['old_records']), + 'password hashes: %d/%d Argon2id' % (hashes['argon2id'], hashes['total']), + 'API write delta: ' + json.dumps(checks['api_write_delta']), + 'one-shot migrate exit: %d; versions after: %s' % (migrate.returncode, versions_after), + ] + (ROOT / 'evidence/db-checks.txt').write_text('\n'.join(text) + '\n') + print('\n'.join(text)) + if failed: + raise SystemExit('FAILED checks: ' + ', '.join(failed)) + print('PASS: database checks') + + +if __name__ == '__main__': + try: + main() + except Exception as exc: # noqa: BLE001 + print('FAIL:', exc) + raise SystemExit(1) diff --git a/scripts/failover-matrix.py b/scripts/failover-matrix.py index e4d5b7c2..c506c1f0 100755 --- a/scripts/failover-matrix.py +++ b/scripts/failover-matrix.py @@ -109,7 +109,9 @@ def set_profile(replicas, cpu, memory, image): 'API_IMAGE': image, 'GIT_REVISION': run(['git', 'rev-parse', 'HEAD']).stdout.strip(), } - compose('up', '-d', '--no-deps', '--force-recreate', 'api', env_extra=env_extra) + for container in [c['container_id'] for c in api_containers()]: + run(['docker', 'rm', '-f', container], check=False) + compose('up', '-d', '--no-deps', 'api', env_extra=env_extra) wait_all_running(replicas) if not wait_http_ready(90): raise RuntimeError('LB did not become ready after recreating API replicas') diff --git a/scripts/failure-checks.py b/scripts/failure-checks.py new file mode 100755 index 00000000..272eeb62 --- /dev/null +++ b/scripts/failure-checks.py @@ -0,0 +1,144 @@ +#!/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) diff --git a/scripts/lab3_metrics.py b/scripts/lab3_metrics.py index 81a684fa..7d6bbd2a 100644 --- a/scripts/lab3_metrics.py +++ b/scripts/lab3_metrics.py @@ -11,6 +11,7 @@ Nothing here reads tokens or message bodies. All data is synthetic. """ import csv import datetime as dt +import re import io import json import os @@ -63,6 +64,22 @@ def compose(*args, env_extra=None, check=True): return run([COMPOSE, '--env-file', '.env'] + list(args), env=env, check=check) +def remove_service_containers(service): + """Remove every container of a compose service, running or stopped. + + Compose v2 does not reliably converge `deploy.replicas` when a service is + force-recreated after an earlier scale-down; stale replicas can keep the + service label and confuse both HAProxy and the experiment. The scaling + scripts therefore remove the API containers explicitly before creating the + exact requested count. PostgreSQL/Valkey volumes are never touched here. + """ + removed = [] + for item in containers(service, running_only=False): + run(['docker', 'rm', '-f', item['container_id']], check=False) + removed.append(item['container_id']) + return removed + + def image_id(container): return run(['docker', 'inspect', '-f', '{{.Image}}', container]).stdout.strip() @@ -132,10 +149,10 @@ def cgroup_all(): return result -def psql_json(sql): +def psql_json(sql, database=None): command = ['docker', 'exec', '-i', containers('postgres')[0]['container_id'], 'psql', '-X', '-A', '-t', '-v', 'ON_ERROR_STOP=1', - '-U', ENV['POSTGRES_USER'], '-d', ENV['POSTGRES_DB'], '-c', sql] + '-U', ENV['POSTGRES_USER'], '-d', database or ENV['POSTGRES_DB'], '-c', sql] result = run(command) text = result.stdout.strip() if not text: @@ -143,8 +160,8 @@ def psql_json(sql): return json.loads(text.splitlines()[-1]) -def db_snapshot(): - database = psql_json(""" +def db_snapshot(database=None): + db = psql_json(""" SELECT json_build_object( 'xact_commit', xact_commit, 'xact_rollback', xact_rollback, 'blks_read', blks_read, 'blks_hit', blks_hit, @@ -153,7 +170,7 @@ def db_snapshot(): 'tup_deleted', tup_deleted, 'deadlocks', deadlocks, 'temp_files', temp_files, 'temp_bytes', temp_bytes, 'stats_reset', stats_reset) - FROM pg_stat_database WHERE datname = current_database();""") + FROM pg_stat_database WHERE datname = current_database();""", database) activity = psql_json(""" SELECT json_build_object( 'total', count(*), @@ -161,7 +178,7 @@ def db_snapshot(): 'idle', count(*) FILTER (WHERE state = 'idle'), 'active_waiting', count(*) FILTER (WHERE state = 'active' AND wait_event_type IS NOT NULL), 'idle_in_transaction', count(*) FILTER (WHERE state = 'idle in transaction')) - FROM pg_stat_activity WHERE datname = current_database();""") + FROM pg_stat_activity WHERE datname = current_database();""", database) datasets = psql_json(""" SELECT json_build_object( 'messages', (SELECT count(*) FROM messages), @@ -169,26 +186,26 @@ def db_snapshot(): 'users', (SELECT count(*) FROM users), 'chats', (SELECT count(*) FROM chats), 'db_bytes', pg_database_size(current_database()), - 'locks', (SELECT count(*) FROM pg_locks));""") + 'locks', (SELECT count(*) FROM pg_locks));""", database) settings = psql_json(""" SELECT json_build_object( 'max_connections', current_setting('max_connections')::int, 'shared_buffers', current_setting('shared_buffers'), - 'synchronous_commit', current_setting('synchronous_commit'));""") + 'synchronous_commit', current_setting('synchronous_commit'));""", database) wal = psql_json(""" SELECT json_build_object( 'wal_records', wal_records, 'wal_fpi', wal_fpi, 'wal_bytes', wal_bytes, 'wal_buffers_full', wal_buffers_full, 'wal_write', wal_write, 'wal_sync', wal_sync, 'wal_write_time', wal_write_time, - 'wal_sync_time', wal_sync_time) FROM pg_stat_wal;""") + 'wal_sync_time', wal_sync_time) FROM pg_stat_wal;""", database) bgwriter = psql_json(""" SELECT json_build_object( 'checkpoints_timed', checkpoints_timed, 'checkpoints_req', checkpoints_req, 'buffers_checkpoint', buffers_checkpoint, 'buffers_clean', buffers_clean, 'maxwritten_clean', maxwritten_clean, 'buffers_backend', buffers_backend, - 'buffers_backend_fsync', buffers_backend_fsync) FROM pg_stat_bgwriter;""") + 'buffers_backend_fsync', buffers_backend_fsync) FROM pg_stat_bgwriter;""", database) row = activity or {} - row['database'] = database or {} + row['database'] = db or {} row['datasets'] = datasets or {} row['settings'] = settings or {} row['wal'] = wal or {} @@ -196,7 +213,7 @@ def db_snapshot(): return row -def db_activity_sample(): +def db_activity_sample(database=None): return psql_json(""" SELECT json_build_object( 'active', count(*) FILTER (WHERE state = 'active'), @@ -207,7 +224,7 @@ def db_activity_sample(): FROM pg_stat_activity WHERE state = 'active' AND wait_event_type IS NOT NULL GROUP BY 1) grouped), '{}'::json)) - FROM pg_stat_activity;""") + FROM pg_stat_activity;""", database) def haproxy_snapshot(): @@ -244,12 +261,12 @@ def api_stats(): return result -def snapshot(): +def snapshot(database=None): started = time.monotonic() data = { 'collected_at': iso(), 'cgroups': cgroup_all(), - 'db': db_snapshot(), + 'db': db_snapshot(database), 'haproxy': haproxy_snapshot(), 'api': api_stats(), 'containers': {service: containers(service) for service in SERVICES}, @@ -258,6 +275,41 @@ def snapshot(): return data +def admin_psql(sql, database='postgres'): + container = containers('postgres')[0]['container_id'] + result = run(['docker', 'exec', '-i', container, + 'psql', '-X', '-A', '-t', '-v', 'ON_ERROR_STOP=1', + '-U', ENV['POSTGRES_USER'], '-d', database, '-c', sql], check=False) + if result.returncode != 0: + raise RuntimeError('admin psql failed: ' + (result.stderr or result.stdout)[-600:]) + return result.stdout.strip() + + +def reset_database(name): + if not re.match(r'^[a-z_][a-z0-9_]*$', name): + raise ValueError('unsafe database name') + admin_psql("SELECT pg_terminate_backend(pid) FROM pg_stat_activity " + "WHERE datname = '%s' AND pid <> pg_backend_pid();" % name) + admin_psql('DROP DATABASE IF EXISTS "%s";' % name) + admin_psql('CREATE DATABASE "%s" OWNER "%s";' % (name, ENV['POSTGRES_USER'])) + + +def drop_database(name): + if not re.match(r'^[a-z_][a-z0-9_]*$', name): + raise ValueError('unsafe database name') + admin_psql("SELECT pg_terminate_backend(pid) FROM pg_stat_activity " + "WHERE datname = '%s' AND pid <> pg_backend_pid();" % name) + admin_psql('DROP DATABASE IF EXISTS "%s";' % name) + + +def migrate_database(image, revision, database): + env_extra = {'API_IMAGE': image, 'GIT_REVISION': revision, 'POSTGRES_DB': database} + result = compose('run', '--rm', 'migrate', env_extra=env_extra, check=False) + if result.returncode != 0: + raise RuntimeError('migrate for %s failed: %s' % (database, (result.stderr or result.stdout)[-800:])) + return result.stdout.strip().splitlines()[-3:] + + def wait_ready(timeout=90): deadline = time.monotonic() + timeout while time.monotonic() < deadline: @@ -288,8 +340,10 @@ def wait_api_running(expected, timeout=90): def set_stack_profile(image, revision, replicas, api_cpu, api_mem, gomemlimit, postgres_cpu='0.7', postgres_mem='512M', valkey_cpu='0.1', - valkey_mem='128M', lb_cpu='0.2', lb_mem='64M', recreate_state=False): + valkey_mem='128M', lb_cpu='0.2', lb_mem='64M', recreate_state=False, + database='messenger', reset_database_first=False): env_extra = { + 'POSTGRES_DB': database, 'API_IMAGE': image, 'GIT_REVISION': revision, 'API_REPLICAS': str(replicas), @@ -305,7 +359,11 @@ def set_stack_profile(image, revision, replicas, api_cpu, api_mem, gomemlimit, } if recreate_state: compose('up', '-d', '--no-deps', '--force-recreate', 'postgres', 'valkey', 'lb', env_extra=env_extra) - compose('up', '-d', '--no-deps', '--force-recreate', 'api', env_extra=env_extra) + remove_service_containers('api') + if reset_database_first: + reset_database(database) + migrate_database(image, revision, database) + compose('up', '-d', '--no-deps', 'api', env_extra=env_extra) wait_api_running(replicas) if not wait_ready(120): raise RuntimeError('LB did not become ready') diff --git a/scripts/plot_track1.py b/scripts/plot_track1.py new file mode 100644 index 00000000..2489dbda --- /dev/null +++ b/scripts/plot_track1.py @@ -0,0 +1,192 @@ +#!/usr/bin/env python3 +"""Render track-1 summary as dependency-free SVG charts. + +Input: evidence/track1/summary.json produced by scripts/track1.py. +Output: evidence/track1/plots/*.svg. The charts plot medians of the recorded +runs; raw run files remain the source of truth. +""" +import json +import math +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +SUMMARY = ROOT / 'evidence/track1/summary.json' +OUT = ROOT / 'evidence/track1/plots' + +COLORS = ['#1f77b4', '#d62728', '#2ca02c', '#ff7f0e', '#9467bd'] + + +def esc(value): + return (str(value).replace('&', '&').replace('<', '<') + .replace('>', '>').replace('"', '"')) + + +def svg_header(width, height, title, subtitle): + return ['', + '' % (width, height, width, height), + '', + '%s' % esc(title), + '%s' % esc(subtitle)] + + +def axes(width, height, xlabels, ymax, ylabel, left=90, right=40, top=90, bottom=80): + part = [] + plot_w = width - left - right + plot_h = height - top - bottom + for step in range(6): + value = ymax * step / 5.0 + y = top + plot_h - plot_h * step / 5.0 + part.append('' % (left, y, width - right, y)) + part.append('%.1f' % (left - 8, y + 4, value)) + part.append('' % (left, top + plot_h, width - right, top + plot_h)) + part.append('' % (left, top, left, top + plot_h)) + if len(xlabels) == 1: + positions = [left + plot_w / 2.0] + else: + positions = [left + plot_w * i / (len(xlabels) - 1.0) for i in range(len(xlabels))] + for label, x in zip(xlabels, positions): + part.append('%s' % (x, top + plot_h + 24, esc(label))) + part.append('%s' % (left + plot_w / 2.0, height - 22, esc(ylabel))) + part.append('%s' % (24, top + plot_h / 2, 24, top + plot_h / 2, esc(ylabel))) + return part, positions, plot_w, plot_h + + +def line_chart(path, title, subtitle, xlabels, series, ylabel, ymax=None, value_suffix=''): + width, height = 960, 560 + top, bottom = 90, 80 + all_values = [value for _, values in series for value in values if value is not None] + if ymax is None: + ymax = max(all_values) * 1.15 if all_values else 1.0 + if ymax <= 0: + ymax = 1.0 + # Round the axis up to a readable number. + magnitude = 10 ** math.floor(math.log10(ymax)) + ymax = math.ceil(ymax / magnitude) * magnitude + part, positions, plot_w, plot_h = axes(width, height, xlabels, ymax, ylabel) + for index, (name, values) in enumerate(series): + color = COLORS[index % len(COLORS)] + points = [] + for point, value in zip(positions, values): + if value is None: + continue + y = top + plot_h - (value / ymax) * plot_h + points.append((point, y, value)) + if len(points) > 1: + path_data = ' '.join('%s%.1f,%.1f' % ('M' if i == 0 else 'L', x, y) for i, (x, y, _) in enumerate(points)) + part.append('' % (path_data, color)) + for x, y, value in points: + part.append('' % (x, y, color)) + part.append('%s%s' % (x, y - 10, color, esc(('%.1f' % value) if isinstance(value, float) else value), value_suffix)) + legend_y = height - 46 + legend_x = 110 + index * 230 + part.append('' % (legend_x, legend_y, legend_x + 24, legend_y, color)) + part.append('%s' % (legend_x + 32, legend_y + 4, esc(name))) + part.append('') + Path(path).write_text('\n'.join(part) + '\n') + + +def bar_chart(path, title, subtitle, xlabels, series, ylabel, ymax=None, value_suffix=''): + width, height = 960, 560 + top, bottom = 90, 100 + all_values = [value for _, values in series for value in values if value is not None] + if ymax is None: + ymax = max(all_values) * 1.2 if all_values else 1.0 + part, positions, plot_w, plot_h = axes(width, height, xlabels, ymax, ylabel) + group_width = plot_w / max(1, len(positions)) + bar_width = group_width * 0.7 / max(1, len(series)) + for series_index, (name, values) in enumerate(series): + color = COLORS[series_index % len(COLORS)] + for index, value in enumerate(values): + if value is None: + continue + x = positions[index] - group_width * 0.35 + series_index * bar_width + bar_h = value / ymax * plot_h + y = top + plot_h - bar_h + part.append('' % (x, y, bar_width - 3, bar_h, color)) + part.append('%s%s' % (x + bar_width / 2, y - 6, esc(('%.1f' % value)), value_suffix)) + legend_y = height - 46 + legend_x = 110 + series_index * 230 + part.append('' % (legend_x, legend_y - 9, color)) + part.append('%s' % (legend_x + 24, legend_y + 1, esc(name))) + part.append('') + Path(path).write_text('\n'.join(part) + '\n') + + +def get(group, key, field, default=None): + if key not in group: + return default + value = group[key].get(field, default) + return default if value is None else value + + +def main(): + if not SUMMARY.exists(): + raise SystemExit('missing %s; run scripts/track1.py first' % SUMMARY) + data = json.loads(SUMMARY.read_text()) + OUT.mkdir(parents=True, exist_ok=True) + fixed = data['medians']['fixed_total'] + growth = data['medians']['resource_growth'] + improvement = data['medians']['improvement'] + fixed_keys = ['1', '2', '4'] + growth_keys = ['0.4', '0.7', '0.9'] + revisions = sorted({run['config'].get('revision') for run in data['runs']['fixed_total']}) + subtitle = 'Colima 2 vCPU / 2 GiB, one Docker host; medians of %d alternating runs; revision %s' % ( + len(data['runs']['fixed_total']) // max(1, len(fixed_keys)), ', '.join(filter(None, revisions))[:12]) + + line_chart(OUT / 'fixed-rps.svg', + 'Fixed total API CPU/RAM: 1 vs 2 vs 4 replicas', + subtitle + '; total API 0.8 vCPU / 512 MiB', + [key + ' replica' + ('' if key == '1' else 's') for key in fixed_keys], + [('successful RPS', [get(fixed, key, 'successful_rps', 0) for key in fixed_keys])], + 'HTTP 2xx acknowledgements / second', value_suffix='') + line_chart(OUT / 'fixed-latency.svg', + 'Latency at fixed total CPU: more replicas, same budget', + subtitle + '; successful requests only', + [key + ' replica' + ('' if key == '1' else 's') for key in fixed_keys], + [('p50 ms', [get(fixed, key, 'p50_ms', 0) for key in fixed_keys]), + ('p95 ms', [get(fixed, key, 'p95_ms', 0) for key in fixed_keys]), + ('p99 ms', [get(fixed, key, 'p99_ms', 0) for key in fixed_keys])], + 'milliseconds', value_suffix=' ms') + bar_chart(OUT / 'saturation.svg', + 'Where the fixed CPU budget goes (median utilization)', + subtitle + '; cgroup CPU usage / cgroup CPU limit', + [key + ' replica' + ('' if key == '1' else 's') for key in fixed_keys], + [('API', [100 * get(fixed, key, 'api_utilization', 0) for key in fixed_keys]), + ('PostgreSQL', [100 * get(fixed, key, 'db_utilization', 0) for key in fixed_keys]), + ('HAProxy', [100 * (get(fixed, key, 'lb_used_cores', 0) / 0.2) for key in fixed_keys])], + 'percent of container CPU limit', ymax=110, value_suffix='%') + line_chart(OUT / 'growth-rps.svg', + 'Resource-growth series at 4 replicas', + subtitle + '; shared PostgreSQL/Valkey/LB limits fixed', + ['API total %.1f vCPU' % float(key) for key in growth_keys], + [('successful RPS', [get(growth, key, 'successful_rps', 0) for key in growth_keys])], + 'HTTP 2xx acknowledgements / second') + bar_chart(OUT / 'growth-utilization.svg', + 'Resource-growth series: utilization of the fixed shared backend', + subtitle + '; cgroup CPU usage / cgroup CPU limit', + ['API total %.1f vCPU' % float(key) for key in growth_keys], + [('API', [100 * get(growth, key, 'api_utilization', 0) for key in growth_keys]), + ('PostgreSQL', [100 * get(growth, key, 'db_utilization', 0) for key in growth_keys])], + 'percent of container CPU limit', ymax=110, value_suffix='%') + base = get(improvement, 'baseline', 'successful_rps', 0) + opt = get(improvement, 'optimized', 'successful_rps', 0) + bar_chart(OUT / 'improvement-rps.svg', + 'Confirmed improvement at 4x0.2 vCPU: one atomic statement', + 'Baseline: explicit transaction + message INSERT + idempotency INSERT. Final: one data-modifying CTE. ' + 'Median of alternating runs; +%.1f%% RPS.' % (((opt - base) / base * 100.0) if base else 0.0), + ['baseline', 'optimized'], + [('successful RPS', [base, opt])], + 'HTTP 2xx acknowledgements / second') + bar_chart(OUT / 'improvement-latency.svg', + 'Confirmed improvement: p95 latency at the same limit', + 'Successful POST requests; lower is better; same alternating runs', + ['baseline', 'optimized'], + [('p95 ms', [get(improvement, 'baseline', 'p95_ms', 0), + get(improvement, 'optimized', 'p95_ms', 0)])], + 'milliseconds', value_suffix=' ms') + print('wrote', OUT) + + +if __name__ == '__main__': + main() diff --git a/scripts/rolling-update.sh b/scripts/rolling-update.sh new file mode 100755 index 00000000..bb091bfe --- /dev/null +++ b/scripts/rolling-update.sh @@ -0,0 +1,113 @@ +#!/bin/sh +# Level-4 rolling replacement under load. +# +# Builds a second image tag from the same source tree (VERSION=2.0.0, which is +# visible as the non-contract X-App-Version header), starts a mixed read/write +# probe, and replaces each API container one at a time. The migration command +# is re-run once against the new image while old replicas still serve; the +# schema is unchanged between these revisions, so old and new processes are +# compatible by construction. This is an additive, advisory-locked migration +# boundary, not a test of a destructive schema change. +set -eu +cd "$(dirname "$0")/.." + +NEW_IMAGE=${NEW_IMAGE:-mtusi-messenger-lab3-melnikov:rolling} +NEW_VERSION=${NEW_VERSION:-2.0.0} +REPLICAS=${API_REPLICAS:-2} +CPU=${API_CPU_LIMIT:-0.4} +MEM=${API_MEM_LIMIT:-256M} +GOMEM=${GOMEMLIMIT:-240MiB} +PROBE=/tmp/mtusi-lab3-loadgen-rolling +OUT=evidence/rolling-update +mkdir -p "$OUT" +rev=$(git rev-parse HEAD 2>/dev/null || echo unknown) +compose="./scripts/compose.sh --env-file .env" + +echo "rolling: building $NEW_IMAGE from $rev (version $NEW_VERSION)" +GIT_REVISION="$rev" API_IMAGE="$NEW_IMAGE" docker build \ + --build-arg VERSION="$NEW_VERSION" --build-arg REVISION="$rev" \ + -t "$NEW_IMAGE" . >/dev/null + +go build -o "$PROBE" ./cmd/loadgen + +# Ensure the stand starts with exactly the old replicas and the requested limits. +# Remove stale API containers first: a stopped container from an earlier +# failover would otherwise be counted or started by compose. +for container in $(docker ps -aq --filter label=com.docker.compose.service=api \ + --filter label=com.docker.compose.project=mtusi-lab3-melnikov); do + docker rm -f "$container" >/dev/null 2>&1 || true +done +API_IMAGE=mtusi-messenger-lab3-melnikov:local GIT_REVISION="$rev" \ +API_REPLICAS="$REPLICAS" API_CPU_LIMIT="$CPU" API_MEM_LIMIT="$MEM" GOMEMLIMIT="$GOMEM" \ + $compose up -d --no-deps api >/dev/null +./scripts/wait-ready.sh >/dev/null + +before=$(docker ps -aq --filter label=com.docker.compose.service=api \ + --filter label=com.docker.compose.project=mtusi-lab3-melnikov) +old_count=$(printf '%s\n' "$before" | grep -c . || true) +if [ "$old_count" -ne "$REPLICAS" ]; then + echo "rolling: expected $REPLICAS old API containers, found $old_count" >&2 + exit 1 +fi + +# Pick the target containers before load starts. +targets=$(printf '%s\n' "$before" | head -n "$REPLICAS") + +echo "rolling: starting mixed probe" +"$PROBE" -base-url http://127.0.0.1:8083 -duration 50s -warmup 3s -concurrency 8 \ + -read-ratio 0.5 -timeout 2s -retry-uncertain \ + -output "$OUT/loadgen.json" -note "rolling update 1.0.0 -> $NEW_VERSION" \ + > "$OUT/loadgen.stdout" 2>&1 & +probe_pid=$! +sleep 5 + +# Re-run the one-shot migration under running old replicas. It is a no-op for +# this revision, which is exactly the compatibility property being shown. +API_IMAGE="$NEW_IMAGE" GIT_REVISION="$rev" $compose run --rm migrate \ + > "$OUT/migrate.txt" 2>&1 || { echo "rolling: migration failed" >&2; cat "$OUT/migrate.txt" >&2; exit 1; } + +step=0 +for container in $targets; do + step=$((step + 1)) + hostname=$(docker inspect -f '{{.Config.Hostname}}' "$container") + image_before=$(docker inspect -f '{{.Image}}' "$container") + echo "rolling: step $step/$REPLICAS stopping $container ($hostname)" + docker stop --time 15 "$container" >/dev/null + docker rm "$container" >/dev/null + API_IMAGE="$NEW_IMAGE" GIT_REVISION="$rev" API_REPLICAS="$REPLICAS" \ + API_CPU_LIMIT="$CPU" API_MEM_LIMIT="$MEM" GOMEMLIMIT="$GOMEM" \ + $compose up -d --no-deps --no-recreate api >/dev/null + + attempts=0 + while [ "$attempts" -lt 90 ]; do + current=$(docker ps -q --filter label=com.docker.compose.service=api \ + --filter label=com.docker.compose.project=mtusi-lab3-melnikov | wc -l | tr -d ' ') + healthy=1 + for check in $(docker ps -q --filter label=com.docker.compose.service=api \ + --filter label=com.docker.compose.project=mtusi-lab3-melnikov); do + status=$(docker inspect -f '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' "$check") + [ "$status" = "healthy" ] || healthy=0 + done + if [ "$current" -eq "$REPLICAS" ] && [ "$healthy" -eq 1 ]; then + break + fi + attempts=$((attempts + 1)) + sleep 1 + done + if [ "$attempts" -ge 90 ]; then + echo "rolling: replacement did not become healthy" >&2 + exit 1 + fi + echo "rolling: step $step complete (old image $image_before removed)" +done + +wait "$probe_pid" +new_images=$(for container in $(docker ps -q --filter label=com.docker.compose.service=api \ + --filter label=com.docker.compose.project=mtusi-lab3-melnikov); do + docker inspect -f '{{.Image}}' "$container"; done | sort -u) +if [ "$(printf '%s\n' "$new_images" | grep -c .)" -ne 1 ]; then + echo "rolling: API containers run more than one image after the roll" >&2 + exit 1 +fi +echo "rolling: all $REPLICAS API containers now run $NEW_IMAGE ($new_images)" +echo "PASS: rolling replacement completed under load" diff --git a/scripts/track1.py b/scripts/track1.py index d6952cb5..d660d53d 100755 --- a/scripts/track1.py +++ b/scripts/track1.py @@ -41,6 +41,7 @@ BASELINE_IMAGE = 'mtusi-messenger-lab3-melnikov:track-baseline' DURATION = 20 WARMUP = 5 CONCURRENCY = 32 +TRACK_DB = 'messenger_track' def now(): @@ -68,17 +69,21 @@ def config(replicas, cpu_per, mem_per, cpu_total, mem_total, image, label): def run_one(label, cfg, revision, raw_dir, run_dir): + # Every configuration starts from the same freshly migrated database. The + # track database is separate from the stand's main DB and is dropped at the + # end, so the comparison is not biased by 20 minutes of accumulated data. M.set_stack_profile(cfg['image'], revision, cfg['replicas'], cfg['api_cpu_per_replica'], - cfg['api_mem_per_replica'], cfg['gomemlimit']) + cfg['api_mem_per_replica'], cfg['gomemlimit'], + database=TRACK_DB, reset_database_first=True) time.sleep(2) # let HAProxy's resolver drop a removed backend - before = M.snapshot() + before = M.snapshot(database=TRACK_DB) activity_samples = [] sampler_stop = threading.Event() def sample_activity(): while not sampler_stop.is_set(): try: - activity_samples.append(M.db_activity_sample()) + activity_samples.append(M.db_activity_sample(database=TRACK_DB)) except Exception: pass sampler_stop.wait(0.5) @@ -96,7 +101,7 @@ def run_one(label, cfg, revision, raw_dir, run_dir): wall_end_utc = M.iso() sampler_stop.set() sampler.join(timeout=5) - after = M.snapshot() + after = M.snapshot(database=TRACK_DB) elapsed = wall_end - wall_start record = M.summarize_run(label, cfg, before, after, elapsed, load) record['wall_window'] = {'started_at': wall_start_utc, 'finished_at': wall_end_utc, @@ -213,6 +218,7 @@ def main(): 'concurrency': CONCURRENCY, 'loadgen': 'cmd/loadgen (Go, HTTP acknowledgement throughput)', }, + 'dataset_policy': 'before every measured run the dedicated messenger_track database is dropped, recreated and migrated; each run starts with 0 synthetic messages and grows only during its 5s warmup + 20s measurement. The main messenger database is untouched.', 'vm_capacity_note': 'Colima VM has 2 vCPU / 2 GiB; all API processes, PostgreSQL, Valkey and HAProxy share one kernel and one Docker host. The experiment proves process-level scaling limits, not node-level HA.', 'limits': { 'postgres_cpu': 0.7, 'postgres_mem': '512M', @@ -227,7 +233,6 @@ def main(): M.set_stack_profile(args.final_image, revision, 2, 0.4, '256M', '240MiB', recreate_state=True) if not M.wait_ready(120): raise RuntimeError('stack not ready') - fixed = [] for rep in range(reps): for replicas, cpu, mem, gomem in ((1, 0.8, '512M', '480MiB'), @@ -257,8 +262,10 @@ def main(): cfg['revision'] = revision if name == 'optimized' else revision + '+baseline-image' improvement.append(run_one(label, cfg, revision, raw_dir, run_dir)) - # Leave the stand in the documented default profile and final image. - M.set_stack_profile(args.final_image, revision, 2, 0.4, '256M', '240MiB') + # Leave the stand in the documented default profile and main database, + # then remove the dedicated experiment database. + M.set_stack_profile(args.final_image, revision, 2, 0.4, '256M', '240MiB', database='messenger') + M.drop_database(TRACK_DB) time.sleep(2) summary = {