forked from mtusi2026/mtusi2026lab3
242 lines
10 KiB
Python
Executable File
242 lines
10 KiB
Python
Executable File
#!/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(),
|
|
}
|
|
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')
|
|
|
|
|
|
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)
|