ci: deploy published Planet releases by image digest
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s

This commit is contained in:
linkong committed 2026-11-24 17:27:54 +08:00
1 parent e53c3af355
commit 1e9508f2f1
12 files changed
+1296 -51

No files matched your search

+1
View File
@@ -24,6 +24,7 @@ main() {
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_docker_proxy.py
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_docker_mirror.py
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_database_startup.py
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_production_release.py
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_windows_restart.py
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_error_diagnostics.py
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_tool_resolution.py
+239
View File
@@ -0,0 +1,239 @@
import hashlib
import io
import json
import sys
import tarfile
import tempfile
import unittest
from contextlib import ExitStack
from pathlib import Path
from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import production_deploy as deploy
import production_registry as registry
import production_release as publisher
def hotfix(tag):
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as archive:
for name, data in {
"bundle-meta.json": json.dumps({"version": tag[1:], "shellVersion": tag[1:]}).encode(),
"index.html": b"<html>release test</html>",
}.items():
member = tarfile.TarInfo(name)
member.size = len(data)
archive.addfile(member, io.BytesIO(data))
return buf.getvalue()
class TransactionTests(unittest.TestCase):
old, tag = "v1.0.0", "v1.1.0"
def setUp(self):
self.stack = ExitStack()
self.addCleanup(self.stack.close)
base = Path(self.stack.enter_context(tempfile.TemporaryDirectory()))
self.host = deploy.Host(base / "host", base / "settings", base / "state")
self.host.state.mkdir()
folder = self.host.directory(self.old)
folder.mkdir(parents=True)
for name in deploy.HOST_FILES:
(folder / name).write_text("host-managed")
deploy.point_current(self.host, self.old)
self.old_refs = {key: "previous-" + key for key in registry.SERVICES}
self.new_refs = {key: "candidate-" + key for key in registry.SERVICES}
lines = [f"{key}={self.old_refs[name]}" for name, key in registry.SERVICES.items()]
self.host.env.write_text(
"\n".join(lines + ["LIMIT=500m", "CLIENT_UPDATE_PUBLISH_TOKEN=fixture"]) + "\n"
)
self.running = self.old_refs.copy()
self.manifest = base / "manifest.json"
self.original = b'{"bundle":{"version":"1.0.0","sha256":"previous"}}'
self.manifest.write_bytes(self.original)
self.calls = []
self.data = hotfix(self.tag)
self.sha = hashlib.sha256(self.data).hexdigest()
self.release = {"tag_name": self.tag, "draft": False, "prerelease": False}
self.mock("read_url", return_value=json.dumps(self.release).encode())
self.mock("tag_commit", return_value="f" * 40)
self.images = self.mock("resolved_images", return_value=self.new_refs)
self.mock("release_bundle", return_value=("bundle.tar.gz", self.data, self.sha))
self.mock("inspect", side_effect=lambda name: {"Config": {"Image": self.running[name]}})
self.mock("data_containers", return_value={"postgres": "same-db", "redis": "same-redis"})
self.mock("live_manifest_path", return_value=self.manifest)
self.mock("docker", side_effect=lambda *args: self.calls.append(args[0]))
self.mock("backup_database", side_effect=lambda p: p.write_bytes(b"verified backup"))
self.mock("check_routes", side_effect=lambda: self.calls.append("health"))
self.service = self.mock("rollout_services", side_effect=self.roll)
self.publish = self.mock("publish_hotfix_bundle", side_effect=self.publish_data)
self.verify = self.mock("check_hotfix", side_effect=self.verify_data)
def mock(self, name, **kwargs):
return self.stack.enter_context(patch.object(deploy, name, **kwargs))
def roll(self, host, tag, refs):
self.calls.append(tag)
self.running.update(refs)
def publish_data(self, **kwargs):
self.calls.append("hotfix")
archive, digest = kwargs["assets"][0]
self.assertEqual(hashlib.sha256(archive.read_bytes()).hexdigest(), digest)
self.manifest.write_text(
json.dumps({"bundle": {"version": kwargs["tag"][1:], "sha256": digest}})
)
def verify_data(self, tag, digest, shell_version=None):
self.assertEqual(
json.loads(self.manifest.read_bytes())["bundle"], {"version": tag[1:], "sha256": digest}
)
def test_new_release_and_duplicate_tick(self):
deploy.reconcile(self.host)
self.assertEqual(self.calls, ["pull"] * 3 + [self.tag, "health", "hotfix"])
self.assertEqual(self.host.current(), self.tag)
self.assertEqual(self.running, self.new_refs)
self.assertIn("LIMIT=500m\n", self.host.env.read_text())
self.assertTrue((self.host.state / "last-success/database.dump").is_file())
deploy.reconcile(self.host)
self.assertEqual(self.service.call_count, 1)
def test_manifest_failure_restores_previous_release_and_parks_it(self):
def verify(tag, sha, shell_version=None):
if tag == self.tag:
raise RuntimeError("independent public download failed")
self.verify_data(tag, sha)
self.verify.side_effect = verify
with self.assertRaisesRegex(RuntimeError, "download failed"):
deploy.reconcile(self.host)
self.assertEqual(self.host.current(), self.old)
self.assertEqual(self.running, self.old_refs)
self.assertEqual(self.manifest.read_bytes(), self.original)
self.assertTrue((self.host.state / "last-failed/database.dump").is_file())
deploy.reconcile(self.host)
self.assertEqual(self.service.call_count, 2)
self.verify.side_effect = self.verify_data
deploy.reconcile(self.host, retry=True)
self.assertEqual(self.host.current(), self.tag)
def test_interrupted_rollout_recovers_before_processing_latest(self):
self.service.side_effect = KeyboardInterrupt()
with self.assertRaises(KeyboardInterrupt):
deploy.reconcile(self.host)
self.assertTrue((self.host.state / "pending/release.json").is_file())
self.service.side_effect = self.roll
deploy.reconcile(self.host)
self.assertFalse((self.host.state / "pending").exists())
self.assertEqual(self.host.current(), self.old)
self.assertEqual(self.running, self.old_refs)
self.assertEqual(self.calls.count(self.old), 1)
self.publish.assert_not_called()
def test_incomplete_publication_does_not_change_production(self):
self.images.side_effect = RuntimeError("image is missing")
env = self.host.env.read_bytes()
with self.assertRaisesRegex(RuntimeError, "image is missing"):
deploy.reconcile(self.host)
self.assertEqual(self.host.env.read_bytes(), env)
self.assertFalse((self.host.state / "pending").exists())
self.service.assert_not_called()
def test_drafts_prereleases_and_older_versions_never_roll_out(self):
for tag, draft, pre in [
(self.tag, True, False),
(self.tag, False, True),
("v0.9.9", False, False),
]:
data = json.dumps({"tag_name": tag, "draft": draft, "prerelease": pre}).encode()
with patch.object(deploy, "read_url", return_value=data):
deploy.reconcile(self.host)
self.images.assert_not_called()
class ImageTests(unittest.TestCase):
def test_interrupted_upload_reuses_identical_local_artifacts(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
supplied = root / "supplied"
supplied.mkdir()
cache = root / "cache"
tag = "v1.2.3"
for name in (
"Planet Earth-1.2.3-win.zip",
"Planet Earth-1.2.3-mac.zip",
"planet_1.2.3.deb",
):
(supplied / name).write_bytes(b"original")
(supplied / "planet-earth-bundle-1.2.3.tar.gz").write_bytes(hotfix(tag))
suffixes = (".zip", ".deb", ".tar.gz")
publisher.cached_packages(root, supplied, cache, tag, suffixes)
original = "Planet Earth-1.2.3-win.zip"
(supplied / original).write_bytes(b"later build")
publisher.cached_packages(root, supplied, cache, tag, suffixes)
self.assertEqual((cache / original).read_bytes(), b"original")
(cache / original).write_bytes(b"corrupt cache")
with self.assertRaisesRegex(ValueError, "differ"):
publisher.cached_packages(root, supplied, cache, tag, suffixes)
def test_builds_only_missing_service_from_tag_and_verifies_after_push(self):
with (
tempfile.TemporaryDirectory() as temp,
patch.object(publisher, "resolve_image") as resolve,
patch.object(publisher.subprocess, "run") as run,
):
resolve.side_effect = ["provider-pin", "backend-pin", None, "admin-pin"]
publisher.ensure_images(Path(temp), "v1.2.3", "a" * 40)
args = run.call_args.args[0]
self.assertIn("linux/amd64", args)
self.assertIn("PLANET_FRONTEND_TARGET=admin", args)
self.assertIn("org.opencontainers.image.revision=" + "a" * 40, args)
self.assertTrue(any("push=true" in x and "admin:v1.2.3" in x for x in args))
run.assert_called_once()
def test_registry_verifies_actual_config_and_commit_before_accepting_digest(self):
commit = "a" * 40
cfg = json.dumps(
{
"os": "linux",
"architecture": "amd64",
"config": {
"Labels": {
"org.opencontainers.image.revision": commit,
"planet.frontend.target": "admin",
}
},
}
).encode()
raw = json.dumps({"config": {"digest": registry.digest(cfg)}}).encode()
with patch.object(registry, "read_url", side_effect=[b'{"token":"read"}', raw, cfg]):
pin = registry.resolve_image("admin", "v1.2.3", commit)
self.assertTrue(pin.endswith("@" + registry.digest(raw)))
for bad_commit, bad_cfg in [("b" * 40, cfg), (commit, cfg + b" ")]:
with (
patch.object(registry, "read_url", side_effect=[b'{"token":"read"}', raw, bad_cfg]),
self.assertRaises(ValueError),
):
registry.resolve_image("admin", "v1.2.3", bad_commit)
def test_corrupt_bundle_and_duplicate_checksum_are_rejected(self):
tag = "v1.2.3"
name = "planet-earth-bundle-1.2.3.tar.gz"
data = hotfix(tag)
expected = f"{hashlib.sha256(data).hexdigest()} {name}\n".encode()
release = {
"tag_name": tag,
"assets": [{"name": name, "size": len(data)}, {"name": "SHA256SUMS.txt", "size": 99}],
}
for sums, content in [(expected + expected, data), (expected, b"x" * len(data))]:
with (
patch.object(registry, "read_url", side_effect=[sums, content]),
self.assertRaises(ValueError),
):
registry.release_bundle(release, tag)
if __name__ == "__main__":
unittest.main()
+479
View File
@@ -0,0 +1,479 @@
#!/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"<html" not in read_url(ADMIN + "/earth").lower():
raise RuntimeError("Admin Earth entry did not return HTML")
def check_hotfix(tag, sha, shell_version=None):
manifest = json.loads(read_url(PUBLIC + "/api/v1/client/update-manifest"))
bundle = manifest.get("bundle") or {}
path = f"/api/v1/client/updates/files/planet-earth-bundle-{tag[1:]}.tar.gz"
if (
manifest.get("shell", {}).get("version") != (shell_version or tag[1:])
or bundle.get("version") != tag[1:]
or bundle.get("sha256") != sha
or bundle.get("url") != path
):
raise RuntimeError("Live hotfix manifest does not match the release")
if hashlib.sha256(read_url(PUBLIC + path, limit=32 * 1024 * 1024)).hexdigest() != sha:
raise RuntimeError("Live hotfix download failed SHA-256 verification")
def minimum_shell(data, tag):
with tarfile.open(fileobj=io.BytesIO(data), mode="r:gz") as archive:
member = archive.getmember("bundle-meta.json")
if not member.isfile() or member.size > 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}")
+155
View File
@@ -0,0 +1,155 @@
"""Read the public Planet release and immutable linux/amd64 images from Gitea."""
from __future__ import annotations
import hashlib
import json
import re
import time
import urllib.error
import urllib.parse
import urllib.request
SERVER = "https://gitea.rclaw.top"
REPO = "linkong/planet"
REGISTRY = urllib.parse.urlsplit(SERVER).netloc
API = f"{SERVER}/api/v1/repos/{REPO}"
SERVICES = {
"aiprovider": "AI_PROVIDER_IMAGE_NAME",
"backend": "BACKEND_IMAGE_NAME",
"admin": "ADMIN_IMAGE_NAME",
}
MANIFEST_TYPES = ", ".join(
(
"application/vnd.oci.image.index.v1+json",
"application/vnd.oci.image.manifest.v1+json",
"application/vnd.docker.distribution.manifest.list.v2+json",
"application/vnd.docker.distribution.manifest.v2+json",
)
)
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *args):
return None
def read_url(url, *, headers=None, limit=2 * 1024 * 1024):
"""Bound a release download and keep authorization on its original HTTPS endpoint."""
request = urllib.request.Request(url, headers=headers or {})
for attempt in range(3):
try:
with urllib.request.build_opener(NoRedirect()).open(request, timeout=30) as response:
data = response.read(limit + 1)
if len(data) > limit:
raise ValueError(f"Release response exceeds {limit} bytes")
return data
except urllib.error.HTTPError as exc:
if exc.code not in (502, 503, 504) or attempt == 2:
raise
except (urllib.error.URLError, TimeoutError, ConnectionError) as exc:
if attempt == 2:
raise RuntimeError(f"Could not read release metadata from {url}") from exc
time.sleep(1 + attempt)
def version(tag):
if not isinstance(tag, str) or not re.fullmatch(
r"v(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)", tag
):
raise ValueError(f"Expected a stable version tag, got {tag!r}")
return tuple(int(part) for part in tag[1:].split("."))
def tag_commit(tag):
version(tag)
commit = json.loads(read_url(f"{API}/tags/{tag}"))["commit"]["sha"]
if not re.fullmatch("[0-9a-f]{40,64}", commit):
raise ValueError("Invalid Gitea commit ID")
return commit
def release_bundle(release, tag):
"""Read the published hotfix and check it against the release checksum file."""
version(tag)
if release.get("tag_name") != tag or release.get("draft") or release.get("prerelease"):
raise ValueError("Expected the selected stable, published release")
assets = release.get("assets") or []
sizes = {entry["name"]: entry["size"] for entry in assets}
if len(assets) != len(sizes):
raise ValueError("Duplicate release attachment names")
name = f"planet-earth-bundle-{tag[1:]}.tar.gz"
base = f"{SERVER}/{REPO}/releases/download/{tag}"
if not 0 < sizes.get(name, 0) <= 32 * 1024 * 1024 or "SHA256SUMS.txt" not in sizes:
raise ValueError("Release has no complete Earth bundle and checksum list")
sums = read_url(f"{base}/SHA256SUMS.txt", limit=128 * 1024).decode().splitlines()
hashes = [line.split(" ", 1)[0] for line in sums if line.endswith(" " + name)]
data = read_url(f"{base}/{name}", limit=sizes[name])
sha = hashlib.sha256(data).hexdigest()
if hashes != [sha] or len(data) != sizes[name]:
raise ValueError("Earth bundle failed release SHA-256 or size verification")
return name, data, sha
def image_name(service):
if service not in SERVICES:
raise ValueError(f"Unexpected production service: {service}")
return f"{REGISTRY}/{REPO}/{service}"
def digest(data):
return "sha256:" + hashlib.sha256(data).hexdigest()
def descriptor_digest(desc):
value = desc["digest"]
if not re.fullmatch(r"sha256:[a-f0-9]{64}", value):
raise ValueError("Registry returned an invalid digest")
return value
def resolve_image(service, tag, commit):
"""Return the immutable platform image; only an absent tag returns None."""
version(tag)
name = image_name(service)
repository = f"{REPO}/{service}"
query = urllib.parse.urlencode(
{"service": "container_registry", "scope": f"repository:{repository}:pull"}
)
token = json.loads(read_url(f"{SERVER}/v2/token?{query}"))["token"]
headers = {"Authorization": "Bearer " + token, "Accept": MANIFEST_TYPES}
base = f"{SERVER}/v2/{repository}"
try:
raw = read_url(f"{base}/manifests/{tag}", headers=headers)
except urllib.error.HTTPError as exc:
if exc.code == 404:
return None
raise
manifest = json.loads(raw)
if "manifests" in manifest:
candidates = [
entry
for entry in manifest["manifests"]
if entry.get("platform", {}).get("os") == "linux"
and entry["platform"].get("architecture") == "amd64"
]
if len(candidates) != 1:
raise ValueError(f"{name}:{tag} must contain one linux/amd64 image")
selected = descriptor_digest(candidates[0])
raw = read_url(f"{base}/manifests/{selected}", headers=headers)
if digest(raw) != selected:
raise ValueError("Registry platform manifest failed digest verification")
manifest = json.loads(raw)
config_digest = descriptor_digest(manifest["config"])
config_raw = read_url(f"{base}/blobs/{config_digest}", headers=headers)
if digest(config_raw) != config_digest:
raise ValueError("Registry image configuration failed digest verification")
config = json.loads(config_raw)
labels = config.get("config", {}).get("Labels") or {}
if (config.get("os"), config.get("architecture")) != ("linux", "amd64"):
raise ValueError(f"{name}:{tag} is not a linux/amd64 image")
if labels.get("org.opencontainers.image.revision") != commit:
raise ValueError(f"{name}:{tag} belongs to a different commit")
if service == "admin" and labels.get("planet.frontend.target") != "admin":
raise ValueError("The production Admin image must be built with the admin-only target")
return f"{name}:{tag}@{digest(raw)}"
+223
View File
@@ -0,0 +1,223 @@
"""Prepare a tagged Planet release on the publishing workstation."""
from __future__ import annotations
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
from contextlib import contextmanager
from pathlib import Path
if __package__:
from .production_registry import (
REPO,
SERVER,
SERVICES,
image_name,
resolve_image,
tag_commit,
version,
)
else:
from production_registry import (
REPO,
SERVER,
SERVICES,
image_name,
resolve_image,
tag_commit,
version,
)
def git(*args, cwd=None):
return subprocess.check_output(["git", *args], cwd=cwd, text=True).strip()
def verified_tag(tag):
commit = tag_commit(tag)
if git("rev-parse", "--verify", f"{commit}^{{commit}}") != commit:
raise RuntimeError("The remote release commit is not available locally")
if git("show", f"{commit}:VERSION") != tag[1:]:
raise ValueError("Tagged VERSION differs from the published tag")
return commit
def docker_config():
config = os.environ.get("PLANET_RELEASE_DOCKER_CONFIG")
if config:
return Path(config).expanduser()
return (
Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "planet" / "registry"
)
def ensure_images(source, tag, commit):
for service in SERVICES:
pin = resolve_image(service, tag, commit)
if not pin:
context = source / "frontend" if service == "admin" else source
dockerfile = (
context / "Dockerfile" if service == "admin" else source / service / "Dockerfile"
)
cmd = [
"docker",
"--config",
str(docker_config()),
"buildx",
"build",
"--platform",
"linux/amd64",
"--provenance=false",
"--file",
str(dockerfile),
"--label",
f"org.opencontainers.image.revision={commit}",
"--label",
f"org.opencontainers.image.version={tag[1:]}",
"--label",
f"org.opencontainers.image.source={SERVER}/{REPO}",
]
if service == "admin":
cmd += [
"--build-arg",
"PLANET_FRONTEND_TARGET=admin",
"--label",
"planet.frontend.target=admin",
]
uv_config = Path.home() / ".config/uv/uv.toml"
if service != "admin" and uv_config.is_file():
cmd += ["--secret", f"id=planet_uv_config,src={uv_config}"]
cmd += [
"--output",
f"type=image,name={image_name(service)}:{tag},push=true,compression=gzip,force-compression=true",
str(context),
]
subprocess.run(cmd, check=True)
pin = resolve_image(service, tag, commit)
if not pin:
raise RuntimeError(f"Pushed image is not visible: {service}:{tag}")
print(f"Verified {pin}", flush=True)
def select_packages(directory, tag, suffixes):
number = re.compile(rf"(?<![\d.]){re.escape(tag[1:])}(?!\d|\.\d)")
paths = (
[
p
for p in directory.iterdir()
if p.is_file() and number.search(p.name) and p.name.lower().endswith(suffixes)
]
if directory.is_dir()
else []
)
names = [p.name.lower() for p in paths]
if not (
any(n.endswith(".exe") or n.endswith("-win.zip") for n in names)
and any(n.endswith(".dmg") or "mac" in n and n.endswith(".zip") for n in names)
and any(n.endswith((".appimage", ".deb")) for n in names)
and f"planet-earth-bundle-{tag[1:]}.tar.gz" in names
):
return []
bundle = directory / f"planet-earth-bundle-{tag[1:]}.tar.gz"
with tarfile.open(bundle, "r:gz") as archive:
member = archive.getmember("bundle-meta.json")
if not member.isfile() or member.size > 8192:
raise ValueError("Invalid hotfix package metadata")
if json.load(archive.extractfile(member)).get("version") != tag[1:]:
raise ValueError("Hotfix contents do not match the release tag")
return paths
@contextmanager
def local_release_lock(path):
with path.open("a+b") as lock:
if os.name == "nt":
import msvcrt
lock.seek(0)
msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1)
else:
import fcntl
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
yield
def package_hash(path):
with path.open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
def cached_packages(source, supplied, cache, tag, suffixes):
if not cache.exists():
if supplied is None:
subprocess.run(["./planet.sh", "bundle", "--all"], cwd=source, check=True)
supplied = source / "client/release"
packages = select_packages(supplied, tag, suffixes)
if not packages:
raise RuntimeError(f"Missing tagged desktop clients or Earth hotfix in {supplied}")
with tempfile.TemporaryDirectory(dir=cache.parent) as tmp:
stage = Path(tmp) / "assets"
stage.mkdir()
for package in packages:
shutil.copy2(package, stage / package.name)
sums = {p.name: package_hash(p) for p in stage.iterdir()}
(stage / "checksums.json").write_text(json.dumps(sums))
os.rename(stage, cache)
packages = select_packages(cache, tag, suffixes)
expected = json.loads((cache / "checksums.json").read_text())
if not packages or {p.name: package_hash(p) for p in packages} != expected:
raise ValueError("The saved release artifacts differ from the original build")
return packages
@contextmanager
def prepare(tag, assets_dir, suffixes, *, already_published=False):
version(tag)
commit = verified_tag(tag)
state = Path(os.environ.get("XDG_STATE_HOME") or Path.home() / ".local/state")
state = state / "planet-releases" / tag / "publisher"
state.mkdir(mode=0o700, parents=True, exist_ok=True)
cache = state / commit
with (
local_release_lock(state / "lock"),
tempfile.TemporaryDirectory(prefix="planet-publish-") as tmp,
):
worktree = Path(tmp) / "src"
subprocess.run(
["git", "worktree", "add", "--quiet", "--detach", str(worktree), commit], check=True
)
try:
ensure_images(worktree, tag, commit)
stage = Path(tmp) / "assets"
stage.mkdir()
if not already_published:
for package in cached_packages(worktree, assets_dir, cache, tag, suffixes):
try:
os.link(package, stage / package.name)
except OSError:
shutil.copy2(package, stage / package.name)
yield stage, worktree / "docs/CHANGELOG.md"
# The verified public release now holds these bytes. Keep the cache on upload failure.
if cache.exists():
shutil.rmtree(cache)
finally:
# This detached checkout and its generated build files are private to this invocation.
subprocess.run(["git", "worktree", "remove", "--force", str(worktree)], check=True)
if __name__ == "__main__":
if len(sys.argv) != 2:
sys.exit("Usage: production_release.py vX.Y.Z")
release_tag = sys.argv[1]
revision = verified_tag(release_tag)
if git("rev-parse", "HEAD") != revision or git("status", "--porcelain", "--untracked-files=no"):
sys.exit("Image-only CI jobs require a clean checkout at the tagged commit")
ensure_images(Path.cwd(), release_tag, revision)
+71 -21
View File
@@ -11,6 +11,8 @@ import os
import re
import subprocess
import sys
import tarfile
import time
import urllib.error
import urllib.parse
import urllib.request
@@ -24,6 +26,10 @@ class RejectRedirects(urllib.request.HTTPRedirectHandler):
return None
class RetryableUploadError(RuntimeError):
"""The server may already have received the attachment."""
API_OPENER = urllib.request.build_opener(RejectRedirects())
@@ -226,7 +232,8 @@ def upload_asset_with_curl(
capture_output=True,
)
if proc.returncode != 0:
raise RuntimeError(
error = RetryableUploadError if proc.returncode in (6, 7, 18, 28, 52, 55, 56, 92) else RuntimeError
raise error(
f"curl upload failed for {file_path.name} (exit={proc.returncode}): {proc.stderr.strip()}"
)
@@ -243,7 +250,8 @@ def upload_asset_with_curl(
"Check Gitea app.ini [attachment] MAX_SIZE and Nginx/Ingress client_max_body_size (>= 300M)."
)
if status_code != 201:
raise RuntimeError(f"Upload failed for {file_path.name} (HTTP {status_code})")
error = RetryableUploadError if status_code in (408, 409, 429, 502, 503, 504) else RuntimeError
raise error(f"Upload failed for {file_path.name} (HTTP {status_code})")
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
@@ -251,7 +259,7 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
parser.add_argument("--tag", required=True, help="Git release tag, e.g. v0.77.0")
parser.add_argument(
"--assets-dir",
default="client/release",
default=None,
help="Directory containing packaged client binaries (default: client/release)",
)
parser.add_argument(
@@ -387,17 +395,30 @@ def publish_release(
if path.name in existing:
verify_existing_asset(existing[path.name], path, sha, server, authorization)
print(f"verified existing {path.name}", flush=True)
for path, _sha in assets:
for path, sha in assets:
if path.name in existing:
continue
name = urllib.parse.quote(path.name, safe="")
print(f"uploading {path.name}...", flush=True)
upload_asset_with_curl(f"{release_url}/assets?name={name}", authorization, path)
for attempt in range(3):
try:
upload_asset_with_curl(f"{release_url}/assets?name={name}", authorization, path)
break
except RetryableUploadError:
received = list_assets(release_url, authorization).get(path.name)
if received:
verify_existing_asset(received, path, sha, server, authorization)
break
if attempt == 2:
raise
time.sleep(2 ** attempt)
uploaded = list_assets(release_url, authorization)
for path, _sha in assets:
for path, sha in assets:
if uploaded.get(path.name, {}).get("size") != path.stat().st_size:
raise RuntimeError(f"Missing or incomplete attachment: {path.name}")
if path.name not in existing or uploaded[path.name].get("id") != existing[path.name].get("id"):
verify_existing_asset(uploaded[path.name], path, sha, server, authorization)
status, published = api_request(
"PATCH", release_url, authorization, {"name": tag, "body": notes, "draft": False}
@@ -416,6 +437,7 @@ def publish_hotfix_bundle(
notes: str,
release_html_url: str,
assets: list[tuple[Path, str]],
min_shell_version: str | None = None,
) -> None:
hotfix_tar = next(
(
@@ -448,15 +470,15 @@ def publish_hotfix_bundle(
"@-",
"-F",
f"file=@{hotfix_tar}",
"-F",
"--form-string",
f"version={version}",
"-F",
f"min_shell_version={version}",
"-F",
"--form-string",
f"min_shell_version={min_shell_version or version}",
"--form-string",
f"shell_version={version}",
"-F",
"--form-string",
f"shell_download_url={release_html_url}",
"-F",
"--form-string",
f"release_notes={notes[:2000]}",
endpoint,
],
@@ -495,14 +517,14 @@ def main(argv: list[str] | None = None) -> int:
print("error: unable to resolve Gitea server URL or owner/repo slug", file=sys.stderr)
return 1
notes = extract_release_notes(Path(args.changelog), args.tag)
assets_dir = Path(args.assets_dir)
assets = collect_release_assets(assets_dir)
if not assets:
print(f"error: no distributable assets found in {assets_dir}", file=sys.stderr)
return 1
assets_dir = Path(args.assets_dir or "client/release")
if args.dry_run:
notes = extract_release_notes(Path(args.changelog), args.tag)
assets = collect_release_assets(assets_dir)
if not assets:
print(f"error: no distributable assets found in {assets_dir}", file=sys.stderr)
return 1
print(f"server: {server}")
print(f"repo: {repo}")
print(f"tag: {args.tag}")
@@ -514,13 +536,41 @@ def main(argv: list[str] | None = None) -> int:
return 0
try:
if args.use_git_credential:
if __package__:
from .production_registry import API, REPO, SERVER, release_bundle
from .production_release import prepare
else:
from production_registry import API, REPO, SERVER, release_bundle
from production_release import prepare
production = (server, repo) == (SERVER, REPO) and re.fullmatch(r"v\d+\.\d+\.\d+", args.tag)
token = os.environ.get("GITEA_TOKEN")
if not token and (not production or os.environ.get("GITHUB_SERVER_URL", "").rstrip("/") == server):
token = os.environ.get("GITHUB_TOKEN")
if args.use_git_credential or (production and not token):
authorization = git_credential_authorization(origin, server, repo)
else:
token = os.environ.get("GITEA_TOKEN") or os.environ.get("GITHUB_TOKEN")
if not token:
raise RuntimeError("Set GITEA_TOKEN or use the saved HTTPS Git credential")
authorization = f"token {token}"
if production:
status, public = api_request("GET", f"{API}/releases/tags/{args.tag}", authorization)
if status not in (200, 404):
raise RuntimeError(f"Cannot inspect the release (HTTP {status})")
published = status == 200 and isinstance(public, dict) and public.get("draft") is False
supplied = assets_dir if args.assets_dir else None
with prepare(args.tag, supplied, ASSET_SUFFIXES, already_published=published) as (stage, changelog):
if published:
release_bundle(public, args.tag)
print(f"Verified published release {args.tag}; production follows stable releases")
else:
notes = extract_release_notes(changelog, args.tag)
publish_release(server, repo, args.tag, notes, collect_release_assets(stage), authorization)
return 0
notes = extract_release_notes(Path(args.changelog), args.tag)
assets = collect_release_assets(assets_dir)
if not assets:
raise RuntimeError(f"No distributable assets found in {assets_dir}")
release_html_url = publish_release(server, repo, args.tag, notes, assets, authorization)
hotfix_url = str(args.hotfix_publish_url or "").strip()
hotfix_token = str(args.hotfix_publish_token or "").strip()
@@ -533,7 +583,7 @@ def main(argv: list[str] | None = None) -> int:
release_html_url=release_html_url,
assets=assets,
)
except (RuntimeError, urllib.error.URLError, TimeoutError) as exc:
except (RuntimeError, ValueError, KeyError, OSError, subprocess.SubprocessError, tarfile.TarError) as exc:
print(f"error: {exc}", file=sys.stderr)
return 1
return 0