Files
Kamino/scripts/next_image_version.py
Defame1297 a48cd063ea fix(ci): treat only a NAME_UNKNOWN 404 as an image with no tags
next_image_version.py read any 404 on the first tags/list page as a
repository not pushed yet, so a wrong registry path or a proxy's 404 page
would restart the image at <base>.0 instead of failing. The OCI
distribution spec answers a missing repository with 404 and the error
code NAME_UNKNOWN, so only that answer now means no tags.

RegistryError carried only the readable text of the body, so it now also
carries the body's OCI error codes. The tests cover a plain 404 page and a
404 with another code, both of which now raise.

Assisted-by: Claude Code
2026-12-02 08:51:21 +00:00

192 lines
6.8 KiB
Python

# SPDX-FileCopyrightText: Defame1297 and contributors
# SPDX-License-Identifier: GPL-3.0-or-later
"""Choose the version an image build publishes, or none.
python3 scripts/next_image_version.py <source-dir> <image-name> <registry-url>
Prints "<version> <checksum>" when the image's inputs differ from the newest published
<base>.N (its input-checksum label), and nothing when they match.
"""
import hashlib
import json
import os
import pathlib
import re
import sys
import urllib.error
import urllib.parse
import urllib.request
import check_image_versions as civ
def input_checksum(root, entry):
"""sha256 over the path, executable bit and content of every input file of the image."""
root = pathlib.Path(root)
context = root / entry["subpath"] if entry["subpath"] else root
dockerfile = (context / entry["dockerfile"]).read_text(encoding="utf-8")
dirs, files = civ.inputs_of(entry, dockerfile)
paths = sorted(
p.relative_to(root).as_posix()
for p in root.rglob("*")
if (p.is_file() or p.is_symlink()) and ".git" not in p.relative_to(root).parts
)
digest = hashlib.sha256()
for path in civ.touched(paths, dirs, files):
full = root / path
if full.is_symlink():
kind, body = "l", os.readlink(full).encode()
else:
kind, body = ("x" if os.access(full, os.X_OK) else "f"), full.read_bytes()
digest.update(f"{path}\0{kind}\0{hashlib.sha256(body).hexdigest()}\n".encode())
return digest.hexdigest()
def next_version(base, tags, checksum, label_of):
"""The next <base>.N, or None when the newest one was built from these inputs."""
patches = [
int(m[1])
for t in tags
if (m := re.fullmatch(re.escape(base) + r"\.(0|[1-9][0-9]*)", t))
]
if not patches:
return f"{base}.0"
newest = max(patches)
if label_of(f"{base}.{newest}") == checksum:
return None
return f"{base}.{newest + 1}"
LABEL = "net.rkdr.mortis.inputs-sha256"
MANIFEST_TYPES = (
"application/vnd.oci.image.manifest.v1+json",
"application/vnd.docker.distribution.manifest.v2+json",
)
# Bot filters in front of a registry commonly refuse Python's default User-Agent.
USER_AGENT = "kamino-next-image-version"
class RegistryError(Exception):
def __init__(self, url, status, text, challenge="", codes=()):
super().__init__(f"GET {url}: HTTP {status}: {text}")
self.status, self.challenge, self.codes = status, challenge, codes
def _error_codes(raw):
"""The OCI error codes of an error body (`{"errors": [{"code": ...}]}`), or () for any other body."""
try:
errors = json.loads(raw).get("errors") or []
return tuple(e.get("code") for e in errors if isinstance(e, dict))
except (ValueError, AttributeError, TypeError):
return ()
def _readable(raw):
"""The visible text of an error page on one line, so the job log shows a block page."""
text = re.sub(
r"<(script|style)\b.*?</\1>|<[^>]+>", " ", raw, flags=re.DOTALL | re.IGNORECASE
)
return " ".join(text.split())[:300]
def _fetch(url, headers):
"""(JSON body, headers) of a GET; any HTTP error is a RegistryError naming status and text."""
request = urllib.request.Request(url, headers={**headers, "User-Agent": USER_AGENT})
try:
with urllib.request.urlopen(request, timeout=30) as resp:
return json.load(resp), resp.headers
except urllib.error.HTTPError as exc:
raw = exc.read(20000).decode("utf-8", errors="replace")
challenge = exc.headers.get("WWW-Authenticate", "")
raise RegistryError(
url, exc.code, _readable(raw), challenge, _error_codes(raw)
) from exc
class Registry:
"""Anonymous reads of one image in an OCI registry: the images are public."""
def __init__(self, base_url, image):
self.base_url, self.image, self.token = base_url, image, None
def _get(self, path, accept="application/json"):
url = f"{self.base_url}/v2/{self.image}/{path}"
headers = {"Accept": accept}
if self.token:
headers["Authorization"] = f"Bearer {self.token}"
try:
return _fetch(url, headers)
except RegistryError as exc:
# One login at most: a 401 after it is final, whatever token it gave.
if (
exc.status != 401
or self.token is not None
or not self._login(exc.challenge)
):
raise
return self._get(path, accept)
def _login(self, challenge_header):
"""Fetch an anonymous pull token from the 401 challenge's realm; False when it names none."""
challenge = dict(re.findall(r'(\w+)="([^"]*)"', challenge_header))
if "realm" not in challenge:
return False
query = urllib.parse.urlencode(
{
"service": challenge.get("service", ""),
"scope": f"repository:{self.image}:pull",
}
)
self.token = _fetch(f"{challenge['realm']}?{query}", {})[0]["token"]
return True
def tags(self):
tags, path = [], "tags/list"
while path:
try:
body, headers = self._get(path)
except RegistryError as exc:
# A repository not pushed yet is 404 NAME_UNKNOWN (OCI distribution spec): no tags.
# Any other 404, such as a wrong registry path, must fail rather than restart at .0.
if exc.status == 404 and "NAME_UNKNOWN" in exc.codes and not tags:
return []
raise
tags += body.get("tags") or []
link = re.search(r"<[^>]*/tags/list(\?[^>]*)>", headers.get("Link", ""))
path = f"tags/list{link[1]}" if link else None
return tags
def label(self, tag):
manifest = self._get(f"manifests/{tag}", ", ".join(MANIFEST_TYPES))[0]
if manifest.get("mediaType") not in MANIFEST_TYPES:
raise ValueError(
f"{self.image}:{tag} is not a single-platform image manifest"
)
config = self._get(f"blobs/{manifest['config']['digest']}")[0]
return (config.get("config", {}).get("Labels") or {}).get(LABEL)
def main(argv):
if len(argv) != 4:
sys.stderr.write(__doc__)
return 2
root, name, url = pathlib.Path(argv[1]), argv[2], argv[3]
entry = civ.matrix_of((root / civ.MATRIX_FILE).read_text(encoding="utf-8"))[name]
checksum = input_checksum(root, entry)
registry = Registry(url, f"mortis/{name}")
try:
version = next_version(entry["base"], registry.tags(), checksum, registry.label)
except RegistryError as exc:
sys.stderr.write(f"::error::{exc}\n")
return 1
if version:
print(version, checksum)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))