From b8195684e712bd2f1b76cc967905a2ce2dcee780 Mon Sep 17 00:00:00 2001 From: jwoa95 <88512616+jwoa95@users.noreply.github.com> Date: Wed, 11 Nov 2026 18:09:51 +0000 Subject: [PATCH] fix(ecr): wait for backing registry HTTP readiness (#7993) * test(ecr): wait for backing registry before TLS checks The first TLS registry ping can race backing container startup and return HTTP 502. Start the test registry and wait up to ten seconds for its HTTP endpoint before exercising the existing TLS and plain-HTTP assertions. Extracted from PR #7700 at reviewer request. The original test reproduced the failure before this wait and passed after it. Validation on current main 9f77c736e: EcrTlsDataPlaneDockerIntegrationTest passes with no skips and zero Checkstyle violations. * test(ecr): reuse readiness client and report registry diagnostics Reuse one backing-registry HTTP client across readiness polls. On timeout include the endpoint, host port, manager state, container status and a bounded log tail while preserving the original timeout cause. * fix(ecr): wait for backing registry HTTP readiness Wait for /v2/ with SidecarHealthHelper before reconciling or marking new and adopted registries ready. Retry failed readiness without recreating a running registry. Remove the test-only TLS wait and diagnostics, the unused RegistryHttpClient.ping method, and redundant polling in the port-conflict test. Verify startup and adoption through the mocked health helper without real sleeps. --- .../ecr/registry/EcrRegistryManager.java | 24 +++--- .../ecr/registry/RegistryHttpClient.java | 15 ---- .../ecr/registry/EcrRegistryManagerTest.java | 80 +++++++++++++++++++ ...stryPortConflictDockerIntegrationTest.java | 17 ++-- 4 files changed, 95 insertions(+), 41 deletions(-) diff --git a/src/main/java/io/floci/aws/services/ecr/registry/EcrRegistryManager.java b/src/main/java/io/floci/aws/services/ecr/registry/EcrRegistryManager.java index 244e39ef49..2763f32fdd 100644 --- a/src/main/java/io/floci/aws/services/ecr/registry/EcrRegistryManager.java +++ b/src/main/java/io/floci/aws/services/ecr/registry/EcrRegistryManager.java @@ -23,6 +23,7 @@ import io.floci.aws.core.common.docker.ContainerSpec; import io.floci.aws.core.common.docker.ContainerStorageHelper; import io.floci.aws.core.common.docker.CurrentContainerNetworkResolver; import io.floci.aws.core.common.docker.PortAllocator; +import io.floci.aws.core.common.docker.SidecarHealthHelper; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; @@ -421,6 +422,9 @@ public class EcrRegistryManager { if (started) { ContainerPresence presence = lifecycleManager.presenceOf(containerId); if (presence == ContainerPresence.RUNNING || presence == ContainerPresence.UNKNOWN) { + if (!ready) { + completeStartup(); + } return; } String previousContainerId = containerId; @@ -453,8 +457,7 @@ public class EcrRegistryManager { } else if (!onAnotherNetwork(existing.get())) { this.activeContainerName = adoptedName; adoptExisting(existing.get()); - runReconcileOnce(); - this.ready = true; + completeStartup(); return; } // Recreated under the current name; the data volume is resolved by its own probe. @@ -480,6 +483,11 @@ public class EcrRegistryManager { } catch (Exception e) { throw new RuntimeException("Failed to start ECR backing registry container: " + e.getMessage(), e); } + completeStartup(); + } + + private void completeStartup() { + SidecarHealthHelper.waitForHealth(httpClient().baseUrl(), "/v2/"); runReconcileOnce(); this.ready = true; } @@ -587,18 +595,6 @@ public class EcrRegistryManager { return; } try { - // Give the registry a moment to be ready on first start - for (int i = 0; i < 10; i++) { - if (httpClient().ping()) { - break; - } - try { - Thread.sleep(200); - } catch (InterruptedException ie) { - Thread.currentThread().interrupt(); - return; - } - } List repos = httpClient().catalog(); reconcileHook.accept(repos); reconciled = true; diff --git a/src/main/java/io/floci/aws/services/ecr/registry/RegistryHttpClient.java b/src/main/java/io/floci/aws/services/ecr/registry/RegistryHttpClient.java index b5328ef370..59ce9ba940 100644 --- a/src/main/java/io/floci/aws/services/ecr/registry/RegistryHttpClient.java +++ b/src/main/java/io/floci/aws/services/ecr/registry/RegistryHttpClient.java @@ -36,21 +36,6 @@ public class RegistryHttpClient { .build(); } - /** Returns true if the registry responds to {@code GET /v2/}. */ - public boolean ping() { - try { - HttpResponse resp = http.send( - HttpRequest.newBuilder(URI.create(baseUrl + "/v2/")) - .timeout(Duration.ofSeconds(5)) - .GET() - .build(), - HttpResponse.BodyHandlers.discarding()); - return resp.statusCode() < 500; - } catch (Exception e) { - return false; - } - } - /** * Lists all repository names known to the backing registry, following the * {@code Link} header pagination that {@code GET /v2/_catalog} uses diff --git a/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryManagerTest.java b/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryManagerTest.java index 0cce3c9a68..c0ea5f143c 100644 --- a/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryManagerTest.java +++ b/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryManagerTest.java @@ -29,16 +29,22 @@ import io.floci.aws.core.common.docker.ContainerSpec; import io.floci.aws.core.common.docker.CurrentContainerNetworkResolver; import io.floci.aws.core.common.docker.HostBlindPortAllocator; import io.floci.aws.core.common.docker.PortAllocator; +import io.floci.aws.core.common.docker.SidecarHealthHelper; import io.floci.aws.testing.ManualClock; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.MockMakers; +import org.mockito.MockedStatic; import org.mockito.Mockito; import java.io.Closeable; import java.time.Duration; import java.time.Instant; +import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; @@ -89,9 +95,11 @@ class EcrRegistryManagerTest { private InspectImageCmd inspectImage; private RegionResolver regionResolver; private EcrRegistryManager manager; + private MockedStatic health; @BeforeEach void setUp() { + health = Mockito.mockStatic(SidecarHealthHelper.class, Mockito.withSettings().mockMaker(MockMakers.INLINE)); portAllocator = new HostBlindPortAllocator(); containerBuilder = Mockito.mock(ContainerBuilder.class); @@ -142,6 +150,78 @@ class EcrRegistryManagerTest { containerDetector, currentContainerNetworkResolver, portAllocator, config, regionResolver); } + @AfterEach + void tearDown() { + health.close(); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void ensureStartedWaitsForRegistryHttpWhenStartingOrAdopting(boolean adopt) { + ContainerLifecycleManager.ContainerInfo info = + new ContainerLifecycleManager.ContainerInfo("container-id", Map.of()); + if (adopt) { + Container existing = Mockito.mock(Container.class); + when(existing.getId()).thenReturn("container-id"); + when(existing.getPorts()).thenReturn(new ContainerPort[] { + new ContainerPort().withIp("127.0.0.1").withPrivatePort(5000).withPublicPort(BASE_PORT) + }); + when(lifecycleManager.findByName(REGISTRY_NAME)).thenReturn(Optional.of(existing)); + when(lifecycleManager.adopt("container-id", List.of(5000), Optional.empty())).thenReturn(info); + } else { + when(lifecycleManager.createAndStart(any())).thenReturn(info); + } + + manager.ensureStarted(); + + health.verify(() -> SidecarHealthHelper.waitForHealth("http://localhost:" + BASE_PORT, "/v2/")); + manager.ensureStarted(); + health.verifyNoMoreInteractions(); + } + + @Test + void ensureStartedRetriesReadinessAfterHealthCheckFails() { + when(lifecycleManager.createAndStart(any())).thenReturn( + new ContainerLifecycleManager.ContainerInfo("container-id", Map.of())); + health.when(() -> SidecarHealthHelper.waitForHealth("http://localhost:" + BASE_PORT, "/v2/")) + .thenThrow(new IllegalStateException("Registry is not healthy")) + .thenAnswer(invocation -> null); + + assertFalse(manager.tryEnsureStarted()); + assertTrue(manager.tryEnsureStarted()); + + health.verify(() -> SidecarHealthHelper.waitForHealth("http://localhost:" + BASE_PORT, "/v2/"), times(2)); + verify(lifecycleManager).createAndStart(any()); + } + + @Test + void ensureStartedReconcilesOnlyAfterHttpReadiness() throws Exception { + when(lifecycleManager.createAndStart(any())).thenReturn( + new ContainerLifecycleManager.ContainerInfo("container-id", Map.of())); + List events = new ArrayList<>(); + RegistryHttpClient client = Mockito.mock(RegistryHttpClient.class); + when(client.baseUrl()).thenReturn("http://localhost:" + BASE_PORT); + when(client.catalog()).thenAnswer(invocation -> { + events.add("catalog"); + return List.of("repository"); + }); + manager = Mockito.spy(manager); + Mockito.doReturn(client).when(manager).httpClient(); + health.when(() -> SidecarHealthHelper.waitForHealth(client.baseUrl(), "/v2/")) + .thenAnswer(invocation -> { + events.add("healthy"); + return null; + }); + manager.setReconcileHook(repositories -> { + assertEquals(List.of("repository"), repositories); + events.add("reconciled"); + }); + + manager.ensureStarted(); + + assertEquals(List.of("healthy", "catalog", "reconciled"), events); + } + @Test void ensureStartedLabelsContainerWithResourceIdentity() { when(lifecycleManager.createAndStart(any())).thenReturn( diff --git a/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryPortConflictDockerIntegrationTest.java b/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryPortConflictDockerIntegrationTest.java index cbdf949711..6cb4f3c3bf 100644 --- a/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryPortConflictDockerIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryPortConflictDockerIntegrationTest.java @@ -11,6 +11,7 @@ import io.floci.aws.core.common.docker.ContainerStorageHelper; import io.floci.aws.core.common.docker.CurrentContainerNetworkResolver; import io.floci.aws.core.common.docker.HostBlindPortAllocator; import io.floci.aws.core.common.docker.PortAllocator; +import io.floci.aws.core.common.docker.SidecarHealthHelper; import io.floci.aws.testing.TestImages; import io.quarkus.test.junit.QuarkusTest; import jakarta.inject.Inject; @@ -63,7 +64,7 @@ class EcrRegistryPortConflictDockerIntegrationTest { } @Test - void registriesCompetingForOneRangeStartOnDifferentPortsUntilItIsExhausted() throws InterruptedException { + void registriesCompetingForOneRangeStartOnDifferentPortsUntilItIsExhausted() { int port = freePortPair(); EmulatorConfig configA = config(port); EmulatorConfig configB = config(port); @@ -79,7 +80,9 @@ class EcrRegistryPortConflictDockerIntegrationTest { assertEquals(port, a.effectivePort()); assertEquals(port + 1, b.effectivePort()); - assertTrue(isReachable(a) && isReachable(b), "both registries must answer on their own port"); + assertTrue(SidecarHealthHelper.probeHealth(a.httpClient().baseUrl(), "/v2/") + && SidecarHealthHelper.probeHealth(b.httpClient().baseUrl(), "/v2/"), + "both registries must answer on their own port"); assertEquals(port, allocatorB.allocate(port, port + 1), "the refused port must be released"); RuntimeException ex = assertThrows(RuntimeException.class, c::ensureStarted); @@ -127,16 +130,6 @@ class EcrRegistryPortConflictDockerIntegrationTest { return port; } - private static boolean isReachable(EcrRegistryManager manager) throws InterruptedException { - for (int attempt = 0; attempt < 50; attempt++) { - if (manager.httpClient().ping()) { - return true; - } - Thread.sleep(200); - } - return false; - } - private boolean isDockerAvailable() { try { dockerClient.pingCmd().exec();