#!/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 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, resolve_image, tag_commit, version, ) from .release_publish import publish_hotfix_bundle else: from production_registry import ( API, REPO, SERVER, SERVICES, read_url, release_bundle, resolve_image, 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): directory = host.directory(tag) for name in SERVICES: 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(): for url in (PUBLIC + "/health/ready", PUBLIC + "/api/v1/visualization/geo/summary"): if not isinstance(json.loads(read_url(url)), dict): raise RuntimeError(f"Unexpected response from {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"] 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: 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) set_images(host, journal["old_images"]) rollout_services(host, previous, journal["old_images"]) point_current(host, previous) check_routes() if before: 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): images = {} 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 def deploy(host, release, previous, tag, images, commit): name, data, sha = release_bundle(release, tag) minimum = minimum_shell(data, tag) settings = env_settings(host) token = settings.get("CLIENT_UPDATE_PUBLISH_TOKEN", "").strip("'\u0022") if not token: raise RuntimeError("Production hotfix publisher credential is missing") old_images = {n: settings[k].strip("'\u0022") for n, k in SERVICES.items()} for service, ref in images.items(): docker("pull", "--platform", "linux/amd64", ref) if inspect(service)["Config"]["Image"] != old_images[service]: raise RuntimeError("Running image differs from the host configuration: " + service) stage_config(host, previous, tag) manifest = live_manifest_path() bundle_path = manifest.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), sha=sha, commit=commit, ), manifest, ) try: set_images(host, images) rollout_services(host, tag, images) check_routes() if data_containers() != original_stores: raise RuntimeError("PostgreSQL or Redis container identity changed") 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.get("body") or "", release_html_url=f"{SERVER}/{REPO}/releases/tag/{tag}", assets=[(archive, sha)], min_shell_version=minimum, ) check_hotfix(tag, sha) 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}", flush=True) 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() release = json.loads(read_url(API + "/releases/latest")) tag = release["tag_name"] if release.get("draft") or release.get("prerelease"): return try: candidate_version = version(tag) except ValueError: print(f"Ignoring release with a non-production tag: {tag!r}") return if candidate_version < version(previous): return if tag == previous and not check: print(f"{tag} is already active") return commit = tag_commit(tag) 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) if check: _, 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() check_hotfix(tag, sha) print(f"Verified {tag} at {commit}; active release {previous}", flush=True) return deploy(host, release, previous, tag, images, commit) 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}")