diff --git a/tests/external/update/docker/test_image_architectures.py b/tests/external/update/docker/test_image_architectures.py index 4e6dc331dc..6474ce62be 100644 --- a/tests/external/update/docker/test_image_architectures.py +++ b/tests/external/update/docker/test_image_architectures.py @@ -55,7 +55,7 @@ import unittest from typing import ClassVar from utils.annotations.message import warning -from utils.docker.image.architectures import role_capability +from utils.docker.image.architectures import role_capability, service_platforms from utils.docker.image.discovery import iter_role_images from utils.docker.registry import manifest_platforms_probed from utils.github.variant.pools import ARCHITECTURES @@ -79,7 +79,11 @@ class ImageArchitectures(unittest.TestCase): @classmethod def setUpClass(cls) -> None: - refs = [ref for ref in iter_role_images(PROJECT_ROOT) if not ref.derived] + refs = [ + ref + for ref in iter_role_images(PROJECT_ROOT) + if not ref.derived or ref.architecture + ] cls.by_role = collections.defaultdict(list) for ref in refs: cls.by_role[ref.role].append(ref) @@ -104,7 +108,7 @@ class ImageArchitectures(unittest.TestCase): Returns: What :func:`role_capability` returns for the role's images. """ - offered = {} + probes = collections.defaultdict(list) for ref in self.by_role[role]: platforms = self.probed.get((_pull_image(ref), ref.version)) if platforms is None: @@ -115,8 +119,11 @@ class ImageArchitectures(unittest.TestCase): title="🔍 Unverified image architectures", file=f"roles/{ref.role}/{ROLE_FILE_META_SERVICES}", ) - offered[f"{ref.service} ({_pull_image(ref)}:{ref.version})"] = platforms - return role_capability(offered) + label = f"{ref.service} ({_pull_image(ref)})" + probes[label].append((ref.architecture, platforms)) + return role_capability( + {label: service_platforms(pairs) for label, pairs in probes.items()} + ) @staticmethod def _named(blame: dict, architecture: str) -> str: diff --git a/tests/external/update/docker/test_image_pin_policy.py b/tests/external/update/docker/test_image_pin_policy.py index be4e27c3fa..b929ab26ea 100644 --- a/tests/external/update/docker/test_image_pin_policy.py +++ b/tests/external/update/docker/test_image_pin_policy.py @@ -72,7 +72,9 @@ class TestImagePinPolicy(unittest.TestCase): f" roles/{ref.role}/{ROLE_FILE_META_SERVICES}: {ref.service} pins " f"{ref.version!r}, which is neither a version nor a digest" for ref in refs - if pin_class(ref.version) == REF and not _declared(ref, RULE_BY_CLASS[REF]) + if not ref.derived + and pin_class(ref.version) == REF + and not _declared(ref, RULE_BY_CLASS[REF]) ] if offenders: diff --git a/tests/unit/python/utils/docker/test_image_architectures.py b/tests/unit/python/utils/docker/test_image_architectures.py index 7130f9a472..d7d5674aea 100644 --- a/tests/unit/python/utils/docker/test_image_architectures.py +++ b/tests/unit/python/utils/docker/test_image_architectures.py @@ -10,11 +10,17 @@ from __future__ import annotations import unittest -from utils.docker.image.architectures import role_capability, runnable_architectures +from utils.docker.image.architectures import ( + role_capability, + runnable_architectures, + service_platforms, +) BOTH = {"linux/amd64", "linux/arm64"} AMD64 = {"linux/amd64"} ARM64 = {"linux/arm64"} +PINNED = "" +REWRITTEN = "arm64" class TestRunnableArchitectures(unittest.TestCase): @@ -94,5 +100,38 @@ class TestRoleCapability(unittest.TestCase): self.assertEqual((None, {}, []), role_capability({})) +class TestServicePlatforms(unittest.TestCase): + def test_a_derived_arm64_tag_completes_an_amd64_only_pin(self) -> None: + merged = service_platforms([(PINNED, AMD64), (REWRITTEN, ARM64)]) + capability, blame, _unread = role_capability({"speech": merged}) + + self.assertEqual({"amd64", "arm64"}, capability) + self.assertEqual({}, blame) + + def test_an_amd64_only_pin_without_a_derived_tag_stays_amd64(self) -> None: + capability, blame, _unread = role_capability( + {"speech": service_platforms([(PINNED, AMD64)])} + ) + + self.assertEqual({"amd64"}, capability) + self.assertEqual({"arm64": ["speech"]}, blame) + + def test_a_derived_tag_counts_only_on_its_own_architecture(self) -> None: + merged = service_platforms([(PINNED, AMD64), (REWRITTEN, AMD64)]) + + self.assertEqual( + AMD64, + merged, + "an arm64 tag that publishes amd64 only must not make the service " + "look arm64-capable", + ) + + def test_the_pin_no_longer_counts_for_a_rewritten_architecture(self) -> None: + self.assertEqual(AMD64, service_platforms([(PINNED, BOTH), (REWRITTEN, set())])) + + def test_one_unread_tag_leaves_the_service_unread(self) -> None: + self.assertIsNone(service_platforms([(PINNED, AMD64), (REWRITTEN, None)])) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/utils/docker/test_image_discovery_variants.py b/tests/unit/python/utils/docker/test_image_discovery_variants.py index 0f7b688be7..f57af7279b 100644 --- a/tests/unit/python/utils/docker/test_image_discovery_variants.py +++ b/tests/unit/python/utils/docker/test_image_discovery_variants.py @@ -22,6 +22,52 @@ engine: """ +COMMIT = "d1be6fde11ac6e0407606b4e42fe72d34add8037" + +WITH_ARCHITECTURE_TAGS = f"""--- +speech: + image: ghcr.io/ggml-org/whisper.cpp + version: main-{COMMIT} + architecture_tags: + arm64: + prefix: main- + replacement: main-arm64- +""" + + +def _refs(services_yaml: str) -> list: + with tempfile.TemporaryDirectory() as tmp: + services = Path(tmp) / "roles" / "svc-demo" / ROLE_FILE_META_SERVICES + services.parent.mkdir(parents=True) + services.write_text(services_yaml, encoding="utf-8") + return list(iter_role_images(Path(tmp))) + + +class TestImageDiscoveryArchitectureTags(unittest.TestCase): + def test_the_derived_arm64_tag_yields_its_own_ref(self) -> None: + refs = { + (ref.version, ref.architecture, ref.derived) + for ref in _refs(WITH_ARCHITECTURE_TAGS) + } + + self.assertEqual( + {(f"main-{COMMIT}", "", False), (f"main-arm64-{COMMIT}", "arm64", True)}, + refs, + ) + + def test_the_arm64_ref_pulls_from_the_same_image(self) -> None: + sources = {ref.source for ref in _refs(WITH_ARCHITECTURE_TAGS)} + + self.assertIn(f"ghcr.io/ggml-org/whisper.cpp:main-arm64-{COMMIT}", sources) + + def test_a_service_without_architecture_tags_yields_no_arch_ref(self) -> None: + self.assertEqual({""}, {ref.architecture for ref in _refs(BASE)}) + + def test_a_pin_that_lost_the_rewritten_prefix_fails_the_scan(self) -> None: + with self.assertRaises(ValueError): + _refs(WITH_ARCHITECTURE_TAGS.replace(f"main-{COMMIT}", "v1.9.6")) + + class TestImageDiscoveryVersionVariants(unittest.TestCase): def _versions(self, services_yaml: str) -> set[str]: with tempfile.TemporaryDirectory() as tmp: diff --git a/utils/docker/image/architecture_tags.py b/utils/docker/image/architecture_tags.py new file mode 100644 index 0000000000..c3b3211064 --- /dev/null +++ b/utils/docker/image/architecture_tags.py @@ -0,0 +1,88 @@ +from __future__ import annotations + +from collections.abc import Mapping + +PREFIX = "prefix" +REPLACEMENT = "replacement" + + +def _mapping(rewrites: object) -> Mapping: + if not isinstance(rewrites, Mapping): + raise TypeError( + f"architecture_tags is a {type(rewrites).__name__}, not a mapping" + ) + return rewrites + + +def _rewrite(architecture: str, rewrite: object) -> tuple[str, str]: + if not isinstance(rewrite, Mapping): + raise TypeError( + f"architecture_tags.{architecture} is a {type(rewrite).__name__}, " + f"not a mapping of {PREFIX} and {REPLACEMENT}" + ) + prefix, replacement = (str(rewrite.get(key) or "") for key in (PREFIX, REPLACEMENT)) + if not prefix or not replacement: + raise ValueError( + f"architecture_tags.{architecture} needs a non-empty {PREFIX} and " + f"{REPLACEMENT}" + ) + return prefix, replacement + + +def architecture_tag(version: str, architecture: str, rewrites: object) -> str: + """ + Args: + version: the one tag the service pins in ``version``. + architecture: the OCI architecture of the node that pulls the image, + such as ``amd64`` or ``arm64``. + rewrites: the service's ``architecture_tags``, mapping an architecture + to the ``prefix`` of ``version`` its own tag swaps for + ``replacement``; empty or None when every architecture pulls + ``version``. + + Returns: + The tag *architecture* pulls: ``version`` with its prefix rewritten + for an architecture that has a rewrite, ``version`` itself otherwise. + + Raises: + TypeError: *rewrites* or its rewrite for *architecture* is no mapping. + ValueError: the rewrite for *architecture* lacks a prefix or a + replacement, or *version* does not start with that prefix, as + after a bump to a tag of another shape. + """ + if not rewrites: + return version + rewrites = _mapping(rewrites) + if architecture not in rewrites: + return version + prefix, replacement = _rewrite(architecture, rewrites[architecture]) + if not version.startswith(prefix): + raise ValueError( + f"version {version!r} does not start with {prefix!r}, so its " + f"{architecture} tag cannot be derived from it" + ) + return replacement + version[len(prefix) :] + + +def architecture_tags(version: str, rewrites: object) -> dict[str, str]: + """ + Args: + version: the one tag the service pins in ``version``. + rewrites: the service's ``architecture_tags``, as `architecture_tag` + reads them. + + Returns: + The derived tag of every architecture with a rewrite, keyed by + architecture; empty when every architecture pulls ``version``. + + Raises: + TypeError: as `architecture_tag` raises it. + ValueError: as `architecture_tag` raises it. + """ + if not rewrites: + return {} + rewrites = _mapping(rewrites) + return { + str(architecture): architecture_tag(version, str(architecture), rewrites) + for architecture in rewrites + } diff --git a/utils/docker/image/architectures.py b/utils/docker/image/architectures.py index 16e4fc8286..1bf030124c 100644 --- a/utils/docker/image/architectures.py +++ b/utils/docker/image/architectures.py @@ -32,6 +32,42 @@ def runnable_architectures(platforms) -> set[str]: return offered +def _architecture(platform: str) -> str: + return str(platform).partition("/")[2] + + +def service_platforms(probes) -> set[str] | None: + """Args: + probes: ``(architecture, platforms)`` per tag of the service. + ``architecture`` names the one architecture an + ``architecture_tags`` tag is pulled on and is empty for the pinned + ``version``, which every other architecture pulls; ``platforms`` + is what the registry reports for the tag, or ``None`` when its + answer was indeterminate. + + Returns: + The ``os/architecture`` entries the service runs on as deployed, or + ``None`` when any of its tags went unread, which + :func:`role_capability` then reports as unread instead of reading a + missing architecture into it. + """ + rewritten = {architecture for architecture, _platforms in probes if architecture} + merged: set[str] = set() + for architecture, platforms in probes: + if platforms is None: + return None + merged.update( + platform + for platform in platforms + if ( + _architecture(platform) == architecture + if architecture + else _architecture(platform) not in rewritten + ) + ) + return merged + + def role_capability( offered, ) -> tuple[set[str] | None, dict[str, list[str]], list[str]]: diff --git a/utils/docker/image/discovery.py b/utils/docker/image/discovery.py index 84016dd71f..1d2b6dfbf6 100644 --- a/utils/docker/image/discovery.py +++ b/utils/docker/image/discovery.py @@ -4,6 +4,7 @@ from dataclasses import dataclass from typing import TYPE_CHECKING from utils.cache.yaml import load_yaml_any as _load_yaml_cached +from utils.docker.image.architecture_tags import architecture_tags from utils.docker.image.pin import pull_reference from utils.roles import lifecycle from utils.roles.custom import resolve_role_version @@ -56,9 +57,12 @@ class ImageRef: registry: source registry hostname, e.g. ``docker.io``, ``quay.io`` source_file: file the ref was read from, role-relative for a role image and repository-relative for a ``runner`` image - derived: the ref carries a ``version_variants`` suffix rather than the - version the service declares, so it is a tag the mirror must carry - but never the version a role deploys + derived: the ref carries a ``version_variants`` suffix or an + ``architecture_tags`` rewrite rather than the version the service + declares, so it is a tag the mirror must carry but never a version + an updater bumps + architecture: the one architecture an ``architecture_tags`` ref is + pulled on; empty for a ref every other architecture pulls """ @@ -70,6 +74,7 @@ class ImageRef: registry: str = "docker.io" source_file: str = ROLE_FILE_META_SERVICES derived: bool = False + architecture: str = "" @property def addressable(self) -> str: @@ -231,7 +236,8 @@ def iter_role_images(repo_root: Path) -> Iterable[ImageRef]: A role whose vars derive a further tag from ``version`` lists the suffixes under ``.version_variants``; each yields its own ref, because this function is the only enumeration the mirror sees and a tag it never emits - can never be mirrored. + can never be mirrored. ``.architecture_tags`` yields one ref per + rewritten architecture the same way, carrying that architecture. Two kinds of role are left out. One the updaters do not maintain (``is_maintained``), and one whose lifecycle status lacks the @@ -291,6 +297,20 @@ def iter_role_images(repo_root: Path) -> Iterable[ImageRef]: derived=bool(suffix), ) + tags = architecture_tags(version, service.get("architecture_tags")) + for architecture, tag in sorted(tags.items()): + yield ImageRef( + role=role_name, + service=str(service_name), + name=canonical_image_name(image), + version=tag, + source=image_source(image, tag), + registry=_detect_registry(image), + source_file=ROLE_FILE_META_SERVICES, + derived=True, + architecture=architecture, + ) + RUNNER_ROLE = "runner" RUNNER_COMPOSE_FILES = ("compose.yml", "compose/infra.yml")