diff --git a/requirements/requirements.galaxy.yml b/requirements/requirements.galaxy.yml index ef98c31538..811fd78003 100644 --- a/requirements/requirements.galaxy.yml +++ b/requirements/requirements.galaxy.yml @@ -7,7 +7,7 @@ collections: - name: kewlfft.aur version: 0.13.0 - name: community.general - version: 13.5.0 + version: 14.0.0 - name: community.docker version: 5.4.0 - name: community.library_inventory_filtering_v1 diff --git a/requirements/requirements.git.yml b/requirements/requirements.git.yml index 58808ee14c..92c5af26e7 100644 --- a/requirements/requirements.git.yml +++ b/requirements/requirements.git.yml @@ -18,7 +18,7 @@ collections: - name: community.general source: https://github.com/ansible-collections/community.general.git type: git - version: 13.5.0 + version: 14.0.0 - name: community.docker source: https://github.com/ansible-collections/community.docker.git diff --git a/roles/sys-svc-compose/filter_plugins/compose_rehash.py b/roles/sys-svc-compose/filter_plugins/compose_rehash.py new file mode 100644 index 0000000000..23a4a00750 --- /dev/null +++ b/roles/sys-svc-compose/filter_plugins/compose_rehash.py @@ -0,0 +1,65 @@ +import re + +from plugins.lookup.compose_volumes import _config_secret_name + +SECTIONS = ("configs", "secrets") +HASH_LENGTH = 8 + + +def compose_hashed_entries(compose): + """Return the configs and secrets whose name carries the content hash of their file. + + Args: + compose: the parsed compose.yml. + + Returns: + ``[{name, entity, key, file}]`` for every top-level config or secret + named ``__`` with a ``file`` source, the shape the + ``compose_volumes`` lookup writes. Explicitly named entries, which do + not end in their own key and a hash, are left out. + """ + entries = [] + for section in SECTIONS: + for key, spec in (compose.get(section) or {}).items(): + if ( + not isinstance(spec, dict) + or not spec.get("file") + or not spec.get("name") + ): + continue + name = str(spec["name"]) + match = re.fullmatch( + rf"(?P.+)_{re.escape(str(key))}_[0-9a-f]{{{HASH_LENGTH}}}", name + ) + if match: + entries.append( + { + "name": name, + "entity": match["entity"], + "key": str(key), + "file": str(spec["file"]), + } + ) + return entries + + +def compose_rehashed_name(entry): + """Return the name the ``compose_volumes`` lookup gives an entry's file as it is now. + + Args: + entry: one item of ``compose_hashed_entries``. + + Returns: + ``__`` from the lookup's own naming function, read + on the controller like the render, so an unchanged file keeps exactly + the name the next render writes. + """ + return _config_secret_name(entry["entity"], entry["key"], entry["file"]) + + +class FilterModule: + def filters(self): + return { + "compose_hashed_entries": compose_hashed_entries, + "compose_rehashed_name": compose_rehashed_name, + } diff --git a/roles/sys-svc-compose/handlers/compose.yml b/roles/sys-svc-compose/handlers/compose.yml index eb9f6bce0d..ca78abe2e7 100644 --- a/roles/sys-svc-compose/handlers/compose.yml +++ b/roles/sys-svc-compose/handlers/compose.yml @@ -6,6 +6,12 @@ - compose-build - container-recreate +- name: "🔁 Update the config and secret hashes in compose.yml" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/rehash_configs.yml') }}" + listen: + - compose-up + - container-recreate + - name: 📝 Generate CA trust override ansible.builtin.shell: | set -euo pipefail diff --git a/roles/sys-svc-compose/tasks/utils/rehash_configs.yml b/roles/sys-svc-compose/tasks/utils/rehash_configs.yml new file mode 100644 index 0000000000..bfc61e79b0 --- /dev/null +++ b/roles/sys-svc-compose/tasks/utils/rehash_configs.yml @@ -0,0 +1,25 @@ +--- +- name: "🔍 Stat compose.yml of '{{ application_id }}'" + ansible.builtin.stat: + path: "{{ lookup('container', application_id, 'files.compose') }}" + get_checksum: false + register: sys_svc_compose_rehash_stat + +- name: "🔁 Update the hashed config and secret names of '{{ application_id }}'" + when: sys_svc_compose_rehash_stat.stat.exists + block: + - name: "📖 Read compose.yml of '{{ application_id }}'" + ansible.builtin.slurp: # nocheck: stack-host-consumer (the block is gated by the stat of this same file) + src: "{{ lookup('container', application_id, 'files.compose') }}" + register: sys_svc_compose_rehash_compose + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + + - name: "🔁 Point each hashed name of '{{ application_id }}' at its file's current content" + ansible.builtin.replace: # nocheck: stack-host-consumer (the block is gated by the stat of this same file) + path: "{{ lookup('container', application_id, 'files.compose') }}" + regexp: "(?/dev/null || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error echo "[arch] Installing build toolchain..." - pacman -Syu --noconfirm --needed base-devel sudo rsync + pacman -Syu --noconfirm --needed base-devel sudo tar if ! id "${builder}" >/dev/null 2>&1; then echo "[arch] Creating build user '${builder}'..." @@ -41,13 +41,7 @@ build_and_install_arch() { chmod 0440 /etc/sudoers.d/99-"${builder}"-pacman echo "[arch] Preparing build workspace ${build_root}..." - rm -rf "${build_root}" - mkdir -p "${build_root}" - rsync -a --delete \ - --exclude '.git' \ - --exclude '.venv' \ - --exclude '__pycache__' \ - "${REPO_ROOT}/" "${build_root}/" + bash "${SCRIPT_DIR}/stage.sh" "${REPO_ROOT}" "${build_root}" '.git' '.venv' '__pycache__' chown -R "${builder}:${builder}" "${build_root}" @@ -86,15 +80,10 @@ build_and_install_debian_like() { build-essential \ debhelper \ dpkg-dev \ - rsync + tar echo "[debian] Preparing build workspace ${build_root}..." - rm -rf "${build_root}" - mkdir -p "${build_root}" - rsync -a \ - --exclude 'packaging/debian' \ - --exclude '.git' \ - "${REPO_ROOT}/" "${build_root}/" + bash "${SCRIPT_DIR}/stage.sh" "${REPO_ROOT}" "${build_root}" 'packaging/debian' '.git' mkdir -p "${build_root}/debian" cp -a "${REPO_ROOT}/packaging/debian/." "${build_root}/debian/" diff --git a/scripts/install/stage.sh b/scripts/install/stage.sh new file mode 100755 index 0000000000..21124cd13f --- /dev/null +++ b/scripts/install/stage.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# Param: $1 source tree to copy +# Param: $2 build workspace, removed and recreated empty +# Param: $3... exclusion patterns, unanchored, so `.git` drops every `.git` at any depth +set -euo pipefail + +src="${1:?usage: stage.sh SRC DEST [EXCLUDE...]}" +dest="${2:?usage: stage.sh SRC DEST [EXCLUDE...]}" +shift 2 + +excludes=() +for pattern in "$@"; do + excludes+=("--exclude=${pattern}") +done + +rm -rf "${dest}" +mkdir -p "${dest}" +tar -C "${src}" "${excludes[@]}" --format=posix -cf - . | tar -C "${dest}" -xf - diff --git a/scripts/system/apparmor/common.sh b/scripts/system/apparmor/common.sh index d6c252267c..914a2b9b84 100755 --- a/scripts/system/apparmor/common.sh +++ b/scripts/system/apparmor/common.sh @@ -1,5 +1,10 @@ #!/usr/bin/env bash +# shellcheck disable=SC2034 +APPARMOR_UNCONFINED_RESTRICTION_SYSCTL=/proc/sys/kernel/apparmor_restrict_unprivileged_unconfined +# shellcheck disable=SC2034 +APPARMOR_UNCONFINED_RESTRICTION_STATE=/run/infinito/apparmor-restrict-unprivileged-unconfined + apparmor_log() { printf '%s\n' "$*" } @@ -47,6 +52,46 @@ apparmor_removable_profiles() { sed -E 's/ \([a-z]+\)$//' | grep -v -E '//|^docker-default$' } +# Param: $1 sysctl file of kernel.apparmor_restrict_unprivileged_unconfined +# Param: $2 state file that keeps the value found before lifting it +apparmor_lift_unconfined_restriction() { + local sysctl="$1" + local state="$2" + local current="" + + if [[ ! -e "${sysctl}" ]]; then + apparmor_log "[apparmor] ${sysctl} absent; containers are not stacked onto unconfined" + return 0 + fi + + current="$(tr -d '[:space:]' <"${sysctl}")" + if [[ "${current}" == "0" ]]; then + apparmor_log "[apparmor] unprivileged-unconfined restriction already off" + return 0 + fi + + mkdir -p "$(dirname "${state}")" + printf '%s\n' "${current}" >"${state}" + printf '0\n' >"${sysctl}" + apparmor_log "[apparmor] lifted unprivileged-unconfined restriction (was ${current}); containers keep plain docker-default" +} + +# Param: $1 sysctl file of kernel.apparmor_restrict_unprivileged_unconfined +# Param: $2 state file written by apparmor_lift_unconfined_restriction +apparmor_reinstate_unconfined_restriction() { + local sysctl="$1" + local state="$2" + + if [[ ! -f "${state}" ]]; then + apparmor_log "[apparmor] no lifted unprivileged-unconfined restriction to reinstate" + return 0 + fi + + tr -d '[:space:]' <"${state}" >"${sysctl}" + rm -f "${state}" + apparmor_log "[apparmor] reinstated unprivileged-unconfined restriction" +} + systemd_is_operational() { command -v systemctl >/dev/null 2>&1 && [[ -d /run/systemd/system ]] } diff --git a/scripts/system/apparmor/restore.sh b/scripts/system/apparmor/restore.sh index 221ff68424..9784e1e5a8 100755 --- a/scripts/system/apparmor/restore.sh +++ b/scripts/system/apparmor/restore.sh @@ -7,6 +7,8 @@ source "${SCRIPT_DIR}/common.sh" echo "[apparmor] restoring profiles" +apparmor_reinstate_unconfined_restriction "${APPARMOR_UNCONFINED_RESTRICTION_SYSCTL}" "${APPARMOR_UNCONFINED_RESTRICTION_STATE}" + if ! apparmor_should_manage; then echo "[apparmor] skipping restore: $(apparmor_skip_reason)" exit 0 diff --git a/scripts/system/apparmor/teardown.sh b/scripts/system/apparmor/teardown.sh index f09ee0bf35..b2af2905e6 100755 --- a/scripts/system/apparmor/teardown.sh +++ b/scripts/system/apparmor/teardown.sh @@ -29,4 +29,6 @@ else echo "[apparmor] ${APPARMOR_FS}/.remove is not writable; skipping profile unload" fi +apparmor_lift_unconfined_restriction "${APPARMOR_UNCONFINED_RESTRICTION_SYSCTL}" "${APPARMOR_UNCONFINED_RESTRICTION_STATE}" + echo "[apparmor] teardown complete" diff --git a/tests/unit/python/roles/sys-svc-compose/filter_plugins/__init__.py b/tests/unit/python/roles/sys-svc-compose/filter_plugins/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/sys-svc-compose/filter_plugins/test_compose_rehash.py b/tests/unit/python/roles/sys-svc-compose/filter_plugins/test_compose_rehash.py new file mode 100644 index 0000000000..2570e24b2e --- /dev/null +++ b/tests/unit/python/roles/sys-svc-compose/filter_plugins/test_compose_rehash.py @@ -0,0 +1,134 @@ +import importlib.util +import re +import tempfile +import unittest +import unittest.mock as mock +from pathlib import Path + +from plugins.lookup.compose_volumes import compose_volumes +from utils import PROJECT_ROOT +from utils.cache import _reset_cache_for_tests +from utils.cache.yaml import dump_yaml_str, load_yaml_str + +_spec = importlib.util.spec_from_file_location( + "compose_rehash", + PROJECT_ROOT / "roles/sys-svc-compose/filter_plugins/compose_rehash.py", +) +compose_rehash = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(compose_rehash) + +APPLICATIONS = { + "app": { + "services": { + "mariadb": {"enabled": False, "shared": False}, + "redis": {"enabled": False}, + "sso": {"enabled": False, "flavor": "oauth2"}, + } + } +} + + +def render_in_a_fresh_worker(configs, secrets): + _reset_cache_for_tests() + return load_yaml_str( + compose_volumes( + APPLICATIONS, + "app", + extra_configs={key: {"file": str(path)} for key, path in configs.items()}, + extra_secrets={key: {"file": str(path)} for key, path in secrets.items()}, + dir_var_lib="/var/lib/infinito", + ) + ) + + +def flush_in_a_fresh_worker(compose): + _reset_cache_for_tests() + text = dump_yaml_str(compose) + for entry in compose_rehash.compose_hashed_entries(compose): + text = re.sub( + rf"(? list[_SockFilter]: + ld_abs, jeq, ret = 0x20, 0x15, 0x06 + allow, deny = 0x7FFF0000, 0x00050000 | errno.EACCES + numbers = SIGNAL_SYSCALLS[machine] + program = [ + _SockFilter(ld_abs, 0, 0, 4), + _SockFilter(jeq, 1, 0, AUDIT_ARCH[machine]), + _SockFilter(ret, 0, 0, allow), + _SockFilter(ld_abs, 0, 0, 0), + ] + for index, number in enumerate(numbers): + program.append(_SockFilter(jeq, len(numbers) - index, 0, number)) + program.append(_SockFilter(ret, 0, 0, allow)) + program.append(_SockFilter(ret, 0, 0, deny)) + return program + + +def _ban_signals() -> None: + program = _signal_ban_program(platform.machine()) + filters = (_SockFilter * len(program))(*program) + fprog = _SockFprog(len(program), filters) + libc = ctypes.CDLL(None, use_errno=True) + libc.prctl.argtypes = [ + ctypes.c_int, + ctypes.c_ulong, + ctypes.c_ulong, + ctypes.c_ulong, + ctypes.c_ulong, + ] + if libc.prctl(38, 1, 0, 0, 0) != 0: + raise OSError(ctypes.get_errno(), "PR_SET_NO_NEW_PRIVS failed") + if libc.prctl(22, 2, ctypes.addressof(fprog), 0, 0) != 0: + raise OSError(ctypes.get_errno(), "PR_SET_SECCOMP failed") + + +def _run_without_signals(argv: list[str]) -> subprocess.CompletedProcess: + proc = subprocess.Popen( + argv, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + preexec_fn=_ban_signals, + start_new_session=True, + ) + try: + stdout, stderr = proc.communicate(timeout=TIMEOUT_SECONDS) + except subprocess.TimeoutExpired: + os.killpg(proc.pid, signal.SIGKILL) + proc.communicate() + raise + return subprocess.CompletedProcess(argv, proc.returncode, stdout, stderr) + + +def _tree(root: Path, files: dict[str, str]) -> None: + for relative, content in files.items(): + path = root / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content) + + +def _stage(src: Path, dest: Path, *excludes: str) -> subprocess.CompletedProcess: + return _run_without_signals(["bash", str(STAGE), str(src), str(dest), *excludes]) + + +@unittest.skipUnless( + platform.machine() in AUDIT_ARCH, "seccomp table covers x86_64 and aarch64" +) +class StageWithoutSignalsTests(unittest.TestCase): + def setUp(self): + self._tmp = tempfile.TemporaryDirectory() + self.addCleanup(self._tmp.cleanup) + self.src = Path(self._tmp.name) / "src" + self.dest = Path(self._tmp.name) / "dest" + _tree(self.src, {"README.md": "readme\n", "pkg/a/data.yml": "- x\n"}) + + def test_the_harness_refuses_every_signal(self): + result = _run_without_signals(["bash", "-c", "kill -0 $$"]) + self.assertNotEqual(result.returncode, 0) + self.assertIn("Permission denied", result.stderr) + + def test_staging_finishes_while_signals_are_refused(self): + result = _stage(self.src, self.dest) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertTrue( + filecmp.cmp( + self.src / "pkg/a/data.yml", + self.dest / "pkg/a/data.yml", + shallow=False, + ) + ) + + def test_a_name_pattern_drops_matches_at_every_depth(self): + _tree(self.src, {".git/HEAD": "ref\n", "pkg/a/.git": "gitdir\n"}) + result = _stage(self.src, self.dest, ".git") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertFalse((self.dest / ".git").exists()) + self.assertFalse((self.dest / "pkg/a/.git").exists()) + self.assertTrue((self.dest / "pkg/a/data.yml").is_file()) + + def test_a_path_pattern_drops_only_that_subtree(self): + _tree( + self.src, + {"packaging/debian/control": "c\n", "packaging/arch/PKGBUILD": "p\n"}, + ) + result = _stage(self.src, self.dest, "packaging/debian") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertFalse((self.dest / "packaging/debian").exists()) + self.assertTrue((self.dest / "packaging/arch/PKGBUILD").is_file()) + + def test_a_previous_workspace_is_replaced(self): + _tree(self.dest, {"stale.txt": "old\n"}) + result = _stage(self.src, self.dest) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertFalse((self.dest / "stale.txt").exists()) + + def test_symlinks_stay_links(self): + (self.src / "link").symlink_to("README.md") + result = _stage(self.src, self.dest) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual((self.dest / "link").readlink(), Path("README.md")) + + def test_the_executable_bit_survives(self): + script = self.src / "run.sh" + script.write_text("#!/bin/sh\n") + script.chmod(0o755) + result = _stage(self.src, self.dest) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertTrue( + stat.S_IMODE((self.dest / "run.sh").stat().st_mode) & stat.S_IXUSR + ) + + def test_a_missing_destination_is_rejected(self): + result = _run_without_signals(["bash", str(STAGE), str(self.src)]) + self.assertNotEqual(result.returncode, 0) + self.assertFalse(self.dest.exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/scripts/system/apparmor/test_common.py b/tests/unit/python/scripts/system/apparmor/test_common.py index 8b4440f1e4..c688d8b670 100644 --- a/tests/unit/python/scripts/system/apparmor/test_common.py +++ b/tests/unit/python/scripts/system/apparmor/test_common.py @@ -8,7 +8,9 @@ profile, and BuildKit then failed each node image RUN step with from __future__ import annotations import subprocess +import tempfile import unittest +from pathlib import Path from utils.cache.files import PROJECT_ROOT @@ -44,5 +46,74 @@ class TestRemovableProfiles(unittest.TestCase): ) +def _call(function: str, sysctl: Path, state: Path) -> subprocess.CompletedProcess: + return subprocess.run( + [ + "bash", + "-c", + f'source "{COMMON}"; {function} "$1" "$2"', + "-", + str(sysctl), + str(state), + ], + capture_output=True, + text=True, + check=False, + ) + + +def _value(path: Path) -> str: + return path.read_text().strip() # nocheck: cache-read - per-test temp file + + +class TestUnconfinedRestriction(unittest.TestCase): + def setUp(self) -> None: + self._tmp = tempfile.TemporaryDirectory() + self.addCleanup(self._tmp.cleanup) + self.sysctl = Path(self._tmp.name) / "apparmor_restrict_unprivileged_unconfined" + self.state = Path(self._tmp.name) / "run" / "infinito" / "restriction" + + def test_lifting_turns_the_restriction_off(self) -> None: + self.sysctl.write_text("1\n") + result = _call("apparmor_lift_unconfined_restriction", self.sysctl, self.state) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(_value(self.sysctl), "0") + + def test_lifting_records_the_previous_value(self) -> None: + self.sysctl.write_text("1\n") + _call("apparmor_lift_unconfined_restriction", self.sysctl, self.state) + self.assertEqual(_value(self.state), "1") + + def test_lifting_an_already_lifted_restriction_records_nothing(self) -> None: + self.sysctl.write_text("0\n") + result = _call("apparmor_lift_unconfined_restriction", self.sysctl, self.state) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertFalse(self.state.exists()) + + def test_a_kernel_without_the_sysctl_is_left_alone(self) -> None: + result = _call("apparmor_lift_unconfined_restriction", self.sysctl, self.state) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertFalse(self.sysctl.exists()) + self.assertFalse(self.state.exists()) + + def test_reinstating_restores_the_recorded_value(self) -> None: + self.sysctl.write_text("1\n") + _call("apparmor_lift_unconfined_restriction", self.sysctl, self.state) + result = _call( + "apparmor_reinstate_unconfined_restriction", self.sysctl, self.state + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(_value(self.sysctl), "1") + self.assertFalse(self.state.exists()) + + def test_reinstating_without_a_record_changes_nothing(self) -> None: + self.sysctl.write_text("0\n") + result = _call( + "apparmor_reinstate_unconfined_restriction", self.sysctl, self.state + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(_value(self.sysctl), "0") + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/utils/update/test_follow.py b/tests/unit/python/utils/update/test_follow.py index 036f756f43..d119f19b3c 100644 --- a/tests/unit/python/utils/update/test_follow.py +++ b/tests/unit/python/utils/update/test_follow.py @@ -1,9 +1,14 @@ from __future__ import annotations +import contextlib +import http.client +import io +import json import unittest +import urllib.error from unittest import mock -from utils.update.follow import followed_tags +from utils.update.follow import followed_tags, tag_digest UBUNTU = { "latest": "sha256:lts", @@ -40,10 +45,47 @@ class TestFollowedTags(unittest.TestCase): self.assertEqual(followed_tags("fedora", tags, {"version": "44"}, "44"), tags) self.assertEqual(followed_tags("fedora", tags, None, "44"), tags) - def test_an_unreadable_registry_proposes_nothing(self) -> None: - with mock.patch("utils.update.follow.tag_digest", side_effect=OSError): + def test_an_unreadable_registry_proposes_nothing_and_says_so(self) -> None: + stderr = io.StringIO() + with ( + mock.patch("utils.update.follow.tag_digest", side_effect=OSError("429")), + contextlib.redirect_stderr(stderr), + ): found = followed_tags("fedora", list(FEDORA), {"follow": "latest"}, "44") self.assertEqual(found, []) + self.assertIn("WARN fedora:44", stderr.getvalue()) + + def test_an_incomplete_response_proposes_nothing_and_says_so(self) -> None: + stderr = io.StringIO() + with ( + mock.patch( + "utils.update.follow.get", + side_effect=http.client.IncompleteRead(b"{", 120), + ), + contextlib.redirect_stderr(stderr), + ): + found = followed_tags("fedora", list(FEDORA), {"follow": "latest"}, "44") + self.assertEqual(found, []) + self.assertIn("WARN fedora:44", stderr.getvalue()) + self.assertIn("IncompleteRead", stderr.getvalue()) + + def test_a_rate_limited_digest_is_retried(self) -> None: + limited = urllib.error.HTTPError("url", 429, "Too Many Requests", {}, None) + body = json.dumps({"digest": "sha256:45"}).encode() + with ( + mock.patch("utils.update.follow.get", side_effect=[limited, body]), + mock.patch("utils.update.follow.time.sleep"), + ): + self.assertEqual(tag_digest("fedora", "latest"), "sha256:45") + + def test_a_persistent_rate_limit_still_raises(self) -> None: + limited = urllib.error.HTTPError("url", 429, "Too Many Requests", {}, None) + with ( + mock.patch("utils.update.follow.get", side_effect=[limited] * 3), + mock.patch("utils.update.follow.time.sleep"), + self.assertRaises(urllib.error.HTTPError), + ): + tag_digest("fedora", "latest") if __name__ == "__main__": diff --git a/utils/update/follow.py b/utils/update/follow.py index 5444196ef2..8c22f84128 100644 --- a/utils/update/follow.py +++ b/utils/update/follow.py @@ -9,12 +9,18 @@ rawhide) point elsewhere. from __future__ import annotations +import http.client import json +import sys +import time +import urllib.error from utils.docker.image.ref import dockerhub_repo from utils.update.base import version_depth, version_flavor, version_key from utils.update.fetch import get +RETRIES = 3 + def tag_digest(image: str, tag: str) -> str: """Return the digest Docker Hub reports for ``image:tag``. @@ -24,7 +30,14 @@ def tag_digest(image: str, tag: str) -> str: tag: the tag to resolve. """ url = f"https://hub.docker.com/v2/repositories/{dockerhub_repo(image)}/tags/{tag}" - return str(json.loads(get(url))["digest"]) + for attempt in range(RETRIES): + try: + return str(json.loads(get(url))["digest"]) + except urllib.error.HTTPError as exc: + if exc.code != 429 or attempt == RETRIES - 1: + raise + time.sleep(2**attempt) + raise RuntimeError(f"{image}:{tag}: no digest after {RETRIES} attempts") def followed_tags( @@ -42,7 +55,7 @@ def followed_tags( Returns: The tags unchanged without ``follow``; otherwise the newer tags of the pin's depth and flavor that share the followed tag's digest, and none - when Docker Hub cannot be read. + when Docker Hub cannot be read, which is reported on stderr. """ follow = config.get("follow") if isinstance(config, dict) else None if follow is None: @@ -56,6 +69,23 @@ def followed_tags( ] try: target = tag_digest(image, str(follow)) - return [tag for tag in newer if tag_digest(image, tag) == target] - except (OSError, ValueError, KeyError): + kept = [tag for tag in newer if tag_digest(image, tag) == target] + except ( + OSError, + ValueError, + KeyError, + RuntimeError, + http.client.HTTPException, + ) as exc: + print( + f"[follow] WARN {image}:{current}: Docker Hub digests unreadable " + f"({type(exc).__name__}: {exc}); proposing nothing", + file=sys.stderr, + ) return [] + print( + f"[follow] {image}:{current}: {follow} matches {kept or 'none'} " + f"among newer {newer or 'none'}", + file=sys.stderr, + ) + return kept