This is an automated email from the ASF dual-hosted git repository.

apupier pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 5e0bd653519029c87a9d2ee61892a268faf3d388
Author: Aurélien Pupier <[email protected]>
AuthorDate: Tue Nov 24 08:19:01 2026 +0100

    CAMEL-26387: retry the pull inside HostArchitectureImagePullPolicy and use 
the daemon architecture
    
    Address the review of the pull request:
    - do the retries of the pull in the policy, as Testcontainers does, until
      pull.timeout. Retry when the pull is interrupted because it made no
      progress (the interrupted status is not restored, it would make the next
      Docker call and the sleep of the caller fail at once), on a server error
      and when the registry quota is exceeded. Other failures, like an image
      without a variant for the platform, fail at once with a clear message.
      This does not depend on TestServiceUtil.tryInitialize, which is not used 
by
      the services created with createSingletonService()
    - use the architecture of the Docker daemon instead of the one of the JVM,
      the JVM one is only used if the daemon one is not known
    - document the scope (all the containers of the classpath, like Ryuk, which
      has ppc64le and s390x variants), the precedence and the concurrency
      limitations
    - make the policy testable with a package-private constructor and add unit
      tests for the remove, pull, retry and failure paths
    
    Co-authored-by: IBM Bob 2.2.1
    Signed-off-by: Aurélien Pupier <[email protected]>
---
 .../common/HostArchitectureImagePullPolicy.java    | 283 ++++++++++++++++-----
 .../HostArchitectureImagePullPolicyTest.java       | 228 +++++++++++++++++
 2 files changed, 454 insertions(+), 57 deletions(-)

diff --git 
a/test-infra/camel-test-infra-common/src/main/java/org/apache/camel/test/infra/common/HostArchitectureImagePullPolicy.java
 
b/test-infra/camel-test-infra-common/src/main/java/org/apache/camel/test/infra/common/HostArchitectureImagePullPolicy.java
index 51783910586f..f611637d65aa 100644
--- 
a/test-infra/camel-test-infra-common/src/main/java/org/apache/camel/test/infra/common/HostArchitectureImagePullPolicy.java
+++ 
b/test-infra/camel-test-infra-common/src/main/java/org/apache/camel/test/infra/common/HostArchitectureImagePullPolicy.java
@@ -16,10 +16,13 @@
  */
 package org.apache.camel.test.infra.common;
 
+import java.time.Duration;
+import java.time.Instant;
 import java.util.Locale;
 
 import com.github.dockerjava.api.DockerClient;
-import com.github.dockerjava.api.command.InspectImageResponse;
+import com.github.dockerjava.api.exception.DockerClientException;
+import com.github.dockerjava.api.exception.InternalServerErrorException;
 import com.github.dockerjava.api.exception.NotFoundException;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -29,9 +32,10 @@ import org.testcontainers.images.ImagePullPolicy;
 import org.testcontainers.images.TimeLimitedLoggedPullImageResultCallback;
 import org.testcontainers.utility.DockerImageName;
 import org.testcontainers.utility.DockerLoggerFactory;
+import org.testcontainers.utility.TestcontainersConfiguration;
 
 /**
- * Testcontainers {@link ImagePullPolicy} making sure that the image used 
matches the architecture of the host.
+ * Testcontainers {@link ImagePullPolicy} making sure that the image used 
matches the architecture of the Docker daemon.
  * <p>
  * When pulling an image fails (for instance because the registry mirror 
replies {@code toomanyrequests}),
  * Testcontainers silently retries the pull for {@code linux/amd64}. On hosts 
with another architecture (ppc64le, s390x)
@@ -42,20 +46,37 @@ import org.testcontainers.utility.DockerLoggerFactory;
  * <p>
  * When the check is enabled, this policy:
  * <ul>
- * <li>removes a local image whose architecture differs from the host one, and 
logs it</li>
- * <li>pulls the image itself, explicitly for the host platform, without any 
fallback to another architecture. If this
- * fails a {@link ContainerFetchException} is thrown, which is retried by
- * {@link 
org.apache.camel.test.infra.common.services.TestServiceUtil#tryInitialize}</li>
+ * <li>removes a local image whose architecture differs from the daemon one, 
and logs it</li>
+ * <li>pulls the image itself, explicitly for the daemon platform, without any 
fallback to another architecture</li>
+ * <li>as Testcontainers does, retries the pull until {@code pull.timeout} 
(default 120s) when it is interrupted because
+ * it made no progress, when the daemon replies with a server error or when 
the registry replies that a quota or rate
+ * limit is exceeded ({@code toomanyrequests}). Any other failure, like an 
image that has no variant for the platform,
+ * is not retried and fails immediately with a {@link 
ContainerFetchException}</li>
+ * <li>checks the architecture of the image after the pull</li>
  * </ul>
- * The check is enabled by default on ppc64le and s390x hosts, and can be 
forced on or off with the
+ * The retries are done by the policy itself, they do not depend on the 
caller, for instance
+ * {@link 
org.apache.camel.test.infra.common.services.TestServiceUtil#tryInitialize} is 
not used by the services created
+ * with {@code createSingletonService()}.
+ * <p>
+ * The check is enabled by default on ppc64le and s390x daemons, and can be 
forced on or off with the
  * {@value #CHECK_PROPERTY} system property. When disabled, the behavior is 
the same as the Testcontainers default
- * policy: an image is only pulled if it is not available locally.
+ * policy: an image is only pulled if it is not available locally. The 
architecture is the one of the Docker daemon,
+ * which can be different from the one of the JVM, for instance with a remote 
{@code DOCKER_HOST}. The JVM one is only
+ * used when the daemon one cannot be determined.
  * <p>
- * This policy is registered through the {@code testcontainers.properties} 
file of this module.
+ * <b>Scope:</b> this policy is registered through the {@code 
testcontainers.properties} file of this module, which is
+ * in the jar. Testcontainers merges all the {@code testcontainers.properties} 
files of the classpath, so the policy
+ * applies to all the containers started with Testcontainers when this module 
is on the classpath, not only to the ones
+ * of {@code camel-test-infra}, for instance the Ryuk container or the ones of 
downstream projects. It is the same as
+ * the Testcontainers default on amd64 and arm64. The {@code 
TESTCONTAINERS_PULL_POLICY} environment variable, the
+ * {@code ~/.testcontainers.properties} file and a {@code 
testcontainers.properties} file in the module test resources
+ * have precedence. If several jars of the classpath define {@code 
pull.policy}, which one is used is not defined.
  * <p>
- * <b>Concurrency:</b> Testcontainers constructs a new policy instance per 
container and calls {@code shouldPull} once
- * per image, so concurrent calls for the same image are not expected in 
normal use. No additional synchronization is
- * applied.
+ * <b>Concurrency:</b> Testcontainers uses one instance of the policy for the 
JVM, and {@code shouldPull} is called for
+ * each container started, so it can be called concurrently for the same 
image. Docker operations are not atomic: two
+ * callers can both find a wrong-architecture image and remove or pull it at 
the same time. This is tolerated: removing
+ * and pulling are idempotent and a failed removal is only logged. Several 
JVMs can also share the same daemon. This
+ * only happens if a wrong-architecture image is already in the cache.
  */
 public class HostArchitectureImagePullPolicy implements ImagePullPolicy {
 
@@ -63,89 +84,184 @@ public class HostArchitectureImagePullPolicy implements 
ImagePullPolicy {
 
     private static final Logger LOG = 
LoggerFactory.getLogger(HostArchitectureImagePullPolicy.class);
 
-    private final String hostArch;
-    private final boolean enabled;
+    private static final Duration INITIAL_RETRY_DELAY = Duration.ofSeconds(1);
+    private static final Duration MAX_RETRY_DELAY = Duration.ofSeconds(15);
+
+    private final ImageOperations operations;
+    private final Boolean enabledOverride;
+    private final Duration pullTimeout;
+    private final Duration initialRetryDelay;
+
+    private volatile String hostArch;
 
     public HostArchitectureImagePullPolicy() {
-        this.hostArch = normalizeArch(System.getProperty("os.arch"));
-        this.enabled = Boolean.parseBoolean(
-                System.getProperty(CHECK_PROPERTY, 
String.valueOf(isCheckedByDefault(hostArch))));
+        this(new DockerClientImageOperations(), null, null,
+             
Duration.ofSeconds(TestcontainersConfiguration.getInstance().getImagePullTimeout()),
 INITIAL_RETRY_DELAY);
+    }
+
+    /**
+     * @param operations        the operations on the Docker daemon
+     * @param hostArch          the architecture of the daemon, or {@code 
null} to get it from the daemon
+     * @param enabledOverride   if the check is enabled, or {@code null} to 
use the system property and the default of
+     *                          the architecture
+     * @param pullTimeout       the time during which a failed pull is retried
+     * @param initialRetryDelay the delay before the first retry, doubled for 
each retry
+     */
+    HostArchitectureImagePullPolicy(ImageOperations operations, String 
hostArch, Boolean enabledOverride,
+                                    Duration pullTimeout, Duration 
initialRetryDelay) {
+        this.operations = operations;
+        this.hostArch = hostArch == null ? null : normalizeArch(hostArch);
+        this.enabledOverride = enabledOverride;
+        this.pullTimeout = pullTimeout;
+        this.initialRetryDelay = initialRetryDelay;
     }
 
     @Override
     public boolean shouldPull(DockerImageName imageName) {
-        DockerClient client = DockerClientFactory.lazyClient();
         String name = imageName.asCanonicalNameString();
+        String arch = hostArch();
 
-        String localArch = inspectLocalArch(client, name);
-        if (!enabled) {
+        String localArch = operations.inspectArch(name);
+        if (!isEnabled(arch)) {
             return localArch == null;
         }
 
         if (localArch != null) {
-            if (hostArch.equals(normalizeArch(localArch))) {
+            if (arch.equals(normalizeArch(localArch))) {
                 return false;
             }
             LOG.warn("Local image {} has architecture {} but the host is {}, 
removing it and pulling it again",
-                    name, localArch, hostArch);
-            removeImage(client, name);
+                    name, localArch, arch);
+            removeImage(name);
         }
 
-        pullForHostPlatform(client, imageName);
+        pullForHostPlatform(imageName, arch);
         return false;
     }
 
-    private void pullForHostPlatform(DockerClient client, DockerImageName 
imageName) {
-        String name = imageName.asCanonicalNameString();
-        String platform = "linux/" + hostArch;
-        LOG.info("Pulling image {} for platform {}", name, platform);
+    private boolean isEnabled(String arch) {
+        if (enabledOverride != null) {
+            return enabledOverride;
+        }
+        return Boolean.parseBoolean(System.getProperty(CHECK_PROPERTY, 
String.valueOf(isCheckedByDefault(arch))));
+    }
+
+    private String hostArch() {
+        String arch = hostArch;
+        if (arch == null) {
+            arch = resolveHostArch();
+            hostArch = arch;
+        }
+        return arch;
+    }
+
+    private String resolveHostArch() {
+        String daemonArch = null;
         try {
-            client.pullImageCmd(imageName.getUnversionedPart())
-                    .withTag(imageName.getVersionPart())
-                    .withPlatform(platform)
-                    .exec(new 
TimeLimitedLoggedPullImageResultCallback(DockerLoggerFactory.getLogger(name)))
-                    .awaitCompletion();
-        } catch (InterruptedException e) {
-            Thread.currentThread().interrupt();
-            throw new ContainerFetchException("Interrupted while pulling image 
" + name + " for platform " + platform, e);
+            daemonArch = operations.daemonArch();
         } catch (RuntimeException e) {
-            // Do not let Testcontainers fall back to linux/amd64, this would 
leave an image that cannot run on this host
-            throw new ContainerFetchException(
-                    "Failed to pull image " + name + " for platform " + 
platform + " (set -D" + CHECK_PROPERTY
-                                              + "=false to disable the 
architecture check): " + e.getMessage(),
-                    e);
+            LOG.warn("Failed to get the architecture of the Docker daemon, 
using the one of the JVM: {}", e.getMessage());
+        }
+        if (daemonArch == null || daemonArch.isEmpty()) {
+            return normalizeArch(System.getProperty("os.arch"));
+        }
+        return normalizeArch(daemonArch);
+    }
+
+    private void pullForHostPlatform(DockerImageName imageName, String arch) {
+        String name = imageName.asCanonicalNameString();
+        String platform = "linux/" + arch;
+        LOG.info("Pulling image {} for platform {}", name, platform);
+
+        Instant deadline = Instant.now().plus(pullTimeout);
+        Duration delay = initialRetryDelay;
+        while (true) {
+            RuntimeException transientFailure;
+            try {
+                operations.pull(imageName, platform);
+                break;
+            } catch (InterruptedException e) {
+                // Testcontainers interrupts the thread when a pull made no 
progress for pull.pause.timeout, and retries
+                // the pull. The interrupted status is cleared when the 
exception is thrown, it must not be restored:
+                // that would make the next Docker call, or the sleep of the 
caller, fail immediately.
+                transientFailure = new ContainerFetchException("Pull of image 
" + name + " made no progress", e);
+            } catch (InternalServerErrorException e) {
+                transientFailure = e;
+            } catch (DockerClientException e) {
+                if (!isQuotaExceeded(e)) {
+                    throw permanentFailure(name, platform, e);
+                }
+                transientFailure = e;
+            } catch (RuntimeException e) {
+                throw permanentFailure(name, platform, e);
+            }
+
+            if (Instant.now().plus(delay).isAfter(deadline)) {
+                throw new ContainerFetchException(
+                        "Failed to pull image " + name + " for platform " + 
platform + " during "
+                                                  + pullTimeout.getSeconds() + 
"s: " + transientFailure.getMessage(),
+                        transientFailure);
+            }
+            LOG.warn("Pulling image {} for platform {} failed, retrying in 
{}ms ({}s remaining): {}", name, platform,
+                    delay.toMillis(), Duration.between(Instant.now(), 
deadline).getSeconds(),
+                    transientFailure.getMessage());
+            sleep(delay, name);
+            delay = delay.multipliedBy(2).compareTo(MAX_RETRY_DELAY) > 0 ? 
MAX_RETRY_DELAY : delay.multipliedBy(2);
         }
 
-        String pulledArch = inspectLocalArch(client, name);
+        String pulledArch = operations.inspectArch(name);
         if (pulledArch == null) {
-            // Pull succeeded but inspect returned no architecture — treat as 
a failed pull so the caller retries
             throw new ContainerFetchException(
-                    "Image " + name + " was pulled for platform " + platform
-                                              + " but could not be inspected 
afterwards");
+                    "Image " + name + " was pulled for platform " + platform + 
" but could not be inspected afterwards");
         }
-        if (!hostArch.equals(normalizeArch(pulledArch))) {
+        if (!arch.equals(normalizeArch(pulledArch))) {
             LOG.warn("Image {} has architecture {} after pulling it for 
platform {}, removing it", name, pulledArch,
                     platform);
-            removeImage(client, name);
+            removeImage(name);
             throw new ContainerFetchException(
-                    "Image " + name + " has architecture " + pulledArch + " 
but the host is " + hostArch);
+                    "Image " + name + " has architecture " + pulledArch + " 
but the host is " + arch);
         }
     }
 
-    private static String inspectLocalArch(DockerClient client, String name) {
+    private static void sleep(Duration delay, String name) {
         try {
-            InspectImageResponse image = client.inspectImageCmd(name).exec();
-            return image.getArch();
-        } catch (NotFoundException e) {
-            return null;
+            Thread.sleep(delay.toMillis());
+        } catch (InterruptedException e) {
+            Thread.currentThread().interrupt();
+            throw new ContainerFetchException("Interrupted while waiting to 
pull image " + name + " again", e);
+        }
+    }
+
+    private static ContainerFetchException permanentFailure(String name, 
String platform, RuntimeException e) {
+        // Do not let Testcontainers fall back to linux/amd64, this would 
leave an image that cannot run on this host
+        String arch = platform.substring("linux/".length());
+        String skipHint = isCheckedByDefault(arch)
+                ? ", the tests needing it can be skipped with the skipITs." + 
arch
+                  + " Maven property"
+                : "";
+        return new ContainerFetchException(
+                "Failed to pull image " + name + " for platform " + platform
+                                           + ", it is probably not available 
for this platform" + skipHint
+                                           + ", set -D" + CHECK_PROPERTY
+                                           + "=false to disable the 
architecture check: " + e.getMessage(),
+                e);
+    }
+
+    private static boolean isQuotaExceeded(Exception e) {
+        String message = e.getMessage();
+        if (message == null) {
+            return false;
         }
+        String lower = message.toLowerCase(Locale.ROOT);
+        return lower.contains("toomanyrequests") || lower.contains("too many 
requests") || lower.contains("quota exceeded")
+                || lower.contains("rate limit");
     }
 
-    private static void removeImage(DockerClient client, String name) {
+    private void removeImage(String name) {
         try {
-            // withForce(true) untags and removes the image even if its tag is 
referenced by a stopped container;
-            // this is intentional so we do not leave a wrong-architecture 
image in the cache.
-            client.removeImageCmd(name).withForce(true).exec();
+            // Forced, to remove the image even if it is referenced by a 
stopped container: a wrong-architecture image
+            // must not stay in the cache.
+            operations.remove(name);
         } catch (RuntimeException e) {
             LOG.warn("Failed to remove image {}: {}", name, e.getMessage());
         }
@@ -174,4 +290,57 @@ public class HostArchitectureImagePullPolicy implements 
ImagePullPolicy {
                 return arch.toLowerCase(Locale.ROOT);
         }
     }
+
+    /**
+     * The operations done on the Docker daemon, to be able to test the policy 
without it.
+     */
+    interface ImageOperations {
+
+        /**
+         * @return the architecture of the Docker daemon, or {@code null} if 
it is not known
+         */
+        String daemonArch();
+
+        /**
+         * @return the architecture of the local image, or {@code null} if the 
image is not available locally
+         */
+        String inspectArch(String name);
+
+        void remove(String name);
+
+        void pull(DockerImageName imageName, String platform) throws 
InterruptedException;
+    }
+
+    private static final class DockerClientImageOperations implements 
ImageOperations {
+
+        @Override
+        public String daemonArch() {
+            return DockerClientFactory.instance().getInfo().getArchitecture();
+        }
+
+        @Override
+        public String inspectArch(String name) {
+            try {
+                return 
DockerClientFactory.lazyClient().inspectImageCmd(name).exec().getArch();
+            } catch (NotFoundException e) {
+                return null;
+            }
+        }
+
+        @Override
+        public void remove(String name) {
+            DockerClient client = DockerClientFactory.lazyClient();
+            client.removeImageCmd(name).withForce(true).exec();
+        }
+
+        @Override
+        public void pull(DockerImageName imageName, String platform) throws 
InterruptedException {
+            
DockerClientFactory.lazyClient().pullImageCmd(imageName.getUnversionedPart())
+                    .withTag(imageName.getVersionPart())
+                    .withPlatform(platform)
+                    .exec(new TimeLimitedLoggedPullImageResultCallback(
+                            
DockerLoggerFactory.getLogger(imageName.asCanonicalNameString())))
+                    .awaitCompletion();
+        }
+    }
 }
diff --git 
a/test-infra/camel-test-infra-common/src/test/java/org/apache/camel/test/infra/common/HostArchitectureImagePullPolicyTest.java
 
b/test-infra/camel-test-infra-common/src/test/java/org/apache/camel/test/infra/common/HostArchitectureImagePullPolicyTest.java
index 6302b767d594..fbbbd374a1dd 100644
--- 
a/test-infra/camel-test-infra-common/src/test/java/org/apache/camel/test/infra/common/HostArchitectureImagePullPolicyTest.java
+++ 
b/test-infra/camel-test-infra-common/src/test/java/org/apache/camel/test/infra/common/HostArchitectureImagePullPolicyTest.java
@@ -16,14 +16,30 @@
  */
 package org.apache.camel.test.infra.common;
 
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Queue;
+
+import com.github.dockerjava.api.exception.DockerClientException;
+import com.github.dockerjava.api.exception.InternalServerErrorException;
+import com.github.dockerjava.api.exception.NotFoundException;
 import org.junit.jupiter.api.Test;
+import org.testcontainers.containers.ContainerFetchException;
+import org.testcontainers.utility.DockerImageName;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
 class HostArchitectureImagePullPolicyTest {
 
+    private static final DockerImageName IMAGE = 
DockerImageName.parse("mirror.gcr.io/nats:2.15.3");
+    private static final String NAME = IMAGE.asCanonicalNameString();
+
     @Test
     void normalizesJavaAndDockerArchitectures() {
         assertEquals("amd64", 
HostArchitectureImagePullPolicy.normalizeArch("amd64"));
@@ -42,4 +58,216 @@ class HostArchitectureImagePullPolicyTest {
         
assertFalse(HostArchitectureImagePullPolicy.isCheckedByDefault("amd64"));
         
assertFalse(HostArchitectureImagePullPolicy.isCheckedByDefault("arm64"));
     }
+
+    @Test
+    void usesTheLocalImageWithTheRightArchitecture() {
+        StubOperations operations = new 
StubOperations("ppc64le").withLocalImage("ppc64le");
+
+        assertFalse(policy(operations, "ppc64le", true).shouldPull(IMAGE));
+
+        assertTrue(operations.pulls.isEmpty());
+        assertTrue(operations.removed.isEmpty());
+    }
+
+    @Test
+    void pullsAMissingImageForTheHostPlatform() {
+        StubOperations operations = new StubOperations("ppc64le");
+
+        assertFalse(policy(operations, "ppc64le", true).shouldPull(IMAGE));
+
+        assertEquals(List.of("linux/ppc64le"), operations.pulls);
+        assertEquals("ppc64le", operations.localArch);
+    }
+
+    @Test
+    void removesAndPullsAgainAnImageWithTheWrongArchitecture() {
+        StubOperations operations = new 
StubOperations("s390x").withLocalImage("amd64");
+
+        assertFalse(policy(operations, "s390x", true).shouldPull(IMAGE));
+
+        assertEquals(List.of(NAME), operations.removed);
+        assertEquals(List.of("linux/s390x"), operations.pulls);
+        assertEquals("s390x", operations.localArch);
+    }
+
+    @Test
+    void doesNothingWhenDisabled() {
+        StubOperations operations = new 
StubOperations("amd64").withLocalImage("arm64");
+        assertFalse(policy(operations, "amd64", false).shouldPull(IMAGE));
+
+        StubOperations missing = new StubOperations("amd64");
+        assertTrue(policy(missing, "amd64", false).shouldPull(IMAGE));
+
+        assertTrue(operations.pulls.isEmpty());
+        assertTrue(operations.removed.isEmpty());
+        assertTrue(missing.pulls.isEmpty());
+    }
+
+    @Test
+    void getsTheArchitectureFromTheDaemon() {
+        StubOperations operations = new StubOperations("ppc64le");
+        operations.daemonArch = "ppc64le";
+
+        assertFalse(policy(operations, null, null).shouldPull(IMAGE));
+
+        assertEquals(List.of("linux/ppc64le"), operations.pulls);
+    }
+
+    @Test
+    void fallsBackToTheJvmArchitectureWhenTheDaemonOneIsUnknown() {
+        StubOperations operations = new StubOperations(
+                HostArchitectureImagePullPolicy
+                        .normalizeArch(System.getProperty("os.arch")));
+        operations.daemonArch = null;
+        // the check is disabled by default except on ppc64le and s390x, force 
it to see the platform
+        assertFalse(policy(operations, null, true).shouldPull(IMAGE));
+
+        assertEquals(List.of("linux/" + 
HostArchitectureImagePullPolicy.normalizeArch(System.getProperty("os.arch"))),
+                operations.pulls);
+    }
+
+    @Test
+    void retriesWhenTheQuotaIsExceeded() {
+        StubOperations operations = new StubOperations("ppc64le");
+        operations.failures.add(new DockerClientException("Could not pull 
image: toomanyrequests: Quota exceeded"));
+        operations.failures.add(new DockerClientException("Could not pull 
image: toomanyrequests: Quota exceeded"));
+
+        assertFalse(policy(operations, "ppc64le", true).shouldPull(IMAGE));
+
+        assertEquals(3, operations.pulls.size());
+        assertEquals("ppc64le", operations.localArch);
+    }
+
+    @Test
+    void retriesWhenThePullMadeNoProgress() {
+        StubOperations operations = new StubOperations("ppc64le");
+        operations.interruptions = 1;
+
+        assertFalse(policy(operations, "ppc64le", true).shouldPull(IMAGE));
+
+        assertEquals(2, operations.pulls.size());
+        // the interrupted status must not be restored, it would make the 
following Docker calls and sleeps fail
+        assertFalse(Thread.currentThread().isInterrupted());
+    }
+
+    @Test
+    void retriesWhenTheDaemonFails() {
+        StubOperations operations = new StubOperations("ppc64le");
+        operations.failures.add(new InternalServerErrorException("timeout"));
+
+        assertFalse(policy(operations, "ppc64le", true).shouldPull(IMAGE));
+
+        assertEquals(2, operations.pulls.size());
+    }
+
+    @Test
+    void doesNotRetryWhenTheImageIsNotAvailableForThePlatform() {
+        StubOperations operations = new StubOperations("ppc64le");
+        operations.failures.add(new DockerClientException(
+                "Could not pull image: no matching manifest for linux/ppc64le 
in the manifest list entries"));
+
+        ContainerFetchException e = assertThrows(ContainerFetchException.class,
+                () -> policy(operations, "ppc64le", true).shouldPull(IMAGE));
+
+        assertEquals(1, operations.pulls.size());
+        assertTrue(e.getMessage().contains("skipITs.ppc64le"), e.getMessage());
+        assertNull(operations.localArch);
+    }
+
+    @Test
+    void doesNotRetryOtherFailures() {
+        StubOperations operations = new StubOperations("s390x");
+        operations.failures.add(new NotFoundException("no such image"));
+
+        assertThrows(ContainerFetchException.class, () -> policy(operations, 
"s390x", true).shouldPull(IMAGE));
+
+        assertEquals(1, operations.pulls.size());
+    }
+
+    @Test
+    void stopsRetryingAfterThePullTimeout() {
+        StubOperations operations = new StubOperations("ppc64le");
+        for (int i = 0; i < 100; i++) {
+            operations.failures.add(new 
DockerClientException("toomanyrequests"));
+        }
+        HostArchitectureImagePullPolicy policy = new 
HostArchitectureImagePullPolicy(
+                operations, "ppc64le", true, Duration.ofMillis(100), 
Duration.ofMillis(20));
+
+        assertThrows(ContainerFetchException.class, () -> 
policy.shouldPull(IMAGE));
+
+        assertTrue(operations.pulls.size() < 100);
+    }
+
+    @Test
+    void failsWhenTheImageCannotBeInspectedAfterThePull() {
+        StubOperations operations = new StubOperations("ppc64le");
+        operations.pulledArch = null;
+
+        assertThrows(ContainerFetchException.class, () -> policy(operations, 
"ppc64le", true).shouldPull(IMAGE));
+    }
+
+    @Test
+    void removesTheImageWhenItHasTheWrongArchitectureAfterThePull() {
+        StubOperations operations = new StubOperations("ppc64le");
+        operations.pulledArch = "amd64";
+
+        assertThrows(ContainerFetchException.class, () -> policy(operations, 
"ppc64le", true).shouldPull(IMAGE));
+
+        assertEquals(List.of(NAME), operations.removed);
+    }
+
+    private static HostArchitectureImagePullPolicy policy(StubOperations 
operations, String hostArch, Boolean enabled) {
+        return new HostArchitectureImagePullPolicy(
+                operations, hostArch, enabled, Duration.ofSeconds(10), 
Duration.ofMillis(1));
+    }
+
+    private static final class StubOperations implements 
HostArchitectureImagePullPolicy.ImageOperations {
+
+        final List<String> pulls = new ArrayList<>();
+        final List<String> removed = new ArrayList<>();
+        final Queue<RuntimeException> failures = new LinkedList<>();
+        String daemonArch;
+        String localArch;
+        String pulledArch;
+        int interruptions;
+
+        StubOperations(String pulledArch) {
+            this.pulledArch = pulledArch;
+        }
+
+        StubOperations withLocalImage(String arch) {
+            this.localArch = arch;
+            return this;
+        }
+
+        @Override
+        public String daemonArch() {
+            return daemonArch;
+        }
+
+        @Override
+        public String inspectArch(String name) {
+            return localArch;
+        }
+
+        @Override
+        public void remove(String name) {
+            removed.add(name);
+            localArch = null;
+        }
+
+        @Override
+        public void pull(DockerImageName imageName, String platform) throws 
InterruptedException {
+            pulls.add(platform);
+            if (interruptions > 0) {
+                interruptions--;
+                throw new InterruptedException("no progress");
+            }
+            RuntimeException failure = failures.poll();
+            if (failure != null) {
+                throw failure;
+            }
+            localArch = pulledArch;
+        }
+    }
 }

Reply via email to