#!/usr/bin/env python3 """Reconcile published Planet releases with the existing lightweight production Compose stack.""" from __future__ import annotations import argparse import fcntl import hashlib import io import json import os import re import shutil import subprocess import sys import tarfile import tempfile import time from dataclasses import dataclass from pathlib import Path if __package__: from .production_registry import ( API, REPO, SERVER, SERVICES, read_url, release_bundle, release_by_tag, release_manifest, resolve_image, resolve_release_manifest_oci, resolve_service_ref, tag_commit, version, ) from .release_publish import publish_hotfix_bundle else: from production_registry import ( API, REPO, SERVER, SERVICES, read_url, release_bundle, release_by_tag, release_manifest, resolve_image, resolve_release_manifest_oci, resolve_service_ref, tag_commit, version, ) from release_publish import publish_hotfix_bundle PUBLIC = "https://rclaw.top" ADMIN = "https://admin.rclaw.top" PROJECT = "planet-production" HOST_FILES = ( "compose.yaml", "compose.pilot.yaml", "planet-https.conf", "planet-api-locations.conf", ) @dataclass(frozen=True) class Host: root: Path = Path("/opt/planet") env: Path = Path("/etc/planet/deploy.env") state: Path = Path("/var/lib/planet-release-deploy") def directory(self, tag): version(tag) path = self.root / "releases" / tag if path.is_symlink(): raise ValueError("Release directories must not be symbolic links") return path def current(self): path = (self.root / "current").resolve(strict=True) if path != self.directory(path.name): raise ValueError("Unexpected active release directory") return path.name def sync_directory(path): fd = os.open(path, os.O_DIRECTORY | os.O_RDONLY) try: os.fsync(fd) finally: os.close(fd) def atomic_file(path, data, mode=0o600): fd, name = tempfile.mkstemp(prefix="." + path.name, dir=path.parent) try: with os.fdopen(fd, "wb") as out: os.fchmod(out.fileno(), mode) out.write(data) out.flush() os.fsync(out.fileno()) os.replace(name, path) sync_directory(path.parent) finally: Path(name).unlink(missing_ok=True) def point_current(host, tag): link = host.root / "current" with tempfile.TemporaryDirectory(dir=host.root) as temp: candidate = Path(temp) / "current" candidate.symlink_to(host.directory(tag)) os.replace(candidate, link) sync_directory(host.root) def env_settings(host): return dict( line.split("=", 1) for line in host.env.read_text().splitlines() if "=" in line and not line.lstrip().startswith("#") ) def set_images(host, images): values = {SERVICES[service]: images[service] for service in SERVICES} found = set() lines = host.env.read_text().splitlines(keepends=True) for index, line in enumerate(lines): key = line.partition("=")[0] if key in values: found.add(key) lines[index] = f"{key}={values[key]}\n" if missing := values.keys() - found: raise ValueError("Missing production image settings: " + ", ".join(sorted(missing))) atomic_file(host.env, "".join(lines).encode()) def docker(*args): return subprocess.check_output(["docker", *map(str, args)], text=True).strip() def container_name(service): return "planet_deploy_" + service def inspect(service): return json.loads(docker("inspect", container_name(service)))[0] def data_containers(): return {name: inspect(name)["Id"] for name in ("postgres", "redis")} def live_manifest_path(): mounts = inspect("backend")["Mounts"] [mount] = [m for m in mounts if m["Destination"] == "/app/backend/data/client-updates"] if mount.get("Name") != PROJECT + "_client_updates_data" or mount["Type"] != "volume": raise RuntimeError("Expected the persistent production client update volume") return Path(mount["Source"]) / "manifest.json" def stage_config(host, previous, tag): source, target = host.directory(previous), host.directory(tag) target.mkdir(exist_ok=True) sync_directory(target.parent) for name in HOST_FILES: original, dest = source / name, target / name if dest.exists(): if dest.is_symlink() or dest.read_bytes() != original.read_bytes(): raise RuntimeError(f"Existing host configuration differs: {dest}") else: atomic_file(dest, original.read_bytes(), original.stat().st_mode & 0o777) return target def rollout_services(host, tag, images, services=None): directory = host.directory(tag) targets = tuple(SERVICES) if services is None else tuple(services) for name in targets: print(f"Starting {name} from {images[name]}", flush=True) docker( "compose", "--project-name", PROJECT, "--env-file", host.env, "-f", directory / "compose.yaml", "-f", directory / "compose.pilot.yaml", "up", "-d", "--no-deps", "--no-build", "--pull", "never", name, ) deadline = time.monotonic() + 100 while True: container = inspect(name) state = container["State"] if ( container["Config"]["Image"] == images[name] and state["Status"] == "running" and state.get("Health", {}).get("Status") == "healthy" ): break if ( state["Status"] in ("exited", "dead") or state.get("OOMKilled") or time.monotonic() >= deadline ): raise RuntimeError(f"{name} did not become healthy") time.sleep(2) def check_routes(api_key: str | None = None): for url in (PUBLIC + "/health/ready", PUBLIC + "/api/v1/client/update-manifest"): if not isinstance(json.loads(read_url(url)), dict): raise RuntimeError(f"Unexpected response from {url}") resolved_key = ( api_key if api_key is not None else os.environ.get("PLANET_DEPLOY_API_KEY", "") ).strip() if resolved_key: summary_url = PUBLIC + "/api/v1/visualization/geo/summary" if not isinstance( json.loads(read_url(summary_url, headers={"X-API-Key": resolved_key})), dict ): raise RuntimeError(f"Unexpected response from {summary_url}") if b" 8192: raise ValueError("Invalid hotfix metadata") meta = json.load(archive.extractfile(member)) if meta.get("version") != tag[1:]: raise ValueError("Hotfix metadata version differs from the release") minimum = meta.get("minShellVersion") or meta["shellVersion"] if version("v" + minimum) > version(tag): raise ValueError("Hotfix requires a newer shell than the release") return minimum def backup_database(target): with target.open("xb") as out: subprocess.run( [ "docker", "exec", container_name("postgres"), "sh", "-ec", 'exec pg_dump -Fc -Z 1 -U "$POSTGRES_USER" "$POSTGRES_DB"', ], stdout=out, check=True, ) os.fsync(out.fileno()) with target.open("rb") as source: catalog = subprocess.check_output( ["docker", "exec", "-i", container_name("postgres"), "pg_restore", "-l"], stdin=source ) if b"TABLE DATA" not in catalog: raise RuntimeError("Pre-deployment database backup failed verification") def save_journal(host, journal, manifest): with tempfile.TemporaryDirectory(dir=host.state) as scratch: directory = Path(scratch) / "transaction" directory.mkdir() atomic_file(directory / "release.json", json.dumps(journal).encode()) if manifest.exists(): atomic_file(directory / "previous-manifest.json", manifest.read_bytes()) backup_database(directory / "database.dump") sync_directory(directory) os.rename(directory, host.state / "pending") sync_directory(host.state) def finish_journal(host, name): previous = host.state / name if previous.exists(): shutil.rmtree(previous) os.rename(host.state / "pending", previous) sync_directory(host.state) def rollback(host): pending = host.state / "pending" journal = json.loads((pending / "release.json").read_text()) previous = journal["previous"] client_mode = journal.get("client_mode", "full") print(f"Restoring {previous} after interrupted or unsuccessful {journal['tag']}", flush=True) manifest = Path(journal["manifest"]) old = pending / "previous-manifest.json" before = old.read_bytes() if old.exists() else None current = manifest.read_bytes() if manifest.exists() else None if current != before: if client_mode == "none": raise RuntimeError( "Hotfix manifest changed independently; preserved the transaction for review" ) bundle = json.loads(current or b"{}").get("bundle") or {} if bundle.get("version") != journal["tag"][1:] or bundle.get("sha256") != journal["sha"]: raise RuntimeError( "Hotfix manifest changed independently; preserved the transaction for review" ) if before is None: manifest.unlink() sync_directory(manifest.parent) else: atomic_file(manifest, before, 0o644) old_images = journal["old_images"] rolled_services = [ name for name in SERVICES if inspect(name)["Config"]["Image"] != old_images[name] ] set_images(host, old_images) if not rolled_services or set(rolled_services) == set(SERVICES): rollout_services(host, previous, old_images) else: rollout_services(host, previous, old_images, services=rolled_services) point_current(host, previous) check_routes() if before and client_mode != "none": old_manifest = json.loads(before) bundle = old_manifest.get("bundle") if bundle: check_hotfix( "v" + bundle["version"], bundle["sha256"], old_manifest.get("shell", {}).get("version"), ) finish_journal(host, "last-failed") print(f"Rollback to {previous} verified", flush=True) def resolved_images(tag, commit, manifest=None): images = {} if manifest is None: for service in SERVICES: ref = resolve_image(service, tag, commit) if not ref: raise RuntimeError(f"Waiting for the published {service}:{tag} image") images[service] = ref return images changed_services = set(manifest.get("changed_services") or []) for service in SERVICES: pinned = manifest["services"][service] if service in changed_services: ref = resolve_image(service, tag, commit) if not ref: raise RuntimeError(f"Waiting for the published {service}:{tag} image") if ref != pinned: raise ValueError(f"{service}:{tag} digest does not match release manifest") images[service] = ref else: images[service] = resolve_service_ref(service, pinned) return images def deploy(host, release, previous, tag, images, commit, *, manifest=None): client_mode = (manifest.get("client") or {}).get("mode", "full") if manifest else "full" client_info = (manifest or {}).get("client") or {} if client_mode == "none": name, data, sha = None, None, None minimum = None shell_version = client_info.get("shell_version") else: name, data, sha = release_bundle(release, tag) minimum = client_info.get("min_shell_version") or minimum_shell(data, tag) shell_version = client_info.get("shell_version") or tag[1:] settings = env_settings(host) old_images = {n: settings[k].strip("'\u0022") for n, k in SERVICES.items()} changed_services = [service for service in SERVICES if images[service] != old_images[service]] token = settings.get("CLIENT_UPDATE_PUBLISH_TOKEN", "").strip("'\u0022") if client_mode != "none" and not token: raise RuntimeError("Production hotfix publisher credential is missing") for service in changed_services: docker("pull", "--platform", "linux/amd64", images[service]) for service in SERVICES: if inspect(service)["Config"]["Image"] != old_images[service]: raise RuntimeError("Running image differs from the host configuration: " + service) stage_config(host, previous, tag) manifest_file = live_manifest_path() if client_mode != "none": bundle_path = manifest_file.parent / name if bundle_path.exists() and hashlib.sha256(bundle_path.read_bytes()).hexdigest() != sha: raise RuntimeError("Existing versioned hotfix file has different contents") original_stores = data_containers() save_journal( host, dict( tag=tag, previous=previous, old_images=old_images, manifest=str(manifest_file), sha=sha, client_mode=client_mode, commit=commit, ), manifest_file, ) try: if changed_services: set_images(host, images) if set(changed_services) == set(SERVICES): rollout_services(host, tag, images) else: rollout_services(host, tag, images, services=changed_services) check_routes() if data_containers() != original_stores: raise RuntimeError("PostgreSQL or Redis container identity changed") if client_mode != "none": with tempfile.TemporaryDirectory(dir=host.state) as tmp: archive = Path(tmp) / name archive.write_bytes(data) publish_hotfix_bundle( publish_url=PUBLIC, publish_token=token, tag=tag, notes=(release or {}).get("body") or "", release_html_url=f"{SERVER}/{REPO}/releases/tag/v{shell_version}", assets=[(archive, sha)], min_shell_version=minimum, shell_version=shell_version, ) check_hotfix(tag, sha, shell_version=shell_version) point_current(host, tag) finish_journal(host, "last-success") except Exception as exc: print(f"Deploying {tag} failed: {exc}", file=sys.stderr, flush=True) rollback(host) raise print( f"Deployed {tag} at {commit} (services={','.join(changed_services) or 'none'}, client={client_mode})", flush=True, ) def discover_latest_release(previous, *, check=False): """Discover the highest deliverable stable release from Gitea tags and OCI/Release metadata.""" payload = json.loads(read_url(API + "/tags?limit=30")) if isinstance(payload, dict) and "tag_name" in payload: tag = payload["tag_name"] if payload.get("draft") or payload.get("prerelease"): return None try: candidate_version = version(tag) except ValueError: print(f"Ignoring release with a non-production tag: {tag!r}") return None if candidate_version < version(previous): return None if tag == previous and not check: return tag, None, None, payload commit = tag_commit(tag) manifest = release_manifest(payload, tag) return tag, commit, manifest, payload if not isinstance(payload, list): raise ValueError("Gitea returned unexpected tag listing payload") min_ver = version(previous) candidates = [] for entry in payload: if not isinstance(entry, dict): continue name = entry.get("name") if not isinstance(name, str): continue try: ver = version(name) except ValueError: continue if ver >= min_ver: sha = (entry.get("commit") or {}).get("sha") candidates.append((ver, name, sha)) candidates.sort(reverse=True) for _, tag, sha in candidates: commit = sha if (isinstance(sha, str) and re.fullmatch("[0-9a-f]{40,64}", sha)) else tag_commit(tag) manifest = resolve_release_manifest_oci(tag, commit) if manifest is not None: if manifest["client"]["mode"] == "none": return tag, commit, manifest, None release = release_by_tag(tag) if release is not None: return tag, commit, manifest, release continue release = release_by_tag(tag) if release is not None: return tag, commit, release_manifest(release, tag), release return None def reconcile(host, *, check=False, retry=False): if (host.state / "pending").exists(): if check: raise RuntimeError("A previous rollout is pending recovery") rollback(host) previous = host.current() discovered = discover_latest_release(previous, check=check) if discovered is None: return tag, commit, manifest, release = discovered if tag == previous and not check: print(f"{tag} is already active") return failed = host.state / "last-failed/release.json" if ( tag != previous and failed.is_file() and json.loads(failed.read_text())["tag"] == tag and not retry ): print(f"{tag} previously rolled back; waiting for a new release or --retry", flush=True) return images = resolved_images(tag, commit, manifest=manifest) if check: client_mode = (manifest.get("client") or {}).get("mode", "full") if manifest else "full" sha = None shell_version = (manifest or {}).get("client", {}).get("shell_version") if manifest else tag[1:] if client_mode != "none": _, data, sha = release_bundle(release, tag) minimum_shell(data, tag) if tag == previous: for name, ref in images.items(): container = inspect(name) if ( container["Config"]["Image"] != ref or container["State"]["Health"]["Status"] != "healthy" ): raise RuntimeError("Active service differs from the release: " + name) check_routes() if client_mode != "none": check_hotfix(tag, sha, shell_version=shell_version) print(f"Verified {tag} at {commit}; active release {previous}", flush=True) return deploy(host, release, previous, tag, images, commit, manifest=manifest) def main(): parser = argparse.ArgumentParser(description=__doc__) group = parser.add_mutually_exclusive_group() group.add_argument( "--check", action="store_true", help="Verify the release without switching production" ) group.add_argument( "--retry", action="store_true", help="Retry the latest release after a verified rollback" ) args = parser.parse_args() os.umask(0o077) host = Host() host.state.mkdir(mode=0o700, parents=True, exist_ok=True) with (host.state / "lock").open("a") as lock: try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: print("Another production release check is running") return reconcile(host, check=args.check, retry=args.retry) if __name__ == "__main__": try: main() except ( RuntimeError, ValueError, KeyError, OSError, tarfile.TarError, subprocess.SubprocessError, ) as exc: sys.exit(f"Production release check failed: {exc}")