Files
planet/scripts/production_release.py
T
linkong 2c439b7235
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
release: bump version to 0.80.2
2026-11-30 11:06:33 +08:00

352 lines
13 KiB
Python

"""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 (
API,
MANIFEST_NAME,
REPO,
SERVER,
SERVICES,
image_name,
read_url,
release_manifest,
resolve_image,
resolve_service_ref,
tag_commit,
version,
)
from .release_scope import resolve_release_scope
else:
from production_registry import (
API,
MANIFEST_NAME,
REPO,
SERVER,
SERVICES,
image_name,
read_url,
release_manifest,
resolve_image,
resolve_service_ref,
tag_commit,
version,
)
from release_scope import resolve_release_scope
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, *, services=None, previous_services=None):
target_services = set(SERVICES if services is None else services)
resolved_pins = {}
for service in SERVICES:
if service not in target_services:
prev_ref = (previous_services or {}).get(service)
if not prev_ref:
raise RuntimeError(
f"Cannot reuse unchanged {service} image without a verified previous release pin"
)
resolved_pins[service] = prev_ref
print(f"Reused {prev_ref}", flush=True)
continue
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}")
resolved_pins[service] = pin
print(f"Verified {pin}", flush=True)
return resolved_pins
def select_packages(directory, tag, suffixes, *, client_mode="full"):
if client_mode == "none":
return []
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 []
)
bundle = directory / f"planet-earth-bundle-{tag[1:]}.tar.gz"
if not bundle.is_file():
return []
if client_mode == "full":
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)
):
return []
elif client_mode == "hotfix":
paths = [bundle]
else:
raise ValueError(f"Unsupported client_mode: {client_mode!r}")
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, *, client_mode="full"):
if client_mode == "none":
return []
if not cache.exists():
if supplied is None:
bundle_flag = "--hotfix" if client_mode == "hotfix" else "--all"
subprocess.run(["./planet.sh", "bundle", bundle_flag], cwd=source, check=True)
supplied = source / "client/release"
packages = select_packages(supplied, tag, suffixes, client_mode=client_mode)
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, client_mode=client_mode)
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
def resolve_previous_release_state(previous_tag):
"""Fetch verified service image refs and active desktop shell version from ``previous_tag``."""
if not previous_tag:
return {}, None, None
release = json.loads(read_url(f"{API}/releases/tags/{previous_tag}"))
manifest = release_manifest(release, previous_tag)
if manifest is not None:
pins = {
service: resolve_service_ref(service, ref)
for service, ref in manifest["services"].items()
}
client = manifest.get("client") or {}
return pins, client.get("shell_version"), client.get("min_shell_version")
prev_commit = tag_commit(previous_tag)
pins = {}
for service in SERVICES:
pin = resolve_image(service, previous_tag, prev_commit)
if not pin:
raise RuntimeError(f"Missing {service}:{previous_tag} image in previous release")
pins[service] = pin
return pins, previous_tag[1:], previous_tag[1:]
def build_release_manifest(tag, commit, scope, service_refs, packages, *, shell_version=None, min_shell_version=None):
ver = tag[1:]
bundle_name = f"planet-earth-bundle-{ver}.tar.gz"
bundle_path = next((p for p in packages if p.name == bundle_name), None)
if scope.client_mode == "full":
resolved_shell = ver
resolved_min_shell = ver
else:
resolved_shell = shell_version or ver
resolved_min_shell = min_shell_version or resolved_shell
return {
"schema_version": 1,
"tag": tag,
"commit": commit,
"previous_tag": scope.previous_tag,
"components": list(scope.components),
"changed_services": list(scope.services),
"services": dict(service_refs),
"client": {
"mode": scope.client_mode,
"shell_version": resolved_shell,
"min_shell_version": resolved_min_shell,
"bundle": bundle_path.name if bundle_path else None,
"bundle_sha256": package_hash(bundle_path) if bundle_path else None,
},
}
@contextmanager
def prepare(tag, assets_dir, suffixes, *, already_published=False, scope_override=None):
version(tag)
commit = verified_tag(tag)
scope = resolve_release_scope(tag, commit, override=scope_override)
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_key = f"{commit}-{scope.client_mode}"
cache = state / cache_key
prev_services = {}
prev_shell_version = None
prev_min_shell_version = None
if len(scope.services) < len(SERVICES) or scope.client_mode != "full":
if scope.previous_tag:
prev_services, prev_shell_version, prev_min_shell_version = resolve_previous_release_state(
scope.previous_tag
)
elif len(scope.services) < len(SERVICES):
raise RuntimeError("No previous stable release found to reuse unchanged services")
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:
service_refs = ensure_images(
worktree,
tag,
commit,
services=scope.services,
previous_services=prev_services,
)
stage = Path(tmp) / "assets"
stage.mkdir()
if not already_published:
staged_packages = []
for package in cached_packages(
worktree,
assets_dir,
cache,
tag,
suffixes,
client_mode=scope.client_mode,
):
dest = stage / package.name
try:
os.link(package, dest)
except OSError:
shutil.copy2(package, dest)
staged_packages.append(dest)
manifest = build_release_manifest(
tag,
commit,
scope,
service_refs,
staged_packages,
shell_version=prev_shell_version,
min_shell_version=prev_min_shell_version,
)
(stage / MANIFEST_NAME).write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
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)