Files
dpl/scripts/fuc-xb-launch/run-final-import.py
T

80 lines
3.5 KiB
Python

#!/usr/bin/env python3
"""Back up, import and independently verify one sealed production cutover."""
import fcntl
import json
import os
from pathlib import Path
import re
import secrets
import shutil
import subprocess
import sys
HERE = Path(__file__).resolve().parent
PRIVATE = Path("/var/www/wwwroot/fuc-xb-test/private")
CURRENT = Path("/var/www/wwwroot/fuc-xb-test/current")
def command(args, environment, timeout):
result = subprocess.run(args, env=environment, capture_output=True, text=True, timeout=timeout)
if result.returncode:
diagnostic = result.stderr.strip().splitlines()
if diagnostic and len(diagnostic[-1]) <= 140:
raise RuntimeError(diagnostic[-1])
raise RuntimeError("A cutover command failed")
return json.loads(result.stdout.strip().splitlines()[-1])
def main():
if os.geteuid() != 0 or len(sys.argv) != 2 or not re.fullmatch(r"cutover-[0-9]{8}T[0-9]{6}Z", sys.argv[1]):
raise RuntimeError("Expected an exact root-owned cutover window")
window = sys.argv[1]
directory = PRIVATE / window
release = HERE.parents[1]
if directory.resolve() != directory or directory.stat().st_uid != 0 or directory.stat().st_mode & 0o077:
raise RuntimeError("Cutover directory is not private")
if release != CURRENT.resolve() or not re.fullmatch(r"[a-f0-9]{40}", release.name):
raise RuntimeError("Run the deployed cutover release")
env = {key: value for key, value in os.environ.items() if key in ("PATH", "LANG", "LC_ALL", "TZ")}
with (directory / "final-import.lock").open("a") as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
if not (directory / "old-fuc-full.json").exists():
command(["python3", str(HERE / "backup-legacy.py"), window], env, 100)
if not (directory / "import-ready.json").exists():
command(["python3", str(HERE / "prepare-final-import.py"), window], env, 160)
runtime = Path("/tmp/fuc-xb-cutover-" + secrets.token_hex(4))
runtime.mkdir(mode=0o700)
try:
for relative in ("storage/framework/cache/data", "storage/framework/sessions",
"storage/framework/views", "storage/logs"):
(runtime / relative).mkdir(parents=True)
env["FUC_CUTOVER_RUNTIME"] = str(runtime)
importer = ["php", str(HERE / "refresh-plan.php"), window]
committed = command(importer + ["cutover-commit"], env, 240)
verified = command(importer + ["cutover-verify"], env, 40)
if committed.get("committed_sha256", committed.get("readback_sha256")) != verified["readback_sha256"]:
raise RuntimeError("Independent target readback differs")
receipt = directory / "target-import-verified.json"
if receipt.exists():
if json.loads(receipt.read_text()) != verified:
raise RuntimeError("Final verification receipt changed")
else:
with receipt.open("x") as handle:
json.dump(verified, handle, indent=2)
handle.write("\n")
handle.flush()
os.fsync(handle.fileno())
print(json.dumps(verified))
finally:
shutil.rmtree(runtime)
if __name__ == "__main__":
os.umask(0o077)
try:
main()
except (OSError, ValueError, KeyError, RuntimeError, subprocess.SubprocessError) as failure:
sys.exit(str(failure) if isinstance(failure, RuntimeError) else type(failure).__name__)