fix(ec2): prevent SSH port collision on concurrent RunInstances (#721) (#733)

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
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-05-07 00:37:31 -05:00
1 parent 3b54255d7f
commit d51a0f9ce8
3 files changed
+123 -5

No files matched your search

@@ -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<Integer> 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.
@@ -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());