fix(ecs): retry teardown of redeployed task containers (#4280)

* fix(ecs): retry teardown of redeployed task containers

* test(ecs): wait for explicit task stop in SDK compatibility test

* fix(ecs): serialize teardown and align stop compatibility test

* test(ecs): observe blocked concurrent stop without delay

* fix(ecs): preserve unknown exits and serialize startup transition
This commit is contained in:
Abhigya authored and GitHub committed 2026-09-24 15:51:05 -04:00
1 parent ecc4b1a569
commit 76cc27f2f1
7 files changed
+552 -36

No files matched your search

@@ -9,7 +9,9 @@ import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ecs.container.EcsContainerManager;
import io.github.hectorvent.floci.services.ecs.container.EcsTaskHandle;
import io.github.hectorvent.floci.services.ecs.model.Container;
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.LaunchType;
import org.junit.jupiter.api.Test;
@@ -17,12 +19,19 @@ import java.io.Closeable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@@ -38,6 +47,308 @@ class EcsServiceTeardownTest {
private static final String REGION = "us-east-1";
@Test
void startupTransitionWaitsForTheTaskLock() throws Exception {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().ecs().mock()).thenReturn(false);
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
EcsContainerManager containerManager = mock(EcsContainerManager.class);
CountDownLatch startEntered = new CountDownLatch(1);
CountDownLatch finishStart = new CountDownLatch(1);
AtomicReference<EcsTask> startingTask = new AtomicReference<>();
when(containerManager.startTask(any(), any(), any(), anyString())).thenAnswer(invocation -> {
EcsTask task = invocation.getArgument(0);
startingTask.set(task);
startEntered.countDown();
if (!finishStart.await(5, TimeUnit.SECONDS)) {
throw new IllegalStateException("container startup was not released");
}
return new EcsTaskHandle(task.getTaskArn(), Map.of("app", "docker-id"), Map.of());
});
EcsService service = new EcsService(new RegionResolver(REGION, "000000000000"),
containerManager, config, mock(EcsLoadBalancerRegistrar.class),
new SingleUseStorageFactory(), null);
service.initializeStorage();
ContainerDefinition definition = new ContainerDefinition();
definition.setName("app");
definition.setImage("nginx:alpine");
service.registerTaskDefinition("locked-start", List.of(definition), null, null, null,
null, null, List.of(), REGION);
AtomicReference<Throwable> launchFailure = new AtomicReference<>();
Thread launch = new Thread(() -> {
try {
service.runTask(null, "locked-start", 1, LaunchType.FARGATE, null, null,
List.of(), null, REGION);
} catch (Throwable failure) {
launchFailure.set(failure);
}
});
launch.start();
try {
assertTrue(startEntered.await(5, TimeUnit.SECONDS));
synchronized (startingTask.get()) {
finishStart.countDown();
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
while (launch.getState() != Thread.State.BLOCKED) {
assertTrue(launch.isAlive(), "startup finished without acquiring the task lock");
assertTrue(System.nanoTime() < deadline, "startup did not wait for the task lock");
Thread.onSpinWait();
}
}
launch.join(5000);
assertFalse(launch.isAlive());
assertNull(launchFailure.get());
assertEquals("RUNNING", startingTask.get().getLastStatus());
} finally {
finishStart.countDown();
service.stopManagedContainers();
}
}
@Test
void stopDuringContainerStartupCompletesAfterTheHandleArrives() throws Exception {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().ecs().mock()).thenReturn(false);
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
EcsContainerManager containerManager = mock(EcsContainerManager.class);
CountDownLatch startEntered = new CountDownLatch(1);
CountDownLatch finishStart = new CountDownLatch(1);
AtomicReference<String> taskArn = new AtomicReference<>();
EcsTaskHandle handle = new EcsTaskHandle("task-arn", Map.of("app", "docker-id"), Map.of());
when(containerManager.startTask(any(), any(), any(), anyString())).thenAnswer(invocation -> {
EcsTask task = invocation.getArgument(0);
taskArn.set(task.getTaskArn());
startEntered.countDown();
if (!finishStart.await(5, TimeUnit.SECONDS)) {
throw new IllegalStateException("container startup was not released");
}
Container container = new Container();
container.setName("app");
container.setRuntimeId("docker-id");
task.setContainers(List.of(container));
return handle;
});
when(containerManager.stopTaskAndCollectExitCodes(handle)).thenAnswer(ignored -> {
handle.recordContainerRemoved("app");
return Map.of("app", 0);
});
EcsService service = new EcsService(
new RegionResolver(REGION, "000000000000"), containerManager, config,
mock(EcsLoadBalancerRegistrar.class), new SingleUseStorageFactory(), null);
service.initializeStorage();
ContainerDefinition definition = new ContainerDefinition();
definition.setName("app");
definition.setImage("nginx:alpine");
service.registerTaskDefinition("startup-stop", List.of(definition), null, null, null,
null, null, List.of(), REGION);
CompletableFuture<List<EcsTask>> launch = CompletableFuture.supplyAsync(() ->
service.runTask(null, "startup-stop", 1, LaunchType.FARGATE, null, null,
List.of(), null, REGION));
try {
assertTrue(startEntered.await(5, TimeUnit.SECONDS));
assertEquals("STOPPING", service.stopTask(null, taskArn.get(), null, REGION).getLastStatus());
} finally {
finishStart.countDown();
}
launch.get(5, TimeUnit.SECONDS);
assertEquals("STOPPED", service.describeTasks(null, List.of(taskArn.get()), REGION).getFirst().getLastStatus());
verify(containerManager).stopTaskAndCollectExitCodes(handle);
service.stopManagedContainers();
}
@Test
void stopTaskRecoversContainerIdsWhenTheRuntimeHandleIsMissing() {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().ecs().mock()).thenReturn(false);
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
EcsContainerManager containerManager = mock(EcsContainerManager.class);
EcsTaskHandle original = new EcsTaskHandle("task-arn", Map.of("app", "docker-id"), Map.of());
when(containerManager.startTask(any(), any(), any(), anyString())).thenAnswer(invocation -> {
EcsTask task = invocation.getArgument(0);
Container container = new Container();
container.setName("app");
container.setDockerId("docker-id");
task.setContainers(List.of(container));
return original;
});
when(containerManager.stopTaskAndCollectExitCodes(any())).thenAnswer(invocation -> {
EcsTaskHandle stoppingHandle = invocation.getArgument(0);
stoppingHandle.recordContainerRemoved("app");
return Map.of("app", 0);
});
EcsService service = new EcsService(
new RegionResolver(REGION, "000000000000"), containerManager, config,
mock(EcsLoadBalancerRegistrar.class), new SingleUseStorageFactory(), null);
service.initializeStorage();
ContainerDefinition definition = new ContainerDefinition();
definition.setName("app");
definition.setImage("nginx:alpine");
service.registerTaskDefinition("recover-handle", List.of(definition), null, null, null,
null, null, List.of(), REGION);
String taskArn = service.runTask(null, "recover-handle", 1, LaunchType.FARGATE, null, null,
List.of(), null, REGION).getFirst().getTaskArn();
// A no-op Docker test double leaves the container alive while shutdown drops its handle.
service.stopManagedContainers();
service.afterReset();
service.stopTask(null, taskArn, null, REGION);
verify(containerManager).stopTaskAndCollectExitCodes(argThat(
handle -> "docker-id".equals(handle.getContainerIds().get("app"))));
assertEquals("STOPPED", service.describeTasks(null, List.of(taskArn), REGION).getFirst().getLastStatus());
service.stopManagedContainers();
}
@Test
void failedContainerRemovalKeepsTaskStoppingUntilReconciliationRetries() {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().ecs().mock()).thenReturn(false);
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
EcsContainerManager containerManager = mock(EcsContainerManager.class);
EcsTaskHandle handle = new EcsTaskHandle("task-arn", Map.of("app", "docker-id"), Map.of());
when(containerManager.startTask(any(), any(), any(), anyString())).thenReturn(handle);
Map<String, Integer> failed = new HashMap<>();
failed.put("app", null);
AtomicInteger attempts = new AtomicInteger();
when(containerManager.stopTaskAndCollectExitCodes(handle)).thenAnswer(ignored -> {
if (attempts.incrementAndGet() == 1) {
return failed;
}
handle.recordContainerRemoved("app");
return Map.of("app", 0);
});
EcsService service = new EcsService(
new RegionResolver(REGION, "000000000000"), containerManager, config,
mock(EcsLoadBalancerRegistrar.class), new SingleUseStorageFactory(), null);
service.initializeStorage();
ContainerDefinition definition = new ContainerDefinition();
definition.setName("app");
definition.setImage("nginx:alpine");
service.registerTaskDefinition("retry-removal", List.of(definition), null, null, null,
null, null, List.of(), REGION);
String taskArn = service.runTask(null, "retry-removal", 1, LaunchType.FARGATE, null, null,
List.of(), null, REGION).getFirst().getTaskArn();
service.stopTask(null, taskArn, null, REGION);
assertEquals("STOPPING", service.describeTasks(null, List.of(taskArn), REGION).getFirst().getLastStatus());
service.reconcile();
assertEquals("STOPPED", service.describeTasks(null, List.of(taskArn), REGION).getFirst().getLastStatus());
verify(containerManager, times(2)).stopTaskAndCollectExitCodes(handle);
}
@Test
void removedContainerWithUnknownExitCodeStopsWithoutInventingSuccess() {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().ecs().mock()).thenReturn(false);
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
EcsContainerManager containerManager = mock(EcsContainerManager.class);
EcsTaskHandle handle = new EcsTaskHandle("task-arn", Map.of("app", "docker-id"), Map.of());
when(containerManager.startTask(any(), any(), any(), anyString())).thenAnswer(invocation -> {
EcsTask task = invocation.getArgument(0);
Container container = new Container();
container.setName("app");
task.setContainers(List.of(container));
return handle;
});
when(containerManager.stopTaskAndCollectExitCodes(handle)).thenAnswer(ignored -> {
handle.recordContainerRemoved("app");
Map<String, Integer> codes = new HashMap<>();
codes.put("app", null);
return codes;
});
EcsService service = new EcsService(new RegionResolver(REGION, "000000000000"),
containerManager, config, mock(EcsLoadBalancerRegistrar.class),
new SingleUseStorageFactory(), null);
service.initializeStorage();
ContainerDefinition definition = new ContainerDefinition();
definition.setName("app");
definition.setImage("nginx:alpine");
service.registerTaskDefinition("unknown-exit", List.of(definition), null, null, null,
null, null, List.of(), REGION);
String taskArn = service.runTask(null, "unknown-exit", 1, LaunchType.FARGATE, null, null,
List.of(), null, REGION).getFirst().getTaskArn();
EcsTask stopped = service.stopTask(null, taskArn, null, REGION);
assertEquals("STOPPED", stopped.getLastStatus());
assertNull(stopped.getContainers().getFirst().getExitCode());
service.reconcile();
verify(containerManager, times(1)).stopTaskAndCollectExitCodes(handle);
service.stopManagedContainers();
}
@Test
void concurrentStopsTeardownTheTaskOnlyOnce() throws Exception {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().ecs().mock()).thenReturn(false);
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
EcsContainerManager containerManager = mock(EcsContainerManager.class);
EcsTaskHandle handle = new EcsTaskHandle("task-arn", Map.of("app", "docker-id"), Map.of());
when(containerManager.startTask(any(), any(), any(), anyString())).thenReturn(handle);
CountDownLatch teardownEntered = new CountDownLatch(1);
CountDownLatch finishTeardown = new CountDownLatch(1);
when(containerManager.stopTaskAndCollectExitCodes(handle)).thenAnswer(ignored -> {
teardownEntered.countDown();
if (!finishTeardown.await(5, TimeUnit.SECONDS)) {
throw new IllegalStateException("teardown was not released");
}
handle.recordContainerRemoved("app");
return Map.of("app", 0);
});
EcsService service = new EcsService(
new RegionResolver(REGION, "000000000000"), containerManager, config,
mock(EcsLoadBalancerRegistrar.class), new SingleUseStorageFactory(), null);
service.initializeStorage();
ContainerDefinition definition = new ContainerDefinition();
definition.setName("app");
definition.setImage("nginx:alpine");
service.registerTaskDefinition("concurrent-stop", List.of(definition), null, null, null,
null, null, List.of(), REGION);
String taskArn = service.runTask(null, "concurrent-stop", 1, LaunchType.FARGATE, null, null,
List.of(), null, REGION).getFirst().getTaskArn();
CompletableFuture<EcsTask> first = CompletableFuture.supplyAsync(() ->
service.stopTask(null, taskArn, null, REGION));
try {
assertTrue(teardownEntered.await(5, TimeUnit.SECONDS));
AtomicReference<Throwable> secondFailure = new AtomicReference<>();
Thread second = new Thread(() -> {
try {
service.stopTask(null, taskArn, null, REGION);
} catch (Throwable failure) {
secondFailure.set(failure);
}
});
second.start();
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
while (second.getState() != Thread.State.BLOCKED) {
assertTrue(second.isAlive(), "second stop finished without waiting for the first");
assertTrue(System.nanoTime() < deadline, "second stop never queued on the task");
Thread.onSpinWait();
}
finishTeardown.countDown();
first.get(5, TimeUnit.SECONDS);
second.join(5000);
assertFalse(second.isAlive(), "second stop did not finish");
assertNull(secondFailure.get());
verify(containerManager, times(1)).stopTaskAndCollectExitCodes(handle);
assertEquals("STOPPED", service.describeTasks(null, List.of(taskArn), REGION).getFirst().getLastStatus());
} finally {
finishTeardown.countDown();
}
}
@Test
void stopManagedContainersStopsEachRunningTaskOnce() {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
@@ -118,10 +429,11 @@ class EcsServiceTeardownTest {
when(containerManager.startTask(any(), any(), any(), anyString())).thenReturn(handle);
AtomicInteger teardownAttempts = new AtomicInteger();
when(containerManager.stopTaskAndCollectExitCodes(handle)).thenAnswer(ignored -> {
handle.recordContainerRemoved("app");
if (teardownAttempts.incrementAndGet() == 2) {
handle.removeLogStream("docker-id");
}
return Map.of();
return Map.of("app", 0);
});
EcsService service = new EcsService(
@@ -20,17 +20,107 @@ import java.io.Closeable;
import java.util.LinkedHashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.doAnswer;
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.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class EcsContainerManagerLifecycleTest {
@Test
void forceRemovalWithUnknownExitCodeDoesNotBecomeSuccessOnRetry() {
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
DockerClient dockerClient = mock(DockerClient.class);
StopContainerCmd stop = mock(StopContainerCmd.class);
RemoveContainerCmd remove = mock(RemoveContainerCmd.class);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
when(dockerClient.stopContainerCmd("docker-id")).thenReturn(stop);
when(stop.withTimeout(5)).thenReturn(stop);
when(dockerClient.removeContainerCmd("docker-id")).thenReturn(remove);
when(remove.withForce(true)).thenReturn(remove);
EcsContainerManager manager = spy(manager(lifecycleManager));
EcsTaskHandle handle = new EcsTaskHandle("task-arn", Map.of("app", "docker-id"), Map.of());
doAnswer(ignored -> handle.allContainersRemoved() ? 0 : null)
.when(manager).getExitCodeIfStopped("docker-id");
Map<String, Integer> firstAttempt = manager.stopTaskAndCollectExitCodes(handle);
Map<String, Integer> retry = manager.stopTaskAndCollectExitCodes(handle);
assertTrue(handle.allContainersRemoved());
assertTrue(firstAttempt.containsKey("app"));
assertNull(firstAttempt.get("app"));
assertNull(retry.get("app"));
verify(remove, times(1)).exec();
}
@Test
void failedRemovalLeavesTheTaskContainerUnresolvedForRetry() {
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
DockerClient dockerClient = mock(DockerClient.class);
StopContainerCmd stop = mock(StopContainerCmd.class);
RemoveContainerCmd remove = mock(RemoveContainerCmd.class);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
when(dockerClient.stopContainerCmd("docker-id")).thenReturn(stop);
when(stop.withTimeout(5)).thenReturn(stop);
when(dockerClient.removeContainerCmd("docker-id")).thenReturn(remove);
when(remove.withForce(true)).thenReturn(remove);
doThrow(new RuntimeException("remove failed")).when(remove).exec();
EcsContainerManager manager = spy(manager(lifecycleManager));
doReturn(0).when(manager).getExitCodeIfStopped("docker-id");
EcsTaskHandle handle = new EcsTaskHandle("task-arn", Map.of("app", "docker-id"), Map.of());
Map<String, Integer> exitCodes = manager.stopTaskAndCollectExitCodes(handle);
assertTrue(exitCodes.containsKey("app"));
assertNull(exitCodes.get("app"), "an unremoved container must remain retryable even after it exits");
}
@Test
void retryPreservesExitCodeOfASiblingRemovedOnTheFirstAttempt() {
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
DockerClient dockerClient = mock(DockerClient.class);
StopContainerCmd firstStop = mock(StopContainerCmd.class);
StopContainerCmd secondStop = mock(StopContainerCmd.class);
RemoveContainerCmd firstRemove = mock(RemoveContainerCmd.class);
RemoveContainerCmd secondRemove = mock(RemoveContainerCmd.class);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
when(dockerClient.stopContainerCmd("first-id")).thenReturn(firstStop);
when(dockerClient.stopContainerCmd("second-id")).thenReturn(secondStop);
when(firstStop.withTimeout(5)).thenReturn(firstStop);
when(secondStop.withTimeout(5)).thenReturn(secondStop);
when(dockerClient.removeContainerCmd("first-id")).thenReturn(firstRemove);
when(dockerClient.removeContainerCmd("second-id")).thenReturn(secondRemove);
when(firstRemove.withForce(true)).thenReturn(firstRemove);
when(secondRemove.withForce(true)).thenReturn(secondRemove);
doThrow(new RuntimeException("remove failed")).doNothing().when(secondRemove).exec();
EcsContainerManager manager = spy(manager(lifecycleManager));
doReturn(137).when(manager).getExitCodeIfStopped("first-id");
doReturn(0).when(manager).getExitCodeIfStopped("second-id");
EcsTaskHandle handle = new EcsTaskHandle("task-arn",
Map.of("first", "first-id", "second", "second-id"), Map.of());
Map<String, Integer> firstAttempt = manager.stopTaskAndCollectExitCodes(handle);
assertNull(firstAttempt.get("second"));
doReturn(0).when(manager).getExitCodeIfStopped("first-id");
Map<String, Integer> retry = manager.stopTaskAndCollectExitCodes(handle);
assertEquals(137, retry.get("first"));
assertEquals(0, retry.get("second"));
}
@Test
void finalizesTaskLogStreamsAfterForceRemovingAContainerWhoseStopFails() {
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);