diff --git a/cli/contributing/update/docker/__main__.py b/cli/contributing/update/docker/__main__.py index 29765c801a..0ce9c84933 100755 --- a/cli/contributing/update/docker/__main__.py +++ b/cli/contributing/update/docker/__main__.py @@ -40,6 +40,11 @@ def main() -> int: args = parser.parse_args() repo_root = args.repo_root.resolve() + if args.compose and repo_root != PROJECT_ROOT: + parser.error( + "--compose lists the tracked files of this checkout only; " + "drop --repo-root or run the command from the other checkout" + ) updates = ( find_outdated_compose_updates(repo_root, repository_files()) if args.compose diff --git a/tests/unit/python/utils/update/test_docker_compose.py b/tests/unit/python/utils/update/test_docker_compose.py index c923119490..f695387ffa 100644 --- a/tests/unit/python/utils/update/test_docker_compose.py +++ b/tests/unit/python/utils/update/test_docker_compose.py @@ -1,12 +1,16 @@ from __future__ import annotations +import contextlib +import io import os import re +import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path +from cli.contributing.update.docker import __main__ as docker_cli 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 @@ -265,6 +269,34 @@ class TestComposeDiscovery(unittest.TestCase): [("literal", "nginx")], ) + def test_a_compose_file_in_the_role_tree_is_not_discovered(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + _write(root / "roles/svc-x/files/stack.yaml", STACK) + _write(root / "ops/stack.yaml", STACK) + files = docker.compose_files( + root, ["roles/svc-x/files/stack.yaml", "ops/stack.yaml"] + ) + self.assertEqual(files, ["ops/stack.yaml"]) + + def test_an_image_value_on_the_line_after_its_key_is_not_collected(self): + split = ( + "services:\n" + " split:\n" + " image:\n" + " redis:7.4.1\n" + " inline:\n" + " image: nginx:1.27-alpine\n" + ) + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + _write(root / "ops/split.yml", split) + entries = docker.collect_compose_entries(root, ["ops/split.yml"]) + self.assertEqual( + [(entry.service, entry.image) for entry in entries], + [("inline", "nginx")], + ) + def test_the_version_policy_of_role_pins_applies(self): with tempfile.TemporaryDirectory() as tmp: root = _repo(Path(tmp)) @@ -288,6 +320,63 @@ class TestComposeDiscovery(unittest.TestCase): }, ) + def test_a_service_on_the_shared_version_without_its_release_holds_the_group( + self, + ): + pair = ( + "services:\n" + " api:\n" + " image: acme/api:1.0.0\n" + " worker:\n" + " image: acme/worker:1.0.0\n" + ) + published = {"acme/api": ["1.0.0", "1.0.1"], "acme/worker": ["1.0.0"]} + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + _write(root / "ops/pair.yml", pair) + with ( + mock.patch.dict(os.environ, {"INFINITO_WORKER_FETCH": "2"}), + _registry(published), + ): + partial = docker.find_outdated_compose_updates(root, ["ops/pair.yml"]) + published["acme/worker"].append("1.0.1") + with ( + mock.patch.dict(os.environ, {"INFINITO_WORKER_FETCH": "2"}), + _registry(published), + ): + complete = docker.find_outdated_compose_updates(root, ["ops/pair.yml"]) + self.assertEqual(partial, []) + self.assertEqual( + {update.entry.service: update.latest for update in complete}, + {"api": "1.0.1", "worker": "1.0.1"}, + ) + + +class TestComposeCli(unittest.TestCase): + def _main(self, *argv: str) -> mock.Mock: + find = mock.Mock(return_value=[]) + with ( + mock.patch.object(sys, "argv", ["update-docker", *argv]), + mock.patch.object(docker_cli, "find_outdated_compose_updates", find), + mock.patch.object(docker_cli, "repository_files", return_value=()), + contextlib.redirect_stdout(io.StringIO()), + contextlib.redirect_stderr(io.StringIO()), + ): + self.assertEqual(docker_cli.main(), 0) + return find + + def test_compose_refuses_a_repo_root_other_than_the_one_it_lists(self): + with ( + tempfile.TemporaryDirectory() as tmp, + self.assertRaises(SystemExit) as raised, + ): + self._main("--compose", "--repo-root", tmp) + self.assertEqual(raised.exception.code, 2) + + def test_compose_scans_the_default_repo_root(self): + find = self._main("--compose") + find.assert_called_once_with(PROJECT_ROOT, ()) + class TestComposeBump(unittest.TestCase): def test_only_the_due_tags_move_and_every_other_file_and_byte_stays(self): diff --git a/tests/unit/python/utils/update/test_docker_release_groups.py b/tests/unit/python/utils/update/test_docker_release_groups.py index 72b6c22256..35573f63e8 100644 --- a/tests/unit/python/utils/update/test_docker_release_groups.py +++ b/tests/unit/python/utils/update/test_docker_release_groups.py @@ -41,6 +41,10 @@ def _jitsi_updates(version: str, latest: str): ] +def _held(updates: list[DockerImageVersionUpdate], tags: dict[str, list[str]]): + return _held_to_release_groups([update.entry for update in updates], updates, tags) + + class TestReleaseGroupsMoveTogether(unittest.TestCase): def test_a_partial_publish_holds_the_whole_group_back(self): tags = { @@ -51,16 +55,30 @@ class TestReleaseGroupsMoveTogether(unittest.TestCase): } updates = _jitsi_updates("stable-9400", "stable-9700") - held = _held_to_release_groups(updates, tags) + held = _held(updates, tags) self.assertEqual({update.latest for update in held}, {"stable-9646"}) self.assertEqual(len(held), 4) + def test_a_member_without_a_newer_tag_holds_the_whole_group(self): + tags = { + "jitsi/web": ["stable-9400"], + "jitsi/prosody": ["stable-9400", "stable-9700"], + "jitsi/jicofo": ["stable-9400", "stable-9700"], + "jitsi/jvb": ["stable-9400", "stable-9700"], + } + updates = _jitsi_updates("stable-9400", "stable-9700") + entries = [update.entry for update in updates] + + held = _held_to_release_groups(entries, updates[1:], tags) + + self.assertEqual(held, []) + def test_a_group_all_publish_moves_to_the_head(self): tags = {f"jitsi/{name}": ["stable-9400", "stable-9700"] for name in JITSI} updates = _jitsi_updates("stable-9400", "stable-9700") - held = _held_to_release_groups(updates, tags) + held = _held(updates, tags) self.assertEqual({update.latest for update in held}, {"stable-9700"}) @@ -73,7 +91,7 @@ class TestReleaseGroupsMoveTogether(unittest.TestCase): } updates = _jitsi_updates("stable-9400", "stable-9704") - self.assertEqual(_held_to_release_groups(updates, tags), []) + self.assertEqual(_held(updates, tags), []) def test_a_lone_entry_is_untouched(self): update = DockerImageVersionUpdate( @@ -81,7 +99,7 @@ class TestReleaseGroupsMoveTogether(unittest.TestCase): latest="v0.36.0", ) - held = _held_to_release_groups([update], {"getfider/fider": ["v0.36.0"]}) + held = _held([update], {"getfider/fider": ["v0.36.0"]}) self.assertEqual(held, [update]) @@ -101,7 +119,7 @@ class TestReleaseGroupsMoveTogether(unittest.TestCase): ), ] - held = _held_to_release_groups(updates, tags) + held = _held(updates, tags) self.assertEqual( [update.latest for update in held], ["stable-9700", "stable-9400"] diff --git a/utils/update/docker.py b/utils/update/docker.py index 3957c0bf5b..1aa4bd2280 100644 --- a/utils/update/docker.py +++ b/utils/update/docker.py @@ -48,6 +48,7 @@ from utils.docker.image.ref import ( split_registry_and_name, ) from utils.docker.registry import fetch_registry_tags +from utils.meta.role.names import ROLES_DIR from utils.roles.mapping import ROLE_FILE_META_SERVICES from utils.security.suppressions import drop_image_tag_entries from utils.update.base import ( @@ -347,7 +348,7 @@ def _owned_candidate(rel: str) -> bool: return ( rel.endswith(COMPOSE_SUFFIXES) and path.name not in DEPENDABOT_COMPOSE_FILES - and path.parts[0] != TEST_TREE + and path.parts[0] not in (TEST_TREE, ROLES_DIR) ) @@ -360,8 +361,10 @@ def compose_files(repo_root: Path, tracked: Iterable[str]) -> list[str]: 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``). + document, the test tree ``TEST_TREE``, the role tree ``ROLES_DIR``, + whose images ``meta/services.yml`` pins for :func:`collect_entries`, + and the files Dependabot's ``docker-compose`` ecosystem bumps + (``DEPENDABOT_COMPOSE_FILES``). """ owned: list[str] = [] for rel in tracked: @@ -379,14 +382,16 @@ def compose_files(repo_root: Path, tracked: Iterable[str]) -> list[str]: return sorted(owned) -def _compose_image_lines(raw: str) -> dict[str, tuple[int, int]]: +def _compose_image_lines(raw: str) -> dict[str, int]: """Args: raw: text of a compose file. Returns: - Each compose service mapped to the 0-indexed lines of its ``image`` - key and value. + Each compose service mapped to the 0-indexed line of its ``image`` + key, for the keys whose tagged value sits on that line in the one + form ``_IMAGE_VALUE_RE`` rewrites. """ + text_lines = raw.splitlines() root = yaml.compose(raw) services = next( ( @@ -396,13 +401,18 @@ def _compose_image_lines(raw: str) -> dict[str, tuple[int, int]]: ), None, ) - lines: dict[str, tuple[int, int]] = {} + lines: dict[str, 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) + line = field.start_mark.line + if ( + field.value == "image" + and value.start_mark.line == line + and _IMAGE_VALUE_RE.match(text_lines[line]) + ): + lines[service.value] = line return lines @@ -417,8 +427,8 @@ def suppressed_compose_services(compose_path: Path) -> set[str]: 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") + for service, line in _compose_image_lines(raw).items() + if is_suppressed_at(lines, line + 1, "docker-version") } @@ -529,11 +539,13 @@ def outdated(entries: list[DockerImageVersionEntry]) -> list[DockerImageVersionU if latest and version_key(entry.version) < version_key(latest): updates.append(DockerImageVersionUpdate(entry=entry, latest=latest)) - return _held_to_release_groups(updates, image_tags) + return _held_to_release_groups(entries, updates, image_tags) def _held_to_release_groups( - updates: list[DockerImageVersionUpdate], image_tags: dict[str, list[str]] + entries: list[DockerImageVersionEntry], + updates: list[DockerImageVersionUpdate], + image_tags: dict[str, list[str]], ) -> list[DockerImageVersionUpdate]: """Hold every member of a release group to the newest tag all of them publish. @@ -546,37 +558,41 @@ def _held_to_release_groups( deploying a mixed set. Args: + entries: every collected pin, so a member without a candidate of its + own still holds its group. updates: the per-entry candidates, before grouping. image_tags: every tag fetched per image, keyed as in the caller. Returns: The updates, each group lowered to its common newest tag, and dropped - entirely where the group shares no newer tag at all. + entirely where a member has no candidate or the group shares no newer + tag at all. """ - groups: dict[tuple[str, Path, str], list[DockerImageVersionUpdate]] = defaultdict( + due = {update.entry: update for update in updates} + groups: dict[tuple[str, Path, str], list[DockerImageVersionEntry]] = defaultdict( list ) - for update in updates: - entry = update.entry - groups[(entry.role, entry.config_path, entry.version)].append(update) + for entry in entries: + groups[(entry.role, entry.config_path, entry.version)].append(entry) held: list[DockerImageVersionUpdate] = [] for group in groups.values(): + if not all(entry in due for entry in group): + continue if len(group) == 1: - held.extend(group) + held.append(due[group[0]]) continue shared = set.intersection( - *(set(image_tags.get(update.entry.image, [])) for update in group) + *(set(image_tags.get(entry.image, [])) for entry in group) ) - current = group[0].entry.version + current = group[0].version common = latest_semver( sorted(shared), version_depth(current), version_flavor(current) ) if not common or version_key(current) >= version_key(common): continue held.extend( - DockerImageVersionUpdate(entry=update.entry, latest=common) - for update in group + DockerImageVersionUpdate(entry=entry, latest=common) for entry in group ) return held @@ -665,16 +681,16 @@ def update_compose_images(compose_path: Path, service_versions: dict[str, str]) ) lines = raw.splitlines(keepends=True) changed = False - for service, (_key_line, value_line) in _compose_image_lines(raw).items(): + for service, line in _compose_image_lines(raw).items(): latest = service_versions.get(service) - body = lines[value_line].rstrip("\n") + body = lines[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] = ( + lines[line] = ( f"{match['prefix']}{quote}{match['name']}:{latest}{quote}" - f"{match['suffix']}{lines[value_line][len(body) :]}" + f"{match['suffix']}{lines[line][len(body) :]}" ) changed = True if changed: