feat: implement lab3 API load balancing and failover
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate local-only credentials and select an available public port."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import socket
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
os.umask(0o077)
|
||||
(root / 'secrets').mkdir(exist_ok=True)
|
||||
p = root / 'secrets/postgres_password'
|
||||
if not p.exists():
|
||||
p.write_text(secrets.token_hex(24))
|
||||
u = root / 'secrets/database_url'
|
||||
if not u.exists():
|
||||
u.write_text('postgresql://messenger:' + p.read_text().strip() + '@postgres:5432/messenger')
|
||||
e = root / '.env'
|
||||
if not e.exists():
|
||||
for port in range(8080, 8100):
|
||||
with socket.socket() as sock:
|
||||
try:
|
||||
sock.bind(('127.0.0.1', port))
|
||||
except PermissionError:
|
||||
raise SystemExit('Port probing denied by sandbox; rerun bootstrap with local network permission')
|
||||
except OSError:
|
||||
continue
|
||||
e.write_text(f'PUBLIC_PORT={port}\n')
|
||||
break
|
||||
else:
|
||||
raise RuntimeError('No available port')
|
||||
print('Local configuration ready; ' + e.read_text().strip())
|
||||
@@ -0,0 +1,19 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Sanitized Docker metadata; deliberately omit Config.Env and secret files."""
|
||||
import datetime
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
root=Path(__file__).resolve().parents[1]
|
||||
ids=subprocess.check_output([str(root/'scripts/compose.sh'),'ps','-a','-q'],text=True).splitlines()
|
||||
result=[]
|
||||
for container in json.loads(subprocess.check_output(['docker','inspect',*ids],text=True)):
|
||||
result.append({'name':container['Name'],'id':container['Id'],'image':container['Image'],
|
||||
'state':{k:v for k,v in container['State'].items() if k in ['Status','Running','StartedAt','FinishedAt','ExitCode']},
|
||||
'health':container['State'].get('Health',{}).get('Status'),
|
||||
'memory_limit_bytes':container['HostConfig']['Memory'],
|
||||
'nano_cpus':container['HostConfig']['NanoCpus'],
|
||||
'port_bindings':container['HostConfig']['PortBindings'],
|
||||
'volumes':[m['Name'] for m in container['Mounts'] if m['Type']=='volume']})
|
||||
print(json.dumps({'recorded_at_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'containers':result},indent=2))
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
if [ -d /Applications/Docker.app/Contents/Resources/bin ]; then
|
||||
export PATH="/Applications/Docker.app/Contents/Resources/bin:$PATH"
|
||||
fi
|
||||
exec docker compose --env-file .env "$@"
|
||||
Executable
+53
@@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Local synthetic demonstration; credentials stay in ignored secrets/demo.json."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0,str(ROOT/'tests'))
|
||||
from client import Client
|
||||
|
||||
parser=argparse.ArgumentParser()
|
||||
parser.add_argument('action',choices=['register','chat','message','history','instances','idempotency'])
|
||||
parser.add_argument('--text',default='Синтетическое сообщение для демонстрации')
|
||||
parser.add_argument('--key')
|
||||
args=parser.parse_args()
|
||||
os.umask(0o077)
|
||||
state_file=ROOT/'secrets/demo.json'
|
||||
state=json.loads(state_file.read_text()) if state_file.exists() else {}
|
||||
c=Client()
|
||||
if args.action=='register':
|
||||
state={'actor':c.user('demo')}
|
||||
print('Registered and authenticated synthetic user:',state['actor']['id'])
|
||||
elif args.action=='chat':
|
||||
state['chat']=c.call('POST','/api/v1/chats',201,actor=state['actor'],body={'title':'Демонстрация','member_ids':[state['actor']['id']]},schema='Chat')['json']
|
||||
print(json.dumps(state['chat'],ensure_ascii=False,indent=2))
|
||||
elif args.action=='message':
|
||||
result=c.message(state['actor'],state['chat'],args.text,key=args.key)
|
||||
print('HTTP',result['status'],'instance',result['headers']['X-Instance-Id'])
|
||||
print(json.dumps(result['json'],ensure_ascii=False,indent=2))
|
||||
elif args.action=='history':
|
||||
from resilience import history
|
||||
print(json.dumps(history(c,state['actor'],state['chat']),ensure_ascii=False,indent=2))
|
||||
elif args.action=='instances':
|
||||
seen=set()
|
||||
for _ in range(12):
|
||||
result=c.call('GET','/api/v1/users/me',actor=state['actor'],schema='User')
|
||||
alias=result['headers']['X-Instance-Id']
|
||||
seen.add(alias)
|
||||
print('HTTP 200 instance',alias,'same_user',result['json']['id']==state['actor']['id'])
|
||||
print('Distinct API processes:',len(seen))
|
||||
elif args.action=='idempotency':
|
||||
key=uuid.uuid4().hex
|
||||
first=c.message(state['actor'],state['chat'],'idem demonstration',key)
|
||||
second=c.message(state['actor'],state['chat'],'idem demonstration',key)
|
||||
assert first['json']==second['json']
|
||||
path='/api/v1/chats/'+state['chat']['id']+'/messages'
|
||||
c.call('POST',path,409,actor=state['actor'],body={'text':'changed'},headers={'Idempotency-Key':key})
|
||||
print('PASS: 201 + 201 same message',first['json']['id'],'; changed body 409')
|
||||
state_file.parent.mkdir(exist_ok=True)
|
||||
state_file.write_text(json.dumps(state))
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
# Restart every running replica and both stores; volumes and tokens survive.
|
||||
scripts/compose.sh restart postgres redis api lb
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
# Target only existing API containers, never their dependencies.
|
||||
for id in $(scripts/compose.sh ps -a -q api); do
|
||||
docker start "$id"
|
||||
done
|
||||
Executable
+79
@@ -0,0 +1,79 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Sequential replacement on a single Compose host; run build/migrate first.
|
||||
No schema changes are applied here. Compatible old/new APIs are required.
|
||||
"""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
COMPOSE = [str(ROOT / 'scripts/compose.sh')]
|
||||
|
||||
|
||||
def command(*args):
|
||||
return subprocess.check_output(args, cwd=ROOT, text=True, stderr=subprocess.DEVNULL).strip()
|
||||
|
||||
|
||||
def containers():
|
||||
return command(*COMPOSE, 'ps', '-q', 'api').splitlines()
|
||||
|
||||
|
||||
def instance(container):
|
||||
return command('docker', 'exec', container, 'python', '-c',
|
||||
'import urllib.request; r=urllib.request.urlopen("http://127.0.0.1:8080/health/ready",timeout=2); print(r.headers["X-Instance-Id"])')
|
||||
|
||||
|
||||
def rolling_update():
|
||||
originals = containers()
|
||||
if len(originals) != 2:
|
||||
raise RuntimeError('Restore exactly two healthy API replicas first')
|
||||
for container in originals:
|
||||
instance(container)
|
||||
port = dict(line.split('=', 1) for line in (ROOT / '.env').read_text().splitlines() if '=' in line)['PUBLIC_PORT']
|
||||
events = []
|
||||
for old in originals:
|
||||
before = set(containers())
|
||||
survivor = next(c for c in before if c != old)
|
||||
instance(survivor)
|
||||
old_alias = instance(old)
|
||||
old_image = command("docker", "inspect", "--format", "{{.Image}}", old)
|
||||
old_ip = command("docker", "inspect", "--format", "{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}", old)
|
||||
started = time.monotonic()
|
||||
command('docker', 'stop', '--timeout', '6', old)
|
||||
command('docker', 'rm', old)
|
||||
# --no-recreate keeps the healthy survivor, even after an image build.
|
||||
command(*COMPOSE, 'up', '-d', '--no-deps', '--no-recreate', '--scale', 'api=2', 'api')
|
||||
after = set(containers())
|
||||
assert survivor in after and old not in after
|
||||
new = next(c for c in after if c not in before)
|
||||
deadline = time.monotonic() + 45
|
||||
seen = set()
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
new_alias = instance(new)
|
||||
with urllib.request.urlopen(f'http://127.0.0.1:{port}/health/ready', timeout=2) as r:
|
||||
seen.add(r.headers['X-Instance-Id'])
|
||||
if new_alias in seen and instance(survivor) in seen:
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(.2)
|
||||
else:
|
||||
raise RuntimeError('Replacement did not join LB')
|
||||
event = {'old_container': old, 'old_instance': old_alias,
|
||||
'new_container': new, 'new_instance': new_alias,
|
||||
'survivor_container': survivor,
|
||||
'old_image': old_image,
|
||||
'new_image': command('docker', 'inspect', '--format', '{{.Image}}', new),
|
||||
'old_ip': old_ip,
|
||||
'new_ip': command('docker', 'inspect', '--format', '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}', new),
|
||||
'replacement_seconds': round(time.monotonic()-started, 3)}
|
||||
events.append(event)
|
||||
print(json.dumps(event), flush=True)
|
||||
return events
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
rolling_update()
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
exec python3 scripts/rolling-update.py
|
||||
Executable
+15
@@ -0,0 +1,15 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
: "${TARGET_INSTANCE_ID:?TARGET_INSTANCE_ID is required}"
|
||||
found=''
|
||||
for id in $(scripts/compose.sh ps -q api); do
|
||||
actual=$(docker exec "$id" python -c 'import urllib.request; r=urllib.request.urlopen("http://127.0.0.1:8080/health/live",timeout=2); print(r.headers["X-Instance-Id"])')
|
||||
if [ "$actual" = "$TARGET_INSTANCE_ID" ]; then
|
||||
found="$id"
|
||||
break
|
||||
fi
|
||||
done
|
||||
[ -n "$found" ] || { echo 'No matching running API process' >&2; exit 1; }
|
||||
printf 'Stopping API container %s instance %s\n' "$found" "$TARGET_INSTANCE_ID"
|
||||
docker stop --timeout 6 "$found"
|
||||
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Summarize sampled peaks per service, summing replicas within each sample."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
root=Path(__file__).resolve().parents[1]
|
||||
out={}
|
||||
for name in ['load-baseline','failover-replica-1','failover-replica-2','rolling-update','rolling-continuity']:
|
||||
file=root/'evidence'/(name+('-resources.json' if name=='load-baseline' else '.json'))
|
||||
if not file.exists():
|
||||
continue
|
||||
raw=json.loads(file.read_text())
|
||||
samples=raw if isinstance(raw,list) else raw['resources']
|
||||
summary={}
|
||||
for sample in samples:
|
||||
groups={}
|
||||
for row in sample['containers']:
|
||||
service=re.sub(r'-[0-9]+$','',row['Name'].removeprefix('mtusi2026lab3-'))
|
||||
cpu=float(row['CPUPerc'].rstrip('%'))
|
||||
match=re.match(r'([0-9.]+)([A-Za-z]+)',row['MemUsage'].split('/')[0].strip())
|
||||
mib=float(match[1])*{'B':1/1048576,'KiB':1/1024,'MiB':1,'GiB':1024}[match[2]]
|
||||
value=groups.setdefault(service,[0,0])
|
||||
value[0]+=cpu
|
||||
value[1]+=mib
|
||||
for service,(cpu,mem) in groups.items():
|
||||
value=summary.setdefault(service,{'peak_sampled_cpu_percent':0,'peak_sampled_memory_mib':0})
|
||||
value['peak_sampled_cpu_percent']=max(value['peak_sampled_cpu_percent'],round(cpu,2))
|
||||
value['peak_sampled_memory_mib']=max(value['peak_sampled_memory_mib'],round(mem,2))
|
||||
out[name]={'samples':len(samples),'service_totals':summary}
|
||||
(root/'evidence/resources-summary.json').write_text(json.dumps(out,indent=2)+'\n')
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
python3 scripts/bootstrap.py
|
||||
scripts/compose.sh config --quiet
|
||||
scripts/compose.sh up -d --build
|
||||
export BASE_URL="http://localhost:$(sed -n 's/^PUBLIC_PORT=//p' .env)"
|
||||
python3 scripts/wait-ready.py
|
||||
printf 'API and Swagger: %s/docs\n' "$BASE_URL"
|
||||
Executable
+26
@@ -0,0 +1,26 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
export BASE_URL="${BASE_URL:-http://localhost:$(sed -n 's/^PUBLIC_PORT=//p' .env)}"
|
||||
make check > evidence/check.txt 2>&1
|
||||
make validate PYTHON=.venv/bin/python > evidence/validate.txt 2>&1
|
||||
make test > evidence/smoke.txt 2>&1
|
||||
python3 student-tests/check_auth.py > evidence/auth.txt 2>&1
|
||||
python3 student-tests/scenarios.py idempotency --output evidence/idempotency.json
|
||||
python3 scripts/capture-state.py > evidence/persistence-containers-before.json
|
||||
make test-persistence ACTION_SCRIPT=scripts/restart.sh > evidence/persistence.txt 2>&1
|
||||
python3 scripts/wait-ready.py
|
||||
python3 scripts/capture-state.py > evidence/persistence-containers-after.json
|
||||
make test-failover ACTION_SCRIPT=scripts/stop-one.sh > evidence/failover-public.txt 2>&1
|
||||
scripts/restore.sh
|
||||
python3 scripts/wait-ready.py
|
||||
python3 student-tests/scenarios.py failover --target-index 0 --output evidence/failover-replica-1.json
|
||||
python3 student-tests/scenarios.py failover --target-index 1 --output evidence/failover-replica-2.json
|
||||
python3 student-tests/baseline.py
|
||||
python3 student-tests/scenarios.py rolling --output evidence/rolling-update.json
|
||||
|
||||
python3 student-tests/dns.py
|
||||
python3 student-tests/readiness.py
|
||||
python3 scripts/summarize-resources.py
|
||||
python3 scripts/capture-state.py > evidence/containers.json
|
||||
scripts/compose.sh ps -a > evidence/containers.txt
|
||||
@@ -0,0 +1,19 @@
|
||||
#!/usr/bin/env python3
|
||||
import os
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
base = os.getenv('BASE_URL', 'http://localhost:8080')
|
||||
seen = set()
|
||||
for _ in range(180):
|
||||
try:
|
||||
with urllib.request.urlopen(base+'/health/ready', timeout=2) as r:
|
||||
seen.add(r.headers['X-Instance-Id'])
|
||||
if len(seen)>=2:
|
||||
print('Ready: two API instances through LB:', ', '.join(sorted(seen)))
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(.5)
|
||||
else:
|
||||
raise SystemExit('Two ready instances not observed in readiness deadline')
|
||||
Reference in New Issue
Block a user