156 lines
6.1 KiB
Python
156 lines
6.1 KiB
Python
"""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)}"
|