Добавить restart-hook и доказательства локальных проверок

This commit is contained in:
2026-11-16 21:47:40 +00:00
parent 39197c218f
commit 87d279bfb5
6 changed files with 204 additions and 0 deletions
+34
View File
@@ -0,0 +1,34 @@
$ /workspace/scratch/a9cc7b7e4e4a/.venv/bin/python -m messenger.migrate
Migrations applied successfully (already applied versions skipped).
$ /workspace/scratch/a9cc7b7e4e4a/.venv/bin/python -m messenger.migrate
Migrations applied successfully (already applied versions skipped).
$ make check validate student-test PYTHON=/workspace/scratch/a9cc7b7e4e4a/.venv/bin/python
/workspace/scratch/a9cc7b7e4e4a/.venv/bin/python scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
/workspace/scratch/a9cc7b7e4e4a/.venv/bin/python scripts/validate_openapi.py
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
/workspace/scratch/a9cc7b7e4e4a/.venv/bin/python -m unittest discover -s student-tests -v
test_atomic_chat_and_migration_repeat (test_api.ApiTests.test_atomic_chat_and_migration_repeat) ... ok
test_authentication_and_logout (test_api.ApiTests.test_authentication_and_logout) ... ok
test_expiry_and_restart_app (test_api.ApiTests.test_expiry_and_restart_app) ... ok
test_pagination_survives_new_app (test_api.ApiTests.test_pagination_survives_new_app) ... ok
test_strict_validation_and_private_chat (test_api.ApiTests.test_strict_validation_and_private_chat) ... ok
----------------------------------------------------------------------
Ran 5 tests in 4.193s
OK
$ make test BASE_URL=http://127.0.0.1:18080 PYTHON=/workspace/scratch/a9cc7b7e4e4a/.venv/bin/python
/workspace/scratch/a9cc7b7e4e4a/.venv/bin/python tests/smoke.py --base-url "http://127.0.0.1:18080"
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
$ make test-persistence ACTION_SCRIPT=/tmp/messenger-lab2-3_7rknxw/restart.sh BASE_URL=http://127.0.0.1:18080 PYTHON=/workspace/scratch/a9cc7b7e4e4a/.venv/bin/python
/workspace/scratch/a9cc7b7e4e4a/.venv/bin/python tests/resilience.py --mode persistence --action-script "/tmp/messenger-lab2-3_7rknxw/restart.sh" --base-url "http://127.0.0.1:18080"
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
Real local PostgreSQL restart (not Docker)
API PID: 34 -> 1056
PostgreSQL start: 2026-11-15T21:29:56.296193+00:00 -> 2026-11-15T21:30:04.106927+00:00
Same data directory; no initdb/migrations/reseed in restart hook.
Verified database: PostgreSQL 16.2 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 10.2.1 20210130 (Red Hat 10.2.1-11), 64-bit
PASS: DB outage gives ready=503, live=200
+4
View File
@@ -0,0 +1,4 @@
Real local PostgreSQL restart (not Docker)
API PID: 34 -> 1056
PostgreSQL start: 2026-11-15T21:29:56.296193+00:00 -> 2026-11-15T21:30:04.106927+00:00
Same data directory; no initdb/migrations/reseed in restart hook.
+2
View File
@@ -0,0 +1,2 @@
/mtusi2026lab2-db-1 2026-11-15T21:36:49.02822853Z running
/mtusi2026lab2-api-1 2026-11-15T21:36:51.309065877Z running
+2
View File
@@ -0,0 +1,2 @@
/mtusi2026lab2-db-1 2026-11-15T21:35:53.794161714Z running
/mtusi2026lab2-api-1 2026-11-15T21:35:56.415432352Z running
+138
View File
@@ -0,0 +1,138 @@
"""Optional Linux/macOS verification with real local PostgreSQL binaries.
Usage: python scripts/check_local.py --pg-bin /path/to/postgresql/bin
Creates a private temporary cluster; never touches an existing database.
The normal delivery/deployment path remains Docker Compose.
"""
import argparse
import json
import os
from pathlib import Path
import shlex
import signal
import subprocess
import sys
import tempfile
import time
from urllib.request import urlopen
ROOT = Path(__file__).resolve().parents[1]
def pg(state, *args):
return subprocess.run([str(Path(state['bin']) / 'pg_ctl'), '-D', state['data'], *args],
check=True, stdout=subprocess.DEVNULL)
def start_api(state, env):
with open(Path(state['data']).parent / 'api.log', 'a') as log:
process = subprocess.Popen([sys.executable, '-m', 'messenger'], cwd=ROOT,
env=env, stdout=log, stderr=log, start_new_session=True)
state['api_pid'] = process.pid
return process
def ready():
for _ in range(100):
try:
with urlopen('http://127.0.0.1:18080/health/ready', timeout=1) as r:
if r.status == 200:
return
except OSError:
time.sleep(0.1)
raise RuntimeError('Local API did not become ready')
def restart(state_path):
import psycopg
state = json.loads(state_path.read_text())
with psycopg.connect(os.environ['DATABASE_URL']) as conn:
before = conn.execute('SELECT pg_postmaster_start_time()').fetchone()[0]
old_pid = state['api_pid']
os.kill(old_pid, signal.SIGTERM)
pg(state, '-m', 'fast', '-w', 'stop')
pg(state, '-l', str(state_path.parent / 'postgres.log'), '-w', 'start')
start_api(state, dict(os.environ))
state_path.write_text(json.dumps(state))
ready()
with psycopg.connect(os.environ['DATABASE_URL']) as conn:
after = conn.execute('SELECT pg_postmaster_start_time()').fetchone()[0]
assert before != after and old_pid != state['api_pid']
(ROOT / 'evidence/local-restart.txt').write_text(
'Real local PostgreSQL restart (not Docker)\n'
'API PID: %s -> %s\nPostgreSQL start: %s -> %s\n'
'Same data directory; no initdb/migrations/reseed in restart hook.\n' %
(old_pid, state['api_pid'], before.isoformat(), after.isoformat()))
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--pg-bin')
parser.add_argument('--restart', type=Path)
args = parser.parse_args()
if args.restart:
restart(args.restart)
return
if not args.pg_bin:
parser.error('--pg-bin is required')
binary = Path(args.pg_bin).resolve()
with tempfile.TemporaryDirectory(prefix='messenger-lab2-') as tmp:
temp = Path(tmp)
state_path = temp / 'state.json'
state = {'bin': str(binary), 'data': str(temp / 'data')}
env = dict(os.environ, DATABASE_URL='postgresql://127.0.0.1:15432/postgres',
APP_PORT='18080', APP_HOST='127.0.0.1', SESSION_TTL_SECONDS='3600')
env.pop('DATABASE_URL_FILE', None)
env['SESSION_STORE'] = 'postgres'
subprocess.run([str(binary / 'initdb'), '-D', state['data'], '-A', 'trust',
'--no-locale', '-E', 'UTF8'], check=True, stdout=subprocess.DEVNULL)
with (Path(state['data']) / 'postgresql.conf').open('a') as f:
f.write("\nport=15432\nlisten_addresses='127.0.0.1'\nunix_socket_directories=''\ntimezone='UTC'\n")
initial_process = None
try:
pg(state, '-l', str(temp / 'postgres.log'), '-w', 'start')
def run(command):
print('$ ' + ' '.join(command), flush=True)
subprocess.run(command, env=env, cwd=ROOT, check=True)
run([sys.executable, '-m', 'messenger.migrate'])
run([sys.executable, '-m', 'messenger.migrate'])
initial_process = start_api(state, env)
state_path.write_text(json.dumps(state))
ready()
run(['make', 'check', 'validate', 'student-test', 'PYTHON=' + sys.executable])
run(['make', 'test', 'BASE_URL=http://127.0.0.1:18080', 'PYTHON=' + sys.executable])
hook = temp / 'restart.sh'
hook.write_text('#!/bin/sh\nexec ' + shlex.join([sys.executable, str(Path(__file__).resolve()),
'--restart', str(state_path)]) + '\n')
hook.chmod(0o700)
run(['make', 'test-persistence', 'ACTION_SCRIPT=' + str(hook),
'BASE_URL=http://127.0.0.1:18080', 'PYTHON=' + sys.executable])
print((ROOT / 'evidence/local-restart.txt').read_text(), flush=True)
import psycopg
with psycopg.connect(env['DATABASE_URL']) as conn:
print('Verified database: ' + conn.execute('SELECT version()').fetchone()[0], flush=True)
# A real dependency outage must not leave the application ready.
pg(state, '-m', 'fast', '-w', 'stop')
from urllib.error import HTTPError
try:
urlopen('http://127.0.0.1:18080/health/ready', timeout=8)
raise AssertionError('Readiness must fail without PostgreSQL')
except HTTPError as error:
assert error.code == 503
assert urlopen('http://127.0.0.1:18080/health/live').status == 200
print('PASS: DB outage gives ready=503, live=200', flush=True)
finally:
if state_path.exists():
current = json.loads(state_path.read_text())
try:
os.kill(current['api_pid'], signal.SIGTERM)
except ProcessLookupError:
pass
if initial_process is not None:
initial_process.wait(timeout=10)
subprocess.run([str(binary / 'pg_ctl'), '-D', state['data'], '-m', 'fast', '-w', 'stop'],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
if __name__ == '__main__':
main()
+24
View File
@@ -0,0 +1,24 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
# Stop API first; restart the only store, keeping its named volume.
mkdir -p evidence
snapshot() {
for service in db api; do
id=$(docker compose ps -q "$service")
docker inspect --format '{{.Name}} {{.State.StartedAt}} {{.State.Status}}' "$id"
done
}
snapshot > evidence/restart-before.txt
docker compose stop -t 10 api
docker compose restart -t 10 db
# Wait for DB before the API applies idempotent migrations.
i=0
until docker compose exec -T db pg_isready -U messenger -d messenger >/dev/null 2>&1; do
i=$((i + 1))
[ "$i" -lt 30 ] || exit 1
sleep 1
done
docker compose start api
snapshot > evidence/restart-after.txt
# Public resilience.py waits for readiness and tests the OLD token.