mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
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:
1 parent
ecc4b1a569
commit
76cc27f2f1
7 files changed
+552
-36
No files matched your search
+5
-12
@@ -195,8 +195,8 @@ class EcsOneShotTaskLifecycleTest {
|
||||
|
||||
@Test
|
||||
@Order(7)
|
||||
@DisplayName("StopTask - explicit stop populates exitCode when already stopped")
|
||||
void explicitStopExitCode() {
|
||||
@DisplayName("StopTask - explicit stop requests terminal status")
|
||||
void explicitStopRequestsTerminalStatus() {
|
||||
// Register and run a second task; stop it explicitly before it exits naturally.
|
||||
String family2 = family + "-explicit";
|
||||
ecs.registerTaskDefinition(RegisterTaskDefinitionRequest.builder()
|
||||
@@ -221,21 +221,14 @@ class EcsOneShotTaskLifecycleTest {
|
||||
.count(1)
|
||||
.build()).tasks().get(0).taskArn();
|
||||
|
||||
Task stopped = ecs.stopTask(StopTaskRequest.builder()
|
||||
Task stopping = ecs.stopTask(StopTaskRequest.builder()
|
||||
.cluster(clusterName)
|
||||
.task(explicitTaskArn)
|
||||
.reason("test-explicit-stop")
|
||||
.build()).task();
|
||||
|
||||
assertThat(stopped.lastStatus()).isEqualTo("STOPPED");
|
||||
assertThat(stopped.stoppedAt()).isNotNull();
|
||||
|
||||
// exitCode should be present (Docker assigns 137 for SIGKILL on explicit stop)
|
||||
assertThat(stopped.containers()).isNotEmpty();
|
||||
stopped.containers().forEach(c ->
|
||||
assertThat(c.exitCode())
|
||||
.as("explicit stopTask must populate exitCode on container %s", c.name())
|
||||
.isNotNull());
|
||||
assertThat(stopping.desiredStatus()).isEqualTo("STOPPED");
|
||||
assertThat(stopping.stoppedReason()).isEqualTo("test-explicit-stop");
|
||||
}
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -266,6 +266,10 @@ applied without rolling anything. An update replaces only the members it names:
|
||||
`placementStrategy` alone leaves a `placementConstraints` stored earlier in place, and an empty
|
||||
array clears a member the way AWS clears it.
|
||||
|
||||
When a service replaces or stops a task in Docker mode, the task remains `STOPPING` until its
|
||||
containers are removed. A failed Docker removal is retried on later reconciliation ticks, so the
|
||||
task is not reported as `STOPPED` while its container may still be serving.
|
||||
|
||||
Every `awsvpc` task gets a real ENI in the subnet it asked for, in Docker and in mock mode alike,
|
||||
and reports it as an `attachments` entry with its `networkInterfaceId`, `privateIPv4Address` and
|
||||
`subnetId`; the task's containers report the same interface in `networkInterfaces`. A subnet that
|
||||
|
||||
@@ -1290,13 +1290,22 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
task.setPullStartedAt(Instant.now());
|
||||
EcsTaskHandle handle = containerManager.startTask(task, taskDef, containerOverrides, region);
|
||||
task.setPullStoppedAt(Instant.now());
|
||||
taskHandles.put(taskArn, handle);
|
||||
markTaskRunning(task);
|
||||
cluster.setRunningTasksCount(cluster.getRunningTasksCount() + 1);
|
||||
LOG.infov("Started ECS task (docker): {0}", taskArn);
|
||||
registerTaskWithLoadBalancers(task, cluster, region);
|
||||
if (eventPublisher != null) {
|
||||
eventPublisher.emitTaskLadder(task, TaskStatus.PENDING, TaskStatus.RUNNING, region);
|
||||
boolean stopRequested;
|
||||
synchronized (task) {
|
||||
taskHandles.put(taskArn, handle);
|
||||
markTaskRunning(task);
|
||||
cluster.setRunningTasksCount(cluster.getRunningTasksCount() + 1);
|
||||
LOG.infov("Started ECS task (docker): {0}", taskArn);
|
||||
stopRequested = TaskStatus.STOPPED.name().equals(task.getDesiredStatus());
|
||||
if (!stopRequested) {
|
||||
registerTaskWithLoadBalancers(task, cluster, region);
|
||||
}
|
||||
if (eventPublisher != null) {
|
||||
eventPublisher.emitTaskLadder(task, TaskStatus.PENDING, TaskStatus.RUNNING, region);
|
||||
}
|
||||
}
|
||||
if (stopRequested) {
|
||||
stopTask(cluster.getClusterName(), taskArn, task.getStoppedReason(), task.getStopCode(), region);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.errorv("Failed to start ECS task {0}: {1}", taskArn, e.getMessage());
|
||||
@@ -1659,30 +1668,52 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
*/
|
||||
private EcsTask stopTask(String clusterRef, String taskRef, String reason, String stopCode, String region) {
|
||||
EcsTask task = resolveTaskOrThrow(taskRef, region);
|
||||
synchronized (task) {
|
||||
return stopTaskLocked(task, reason, stopCode, region);
|
||||
}
|
||||
}
|
||||
|
||||
private EcsTask stopTaskLocked(EcsTask task, String reason, String stopCode, String region) {
|
||||
if (TaskStatus.STOPPED.name().equals(task.getLastStatus())) {
|
||||
return task;
|
||||
}
|
||||
task.setDesiredStatus(TaskStatus.STOPPED.name());
|
||||
task.setLastStatus(TaskStatus.STOPPING.name());
|
||||
task.setStoppingAt(Instant.now());
|
||||
task.setStoppedReason(reason != null ? reason : "Stopped by user");
|
||||
task.setStopCode(stopCode);
|
||||
task.bumpVersion();
|
||||
|
||||
deregisterTaskFromLoadBalancers(task, region);
|
||||
if (!TaskStatus.STOPPING.name().equals(task.getLastStatus())) {
|
||||
task.setDesiredStatus(TaskStatus.STOPPED.name());
|
||||
task.setLastStatus(TaskStatus.STOPPING.name());
|
||||
task.setStoppingAt(Instant.now());
|
||||
task.setStoppedReason(reason != null ? reason : "Stopped by user");
|
||||
task.setStopCode(stopCode);
|
||||
task.bumpVersion();
|
||||
deregisterTaskFromLoadBalancers(task, region);
|
||||
}
|
||||
|
||||
Map<String, Integer> exitCodes = Map.of();
|
||||
Map<String, Instant> finishedAt = Map.of();
|
||||
if (dockerMode) {
|
||||
EcsTaskHandle handle = taskHandles.remove(task.getTaskArn());
|
||||
EcsTaskHandle handle = taskHandles.get(task.getTaskArn());
|
||||
if (handle == null) {
|
||||
handle = recoverTaskHandle(task, region);
|
||||
if (handle == null) {
|
||||
LOG.warnv("Cannot stop ECS task {0}: no Docker container IDs are available", task.getTaskArn());
|
||||
return task;
|
||||
}
|
||||
}
|
||||
try {
|
||||
exitCodes = containerManager.stopTaskAndCollectExitCodes(handle);
|
||||
} finally {
|
||||
retainUnresolvedLogHandle(task.getTaskArn(), handle);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv(e, "Could not stop ECS task {0}; retrying on the next reconciliation tick",
|
||||
task.getTaskArn());
|
||||
return task;
|
||||
}
|
||||
if (handle != null) {
|
||||
finishedAt = handle.getFinishedAt();
|
||||
if (exitCodes.size() != handle.getContainerIds().size()
|
||||
|| !handle.allContainersRemoved()) {
|
||||
LOG.warnv("ECS task {0} still has containers pending removal; retrying on the next reconciliation tick",
|
||||
task.getTaskArn());
|
||||
return task;
|
||||
}
|
||||
taskHandles.remove(task.getTaskArn(), handle);
|
||||
retainUnresolvedLogHandle(task.getTaskArn(), handle);
|
||||
finishedAt = handle.getFinishedAt();
|
||||
}
|
||||
|
||||
task.setLastStatus(TaskStatus.STOPPED.name());
|
||||
@@ -3900,6 +3931,16 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
if (task == null) {
|
||||
return;
|
||||
}
|
||||
synchronized (task) {
|
||||
reconcileTaskLocked(taskArn, task);
|
||||
}
|
||||
}
|
||||
|
||||
private void reconcileTaskLocked(String taskArn, EcsTask task) {
|
||||
if (TaskStatus.STOPPING.name().equals(task.getLastStatus())) {
|
||||
stopTask(task.getClusterArn(), taskArn, task.getStoppedReason(), task.getStopCode(), taskRegion(task));
|
||||
return;
|
||||
}
|
||||
|
||||
if (TaskStatus.STOPPED.name().equals(task.getLastStatus())) {
|
||||
reconcileStoppedTask(taskArn);
|
||||
@@ -4045,6 +4086,37 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
}
|
||||
}
|
||||
|
||||
private EcsTaskHandle recoverTaskHandle(EcsTask task, String region) {
|
||||
if (task.getContainers() == null || task.getContainers().isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
Map<String, String> containerIds = new LinkedHashMap<>();
|
||||
for (Container container : task.getContainers()) {
|
||||
String dockerId = container.getDockerId() != null
|
||||
? container.getDockerId() : container.getRuntimeId();
|
||||
if (dockerId == null) {
|
||||
return null;
|
||||
}
|
||||
containerIds.put(container.getName(), dockerId);
|
||||
}
|
||||
Map<String, Integer> stopTimeouts = new LinkedHashMap<>();
|
||||
try {
|
||||
TaskDefinition definition = resolveTaskDefinitionOrThrow(task.getTaskDefinitionArn(), region);
|
||||
for (ContainerDefinition container : definition.getContainerDefinitions()) {
|
||||
if (container.getStopTimeout() != null) {
|
||||
stopTimeouts.put(container.getName(), container.getStopTimeout());
|
||||
}
|
||||
}
|
||||
} catch (AwsException e) {
|
||||
LOG.warnv(e, "Could not load task definition for {0}; using the default container stop timeout",
|
||||
task.getTaskArn());
|
||||
}
|
||||
EcsTaskHandle recovered = new EcsTaskHandle(task.getTaskArn(), containerIds, Map.of(),
|
||||
null, task.getNetworkInterfaceId(), region, stopTimeouts);
|
||||
EcsTaskHandle existing = taskHandles.putIfAbsent(task.getTaskArn(), recovered);
|
||||
return existing != null ? existing : recovered;
|
||||
}
|
||||
|
||||
/**
|
||||
* DAEMON scheduling: exactly one task on each ACTIVE container instance of the cluster,
|
||||
* none anywhere else. {@code desiredCount} is derived from the instance count, as AWS
|
||||
|
||||
+20
-3
@@ -1110,6 +1110,9 @@ public class EcsContainerManager {
|
||||
// period its container definition asked for.
|
||||
Set<String> terminatedContainerIds = new HashSet<>();
|
||||
for (Map.Entry<String, String> entry : handle.getContainerIds().entrySet()) {
|
||||
if (handle.isContainerRemoved(entry.getKey())) {
|
||||
continue;
|
||||
}
|
||||
String dockerId = entry.getValue();
|
||||
try {
|
||||
lifecycleManager.getDockerClient().stopContainerCmd(dockerId)
|
||||
@@ -1126,24 +1129,38 @@ public class EcsContainerManager {
|
||||
// Phase 2: inspect exit codes, then remove.
|
||||
for (Map.Entry<String, String> entry : handle.getContainerIds().entrySet()) {
|
||||
String name = entry.getKey();
|
||||
if (handle.isContainerRemoved(name)) {
|
||||
exitCodes.put(name, handle.getRecordedExitCode(name));
|
||||
continue;
|
||||
}
|
||||
String dockerId = entry.getValue();
|
||||
exitCodes.put(name, getExitCodeIfStopped(dockerId));
|
||||
Integer exitCode = handle.getRecordedExitCode(name);
|
||||
if (exitCode == null) {
|
||||
exitCode = getExitCodeIfStopped(dockerId);
|
||||
handle.recordExitCode(name, exitCode);
|
||||
}
|
||||
exitCodes.put(name, exitCode);
|
||||
// Read before the removal below, which is the last moment the daemon still knows it.
|
||||
handle.recordFinishedAt(name, getFinishedAtIfStopped(dockerId));
|
||||
try {
|
||||
lifecycleManager.getDockerClient().removeContainerCmd(dockerId).withForce(true).exec();
|
||||
terminatedContainerIds.add(dockerId);
|
||||
handle.recordContainerRemoved(name);
|
||||
} catch (NotFoundException ignored) {
|
||||
terminatedContainerIds.add(dockerId);
|
||||
handle.recordContainerRemoved(name);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Error removing ECS container {0}: {1}", dockerId, e.getMessage());
|
||||
exitCodes.put(name, null);
|
||||
}
|
||||
}
|
||||
// A force removal terminates Docker's follow-log transport even when the preceding stop failed.
|
||||
// Preserve handles for any container that still may be running after both operations failed.
|
||||
terminatedContainerIds.forEach(dockerId -> finalizeLogStream(handle, dockerId));
|
||||
cleanupProtectedNetwork(handle);
|
||||
removeFirelensVolume(handle);
|
||||
if (handle.allContainersRemoved()) {
|
||||
cleanupProtectedNetwork(handle);
|
||||
removeFirelensVolume(handle);
|
||||
}
|
||||
return exitCodes;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,8 +2,10 @@ package io.github.hectorvent.floci.services.ecs.container;
|
||||
|
||||
import java.io.Closeable;
|
||||
import java.time.Instant;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Holds the runtime Docker container IDs for a running ECS task.
|
||||
@@ -34,6 +36,10 @@ public class EcsTaskHandle {
|
||||
* removed, so the time has to be kept here for the caller that stamps the task's containers.
|
||||
*/
|
||||
private final Map<String, Instant> finishedAt = new LinkedHashMap<>();
|
||||
/** Exit codes read before Docker removes a container, retained across teardown retries. */
|
||||
private final Map<String, Integer> exitCodes = new LinkedHashMap<>();
|
||||
/** Container names confirmed removed, including those whose exit code was unavailable. */
|
||||
private final Set<String> removedContainers = new HashSet<>();
|
||||
|
||||
public EcsTaskHandle(String taskArn, Map<String, String> containerIds,
|
||||
Map<String, Closeable> logStreamsByContainerId) {
|
||||
@@ -85,6 +91,28 @@ public class EcsTaskHandle {
|
||||
return finishedAt;
|
||||
}
|
||||
|
||||
public Integer getRecordedExitCode(String containerName) {
|
||||
return exitCodes.get(containerName);
|
||||
}
|
||||
|
||||
public void recordExitCode(String containerName, Integer exitCode) {
|
||||
if (exitCode != null) {
|
||||
exitCodes.putIfAbsent(containerName, exitCode);
|
||||
}
|
||||
}
|
||||
|
||||
public void recordContainerRemoved(String containerName) {
|
||||
removedContainers.add(containerName);
|
||||
}
|
||||
|
||||
public boolean isContainerRemoved(String containerName) {
|
||||
return removedContainers.contains(containerName);
|
||||
}
|
||||
|
||||
public boolean allContainersRemoved() {
|
||||
return removedContainers.containsAll(containerIds.keySet());
|
||||
}
|
||||
|
||||
/** Removes and returns the log stream that no longer needs task-level ownership. */
|
||||
public Closeable removeLogStream(String containerId) {
|
||||
return logStreamsByContainerId.remove(containerId);
|
||||
|
||||
@@ -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(
|
||||
|
||||
+90
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user