okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Docker docs, compose defaults, scripts and the file test name the 0.2.7 image tags (0.2.7-cuda13 and the other flavors)df20d7784

main
7.6 KiB148 linesraw
1#!/usr/bin/env python3
2"""Fetch the engine packages for the Docker images from a release, checked against the signed update feed.
3
4    python3 docker/fetch-engines.py --release-tag v0.2.7 --flavors cuda13,cuda12,rocm-gfx120x --out ./pkgs
5    python3 docker/fetch-engines.py --source /path/to/release-folder --flavors cuda13 --out ./pkgs
6    python3 docker/fetch-engines.py --release-tag v0.2.7 --list
7
8What it does, in the same order and with the same code as `strata update`:
9
101. reads strata-feed.json and strata-feed.json.sig from the release (GitHub release assets, or a folder / URL given with --source)
11   and checks the Ed25519 signature against the public key in strata_control/update_keys.json;
122. for each flavor picks the linux-x86_64 engine package the feed lists for it (see FLAVORS);
133. downloads the archive and checks its size and SHA-256 against the signed feed (a mismatch deletes the file and stops);
144. unpacks it (the archive's names and links are checked, its size may not exceed what the feed declares), checks that the
15   manifest is the one the feed names and says what the feed says, then the package signature and every file's hash.
16
17Stdout gets one line per flavor, tab separated: `<flavor> <build.sh --flavor value> <package folder>`; everything else goes to
18stderr. Nothing is installed anywhere and nothing is pushed. Needs only the Python standard library and this repository.
19"""
20from __future__ import annotations
21
22import argparse
23import shutil
24import sys
25from pathlib import Path
26
27REPO_ROOT = Path(__file__).resolve().parent.parent
28sys.path.insert(0, str(REPO_ROOT))
29
30from strata_control import engine_component as ec, feed as feedmod, signing, transfer, updater  # noqa: E402
31
32#: image flavor (the tag suffix) -> (feed backend, feed variant or None for any, docker/build.sh --flavor)
33FLAVORS = {
34    "cuda13": ("cuda", "cuda13", "cuda"),
35    "cuda12": ("cuda", "cuda12", "cuda"),
36    "rocm-gfx120x": ("hip", "rx9070", "hip"),       # RX 9000, Radeon AI PRO R9700 (gfx1200 / gfx1201)
37    "rocm-gfx110x": ("hip", "rx7900", "hip"),       # RX 7000 (gfx1100 / gfx1101 / gfx1102)
38    "rocm-gfx1151": ("hip", "halo", "hip"),         # Strix Halo (gfx1151)
39    "sycl": ("sycl", None, "sycl"),                 # Intel Arc; only when the release has a Linux SYCL package
40}
41PLATFORM = "linux-x86_64"
42
43
44def log(message: str) -> None:
45    print(message, file=sys.stderr, flush=True)
46
47
48def pick(feed: feedmod.Feed, flavor: str) -> feedmod.EnginePackage | None:
49    backend, variant, _ = FLAVORS[flavor]
50    found = [p for p in feed.engine if p.platform == PLATFORM and p.backend == backend and (variant is None or p.variant == variant)]
51    if not found:
52        return None
53    return max(found, key=lambda p: feedmod.version_key(p.version))
54
55
56def fetch_one(feed: feedmod.Feed, pkg: feedmod.EnginePackage, out: Path, trusted: dict) -> Path:
57    folder = out / updater.folder_name(pkg)
58    archive = out / ".partial" / pkg.url.rsplit("/", 1)[-1]
59    if folder.is_dir() and (folder / ec.MANIFEST).is_file() and transfer.sha256_file(folder / ec.MANIFEST) == pkg.manifest_sha256:
60        log(f"  {folder.name}: already unpacked, manifest matches the feed")
61    else:
62        log(f"  downloading {pkg.url} ({pkg.size / (1 << 20):.0f} MiB)")
63        try:
64            transfer.download(feed.url(pkg.url), archive, size=pkg.size, sha256=pkg.sha256)
65        except transfer.TransferError as exc:
66            raise SystemExit(f"fetch-engines: {exc}")
67        log("  size and SHA-256 match the signed feed; unpacking")
68        try:
69            updater.extract(archive, folder, pkg.format, pkg.installed_bytes)
70        except updater.UpdateError as exc:
71            raise SystemExit(f"fetch-engines: {exc}")
72        finally:
73            archive.unlink(missing_ok=True)
74    manifest = folder / ec.MANIFEST
75    if transfer.sha256_file(manifest) != pkg.manifest_sha256:
76        raise SystemExit(f"fetch-engines: {folder.name} has a manifest the signed feed does not name")
77    try:
78        component = ec.read_manifest(folder)
79    except ec.ComponentProblem as exc:
80        raise SystemExit(f"fetch-engines: {folder.name}: the package manifest is invalid: {exc}")
81    for name, a, b in (("version", component.version, pkg.version), ("platform", component.platform, pkg.platform),
82                       ("backend", component.backend, pkg.backend), ("variant", component.variant, pkg.variant),
83                       ("build_id", component.build_id, pkg.build_id), ("archs", set(component.archs), set(pkg.archs))):
84        if a != b:
85            raise SystemExit(f"fetch-engines: {folder.name}: the manifest says a different {name} than the signed feed")
86    outer = ec._verifier
87    signing.install_component_verifier(trusted)
88    try:
89        ec.verify_signature(component, {ec.ENV_REQUIRE_SIGNED: "1"})
90        ec.verify(component, full=True)
91    except ec.ComponentProblem as exc:
92        raise SystemExit(f"fetch-engines: {folder.name} failed its check: {exc}")
93    finally:
94        ec.register_signature_verifier(outer)
95    log(f"  {folder.name}: signature and every file verified (build {pkg.build_id})")
96    return folder
97
98
99def main() -> int:
100    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
101    ap.add_argument("--release-tag", help="the GitHub release tag, for example v0.2.7")
102    ap.add_argument("--repo", default="Niko1221/Strata", help="owner/name of the GitHub repository (default %(default)s)")
103    ap.add_argument("--source", help="a release folder or base URL holding strata-feed.json(.sig) and the archives (instead of --release-tag)")
104    ap.add_argument("--flavors", default=",".join(FLAVORS), help="comma separated; default: all (%s)" % ", ".join(FLAVORS))
105    ap.add_argument("--out", type=Path, help="where the unpacked package folders go")
106    ap.add_argument("--skip-missing", action="store_true", help="a flavor the feed has no package for is skipped (default: an error)")
107    ap.add_argument("--list", action="store_true", help="only print which package each flavor would use")
108    a = ap.parse_args()
109    if bool(a.release_tag) == bool(a.source):
110        ap.error("give exactly one of --release-tag and --source")
111    if not a.list and not a.out:
112        ap.error("--out is required")
113    flavors = [f.strip() for f in a.flavors.split(",") if f.strip()]
114    unknown = [f for f in flavors if f not in FLAVORS]
115    if unknown:
116        ap.error(f"unknown flavor {', '.join(unknown)} (known: {', '.join(FLAVORS)})")
117    source = a.source or f"https://github.com/{a.repo}/releases/download/{a.release_tag}"
118    trusted = signing.load_trusted_keys()
119    log(f"feed: {source}")
120    try:
121        feed = feedmod.fetch(source, trusted)
122    except feedmod.FeedError as exc:
123        raise SystemExit(f"fetch-engines: {exc}")
124    log(f"feed signature OK (key {feed.key_id}), channel {feed.channel}, sequence {feed.sequence}")
125    status = 0
126    for flavor in flavors:
127        pkg = pick(feed, flavor)
128        if pkg is None:
129            log(f"{flavor}: the feed has no {PLATFORM} package for it")
130            if not a.skip_missing:
131                status = 3
132            else:
133                print(f"{flavor}\t{FLAVORS[flavor][2]}\tSKIP")
134            continue
135        log(f"{flavor}: {pkg.label} ({pkg.url})")
136        if a.list:
137            print(f"{flavor}\t{FLAVORS[flavor][2]}\t{pkg.url}\t{pkg.size}\t{pkg.sha256}")
138            continue
139        a.out.mkdir(parents=True, exist_ok=True)
140        folder = fetch_one(feed, pkg, a.out, trusted)
141        print(f"{flavor}\t{FLAVORS[flavor][2]}\t{folder}", flush=True)
142    if a.out and (a.out / ".partial").is_dir():
143        shutil.rmtree(a.out / ".partial", ignore_errors=True)
144    return status
145
146
147if __name__ == "__main__":
148    sys.exit(main())