Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

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

Hector Ventura3771c1e9a22f
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java
index e19d0114d8..65844ff352 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java
@@ -67,7 +67,15 @@ public class ContainerLifecycleManager {
*/
public ContainerInfo createAndStart(ContainerSpec spec) {
String containerId = create(spec);
- return startCreated(containerId, spec);
+ try {
+ return startCreated(containerId, spec);
+ } catch (Exception e) {
+ // A failed start (e.g. host-port conflict) must not leak the created
+ // container: retrying callers would accumulate Created containers and
+ // fixed-name callers would hit name conflicts on the next attempt.
+ removeIfExists(containerId);
+ throw e;
+ }
}
/**
diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java
index 71308bfee3..ee51aae086 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java
@@ -17,6 +17,7 @@ import io.github.hectorvent.floci.services.ecs.model.EcsTask;
import io.github.hectorvent.floci.services.ecs.model.EfsVolumeConfiguration;
import io.github.hectorvent.floci.services.ecs.model.MountPoint;
import io.github.hectorvent.floci.services.ecs.model.NetworkBinding;
+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 io.github.hectorvent.floci.services.ecs.model.Volume;
@@ -132,16 +133,19 @@ public class EcsContainerManager {
specBuilder.withMemoryMb(def.getMemory());
}
- // Add port mappings. An explicit hostPort is always published to the
- // Docker host so the service is reachable at localhost:<hostPort>,
- // matching AWS bridge mode (mirrors the ECR registry's fixed-port
- // publishing). When no hostPort is requested, publish a dynamic host
- // port in native mode; in Docker mode only expose the port, since ECS
+ // Add port mappings. In bridge/host mode an explicit hostPort is
+ // published to the Docker host literally, matching AWS bridge mode
+ // (mirrors the ECR registry's fixed-port publishing). In awsvpc mode
+ // every AWS task gets its own ENI, so a literal hostPort carries no
+ // host-binding semantics and would collide across tasks on the single
+ // local Docker host (#1778) — awsvpc mappings always get a dynamic
+ // host port in native mode, or expose-only in Docker mode where ECS
// consumers reach containers via the docker network IP.
if (def.getPortMappings() != null) {
+ boolean awsvpc = taskDef.getNetworkMode() == NetworkMode.awsvpc;
boolean publishToHost = !containerDetector.isRunningInContainer();
for (PortMapping pm : def.getPortMappings()) {
- if (pm.hostPort() > 0) {
+ if (!awsvpc && pm.hostPort() > 0) {
specBuilder.withPortBinding(pm.containerPort(), pm.hostPort());
} else if (publishToHost) {
specBuilder.withDynamicPort(pm.containerPort());
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerStartFailureTest.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerStartFailureTest.java
new file mode 100644
index 0000000000..e2807ab2f7
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerStartFailureTest.java
@@ -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));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsLoadBalancerRegistrarTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsLoadBalancerRegistrarTest.java
index 387d898948..258375ad3a 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsLoadBalancerRegistrarTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsLoadBalancerRegistrarTest.java
@@ -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");
diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerPortMappingsTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerPortMappingsTest.java
index 3d6d3c9eee..8541795793 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerPortMappingsTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerPortMappingsTest.java
@@ -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);