diff --git a/.github/workflows/cron-update.yml b/.github/workflows/cron-update.yml index 9be204fb75..e4ae9aebff 100644 --- a/.github/workflows/cron-update.yml +++ b/.github/workflows/cron-update.yml @@ -65,6 +65,53 @@ jobs: UPDATE_BASE_BRANCH: main run: bash scripts/github/update/open/role_prs.sh roles + update-compose-image-versions: + name: 🐳 Update compose file image versions + if: vars.CI_ENABLE_AUTO_UPDATES == 'true' + runs-on: ubuntu-26.04 + steps: + - name: ⬇️ Checkout + uses: actions/checkout@v7.0.0 + with: + ref: main + + - name: 🔧 Set up Python + uses: actions/setup-python@v6 + with: + python-version: "3.12" + cache: pip + cache-dependency-path: pyproject.toml + + - name: 📦 Install update dependencies + run: bash scripts/github/update/install_python.sh + + - name: 🔄 Update compose file image versions + run: bash scripts/github/update/image_versions.sh --compose + + - name: 🔎 Check for changes + id: diff + run: bash scripts/github/resolve/check_git_changes.sh '*.yml' '*.yaml' + + - name: ⚙️ Generate app token + if: steps.diff.outputs.changed == 'true' + id: app-token + uses: actions/create-github-app-token@v3 + with: + client-id: ${{ secrets.BOT_APP_CLIENT_ID }} + private-key: ${{ secrets.BOT_APP_PRIVATE_KEY }} + + - name: 📂 Open PR if compose file image versions changed + if: steps.diff.outputs.changed == 'true' + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + APP_SLUG: ${{ steps.app-token.outputs.app-slug }} + UPDATE_BRANCH_PREFIX: update/compose-image-versions + UPDATE_COMMIT_MESSAGE: "update(images): update Docker image versions (compose)" + UPDATE_PR_TITLE: "update(images): update Docker image versions (compose)" + UPDATE_PR_BODY: "Automated update of the semver-tagged `image:` literals in the tracked YAML files that hold a compose `services:` mapping, under the version policy of `roles/*/meta/services.yml`. Files the Dependabot docker-compose ecosystem covers stay with Dependabot." + UPDATE_BASE_BRANCH: main + run: bash scripts/github/update/open/pr.sh '*.yml' '*.yaml' + update-version-sources: name: 🔖 Update declared version sources if: vars.CI_ENABLE_AUTO_UPDATES == 'true' diff --git a/cli/contributing/update/README.md b/cli/contributing/update/README.md index 7b84af11d0..0b933bf733 100644 --- a/cli/contributing/update/README.md +++ b/cli/contributing/update/README.md @@ -6,6 +6,18 @@ Repository-side version maintenance: scan role configuration files for declared Every role-scoped updater (`docker`, `source`, `pip`, `repository`) and the addon check skip a role whose [lifecycle](../../../docs/contributing/design/role/services/lifecycle.md) is `eol`: no update PR is opened for it and no external test warns about its pins. +## Docker images + +`python -m cli.contributing.update.docker` bumps the semver `version:` of every `image` in `roles/*/meta/services.yml`; with `--compose` it bumps the tag of every `image:` literal in the compose files instead, under the same version policy (same depth and flavor, release groups held per file, `# nocheck: docker-version` above `image:` freezes a pin). + +A compose file is recognized by its content, not its name: a tracked `.yml` or `.yaml` file whose top level holds a `services` mapping with at least one `image` string. An `image:` that interpolates a variable, carries no tag or is pinned by digest is left alone. Three kinds of file never reach the compose updater: + +- Jinja templates (`*.j2`): role templates render `image:` from the `meta/services.yml` pins the role updater owns. +- Fixtures under `tests/`: their pins are test input, not a deployment. +- Files named like a Dependabot `docker-compose` manifest (`compose.yml`, `compose.yaml`, `docker-compose.yml`, `docker-compose.yaml`): Dependabot already bumps them, so a second updater would open a second PR for the same pin. + +`roles/*/meta/services.yml` holds no top-level `services` mapping, so no pin is updated by both updaters. The `update-compose-image-versions` job of `.github/workflows/cron-update.yml` opens one PR for all compose files on its own `update/compose-image-versions-` branch, and `scripts/github/update/open/pr.sh` skips it while an open PR on that prefix carries the same change. + ## Repository refs `python -m cli.contributing.update.repository` bumps every `ref:` that sits next to a `repository:` in `roles/*/meta/services.yml` or `roles/*/meta/addons/*.yml`, at any depth, an addon's `config` included: diff --git a/cli/contributing/update/docker/__main__.py b/cli/contributing/update/docker/__main__.py index c7188568ab..29765c801a 100755 --- a/cli/contributing/update/docker/__main__.py +++ b/cli/contributing/update/docker/__main__.py @@ -4,7 +4,12 @@ from __future__ import annotations import argparse from pathlib import Path -from utils.update.docker import apply_updates, find_outdated_updates +from utils.cache.files import repository_files +from utils.update.docker import ( + apply_updates, + find_outdated_compose_updates, + find_outdated_updates, +) from . import PROJECT_ROOT @@ -13,6 +18,14 @@ def main() -> int: parser = argparse.ArgumentParser( description="Update semver-based Docker image versions in roles/*/meta/services.yml." ) + parser.add_argument( + "--compose", + action="store_true", + help=( + "Update the image tags of the tracked YAML files holding a compose " + "'services' mapping instead" + ), + ) parser.add_argument( "--repo-root", type=Path, @@ -27,7 +40,11 @@ def main() -> int: args = parser.parse_args() repo_root = args.repo_root.resolve() - updates = find_outdated_updates(repo_root) + updates = ( + find_outdated_compose_updates(repo_root, repository_files()) + if args.compose + else find_outdated_updates(repo_root) + ) if not updates: print("Docker image versions are already up to date.") diff --git a/tests/integration/meta/workflows/test_cron_update_compose.py b/tests/integration/meta/workflows/test_cron_update_compose.py new file mode 100644 index 0000000000..fbd807d98b --- /dev/null +++ b/tests/integration/meta/workflows/test_cron_update_compose.py @@ -0,0 +1,219 @@ +from __future__ import annotations + +import fnmatch +import os +import shlex +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +from utils.cache.files import repository_files +from utils.cache.yaml import load_yaml_any +from utils.update.docker import collect_entries, compose_files + +from . import PROJECT_ROOT + +WORKFLOW = PROJECT_ROOT / ".github" / "workflows" / "cron-update.yml" +JOB = "update-compose-image-versions" +UPDATE = "scripts/github/update/image_versions.sh" +CHECK = "scripts/github/resolve/check_git_changes.sh" +OPEN_PR = "scripts/github/update/open/pr.sh" +EXEMPLAR = "compose/cache.override.yml" +UNTOUCHED = ".pre-commit-config.yaml" +PINNED = "services:\n registry-cache:\n image: rpardini/docker-registry-proxy:{}\n" +GH_STUB = r"""#!/usr/bin/env bash +printf '%s\n' "$*" >> "${GH_STUB_LOG}" +if [[ "$1 $2" == "pr list" ]]; then + prefix="$(printf '%s' "$*" | sed -nE 's/.*startswith\("([^"]+)"\).*/\1/p')" + if [[ -n "${prefix}" && "${GH_STUB_BRANCH}" == "${prefix}"* ]]; then + printf '7\tfalse\t%s\n' "${GH_STUB_BRANCH}" + fi +fi +""" + + +def _jobs() -> dict: + return load_yaml_any(str(WORKFLOW))["jobs"] + + +def _step(job: dict, script: str) -> dict: + return next(step for step in job["steps"] if script in str(step.get("run", ""))) + + +def _args(step: dict, script: str) -> list[str]: + argv = shlex.split(step["run"]) + return argv[argv.index(script) + 1 :] + + +def _prefixes() -> dict[str, str]: + return { + name: step["env"]["UPDATE_BRANCH_PREFIX"] + for name, job in _jobs().items() + for step in job.get("steps", []) + if "UPDATE_BRANCH_PREFIX" in (step.get("env") or {}) + } + + +def _owned() -> list[str]: + return compose_files(PROJECT_ROOT, repository_files()) + + +class TestComposeUpdateJob(unittest.TestCase): + def test_compose_bumps_open_one_pr_on_a_branch_prefix_of_their_own(self): + job = _jobs()[JOB] + self.assertEqual(_args(_step(job, UPDATE), UPDATE), ["--compose"]) + self.assertIn(OPEN_PR, _step(job, OPEN_PR)["run"]) + prefixes = _prefixes() + own = prefixes.pop(JOB) + clashes = { + name: prefix + for name, prefix in prefixes.items() + if prefix.startswith(own) or own.startswith(prefix) + } + self.assertEqual(clashes, {}) + + def test_the_change_check_and_the_pr_cover_every_compose_file(self): + job = _jobs()[JOB] + pathspecs = _args(_step(job, OPEN_PR), OPEN_PR) + self.assertEqual(_args(_step(job, CHECK), CHECK), pathspecs) + owned = _owned() + self.assertIn(EXEMPLAR, owned) + self.assertEqual( + [ + rel + for rel in owned + if not any(fnmatch.fnmatchcase(rel, spec) for spec in pathspecs) + ], + [], + ) + + def test_no_file_is_bumped_by_both_docker_updaters(self): + role_files = { + entry.config_path.relative_to(PROJECT_ROOT).as_posix() + for entry in collect_entries(PROJECT_ROOT) + } + self.assertTrue(role_files) + self.assertEqual(set(_owned()) & role_files, set()) + + +class ComposePrFixture: + """A throwaway repo whose compose pin the job bumped, run through the job's PR step. + + Args: + tmp: directory that holds the repo and the ``gh`` stub. + """ + + def __init__(self, tmp: str) -> None: + self.repo = Path(tmp) / "repo" + stub_dir = Path(tmp) / "bin" + stub_dir.mkdir() + stub = stub_dir / "gh" + stub.write_text(GH_STUB) + stub.chmod(0o755) + self.step = _step(_jobs()[JOB], OPEN_PR) + self.prefix = self.step["env"]["UPDATE_BRANCH_PREFIX"] + inherited = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")} + job_env = { + key: value + for key, value in self.step["env"].items() + if key not in {"GH_TOKEN", "APP_SLUG"} + } + self.env = { + **inherited, + **job_env, + "PATH": os.pathsep.join( + [str(stub_dir), str(Path(sys.executable).parent), os.environ["PATH"]] + ), + "PYTHONPATH": str(PROJECT_ROOT), + "GH_STUB_LOG": str(Path(tmp) / "gh.log"), + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ALLOW_PROTOCOL": "file", + "GH_TOKEN": "unused", + "UPDATE_BRANCH_SUFFIX": "20261123", + } + pinned = self.repo / EXEMPLAR + pinned.parent.mkdir(parents=True) + self.git("init", "-b", "main") + self.git("remote", "add", "origin", "https://github.com/acme/widgets.git") + pinned.write_text(PINNED.format("0.6.5")) + (self.repo / UNTOUCHED).write_text("repos: []\n") + self.git("add", "-A") + self.git( + "-c", + "user.name=test", + "-c", + "user.email=test@example.invalid", + "commit", + "-m", + "init", + ) + pinned.write_text(PINNED.format("0.8.0")) + + def git(self, *args: str, stdin: str | None = None) -> str: + return subprocess.run( + ["git", *args], + cwd=self.repo, + env=self.env, + input=stdin, + capture_output=True, + text=True, + check=True, + ).stdout.strip() + + def fingerprint(self) -> str: + blob = self.git("hash-object", EXEMPLAR) + return self.git("hash-object", "--stdin", stdin=f"{blob}\t{EXEMPLAR}\n") + + def open_pr(self, open_branch: str) -> subprocess.CompletedProcess: + """Run the job's PR step while ``gh`` knows one open PR. + + Args: + open_branch: head branch of that PR; ``gh`` lists it only when it + starts with the prefix the step filters on. + """ + return subprocess.run( + ["bash", str(PROJECT_ROOT / OPEN_PR), *_args(self.step, OPEN_PR)], + cwd=self.repo, + env={**self.env, "GH_STUB_BRANCH": open_branch}, + capture_output=True, + text=True, + check=False, + ) + + +class TestComposePrDedupe(unittest.TestCase): + def test_an_open_pr_carrying_the_same_bump_is_not_opened_again(self): + with tempfile.TemporaryDirectory() as tmp: + fixture = ComposePrFixture(tmp) + fp = fixture.fingerprint()[:7] + result = fixture.open_pr(f"{fixture.prefix}-20261122-{fp}") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn("Open PR #7 already carries this exact change", result.stdout) + self.assertNotIn("Pushing change to branch", result.stdout) + + def test_an_open_role_pr_does_not_hold_back_the_compose_pr(self): + with tempfile.TemporaryDirectory() as tmp: + fixture = ComposePrFixture(tmp) + fp = fixture.fingerprint()[:7] + role_branch = f"update/docker-image-versions-svc-x-20261122-{fp}" + result = fixture.open_pr(role_branch) + self.assertNotIn("already carries this exact change", result.stdout) + self.assertIn( + f"Pushing change to branch {fixture.prefix}-20261123-{fp}", result.stdout + ) + + def test_an_open_pr_of_another_bump_does_not_hold_back_this_one(self): + with tempfile.TemporaryDirectory() as tmp: + fixture = ComposePrFixture(tmp) + fp = fixture.fingerprint()[:7] + result = fixture.open_pr(f"{fixture.prefix}-20261122-0000000") + self.assertIn("head unfetchable; treating as non-duplicate", result.stdout) + self.assertIn( + f"Pushing change to branch {fixture.prefix}-20261123-{fp}", result.stdout + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/integration/meta/workflows/test_dependabot_coverage.py b/tests/integration/meta/workflows/test_dependabot_coverage.py index f3ec8faa4c..fec5a5dcba 100644 --- a/tests/integration/meta/workflows/test_dependabot_coverage.py +++ b/tests/integration/meta/workflows/test_dependabot_coverage.py @@ -7,6 +7,7 @@ from pathlib import Path from utils.cache.files import iter_non_ignored_files, read_text from utils.cache.yaml import load_yaml_any +from utils.update.docker import DEPENDABOT_COMPOSE_FILES from . import PROJECT_ROOT @@ -69,12 +70,7 @@ ECOSYSTEM_FILENAME_INDICATORS: dict[str, list[str]] = { "helm": ["Chart.yaml"], "pre-commit": [".pre-commit-config.yaml"], "docker": ["Dockerfile", "*.dockerfile", "Dockerfile.*"], - "docker-compose": [ - "docker-compose.yml", - "docker-compose.yaml", - "compose.yml", - "compose.yaml", - ], + "docker-compose": [*DEPENDABOT_COMPOSE_FILES], } # Mapping: Dependabot ecosystem name → repository-relative path patterns diff --git a/tests/unit/python/utils/update/test_docker_compose.py b/tests/unit/python/utils/update/test_docker_compose.py new file mode 100644 index 0000000000..c923119490 --- /dev/null +++ b/tests/unit/python/utils/update/test_docker_compose.py @@ -0,0 +1,389 @@ +from __future__ import annotations + +import os +import re +import tempfile +import unittest +import unittest.mock as mock +from pathlib import Path + +from utils.cache.files import PROJECT_ROOT, read_text +from utils.cache.reset import _reset_cache_for_tests +from utils.docker.image.discovery import RUNNER_ROLE +from utils.roles.mapping import ROLE_FILE_META_SERVICES, ROLE_FILE_TEMPL_COMPOSE +from utils.update import docker + +COMPOSE = """\ +--- +x-ci-defaults: &ci_defaults + dns_opt: + - ndots:1 + +services: + coredns: + image: coredns/coredns:1.14.4 + command: ["-conf", "/Corefile"] + infinito: + <<: *ci_defaults + image: "${INFINITO_IMAGE}" +""" + +CACHE_OVERRIDE = """\ +--- +# Layered on compose.yml by the dev tooling. + +services: + registry-cache: + image: rpardini/docker-registry-proxy:0.6.5 + container_name: infinito-registry-cache + package-cache: + image: "sonatype/nexus3:3.91.1-ubi" # Keep comment + package-cache-frontend: + image: nginx:1.27-alpine + frozen: + # nocheck: docker-version upstream dropped the arm64 build + image: busybox:1.36.1 + moving: + image: alpine:latest + untagged: + image: busybox + pinned: + image: nginx@sha256:d5591131b1d898cd02fc7a17adb8ea026352d67809bc9289707778e9e03a76a4 + interpolated: + image: "${INFINITO_IMAGE}:1.0.0" +""" + +STACK = """\ +services: + mirror: + image: registry:2.8.3 + restart: unless-stopped +""" + +SWARM = """\ +x-node: &node + image: infinito-swarm-node +services: + manager: + <<: *node +""" + +PLAYBOOK = """\ +--- +- name: a playbook, not a compose file + command: /bin/true +""" + +HARNESS = """\ +services: + outside: + image: postgres:16.4 +""" + +TEMPLATE = """\ +services: + registry: + image: "{{ REGISTRY_IMAGE }}:{{ REGISTRY_VERSION }}" + literal: + image: redis:7.4.1 +""" + +SERVICES = """\ +moodle: + image: bitnamilegacy/moodle + version: "4.5" +services: + image: redis + version: "7.4.1" +""" + +SYMFONY = """\ +services: + _defaults: + autowire: true + session.handler: + class: Symfony\\Component\\HttpFoundation\\Session\\Storage\\Handler\\PdoSessionHandler +""" + +TWO_DOCUMENTS = """\ +services: + first: + image: redis:7.4.1 +--- +services: + second: + image: redis:7.4.1 +""" + +UNPARSABLE = """\ +services: + broken: [redis:7.4.1 +""" + +TRACKED = { + "compose.yml": COMPOSE, + "compose/cache.override.yml": CACHE_OVERRIDE, + "compose/swarm/compose.yml": SWARM, + "compose/swarm/playbook.yml": PLAYBOOK, + "ci/registry.stack.yaml": STACK, + f"roles/svc-x/{ROLE_FILE_META_SERVICES}": SERVICES, + f"roles/svc-x/{ROLE_FILE_TEMPL_COMPOSE}": TEMPLATE, + "roles/svc-x/files/test/compose.yml": HARNESS, + "roles/svc-x/files/docker-compose.yaml": HARNESS, + "roles/svc-x/files/session.yaml": SYMFONY, + "tests/fixtures/stack.yml": STACK, + "ops/two.yml": TWO_DOCUMENTS, + "ops/broken.yml": UNPARSABLE, +} + +UNTRACKED = {"scratch/stack.yml": STACK} + +OWNED = ["ci/registry.stack.yaml", "compose/cache.override.yml"] + +TAGS = { + "coredns/coredns": ["1.14.4", "1.14.5", "1.15.0"], + "rpardini/docker-registry-proxy": ["0.6.5", "0.8.0", "latest"], + "sonatype/nexus3": ["3.91.1-ubi", "3.92.0-ubi", "3.93.0", "3.93.0-java21"], + "nginx": ["1.27-alpine", "1.29-alpine", "1.29.3-alpine", "1.30"], + "busybox": ["1.36.1", "1.37.0"], + "alpine": ["latest", "3.20.3"], + "registry": ["2.8.3", "3.0.0"], + "postgres": ["16.4", "17.2"], + "redis": ["7.4.1", "8.0.0"], +} + + +def _write(path: Path, text: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + + +def _repo(root: Path) -> Path: + for rel, text in {**TRACKED, **UNTRACKED}.items(): + _write(root / rel, text) + return root + + +def _registry(tags: dict[str, list[str]]): + def _tags(image: str, *_args, **_kwargs) -> list[str]: + return tags.get(image, []) + + return mock.patch.multiple( + docker, + fetch_dockerhub_tags=mock.Mock(side_effect=_tags), + fetch_ghcr_tags=mock.Mock(side_effect=_tags), + fetch_mcr_tags=mock.Mock(side_effect=_tags), + fetch_registry_tags=mock.Mock(side_effect=_tags), + ) + + +def _bump(root: Path, tracked: list[str], tags: dict[str, list[str]]) -> list[Path]: + with ( + mock.patch.dict(os.environ, {"INFINITO_WORKER_FETCH": "2"}), + _registry(tags), + ): + return docker.apply_updates(docker.find_outdated_compose_updates(root, tracked)) + + +def _compose_update(path: Path, service: str, image: str, current: str, latest: str): + return docker.DockerImageVersionUpdate( + entry=docker.DockerImageVersionEntry( + role=RUNNER_ROLE, + service=service, + image=image, + version=current, + config_path=path, + ), + latest=latest, + ) + + +class TestComposeDiscovery(unittest.TestCase): + def test_compose_files_are_recognized_by_their_services_content(self): + with tempfile.TemporaryDirectory() as tmp: + root = _repo(Path(tmp)) + files = docker.compose_files(root, list(TRACKED)) + self.assertEqual(files, OWNED) + + def test_the_tagged_semver_pins_of_the_compose_files_are_collected(self): + with tempfile.TemporaryDirectory() as tmp: + root = _repo(Path(tmp)) + found = [ + ( + entry.config_path.relative_to(root).as_posix(), + entry.role, + entry.service, + entry.image, + entry.version, + ) + for entry in docker.collect_compose_entries(root, list(TRACKED)) + ] + self.assertEqual( + found, + [ + ("ci/registry.stack.yaml", RUNNER_ROLE, "mirror", "registry", "2.8.3"), + ( + "compose/cache.override.yml", + RUNNER_ROLE, + "registry-cache", + "rpardini/docker-registry-proxy", + "0.6.5", + ), + ( + "compose/cache.override.yml", + RUNNER_ROLE, + "package-cache", + "sonatype/nexus3", + "3.91.1-ubi", + ), + ( + "compose/cache.override.yml", + RUNNER_ROLE, + "package-cache-frontend", + "nginx", + "1.27-alpine", + ), + ], + ) + + def test_an_image_inherited_through_a_merge_anchor_is_not_collected(self): + merged = ( + "x-base: &base\n" + " image: redis:7.4.1\n" + "services:\n" + " inherited:\n" + " <<: *base\n" + " literal:\n" + " image: nginx:1.27-alpine\n" + ) + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + _write(root / "ops/merged.yml", merged) + entries = docker.collect_compose_entries(root, ["ops/merged.yml"]) + self.assertEqual( + [(entry.service, entry.image) for entry in entries], + [("literal", "nginx")], + ) + + def test_the_version_policy_of_role_pins_applies(self): + with tempfile.TemporaryDirectory() as tmp: + root = _repo(Path(tmp)) + with ( + mock.patch.dict(os.environ, {"INFINITO_WORKER_FETCH": "2"}), + _registry(TAGS), + ): + moves = { + update.entry.service: update.latest + for update in docker.find_outdated_compose_updates( + root, list(TRACKED) + ) + } + self.assertEqual( + moves, + { + "mirror": "3.0.0", + "registry-cache": "0.8.0", + "package-cache": "3.92.0-ubi", + "package-cache-frontend": "1.29-alpine", + }, + ) + + +class TestComposeBump(unittest.TestCase): + def test_only_the_due_tags_move_and_every_other_file_and_byte_stays(self): + with tempfile.TemporaryDirectory() as tmp: + root = _repo(Path(tmp)) + changed = _bump(root, list(TRACKED), TAGS) + _reset_cache_for_tests() + after = {rel: read_text(str(root / rel)) for rel in TRACKED} + + self.assertEqual( + sorted(path.relative_to(root).as_posix() for path in changed), OWNED + ) + expected = { + **TRACKED, + "ci/registry.stack.yaml": STACK.replace("registry:2.8.3", "registry:3.0.0"), + "compose/cache.override.yml": CACHE_OVERRIDE.replace( + "docker-registry-proxy:0.6.5", "docker-registry-proxy:0.8.0" + ) + .replace('nexus3:3.91.1-ubi"', 'nexus3:3.92.0-ubi"') + .replace("nginx:1.27-alpine", "nginx:1.29-alpine"), + } + self.assertEqual(after, expected) + + def test_the_real_registry_cache_pin_moves_to_the_newest_tag_alone(self): + rel = "compose/cache.override.yml" + original = read_text(str(PROJECT_ROOT / rel)) + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + _write(root / rel, original) + entries = docker.collect_compose_entries(root, [rel]) + tags = {entry.image: [entry.version] for entry in entries} + current = tags["rpardini/docker-registry-proxy"][0] + newest = re.sub( + r"\d+", lambda major: str(int(major.group()) + 1), current, count=1 + ) + tags["rpardini/docker-registry-proxy"] = [current, newest, "latest"] + changed = _bump(root, [rel], tags) + _reset_cache_for_tests() + after = read_text(str(root / rel)) + + self.assertEqual(changed, [root / rel]) + old = f"rpardini/docker-registry-proxy:{current}" + self.assertEqual(original.count(old), 1) + self.assertEqual( + after, + original.replace(old, f"rpardini/docker-registry-proxy:{newest}"), + ) + + def test_quoted_and_commented_tags_keep_their_quotes_and_comments(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "cache.override.yml" + path.write_text(CACHE_OVERRIDE, encoding="utf-8") + + changed = docker.apply_updates( + [ + _compose_update( + path, + "package-cache", + "sonatype/nexus3", + "3.91.1-ubi", + "3.92.0-ubi", + ), + ] + ) + + self.assertEqual(changed, [path]) + self.assertEqual( + read_text(str(path)), + CACHE_OVERRIDE.replace( + 'image: "sonatype/nexus3:3.91.1-ubi" # Keep comment', + 'image: "sonatype/nexus3:3.92.0-ubi" # Keep comment', + ), + ) + + def test_role_pins_still_move_through_their_version_key(self): + with tempfile.TemporaryDirectory() as tmp: + config = Path(tmp) / "roles" / "web-app-moodle" / ROLE_FILE_META_SERVICES + _write(config, SERVICES) + + docker.apply_updates( + [ + docker.DockerImageVersionUpdate( + entry=docker.DockerImageVersionEntry( + role="web-app-moodle", + service="moodle", + image="bitnamilegacy/moodle", + version="4.5", + config_path=config, + ), + latest="5.0", + ) + ] + ) + + self.assertEqual(read_text(str(config)), SERVICES.replace('"4.5"', '"5.0"')) + + +if __name__ == "__main__": + unittest.main() diff --git a/utils/docker/image/discovery.py b/utils/docker/image/discovery.py index 4b11814b39..195fd63022 100644 --- a/utils/docker/image/discovery.py +++ b/utils/docker/image/discovery.py @@ -314,18 +314,19 @@ def _runner_image(service: str, image: str, source_file: str) -> ImageRef | None ) -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. +def iter_compose_images( + repo_root: Path, source_files: Iterable[str] +) -> Iterable[ImageRef]: + """Args: + repo_root: repository root the source files are relative to. + source_files: repository-relative compose files. A file without a + ``services`` mapping, and an ``image`` that interpolates a + variable, carries no tag or is pinned by digest, yield 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 source_file in source_files: + services = load_yaml(repo_root / source_file).get("services") + if not isinstance(services, dict): + continue for service, spec in services.items(): image = ( str(spec.get("image") or "").strip() if isinstance(spec, dict) else "" @@ -336,6 +337,19 @@ def iter_runner_images(repo_root: Path) -> Iterable[ImageRef]: if ref is not None: yield ref + +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 + + yield from iter_compose_images(repo_root, RUNNER_COMPOSE_FILES) + declared = parse_static_env(repo_root / "default.env") for key in RUNNER_ENV_IMAGES: ref = _runner_image(key, declared[key], "default.env") diff --git a/utils/update/docker.py b/utils/update/docker.py index 46a7d1a3d5..3957c0bf5b 100644 --- a/utils/update/docker.py +++ b/utils/update/docker.py @@ -1,13 +1,14 @@ """Detect and rewrite outdated Docker image `version:` tags in -`roles/*/meta/services.yml`. +`roles/*/meta/services.yml`, and the tags of the `image:` literals in the +repository's own compose files (:func:`compose_files`). Counterpart to :mod:`utils.update.repository` (which handles git refs). Both share the semver primitives in :mod:`utils.update.base`; this module owns the Docker-Hub / GHCR registry lookups and the YAML -walker that rewrites the matching ``version:`` line. +walker that rewrites the matching ``version:`` or ``image:`` line. Suppress a check by placing ``# nocheck: docker-version`` on the line -directly above the ``version:`` key. +directly above the ``version:`` key, or above a compose service's ``image:``. A ``version`` that names its own upstream in an ``update:`` block belongs to :mod:`utils.update.source` and is not collected here. @@ -24,6 +25,7 @@ import urllib.error import urllib.request from collections import defaultdict from dataclasses import dataclass +from pathlib import PurePosixPath from typing import TYPE_CHECKING from urllib.parse import quote, urlencode @@ -31,8 +33,13 @@ import yaml from utils.annotations.suppress import is_suppressed_at from utils.cache.files import read_text -from utils.cache.yaml import load_yaml -from utils.docker.image.discovery import iter_role_images +from utils.cache.yaml import load_yaml, load_yaml_any +from utils.docker.image.discovery import ( + RUNNER_ROLE, + ImageRef, + iter_compose_images, + iter_role_images, +) from utils.docker.image.ref import ( GHCR_REGISTRY, MCR_REGISTRY, @@ -56,6 +63,7 @@ from utils.update.base import ( from utils.update.follow import followed_tags if TYPE_CHECKING: + from collections.abc import Iterable from pathlib import Path _KEY_RE = re.compile(r"^(?P\s*)(?P[A-Za-z0-9_-]+):(?P.*)$") @@ -64,6 +72,19 @@ _VERSION_VALUE_RE = re.compile( r"(?P[\"']?)(?P[^\"'#\s]+)(?P=quote)" r"(?P\s*(?:#.*)?)$" ) +_IMAGE_VALUE_RE = re.compile( + r"^(?P\s*image\s*:\s*)" + r"(?P[\"']?)(?P[^\"'#\s]+):(?P[^\"'#\s:/@]+)(?P=quote)" + r"(?P\s*(?:#.*)?)$" +) +COMPOSE_SUFFIXES = (".yml", ".yaml") +DEPENDABOT_COMPOSE_FILES = ( + "compose.yml", + "compose.yaml", + "docker-compose.yml", + "docker-compose.yaml", +) +TEST_TREE = "tests" @dataclass(frozen=True) @@ -289,16 +310,11 @@ def collect_entries(repo_root: Path) -> list[DockerImageVersionEntry]: if ref.service in sourced_services(config_path): continue - if ref.registry == "docker.io": - image = ref.name - else: - image = f"{ref.registry}/{ref.name}" - entries.append( DockerImageVersionEntry( role=ref.role, service=ref.service, - image=image, + image=_entry_image(ref), version=ref.version, config_path=config_path, ) @@ -307,6 +323,138 @@ def collect_entries(repo_root: Path) -> list[DockerImageVersionEntry]: return entries +def _entry_image(ref: ImageRef) -> str: + return ref.name if ref.registry == "docker.io" else f"{ref.registry}/{ref.name}" + + +def declares_compose_images(document: object) -> bool: + """Args: + document: a parsed YAML document. + + Returns: + Whether its top level holds a ``services`` mapping in which at least + one service carries an ``image`` string. + """ + services = document.get("services") if isinstance(document, dict) else None + return isinstance(services, dict) and any( + isinstance(spec, dict) and isinstance(spec.get("image"), str) + for spec in services.values() + ) + + +def _owned_candidate(rel: str) -> bool: + path = PurePosixPath(rel) + return ( + rel.endswith(COMPOSE_SUFFIXES) + and path.name not in DEPENDABOT_COMPOSE_FILES + and path.parts[0] != TEST_TREE + ) + + +def compose_files(repo_root: Path, tracked: Iterable[str]) -> list[str]: + """Args: + repo_root: repository root the tracked paths are relative to. + tracked: repository-relative POSIX paths of the tracked files, as + :func:`utils.cache.files.repository_files` lists them. + + Returns: + The tracked YAML files :func:`declares_compose_images` accepts, + sorted. Left out are Jinja templates, YAML that does not parse as one + document, the test tree ``TEST_TREE`` and the files Dependabot's + ``docker-compose`` ecosystem bumps (``DEPENDABOT_COMPOSE_FILES``). + """ + owned: list[str] = [] + for rel in tracked: + if not _owned_candidate(rel): + continue + path = repo_root / rel + try: + if "services" not in read_text(str(path)): + continue + document = load_yaml_any(str(path)) + except (OSError, UnicodeDecodeError, ValueError, yaml.YAMLError): + continue + if declares_compose_images(document): + owned.append(rel) + return sorted(owned) + + +def _compose_image_lines(raw: str) -> dict[str, tuple[int, int]]: + """Args: + raw: text of a compose file. + + Returns: + Each compose service mapped to the 0-indexed lines of its ``image`` + key and value. + """ + root = yaml.compose(raw) + services = next( + ( + value + for key, value in (root.value if isinstance(root, yaml.MappingNode) else []) + if key.value == "services" and isinstance(value, yaml.MappingNode) + ), + None, + ) + lines: dict[str, tuple[int, int]] = {} + for service, spec in services.value if services else []: + if not isinstance(spec, yaml.MappingNode): + continue + for field, value in spec.value: + if field.value == "image": + lines[service.value] = (field.start_mark.line, value.start_mark.line) + return lines + + +def suppressed_compose_services(compose_path: Path) -> set[str]: + """Args: + compose_path: a compose file of the repository. + + Returns: + The services whose ``image:`` carries ``# nocheck: docker-version``. + """ + raw = read_text(str(compose_path)) + lines = raw.splitlines() + return { + service + for service, (key_line, _value_line) in _compose_image_lines(raw).items() + if is_suppressed_at(lines, key_line + 1, "docker-version") + } + + +def collect_compose_entries( + repo_root: Path, tracked: Iterable[str] +) -> list[DockerImageVersionEntry]: + """Args: + repo_root: repository root the tracked paths are relative to. + tracked: repository-relative paths of the tracked files. + + Returns: + One entry per semver-tagged service ``image`` literal of the + :func:`compose_files`, scoped to the pseudo role ``RUNNER_ROLE``; its + ``config_path`` is the compose file. + """ + entries: list[DockerImageVersionEntry] = [] + for ref in iter_compose_images(repo_root, compose_files(repo_root, tracked)): + compose_path = repo_root / ref.source_file + if not is_semver(ref.version): + continue + if ref.service not in _compose_image_lines(read_text(str(compose_path))): + continue + if ref.service in suppressed_compose_services(compose_path): + continue + entries.append( + DockerImageVersionEntry( + role=ref.role, + service=ref.service, + image=_entry_image(ref), + version=ref.version, + config_path=compose_path, + ) + ) + return entries + + def _registry_cursor(version: str) -> str | None: """Pagination seed for the generic v2 tag scan. @@ -318,7 +466,29 @@ def _registry_cursor(version: str) -> str | None: def find_outdated_updates(repo_root: Path) -> list[DockerImageVersionUpdate]: - entries = collect_entries(repo_root) + return outdated(collect_entries(repo_root)) + + +def find_outdated_compose_updates( + repo_root: Path, tracked: Iterable[str] +) -> list[DockerImageVersionUpdate]: + return outdated(collect_compose_entries(repo_root, tracked)) + + +def _follow_config(entry: DockerImageVersionEntry) -> object: + if entry.role == RUNNER_ROLE: + return None + return (load_yaml(str(entry.config_path)) or {}).get(entry.service) + + +def outdated(entries: list[DockerImageVersionEntry]) -> list[DockerImageVersionUpdate]: + """Args: + entries: pins from :func:`collect_entries` or + :func:`collect_compose_entries`. + + Returns: + The bumps due for *entries*, release groups held together. + """ updates: list[DockerImageVersionUpdate] = [] def _fetch(item: tuple[str, str]) -> tuple[str, list[str]]: @@ -343,9 +513,11 @@ def find_outdated_updates(repo_root: Path) -> list[DockerImageVersionUpdate]: ) for entry in entries: - config = (load_yaml(str(entry.config_path)) or {}).get(entry.service) tags = followed_tags( - entry.image, image_tags.get(entry.image, []), config, entry.version + entry.image, + image_tags.get(entry.image, []), + _follow_config(entry), + entry.version, ) if not tags: continue @@ -366,11 +538,12 @@ def _held_to_release_groups( """Hold every member of a release group to the newest tag all of them publish. - Several images of one role that currently sit on the same version are one - product released together (the four Jitsi components, the six GitLab CNG - images). Upstream does not push them atomically, so a run that lands in the - window between the first and the last push would raise the ones already - there and leave the rest behind, deploying a mixed set. + Several images of one role (or one compose file) that currently sit on the + same version are one product released together (the four Jitsi + components, the six GitLab CNG images). Upstream does not push them + atomically, so a run that lands in the window between the first and the + last push would raise the ones already there and leave the rest behind, + deploying a mixed set. Args: updates: the per-entry candidates, before grouping. @@ -380,9 +553,12 @@ def _held_to_release_groups( The updates, each group lowered to its common newest tag, and dropped entirely where the group shares no newer tag at all. """ - groups: dict[tuple[str, str], list[DockerImageVersionUpdate]] = defaultdict(list) + groups: dict[tuple[str, Path, str], list[DockerImageVersionUpdate]] = defaultdict( + list + ) for update in updates: - groups[(update.entry.role, update.entry.version)].append(update) + entry = update.entry + groups[(entry.role, entry.config_path, entry.version)].append(update) held: list[DockerImageVersionUpdate] = [] for group in groups.values(): @@ -475,15 +651,50 @@ def update_config_versions(config_path: Path, service_versions: dict[str, str]) return bool(moved) +def update_compose_images(compose_path: Path, service_versions: dict[str, str]) -> bool: + """Args: + compose_path: a compose file of the repository. + service_versions: service name to the tag its image moves to. + + Returns: + Whether the file changed; every line but the rewritten tags stays as + it was. + """ + raw = compose_path.read_text( # nocheck: cache-read -- read-then-write of the same file; a cached read would go stale + encoding="utf-8" + ) + lines = raw.splitlines(keepends=True) + changed = False + for service, (_key_line, value_line) in _compose_image_lines(raw).items(): + latest = service_versions.get(service) + body = lines[value_line].rstrip("\n") + match = _IMAGE_VALUE_RE.match(body) + if latest is None or match is None or match["tag"] == latest: + continue + quote = match["quote"] + lines[value_line] = ( + f"{match['prefix']}{quote}{match['name']}:{latest}{quote}" + f"{match['suffix']}{lines[value_line][len(body) :]}" + ) + changed = True + if changed: + compose_path.write_text("".join(lines), encoding="utf-8") + return changed + + def apply_updates(updates: list[DockerImageVersionUpdate]) -> list[Path]: - grouped: dict[Path, dict[str, str]] = {} + grouped: dict[tuple[Path, str], dict[str, str]] = {} for update in updates: - grouped.setdefault(update.entry.config_path, {})[update.entry.service] = ( + entry = update.entry + grouped.setdefault((entry.config_path, entry.role), {})[entry.service] = ( update.latest ) changed_paths: list[Path] = [] - for config_path, service_versions in sorted(grouped.items()): - if update_config_versions(config_path, service_versions): + for (config_path, role), service_versions in sorted(grouped.items()): + rewrite = ( + update_compose_images if role == RUNNER_ROLE else update_config_versions + ) + if rewrite(config_path, service_versions): changed_paths.append(config_path) return changed_paths