Light, fluffy, and always free - The AWS Local Emulator alternative
fix(ecr): retry occupied registry ports (#4857)
Mario Toffia8b1ece9c2443
diff --git a/docs/services/ecr.md b/docs/services/ecr.mdindex 6671bacf87..8e66d88116 100644--- a/docs/services/ecr.md+++ b/docs/services/ecr.md@@ -67,6 +67,8 @@| `FLOCI_SERVICES_ECR_PREFER_LOCAL_IMAGES` | `true` | Use an AWS-shaped ECR image URI as-is when the Docker daemon already has that image, instead of rewriting it to the loopback registry || `FLOCI_SERVICES_ECR_TLS_ENABLED` | `false` | Reserved for future ACM-backed TLS |+When Docker reports the chosen registry port as already in use, for example by another emulator on the same daemon, Floci tries the next free port in the range. When no port in the range is free, startup fails and the error names the ports Docker refused. Any other startup error, such as an unreachable Docker daemon or a failed image pull, fails at once.+### Docker Compose port mappingECR uses Floci's existing `4566` listener. The backing registry binds a loopback-only implementation port, so no ECR range belongs in `docker-compose.yml`:diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/PortAllocator.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/PortAllocator.javaindex e10cdc71fd..e0f0626261 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/docker/PortAllocator.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/PortAllocator.java@@ -9,10 +9,13 @@ import org.jboss.logging.Logger;import java.io.IOException;import java.net.ServerSocket;+import java.util.ArrayList;import java.util.HashSet;import java.util.List;+import java.util.Locale;import java.util.Set;import java.util.concurrent.ConcurrentSkipListSet;+import java.util.function.IntFunction;/*** Utility for allocating free TCP ports for Docker container port bindings.@@ -89,6 +92,56 @@ public class PortAllocator {}}+ /**+ * Allocates a port in the range and hands it to {@code start}, moving on to the next port while+ * Docker refuses the chosen one as already in use. {@link #allocate} cannot rule that out: its+ * probe races Docker binding the port, and from inside a container it cannot see a host process+ * holding one. Refused ports stay reserved until this returns, so no port is tried twice, and are+ * then released, so each is usable again once its holder goes away. Once {@code start} returns,+ * the port is the caller's to release; any other failure releases it and propagates.+ */+ public <T> T allocateAndStart(int basePort, int maxPort, IntFunction<T> start) {+ List<Integer> refused = new ArrayList<>();+ try {+ while (true) {+ int port;+ try {+ port = allocate(basePort, maxPort);+ } catch (RuntimeException e) {+ if (refused.isEmpty()) {+ throw e;+ }+ throw new RuntimeException("Docker reports host ports " + refused+ + " already in use and no other port in " + basePort + "-" + maxPort + " is free", e);+ }+ try {+ return start.apply(port);+ } catch (RuntimeException e) {+ if (!isHostPortCollision(e)) {+ release(port);+ throw e;+ }+ refused.add(port);+ LOG.warnv("Docker reports host port {0} in use; trying another port in {1}-{2}",+ String.valueOf(port), String.valueOf(basePort), String.valueOf(maxPort));+ }+ }+ } finally {+ refused.forEach(this::release);+ }+ }++ private static boolean isHostPortCollision(Throwable error) {+ for (Throwable cause = error; cause != null; cause = cause.getCause()) {+ String message = cause.getMessage();+ if (message != null && (message.toLowerCase(Locale.ROOT).contains("port is already allocated")+ || message.toLowerCase(Locale.ROOT).contains("address already in use"))) {+ return true;+ }+ }+ return false;+ }+/*** Finds any free TCP port using ephemeral port allocation.* This is the fastest method when any port will do.diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.javaindex a48abf2b63..5bdfbe2195 100644--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java@@ -46,7 +46,6 @@ import java.util.ArrayList;import java.util.Base64;import java.util.HashSet;import java.util.List;-import java.util.Locale;import java.util.Map;import java.util.Objects;import java.util.Optional;@@ -597,13 +596,13 @@ public class Ec2ContainerManager {String imdsEndpoint = "http://" + flociHost + ":" + imdsPort;String serviceEndpoint = reachableEndpoint.baseUrl();- while (true) {+ return portAllocator.allocateAndStart(+ config.services().ec2().sshPortRangeStart(),+ config.services().ec2().sshPortRangeEnd(), sshHostPort -> {if (isLaunchCancelled(instance)) {+ portAllocator.release(sshHostPort);return null;}- int sshHostPort = portAllocator.allocate(- config.services().ec2().sshPortRangeStart(),- config.services().ec2().sshPortRangeEnd());SecurityGroupFirewallManager.Namespace namespace = null;String eniId = null;String containerId = null;@@ -665,18 +664,9 @@ public class Ec2ContainerManager {}lifecycleManager.removeIfExists(namespace.helperId());}- if (isHostPortCollision(e)) {- // Docker Desktop can own a published port without exposing it to a host-side- // ServerSocket probe. Keep it unavailable for this process and try the next port.- portAllocator.markReserved(sshHostPort);- LOG.warnv("EC2 instance {0} could not use SSH host port {1}; trying another port",- instanceId, String.valueOf(sshHostPort));- continue;- }- portAllocator.release(sshHostPort);throw e;}- }+ });}private ContainerSpec buildContainerSpec(String containerName, ResolvedAmiImage image, String region,@@ -866,17 +856,6 @@ public class Ec2ContainerManager {return "shutting-down".equals(state) || "terminated".equals(state);}- private static boolean isHostPortCollision(Exception exception) {- for (Throwable cause = exception; cause != null; cause = cause.getCause()) {- String message = cause.getMessage();- if (message != null && (message.toLowerCase(Locale.ROOT).contains("port is already allocated")- || message.toLowerCase(Locale.ROOT).contains("address already in use"))) {- return true;- }- }- return false;- }-private record StartedContainer(String containerId, int sshHostPort, String vpcAddress,SecurityGroupFirewallManager.Namespace namespace, String eniId) {}@@ -910,9 +889,10 @@ public class Ec2ContainerManager {* reboot already handle a null container id, so the rest of the lifecycle keeps working.*/private void markContainerlessRunning(Instance instance) {- LOG.infov("EC2 instance {0} is running without a backing container (no Docker daemon reachable)",- instance.getInstanceId());- instance.setState(InstanceState.running());+ if (markRunning(instance)) {+ LOG.infov("EC2 instance {0} is running without a backing container (no Docker daemon reachable)",+ instance.getInstanceId());+ }}/**diff --git a/src/main/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManager.java b/src/main/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManager.javaindex 9cadd53803..036bf09ac6 100644--- a/src/main/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManager.java+++ b/src/main/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManager.java@@ -304,56 +304,43 @@ public class EcrRegistryManager {}this.activeContainerName = name;- // Allocate port- int chosenPort = portAllocator.allocate(- config.services().ecr().registryBasePort(),- config.services().ecr().registryMaxPort());-try {- String image = config.services().ecr().registryImage();-- // Build environment variables- List<String> env = new ArrayList<>(List.of(- "REGISTRY_STORAGE_DELETE_ENABLED=true",- "REGISTRY_HTTP_ADDR=0.0.0.0:" + CONTAINER_INTERNAL_PORT,- "REGISTRY_HTTP_RELATIVEURLS=true"- ));-- // Build container spec- ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)- .withName(name)- .withEnv(env)- .withLoopbackPortBinding(CONTAINER_INTERNAL_PORT, chosenPort)- .withDockerNetwork(resolveRegistryDockerNetwork())- .withLogRotation()- .withLabels(ContainerStorageHelper.resourceIdentityLabels(- "ecr", null, regionResolver.getAccountId(), regionResolver.getDefaultRegion()));-- // Handle persistence mounting based on storage configuration- addPersistenceMounts(specBuilder, env);-- ContainerSpec spec = specBuilder.build();-- ContainerInfo info = lifecycleManager.createAndStart(spec);- this.containerId = info.containerId();- this.hostPort = chosenPort;+ this.hostPort = portAllocator.allocateAndStart(+ config.services().ecr().registryBasePort(),+ config.services().ecr().registryMaxPort(),+ port -> {+ this.containerId = lifecycleManager.createAndStart(registryContainerSpec(name, port)).containerId();+ return port;+ });this.started = true;- LOG.infov("Started ECR backing registry {0} on host port {1}", name, String.valueOf(chosenPort));+ LOG.infov("Started ECR backing registry {0} on host port {1}", name, String.valueOf(hostPort));// Attach log streaming (new feature)attachLogStream(false);} catch (Exception e) {- // Release the reserved port unless the container actually started, so a- // failed start (e.g. Docker unreachable) does not permanently exhaust the- // registry port pool across retries.- if (!started) {- portAllocator.release(chosenPort);- }throw new RuntimeException("Failed to start ECR backing registry container: " + e.getMessage(), e);}runReconcileOnce();}+ private ContainerSpec registryContainerSpec(String name, int port) {+ List<String> env = new ArrayList<>(List.of(+ "REGISTRY_STORAGE_DELETE_ENABLED=true",+ "REGISTRY_HTTP_ADDR=0.0.0.0:" + CONTAINER_INTERNAL_PORT,+ "REGISTRY_HTTP_RELATIVEURLS=true"+ ));+ ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(config.services().ecr().registryImage())+ .withName(name)+ .withEnv(env)+ .withLoopbackPortBinding(CONTAINER_INTERNAL_PORT, port)+ .withDockerNetwork(resolveRegistryDockerNetwork())+ .withLogRotation()+ .withLabels(ContainerStorageHelper.resourceIdentityLabels(+ "ecr", null, regionResolver.getAccountId(), regionResolver.getDefaultRegion()));+ addPersistenceMounts(specBuilder, env);+ return specBuilder.build();+ }+private String registryContainerName() {return ContainerStorageHelper.dockerName(config, config.services().ecr().registryContainerName());}diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/HostBlindPortAllocator.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/HostBlindPortAllocator.javanew file mode 100644index 0000000000..3b9c4b2f15--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/HostBlindPortAllocator.java@@ -0,0 +1,13 @@+package io.github.hectorvent.floci.core.common.docker;++/**+ * A {@link PortAllocator} that skips the host probe, so a test sees the same ports free on any+ * machine and only the allocator's own reservations and Docker's answers decide which port is used.+ */+public class HostBlindPortAllocator extends PortAllocator {++ @Override+ public boolean isPortFree(int port) {+ return true;+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/PortAllocatorTest.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/PortAllocatorTest.javaindex 009d3b8bfe..5121b6a3eb 100644--- a/src/test/java/io/github/hectorvent/floci/core/common/docker/PortAllocatorTest.java+++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/PortAllocatorTest.java@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.core.common.docker;import org.junit.jupiter.api.Test;+import java.io.IOException;import java.util.ArrayList;import java.util.List;import java.util.Set;@@ -91,4 +92,58 @@ class PortAllocatorTest {assertThrows(RuntimeException.class, () -> allocator.allocate(19900, 19900));allocator.release(port);}++ @Test+ void allocateAndStartMovesPastPortsDockerReportsInUseAndReleasesThem() {+ PortAllocator allocator = new HostBlindPortAllocator();+ List<Integer> tried = new ArrayList<>();++ int started = allocator.allocateAndStart(19900, 19902, port -> {+ tried.add(port);+ if (port < 19902) {+ throw new RuntimeException("Bind for 127.0.0.1:" + port + " failed: port is already allocated");+ }+ return port;+ });++ assertEquals(19902, started);+ assertEquals(List.of(19900, 19901, 19902), tried);+ assertEquals(19900, allocator.allocate(19900, 19902), "refused ports must be released");+ assertEquals(19901, allocator.allocate(19900, 19902), "refused ports must be released");+ assertThrows(RuntimeException.class, () -> allocator.allocate(19902, 19902),+ "the port the start succeeded on must stay reserved");+ }++ @Test+ void allocateAndStartNamesTheRefusedPortsWhenTheRangeRunsOut() {+ PortAllocator allocator = new HostBlindPortAllocator();++ RuntimeException e = assertThrows(RuntimeException.class, () -> allocator.allocateAndStart(19900, 19901,+ port -> {+ throw new RuntimeException(new IOException("listen tcp4 0.0.0.0:" + port+ + ": bind: address already in use"));+ }));++ assertEquals("Docker reports host ports [19900, 19901] already in use and no other port in 19900-19901"+ + " is free", e.getMessage());+ assertEquals(19900, allocator.allocate(19900, 19901), "refused ports must be released");+ assertEquals(19901, allocator.allocate(19900, 19901), "refused ports must be released");+ }++ @Test+ void allocateAndStartReleasesThePortAndRethrowsAnyOtherFailure() {+ PortAllocator allocator = new HostBlindPortAllocator();+ RuntimeException failure = new RuntimeException("Cannot connect to the Docker daemon");+ List<Integer> tried = new ArrayList<>();++ RuntimeException e = assertThrows(RuntimeException.class, () -> allocator.allocateAndStart(19900, 19901,+ port -> {+ tried.add(port);+ throw failure;+ }));++ assertSame(failure, e);+ assertEquals(List.of(19900), tried);+ assertEquals(19900, allocator.allocate(19900, 19901), "the chosen port must be released");+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.javaindex 5155e690e1..6b95456cb6 100644--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java@@ -1161,11 +1161,46 @@ class Ec2ContainerManagerTest {awaitUntil(() -> "running".equals(instance.getState().getName()), Duration.ofSeconds(2));assertEquals(2202, instance.getSshHostPort());verify(harness.lifecycleManager).removeIfExists("container-conflict");- verify(harness.portAllocator).markReserved(2201);+ verify(harness.portAllocator).release(2201);+ verify(harness.portAllocator, never()).markReserved(anyInt());verify(harness.builder).withPortBinding(22, 2201);verify(harness.builder).withPortBinding(22, 2202);}+ @Test+ void launchCancelledDuringAPortRetryStaysTerminatedWhenNoPortIsLeft() throws Exception {+ ExecutorService launchExecutor = Executors.newSingleThreadExecutor();+ LaunchHarness harness = launchHarness(launchExecutor, Duration.ofSeconds(1));+ Instance instance = instance("i-cancelled-during-retry");+ AtomicBoolean dockerGone = new AtomicBoolean();+ AtomicBoolean cancelled = new AtomicBoolean();+ PingCmd ping = mock(PingCmd.class);+ when(harness.dockerClient.pingCmd()).thenReturn(ping);+ when(ping.exec()).thenAnswer(invocation -> {+ if (dockerGone.get()) {+ throw new RuntimeException("No such file or directory");+ }+ return null;+ });+ when(harness.portAllocator.allocate(anyInt(), anyInt()))+ .thenReturn(2201)+ .thenThrow(new RuntimeException("No free port available in range 2200-2299"));+ when(harness.lifecycleManager.startCreated(eq(TEST_CONTAINER_ID), any(ContainerSpec.class)))+ .thenThrow(new RuntimeException("Bind for 0.0.0.0:2201 failed: port is already allocated"));+ doAnswer(invocation -> {+ cancelled.set(harness.manager.cancelLaunch(instance));+ dockerGone.set(true);+ return null;+ }).when(harness.lifecycleManager).removeIfExists(TEST_CONTAINER_ID);++ harness.manager.launch(instance, "ubuntu:24.04", null, "us-west-2");+ launchExecutor.shutdown();+ assertTrue(launchExecutor.awaitTermination(5, TimeUnit.SECONDS), "launch worker should finish");++ assertTrue(cancelled.get(), "the launch should be cancelled while the refused container is removed");+ assertEquals("terminated", instance.getState().getName());+ }+@Testvoid launchReleasesPortAndCleansUpContainerAfterNonRetryableStartFailure() throws Exception {LaunchHarness harness = launchHarness();@@ -1604,6 +1639,7 @@ class Ec2ContainerManagerTest {when(reachableEndpoint.baseUrl()).thenReturn("http://localhost.floci.io:4680");PortAllocator portAllocator = mock(PortAllocator.class);when(portAllocator.allocate(anyInt(), anyInt())).thenReturn(2201);+ when(portAllocator.allocateAndStart(anyInt(), anyInt(), any())).thenCallRealMethod();EmulatorConfig config = mock(EmulatorConfig.class);EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);@@ -2111,6 +2147,7 @@ class Ec2ContainerManagerTest {when(reachableEndpoint.baseUrl()).thenReturn("http://localhost.floci.io:4680");PortAllocator portAllocator = mock(PortAllocator.class);when(portAllocator.allocate(anyInt(), anyInt())).thenReturn(2201);+ when(portAllocator.allocateAndStart(anyInt(), anyInt(), any())).thenCallRealMethod();EmulatorConfig config = mock(EmulatorConfig.class);EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);diff --git a/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManagerTest.javaindex 9091b8fa00..7fbece1263 100644--- a/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManagerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManagerTest.java@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.Cimport io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;import io.github.hectorvent.floci.core.common.docker.CurrentContainerNetworkResolver;import io.github.hectorvent.floci.core.common.docker.ContainerSpec;+import io.github.hectorvent.floci.core.common.docker.HostBlindPortAllocator;import io.github.hectorvent.floci.core.common.docker.PortAllocator;import com.github.dockerjava.api.DockerClient;import com.github.dockerjava.api.async.ResultCallback;@@ -45,13 +46,14 @@ import static org.mockito.ArgumentMatchers.anyInt;import static org.mockito.ArgumentMatchers.anyString;import static org.mockito.ArgumentMatchers.eq;import static org.mockito.Mockito.never;+import static org.mockito.Mockito.times;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;/*** Unit tests for {@link EcrRegistryManager} startup behavior. Uses a real- * {@link PortAllocator} and a mocked Docker layer so the failure path can be- * exercised without a Docker daemon.+ * {@link PortAllocator} that skips the host probe ({@link HostBlindPortAllocator}) and a mocked Docker layer so the+ * failure path can be exercised without a Docker daemon or free host ports.*/class EcrRegistryManagerTest {@@ -78,7 +80,7 @@ class EcrRegistryManagerTest {@BeforeEachvoid setUp() {- portAllocator = new PortAllocator();+ portAllocator = new HostBlindPortAllocator();containerBuilder = Mockito.mock(ContainerBuilder.class);builder = Mockito.mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);@@ -165,6 +167,37 @@ class EcrRegistryManagerTest {assertFalse(ex.getMessage().contains("No free port available"),"port pool leaked on attempt " + attempt + ": " + ex.getMessage());}+ // Only a host-port collision moves on to the next port; any other failure is not retried.+ verify(lifecycleManager, times(6)).createAndStart(any());+ }++ @Test+ void ensureStarted_triesTheNextPortWhenDockerReportsTheChosenPortInUse() {+ when(lifecycleManager.createAndStart(any()))+ .thenThrow(new RuntimeException("Bind for 127.0.0.1:6100 failed: port is already allocated"))+ .thenReturn(new ContainerLifecycleManager.ContainerInfo("container-id", Map.of()));++ manager.ensureStarted();++ assertEquals(MAX_PORT, manager.effectivePort());+ verify(builder).withLoopbackPortBinding(5000, BASE_PORT);+ verify(builder).withLoopbackPortBinding(5000, MAX_PORT);+ assertEquals(BASE_PORT, portAllocator.allocate(BASE_PORT, MAX_PORT), "the refused port must be released");+ }++ @Test+ void ensureStarted_namesTheRefusedPortsWhenEveryPortInTheRangeIsInUse() {+ when(lifecycleManager.createAndStart(any()))+ .thenThrow(new RuntimeException("listen tcp4 127.0.0.1:6100: bind: address already in use"));++ RuntimeException ex = assertThrows(RuntimeException.class, manager::ensureStarted);++ assertTrue(ex.getMessage().contains("[6100, 6101]") && ex.getMessage().contains("6100-6101"),+ ex.getMessage());+ verify(lifecycleManager, times(2)).createAndStart(any());+ assertFalse(manager.isStarted());+ assertEquals(BASE_PORT, portAllocator.allocate(BASE_PORT, MAX_PORT), "refused ports must be released");+ assertEquals(MAX_PORT, portAllocator.allocate(BASE_PORT, MAX_PORT), "refused ports must be released");}@Testdiff --git a/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryPortConflictDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryPortConflictDockerIntegrationTest.javanew file mode 100644index 0000000000..d529d5e6cf--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryPortConflictDockerIntegrationTest.java@@ -0,0 +1,148 @@+package io.github.hectorvent.floci.services.ecr.registry;++import com.github.dockerjava.api.DockerClient;+import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;+import io.github.hectorvent.floci.core.common.docker.ContainerDetector;+import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;+import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;+import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;+import io.github.hectorvent.floci.core.common.docker.CurrentContainerNetworkResolver;+import io.github.hectorvent.floci.core.common.docker.HostBlindPortAllocator;+import io.github.hectorvent.floci.core.common.docker.PortAllocator;+import io.github.hectorvent.floci.testing.TestImages;+import io.quarkus.test.junit.QuarkusTest;+import jakarta.inject.Inject;+import org.junit.jupiter.api.Assumptions;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.mockito.Mockito;++import java.util.Optional;+import java.util.UUID;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.Mockito.when;++/**+ * Several emulators sharing one Docker daemon and one ECR port range, whose allocators cannot see+ * each other's ports: what two starts racing between the probe and {@code docker run} look like,+ * so only Docker's bind conflict tells them apart.+ */+@QuarkusTest+class EcrRegistryPortConflictDockerIntegrationTest {++ @Inject+ DockerClient dockerClient;++ @Inject+ ContainerBuilder containerBuilder;++ @Inject+ ContainerLifecycleManager lifecycleManager;++ @Inject+ ContainerLogStreamer logStreamer;++ @Inject+ ContainerDetector containerDetector;++ @Inject+ CurrentContainerNetworkResolver networkResolver;++ @Inject+ RegionResolver regionResolver;++ @BeforeEach+ void requireDocker() {+ Assumptions.assumeTrue(isDockerAvailable(), "Docker daemon must be available for the ECR port conflict test");+ }++ @Test+ void registriesCompetingForOneRangeStartOnDifferentPortsUntilItIsExhausted() throws InterruptedException {+ int port = freePortPair();+ EmulatorConfig configA = config(port);+ EmulatorConfig configB = config(port);+ EmulatorConfig configC = config(port);+ PortAllocator allocatorB = new HostBlindPortAllocator();+ PortAllocator allocatorC = new HostBlindPortAllocator();+ EcrRegistryManager a = manager(configA, new HostBlindPortAllocator());+ EcrRegistryManager b = manager(configB, allocatorB);+ EcrRegistryManager c = manager(configC, allocatorC);+ try {+ a.ensureStarted();+ b.ensureStarted();++ assertEquals(port, a.effectivePort());+ assertEquals(port + 1, b.effectivePort());+ assertTrue(isReachable(a) && isReachable(b), "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);+ assertTrue(ex.getMessage().contains("[" + port + ", " + (port + 1) + "]"), ex.getMessage());+ assertFalse(c.isStarted());+ assertTrue(lifecycleManager.findByName(+ ContainerStorageHelper.dockerName(configC, "ecr-registry")).isEmpty(),+ "a container Docker refused to start must be removed");+ assertEquals(port, allocatorC.allocate(port, port + 1), "refused ports must be released");+ assertEquals(port + 1, allocatorC.allocate(port, port + 1), "refused ports must be released");+ } finally {+ a.shutdown();+ b.shutdown();+ c.shutdown();+ }+ }++ private EcrRegistryManager manager(EmulatorConfig config, PortAllocator allocator) {+ return new EcrRegistryManager(containerBuilder, lifecycleManager, logStreamer, containerDetector,+ networkResolver, allocator, config, regionResolver);+ }++ private static EmulatorConfig config(int basePort) {+ EmulatorConfig config = Mockito.mock(EmulatorConfig.class, Mockito.RETURNS_DEEP_STUBS);+ when(config.docker().resourceNamespace())+ .thenReturn(Optional.of("ecrport" + UUID.randomUUID().toString().substring(0, 8)));+ // Empty host-persistent-path selects a named volume, which memory mode removes on shutdown.+ when(config.storage().hostPersistentPath()).thenReturn("");+ when(config.storage().mode()).thenReturn("memory");+ when(config.services().ecr().registryContainerName()).thenReturn("ecr-registry");+ when(config.services().ecr().registryImage()).thenReturn(TestImages.REGISTRY);+ when(config.services().ecr().registryBasePort()).thenReturn(basePort);+ when(config.services().ecr().registryMaxPort()).thenReturn(basePort + 1);+ when(config.services().ecr().dockerNetwork()).thenReturn(Optional.empty());+ return config;+ }++ private int freePortPair() {+ PortAllocator probe = new PortAllocator(dockerClient);+ int port = probe.allocate(15100, 15899);+ for (int next = probe.allocate(port + 1, 15899); next != port + 1; next = probe.allocate(next + 1, 15899)) {+ port = next;+ }+ 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();+ return true;+ } catch (Exception ignored) {+ // The assumption in requireDocker reports Docker as unavailable.+ return false;+ }+ }+}