From d51a0f9ce8273267e763250b07fef097fa4222b1 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Thu, 7 May 2026 00:37:31 -0500 Subject: [PATCH] fix(ec2): prevent SSH port collision on concurrent RunInstances (#721) (#733) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit immediately closing a ServerSocket. Between that check and Docker binding the port, a second concurrent RunInstances call saw the same port as free — both instances raced to bind 2200 and the second one failed with "port is already allocated". Fix: PortAllocator now maintains an in-memory ConcurrentSkipListSet of reserved ports. allocate() is synchronized and adds the chosen port to the set before returning, so concurrent callers skip it even before Docker has bound it. release() removes the entry when the container is terminated, making the port available for future instances. Ec2ContainerManager.terminate() now calls portAllocator.release() after the Docker container is removed. Add PortAllocatorTest with 5 cases including a concurrency test that races 20 threads simultaneously to confirm uniqueness. Fixes #721 --- .../core/common/docker/PortAllocator.java | 29 +++++- .../services/ec2/Ec2ContainerManager.java | 4 + .../core/common/docker/PortAllocatorTest.java | 95 +++++++++++++++++++ 3 files changed, 123 insertions(+), 5 deletions(-) create mode 100644 src/test/java/io/github/hectorvent/floci/core/common/docker/PortAllocatorTest.java 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.java index 104890433b..8cdbb9c766 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 @@ -5,6 +5,8 @@ import org.jboss.logging.Logger; import java.io.IOException; import java.net.ServerSocket; +import java.util.Set; +import java.util.concurrent.ConcurrentSkipListSet; /** * Utility for allocating free TCP ports for Docker container port bindings. @@ -16,17 +18,24 @@ public class PortAllocator { private static final Logger LOG = Logger.getLogger(PortAllocator.class); + // Ports reserved by this process but not yet bound by Docker. + // Prevents TOCTOU races when multiple containers are launched concurrently. + private final Set reserved = new ConcurrentSkipListSet<>(); + /** - * Finds a free TCP port within the specified range. + * Atomically finds and reserves a free TCP port within the specified range. + * The port is held in-memory until {@link #release(int)} is called, preventing + * concurrent callers from picking the same port before Docker binds it. * * @param basePort the lowest port number to try (inclusive) - * @param maxPort the highest port number to try (inclusive) - * @return a free port within the range + * @param maxPort the highest port number to try (inclusive) + * @return a reserved free port within the range * @throws RuntimeException if no free port is available in the range */ - public int allocate(int basePort, int maxPort) { + public synchronized int allocate(int basePort, int maxPort) { for (int port = basePort; port <= maxPort; port++) { - if (isPortFree(port)) { + if (!reserved.contains(port) && isPortFree(port)) { + reserved.add(port); LOG.debugv("Allocated port {0} from range {1}-{2}", port, basePort, maxPort); return port; } @@ -34,6 +43,16 @@ public class PortAllocator { throw new RuntimeException("No free port available in range " + basePort + "-" + maxPort); } + /** + * Releases a previously allocated port back to the pool. + * Should be called when the Docker container that was using the port is removed. + */ + public void release(int port) { + if (reserved.remove(port)) { + LOG.debugv("Released port {0}", port); + } + } + /** * 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.java index d285027002..39569f631e 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 @@ -240,6 +240,7 @@ public class Ec2ContainerManager { public void terminate(Instance instance) { String containerId = instance.getDockerContainerId(); String containerIp = instance.getContainerBridgeIp(); + int sshHostPort = instance.getSshHostPort(); instance.setState(InstanceState.shuttingDown()); executor.submit(() -> { if (containerId != null) { @@ -251,6 +252,9 @@ public class Ec2ContainerManager { LOG.warnv("Error removing EC2 container {0}: {1}", containerId, e.getMessage()); } } + if (sshHostPort > 0) { + portAllocator.release(sshHostPort); + } metadataServer.unregisterContainer(containerIp); instance.setState(InstanceState.terminated()); instance.setTerminatedAt(System.currentTimeMillis()); 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.java new file mode 100644 index 0000000000..60b2dac05d --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/PortAllocatorTest.java @@ -0,0 +1,95 @@ +package io.github.hectorvent.floci.core.common.docker; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import static org.junit.jupiter.api.Assertions.*; + +class PortAllocatorTest { + + @Test + void allocatesPortInRange() { + PortAllocator allocator = new PortAllocator(); + // Use a high ephemeral range unlikely to conflict with real services + int port = allocator.allocate(19900, 19999); + assertTrue(port >= 19900 && port <= 19999, "Port should be within range"); + allocator.release(port); + } + + @Test + void reservedPortIsSkippedByNextCaller() { + PortAllocator allocator = new PortAllocator(); + int first = allocator.allocate(19900, 19999); + int second = allocator.allocate(19900, 19999); + assertNotEquals(first, second, "Two sequential allocations must return different ports"); + allocator.release(first); + allocator.release(second); + } + + @Test + void releasedPortBecomesAvailableAgain() { + PortAllocator allocator = new PortAllocator(); + int port = allocator.allocate(19900, 19999); + allocator.release(port); + // After release the same port can be re-allocated + int reused = allocator.allocate(19900, 19999); + assertEquals(port, reused, "Released port should be the first candidate again"); + allocator.release(reused); + } + + @Test + void concurrentAllocationsAreUnique() throws Exception { + PortAllocator allocator = new PortAllocator(); + int threads = 20; + // Range must be at least as wide as the thread count + int base = 19900; + int max = base + threads - 1; + + Set ports = ConcurrentHashMap.newKeySet(); + CountDownLatch ready = new CountDownLatch(threads); + CountDownLatch go = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(threads); + List> futures = new ArrayList<>(); + + for (int i = 0; i < threads; i++) { + futures.add(executor.submit(() -> { + ready.countDown(); + try { go.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } + int p = allocator.allocate(base, max); + ports.add(p); + })); + } + + ready.await(); // all threads are lined up + go.countDown(); // release them simultaneously + + for (Future f : futures) { + f.get(); + } + executor.shutdown(); + + assertEquals(threads, ports.size(), + "Concurrent allocations must all return unique ports; got duplicates: " + ports); + + ports.forEach(allocator::release); + } + + @Test + void throwsWhenRangeExhausted() { + PortAllocator allocator = new PortAllocator(); + // Allocate the only port in a single-port range + int port = allocator.allocate(19900, 19900); + // Now the range is full — next call must throw + assertThrows(RuntimeException.class, () -> allocator.allocate(19900, 19900)); + allocator.release(port); + } +}