fix(ecs): mount and clean up ephemeral task volumes (#5511)

* fix(ecs): mount and clean up ephemeral task volumes

* fix(ecs): retry orphan volume cleanup independently

* fix(ecs): quiet repeated orphan volume cleanup failures
This commit is contained in:
Mohith authored and GitHub committed 2026-10-13 16:34:26 -04:00
1 parent f4c8237229
commit 760c38ef99
16 files changed
+1064 -40

No files matched your search

@@ -29,6 +29,7 @@ import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.Set;
@@ -65,6 +66,22 @@ class ContainerLifecycleManagerVolumeTest {
dockerClient, imageCacheService, containerDetector, portAllocator, config);
}
@Test
void ensureVolumePersistsOwnershipLabelsAndTheirLegacyAliases() {
InspectVolumeCmd inspect = mock(InspectVolumeCmd.class);
when(dockerClient.inspectVolumeCmd("task-volume")).thenReturn(inspect);
when(inspect.exec()).thenThrow(new NotFoundException("missing"));
CreateVolumeCmd create = mock(CreateVolumeCmd.class, RETURNS_SELF);
when(dockerClient.createVolumeCmd()).thenReturn(create);
manager.ensureVolume("task-volume", Map.of("io.floci.service", "ecs",
"io.floci.owner", "alpha/4566", "io.floci.ecs.run", "run-id"));
verify(create).withLabels(argThat(labels -> "ecs".equals(labels.get("io.floci.service"))
&& "alpha/4566".equals(labels.get("io.floci.owner"))
&& "alpha/4566".equals(labels.get("floci_owner_port"))
&& "run-id".equals(labels.get("io.floci.ecs.run"))
&& "run-id".equals(labels.get("floci.ecs-run"))));
}
@Test
void stopAndRemoveStopsContainerBeforeClosingItsLogStream() {
StopContainerCmd stop = mock(StopContainerCmd.class);
@@ -13,6 +13,8 @@ import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.io.IOException;
import java.nio.file.Files;
@@ -49,6 +51,19 @@ class EcsJsonHandlerVolumesTest {
private EmulatorConfig config;
private EcsJsonHandler handler;
@ParameterizedTest
@ValueSource(strings = {"{}", "{\"fileSystemId\":\"\"}", "{\"fileSystemId\":\" \"}", "\"invalid\""})
void registerTaskDefinitionRejectsMalformedEfsVolume(String efs) throws Exception {
JsonNode request = objectMapper.readTree("""
{"family":"invalid-efs","containerDefinitions":[{"name":"app","image":"busybox:stable",
"mountPoints":[{"sourceVolume":"shared","containerPath":"/data"}]}],
"volumes":[{"name":"shared","efsVolumeConfiguration":%s}]}
""".formatted(efs));
AwsException error = assertThrows(AwsException.class,
() -> handler.handle("RegisterTaskDefinition", request, "us-east-1"));
assertEquals("InvalidParameterException", error.getErrorCode());
}
@BeforeEach
void setUp() {
objectMapper = new ObjectMapper();
@@ -49,6 +49,63 @@ class EcsServiceRestartLeftoversTest {
private static final String TARGET_GROUP_ARN =
"arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/web/0123456789abcdef";
@Test
void pendingPreviousRunVolumesDoNotBlockRunTaskOrServiceTasksAndRetryOnTicks() {
SharedStorageFactory storage = new SharedStorageFactory();
persistServiceWithLoadBalancer(storage);
EcsContainerManager manager = mock(EcsContainerManager.class);
when(manager.removeLeftoverContainers()).thenReturn(true);
when(manager.removeLeftoverTaskVolumes()).thenReturn(false, false, true);
when(manager.getExitCodeIfStopped(anyString())).thenReturn(null);
when(manager.startTask(any(), any(), any(), anyString())).thenAnswer(invocation -> {
EcsTask task = invocation.getArgument(0);
return new EcsTaskHandle(task.getTaskArn(), Map.of("web", "docker-id"), Map.of());
});
EcsService restarted = service(storage, false, manager, mock(EcsLoadBalancerRegistrar.class), null);
restarted.releasePreviousRunLeftovers();
EcsTask task = restarted.runTask("app-cluster", "web", 1, LaunchType.EC2, null, null,
null, null, REGION).getFirst();
assertEquals("RUNNING", task.getLastStatus());
restarted.reconcileServices();
verify(manager, times(2)).startTask(any(), any(), any(), anyString());
verify(manager).removeLeftoverTaskVolumes();
restarted.reconcile();
restarted.reconcile();
restarted.reconcile();
verify(manager, times(3)).removeLeftoverTaskVolumes();
verify(manager).removeLeftoverContainers();
verify(manager, times(2)).startTask(any(), any(), any(), anyString());
}
@Test
void volumeCleanupWaitsForContainersAndRetriesWithoutAnyTaskLaunch() {
EcsContainerManager manager = mock(EcsContainerManager.class);
when(manager.removeLeftoverContainers()).thenReturn(false, true);
when(manager.removeLeftoverTaskVolumes()).thenReturn(false, true);
when(manager.getExitCodeIfStopped(anyString())).thenReturn(null);
when(manager.startTask(any(), any(), any(), anyString())).thenAnswer(invocation -> {
EcsTask task = invocation.getArgument(0);
return new EcsTaskHandle(task.getTaskArn(), Map.of("web", "docker-id"), Map.of());
});
EcsService restarted = service(new SharedStorageFactory(), false, manager,
mock(EcsLoadBalancerRegistrar.class), null);
restarted.releasePreviousRunLeftovers();
restarted.reconcile();
verify(manager, never()).removeLeftoverTaskVolumes();
ContainerDefinition definition = new ContainerDefinition();
definition.setName("web");
definition.setImage("busybox:stable");
restarted.registerTaskDefinition("web", List.of(definition), NetworkMode.bridge, null, null,
null, null, List.of(), REGION);
restarted.runTask(null, "web", 1, LaunchType.EC2, null, null, null, null, REGION);
restarted.reconcile();
restarted.reconcile();
restarted.reconcile();
verify(manager, times(2)).removeLeftoverTaskVolumes();
verify(manager, times(2)).removeLeftoverContainers();
}
@Test
void releasesTheRegistrationsThePreviousRunRecorded() {
EcsLoadBalancerRegistrar lbRegistrar = mock(EcsLoadBalancerRegistrar.class);
@@ -138,6 +195,7 @@ class EcsServiceRestartLeftoversTest {
mock(EcsLoadBalancerRegistrar.class), null).releasePreviousRunLeftovers();
verify(containerManager, never()).removeLeftoverContainers();
verify(containerManager, never()).removeLeftoverTaskVolumes();
}
@Test
@@ -158,6 +216,7 @@ class EcsServiceRestartLeftoversTest {
restarted.runTask("app-cluster", "web", 1, LaunchType.EC2, null, null, null, null, REGION);
verify(containerManager, never()).removeLeftoverContainers();
verify(containerManager, never()).removeLeftoverTaskVolumes();
verify(containerManager).startTask(any(), any(), any(), anyString());
verify(lbRegistrar).releaseRecordedTargets();
verify(discoveryRegistrar).releaseRecordedInstances();
@@ -9,16 +9,20 @@ import io.github.hectorvent.floci.core.storage.StorageBackend;
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.container.EcsTaskLaunchException;
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;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.io.Closeable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@@ -33,6 +37,7 @@ 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.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -47,6 +52,127 @@ class EcsServiceTeardownTest {
private static final String REGION = "us-east-1";
@ParameterizedTest
@ValueSource(booleans = {false, true})
void stoppedTaskKeepsItsHandleUntilEphemeralVolumeCleanupSucceeds(boolean exitsNaturally) {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().ecs().mock()).thenReturn(false);
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
EcsContainerManager manager = mock(EcsContainerManager.class);
EcsTaskHandle handle = new EcsTaskHandle("task-arn", Map.of("app", "docker-id"), Map.of(),
null, null, REGION, Map.of(), Set.of("task-volume"));
when(manager.startTask(any(), any(), any(), anyString())).thenReturn(handle);
when(manager.getExitCodeIfStopped("docker-id")).thenReturn(0);
AtomicInteger attempts = new AtomicInteger();
doAnswer(ignored -> {
attempts.incrementAndGet();
handle.recordContainerRemoved("app");
return null;
}).when(manager).cleanupStoppedTask(handle);
when(manager.stopTaskAndCollectExitCodes(handle)).thenAnswer(ignored -> {
handle.recordContainerRemoved("app");
if (attempts.incrementAndGet() > 1) {
handle.recordTaskVolumeRemoved("task-volume");
}
return Map.of("app", 0);
});
EcsService service = new EcsService(new RegionResolver(REGION, "000000000000"), manager, config,
mock(EcsLoadBalancerRegistrar.class), new SingleUseStorageFactory(), null);
service.initializeStorage();
ContainerDefinition definition = new ContainerDefinition();
definition.setName("app");
definition.setImage("app:latest");
service.registerTaskDefinition("volume-retry", List.of(definition), null, null, null,
null, null, List.of(), REGION);
String taskArn = service.runTask(null, "volume-retry", 1, LaunchType.FARGATE, null, null,
List.of(), null, REGION).getFirst().getTaskArn();
if (exitsNaturally) {
service.reconcile();
} else {
service.stopTask(null, taskArn, null, REGION);
}
assertEquals("STOPPED", service.describeTasks(null, List.of(taskArn), REGION).getFirst().getLastStatus());
assertTrue(handle.hasTaskVolumes());
service.reconcile();
assertFalse(handle.hasTaskVolumes());
service.reconcile();
assertEquals(2, attempts.get(), "cleanup stops retrying after the volume is removed");
}
@Test
void failedLaunchCleanupIsRetriedByStoppedTaskReconciliation() {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().ecs().mock()).thenReturn(false);
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
EcsContainerManager manager = mock(EcsContainerManager.class);
EcsTaskHandle partial = new EcsTaskHandle("task-arn", Map.of("app", "docker-id"), Map.of(),
null, null, REGION, Map.of(), Set.of("task-volume"));
when(manager.startTask(any(), any(), any(), anyString()))
.thenThrow(new EcsTaskLaunchException(new IllegalStateException("launch failed"), partial));
when(manager.stopTaskAndCollectExitCodes(partial)).thenAnswer(ignored -> {
partial.recordContainerRemoved("app");
partial.recordTaskVolumeRemoved("task-volume");
return Map.of("app", 137);
});
EcsService service = new EcsService(new RegionResolver(REGION, "000000000000"), manager, config,
mock(EcsLoadBalancerRegistrar.class), new SingleUseStorageFactory(), null);
service.initializeStorage();
ContainerDefinition definition = new ContainerDefinition();
definition.setName("app");
definition.setImage("busybox:stable");
service.registerTaskDefinition("failed-volume-launch", List.of(definition), null, null, null,
null, null, List.of(), REGION);
EcsTask task = service.runTask(null, "failed-volume-launch", 1, LaunchType.FARGATE, null, null,
List.of(), null, REGION).getFirst();
assertEquals("STOPPED", task.getLastStatus());
assertEquals("Failed to start: launch failed", task.getStoppedReason());
assertTrue(partial.hasTaskVolumes());
service.reconcile();
assertFalse(partial.hasTaskVolumes());
service.reconcile();
verify(manager, times(1)).stopTaskAndCollectExitCodes(partial);
service.stopManagedContainers();
}
@Test
void shutdownRetriesVolumeRemovalAndRetainsPendingCleanupAfterReset() {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().ecs().mock()).thenReturn(false);
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
EcsContainerManager manager = mock(EcsContainerManager.class);
EcsTaskHandle handle = new EcsTaskHandle("task-arn", Map.of("app", "docker-id"), Map.of(),
null, null, REGION, Map.of(), Set.of("task-volume"));
when(manager.startTask(any(), any(), any(), anyString())).thenReturn(handle);
doAnswer(ignored -> {
handle.recordContainerRemoved("app");
return null;
}).when(manager).stopTask(handle);
when(manager.stopTaskAndCollectExitCodes(handle)).thenAnswer(ignored -> {
handle.recordTaskVolumeRemoved("task-volume");
return Map.of("app", 0);
});
EcsService service = new EcsService(new RegionResolver(REGION, "000000000000"), manager, config,
mock(EcsLoadBalancerRegistrar.class), new SingleUseStorageFactory(), null);
service.initializeStorage();
ContainerDefinition definition = new ContainerDefinition();
definition.setName("app");
definition.setImage("busybox:stable");
service.registerTaskDefinition("shutdown-volume", List.of(definition), null, null, null,
null, null, List.of(), REGION);
service.runTask(null, "shutdown-volume", 1, LaunchType.FARGATE, null, null,
List.of(), null, REGION);
service.stopManagedContainers();
verify(manager, times(2)).cleanupStoppedTask(handle);
assertTrue(handle.hasTaskVolumes());
service.clear();
service.afterReset();
service.reconcile();
assertFalse(handle.hasTaskVolumes());
service.stopManagedContainers();
}
@Test
void startupTransitionWaitsForTheTaskLock() throws Exception {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
@@ -175,9 +301,12 @@ class EcsServiceTeardownTest {
task.setContainers(List.of(container));
return original;
});
when(containerManager.taskVolumeNames(any(), any())).thenReturn(Set.of("recovered-volume"));
when(containerManager.stopTaskAndCollectExitCodes(any())).thenAnswer(invocation -> {
EcsTaskHandle stoppingHandle = invocation.getArgument(0);
assertEquals(Set.of("recovered-volume"), stoppingHandle.getTaskVolumeNames());
stoppingHandle.recordContainerRemoved("app");
stoppingHandle.recordTaskVolumeRemoved("recovered-volume");
return Map.of("app", 0);
});
@@ -200,6 +329,7 @@ class EcsServiceTeardownTest {
verify(containerManager).stopTaskAndCollectExitCodes(argThat(
handle -> "docker-id".equals(handle.getContainerIds().get("app"))));
verify(containerManager).taskVolumeNames(any(), any());
assertEquals("STOPPED", service.describeTasks(null, List.of(taskArn), REGION).getFirst().getLastStatus());
service.stopManagedContainers();
}
@@ -0,0 +1,163 @@
package io.github.hectorvent.floci.services.ecs.container;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.InspectContainerResponse.Mount;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.core.command.WaitContainerResultCallback;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
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.MountPoint;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import io.github.hectorvent.floci.services.ecs.model.Volume;
import io.github.hectorvent.floci.testing.TestImages;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
@TestProfile(EcsContainerManagerEphemeralVolumesDockerIntegrationTest.VolumeProfile.class)
class EcsContainerManagerEphemeralVolumesDockerIntegrationTest {
@Inject
EcsContainerManager manager;
@Inject
DockerClient dockerClient;
private final List<EcsTaskHandle> handles = new ArrayList<>();
public static class VolumeProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.docker.resource-namespace", "ecs-ephemeral-volumes-test");
}
}
@BeforeEach
void requireDocker() {
try {
dockerClient.pingCmd().exec();
} catch (Exception unavailable) {
Assumptions.abort("Docker daemon must be available for ephemeral volume integration tests");
}
}
@AfterEach
void cleanUpTasks() {
handles.forEach(manager::stopTask);
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void containersShareEphemeralStorageWithinATaskAndRemoveItOnTeardown(boolean emptyHost) throws Exception {
EcsTaskHandle first = startTask("first-task", emptyHost, 300);
assertEquals(0, waitFor(first, "reader"), "the reader must see the writer's file through the shared mount");
Mount firstWriter = dataMount(first, "writer");
Mount firstReader = dataMount(first, "reader");
assertEquals(firstWriter.getName(), firstReader.getName());
assertEquals(Boolean.TRUE, firstWriter.getRW());
assertEquals(Boolean.FALSE, firstReader.getRW());
EcsTaskHandle second = startTask("second-task", emptyHost, 1);
assertEquals(0, waitFor(second, "reader"), "a second task must get its own empty volume");
Mount secondWriter = dataMount(second, "writer");
assertNotEquals(firstWriter.getName(), secondWriter.getName());
assertEquals(0, waitFor(second, "writer"));
manager.stopTask(first);
handles.remove(first);
assertThrows(NotFoundException.class, () -> dockerClient.inspectVolumeCmd(firstWriter.getName()).exec());
dockerClient.inspectVolumeCmd(secondWriter.getName()).exec();
manager.cleanupStoppedTask(second);
handles.remove(second);
assertThrows(NotFoundException.class, () -> dockerClient.inspectVolumeCmd(secondWriter.getName()).exec());
}
@Test
void nextRunRemovesOrphanVolumesAndContainersWithMatchingOwnership() {
EcsTaskHandle task = startTask("orphan-task", false, 300);
String volumeName = task.getTaskVolumeNames().iterator().next();
Map<String, String> labels = dockerClient.inspectVolumeCmd(volumeName).exec().getLabels();
assertEquals("ecs", labels.get(ContainerStorageHelper.SERVICE_LABEL));
assertEquals("ecs-ephemeral-volumes-test/4566", labels.get(ContainerStorageHelper.OWNER_LABEL));
assertTrue(labels.containsKey(EcsContainerManager.RUN_LABEL));
try {
String nextRun = "next-run-" + UUID.randomUUID();
assertTrue(manager.removeLeftoverContainers(nextRun));
dockerClient.inspectVolumeCmd(volumeName).exec();
assertTrue(manager.removeLeftoverTaskVolumes(nextRun));
assertThrows(NotFoundException.class, () -> dockerClient.inspectVolumeCmd(volumeName).exec());
for (String containerId : task.getContainerIds().values()) {
assertThrows(NotFoundException.class, () -> dockerClient.inspectContainerCmd(containerId).exec());
}
} finally {
manager.stopTask(task);
handles.remove(task);
}
}
private EcsTaskHandle startTask(String marker, boolean emptyHost, int writerSleep) {
ContainerDefinition writer = definition("writer", false);
writer.setCommand(List.of("sh", "-c",
"test ! -e /data/marker || exit 41; echo " + marker + " > /data/marker; exec sleep " + writerSleep));
ContainerDefinition reader = definition("reader", true);
reader.setCommand(List.of("sh", "-c", """
for attempt in 1 2 3 4 5; do
if [ "$(cat /data/marker 2>/dev/null)" = "%s" ]; then exit 0; fi
sleep 1
done
exit 42
""".formatted(marker)));
TaskDefinition taskDefinition = new TaskDefinition();
taskDefinition.setFamily("ephemeral-volume-test");
taskDefinition.setContainerDefinitions(List.of(writer, reader));
taskDefinition.setVolumes(List.of(new Volume("shared", null, null,
emptyHost ? Map.of("host", Map.of()) : null)));
EcsTask task = new EcsTask();
task.setTaskArn("arn:aws:ecs:us-east-1:000000000000:task/ephemeral-volume-test/" + UUID.randomUUID());
EcsTaskHandle handle = manager.startTask(task, taskDefinition, List.of(), "us-east-1");
handles.add(handle);
return handle;
}
private static ContainerDefinition definition(String name, boolean readOnly) {
ContainerDefinition definition = new ContainerDefinition();
definition.setName(name);
definition.setImage(TestImages.BUSYBOX);
definition.setStopTimeout(1);
definition.setMountPoints(List.of(new MountPoint("shared", "/data", readOnly)));
return definition;
}
private Mount dataMount(EcsTaskHandle handle, String container) {
return dockerClient.inspectContainerCmd(handle.getContainerIds().get(container)).exec().getMounts().stream()
.filter(mount -> "/data".equals(mount.getDestination().getPath())).findFirst().orElseThrow();
}
private Integer waitFor(EcsTaskHandle handle, String container) throws Exception {
try (WaitContainerResultCallback callback = new WaitContainerResultCallback()) {
return dockerClient.waitContainerCmd(handle.getContainerIds().get(container)).exec(callback)
.awaitStatusCode(20, TimeUnit.SECONDS);
}
}
}
@@ -1,7 +1,10 @@
package io.github.hectorvent.floci.services.ecs.container;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.InspectVolumeResponse;
import com.github.dockerjava.api.command.ListContainersCmd;
import com.github.dockerjava.api.command.ListVolumesCmd;
import com.github.dockerjava.api.command.ListVolumesResponse;
import com.github.dockerjava.api.command.RemoveContainerCmd;
import com.github.dockerjava.api.command.StopContainerCmd;
import com.github.dockerjava.api.model.Container;
@@ -16,6 +19,7 @@ import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.ssm.SsmService;
import io.github.hectorvent.floci.testutil.LogCapture;
import org.junit.jupiter.api.Test;
import java.io.Closeable;
@@ -23,6 +27,8 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -33,6 +39,7 @@ import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
@@ -259,10 +266,126 @@ class EcsContainerManagerLifecycleTest {
verify(lifecycleManager, never()).removeIfExistsStrict(anyString());
}
@Test
void previousRunVolumesAreRemovedAfterContainersAndFailedRemovalIsRetried() {
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
stubLeftoverListing(lifecycle, Map.of(), Map.of());
InspectVolumeResponse old = leftoverVolume("old", "alpha/4566", "previous");
InspectVolumeResponse current = leftoverVolume("current", "alpha/4566", "current");
InspectVolumeResponse foreign = leftoverVolume("foreign", "beta/4566", "previous");
InspectVolumeResponse unowned = leftoverVolume("unowned", "alpha/4566", null);
InspectVolumeResponse conflicting = leftoverVolume("conflicting", "alpha/4566", "previous");
when(conflicting.getLabels()).thenReturn(Map.of("io.floci.service", "ecs",
"io.floci.owner", "alpha/4566", "floci_owner_port", "beta/4566", "io.floci.ecs.run", "previous"));
stubVolumeListing(lifecycle.getDockerClient(), List.of(old, current, foreign, unowned, conflicting));
doThrow(new IllegalStateException("busy")).doNothing().when(lifecycle).removeVolumeStrict("old");
EcsContainerManager manager = manager(lifecycle, namespacedConfig());
assertTrue(manager.removeLeftoverContainers("current"));
assertFalse(manager.removeLeftoverTaskVolumes("current"));
assertTrue(manager.removeLeftoverTaskVolumes("current"));
verify(lifecycle, times(2)).removeVolumeStrict("old");
verify(lifecycle, never()).removeVolumeStrict("current");
verify(lifecycle, never()).removeVolumeStrict("foreign");
verify(lifecycle, never()).removeVolumeStrict("unowned");
verify(lifecycle, never()).removeVolumeStrict("conflicting");
}
@Test
void previousRunVolumeSweepWaitsForContainerRemoval() {
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
stubLeftoverListing(lifecycle, Map.of("old-container", leftover("old-container",
Map.of("io.floci.service", "ecs", "io.floci.owner", "alpha/4566", "io.floci.ecs.run", "previous"))),
Map.of());
doThrow(new IllegalStateException("busy")).when(lifecycle).removeIfExistsStrict("old-container");
assertFalse(manager(lifecycle, namespacedConfig()).removeLeftoverContainers("current"));
verify(lifecycle.getDockerClient(), never()).listVolumesCmd();
}
@Test
void previousRunVolumeSweepRetriesWhenInventoryCannotBeRead() {
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
stubLeftoverListing(lifecycle, Map.of(), Map.of());
when(lifecycle.getDockerClient().listVolumesCmd()).thenThrow(new IllegalStateException("offline"));
EcsContainerManager manager = manager(lifecycle, namespacedConfig());
assertTrue(manager.removeLeftoverContainers("current"));
assertFalse(manager.removeLeftoverTaskVolumes("current"));
verify(lifecycle, never()).removeVolume(anyString());
}
@Test
void volumeRemovalWarnsOncePerVolumeAndResetsAfterSuccessfulRemoval() {
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
stubLeftoverListing(lifecycle, Map.of(), Map.of());
stubVolumeListing(lifecycle.getDockerClient(), List.of(
leftoverVolume("alpha", "alpha/4566", "previous"),
leftoverVolume("beta", "alpha/4566", "previous")));
doThrow(new IllegalStateException("busy")).when(lifecycle).removeVolumeStrict(anyString());
EcsContainerManager manager = manager(lifecycle, namespacedConfig());
List<LogRecord> records = LogCapture.capture(EcsContainerManager.class, () -> {
assertFalse(manager.removeLeftoverTaskVolumes("current"));
assertFalse(manager.removeLeftoverTaskVolumes("current"));
doNothing().when(lifecycle).removeVolumeStrict("alpha");
assertFalse(manager.removeLeftoverTaskVolumes("current"));
doThrow(new IllegalStateException("busy again")).when(lifecycle).removeVolumeStrict("alpha");
assertFalse(manager.removeLeftoverTaskVolumes("current"));
});
assertEquals(List.of(Level.WARNING.intValue(), Level.WARNING.intValue(),
Level.FINE.intValue(), Level.FINE.intValue(), Level.FINE.intValue(),
Level.WARNING.intValue(), Level.FINE.intValue()),
records.stream().map(record -> record.getLevel().intValue()).toList());
verify(lifecycle, times(4)).removeVolumeStrict("alpha");
verify(lifecycle, times(4)).removeVolumeStrict("beta");
verify(lifecycle, never()).removeVolume(anyString());
}
@Test
void volumeListingWarnsOnceAndResetsAfterSuccessfulListing() {
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
stubLeftoverListing(lifecycle, Map.of(), Map.of());
ListVolumesCmd command = lifecycle.getDockerClient().listVolumesCmd();
ListVolumesResponse empty = mock(ListVolumesResponse.class);
when(empty.getVolumes()).thenReturn(List.of());
when(command.exec()).thenThrow(new IllegalStateException("offline"))
.thenThrow(new IllegalStateException("offline"))
.thenReturn(empty, empty).thenThrow(new IllegalStateException("offline again"));
EcsContainerManager manager = manager(lifecycle, namespacedConfig());
List<LogRecord> records = LogCapture.capture(EcsContainerManager.class, () -> {
assertFalse(manager.removeLeftoverTaskVolumes("current"));
assertFalse(manager.removeLeftoverTaskVolumes("current"));
assertTrue(manager.removeLeftoverTaskVolumes("current"));
assertFalse(manager.removeLeftoverTaskVolumes("current"));
});
assertEquals(List.of(Level.WARNING.intValue(), Level.FINE.intValue(), Level.WARNING.intValue()),
records.stream().map(record -> record.getLevel().intValue()).toList());
}
private static InspectVolumeResponse leftoverVolume(String name, String owner, String run) {
InspectVolumeResponse volume = mock(InspectVolumeResponse.class);
when(volume.getName()).thenReturn(name);
Map<String, String> labels = new LinkedHashMap<>();
labels.put("io.floci.service", "ecs");
labels.put("io.floci.owner", owner);
if (run != null) {
labels.put("io.floci.ecs.run", run);
}
when(volume.getLabels()).thenReturn(labels);
return volume;
}
private static void stubVolumeListing(DockerClient docker, List<InspectVolumeResponse> volumes) {
ListVolumesCmd command = mock(ListVolumesCmd.class, RETURNS_SELF);
ListVolumesResponse response = mock(ListVolumesResponse.class);
when(docker.listVolumesCmd()).thenReturn(command);
when(command.exec()).thenReturn(response);
when(response.getVolumes()).thenReturn(volumes);
}
private static void stubLeftoverListing(ContainerLifecycleManager lifecycleManager,
Map<String, Container> newKeys, Map<String, Container> legacyKeys) {
DockerClient dockerClient = mock(DockerClient.class);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
stubVolumeListing(dockerClient, List.of());
ListContainersCmd listCmd = mock(ListContainersCmd.class, RETURNS_SELF);
when(dockerClient.listContainersCmd()).thenReturn(listCmd);
ListContainersCmd byNewKeys = mock(ListContainersCmd.class);
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.ecs.container;
import com.github.dockerjava.api.DockerClient;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
@@ -22,21 +23,33 @@ import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.ssm.SsmService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.doNothing;
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;
@@ -61,6 +74,174 @@ class EcsContainerManagerVolumesTest {
private EcrRegistryManager ecrRegistryManager;
private EcsContainerManager manager;
private static Stream<Volume> ephemeralVolumes() {
return Stream.of(new Volume("shared", null),
new Volume("shared", null, null, Map.of("host", Map.of())),
new Volume("shared", "", null, Map.of("host", Map.of("sourcePath", ""))));
}
@ParameterizedTest
@MethodSource("ephemeralVolumes")
void ephemeralVolumeIsCreatedOnceAndSharedByContainersWithTheirAccessModes(Volume volume) {
EcsTaskHandle handle = manager.startTask(task("000000000000", "us-east-1"),
ephemeralDefinition(volume), List.of(), "us-east-1");
ArgumentCaptor<String> volumeName = ArgumentCaptor.forClass(String.class);
verify(builder).withNamedVolume(volumeName.capture(), eq("/data"), eq(false));
verify(builder).withNamedVolume(volumeName.getValue(), "/data", true);
verify(lifecycleManager).ensureVolume(eq(volumeName.getValue()), any());
verify(lifecycleManager, times(1)).ensureVolume(anyString(), any());
assertEquals(List.of(volumeName.getValue()), handle.getTaskVolumeNames().stream().toList());
verify(builder, never()).withBind(any(), any());
}
@Test
void taskVolumeIdentityIncludesAccountAndRegion() {
TaskDefinition definition = ephemeralDefinition(new Volume("shared", null));
manager.startTask(task("111111111111", "us-east-1"), definition, List.of(), "us-east-1");
manager.startTask(task("222222222222", "us-east-1"), definition, List.of(), "us-east-1");
manager.startTask(task("111111111111", "eu-west-1"), definition, List.of(), "eu-west-1");
ArgumentCaptor<String> names = ArgumentCaptor.forClass(String.class);
verify(lifecycleManager, times(3)).ensureVolume(names.capture(), any());
assertEquals(3, names.getAllValues().stream().distinct().count());
}
@Test
void unmountedAndUnsupportedVolumesAreNotCreatedAsEphemeralStorage() {
ContainerDefinition app = new ContainerDefinition();
app.setName("app");
app.setImage("app:latest");
app.setMountPoints(List.of(new MountPoint("external", "/external", false),
new MountPoint("ebs", "/ebs", false)));
TaskDefinition definition = new TaskDefinition();
definition.setFamily("ephemeral-test");
definition.setContainerDefinitions(List.of(app));
definition.setVolumes(List.of(new Volume("unused", null),
new Volume("external", null, null, Map.of("dockerVolumeConfiguration", Map.of("scope", "shared"))),
new Volume("ebs", null, null, Map.of("configuredAtLaunch", true))));
manager.startTask(task("000000000000", "us-east-1"), definition, List.of(), "us-east-1");
verify(lifecycleManager, never()).ensureVolume(anyString(), any());
verify(builder, never()).withNamedVolume(any(), any(), anyBoolean());
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void failedLaunchRemovesItsEphemeralVolume(boolean firstContainerStarted) {
if (firstContainerStarted) {
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerInfo("docker-id", Map.of()))
.thenThrow(new IllegalStateException("launch failed"));
} else {
when(lifecycleManager.createAndStart(any())).thenThrow(new IllegalStateException("launch failed"));
}
assertThrows(IllegalStateException.class, () -> manager.startTask(task("000000000000", "us-east-1"),
ephemeralDefinition(new Volume("shared", null)), List.of(), "us-east-1"));
ArgumentCaptor<String> name = ArgumentCaptor.forClass(String.class);
verify(lifecycleManager).ensureVolume(name.capture(), any());
verify(lifecycleManager).removeVolume(name.getValue());
}
@Test
void volumeRemovalIsRetriedAfterContainersAreGone() {
when(lifecycleManager.getDockerClient()).thenReturn(mock(DockerClient.class, RETURNS_DEEP_STUBS));
EcsContainerManager stopping = spy(manager);
doReturn(0).when(stopping).getExitCodeIfStopped(anyString());
doReturn(null).when(stopping).getFinishedAtIfStopped(anyString());
EcsTaskHandle handle = stopping.startTask(task("000000000000", "us-east-1"),
ephemeralDefinition(new Volume("shared", null)), List.of(), "us-east-1");
String volumeName = handle.getTaskVolumeNames().iterator().next();
when(lifecycleManager.removeVolume(volumeName)).thenReturn(false, true);
stopping.stopTask(handle);
assertTrue(handle.allContainersRemoved());
assertTrue(handle.hasTaskVolumes());
stopping.stopTask(handle);
assertFalse(handle.hasTaskVolumes());
verify(lifecycleManager, times(2)).removeVolume(volumeName);
}
@Test
void volumeIsKeptUntilEveryContainerHasBeenRemoved() {
EcsTaskHandle handle = manager.startTask(task("000000000000", "us-east-1"),
ephemeralDefinition(new Volume("shared", null)), List.of(), "us-east-1");
String name = handle.getTaskVolumeNames().iterator().next();
doThrow(new IllegalStateException("remove failed")).when(lifecycleManager)
.stopAndRemoveStrict("docker-id", null);
manager.cleanupStoppedTask(handle);
assertTrue(handle.hasTaskVolumes());
verify(lifecycleManager, never()).removeVolume(name);
doNothing().when(lifecycleManager).stopAndRemoveStrict("docker-id", null);
when(lifecycleManager.removeVolume(name)).thenReturn(true);
manager.cleanupStoppedTask(handle);
assertFalse(handle.hasTaskVolumes());
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void failedLaunchPreservesResourcesWhenCleanupFails(boolean containerRemovalFails) {
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerInfo("docker-id", Map.of()))
.thenThrow(new IllegalStateException("launch failed"));
if (containerRemovalFails) {
doThrow(new IllegalStateException("remove failed")).when(lifecycleManager)
.stopAndRemoveStrict("docker-id", null);
} else {
when(lifecycleManager.removeVolume(anyString())).thenReturn(false);
}
EcsTaskLaunchException failure = assertThrows(EcsTaskLaunchException.class,
() -> manager.startTask(task("000000000000", "us-east-1"),
ephemeralDefinition(new Volume("shared", null)), List.of(), "us-east-1"));
EcsTaskHandle handle = failure.getHandle();
assertTrue(handle.hasTaskVolumes());
assertEquals(!containerRemovalFails, handle.allContainersRemoved());
assertEquals("launch failed", failure.getMessage());
doNothing().when(lifecycleManager).stopAndRemoveStrict("docker-id", null);
when(lifecycleManager.removeVolume(anyString())).thenReturn(true);
manager.cleanupStoppedTask(handle);
assertTrue(handle.allContainersRemoved());
assertFalse(handle.hasTaskVolumes());
}
@Test
void recoveredVolumeNamesMatchLaunchAndExcludeUnusedAndExternalVolumes() {
EcsTask task = task("000000000000", "us-east-1");
TaskDefinition definition = ephemeralDefinition(new Volume("shared", null));
EcsTaskHandle handle = manager.startTask(task, definition, List.of(), "us-east-1");
assertEquals(handle.getTaskVolumeNames(), manager.taskVolumeNames(task, definition));
definition.setVolumes(List.of(new Volume("shared", "/host/path")));
assertTrue(manager.taskVolumeNames(task, definition).isEmpty());
definition.setVolumes(List.of(new Volume("shared", null,
new EfsVolumeConfiguration("fs-test", null, null, null, null, null))));
assertTrue(manager.taskVolumeNames(task, definition).isEmpty());
}
private static TaskDefinition ephemeralDefinition(Volume volume) {
ContainerDefinition writer = new ContainerDefinition();
writer.setName("writer");
writer.setImage("app:latest");
writer.setMountPoints(List.of(new MountPoint("shared", "/data", false)));
ContainerDefinition reader = new ContainerDefinition();
reader.setName("reader");
reader.setImage("app:latest");
reader.setMountPoints(List.of(new MountPoint("shared", "/data", true)));
TaskDefinition definition = new TaskDefinition();
definition.setFamily("ephemeral-test");
definition.setContainerDefinitions(List.of(writer, reader));
definition.setVolumes(List.of(volume, new Volume("unused", null)));
return definition;
}
private static EcsTask task(String account, String region) {
EcsTask task = new EcsTask();
task.setTaskArn("arn:aws:ecs:" + region + ":" + account + ":task/test-cluster/same-task-id");
return task;
}
@BeforeEach
void setUp() {
builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
@@ -69,6 +250,7 @@ class EcsContainerManagerVolumesTest {
when(containerBuilder.resolveImage(anyString())).thenAnswer(invocation -> invocation.getArgument(0));
lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.removeVolume(anyString())).thenReturn(true);
when(lifecycleManager.resolveImageForLaunch(any(), any()))
.thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null));
when(lifecycleManager.createAndStart(any()))