From 1ba796d7f11085db45094a52069b575ef23702ca Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sat, 10 Oct 2026 01:14:33 +0200 Subject: [PATCH] fix(ci): pull the images the runner uses itself from the GHCR mirror The GHCR mirror covered role images only. The images the runner pulls on its own went straight to Docker Hub: coredns from compose.yml, the cache stack in compose/cache.override.yml and alpine:latest, the init image of scripts/docker/cache/package-frontend/certs.sh. With the anonymous githubactions quota spent, the guide step of Postmarks#0 (main run 37954203718) and Shopware#2 (#872) died on "toomanyrequests" while pulling alpine:latest, after coredns had hit the same limit. iter_runner_images (utils/docker/image/discovery.py) finds those images, and the mirror sync and the fork-PR wait now cover them next to the role images. On a real GitHub runner compose_file_args layers a generated build/compose/runner-mirror.override.yml that points only the services of the layered compose files at their mirror, and the certificate generator gets the mirrored init image. Local runs and act are unchanged, and the coredns literal stays in compose.yml for Dependabot. test-dns now waits for images-mirror-missing like the deploy and workspace jobs, since it brings up the stack too. Verified with docker compose config on a simulated GitHub runner: the service set is unchanged and only the runner images point at ghcr.io/infinito-nexus/core/mirror/docker.io/..., and an existing role mirror under that scheme pulls anonymously. Co-Authored-By: Claude Opus 5.5 (1M context) --- .github/workflows/call-orchestrator.yml | 1 + .../deploy/development/compose.py | 8 ++ cli/administration/deploy/development/env.py | 6 + .../deploy/development/runner_mirror.py | 68 +++++++++++ cli/contributing/mirror/README.md | 2 + cli/contributing/mirror/sync/__main__.py | 8 +- cli/contributing/mirror/wait/__main__.py | 8 +- .../deploy/development/test_compose.py | 8 +- .../deploy/development/test_runner_mirror.py | 107 ++++++++++++++++++ .../cli/contributing/mirror/test_sync.py | 41 +++++++ .../cli/contributing/mirror/test_wait.py | 56 +++++++++ .../python/utils/docker/test_runner_images.py | 78 +++++++++++++ utils/docker/image/discovery.py | 53 ++++++++- 13 files changed, 436 insertions(+), 8 deletions(-) create mode 100644 cli/administration/deploy/development/runner_mirror.py create mode 100644 tests/unit/python/cli/administration/deploy/development/test_runner_mirror.py create mode 100644 tests/unit/python/cli/contributing/mirror/test_wait.py create mode 100644 tests/unit/python/utils/docker/test_runner_images.py diff --git a/.github/workflows/call-orchestrator.yml b/.github/workflows/call-orchestrator.yml index 76c0812b4f..b311f7c6cd 100644 --- a/.github/workflows/call-orchestrator.yml +++ b/.github/workflows/call-orchestrator.yml @@ -141,6 +141,7 @@ jobs: test-dns: needs: - build-ci-images + - images-mirror-missing - validate-selection uses: ./.github/workflows/call-test-dns.yml with: diff --git a/cli/administration/deploy/development/compose.py b/cli/administration/deploy/development/compose.py index 682c955d3a..3905356f7e 100644 --- a/cli/administration/deploy/development/compose.py +++ b/cli/administration/deploy/development/compose.py @@ -10,10 +10,13 @@ from .env import compose_file_args from .network import detect_outer_network_mtu from .proc import run_streaming from .profile import Profile +from .runner_mirror import env_image if TYPE_CHECKING: from pathlib import Path +INIT_IMAGE_KEY = "INFINITO_CACHE_PACKAGE_FRONTEND_INIT_IMAGE" + class Compose: """Wrapper around `docker compose` for the dev/CI stack.""" @@ -135,6 +138,11 @@ class Compose: / "package-frontend" / "certs.sh" ) + if self.profile.image_mirror_enabled(): + env = { + **env, + INIT_IMAGE_KEY: env_image(self.repo_root, INIT_IMAGE_KEY), + } print(">>> Generating package-cache-frontend CA + per-hostname certs") subprocess.run( [str(helper)], diff --git a/cli/administration/deploy/development/env.py b/cli/administration/deploy/development/env.py index f22b27622f..c5c705cb44 100644 --- a/cli/administration/deploy/development/env.py +++ b/cli/administration/deploy/development/env.py @@ -27,6 +27,12 @@ def compose_file_args() -> list[str]: out += ["-f", "compose/cache.shared.override.yml"] if (os.environ.get("INFINITO_PUBLISH_PORTS") or "").strip().lower() == "false": out += ["-f", "compose/noports.override.yml"] + if profile.image_mirror_enabled(): + from utils.cache.files import PROJECT_ROOT + + from .runner_mirror import write_override + + out += ["-f", write_override(PROJECT_ROOT, out[1::2])] return out diff --git a/cli/administration/deploy/development/runner_mirror.py b/cli/administration/deploy/development/runner_mirror.py new file mode 100644 index 0000000000..ced2b8fbbe --- /dev/null +++ b/cli/administration/deploy/development/runner_mirror.py @@ -0,0 +1,68 @@ +"""Point the images the CI runner pulls itself at their GHCR mirror.""" + +from __future__ import annotations + +import os +from typing import TYPE_CHECKING + +from cli.contributing.mirror.providers import GHCRProvider +from utils.cache.yaml import dump_yaml +from utils.docker.image.discovery import iter_runner_images + +if TYPE_CHECKING: + from pathlib import Path + +OVERRIDE = "build/compose/runner-mirror.override.yml" + + +def mirrored_images(repo_root: Path) -> dict[tuple[str, str], str]: + """Return ``{(source_file, service): mirror reference}`` for every runner image. + + Args: + repo_root: repository root the runner images are declared under. + """ + provider = GHCRProvider( + os.environ["GITHUB_REPOSITORY_OWNER"], + os.environ["GITHUB_REPOSITORY"].split("/", 1)[-1], + os.environ["INFINITO_GHCR_MIRROR_PREFIX"], + ) + return { + ( + image.source_file, + image.service, + ): f"{provider.image_base(image)}:{image.version}" + for image in iter_runner_images(repo_root) + } + + +def write_override(repo_root: Path, layered: list[str]) -> str: + """Write the compose override that swaps the runner's images for mirrors. + + Args: + repo_root: repository root the compose files are relative to. + layered: compose files the stack is built from. Only their services + are overridden, so the override never adds a service of its own. + + Returns: + The override path relative to ``repo_root``. + """ + services = { + service: {"image": reference} + for (source_file, service), reference in mirrored_images(repo_root).items() + if source_file in layered + } + target = repo_root / OVERRIDE + staging = target.with_name(f"{target.name}.{os.getpid()}") + dump_yaml(staging, {"services": services}) + staging.replace(target) + return OVERRIDE + + +def env_image(repo_root: Path, key: str) -> str: + """Return the mirror reference for an image ``default.env`` declares. + + Args: + repo_root: repository root holding ``default.env``. + key: the ``default.env`` key naming the image. + """ + return mirrored_images(repo_root)[("default.env", key)] diff --git a/cli/contributing/mirror/README.md b/cli/contributing/mirror/README.md index af6a5f8ae0..36f1b3bc47 100644 --- a/cli/contributing/mirror/README.md +++ b/cli/contributing/mirror/README.md @@ -1,3 +1,5 @@ # Mirror 🪞 Plan and execute the GHCR image mirror pipeline: emit the `mirrors.yml` mapping that redirects role-declared images to the GHCR mirror, push images upstream-to-GHCR, and clean up stale mirror packages. + +The sync also mirrors the images the CI runner pulls itself, outside every role: the tagged `image` literals of `compose.yml` and `compose/cache.override.yml`, and the image keys of `default.env` listed in `RUNNER_ENV_IMAGES` ([discovery.py](../../../utils/docker/image/discovery.py)). On a GitHub runner, [runner_mirror.py](../../administration/deploy/development/runner_mirror.py) layers a generated compose override that points those services at their mirror, and hands the certificate generator the mirrored init image. diff --git a/cli/contributing/mirror/sync/__main__.py b/cli/contributing/mirror/sync/__main__.py index b7a892c9cf..2212f332db 100644 --- a/cli/contributing/mirror/sync/__main__.py +++ b/cli/contributing/mirror/sync/__main__.py @@ -4,10 +4,11 @@ import argparse import subprocess import sys import time +from itertools import chain from pathlib import Path from cli.contributing.mirror.providers import GHCRProvider -from utils.docker.image.discovery import iter_role_images +from utils.docker.image.discovery import iter_role_images, iter_runner_images def _validate_positive_int(value: str) -> int: @@ -52,7 +53,8 @@ def _throttle_before_next_copy( def main() -> int: parser = argparse.ArgumentParser( description=( - "Mirror every role-declared image to the configured GHCR registry, " + "Mirror every role-declared image and every image the CI runner " + "pulls itself to the configured GHCR registry, " "optionally throttled and optionally skipping already-mirrored " "tags." ), @@ -80,7 +82,7 @@ def main() -> int: last_start_ts: float | None = None - for img in iter_role_images(repo_root): + for img in chain(iter_role_images(repo_root), iter_runner_images(repo_root)): last_start_ts = _throttle_before_next_copy( images_per_hour=args.images_per_hour, last_start_ts=last_start_ts, diff --git a/cli/contributing/mirror/wait/__main__.py b/cli/contributing/mirror/wait/__main__.py index 9f3d911ccd..85769b2f7c 100644 --- a/cli/contributing/mirror/wait/__main__.py +++ b/cli/contributing/mirror/wait/__main__.py @@ -3,10 +3,11 @@ from __future__ import annotations import argparse import sys import time +from itertools import chain from pathlib import Path from cli.contributing.mirror.providers import GHCRProvider -from utils.docker.image.discovery import ImageRef, iter_role_images +from utils.docker.image.discovery import ImageRef, iter_role_images, iter_runner_images def _validate_positive_int(value: str) -> int: @@ -22,7 +23,8 @@ def _validate_positive_int(value: str) -> int: def main() -> int: parser = argparse.ArgumentParser( description=( - "Wait until every role-declared image has been mirrored to the " + "Wait until every role-declared image and every image the CI runner " + "pulls itself has been mirrored to the " "configured GHCR registry. Used on fork pull_request runs that depend " "on a pull_request_target mirror job populating the destination first." ), @@ -47,7 +49,7 @@ def main() -> int: repo_root = Path(args.repo_root).resolve() refs: dict[str, ImageRef] = {} - for img in iter_role_images(repo_root): + for img in chain(iter_role_images(repo_root), iter_runner_images(repo_root)): refs.setdefault(f"{provider.image_base(img)}:{img.version}", img) total = len(refs) diff --git a/tests/unit/python/cli/administration/deploy/development/test_compose.py b/tests/unit/python/cli/administration/deploy/development/test_compose.py index 9e878575e5..db5b966ab6 100644 --- a/tests/unit/python/cli/administration/deploy/development/test_compose.py +++ b/tests/unit/python/cli/administration/deploy/development/test_compose.py @@ -98,9 +98,13 @@ class TestComposeUpRetries(unittest.TestCase): }, clear=False, ) + @patch( + "cli.administration.deploy.development.runner_mirror.write_override", + return_value="build/compose/runner-mirror.override.yml", + ) @patch("subprocess.run", autospec=True) def test_run_skips_cache_override_on_github_runner( - self, run_mock: MagicMock + self, run_mock: MagicMock, _write_override: MagicMock ) -> None: compose = self._compose() @@ -126,6 +130,8 @@ class TestComposeUpRetries(unittest.TestCase): "compose", "-f", "compose.yml", + "-f", + "build/compose/runner-mirror.override.yml", "ps", "-q", "infinito", diff --git a/tests/unit/python/cli/administration/deploy/development/test_runner_mirror.py b/tests/unit/python/cli/administration/deploy/development/test_runner_mirror.py new file mode 100644 index 0000000000..cb9763515a --- /dev/null +++ b/tests/unit/python/cli/administration/deploy/development/test_runner_mirror.py @@ -0,0 +1,107 @@ +from __future__ import annotations + +import os +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +from cli.administration.deploy.development import runner_mirror +from cli.administration.deploy.development.compose import INIT_IMAGE_KEY, Compose +from cli.administration.deploy.development.env import compose_file_args +from utils.cache.files import PROJECT_ROOT +from utils.cache.yaml import load_yaml_any + +GITHUB = { + "GITHUB_REPOSITORY_OWNER": "Acme", + "GITHUB_REPOSITORY": "Acme/Core", + "INFINITO_GHCR_MIRROR_PREFIX": "mirror", +} + +COMPOSE = """\ +services: + coredns: + image: coredns/coredns:1.14.4 +""" + +CACHE_OVERRIDE = """\ +services: + package-cache-frontend: + image: nginx:1.27-alpine +""" + + +def _repo(root: Path) -> Path: + (root / "compose").mkdir() + (root / "compose.yml").write_text(COMPOSE) + (root / "compose" / "cache.override.yml").write_text(CACHE_OVERRIDE) + (root / "default.env").write_text( + "INFINITO_CACHE_PACKAGE_FRONTEND_INIT_IMAGE=alpine:latest\n" + ) + return root + + +class TestRunnerMirror(unittest.TestCase): + @patch.dict(os.environ, GITHUB, clear=False) + def test_the_override_covers_only_services_of_layered_files(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = _repo(Path(tmp)) + relative = runner_mirror.write_override(root, ["compose.yml"]) + written = load_yaml_any(str(root / relative), default_if_missing={}) + self.assertEqual( + written, + { + "services": { + "coredns": { + "image": "ghcr.io/acme/core/mirror/docker.io/coredns/coredns:1.14.4" + } + } + }, + ) + + @patch.dict(os.environ, GITHUB, clear=False) + def test_the_init_image_resolves_to_its_mirror(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + reference = runner_mirror.env_image( + _repo(Path(tmp)), "INFINITO_CACHE_PACKAGE_FRONTEND_INIT_IMAGE" + ) + self.assertEqual(reference, "ghcr.io/acme/core/mirror/docker.io/alpine:latest") + + @patch.dict( + os.environ, + { + **GITHUB, + "INFINITO_RUNNING_ON_GITHUB": "true", + "INFINITO_GIT_COMMON_DIR": "", + "INFINITO_CACHE_STACK": "", + "INFINITO_CACHE_NETWORK": "", + "INFINITO_PUBLISH_PORTS": "", + }, + clear=False, + ) + def test_a_github_runner_layers_the_mirror_override_last(self) -> None: + with patch.object( + runner_mirror, "write_override", return_value=runner_mirror.OVERRIDE + ) as write: + args = compose_file_args() + write.assert_called_once_with(PROJECT_ROOT, ["compose.yml"]) + self.assertEqual(args[-2:], ["-f", runner_mirror.OVERRIDE]) + + @patch.dict( + os.environ, {**GITHUB, "INFINITO_RUNNING_ON_GITHUB": "true"}, clear=False + ) + def test_the_cert_generator_gets_the_mirrored_init_image(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + compose = Compose(_repo(Path(tmp)), "arch") + with patch("subprocess.run") as run: + compose._generate_package_frontend_certs( + {INIT_IMAGE_KEY: "alpine:latest"} + ) + self.assertEqual( + run.call_args.kwargs["env"][INIT_IMAGE_KEY], + "ghcr.io/acme/core/mirror/docker.io/alpine:latest", + ) + + +if __name__ == "__main__": # pragma: no cover + unittest.main() diff --git a/tests/unit/python/cli/contributing/mirror/test_sync.py b/tests/unit/python/cli/contributing/mirror/test_sync.py index 5aed8e86ef..2f8860eb69 100644 --- a/tests/unit/python/cli/contributing/mirror/test_sync.py +++ b/tests/unit/python/cli/contributing/mirror/test_sync.py @@ -23,6 +23,10 @@ class TestMirrorSync(unittest.TestCase): "cli.contributing.mirror.sync.__main__.iter_role_images", return_value=[image], ), + patch( + "cli.contributing.mirror.sync.__main__.iter_runner_images", + return_value=[], + ), patch.object( sync_main.GHCRProvider, "image_base", @@ -50,6 +54,43 @@ class TestMirrorSync(unittest.TestCase): mock_tag_exists.assert_called_once_with(image) mock_mirror.assert_not_called() + def test_runner_images_are_mirrored_with_the_role_images(self) -> None: + image = ImageRef( + role="runner", + service="coredns", + name="coredns/coredns", + version="1.14.4", + source="docker.io/coredns/coredns:1.14.4", + registry="docker.io", + source_file="compose.yml", + ) + + with ( + patch( + "cli.contributing.mirror.sync.__main__.iter_role_images", + return_value=[], + ), + patch( + "cli.contributing.mirror.sync.__main__.iter_runner_images", + return_value=[image], + ), + patch.object(sync_main.GHCRProvider, "mirror") as mock_mirror, + patch( + "sys.argv", + [ + "mirror-sync", + "--ghcr-namespace", + "acme", + "--ghcr-repository", + "myrepo", + ], + ), + ): + result = sync_main.main() + + self.assertEqual(result, 0) + mock_mirror.assert_called_once_with(image) + if __name__ == "__main__": # pragma: no cover unittest.main() diff --git a/tests/unit/python/cli/contributing/mirror/test_wait.py b/tests/unit/python/cli/contributing/mirror/test_wait.py new file mode 100644 index 0000000000..6467cfadfb --- /dev/null +++ b/tests/unit/python/cli/contributing/mirror/test_wait.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +import unittest +from unittest.mock import patch + +import cli.contributing.mirror.wait.__main__ as wait_main +from cli.contributing.mirror.model import ImageRef + + +class TestMirrorWait(unittest.TestCase): + def test_a_missing_runner_mirror_keeps_the_wait_open(self) -> None: + image = ImageRef( + role="runner", + service="coredns", + name="coredns/coredns", + version="1.14.4", + source="docker.io/coredns/coredns:1.14.4", + registry="docker.io", + source_file="compose.yml", + ) + + with ( + patch( + "cli.contributing.mirror.wait.__main__.iter_role_images", + return_value=[], + ), + patch( + "cli.contributing.mirror.wait.__main__.iter_runner_images", + return_value=[image], + ), + patch.object( + wait_main.GHCRProvider, "tag_exists", return_value=False + ) as tag_exists, + patch( + "sys.argv", + [ + "mirror-wait", + "--ghcr-namespace", + "acme", + "--ghcr-repository", + "myrepo", + "--attempts", + "1", + "--sleep-seconds", + "1", + ], + ), + ): + result = wait_main.main() + + self.assertEqual(result, 1) + tag_exists.assert_called_once_with(image) + + +if __name__ == "__main__": # pragma: no cover + unittest.main() diff --git a/tests/unit/python/utils/docker/test_runner_images.py b/tests/unit/python/utils/docker/test_runner_images.py new file mode 100644 index 0000000000..48787e736e --- /dev/null +++ b/tests/unit/python/utils/docker/test_runner_images.py @@ -0,0 +1,78 @@ +from __future__ import annotations + +import tempfile +import unittest +from pathlib import Path + +from utils.cache.files import PROJECT_ROOT +from utils.docker.image.discovery import iter_runner_images + +COMPOSE = """\ +services: + coredns: + image: coredns/coredns:1.14.4 + infinito: + build: + context: . + interpolated: + image: ${INFINITO_IMAGE} + untagged: + image: busybox + pinned: + image: nginx@sha256:d5591131b1d898cd02fc7a17adb8ea026352d67809bc9289707778e9e03a76a4 +""" + +CACHE_OVERRIDE = """\ +services: + package-cache-frontend: + image: nginx:1.27-alpine +""" + +DEFAULT_ENV = "INFINITO_CACHE_PACKAGE_FRONTEND_INIT_IMAGE=alpine:latest\n" + + +def _repo(root: Path) -> Path: + (root / "compose").mkdir() + (root / "compose.yml").write_text(COMPOSE) + (root / "compose" / "cache.override.yml").write_text(CACHE_OVERRIDE) + (root / "default.env").write_text(DEFAULT_ENV) + return root + + +class TestRunnerImages(unittest.TestCase): + def test_tagged_literals_and_the_init_image_are_found(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + found = [ + (image.source_file, image.service, image.source) + for image in iter_runner_images(_repo(Path(tmp))) + ] + self.assertEqual( + found, + [ + ("compose.yml", "coredns", "docker.io/coredns/coredns:1.14.4"), + ( + "compose/cache.override.yml", + "package-cache-frontend", + "docker.io/library/nginx:1.27-alpine", + ), + ( + "default.env", + "INFINITO_CACHE_PACKAGE_FRONTEND_INIT_IMAGE", + "docker.io/library/alpine:latest", + ), + ], + ) + + def test_the_repository_declares_coredns_where_the_runner_reads_it(self) -> None: + services = { + (image.source_file, image.service) + for image in iter_runner_images(PROJECT_ROOT) + } + self.assertIn(("compose.yml", "coredns"), services) + self.assertIn( + ("default.env", "INFINITO_CACHE_PACKAGE_FRONTEND_INIT_IMAGE"), services + ) + + +if __name__ == "__main__": # pragma: no cover + unittest.main() diff --git a/utils/docker/image/discovery.py b/utils/docker/image/discovery.py index 559003e0e7..3246b8fdd5 100644 --- a/utils/docker/image/discovery.py +++ b/utils/docker/image/discovery.py @@ -51,7 +51,8 @@ class ImageRef: version: e.g. ``17-3.5`` source: full pull ref, e.g. ``docker.io/library/postgres:16`` registry: source registry hostname, e.g. ``docker.io``, ``quay.io`` - source_file: role-relative file the ref was read from + source_file: file the ref was read from, role-relative for a role + image and repository-relative for a ``runner`` image """ role: str @@ -225,3 +226,53 @@ def iter_role_images(repo_root: Path) -> Iterable[ImageRef]: registry=_detect_registry(image), source_file=ROLE_FILE_META_SERVICES, ) + + +RUNNER_ROLE = "runner" +RUNNER_COMPOSE_FILES = ("compose.yml", "compose/cache.override.yml") +RUNNER_ENV_IMAGES = ("INFINITO_CACHE_PACKAGE_FRONTEND_INIT_IMAGE",) + + +def _runner_image(service: str, image: str, source_file: str) -> ImageRef | None: + base, suffix = split_name_and_suffix(image) + if not suffix.startswith(":") or not is_mirrorable_image(base): + return None + version = suffix[1:] + return ImageRef( + role=RUNNER_ROLE, + service=service, + name=canonical_image_name(base), + version=version, + source=image_source(base, version), + registry=_detect_registry(base), + source_file=source_file, + ) + + +def iter_runner_images(repo_root: Path) -> Iterable[ImageRef]: + """Yield the images the CI runner pulls itself, outside every role. + + Args: + repo_root: repository root holding the RUNNER_COMPOSE_FILES and + ``default.env``. A compose ``image`` that interpolates a variable, + carries no tag or is pinned by digest yields nothing. + """ + from utils.env.parser import parse_static_env + + for source_file in RUNNER_COMPOSE_FILES: + services = load_yaml(repo_root / source_file).get("services") or {} + for service, spec in services.items(): + image = ( + str(spec.get("image") or "").strip() if isinstance(spec, dict) else "" + ) + if not image or "${" in image: + continue + ref = _runner_image(str(service), image, source_file) + if ref is not None: + yield ref + + declared = parse_static_env(repo_root / "default.env") + for key in RUNNER_ENV_IMAGES: + ref = _runner_image(key, declared[key], "default.env") + if ref is not None: + yield ref