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();