fix(ecs): assign awsvpc tasks dynamic host ports to avoid collisions (#1785)

In awsvpc mode every AWS task receives its own ENI, so a portMapping's
hostPort carries no host-binding semantics. Floci was publishing it
literally on the single local Docker host, so two tasks of the same
service — or two services sharing a port — collided on start.

awsvpc mappings now get a dynamic host port in native mode, or
expose-only in Docker mode where consumers reach containers via the
docker network IP. bridge and host mode keep publishing hostPort
literally, matching AWS.

Also fix the leak this surfaced: a failed start in
ContainerLifecycleManager.createAndStart left the created container
behind, so retrying callers accumulated Created containers and
fixed-name callers hit name conflicts on the next attempt.

Refs #1778
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-07-09 23:45:54 -05:00
1 parent 768019836f
commit 3771c1e9a2
5 files changed
+177 -7

No files matched your search

@@ -0,0 +1,84 @@
package io.github.hectorvent.floci.core.common.docker;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.RemoveContainerCmd;
import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* {@link ContainerLifecycleManager#createAndStart} must not leak the created
* container when the start step fails (e.g. a host-port conflict, issue #1778):
* retrying callers would otherwise accumulate {@code Created} containers, and
* fixed-name callers would hit name conflicts on their next attempt.
*/
@ExtendWith(MockitoExtension.class)
class ContainerLifecycleManagerStartFailureTest {
@Mock
private DockerClient dockerClient;
@Mock
private ImageCacheService imageCacheService;
@Mock
private ContainerDetector containerDetector;
@Mock
private PortAllocator portAllocator;
private ContainerLifecycleManager manager;
private final ContainerSpec spec = new ContainerSpec("busybox:latest");
@BeforeEach
void setUp() {
manager = spy(new ContainerLifecycleManager(
dockerClient, imageCacheService, containerDetector, portAllocator));
}
@Test
void createAndStartRemovesCreatedContainerWhenStartFails() {
RuntimeException startFailure =
new RuntimeException("Bind for 0.0.0.0:80 failed: port is already allocated");
doReturn("container-id").when(manager).create(spec);
doThrow(startFailure).when(manager).startCreated("container-id", spec);
RemoveContainerCmd removeCmd = mock(RemoveContainerCmd.class);
when(dockerClient.removeContainerCmd("container-id")).thenReturn(removeCmd);
when(removeCmd.withForce(true)).thenReturn(removeCmd);
RuntimeException thrown = assertThrows(RuntimeException.class,
() -> manager.createAndStart(spec));
assertSame(startFailure, thrown, "original start failure must propagate");
verify(removeCmd).exec();
}
@Test
void createAndStartDoesNotRemoveContainerOnSuccess() {
ContainerLifecycleManager.ContainerInfo info =
new ContainerLifecycleManager.ContainerInfo("container-id", Map.of());
doReturn("container-id").when(manager).create(spec);
doReturn(info).when(manager).startCreated("container-id", spec);
assertSame(info, manager.createAndStart(spec));
verify(dockerClient, never()).removeContainerCmd(any(String.class));
}
}
@@ -83,6 +83,25 @@ class EcsLoadBalancerRegistrarTest {
"target should be deregistered");
}
@Test
void awsvpcInContainerShapedBindingRegistersContainerPort() {
// In-container mode, awsvpc tasks are expose-only: resolveNetworkBindings
// reports hostPort == containerPort and the registrar must register that
// port (reachable at containerIP:containerPort). The dynamic-host-port
// shape of native mode is covered by registerThenDeregisterTaskContainer.
String tgArn = createTargetGroup("reg-tg-awsvpc");
EcsTask task = taskWithContainer("web", 80, 80);
EcsServiceModel svc = serviceWithLb(tgArn, "web", 80);
registrar.registerTask(task, svc, REGION);
List<TargetHealth> health = elbV2Service.describeTargetHealth(REGION, tgArn, null);
assertEquals(1, health.size(), "one target should be registered");
assertEquals(80, health.get(0).getTarget().getPort());
registrar.deregisterTask(task, svc, REGION);
}
@Test
void serviceWithoutLoadBalancersRegistersNothing() {
String tgArn = createTargetGroup("reg-tg-2");
@@ -11,6 +11,7 @@ import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
import io.github.hectorvent.floci.core.common.docker.LaunchedContainerAwsEnv;
import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
import io.github.hectorvent.floci.services.ecs.model.EcsTask;
import io.github.hectorvent.floci.services.ecs.model.NetworkMode;
import io.github.hectorvent.floci.services.ecs.model.PortMapping;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import org.junit.jupiter.api.BeforeEach;
@@ -42,6 +43,11 @@ import static org.mockito.Mockito.when;
* dynamic host port in native mode and is exposed-only when Floci runs inside
* Docker.
*
* <p>In {@code awsvpc} network mode an explicit hostPort is never bound
* literally (regression coverage for issue #1778: every AWS awsvpc task has its
* own ENI, so identical host ports across tasks must not collide on the single
* local Docker host) — such mappings behave as if hostPort were unset.
*
* <p>The container builder and lifecycle manager are mocked, so the test asserts
* the port arguments that <em>would</em> be handed to Docker without launching
* one — runnable under {@code mvn test} (CI) with no Docker daemon.
@@ -80,6 +86,10 @@ class EcsContainerManagerPortMappingsTest {
}
private void startWith(List<PortMapping> portMappings) {
startWith(portMappings, null);
}
private void startWith(List<PortMapping> portMappings, NetworkMode networkMode) {
ContainerDefinition app = new ContainerDefinition();
app.setName("app");
app.setImage("app:latest");
@@ -88,6 +98,7 @@ class EcsContainerManagerPortMappingsTest {
TaskDefinition taskDef = new TaskDefinition();
taskDef.setFamily("test-family");
taskDef.setContainerDefinitions(List.of(app));
taskDef.setNetworkMode(networkMode);
EcsTask task = new EcsTask();
task.setTaskArn("arn:aws:ecs:us-east-1:000000000000:task/test-cluster/abc123");
@@ -118,6 +129,50 @@ class EcsContainerManagerPortMappingsTest {
verify(builder, never()).withPortBinding(eq(8080), anyInt());
}
@Test
void awsvpcExplicitHostPortUsesDynamicPortInNativeMode() {
when(containerDetector.isRunningInContainer()).thenReturn(false);
startWith(List.of(new PortMapping(80, 80, "tcp")), NetworkMode.awsvpc);
// Regression guard for #1778: awsvpc tasks have per-task ENIs on AWS,
// so the literal hostPort must not be claimed on the shared Docker host.
verify(builder, times(1)).withDynamicPort(80);
verify(builder, never()).withPortBinding(eq(80), anyInt());
}
@Test
void awsvpcExplicitHostPortIsExposedOnlyInContainerMode() {
when(containerDetector.isRunningInContainer()).thenReturn(true);
startWith(List.of(new PortMapping(80, 80, "tcp")), NetworkMode.awsvpc);
verify(builder, times(1)).withExposedPort(80);
verify(builder, never()).withPortBinding(eq(80), anyInt());
verify(builder, never()).withDynamicPort(80);
}
@Test
void twoAwsvpcTasksWithSameHostPortNeverBindLiterally() {
when(containerDetector.isRunningInContainer()).thenReturn(false);
startWith(List.of(new PortMapping(80, 80, "tcp")), NetworkMode.awsvpc);
startWith(List.of(new PortMapping(80, 80, "tcp")), NetworkMode.awsvpc);
verify(builder, times(2)).withDynamicPort(80);
verify(builder, never()).withPortBinding(eq(80), anyInt());
}
@Test
void bridgeModeKeepsLiteralHostPortBinding() {
when(containerDetector.isRunningInContainer()).thenReturn(false);
startWith(List.of(new PortMapping(5000, 5000, "tcp")), NetworkMode.bridge);
verify(builder, times(1)).withPortBinding(5000, 5000);
verify(builder, never()).withDynamicPort(5000);
}
@Test
void inContainerModePublishesExplicitHostPortAndExposesDynamic() {
when(containerDetector.isRunningInContainer()).thenReturn(true);