#!/usr/bin/env python3 """Restore prior local application images from a verified cold backup.""" from __future__ import annotations import argparse import datetime as dt import json import os import re import subprocess import sys import tempfile from pathlib import Path ROOT = Path("/opt/akyldash/current") COMPOSE_FILE = ROOT / "deploy/production/compose.yaml" ENV_FILE = Path("/etc/akyldash/production.env") BACKUP_DIR = Path("/var/backups/akyldash") BACKUP_TOOL = Path("/usr/local/lib/akyldash/archive.py") STATE_FILE = Path("/opt/akyldash/release-state.json") JOURNAL_FILE = Path("/opt/akyldash/release-recovery.json") DEPLOYED_IMAGE_FILE = Path("/opt/akyldash/deployed-image.txt") APP_SERVICES = {"backend", "opensearch"} IMAGE_TAG_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:/-]*") IMAGE_DIGEST_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:/-]*@sha256:[0-9a-f]{64}") def is_digest_reference(reference: str) -> bool: return IMAGE_DIGEST_RE.fullmatch(reference) is not None def image_restore_plan( manifest: dict, configured: dict[str, str], expected_previous: dict[str, dict[str, str]] | None = None, ) -> dict[str, tuple[str, str]]: images = manifest.get("images") if not isinstance(images, dict) or not APP_SERVICES <= images.keys(): raise ValueError("backup has no previous backend and OpenSearch images") plan = {} for service in sorted(APP_SERVICES): image = images[service] if not isinstance(image, dict): raise ValueError(f"invalid image record for {service}") reference = image.get("configured") image_id = image.get("image_id") if expected_previous is None and reference != configured.get(service): raise ValueError(f"Compose image reference changed for {service}; refusing rollback") if not isinstance(reference, str) or not ( IMAGE_TAG_RE.fullmatch(reference) or is_digest_reference(reference) ): raise ValueError(f"invalid image reference for {service}") if not isinstance(image_id, str) or not re.fullmatch(r"sha256:[0-9a-f]{64}", image_id): raise ValueError(f"invalid previous image ID for {service}") if expected_previous is not None and expected_previous.get(service) != { "configured": reference, "image_id": image_id }: raise ValueError(f"backup does not match the pinned previous {service} release") plan[service] = (image_id, reference) return plan def verify_previous_images(plan: dict[str, tuple[str, str]]) -> None: for image_id, reference in plan.values(): try: actual = run(["docker", "image", "inspect", "--format", "{{.Id}}", image_id], capture=True) except subprocess.CalledProcessError as error: raise ValueError(f"previous image is unavailable: {image_id}") from error if actual != image_id: raise ValueError(f"previous image is unavailable: {image_id}") if is_digest_reference(reference): try: referenced_id = run( ["docker", "image", "inspect", "--format", "{{.Id}}", reference], capture=True ) except subprocess.CalledProcessError as error: raise ValueError(f"previous digest reference is unavailable: {reference}") from error if referenced_id != image_id: raise ValueError(f"previous digest reference does not match its recorded image: {reference}") def require_tag_rollback(plan: dict[str, tuple[str, str]]) -> None: if any(is_digest_reference(reference) for _image_id, reference in plan.values()): raise ValueError( "rollback of digest-pinned images is not supported safely; no services or image references were changed" ) def tag_previous_images(plan: dict[str, tuple[str, str]]) -> None: for image_id, reference in plan.values(): if not is_digest_reference(reference): run(["docker", "image", "tag", image_id, reference]) def run(command: list[str], *, capture: bool = False) -> str: result = subprocess.run(command, check=True, text=True, capture_output=capture) return result.stdout.strip() if capture else "" def compose(*args: str, capture: bool = False) -> str: return run( ["docker", "compose", "--env-file", str(ENV_FILE), "-f", str(COMPOSE_FILE), *args], capture=capture, ) def record_backend_image() -> None: container = compose("ps", "--quiet", "backend", capture=True) if not container: raise ValueError("backend container is missing after rollback") image_id = run(["docker", "inspect", "--format", "{{.Image}}", container], capture=True) if not re.fullmatch(r"sha256:[0-9a-f]{64}", image_id): raise ValueError("backend returned an invalid image ID") target = DEPLOYED_IMAGE_FILE with tempfile.NamedTemporaryFile(dir=target.parent, prefix=".deployed-image-", delete=False) as stream: temporary = Path(stream.name) stream.write(f"{image_id}\n".encode("ascii")) os.chmod(temporary, 0o600) try: os.replace(temporary, target) directory_fd = os.open(target.parent, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)) try: os.fsync(directory_fd) finally: os.close(directory_fd) finally: temporary.unlink(missing_ok=True) def running_image_ids() -> dict[str, str]: result: dict[str, str] = {} for service in sorted(APP_SERVICES): container = compose("ps", "--all", "--quiet", service, capture=True) if not container or "\n" in container: raise ValueError(f"expected exactly one running {service} container") inspection = run( ["docker", "inspect", "--format", "{{.State.Running}}\t{{.Image}}", container], capture=True ) running, separator, image_id = inspection.partition("\t") if not separator or running != "true" or not re.fullmatch(r"sha256:[0-9a-f]{64}", image_id): raise ValueError(f"{service} container is not running with a valid image ID") result[service] = image_id return result def require_running_image_ids(expected: dict[str, str], actual: dict[str, str], label: str) -> None: if actual != expected: raise ValueError(f"running image IDs do not match the {label}") def rollback(backup: Path, data_compatible: bool) -> None: sys.path.insert(0, str(BACKUP_TOOL.parent)) from deployment_lock import deployment_lock with deployment_lock(): _rollback_locked(backup, data_compatible) def _rollback_locked(backup: Path, data_compatible: bool) -> None: if JOURNAL_FILE.exists() or JOURNAL_FILE.is_symlink(): raise ValueError(f"recovery journal exists at {JOURNAL_FILE}; resolve it before rollback") if not data_compatible: raise ValueError("confirm data compatibility with --data-compatible before rollback") if not backup.is_file() or backup.is_symlink() or backup.resolve().parent != BACKUP_DIR.resolve(): raise ValueError(f"backup must be a regular file directly under {BACKUP_DIR}") if backup.stat().st_uid != 0 or backup.stat().st_mode & 0o777 != 0o600: raise ValueError("rollback backup must be root-owned mode 0600") checksum = Path(f"{backup}.sha256") if checksum.is_symlink() or not checksum.is_file() or checksum.stat().st_uid != 0 or checksum.stat().st_mode & 0o777 != 0o600: raise ValueError("rollback checksum sidecar must be root-owned mode 0600") sys.path.insert(0, str(BACKUP_TOOL.parent)) from archive import digest, verify_archive manifest = verify_archive(backup) deployment_files = { relative: digest(ROOT / relative) for relative in ("deploy/production/compose.yaml", "deploy/production/Caddyfile") } if deployment_files != manifest.get("deployment_files"): raise ValueError("Compose or Caddyfile changed since this backup; restore the matching Git revision first") rendered = json.loads(compose("config", "--format", "json", capture=True)) configured = {service: rendered["services"][service]["image"] for service in APP_SERVICES} current_running_ids = running_image_ids() state = None expected_previous = None if STATE_FILE.exists() or STATE_FILE.is_symlink(): from release_state import read_json as read_release_state, validate_state state = validate_state(read_release_state(STATE_FILE)) current_refs = {service: state["current"][service]["configured"] for service in APP_SERVICES} if current_refs != configured: raise ValueError("release state does not match current Compose image references") expected_current = {service: state["current"][service]["image_id"] for service in APP_SERVICES} try: require_running_image_ids(expected_current, current_running_ids, "pinned release state") except ValueError as error: raise ValueError(f"current deployment does not match pinned release state: {error}") from error expected_previous = state["previous"] plan = image_restore_plan(manifest, configured, expected_previous) verify_previous_images(plan) if expected_previous is None: require_tag_rollback(plan) backup_name = f"akyldash-pre-rollback-{dt.datetime.now(dt.timezone.utc):%Y%m%dT%H%M%SZ}.tar.gz" backup_output = BACKUP_DIR / backup_name before = {"BACKEND_IMAGE": configured["backend"], "OPENSEARCH_IMAGE": configured["opensearch"]} after = {"BACKEND_IMAGE": plan["backend"][1], "OPENSEARCH_IMAGE": plan["opensearch"][1]} try: compose("stop") run( [ "python3", str(BACKUP_TOOL), "create", "--compose-file", str(COMPOSE_FILE), "--env-file", str(ENV_FILE), "--output", str(backup_output), ] ) run(["python3", str(BACKUP_TOOL), "verify", str(backup_output)]) except Exception as error: from release_state import write_json_atomic journal = { "schema_version": 1, "status": "rollback-backup-failed", "backup": str(backup), "error_type": type(error).__name__, "target": before, } try: compose("up", "--detach", "--no-build", "--wait", "--wait-timeout", "300") journal["recovery"] = "current release restarted; verify service health" except Exception as recovery_error: journal["recovery"] = f"manual recovery required ({type(recovery_error).__name__})" write_json_atomic(JOURNAL_FILE, journal) raise ValueError(f"rollback preflight failed; recovery journal preserved at {JOURNAL_FILE}") from error journal = { "schema_version": 1, "status": "rollback-prepared", "backup": str(backup), "previous": {service: {"configured": plan[service][1], "image_id": plan[service][0]} for service in APP_SERVICES}, "target": {service: {"configured": configured[service]} for service in APP_SERVICES}, } if state is not None: from release_state import write_json_atomic write_json_atomic(JOURNAL_FILE, journal) state_written = False try: tag_previous_images(plan) if state is not None: from release_refs import replace_images replace_images(ENV_FILE, before, after) journal["status"] = "rollback-references-switched" write_json_atomic(JOURNAL_FILE, journal) compose("up", "--detach", "--no-build", "--wait", "--wait-timeout", "300") expected_restored = {service: plan[service][0] for service in APP_SERVICES} require_running_image_ids(expected_restored, running_image_ids(), "rollback plan") run( [ "curl", "--fail", "--silent", "--show-error", "--resolve", "akyldash.kg:443:127.0.0.1", "https://akyldash.kg/review", "--output", "/dev/null", ] ) record_backend_image() if state is not None: from release_state import write_json_atomic restored = { service: {"configured": plan[service][1], "image_id": plan[service][0]} for service in APP_SERVICES } write_json_atomic(STATE_FILE, { "schema_version": 1, "commit": "rollback", "manifest_sha256": "rollback", "current": restored, "previous": state["current"], }) state_written = True JOURNAL_FILE.unlink(missing_ok=True) except Exception as error: if state is not None: from release_refs import read_images, replace_images from release_state import write_json_atomic journal["status"] = "rollback-failed" journal["error_type"] = type(error).__name__ if state_written: journal["status"] = "rollback-active-journal-cleanup-needed" journal["recovery"] = "rollback refs, release state, and health check completed; verify host and resolve journal" write_json_atomic(JOURNAL_FILE, journal) raise ValueError(f"rollback is active; recovery journal preserved at {JOURNAL_FILE}") from error try: current_text, current_env = read_images(ENV_FILE) del current_text active = {"BACKEND_IMAGE": current_env["BACKEND_IMAGE"], "OPENSEARCH_IMAGE": current_env["OPENSEARCH_IMAGE"]} if active == after: replace_images(ENV_FILE, after, before) elif active != before: raise ValueError("image references match neither the rolled-back nor pre-rollback release") _, verified_env = read_images(ENV_FILE) if {"BACKEND_IMAGE": verified_env["BACKEND_IMAGE"], "OPENSEARCH_IMAGE": verified_env["OPENSEARCH_IMAGE"]} != before: raise ValueError("pre-rollback image references could not be verified") compose("up", "--detach", "--no-build", "--wait", "--wait-timeout", "300") require_running_image_ids(expected_current, running_image_ids(), "previous release state") record_backend_image() write_json_atomic(STATE_FILE, state) journal["recovery"] = "current release references restored; verify service health" except Exception as recovery_error: journal["recovery"] = f"manual recovery required ({type(recovery_error).__name__})" write_json_atomic(JOURNAL_FILE, journal) else: from release_state import write_json_atomic journal["status"] = "rollback-failed" journal["error_type"] = type(error).__name__ try: compose("up", "--detach", "--no-build", "--wait", "--wait-timeout", "300") require_running_image_ids(current_running_ids, running_image_ids(), "pre-rollback deployment") record_backend_image() journal["recovery"] = "legacy release restarted; verify service health" except Exception as recovery_error: journal["recovery"] = f"manual recovery required ({type(recovery_error).__name__})" write_json_atomic(JOURNAL_FILE, journal) raise print(f"PASS application images restored from {backup}; pre-rollback backup: {backup_output}") def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("backup", type=Path) parser.add_argument("--data-compatible", action="store_true") args = parser.parse_args() try: if os.geteuid() != 0: raise ValueError("rollback must run through the restricted root helper") rollback(args.backup, args.data_compatible) except Exception as error: print(f"ERROR: {error}", file=sys.stderr) return 1 return 0 if __name__ == "__main__": raise SystemExit(main())