fix(ecr): retry occupied registry ports (#4857)

* fix(ecr): retry occupied registry ports

The backing registry reserved one port from the configured range and gave
up when Docker refused to publish it, although the next port was free. The
allocator's probe races `docker run`, and from inside a container it cannot
see a host process holding the port, so a refusal is expected and not fatal.

A start Docker refuses as a host-port collision now moves on to the next
port in the range; any other failure still fails at once. Refused ports stay
reserved until the start finishes so each is tried once, then are released.
When the range runs out the error names the refused ports. EC2's collision
check moves to PortAllocator so both callers share it.

Closes floci-io/floci#4856

* chore(ecr): keep the port retry tests independent of host ports

The unit tests now use an allocator that skips the host probe, so a busy
6100 or 6101 on the machine cannot change their outcome. The integration
test picks its port pair with the Docker-aware allocator, so a container
already publishing a port is skipped as well, and drops its logger.

* docs(ecr): say other registry start errors still fail at once

The paragraph said startup fails only when the range is full, but a daemon
or image failure still fails without trying another port. The exhaustion
tests now also allocate the last refused port, so releasing only some of
them fails.

* refactor(ec2,ecr): share the port retry loop in PortAllocator

Review asked for the allocate, start and retry loop itself to live in one
place, not just the collision check. PortAllocator.allocateAndStart takes
the start as a callback, moves past ports Docker refuses as in use, and
releases the refused ports when it returns. ECR and EC2 both call it.

EC2 used to mark a refused SSH port reserved for the life of the process.
It now releases it after the launch, as ECR does, so a port whose holder
goes away is usable again.

With the loop moved, a launch cancelled between attempts can now reach
the worker's failure path. When Docker is also gone that path marked the
instance running without a container, so it now goes through markRunning
and leaves a cancelled instance terminated.

* test: share one host-blind PortAllocator across the port tests

PortAllocatorTest, EcrRegistryManagerTest and the ECR port-conflict
integration test each built their own allocator that skips the host
probe. HostBlindPortAllocator replaces the three copies.
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-10-08 15:31:03 -04:00
1 parent f248eb51af
commit 8b1ece9c24
9 files changed
+380 -72

No files matched your search

@@ -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.
@@ -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());
}
}
/**
@@ -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());
}