From 36c4b388dc64941280bcbe3e1f274101c167c00d Mon Sep 17 00:00:00 2001 From: Yashvardhan Nanavati Date: Tue, 14 Jul 2026 23:04:04 -0700 Subject: [PATCH 1/2] feat: parallelize per-arch image pushes and deduplicate manifest tag push Speed up multi-arch builds by pushing per-arch images to the registry in parallel via ThreadPoolExecutor before manifest list creation. This pre-populates registry layers so `buildah manifest push --all` completes faster (~4.5 min saved). For the second manifest tag (commit SHA), use `skopeo copy --all` to copy the manifest list server-side instead of rebuilding it from scratch. Additional robustness improvements: - Add `_verify_manifest_list` to confirm all expected architectures are present in the local manifest list before pushing - Broaden HTTP error regex in `run_cmd` so push failures (403, 5xx) are classified as retryable `ExternalServiceError` - Add 3600s timeout to `_push_image` - Use `docker://` prefix in `buildah manifest add` for remote images - Collect all parallel push errors before raising Co-Authored-By: Claude Opus 4.6 --- .../multi-arch-builder.py | 183 ++++++++++++------ tests/unit/test_multi_arch_builder.py | 146 +++++++++++++- 2 files changed, 263 insertions(+), 66 deletions(-) diff --git a/task/iib-image-builder-oci-ta/multi-arch-builder.py b/task/iib-image-builder-oci-ta/multi-arch-builder.py index 248765f..e7ef093 100644 --- a/task/iib-image-builder-oci-ta/multi-arch-builder.py +++ b/task/iib-image-builder-oci-ta/multi-arch-builder.py @@ -14,9 +14,10 @@ import shutil import subprocess import sys +from concurrent.futures import ThreadPoolExecutor, as_completed +from typing import List, Dict, Any, Optional from dataclasses import dataclass, field from pathlib import Path -from typing import Any from tenacity import ( before_sleep_log, @@ -133,9 +134,10 @@ def run_cmd( ): raise IIBError("Error deleting packages from database") elif cmd[0] == "buildah": - # Check for HTTP 403 or 50X errors on buildah + # Check for transient network/registry errors on any buildah operation network_regexes = [ r".*([e,E]rror:? creating build container).*(:?(403|50[0-9]|125)\s?.*$)", + r".*((?:403 Forbidden|50[0-9] \w+).*$)", r".*(read\/write on closed pipe.*$)", ] for regex in network_regexes: @@ -510,7 +512,6 @@ def _build_image(self, arch: str, destination: str) -> None: destination, ) - # Prepare buildah command with improved options cmd = [ "buildah", "bud", @@ -530,20 +531,16 @@ def _build_image(self, arch: str, destination: str) -> None: self.config.dockerfile_path, ] - # Add labels for label in self.config.labels: cmd.extend(["--label", label.strip()]) if self.config.binary_image: cmd.extend(["--build-arg", f"BINARY_IMAGE={self.config.binary_image}"]) - # Add context cmd.append(self.config.context_path) - # Execute build with retry logic run_cmd(cmd, {"timeout": 3600}, f"build for {arch} failed") - # Verify architecture was set correctly logger.debug("Verifying that %s was built with expected arch %s", destination, arch) self._verify_image_architecture(destination, arch) @@ -554,9 +551,12 @@ def _verify_image_architecture(self, image_name: str, expected_arch: str) -> Non :param str image_name: the image name to verify :param str expected_arch: the expected architecture """ - - # Get image architecture using skopeo inspect - inspect_cmd = ["skopeo", "inspect", "--no-tags", f"containers-storage:{image_name}"] + inspect_cmd = [ + "skopeo", + "inspect", + "--no-tags", + f"containers-storage:{image_name}", + ] result = run_cmd(inspect_cmd, {"timeout": 60}, f"inspect {image_name} failed") image_data = json.loads(result) @@ -585,6 +585,43 @@ def _verify_image_architecture(self, image_name: str, expected_arch: str) -> Non logger.info(f"✓ Architecture verification passed for {image_name}: {arch}") + @retry( + before_sleep=before_sleep_log(logger, logging.WARNING), + reraise=True, + retry=retry_if_exception_type(ExternalServiceError), + stop=stop_after_attempt(3), + wait=wait_exponential(multiplier=2), + ) + def _push_image(self, image: str) -> None: + """Push a single architecture image to the registry.""" + logger.info("Pushing %s to registry", image) + cmd = [ + "buildah", + "push", + "--tls-verify=true", + image, + f"docker://{image}", + ] + run_cmd(cmd, {"timeout": 3600}, exc_msg=f"Failed to push {image}") + logger.info("✓ Pushed %s", image) + + def _verify_manifest_list(self, manifest_name: str, platform_images: List[str]) -> None: + """Verify the local manifest list contains all expected architectures.""" + result = run_cmd( + ["buildah", "manifest", "inspect", manifest_name], + exc_msg=f"Failed to inspect manifest list {manifest_name}", + ) + manifest_data = json.loads(result) + manifests = manifest_data.get("manifests", []) + found_arches = sorted(m.get("platform", {}).get("architecture", "") for m in manifests) + expected_arches = sorted(self.config.arch_map.get(p, p) for p in self.config.platforms) + if found_arches != expected_arches: + raise IIBError( + f"Manifest list {manifest_name} has architectures {found_arches}, " + f"expected {expected_arches}" + ) + logger.info("✓ Manifest list %s verified: %s", manifest_name, ", ".join(found_arches)) + @retry( before_sleep=before_sleep_log(logger, logging.WARNING), reraise=True, @@ -604,55 +641,71 @@ def _create_and_push_manifest_list( """ buildah_manifest_cmd = ["buildah", "manifest"] image_name_repo, image_name_tag = self.config.image_name.split(":", 1) - # Initialize _tags with the output image tag _tags = [image_name_tag] if self.config.commit_sha: _tags.append(self.config.commit_sha) - output_pull_specs = [] - for tag in _tags: - output_pull_spec = f"{image_name_repo}:{tag}" - output_pull_specs.append(output_pull_spec) - try: - run_cmd( - buildah_manifest_cmd + ["rm", output_pull_spec], - exc_msg=( - f"Failed to remove local manifest list. {output_pull_spec} does not exist" - ), - ) - except IIBError as e: - error_msg = str(e) - if "Manifest list not found locally." not in error_msg: - raise IIBError(f"Error removing local manifest list: {error_msg}") - logger.debug( - "Manifest list cannot be removed. No manifest list %s found", output_pull_spec - ) - logger.info("Creating the manifest list %s locally", output_pull_spec) + primary_pull_spec = f"{image_name_repo}:{_tags[0]}" + + # Build and push the manifest list for the primary tag + try: run_cmd( - buildah_manifest_cmd + ["create", output_pull_spec], - exc_msg=f"Failed to create the manifest list locally: {output_pull_spec}", + buildah_manifest_cmd + ["rm", primary_pull_spec], + exc_msg=( + f"Failed to remove local manifest list. {primary_pull_spec} does not exist" + ), + ) + except IIBError as e: + error_msg = str(e) + if "Manifest list not found locally." not in error_msg: + raise IIBError(f"Error removing local manifest list: {error_msg}") + logger.debug( + "Manifest list cannot be removed. No manifest list %s found", + primary_pull_spec, + ) + logger.info("Creating the manifest list %s locally", primary_pull_spec) + run_cmd( + buildah_manifest_cmd + ["create", primary_pull_spec], + exc_msg=f"Failed to create the manifest list locally: {primary_pull_spec}", + ) + for arch_image in platform_images: + run_cmd( + buildah_manifest_cmd + ["add", primary_pull_spec, f"docker://{arch_image}"], + exc_msg=( + f"Failed to add {arch_image} to the local manifest list: {primary_pull_spec}" + ), ) - for arch_image in platform_images: - run_cmd( - buildah_manifest_cmd + ["add", output_pull_spec, arch_image], - exc_msg=( - f"Failed to add {arch_image} to the local manifest list: {output_pull_spec}" - ), - ) - logger.debug("Pushing manifest list %s", output_pull_spec) + self._verify_manifest_list(primary_pull_spec, platform_images) + + logger.debug("Pushing manifest list %s", primary_pull_spec) + run_cmd( + buildah_manifest_cmd + + [ + "push", + "--all", + "--format", + "v2s2", + "--tls-verify=true", + primary_pull_spec, + f"docker://{primary_pull_spec}", + ], + exc_msg=f"Failed to push the manifest list to {primary_pull_spec}", + ) + + # Copy the manifest list to additional tags via skopeo (server-side) + for tag in _tags[1:]: + additional_pull_spec = f"{image_name_repo}:{tag}" + logger.info("Copying manifest list to %s", additional_pull_spec) run_cmd( - buildah_manifest_cmd - + [ - "push", + [ + "skopeo", + "copy", "--all", - "--format", - "v2s2", - "--tls-verify=true", - output_pull_spec, - f"docker://{output_pull_spec}", + f"docker://{primary_pull_spec}", + f"docker://{additional_pull_spec}", ], - exc_msg=f"Failed to push the manifest list to {output_pull_spec}", + exc_msg=f"Failed to copy manifest list to {additional_pull_spec}", ) def build_all(self, ca_bundle_path: str | None = None) -> dict[str, Any]: @@ -735,18 +788,30 @@ def build_all(self, ca_bundle_path: str | None = None) -> dict[str, Any]: logger.error(f"Failed to copy cache to build context: {e}") raise IIBError(f"Failed to copy cache to build context: {e}") - # Build images for each platform + # Build and verify images sequentially, then push in parallel platform_images = [] for platform in self.config.platforms: - try: - platform_clean = platform.strip() - # output-image:tag-platform - platform_image = f"{self.config.image_name}-{platform_clean}" - self._build_image(platform_clean, platform_image) - platform_images.append(platform_image) - except (IIBError, ExternalServiceError) as e: - logger.error(f"Failed to build for {platform}: {e}") - raise + platform_clean = platform.strip() + platform_image = f"{self.config.image_name}-{platform_clean}" + self._build_image(platform_clean, platform_image) + platform_images.append(platform_image) + + # Push all per-arch images in parallel so registry layers are + # present before manifest list creation + logger.info("Pushing per-arch images in parallel") + with ThreadPoolExecutor(max_workers=len(platform_images)) as executor: + futures = {executor.submit(self._push_image, img): img for img in platform_images} + errors = {} + for future in as_completed(futures): + img = futures[future] + try: + future.result() + except Exception as e: + logger.error("Failed to push %s: %s", img, e) + errors[img] = e + if errors: + failed = ", ".join(sorted(errors)) + raise IIBError(f"Failed to push per-arch images: {failed}") # Create and push manifest logger.info("Creating and pushing multi-arch manifest") diff --git a/tests/unit/test_multi_arch_builder.py b/tests/unit/test_multi_arch_builder.py index dad9b89..edc411e 100644 --- a/tests/unit/test_multi_arch_builder.py +++ b/tests/unit/test_multi_arch_builder.py @@ -496,6 +496,122 @@ def test_raises_external_service_error_on_network_failure( builder._build_image.__wrapped__(builder, "amd64", "quay.io/org/img:latest-amd64") +# --------------------------------------------------------------------------- +# MultiArchBuilder._push_image +# --------------------------------------------------------------------------- + + +class TestPushImage: + @patch("multi_arch_builder.run_cmd") + def test_executes_buildah_push_with_correct_flags(self, mock_run_cmd, builder): + builder._push_image.__wrapped__(builder, "quay.io/org/img:latest-amd64") + cmd = mock_run_cmd.call_args[0][0] + assert cmd == [ + "buildah", + "push", + "--tls-verify=true", + "quay.io/org/img:latest-amd64", + "docker://quay.io/org/img:latest-amd64", + ] + + @patch("multi_arch_builder.run_cmd", side_effect=mab.ExternalServiceError("503")) + def test_raises_external_service_error_on_network_failure(self, mock_run_cmd, builder): + with pytest.raises(mab.ExternalServiceError): + builder._push_image.__wrapped__(builder, "quay.io/org/img:latest-amd64") + + +# --------------------------------------------------------------------------- +# MultiArchBuilder._verify_manifest_list +# --------------------------------------------------------------------------- + + +class TestVerifyManifestList: + @patch("multi_arch_builder.run_cmd") + def test_passes_when_all_arches_present(self, mock_run_cmd, builder): + builder.config.platforms = ["amd64", "arm64"] + mock_run_cmd.return_value = json.dumps( + { + "manifests": [ + {"platform": {"architecture": "amd64"}}, + {"platform": {"architecture": "arm64"}}, + ] + } + ) + builder._verify_manifest_list("quay.io/org/img:v1", ["img-amd64", "img-arm64"]) + + @patch("multi_arch_builder.run_cmd") + def test_raises_when_arch_missing(self, mock_run_cmd, builder): + builder.config.platforms = ["amd64", "arm64", "s390x"] + mock_run_cmd.return_value = json.dumps( + { + "manifests": [ + {"platform": {"architecture": "amd64"}}, + {"platform": {"architecture": "arm64"}}, + ] + } + ) + with pytest.raises(mab.IIBError, match="expected.*s390x"): + builder._verify_manifest_list("quay.io/org/img:v1", ["img-amd64", "img-arm64"]) + + @patch("multi_arch_builder.run_cmd") + def test_raises_when_extra_arch_present(self, mock_run_cmd, builder): + builder.config.platforms = ["amd64"] + mock_run_cmd.return_value = json.dumps( + { + "manifests": [ + {"platform": {"architecture": "amd64"}}, + {"platform": {"architecture": "arm64"}}, + ] + } + ) + with pytest.raises(mab.IIBError, match="expected"): + builder._verify_manifest_list("quay.io/org/img:v1", ["img-amd64"]) + + @patch("multi_arch_builder.MultiArchBuilder._create_and_push_manifest_list") + @patch("multi_arch_builder.MultiArchBuilder._build_image") + @patch("multi_arch_builder.generate_cache_locally") + @patch("multi_arch_builder.MultiArchBuilder._prepare_system") + @patch("multi_arch_builder.run_cmd") + def test_parallel_push_reports_all_failures( + self, + mock_run_cmd, + mock_prepare, + mock_gen_cache, + mock_build, + mock_manifest, + builder, + tmp_path, + ): + """When multiple arch pushes fail, all are reported before raising.""" + context = tmp_path / "ctx" + context.mkdir() + (context / "configs").mkdir() + cache_dir = tmp_path / "cache" + cache_dir.mkdir() + dockerfile = context / "Dockerfile" + dockerfile.write_text("FROM scratch\n") + builder.config.context_path = str(context) + builder.config.dockerfile_path = str(dockerfile) + builder.config.cache_dir = str(cache_dir) + builder.config.platforms = ["amd64", "arm64"] + + def run_cmd_side_effect(cmd, *args, **kwargs): + if cmd[0] == "buildah" and "push" in cmd: + raise mab.IIBError(f"push failed for {cmd[-1]}") + return '{"Digest": "sha256:abc"}' + + mock_run_cmd.side_effect = run_cmd_side_effect + mock_gen_cache.side_effect = lambda *a, **kw: ( + (cache_dir / "cache").mkdir(exist_ok=True), + (cache_dir / "cache" / "pkg.json").write_text("{}"), + (cache_dir / "digest").write_text("abc"), + ) + + with pytest.raises(mab.IIBError, match="Failed to push per-arch images"): + builder.build_all() + mock_manifest.assert_not_called() + + # --------------------------------------------------------------------------- # MultiArchBuilder.build_all – catalog dir permission normalization # --------------------------------------------------------------------------- @@ -730,28 +846,40 @@ def populate_cache(*args, **kwargs): class TestCreateAndPushManifestList: + @staticmethod + def _manifest_inspect_json(arches): + return json.dumps({"manifests": [{"platform": {"architecture": a}} for a in arches]}) + @patch("multi_arch_builder.run_cmd") - def test_creates_and_pushes_manifest_for_each_tag(self, mock_run_cmd, builder): - """With a commit_sha, two tags should be created and pushed.""" + def test_creates_manifest_and_copies_to_second_tag(self, mock_run_cmd, builder): + """With a commit_sha, primary tag is built+pushed, second is skopeo-copied.""" builder.config.image_name = "quay.io/org/img:latest" builder.config.commit_sha = "abc123" platform_images = [ "quay.io/org/img:latest-amd64", "quay.io/org/img:latest-arm64", ] - # First call (rm) raises IIBError("Manifest list not found locally.") → tolerated def side_effect(cmd, *args, **kwargs): if "rm" in cmd: raise mab.IIBError("Manifest list not found locally.") + if "inspect" in cmd: + return self._manifest_inspect_json(["amd64", "arm64"]) return "" mock_run_cmd.side_effect = side_effect - # Should not raise builder._create_and_push_manifest_list.__wrapped__(builder, platform_images) - # Expect: for each of 2 tags → rm + create + 2×add + push = 5 calls × 2 = 10 - assert mock_run_cmd.call_count == 10 + # Primary tag: rm + create + 2×add + inspect + push = 6 + # Second tag: 1 skopeo copy = 7 total + assert mock_run_cmd.call_count == 7 + # Last call should be skopeo copy + last_cmd = mock_run_cmd.call_args_list[-1][0][0] + assert last_cmd[0] == "skopeo" + assert "copy" in last_cmd + assert "--all" in last_cmd + assert "docker://quay.io/org/img:latest" in last_cmd + assert "docker://quay.io/org/img:abc123" in last_cmd @patch("multi_arch_builder.run_cmd") def test_removes_existing_manifest_before_creating(self, mock_run_cmd, builder): @@ -764,6 +892,8 @@ def side_effect(cmd, *args, **kwargs): if "rm" in cmd: rm_attempted.append(True) raise mab.IIBError("Manifest list not found locally.") + if "inspect" in cmd: + return self._manifest_inspect_json(["amd64", "arm64"]) return "" mock_run_cmd.side_effect = side_effect @@ -796,10 +926,12 @@ def test_push_uses_docker_scheme_and_all_flag(self, mock_run_cmd, builder): push_cmds = [] def side_effect(cmd, *args, **kwargs): - if "push" in cmd: + if cmd[0] == "buildah" and "push" in cmd: push_cmds.append(cmd) if "rm" in cmd: raise mab.IIBError("Manifest list not found locally.") + if "inspect" in cmd: + return self._manifest_inspect_json(["amd64", "arm64"]) return "" mock_run_cmd.side_effect = side_effect From e6087f16ccf48fe0f13e185eefdc62361704490a Mon Sep 17 00:00:00 2001 From: Yashvardhan Nanavati Date: Mon, 9 Nov 2026 15:35:57 -0500 Subject: [PATCH 2/2] fix: verify published multi-arch manifest and push digests --- .../multi-arch-builder.py | 186 ++++++--- tests/unit/test_multi_arch_builder.py | 378 +++++++++++++++--- 2 files changed, 468 insertions(+), 96 deletions(-) diff --git a/task/iib-image-builder-oci-ta/multi-arch-builder.py b/task/iib-image-builder-oci-ta/multi-arch-builder.py index e7ef093..dda6202 100644 --- a/task/iib-image-builder-oci-ta/multi-arch-builder.py +++ b/task/iib-image-builder-oci-ta/multi-arch-builder.py @@ -14,8 +14,9 @@ import shutil import subprocess import sys +import tempfile from concurrent.futures import ThreadPoolExecutor, as_completed -from typing import List, Dict, Any, Optional +from typing import Any from dataclasses import dataclass, field from pathlib import Path @@ -329,6 +330,9 @@ def arches_from_metadata(metadata: dict[str, Any]) -> list[str] | None: "array must contain at least one architecture" ) + if len(arches) != len(set(arches)): + raise IIBError("Invalid arches in IIB build metadata file: duplicate architectures") + return arches @@ -592,35 +596,74 @@ def _verify_image_architecture(self, image_name: str, expected_arch: str) -> Non stop=stop_after_attempt(3), wait=wait_exponential(multiplier=2), ) - def _push_image(self, image: str) -> None: - """Push a single architecture image to the registry.""" + def _push_image(self, image: str) -> str: + """Push an architecture image and return its remote manifest digest.""" logger.info("Pushing %s to registry", image) - cmd = [ - "buildah", - "push", - "--tls-verify=true", - image, - f"docker://{image}", - ] - run_cmd(cmd, {"timeout": 3600}, exc_msg=f"Failed to push {image}") - logger.info("✓ Pushed %s", image) - - def _verify_manifest_list(self, manifest_name: str, platform_images: List[str]) -> None: - """Verify the local manifest list contains all expected architectures.""" - result = run_cmd( - ["buildah", "manifest", "inspect", manifest_name], - exc_msg=f"Failed to inspect manifest list {manifest_name}", - ) + with tempfile.TemporaryDirectory(prefix="iib-push-") as directory: + digest_file = Path(directory) / "digest" + cmd = [ + "buildah", + "push", + "--tls-verify=true", + "--digestfile", + str(digest_file), + image, + f"docker://{image}", + ] + run_cmd(cmd, {"timeout": 3600}, exc_msg=f"Failed to push {image}") + digest = digest_file.read_text(encoding="utf-8").strip() if digest_file.exists() else "" + if not re.fullmatch(r"sha256:[0-9a-f]{64}", digest): + raise IIBError(f"Invalid push digest for {image}: {digest!r}") + logger.info("✓ Pushed %s at %s", image, digest) + return digest + + def _verify_manifest_list( + self, + manifest_name: str, + platform_images: list[str], + pushed_digests: dict[str, str], + remote_digest: str | None = None, + ) -> None: + """Verify a local or published list points to this run's pushed images.""" + if len(platform_images) != len(self.config.platforms) or set(platform_images) != set( + pushed_digests + ): + raise IIBError("Platform images and pushed digests do not match configured platforms") + if remote_digest: + image_repo = manifest_name.rsplit(":", 1)[0] + result = run_cmd( + ["skopeo", "inspect", "--raw", f"docker://{image_repo}@{remote_digest}"], + {"timeout": 60}, + f"Failed to inspect published manifest {image_repo}@{remote_digest}", + ) + else: + result = run_cmd( + ["buildah", "manifest", "inspect", manifest_name], + exc_msg=f"Failed to inspect manifest list {manifest_name}", + ) manifest_data = json.loads(result) manifests = manifest_data.get("manifests", []) - found_arches = sorted(m.get("platform", {}).get("architecture", "") for m in manifests) - expected_arches = sorted(self.config.arch_map.get(p, p) for p in self.config.platforms) - if found_arches != expected_arches: + found = sorted( + ( + m.get("platform", {}).get("os", ""), + m.get("platform", {}).get("architecture", ""), + m.get("digest", ""), + ) + for m in manifests + ) + expected = sorted( + ("linux", self.config.arch_map.get(platform, platform), pushed_digests[image]) + for platform, image in zip(self.config.platforms, platform_images, strict=True) + ) + if found != expected: raise IIBError( - f"Manifest list {manifest_name} has architectures {found_arches}, " - f"expected {expected_arches}" + f"Manifest list {manifest_name} has entries {found}, expected {expected}" ) - logger.info("✓ Manifest list %s verified: %s", manifest_name, ", ".join(found_arches)) + logger.info( + "✓ Manifest list %s verified: %s", + manifest_name, + ", ".join(arch for _, arch, _ in found), + ) @retry( before_sleep=before_sleep_log(logger, logging.WARNING), @@ -632,7 +675,8 @@ def _verify_manifest_list(self, manifest_name: str, platform_images: List[str]) def _create_and_push_manifest_list( self, platform_images: list[str], - ) -> None: + pushed_digests: dict[str, str], + ) -> str: """ Create and push the manifest list to the configured registry. @@ -640,7 +684,7 @@ def _create_and_push_manifest_list( :raises IIBError: if creating or pushing the manifest list fails """ buildah_manifest_cmd = ["buildah", "manifest"] - image_name_repo, image_name_tag = self.config.image_name.split(":", 1) + image_name_repo, image_name_tag = self.config.image_name.rsplit(":", 1) _tags = [image_name_tag] if self.config.commit_sha: _tags.append(self.config.commit_sha) @@ -669,31 +713,56 @@ def _create_and_push_manifest_list( exc_msg=f"Failed to create the manifest list locally: {primary_pull_spec}", ) for arch_image in platform_images: + image_repo = arch_image.rsplit(":", 1)[0] run_cmd( - buildah_manifest_cmd + ["add", primary_pull_spec, f"docker://{arch_image}"], + buildah_manifest_cmd + + ["add", primary_pull_spec, f"docker://{image_repo}@{pushed_digests[arch_image]}"], exc_msg=( f"Failed to add {arch_image} to the local manifest list: {primary_pull_spec}" ), ) - self._verify_manifest_list(primary_pull_spec, platform_images) + self._verify_manifest_list(primary_pull_spec, platform_images, pushed_digests) logger.debug("Pushing manifest list %s", primary_pull_spec) - run_cmd( - buildah_manifest_cmd - + [ - "push", - "--all", - "--format", - "v2s2", - "--tls-verify=true", - primary_pull_spec, - f"docker://{primary_pull_spec}", - ], - exc_msg=f"Failed to push the manifest list to {primary_pull_spec}", + with tempfile.TemporaryDirectory(prefix="iib-manifest-") as directory: + digest_file = Path(directory) / "digest" + run_cmd( + buildah_manifest_cmd + + [ + "push", + "--all", + "--format", + "v2s2", + "--tls-verify=true", + "--digestfile", + str(digest_file), + primary_pull_spec, + f"docker://{primary_pull_spec}", + ], + exc_msg=f"Failed to push the manifest list to {primary_pull_spec}", + ) + manifest_digest = ( + digest_file.read_text(encoding="utf-8").strip() if digest_file.exists() else "" + ) + if not re.fullmatch(r"sha256:[0-9a-f]{64}", manifest_digest): + raise IIBError( + f"Invalid manifest push digest for {primary_pull_spec}: {manifest_digest!r}" + ) + + primary_inspect = run_cmd( + ["skopeo", "inspect", "--no-tags", f"docker://{primary_pull_spec}"], + {"timeout": 60}, + f"Failed to inspect pushed manifest {primary_pull_spec}", + ) + if json.loads(primary_inspect).get("Digest") != manifest_digest: + raise IIBError(f"Primary manifest tag {primary_pull_spec} has a different digest") + + self._verify_manifest_list( + primary_pull_spec, platform_images, pushed_digests, remote_digest=manifest_digest ) - # Copy the manifest list to additional tags via skopeo (server-side) + # Copy the complete manifest list under each additional tag. for tag in _tags[1:]: additional_pull_spec = f"{image_name_repo}:{tag}" logger.info("Copying manifest list to %s", additional_pull_spec) @@ -702,11 +771,22 @@ def _create_and_push_manifest_list( "skopeo", "copy", "--all", - f"docker://{primary_pull_spec}", + "--preserve-digests", + f"docker://{image_name_repo}@{manifest_digest}", f"docker://{additional_pull_spec}", ], + {"timeout": 3600}, exc_msg=f"Failed to copy manifest list to {additional_pull_spec}", ) + additional_inspect = run_cmd( + ["skopeo", "inspect", "--no-tags", f"docker://{additional_pull_spec}"], + {"timeout": 60}, + f"Failed to inspect manifest tag {additional_pull_spec}", + ) + if json.loads(additional_inspect).get("Digest") != manifest_digest: + raise IIBError(f"Manifest tag {additional_pull_spec} has a different digest") + + return manifest_digest def build_all(self, ca_bundle_path: str | None = None) -> dict[str, Any]: """ @@ -720,6 +800,15 @@ def build_all(self, ca_bundle_path: str | None = None) -> dict[str, Any]: """ logger.info("Starting multi-architecture build") + normalized_platforms = [platform.strip() for platform in self.config.platforms] + if len(normalized_platforms) != len(set(normalized_platforms)): + duplicates = sorted( + platform + for platform in set(normalized_platforms) + if normalized_platforms.count(platform) > 1 + ) + raise IIBError(f"Duplicate architectures: {', '.join(duplicates)}") + # Validate Dockerfile exists if not self.validate_dockerfile(): raise RuntimeError("Dockerfile validation failed") @@ -799,13 +888,14 @@ def build_all(self, ca_bundle_path: str | None = None) -> dict[str, Any]: # Push all per-arch images in parallel so registry layers are # present before manifest list creation logger.info("Pushing per-arch images in parallel") + pushed_digests: dict[str, str] = {} with ThreadPoolExecutor(max_workers=len(platform_images)) as executor: futures = {executor.submit(self._push_image, img): img for img in platform_images} errors = {} for future in as_completed(futures): img = futures[future] try: - future.result() + pushed_digests[img] = future.result() except Exception as e: logger.error("Failed to push %s: %s", img, e) errors[img] = e @@ -817,13 +907,7 @@ def build_all(self, ca_bundle_path: str | None = None) -> dict[str, Any]: logger.info("Creating and pushing multi-arch manifest") # Create and push manifest list - self._create_and_push_manifest_list(platform_images) - - # Get manifest digest - inspect_cmd = ["skopeo", "inspect", "--no-tags", f"docker://{self.config.image_name}"] - result = run_cmd(inspect_cmd, {"timeout": 60}, "inspect manifest failed") - manifest_data = json.loads(result) - digest = manifest_data.get("Digest", "") + digest = self._create_and_push_manifest_list(platform_images, pushed_digests) results = { "image_name": self.config.image_name, diff --git a/tests/unit/test_multi_arch_builder.py b/tests/unit/test_multi_arch_builder.py index edc411e..69bbfb1 100644 --- a/tests/unit/test_multi_arch_builder.py +++ b/tests/unit/test_multi_arch_builder.py @@ -9,6 +9,7 @@ import json import os import subprocess +from pathlib import Path from unittest.mock import MagicMock, patch import multi_arch_builder as mab @@ -27,6 +28,12 @@ def _make_completed_process(returncode=0, stdout="", stderr=""): return proc +def _run_cmd_with_push_digest(cmd, *args, **kwargs): + if "--digestfile" in cmd: + Path(cmd[cmd.index("--digestfile") + 1]).write_text("sha256:" + "a" * 64) + return '{"Digest": "sha256:abc"}' + + # --------------------------------------------------------------------------- # _regex_reverse_search # --------------------------------------------------------------------------- @@ -503,16 +510,36 @@ def test_raises_external_service_error_on_network_failure( class TestPushImage: @patch("multi_arch_builder.run_cmd") - def test_executes_buildah_push_with_correct_flags(self, mock_run_cmd, builder): - builder._push_image.__wrapped__(builder, "quay.io/org/img:latest-amd64") + def test_returns_remote_digest_from_push(self, mock_run_cmd, builder): + digest = "sha256:" + "a" * 64 + + def push_with_digest(cmd, *args, **kwargs): + Path(cmd[cmd.index("--digestfile") + 1]).write_text(digest + "\n") + + mock_run_cmd.side_effect = push_with_digest + result = builder._push_image.__wrapped__(builder, "quay.io/org/img:latest-amd64") + assert result == digest cmd = mock_run_cmd.call_args[0][0] - assert cmd == [ - "buildah", - "push", - "--tls-verify=true", + assert cmd[:3] == ["buildah", "push", "--tls-verify=true"] + assert cmd[-2:] == [ "quay.io/org/img:latest-amd64", "docker://quay.io/org/img:latest-amd64", ] + assert "--digestfile" in cmd + + @patch("multi_arch_builder.run_cmd") + def test_rejects_missing_push_digest(self, mock_run_cmd, builder): + with pytest.raises(mab.IIBError, match="digest"): + builder._push_image.__wrapped__(builder, "quay.io/org/img:latest-amd64") + + @patch("multi_arch_builder.run_cmd") + def test_rejects_malformed_push_digest(self, mock_run_cmd, builder): + def push_with_bad_digest(cmd, *args, **kwargs): + Path(cmd[cmd.index("--digestfile") + 1]).write_text("sha256:bad\n") + + mock_run_cmd.side_effect = push_with_bad_digest + with pytest.raises(mab.IIBError, match="digest"): + builder._push_image.__wrapped__(builder, "quay.io/org/img:latest-amd64") @patch("multi_arch_builder.run_cmd", side_effect=mab.ExternalServiceError("503")) def test_raises_external_service_error_on_network_failure(self, mock_run_cmd, builder): @@ -529,43 +556,87 @@ class TestVerifyManifestList: @patch("multi_arch_builder.run_cmd") def test_passes_when_all_arches_present(self, mock_run_cmd, builder): builder.config.platforms = ["amd64", "arm64"] + digests = {"img-amd64": "sha256:" + "a" * 64, "img-arm64": "sha256:" + "b" * 64} mock_run_cmd.return_value = json.dumps( { "manifests": [ - {"platform": {"architecture": "amd64"}}, - {"platform": {"architecture": "arm64"}}, + { + "platform": {"os": "linux", "architecture": "amd64"}, + "digest": digests["img-amd64"], + }, + { + "platform": {"os": "linux", "architecture": "arm64"}, + "digest": digests["img-arm64"], + }, ] } ) - builder._verify_manifest_list("quay.io/org/img:v1", ["img-amd64", "img-arm64"]) + builder._verify_manifest_list("quay.io/org/img:v1", ["img-amd64", "img-arm64"], digests) @patch("multi_arch_builder.run_cmd") def test_raises_when_arch_missing(self, mock_run_cmd, builder): builder.config.platforms = ["amd64", "arm64", "s390x"] + digests = { + "img-amd64": "sha256:" + "a" * 64, + "img-arm64": "sha256:" + "b" * 64, + "img-s390x": "sha256:" + "c" * 64, + } mock_run_cmd.return_value = json.dumps( { "manifests": [ - {"platform": {"architecture": "amd64"}}, - {"platform": {"architecture": "arm64"}}, + { + "platform": {"os": "linux", "architecture": "amd64"}, + "digest": digests["img-amd64"], + }, + { + "platform": {"os": "linux", "architecture": "arm64"}, + "digest": digests["img-arm64"], + }, ] } ) with pytest.raises(mab.IIBError, match="expected.*s390x"): - builder._verify_manifest_list("quay.io/org/img:v1", ["img-amd64", "img-arm64"]) + builder._verify_manifest_list( + "quay.io/org/img:v1", ["img-amd64", "img-arm64", "img-s390x"], digests + ) @patch("multi_arch_builder.run_cmd") def test_raises_when_extra_arch_present(self, mock_run_cmd, builder): builder.config.platforms = ["amd64"] + digests = {"img-amd64": "sha256:" + "a" * 64} mock_run_cmd.return_value = json.dumps( { "manifests": [ - {"platform": {"architecture": "amd64"}}, - {"platform": {"architecture": "arm64"}}, + { + "platform": {"os": "linux", "architecture": "amd64"}, + "digest": digests["img-amd64"], + }, + { + "platform": {"os": "linux", "architecture": "arm64"}, + "digest": "sha256:" + "b" * 64, + }, ] } ) with pytest.raises(mab.IIBError, match="expected"): - builder._verify_manifest_list("quay.io/org/img:v1", ["img-amd64"]) + builder._verify_manifest_list("quay.io/org/img:v1", ["img-amd64"], digests) + + @patch("multi_arch_builder.run_cmd") + def test_rejects_wrong_child_digest_with_correct_architecture(self, mock_run_cmd, builder): + builder.config.platforms = ["amd64"] + expected = {"img-amd64": "sha256:" + "a" * 64} + mock_run_cmd.return_value = json.dumps( + { + "manifests": [ + { + "platform": {"os": "linux", "architecture": "amd64"}, + "digest": "sha256:" + "b" * 64, + } + ] + } + ) + with pytest.raises(mab.IIBError, match="expected"): + builder._verify_manifest_list("quay.io/org/img:v1", ["img-amd64"], expected) @patch("multi_arch_builder.MultiArchBuilder._create_and_push_manifest_list") @patch("multi_arch_builder.MultiArchBuilder._build_image") @@ -687,7 +758,7 @@ def capture_modes(*args, **kwargs): (cache_dir / "digest").write_text("abc") mock_gen_cache.side_effect = capture_modes - mock_run_cmd.return_value = '{"Digest": "sha256:abc"}' + mock_run_cmd.side_effect = _run_cmd_with_push_digest umask_before = os.umask(0o022) os.umask(umask_before) @@ -718,6 +789,44 @@ def capture_modes(*args, **kwargs): class TestBuildAllSkipsOpmCacheForRegenerateBundle: + @patch("multi_arch_builder.MultiArchBuilder._create_and_push_manifest_list") + @patch("multi_arch_builder.MultiArchBuilder._build_image") + @patch("multi_arch_builder.MultiArchBuilder._prepare_system") + @patch("multi_arch_builder.run_cmd") + def test_uses_verified_push_digest_for_result( + self, mock_run_cmd, mock_prepare, mock_build, mock_manifest, builder, tmp_path + ): + dockerfile = tmp_path / "Dockerfile" + dockerfile.write_text("FROM scratch\n") + builder.config.dockerfile_path = str(dockerfile) + builder.config.skip_opm_cache = True + builder.config.platforms = ["amd64"] + mock_manifest.return_value = "sha256:" + "c" * 64 + mock_run_cmd.side_effect = _run_cmd_with_push_digest + + result = builder.build_all() + + assert result["digest"] == "sha256:" + "c" * 64 + assert not any( + call.args[0][:2] == ["skopeo", "inspect"] for call in mock_run_cmd.call_args_list + ) + + @patch("multi_arch_builder.MultiArchBuilder._build_image") + @patch("multi_arch_builder.MultiArchBuilder._prepare_system") + def test_rejects_duplicate_platforms_before_building( + self, mock_prepare, mock_build, builder, tmp_path + ): + dockerfile = tmp_path / "Dockerfile" + dockerfile.write_text("FROM scratch\n") + builder.config.dockerfile_path = str(dockerfile) + builder.config.skip_opm_cache = True + builder.config.platforms = ["amd64", " amd64 "] + + with pytest.raises(mab.IIBError, match="Duplicate.*amd64"): + builder.build_all() + + mock_build.assert_not_called() + @patch("multi_arch_builder.MultiArchBuilder._create_and_push_manifest_list") @patch("multi_arch_builder.MultiArchBuilder._build_image") @patch("multi_arch_builder.generate_cache_locally") @@ -749,11 +858,15 @@ def test_skips_cache_generation_when_skip_opm_cache_is_true( skip_opm_cache=True, ) builder = mab.MultiArchBuilder(cfg) - mock_run_cmd.return_value = '{"Digest": "sha256:abc"}' + mock_run_cmd.side_effect = _run_cmd_with_push_digest builder.build_all() mock_gen_cache.assert_not_called() + mock_manifest.assert_called_once_with( + ["quay.io/org/img:latest-amd64"], + {"quay.io/org/img:latest-amd64": "sha256:" + "a" * 64}, + ) @patch("multi_arch_builder.MultiArchBuilder._create_and_push_manifest_list") @patch("multi_arch_builder.MultiArchBuilder._build_image") @@ -786,7 +899,7 @@ def test_does_not_require_configs_directory_when_skip_opm_cache( skip_opm_cache=True, ) builder = mab.MultiArchBuilder(cfg) - mock_run_cmd.return_value = '{"Digest": "sha256:abc"}' + mock_run_cmd.side_effect = _run_cmd_with_push_digest builder.build_all() @@ -833,7 +946,7 @@ def populate_cache(*args, **kwargs): (cache_dir / "packages.json").write_text("{}") mock_gen_cache.side_effect = populate_cache - mock_run_cmd.return_value = '{"Digest": "sha256:abc"}' + mock_run_cmd.side_effect = _run_cmd_with_push_digest builder.build_all() @@ -848,43 +961,197 @@ def populate_cache(*args, **kwargs): class TestCreateAndPushManifestList: @staticmethod def _manifest_inspect_json(arches): - return json.dumps({"manifests": [{"platform": {"architecture": a}} for a in arches]}) + digests = {"amd64": "sha256:" + "a" * 64, "arm64": "sha256:" + "b" * 64} + return json.dumps( + { + "manifests": [ + {"platform": {"os": "linux", "architecture": arch}, "digest": digests[arch]} + for arch in arches + ] + } + ) @patch("multi_arch_builder.run_cmd") - def test_creates_manifest_and_copies_to_second_tag(self, mock_run_cmd, builder): - """With a commit_sha, primary tag is built+pushed, second is skopeo-copied.""" + def test_rejects_remote_manifest_with_wrong_child_digest(self, mock_run_cmd, builder): + builder.config.image_name = "quay.io/org/img:latest" + builder.config.commit_sha = "" + builder.config.platforms = ["amd64"] + image = "quay.io/org/img:latest-amd64" + + def side_effect(cmd, *args, **kwargs): + if cmd[:3] == ["buildah", "manifest", "rm"]: + raise mab.IIBError("Manifest list not found locally.") + if cmd[:3] == ["buildah", "manifest", "inspect"]: + return self._manifest_inspect_json(["amd64"]) + if cmd[:3] == ["buildah", "manifest", "push"]: + Path(cmd[cmd.index("--digestfile") + 1]).write_text("sha256:" + "c" * 64) + if cmd[:2] == ["skopeo", "inspect"] and "--raw" in cmd: + return json.dumps( + { + "schemaVersion": 2, + "mediaType": "application/vnd.docker.distribution.manifest.list.v2+json", + "manifests": [ + { + "mediaType": "application/vnd.docker.distribution.manifest.v2+json", + "digest": "sha256:" + "b" * 64, + "size": 123, + "platform": {"architecture": "amd64", "os": "linux"}, + } + ], + } + ) + if cmd[:2] == ["skopeo", "inspect"]: + return json.dumps({"Digest": "sha256:" + "c" * 64}) + return "" + + mock_run_cmd.side_effect = side_effect + + with pytest.raises(mab.IIBError, match="Manifest list.*expected"): + builder._create_and_push_manifest_list.__wrapped__( + builder, [image], {image: "sha256:" + "a" * 64} + ) + + @patch("multi_arch_builder.run_cmd") + def test_keeps_registry_port_in_manifest_reference(self, mock_run_cmd, builder): + builder.config.image_name = "registry.example:5000/org/img:v1" + builder.config.commit_sha = "abc123" + builder.config.platforms = ["amd64"] + image = "registry.example:5000/org/img:v1-amd64" + + def side_effect(cmd, *args, **kwargs): + if cmd[:3] == ["buildah", "manifest", "rm"]: + raise mab.IIBError("Manifest list not found locally.") + if cmd[:3] == ["buildah", "manifest", "inspect"]: + return self._manifest_inspect_json(["amd64"]) + if cmd[:3] == ["buildah", "manifest", "push"]: + Path(cmd[cmd.index("--digestfile") + 1]).write_text("sha256:" + "c" * 64) + if cmd[:2] == ["skopeo", "inspect"] and "--raw" in cmd: + return self._manifest_inspect_json(["amd64"]) + if cmd[:2] == ["skopeo", "inspect"]: + return json.dumps({"Digest": "sha256:" + "c" * 64}) + return "" + + mock_run_cmd.side_effect = side_effect + builder._create_and_push_manifest_list.__wrapped__( + builder, [image], {image: "sha256:" + "a" * 64} + ) + commands = [call.args[0] for call in mock_run_cmd.call_args_list] + assert ["buildah", "manifest", "create", "registry.example:5000/org/img:v1"] in commands + assert [ + "skopeo", + "copy", + "--all", + "--preserve-digests", + "docker://registry.example:5000/org/img@sha256:" + "c" * 64, + "docker://registry.example:5000/org/img:abc123", + ] in commands + + @patch("multi_arch_builder.run_cmd") + def test_adds_pushed_digests_and_pushes_all_for_safety(self, mock_run_cmd, builder): builder.config.image_name = "quay.io/org/img:latest" builder.config.commit_sha = "abc123" platform_images = [ "quay.io/org/img:latest-amd64", "quay.io/org/img:latest-arm64", ] + pushed_digests = { + platform_images[0]: "sha256:" + "a" * 64, + platform_images[1]: "sha256:" + "b" * 64, + } def side_effect(cmd, *args, **kwargs): if "rm" in cmd: raise mab.IIBError("Manifest list not found locally.") - if "inspect" in cmd: + if cmd[:3] == ["buildah", "manifest", "inspect"]: + return self._manifest_inspect_json(["amd64", "arm64"]) + if cmd[:3] == ["buildah", "manifest", "push"]: + Path(cmd[cmd.index("--digestfile") + 1]).write_text("sha256:" + "c" * 64) + if cmd[:2] == ["skopeo", "inspect"] and "--raw" in cmd: return self._manifest_inspect_json(["amd64", "arm64"]) + if cmd[:2] == ["skopeo", "inspect"]: + return json.dumps({"Digest": "sha256:" + "c" * 64}) + return "" + + mock_run_cmd.side_effect = side_effect + manifest_digest = builder._create_and_push_manifest_list.__wrapped__( + builder, platform_images, pushed_digests + ) + assert manifest_digest == "sha256:" + "c" * 64 + + commands = [call.args[0] for call in mock_run_cmd.call_args_list] + add_commands = [cmd for cmd in commands if cmd[:3] == ["buildah", "manifest", "add"]] + assert add_commands == [ + [ + "buildah", + "manifest", + "add", + "quay.io/org/img:latest", + "docker://quay.io/org/img@sha256:" + "a" * 64, + ], + [ + "buildah", + "manifest", + "add", + "quay.io/org/img:latest", + "docker://quay.io/org/img@sha256:" + "b" * 64, + ], + ] + push = next(cmd for cmd in commands if cmd[:3] == ["buildah", "manifest", "push"]) + assert "--all" in push + assert "--all=false" not in push + assert "--digestfile" in push + assert [cmd for cmd in commands if cmd[:2] == ["skopeo", "copy"]] == [ + [ + "skopeo", + "copy", + "--all", + "--preserve-digests", + "docker://quay.io/org/img@sha256:" + "c" * 64, + "docker://quay.io/org/img:abc123", + ] + ] + assert not any(cmd[:2] == ["oras", "tag"] for cmd in commands) + assert [ + "skopeo", + "inspect", + "--raw", + "docker://quay.io/org/img@sha256:" + "c" * 64, + ] in commands + assert sum(cmd[:2] == ["skopeo", "inspect"] for cmd in commands) == 3 + + @patch("multi_arch_builder.run_cmd") + def test_rejects_second_tag_with_different_digest(self, mock_run_cmd, builder): + builder.config.image_name = "quay.io/org/img:latest" + builder.config.commit_sha = "abc123" + image = "quay.io/org/img:latest-amd64" + builder.config.platforms = ["amd64"] + pushed_digests = {image: "sha256:" + "a" * 64} + + def side_effect(cmd, *args, **kwargs): + if "rm" in cmd: + raise mab.IIBError("Manifest list not found locally.") + if cmd[:3] == ["buildah", "manifest", "inspect"]: + return self._manifest_inspect_json(["amd64"]) + if cmd[:3] == ["buildah", "manifest", "push"]: + Path(cmd[cmd.index("--digestfile") + 1]).write_text("sha256:" + "c" * 64) + if cmd[:2] == ["skopeo", "inspect"] and "--raw" in cmd: + return self._manifest_inspect_json(["amd64"]) + if cmd[:2] == ["skopeo", "inspect"]: + digest = "sha256:" + ("d" if cmd[-1].endswith(":abc123") else "c") * 64 + return json.dumps({"Digest": digest}) return "" mock_run_cmd.side_effect = side_effect - builder._create_and_push_manifest_list.__wrapped__(builder, platform_images) - - # Primary tag: rm + create + 2×add + inspect + push = 6 - # Second tag: 1 skopeo copy = 7 total - assert mock_run_cmd.call_count == 7 - # Last call should be skopeo copy - last_cmd = mock_run_cmd.call_args_list[-1][0][0] - assert last_cmd[0] == "skopeo" - assert "copy" in last_cmd - assert "--all" in last_cmd - assert "docker://quay.io/org/img:latest" in last_cmd - assert "docker://quay.io/org/img:abc123" in last_cmd + with pytest.raises(mab.IIBError, match="digest"): + builder._create_and_push_manifest_list.__wrapped__(builder, [image], pushed_digests) @patch("multi_arch_builder.run_cmd") def test_removes_existing_manifest_before_creating(self, mock_run_cmd, builder): builder.config.image_name = "quay.io/org/img:latest" builder.config.commit_sha = "" + builder.config.platforms = ["amd64"] + image = "quay.io/org/img:latest-amd64" + pushed_digests = {image: "sha256:" + "a" * 64} rm_attempted = [] @@ -892,14 +1159,18 @@ def side_effect(cmd, *args, **kwargs): if "rm" in cmd: rm_attempted.append(True) raise mab.IIBError("Manifest list not found locally.") - if "inspect" in cmd: - return self._manifest_inspect_json(["amd64", "arm64"]) + if cmd[:3] == ["buildah", "manifest", "inspect"]: + return self._manifest_inspect_json(["amd64"]) + if cmd[:3] == ["buildah", "manifest", "push"]: + Path(cmd[cmd.index("--digestfile") + 1]).write_text("sha256:" + "c" * 64) + if cmd[:2] == ["skopeo", "inspect"] and "--raw" in cmd: + return self._manifest_inspect_json(["amd64"]) + if cmd[:2] == ["skopeo", "inspect"]: + return json.dumps({"Digest": "sha256:" + "c" * 64}) return "" mock_run_cmd.side_effect = side_effect - builder._create_and_push_manifest_list.__wrapped__( - builder, ["quay.io/org/img:latest-amd64"] - ) + builder._create_and_push_manifest_list.__wrapped__(builder, [image], pushed_digests) assert rm_attempted @patch("multi_arch_builder.run_cmd") @@ -915,13 +1186,16 @@ def side_effect(cmd, *args, **kwargs): mock_run_cmd.side_effect = side_effect with pytest.raises(mab.IIBError, match="Error removing local manifest list"): builder._create_and_push_manifest_list.__wrapped__( - builder, ["quay.io/org/img:latest-amd64"] + builder, + ["quay.io/org/img:latest-amd64"], + {"quay.io/org/img:latest-amd64": "sha256:" + "a" * 64}, ) @patch("multi_arch_builder.run_cmd") - def test_push_uses_docker_scheme_and_all_flag(self, mock_run_cmd, builder): + def test_push_uses_docker_scheme_and_includes_children(self, mock_run_cmd, builder): builder.config.image_name = "quay.io/org/img:v1" builder.config.commit_sha = "" + builder.config.platforms = ["amd64"] push_cmds = [] @@ -930,12 +1204,22 @@ def side_effect(cmd, *args, **kwargs): push_cmds.append(cmd) if "rm" in cmd: raise mab.IIBError("Manifest list not found locally.") - if "inspect" in cmd: - return self._manifest_inspect_json(["amd64", "arm64"]) + if cmd[:3] == ["buildah", "manifest", "inspect"]: + return self._manifest_inspect_json(["amd64"]) + if cmd[:3] == ["buildah", "manifest", "push"]: + Path(cmd[cmd.index("--digestfile") + 1]).write_text("sha256:" + "c" * 64) + if cmd[:2] == ["skopeo", "inspect"] and "--raw" in cmd: + return self._manifest_inspect_json(["amd64"]) + if cmd[:2] == ["skopeo", "inspect"]: + return json.dumps({"Digest": "sha256:" + "c" * 64}) return "" mock_run_cmd.side_effect = side_effect - builder._create_and_push_manifest_list.__wrapped__(builder, ["quay.io/org/img:v1-amd64"]) + builder._create_and_push_manifest_list.__wrapped__( + builder, + ["quay.io/org/img:v1-amd64"], + {"quay.io/org/img:v1-amd64": "sha256:" + "a" * 64}, + ) assert push_cmds, "push was never called" push_cmd = push_cmds[0] @@ -1053,6 +1337,10 @@ def test_raises_when_arches_empty(self): with pytest.raises(mab.IIBError, match="at least one architecture"): mab.arches_from_metadata({"arches": []}) + def test_rejects_duplicate_arches_after_trimming(self): + with pytest.raises(mab.IIBError, match="duplicate architectures"): + mab.arches_from_metadata({"arches": ["amd64", " amd64 "]}) + class TestBinaryImageFromMetadata: def test_returns_image_reference(self, sample_iib_metadata):