import hashlib import json import os import signal import shutil import subprocess import sys import time from datetime import datetime,timedelta,timezone import secrets from pathlib import Path ROOT=Path.cwd() REPO=ROOT/"framework" sys.path.insert(0,str(REPO)) import db_tools as fixture from db_tools import cmd, good, record, require, DOCKER, PASSWORDS from core.approval import issue_approval from core.backup import BackupEngine from core.compatibility import canonical_hash from core.database import get_adapter from core.database_identity import DatabaseIdentityProbe from core.deployment import DeploymentController, DeploymentError from core.dev3.operations import SiteOperations from core.execution import CommandRunner from core.locking import LockError from core.migration import MigrationCoordinator, MigrationError from core.migration_recovery import MigrationRecovery, MigrationRecoveryError from core.migration_archive import MigrationArchive from core.trusted_rehearsal import TrustedRehearsal from core.services import ContainedServiceLifecycle from core.operator_approval import OperatorApprovalPolicy, OperatorGrant from core.releases import ReleaseManager from core.transactions import TransactionError, TransactionJournal REVISION="054c546c8fc24684779dbcc890c72c0bf3d344df" fixture.EXPECTED=REVISION fixture.REPO=REPO MIGRATION="2026_11_28_000001_recovery_probe" BASE="2026_01_01_000000_create_fixture" SITE="absdev-migration-lab" def digest(path): return hashlib.sha256(path.read_bytes()).hexdigest() def write(name,data): (ROOT/name).write_text(json.dumps(data,indent=2,sort_keys=True)+"\n") RUNTIME = None NGINX_IMAGE = "nginx@sha256:552e7481ca93ffccd046aa658dbbed22caefbc09c66fa7cd247cbb90b8a5c609" PYTHON_IMAGE = "python@sha256:22eafb370920ad8b429e0aec3fff433e0669968519f5d60469d83729c138b28b" def live_services(config, app): global RUNTIME site = SITE + "-" + fixture.RUN project = "site-" + site runtime = ROOT / "docker-runtime" runtime.mkdir() gate = runtime / "gate" gate.mkdir(mode=0o755) gate.chmod(0o755) spec = runtime / "nginx.conf" spec.write_text("""pid /tmp/nginx.pid; events {} http { access_log off; server { listen 8080; root /srv/app/current/public; location / { if (-f /gate/closed) { return 503 "maintenance"; } try_files /index.php =404; } } server { listen 127.0.0.1:8081; root /srv/app/current/public; location / { try_files /index.php =404; } } } """) spec.chmod(0o644) # The mount hides private ancestors; static fixture pages remain readable. for directory in (app, app/"releases", *(app/"releases").iterdir()): for child in (directory, directory/"public"): if child.is_dir(): child.chmod(0o755) page=directory/"public/index.php" if page.exists(): page.chmod(0o644) worker={"image":PYTHON_IMAGE,"pull_policy":"never","read_only":True, "entrypoint":["python","-c","import time; time.sleep(600)"],"networks":["private"], "cap_drop":["ALL"],"security_opt":["no-new-privileges:true"],"user":"10001:10001"} services={name:dict(worker) for name in ("php","queue","scheduler")} services["web"]={"image":NGINX_IMAGE,"pull_policy":"never", "entrypoint":["nginx","-g","daemon off;"],"networks":["private"], "volumes":[f"{spec}:/etc/nginx/nginx.conf:ro",f"{app}:/srv/app:ro",f"{gate}:/gate:ro"], "security_opt":["no-new-privileges:true"],"cap_drop":["NET_RAW"]} services["healthcheck"]={k:v for k,v in worker.items() if k!="networks"} services["healthcheck"]["network_mode"]="service:web" services["healthcheck"]["depends_on"]=["web"] (runtime/"compose.yaml").write_text(json.dumps({"services":services,"networks":{"private":{"internal":True}}})) config=json.loads(json.dumps(config)) config["site"].update(root=str(runtime),identifier=site) config["docker"].update(project=project,backend_network="private") wrapper=("sudo","-n","env","DOCKER_CONFIG=/var/tmp/absdev-supported-containment.L6qYEi/docker-config","docker") prefix=("docker","compose","--project-name",project,"--project-directory",str(runtime), "--file",str(runtime/"compose.yaml")) def invoke(*tail,timeout=60): return cmd((*wrapper,*prefix[1:],*tail), timeout=timeout) def verify(argv,*,timeout): require(argv[:len(prefix)]==prefix,"Unexpected Compose project") return invoke(*argv[len(prefix):],timeout=timeout) def runner(argv,*,timeout): result=verify(argv,timeout=timeout) require(result.returncode==0,result.stderr[-800:]) return result.returncode def topology(argv,*,timeout): result=verify(argv,timeout=timeout) require(result.returncode==0,"Compose topology unavailable") return result.stdout def status(service): container=invoke("ps","-aq",service).stdout.strip() return bool(container) and good((*DOCKER,"inspect","--format","{{.State.Running}}",container))=="true" def http(port): probe=("import http.client,json,sys; c=http.client.HTTPConnection('127.0.0.1',int(sys.argv[1]),timeout=3); " "c.request('GET','/'); r=c.getresponse(); print(json.dumps([r.status,r.read().decode().strip()]))") for _ in range(12): result=invoke("exec","-T","healthcheck","python","-c",probe,str(port)) if result.returncode==0: return tuple(json.loads(result.stdout)) time.sleep(.25) raise RuntimeError("Live Nginx probe failed") RUNTIME=lambda: good((*wrapper,*prefix[1:],"down","--timeout","2","--volumes")) require(invoke("up","-d","--pull","never").returncode==0,"Live runtime startup failed") require(http(8080)==(200,"release=2") and all(status(n) for n in ("queue","scheduler")), "Live runtime did not serve the original release with active workers") record("runtime","Nginx served original release and both real worker containers ran before containment","PASS") lifecycle=ContainedServiceLifecycle(config,runner,gate_directory=gate, ingress_sealed=lambda:http(8080)==(503,"maintenance"), worker_running=status,stop_timeout=2,topology_runner=topology) return lifecycle,http,status def exercise(name): fixture.ready("postgres",name,"postgres") admin=fixture.connect("postgres",name,"admin","postgres") good(admin,"CREATE DATABASE fixture;") database=fixture.connect("postgres",name,"admin") for account in ("migration_user","backup_user"): good(database,f"CREATE ROLE {account} LOGIN PASSWORD '{PASSWORDS[account]}';") good(database,f""" REVOKE CONNECT, TEMPORARY ON DATABASE fixture FROM PUBLIC; GRANT CONNECT ON DATABASE fixture TO migration_user,backup_user; CREATE SCHEMA work AUTHORIZATION migration_user; GRANT USAGE ON SCHEMA work TO backup_user; ALTER DEFAULT PRIVILEGES FOR ROLE migration_user IN SCHEMA work GRANT SELECT ON TABLES TO backup_user; REVOKE ALL ON FUNCTION pg_catalog.pg_control_system() FROM PUBLIC; GRANT EXECUTE ON FUNCTION pg_catalog.pg_control_system() TO backup_user,migration_user; """) migration=fixture.connect("postgres",name,"migration_user") good(migration,f""" CREATE TABLE work.migrations(name TEXT PRIMARY KEY); INSERT INTO work.migrations VALUES ('{BASE}'); CREATE TABLE work.items(id INT PRIMARY KEY, label TEXT); INSERT INTO work.items VALUES (1,'original'); """) server=good(database,"SELECT system_identifier FROM pg_control_system();") pgpass="".join(f"127.0.0.1:5432:fixture:{role}:{PASSWORDS[role]}\n" for role in ("backup_user","migration_user")) good((*DOCKER,"exec","-i",name,"sh","-c","umask 077; mkdir -p /run/secrets; cat >/run/secrets/absdev-pgpass"),pgpass) config=json.loads((REPO/"config/site.example.json").read_text()) config["database"].update(driver="pgsql",container=name,host="127.0.0.1",port=5432,name="fixture",username="backup_user") backup_adapter=get_adapter(config) config["database"]["username"]="migration_user" migration_adapter=get_adapter(config) commands=[backup_adapter.live_identity_command(),backup_adapter.backup_command(),migration_adapter.live_identity_command()] runner=CommandRunner([["sudo","-n",*args] for args in commands],timeout=50) def run(args,out): runner(["sudo","-n",*args],out) backup_probe=DatabaseIdentityProbe(backup_adapter,run,server_id=server) identity=DatabaseIdentityProbe(migration_adapter,run,server_id=server) db_identity=canonical_hash(identity.observe()) backup_dir=ROOT/"backups" backup_dir.mkdir() backup=BackupEngine(backup_adapter,backup_dir,run,live_identity=backup_probe) artifact=backup.create() manifest=backup.verify(artifact) require(backup_probe(),"Backup identity not verified") write("backup-manifest.json",manifest) record("postgres","real transactionally consistent PostgreSQL backup verified","PASS",manifest["sha256"]) scratch="isolated_restore_migration_ci" rehearsal_id=canonical_hash({"database":scratch,"cluster":server}) app=ROOT/"app" versions={} for version in ("1","2","3"): p=app/"releases"/version (p/"vendor").mkdir(parents=True) (p/"public/build").mkdir(parents=True) (p/"vendor/autoload.php").write_text("