forked from mtusi2026/mtusi2026lab2
139 lines
6.0 KiB
Python
139 lines
6.0 KiB
Python
"""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()
|