Lab3 baseline: HAProxy, replicated stateless API, shared PostgreSQL/Valkey, idempotent messages

This commit is contained in:
Ivan Melnikov
2026-12-02 18:22:57 +03:00
parent 0ab3a341aa
commit e9bf138053
474 changed files with 206416 additions and 16 deletions
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
# Accept both the Compose v2 plugin ("docker compose") and the standalone
# binary ("docker-compose"), so the same Makefile works on machines where only
# one of them is installed. This wrapper does not change any global setting.
set -eu
if docker compose version >/dev/null 2>&1; then
exec docker compose "$@"
fi
if command -v docker-compose >/dev/null 2>&1; then
exec docker-compose "$@"
fi
echo "Docker Compose is required (docker compose or docker-compose)" >&2
exit 2
+239
View File
@@ -0,0 +1,239 @@
#!/usr/bin/env python3
"""Level-4 evidence: stop every real API replica in turn under load.
For each of the two default API containers this script:
* starts a mixed read/write probe through the LB;
* asks scripts/stop-one.sh to stop the process that actually served the
target X-Instance-Id (the script maps the hostname to one container);
* records per-second successes/errors, first success and first write after
the stop began, and whether the stopped instance answered after the stop;
* restarts exactly that container and waits until the LB routes to it again.
It never removes volumes and never stops PostgreSQL, Valkey or HAProxy.
Python 3.9+, standard library only.
"""
import argparse
import datetime as dt
import json
import os
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
COMPOSE = str(ROOT / 'scripts/compose.sh')
PROJECT = 'mtusi-lab3-melnikov'
LOADGEN = Path('/tmp/mtusi-lab3-loadgen')
OUT = ROOT / 'evidence/failover'
BASE = 'http://127.0.0.1:8083'
def now():
return dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00', 'Z')
def run(command, env=None, cwd=ROOT, check=True):
return subprocess.run(command, cwd=str(cwd), env=env, text=True,
capture_output=True, check=check)
def compose(*args, env_extra=None, check=True):
env = os.environ.copy()
# The compose file interpolates these; keep the experiment deterministic.
env.update(env_extra or {})
return run([COMPOSE, '--env-file', '.env'] + list(args), env=env, check=check)
def api_containers():
result = run(['docker', 'ps', '-aq',
'--filter', 'label=com.docker.compose.service=api',
'--filter', 'label=com.docker.compose.project=' + PROJECT])
containers = []
for container in result.stdout.split():
info = run(['docker', 'inspect', container]).stdout
data = json.loads(info)[0]
containers.append({
'container_id': data['Id'],
'name': data['Name'].lstrip('/'),
'hostname': data['Config']['Hostname'],
'image': data['Config']['Image'],
'state': data['State']['Status'],
'started_at': data['State']['StartedAt'],
'finished_at': data['State'].get('FinishedAt', ''),
'exit_code': data['State'].get('ExitCode'),
})
return sorted(containers, key=lambda item: item['name'])
def wait_http_ready(timeout=60):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
result = run(['curl', '-fsS', '-o', '/dev/null', BASE + '/health/ready'], check=False)
if result.returncode == 0:
return True
time.sleep(0.25)
return False
def wait_all_running(expected, timeout=60):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
containers = api_containers()
if len(containers) == expected and all(c['state'] == 'running' for c in containers):
return containers
time.sleep(0.25)
raise RuntimeError('API replicas did not all reach running state')
def wait_target_serving(target, timeout=45):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
result = run(['curl', '-fsS', '-D', '-', '-o', '/dev/null', BASE + '/health/live'], check=False)
if result.returncode == 0 and ('x-instance-id: ' + target) in result.stdout.lower():
return True
time.sleep(0.2)
return False
def build_loadgen():
run(['go', 'build', '-o', str(LOADGEN), './cmd/loadgen'])
def set_profile(replicas, cpu, memory, image):
env_extra = {
'API_REPLICAS': str(replicas),
'API_CPU_LIMIT': str(cpu),
'API_MEM_LIMIT': memory,
'GOMEMLIMIT': '200MiB',
'API_IMAGE': image,
'GIT_REVISION': run(['git', 'rev-parse', 'HEAD']).stdout.strip(),
}
compose('up', '-d', '--no-deps', '--force-recreate', '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')
def main():
global BASE, OUT
parser = argparse.ArgumentParser(description='Stop each real API replica under load')
parser.add_argument('--base-url', default=BASE)
parser.add_argument('--image', default='mtusi-messenger-lab3-melnikov:local')
parser.add_argument('--replicas', type=int, default=2)
parser.add_argument('--cpu', default='0.4')
parser.add_argument('--memory', default='256M')
parser.add_argument('--output-dir', default='evidence/failover')
args = parser.parse_args()
BASE = args.base_url.rstrip('/')
OUT = (ROOT / args.output_dir).resolve()
OUT.mkdir(parents=True, exist_ok=True)
build_loadgen()
set_profile(args.replicas, args.cpu, args.memory, args.image)
before = api_containers()
if len(before) != args.replicas:
raise RuntimeError('expected %d API containers, got %d' % (args.replicas, len(before)))
if len({item['container_id'] for item in before}) != args.replicas:
raise RuntimeError('API replicas are not distinct container IDs')
if len({item['hostname'] for item in before}) != args.replicas:
raise RuntimeError('API replicas are not distinct instance IDs')
matrix = {
'started_at': now(),
'base_url': BASE,
'image': args.image,
'profile': {'api_replicas': args.replicas, 'api_cpu_limit': args.cpu,
'api_mem_limit': args.memory},
'containers_before': before,
'results': [],
}
for index, item in enumerate(before):
target = item['hostname']
raw_path = OUT / ('%s-%s.json' % (dt.datetime.now(dt.timezone.utc).strftime('%Y%m%dT%H%M%SZ'), target))
command = [
str(LOADGEN), '-base-url', BASE,
'-duration', '16s', '-warmup', '2s', '-concurrency', '8',
'-read-ratio', '0.5', '-timeout', '2s', '-retry-uncertain',
'-stop-instance', target, '-stop-script', str(ROOT / 'scripts/stop-one.sh'),
'-stop-after', '3s', '-output', str(raw_path),
'-note', 'level-4 failover matrix, target ' + target,
]
started = time.time()
probe = run(command, check=False)
elapsed = time.time() - started
if not raw_path.exists():
raise RuntimeError('loadgen produced no output: ' + probe.stderr[-500:])
raw = json.loads(raw_path.read_text())
failover = raw.get('failover') or {}
after_stop = api_containers()
target_container = [c for c in after_stop if c['hostname'] == target]
if not target_container:
raise RuntimeError('target container disappeared')
target_container = target_container[0]
checks = {
'stop_script_exit_zero': failover.get('stop_script_exit') == 0,
'target_container_exited': target_container['state'] == 'exited',
'target_not_answering_after_stop': failover.get('target_responses_after_stop') == 0,
'first_success_within_10s': 0 <= failover.get('first_success_after_stop_seconds', -1) <= 10,
'first_write_within_10s': 0 <= failover.get('first_write_after_stop_seconds', -1) <= 10,
'first_success_on_other_replica_within_10s': 0 <= failover.get('first_success_on_other_replica_seconds', -1) <= 10,
'no_idempotency_violations': not raw.get('idempotency_violations'),
'other_replica_still_running': any(c['hostname'] != target and c['state'] == 'running' for c in after_stop),
}
if not all(checks.values()):
raise RuntimeError('failover checks failed for %s: %r' % (target, checks))
# Restart exactly the stopped container, then wait until the LB serves it.
restore_started = time.time()
run(['docker', 'start', target_container['container_id']])
restored = False
deadline = time.monotonic() + 45
while time.monotonic() < deadline:
current = [c for c in api_containers() if c['hostname'] == target]
if current and current[0]['state'] == 'running' and wait_target_serving(target, 1):
restored = True
break
time.sleep(0.25)
restore_seconds = round(time.time() - restore_started, 3)
if not restored:
raise RuntimeError('restored replica did not start serving again')
matrix['results'].append({
'target_instance': target,
'target_container': {
'container_id': target_container['container_id'],
'name': target_container['name'],
'image': target_container['image'],
'started_at_before': item['started_at'],
'finished_at_after_stop': target_container['finished_at'],
'exit_code_after_stop': target_container['exit_code'],
},
'probe_elapsed_seconds': round(elapsed, 3),
'loadgen': raw,
'checks': checks,
'restore_seconds_until_lb_serves_target': restore_seconds,
'containers_after_stop': after_stop,
})
print('PASS failover target %s: %sB %d success/%d errors, first success %.3fs, other replica %.3fs, first write %.3fs, restore %.3fs' % (
target,
raw.get('successful_rps'), raw.get('successful_requests'), raw.get('failed_requests'),
failover.get('first_success_after_stop_seconds'), failover.get('first_success_on_other_replica_seconds'),
failover.get('first_write_after_stop_seconds'), restore_seconds))
matrix['finished_at'] = now()
matrix['all_checks_passed'] = True
out_file = OUT / 'each-replica.json'
out_file.write_text(json.dumps(matrix, indent=2, ensure_ascii=False) + '\n')
print('wrote', out_file)
print('PASS: stopped and restored each of %d distinct API processes' % len(matrix['results']))
if __name__ == '__main__':
try:
main()
except Exception as exc: # noqa: BLE001 - CLI failure must be non-zero
print('FAIL:', exc)
raise SystemExit(1)
+31
View File
@@ -0,0 +1,31 @@
#!/bin/sh
# Create a local .env with fresh synthetic passwords. The file is ignored by
# Git, is readable only by the current user, and its values are never printed.
set -eu
cd "$(dirname "$0")/.."
if [ -f .env ]; then
echo ".env already exists; refusing to overwrite it" >&2
exit 0
fi
random_secret() {
LC_ALL=C tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 32
}
postgres_password=$(random_secret)
valkey_password=$(random_secret)
if [ "${#postgres_password}" -ne 32 ] || [ "${#valkey_password}" -ne 32 ]; then
echo "could not generate local secrets" >&2
exit 1
fi
revision=$(git rev-parse HEAD 2>/dev/null || echo unknown)
umask 077
sed \
-e "s|^POSTGRES_PASSWORD=.*|POSTGRES_PASSWORD=${postgres_password}|" \
-e "s|^VALKEY_PASSWORD=.*|VALKEY_PASSWORD=${valkey_password}|" \
-e "s|^GIT_REVISION=.*|GIT_REVISION=${revision}|" \
.env.example > .env
chmod 600 .env
echo "wrote .env with generated local synthetic credentials (mode 600); values not printed"
+465
View File
@@ -0,0 +1,465 @@
"""Shared measurement helpers for lab3 experiments (Python 3.9+).
Metric sources are explicit:
* loadgen JSON - HTTP acknowledgement throughput and latency;
* cgroup v2 files - CPU time and throttling of each container (not RSS);
* PostgreSQL views - commits, tuples, buffer hits, connections, waits;
* HAProxy CSV - request totals, queues, 5xx and connection errors;
* internal stats - pgx pool waits and message idempotency counters.
Nothing here reads tokens or message bodies. All data is synthetic.
"""
import csv
import datetime as dt
import io
import json
import os
import statistics
import subprocess
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
COMPOSE = str(ROOT / 'scripts/compose.sh')
PROJECT = 'mtusi-lab3-melnikov'
BASE_URL = 'http://127.0.0.1:8083'
SERVICES = ('api', 'postgres', 'valkey', 'lb')
def utcnow():
return dt.datetime.now(dt.timezone.utc)
def iso(value=None):
return (value or utcnow()).isoformat().replace('+00:00', 'Z')
def read_env():
values = {}
for line in (ROOT / '.env').read_text().splitlines():
line = line.strip()
if not line or line.startswith('#') or '=' not in line:
continue
key, value = line.split('=', 1)
values[key.strip()] = value.strip()
return values
ENV = read_env()
def run(command, env=None, check=True, cwd=ROOT, timeout=None):
result = subprocess.run(command, cwd=str(cwd), env=env, text=True,
capture_output=True, check=False, timeout=timeout)
if check and result.returncode != 0:
raise RuntimeError('command failed (%d): %s\n%s' % (
result.returncode, ' '.join(command[:6]), (result.stderr or result.stdout)[-800:]))
return result
def compose(*args, env_extra=None, check=True):
env = os.environ.copy()
env.update(env_extra or {})
return run([COMPOSE, '--env-file', '.env'] + list(args), env=env, check=check)
def image_id(container):
return run(['docker', 'inspect', '-f', '{{.Image}}', container]).stdout.strip()
def containers(service, running_only=True):
result = run(['docker', 'ps', '-aq',
'--filter', 'label=com.docker.compose.service=' + service,
'--filter', 'label=com.docker.compose.project=' + PROJECT])
items = []
for container in result.stdout.split():
data = json.loads(run(['docker', 'inspect', container]).stdout)[0]
if running_only and data['State']['Status'] != 'running':
continue
items.append({
'container_id': data['Id'],
'name': data['Name'].lstrip('/'),
'hostname': data['Config']['Hostname'],
'image_ref': data['Config']['Image'],
'image_id': data['Image'],
'state': data['State']['Status'],
'started_at': data['State']['StartedAt'],
'cpu_limit_nano': data['HostConfig'].get('NanoCpus', 0),
'memory_limit_bytes': data['HostConfig'].get('Memory', 0),
'cpu_max': read_text(container, '/sys/fs/cgroup/cpu.max').strip(),
'memory_max': read_text(container, '/sys/fs/cgroup/memory.max').strip(),
})
return sorted(items, key=lambda item: item['name'])
def read_text(container, path):
return run(['docker', 'exec', container, 'cat', path], check=False).stdout
def cgroup(container):
raw = read_text(container, '/sys/fs/cgroup/cpu.stat')
values = {}
for line in raw.splitlines():
parts = line.split()
if len(parts) == 2:
try:
values[parts[0]] = int(parts[1])
except ValueError:
pass
memory = read_text(container, '/sys/fs/cgroup/memory.current').strip()
memory_max = read_text(container, '/sys/fs/cgroup/memory.max').strip()
return {
'usage_usec': values.get('usage_usec', 0),
'user_usec': values.get('user_usec', 0),
'system_usec': values.get('system_usec', 0),
'nr_periods': values.get('nr_periods', 0),
'nr_throttled': values.get('nr_throttled', 0),
'throttled_usec': values.get('throttled_usec', 0),
'memory_current_bytes': int(memory) if memory.isdigit() else None,
'memory_max': memory_max,
}
def cgroup_all():
result = {}
for service in SERVICES:
for item in containers(service):
result[item['container_id']] = {
'service': service,
'hostname': item['hostname'],
'cgroup': cgroup(item['container_id']),
}
return result
def psql_json(sql):
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]
result = run(command)
text = result.stdout.strip()
if not text:
return None
return json.loads(text.splitlines()[-1])
def db_snapshot():
database = psql_json("""
SELECT json_build_object(
'xact_commit', xact_commit, 'xact_rollback', xact_rollback,
'blks_read', blks_read, 'blks_hit', blks_hit,
'tup_returned', tup_returned, 'tup_fetched', tup_fetched,
'tup_inserted', tup_inserted, 'tup_updated', tup_updated,
'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();""")
activity = psql_json("""
SELECT json_build_object(
'total', count(*),
'active', count(*) FILTER (WHERE state = 'active'),
'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();""")
datasets = psql_json("""
SELECT json_build_object(
'messages', (SELECT count(*) FROM messages),
'idempotency', (SELECT count(*) FROM message_idempotency),
'users', (SELECT count(*) FROM users),
'chats', (SELECT count(*) FROM chats),
'db_bytes', pg_database_size(current_database()),
'locks', (SELECT count(*) FROM pg_locks));""")
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'));""")
row = activity or {}
row['database'] = database or {}
row['datasets'] = datasets or {}
row['settings'] = settings or {}
return row
def haproxy_snapshot():
container = containers('lb')[0]['container_id']
result = run(['docker', 'exec', container, 'wget', '-qO-', 'http://127.0.0.1:8404/stats;csv'])
lines = [line for line in result.stdout.splitlines() if line.strip()]
if not lines:
return {}
header = lines[0].lstrip('# ').split(',')
rows = {}
for line in lines[1:]:
values = next(csv.reader(io.StringIO(line)))
item = dict(zip(header, values))
key = item.get('pxname', '') + '/' + item.get('svname', '')
rows[key] = item
return {
'public': rows.get('public/FRONTEND', {}),
'backend': rows.get('api/BACKEND', {}),
'servers': {key.split('/', 1)[1]: value for key, value in rows.items()
if key.startswith('api/') and key not in ('api/BACKEND', 'api/FRONTEND')},
'collected_at': iso(),
}
def api_stats():
result = {}
for item in containers('api'):
raw = run(['docker', 'exec', item['container_id'], 'wget', '-qO-',
'http://127.0.0.1:9090/internal/stats'], check=False).stdout
try:
result[item['hostname']] = json.loads(raw)
except ValueError:
result[item['hostname']] = {'error': 'stats unavailable'}
return result
def snapshot():
started = time.monotonic()
data = {
'collected_at': iso(),
'cgroups': cgroup_all(),
'db': db_snapshot(),
'haproxy': haproxy_snapshot(),
'api': api_stats(),
'containers': {service: containers(service) for service in SERVICES},
}
data['collection_seconds'] = round(time.monotonic() - started, 3)
return data
def wait_ready(timeout=90):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
result = run(['curl', '-fsS', '-o', '/dev/null', BASE_URL + '/health/ready'], check=False)
if result.returncode == 0:
return True
time.sleep(0.25)
return False
def wait_api_running(expected, timeout=90):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
items = containers('api')
if len(items) == expected and all(item['state'] == 'running' for item in items):
healthy = True
for item in items:
status = run(['docker', 'inspect', '-f', '{{if .State.Health}}{{.State.Health.Status}}{{end}}',
item['container_id']]).stdout.strip()
if status not in ('healthy',):
healthy = False
break
if healthy:
return items
time.sleep(0.25)
raise RuntimeError('API replicas did not become healthy')
def set_stack_profile(image, revision, replicas, api_cpu, api_mem, gomemlimit,
postgres_cpu='0.6', postgres_mem='512M', valkey_cpu='0.15',
valkey_mem='128M', lb_cpu='0.1', lb_mem='64M', recreate_state=False):
env_extra = {
'API_IMAGE': image,
'GIT_REVISION': revision,
'API_REPLICAS': str(replicas),
'API_CPU_LIMIT': str(api_cpu),
'API_MEM_LIMIT': api_mem,
'GOMEMLIMIT': gomemlimit,
'POSTGRES_CPU_LIMIT': postgres_cpu,
'POSTGRES_MEM_LIMIT': postgres_mem,
'VALKEY_CPU_LIMIT': valkey_cpu,
'VALKEY_MEM_LIMIT': valkey_mem,
'LB_CPU_LIMIT': lb_cpu,
'LB_MEM_LIMIT': lb_mem,
}
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)
wait_api_running(replicas)
if not wait_ready(120):
raise RuntimeError('LB did not become ready')
return env_extra
def delta(before, after):
"""Exact deltas for monotonic counters; elapsed is from snapshot times."""
def cg(snapshot_data):
return snapshot_data['cgroups']
result = {'api': {}, 'postgres': {}, 'valkey': {}, 'lb': {}}
for container_id, item in after['cgroups'].items():
previous = cg(before).get(container_id)
if not previous:
continue
current_values = item['cgroup']
old_values = previous['cgroup']
change = {}
for key in ('usage_usec', 'user_usec', 'system_usec', 'nr_periods', 'nr_throttled', 'throttled_usec'):
change[key] = current_values.get(key, 0) - old_values.get(key, 0)
change['memory_current_bytes_end'] = current_values.get('memory_current_bytes')
change['memory_max'] = current_values.get('memory_max')
result[item['service']][container_id] = change
db_before = before['db']; db_after = after['db']
result['db'] = {
'xact_commit': db_after['database']['xact_commit'] - db_before['database']['xact_commit'],
'xact_rollback': db_after['database']['xact_rollback'] - db_before['database']['xact_rollback'],
'blks_read': db_after['database']['blks_read'] - db_before['database']['blks_read'],
'blks_hit': db_after['database']['blks_hit'] - db_before['database']['blks_hit'],
'tup_inserted': db_after['database']['tup_inserted'] - db_before['database']['tup_inserted'],
'tup_returned': db_after['database']['tup_returned'] - db_before['database']['tup_returned'],
'temp_bytes': db_after['database']['temp_bytes'] - db_before['database']['temp_bytes'],
'deadlocks': db_after['database']['deadlocks'] - db_before['database']['deadlocks'],
'activity_after': db_after['total'],
'active_after': db_after['active'],
'active_waiting_after': db_after['active_waiting'],
'idle_in_transaction_after': db_after['idle_in_transaction'],
'settings': db_after['settings'],
'datasets_after': db_after['datasets'],
}
lb_before = before['haproxy']; lb_after = after['haproxy']
def number(row, key):
try:
return int(float(row.get(key) or 0))
except ValueError:
return 0
result['lb'] = {
'req_tot_delta': number(lb_after['public'], 'req_tot') - number(lb_before['public'], 'req_tot'),
'hrsp_5xx_delta': number(lb_after['public'], 'hrsp_5xx') - number(lb_before['public'], 'hrsp_5xx'),
'hrsp_4xx_delta': number(lb_after['public'], 'hrsp_4xx') - number(lb_before['public'], 'hrsp_4xx'),
'econ_delta': number(lb_after['backend'], 'econ') - number(lb_before['backend'], 'econ'),
'eresp_delta': number(lb_after['backend'], 'eresp') - number(lb_before['backend'], 'eresp'),
'qmax_after': number(lb_after['public'], 'qmax'),
'qcur_after': number(lb_after['public'], 'qcur'),
'rtime_ms_after': number(lb_after['backend'], 'rtime'),
'status_after': lb_after['backend'].get('status'),
}
result['api_pool'] = {}
for instance, current in after['api'].items():
previous = before['api'].get(instance, {})
pool_now = current.get('pool', {})
pool_before = previous.get('pool', {})
result['api_pool'][instance] = {
'max_conns': pool_now.get('max_conns'),
'empty_acquire_delta': pool_now.get('empty_acquire_count', 0) - pool_before.get('empty_acquire_count', 0),
'canceled_acquire_delta': pool_now.get('canceled_acquire_count', 0) - pool_before.get('canceled_acquire_count', 0),
'acquire_delta': pool_now.get('acquire_count', 0) - pool_before.get('acquire_count', 0),
'acquire_ms_delta': pool_now.get('acquire_duration_ms_total', 0) - pool_before.get('acquire_duration_ms_total', 0),
'total_conns_after': pool_now.get('total_conns'),
'acquired_conns_after': pool_now.get('acquired_conns'),
'messages_created_delta': (current.get('messages', {}).get('created', 0) -
previous.get('messages', {}).get('created', 0)),
'messages_replayed_delta': (current.get('messages', {}).get('replayed', 0) -
previous.get('messages', {}).get('replayed', 0)),
'messages_conflicts_delta': (current.get('messages', {}).get('conflicts', 0) -
previous.get('messages', {}).get('conflicts', 0)),
}
return result
def summarize_run(label, config, before, after, elapsed_seconds, load):
change = delta(before, after)
api_cpu = 0.0
api_throttled = 0.0
api_limit = 0.0
for item in after['containers']['api']:
values = change['api'].get(item['container_id'], {})
api_cpu += values.get('usage_usec', 0) / 1e6
api_throttled += values.get('throttled_usec', 0) / 1e6
api_limit += item['cpu_limit_nano'] / 1e9
postgres_values = next(iter(change['postgres'].values()), {})
valkey_values = next(iter(change['valkey'].values()), {})
lb_values = next(iter(change['lb'].values()), {})
postgres_limit = next((item['cpu_limit_nano'] / 1e9 for item in after['containers']['postgres']), 0)
lb_limit = next((item['cpu_limit_nano'] / 1e9 for item in after['containers']['lb']), 0)
valkey_limit = next((item['cpu_limit_nano'] / 1e9 for item in after['containers']['valkey']), 0)
total_api_cpu_used = api_cpu / elapsed_seconds
pool_waits = sum(value.get('empty_acquire_delta', 0) for value in change['api_pool'].values())
pool_acquires = sum(value.get('acquire_delta', 0) for value in change['api_pool'].values())
pool_acquire_ms = sum(value.get('acquire_ms_delta', 0) for value in change['api_pool'].values())
db = change['db']
lb = change['lb']
commits = db['xact_commit']
return {
'label': label,
'config': config,
'measured_seconds': round(elapsed_seconds, 3),
'loadgen': load,
'resource': {
'api_used_cores': round(total_api_cpu_used, 4),
'api_limit_cores': round(api_limit, 4),
'api_utilization': round(total_api_cpu_used / api_limit, 4) if api_limit else None,
'api_throttled_seconds': round(api_throttled, 4),
'db_used_cores': round(postgres_values.get('usage_usec', 0) / 1e6 / elapsed_seconds, 4),
'db_limit_cores': round(postgres_limit, 4),
'db_utilization': round(postgres_values.get('usage_usec', 0) / 1e6 / elapsed_seconds / postgres_limit, 4) if postgres_limit else None,
'db_throttled_seconds': round(postgres_values.get('throttled_usec', 0) / 1e6, 4),
'db_throttled_periods': postgres_values.get('nr_throttled', 0),
'valkey_used_cores': round(valkey_values.get('usage_usec', 0) / 1e6 / elapsed_seconds, 4),
'valkey_limit_cores': round(valkey_limit, 4),
'lb_used_cores': round(lb_values.get('usage_usec', 0) / 1e6 / elapsed_seconds, 4),
'lb_limit_cores': round(lb_limit, 4),
'api_cgroup_memory_end_bytes': [value.get('memory_current_bytes_end') for value in change['api'].values()],
'postgres_cgroup_memory_end_bytes': postgres_values.get('memory_current_bytes_end'),
'valkey_cgroup_memory_end_bytes': valkey_values.get('memory_current_bytes_end'),
'lb_cgroup_memory_end_bytes': lb_values.get('memory_current_bytes_end'),
},
'postgres': {
'commits_delta': commits,
'commits_per_second': round(commits / elapsed_seconds, 3),
'rollbacks_delta': db['xact_rollback'],
'buffer_hit_ratio': round(db['blks_hit'] / (db['blks_hit'] + db['blks_read']), 6) if (db['blks_hit'] + db['blks_read']) else None,
'tuples_inserted_delta': db['tup_inserted'],
'temp_bytes_delta': db['temp_bytes'],
'deadlocks_delta': db['deadlocks'],
'connections_after': db['activity_after'],
'active_after': db['active_after'],
'active_waiting_after': db['active_waiting_after'],
'idle_in_transaction_after': db['idle_in_transaction_after'],
'max_connections': db['settings'].get('max_connections'),
'datasets_after': db['datasets_after'],
'pool_waits_delta': pool_waits,
'pool_acquires_delta': pool_acquires,
'pool_acquire_ms_delta': pool_acquire_ms,
'pool_waits_per_acquire': round(pool_waits / pool_acquires, 6) if pool_acquires else 0,
},
'lb': lb,
'snapshot_before_at': before['collected_at'],
'snapshot_after_at': after['collected_at'],
}
def median(values):
values = [value for value in values if value is not None]
return round(statistics.median(values), 4) if values else None
def run_loadgen(binary, output, duration, warmup, concurrency, note, extra=None):
command = [str(binary), '-base-url', BASE_URL,
'-duration', '%ds' % duration, '-warmup', '%ds' % warmup,
'-concurrency', str(concurrency), '-output', str(output), '-note', note]
command.extend(extra or [])
result = run(command, check=False)
if not Path(output).exists():
raise RuntimeError('loadgen failed: ' + (result.stderr or result.stdout)[-800:])
return json.loads(Path(output).read_text())
def build_metadata(image):
docker_version = run(['docker', 'version', '--format', '{{.Server.Version}}']).stdout.strip()
info = run(['docker', 'info', '--format', '{{.NCPU}} {{.MemTotal}} {{.OperatingSystem}}']).stdout.strip()
uname = run(['uname', '-m']).stdout.strip()
revision = run(['git', 'rev-parse', 'HEAD']).stdout.strip()
status = run(['git', 'status', '--porcelain']).stdout.strip()
return {
'revision': revision,
'worktree_dirty': bool(status),
'image': image,
'docker_server_version': docker_version,
'docker_vm': info,
'arch': uname,
'collected_at': iso(),
'note': 'One Docker VM (Colima); all API replicas share one kernel, DB and LB. Not independent nodes.',
}
+54
View File
@@ -0,0 +1,54 @@
#!/bin/sh
# Restart the API and every state store this lab uses, keeping the named
# volumes and all data. This is the hook for:
# make test-persistence ACTION_SCRIPT=scripts/restart.sh
#
# It never removes volumes, never re-seeds and never prints credentials.
set -eu
cd "$(dirname "$0")/.."
if [ ! -f .env ]; then
echo "restart.sh: .env is missing; run make env first" >&2
exit 2
fi
compose="./scripts/compose.sh --env-file .env"
wait_healthy() {
container=$1
attempts=0
while [ "$attempts" -lt 60 ]; do
status=$(docker inspect -f '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' "$container" 2>/dev/null || echo missing)
if [ "$status" = "healthy" ] || [ "$status" = "running" ]; then
return 0
fi
attempts=$((attempts + 1))
sleep 1
done
echo "restart.sh: $container did not become healthy" >&2
return 1
}
echo "restart.sh: restarting shared postgres and valkey (volumes kept)"
postgres=$($compose ps -q postgres)
valkey=$($compose ps -q valkey)
$compose restart postgres valkey
wait_healthy "$postgres"
wait_healthy "$valkey"
echo "restart.sh: restarting every api replica"
$compose restart api
for container in $($compose ps -q api); do
wait_healthy "$container"
done
attempts=0
while [ "$attempts" -lt 90 ]; do
if curl -fsS -o /dev/null http://127.0.0.1:8083/health/ready 2>/dev/null; then
echo "restart.sh: all lab3 services restarted; volumes preserved"
exit 0
fi
attempts=$((attempts + 1))
sleep 1
done
echo "restart.sh: LB readiness did not recover" >&2
exit 1
+42
View File
@@ -0,0 +1,42 @@
#!/bin/sh
# Stop exactly the API replica that served TARGET_INSTANCE_ID and leave it
# stopped. This is the hook for:
# make test-failover ACTION_SCRIPT=scripts/stop-one.sh
#
# X-Instance-Id is the container hostname in lab3, so the mapping is an exact
# identity match, not a guess from a header prefix. The script touches only
# that one API container: no DB, no sessions, no volumes, no LB.
set -eu
cd "$(dirname "$0")/.."
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
if [ ! -f .env ]; then
echo "stop-one.sh: .env is missing; run make env first" >&2
exit 2
fi
target=""
for container in $(./scripts/compose.sh --env-file .env ps -q api); do
hostname=$(docker inspect -f '{{.Config.Hostname}}' "$container" 2>/dev/null || true)
if [ "$hostname" = "$TARGET_INSTANCE_ID" ]; then
target=$container
break
fi
done
if [ -z "$target" ]; then
echo "stop-one.sh: no running API container has hostname $TARGET_INSTANCE_ID" >&2
exit 1
fi
echo "stop-one.sh: stopping API container $target (instance $TARGET_INSTANCE_ID)"
# SIGTERM starts the drain window; compose stop_grace_period is 15 s and the
# application's hard shutdown budget is 6 s, so this returns well within the
# test's 10 s hook budget. The container stays stopped afterwards.
docker stop --time 15 "$target" >/dev/null
state=$(docker inspect -f '{{.State.Status}}' "$target")
if [ "$state" != "exited" ] && [ "$state" != "dead" ]; then
echo "stop-one.sh: container state is $state, expected exited" >&2
exit 1
fi
echo "stop-one.sh: container $target is $state; other replicas keep serving"
+16
View File
@@ -0,0 +1,16 @@
#!/bin/sh
# Wait until /health/ready answers 200 through the load balancer.
# Usage: scripts/wait-ready.sh [url]
set -eu
url=${1:-http://127.0.0.1:8083/health/ready}
attempts=0
while [ "$attempts" -lt 120 ]; do
if curl -fsS -o /dev/null "$url" 2>/dev/null; then
echo "ready: $url"
exit 0
fi
attempts=$((attempts + 1))
sleep 1
done
echo "not ready after 120 seconds: $url" >&2
exit 1