fix(ecs): return RunTask before the task's images are pulled (#7753)

RunTask and StartTask pulled the images and started the containers inside the
request, so an unreachable registry held the call for minutes. They now answer
PROVISIONING (awsvpc) or PENDING with PENDING containers, as AWS does, and the
launch runs on a virtual-thread executor. A failed pull shows on DescribeTasks
as STOPPED / TaskFailedToStart, and a StopTask during the pull is no longer
overwritten when the containers start.

A RunTask response's PENDING containers carried the ExecuteCommandAgent as
RUNNING with a lastStartedAt; AWS reports it PENDING with neither. A start
failure after a StopTask overwrote the user's reason and UserInitiated code
with TaskFailedToStart.

AWS reports a container's memoryReservation from the moment RunTask answers.
Docker-mode responses had it from the started container; the pending
placeholders now carry it too.

ECS reports a task as pending from RunTask until it runs, through
PROVISIONING as well as PENDING. The cluster's pendingTasksCount was a
stored field nothing ever set, and the pending statistics counted only
PENDING, so both read 0 while a background launch pulled its image.

RunTask now answers before the task's images are pulled, so the test
waits for the launch to land the task instead of expecting RUNNING
straight away.

Closes #7670
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-11-09 09:31:39 -04:00
1 parent ddad6ddeb9
commit c4b22b25bd
28 files changed
+1039 -143

No files matched your search

@@ -21,6 +21,8 @@ import software.amazon.awssdk.services.ecs.model.Volume;
import java.time.Duration;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@@ -47,7 +49,7 @@ class EcsEphemeralVolumeTest {
@ParameterizedTest
@ValueSource(booleans = {false, true})
void nameOnlyAndEmptyHostVolumesShareFilesBetweenContainers(boolean emptyHost) {
void nameOnlyAndEmptyHostVolumesShareFilesBetweenContainers(boolean emptyHost) throws InterruptedException {
String name = "sdk-ephemeral-volume-" + UUID.randomUUID().toString().substring(0, 8);
Volume.Builder volume = Volume.builder().name("shared");
if (emptyHost) {
@@ -82,10 +84,15 @@ class EcsEphemeralVolumeTest {
Task task = started.tasks().get(0);
try {
assertThat(task.containers()).hasSize(2);
assumeTrue(task.containers().stream().allMatch(container -> container.runtimeId() != null),
"ECS Docker mode is required to check files shared by running containers");
DescribeTasksRequest describe = DescribeTasksRequest.builder()
.cluster(name).tasks(task.taskArn()).build();
// RunTask answers before the images are pulled, so whether Docker started the
// containers shows only once the launch is over.
Task launched = awaitLaunched(ecs, describe);
assertThat(launched.stopCodeAsString()).as(launched.stoppedReason())
.isNotEqualTo("TaskFailedToStart");
assumeTrue(launched.containers().stream().allMatch(container -> container.runtimeId() != null),
"ECS Docker mode is required to check files shared by running containers");
assertThat(ecs.waiter().waitUntilTasksStopped(describe,
TestFixtures.waiterOverride(Duration.ofSeconds(30)))
.matched().response()).isPresent();
@@ -106,6 +113,20 @@ class EcsEphemeralVolumeTest {
}
}
/**
* Polls until the task has left PROVISIONING and PENDING. The TasksRunning waiter cannot stand
* in: it fails on STOPPED, and this task's containers exit as soon as they have run.
*/
private static Task awaitLaunched(EcsClient ecs, DescribeTasksRequest describe) throws InterruptedException {
AtomicReference<Task> latest = new AtomicReference<>();
TestFixtures.await(() -> {
Task current = ecs.describeTasks(describe).tasks().get(0);
latest.set(current);
return !"PROVISIONING".equals(current.lastStatus()) && !"PENDING".equals(current.lastStatus());
}, describe.tasks().get(0), "the launch to finish", TimeUnit.SECONDS.toNanos(60), 500);
return latest.get();
}
private static ContainerDefinition container(String name, boolean readOnly, String command) {
return ContainerDefinition.builder().name(name).image("busybox:stable").essential(true)
.command("sh", "-c", command).stopTimeout(1)
@@ -37,6 +37,7 @@ import software.amazon.awssdk.services.ecs.model.StopTaskRequest;
import software.amazon.awssdk.services.ecs.model.Task;
import software.amazon.awssdk.services.ecs.model.TaskDefinition;
import java.time.Duration;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
@@ -107,6 +108,9 @@ class EcsFargateTest {
.containerDefinitions(ContainerDefinition.builder()
.name("app")
.image("nginx:alpine")
// nginx cannot start as user 1000 on a read-only root, and the tests below
// wait for RUNNING, so the container idles until StopTask instead.
.command("sh", "-c", "trap 'exit 0' TERM QUIT; sleep 3600 & wait")
.essential(true)
.user("1000:1000")
.workingDirectory("/srv")
@@ -166,6 +170,8 @@ class EcsFargateTest {
Task task = tasks.get(0);
taskArn = task.taskArn();
// RunTask answers before the images are pulled, as AWS does: an awsvpc task is PROVISIONING.
assertThat(task.lastStatus()).isIn("PROVISIONING", "PENDING");
assertThat(task.launchType()).isEqualTo(LaunchType.FARGATE);
assertThat(task.platformVersion()).isNotBlank();
assertThat(task.platformFamily()).isEqualTo("Linux");
@@ -174,13 +180,17 @@ class EcsFargateTest {
assertThat(task.group()).isEqualTo("family:" + family);
assertThat(task.attachments()).hasSize(1);
assertThat(task.attachments().get(0).type()).isEqualTo("ElasticNetworkInterface");
assertThat(task.attachments().get(0).details())
.anySatisfy(detail -> assertThat(detail.name()).isEqualTo("privateIPv4Address"));
Task described = ecs.describeTasks(DescribeTasksRequest.builder()
DescribeTasksRequest describe = DescribeTasksRequest.builder()
.cluster(clusterName)
.tasks(taskArn)
.build()).tasks().get(0);
.build();
ecs.waiter().waitUntilTasksRunning(describe, TestFixtures.waiterOverride(Duration.ofSeconds(60)));
Task described = ecs.describeTasks(describe).tasks().get(0);
assertThat(described.attachments()).hasSize(1);
assertThat(described.attachments().get(0).details())
.anySatisfy(detail -> assertThat(detail.name()).isEqualTo("privateIPv4Address"));
assertThat(described.connectivityAsString()).isEqualTo("CONNECTED");
assertThat(described.healthStatusAsString()).isNotBlank();
assertThat(described.version()).isPositive();
@@ -228,6 +238,12 @@ class EcsFargateTest {
.build()).tasks().get(0);
try {
// ExecuteCommand reaches only a running task, and RunTask answers before the launch.
ecs.waiter().waitUntilTasksRunning(DescribeTasksRequest.builder()
.cluster(clusterName)
.tasks(plain.taskArn())
.build(),
TestFixtures.waiterOverride(Duration.ofSeconds(60)));
assertThatThrownBy(() -> ecs.executeCommand(ExecuteCommandRequest.builder()
.cluster(clusterName)
.task(plain.taskArn())
@@ -104,7 +104,7 @@ class EcsOneShotTaskLifecycleTest {
@Test
@Order(1)
@DisplayName("RunTask - task starts RUNNING")
@DisplayName("RunTask - task starts PROVISIONING or PENDING")
void runTask() {
List<Task> launched = ecs.runTask(RunTaskRequest.builder()
.cluster(clusterName)
@@ -115,7 +115,9 @@ class EcsOneShotTaskLifecycleTest {
assertThat(launched).hasSize(1);
taskArn = launched.get(0).taskArn();
assertThat(launched.get(0).lastStatus()).isEqualTo("RUNNING");
// RunTask answers before the images are pulled, as AWS does. The task runs for ~2 s, so the
// TasksStopped waiter below, not TasksRunning (which fails on STOPPED), follows it from here.
assertThat(launched.get(0).lastStatus()).isIn("PROVISIONING", "PENDING");
}
@Test
@@ -226,6 +228,16 @@ class EcsOneShotTaskLifecycleTest {
assertThat(stopping.desiredStatus()).isEqualTo("STOPPED");
assertThat(stopping.stoppedReason()).isEqualTo("test-explicit-stop");
// A stop that reaches the task while it is still launching lands asynchronously.
WaiterResponse<DescribeTasksResponse> stopped = ecs.waiter().waitUntilTasksStopped(
DescribeTasksRequest.builder()
.cluster(clusterName)
.tasks(explicitTaskArn)
.build(),
TestFixtures.waiterOverride(Duration.ofSeconds(60)));
assertThat(stopped.matched().response()).isPresent();
assertThat(stopped.matched().response().get().tasks().get(0).lastStatus()).isEqualTo("STOPPED");
}
// ── Helpers ──────────────────────────────────────────────────────────────
@@ -13,6 +13,7 @@ import software.amazon.awssdk.services.ecs.EcsClient;
import software.amazon.awssdk.services.ecs.model.ContainerDefinition;
import software.amazon.awssdk.services.ecs.model.CreateClusterRequest;
import software.amazon.awssdk.services.ecs.model.DeleteClusterRequest;
import software.amazon.awssdk.services.ecs.model.DescribeTasksRequest;
import software.amazon.awssdk.services.ecs.model.ExecuteCommandRequest;
import software.amazon.awssdk.services.ecs.model.LaunchType;
import software.amazon.awssdk.services.ecs.model.LogConfiguration;
@@ -29,6 +30,7 @@ import java.net.http.WebSocket;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@@ -88,6 +90,12 @@ class EcsRunningTaskTest {
.enableExecuteCommand(true)
.count(1)
.build()).tasks().get(0).taskArn();
// RunTask answers before the images are pulled; ExecuteCommand needs the task RUNNING.
ecs.waiter().waitUntilTasksRunning(DescribeTasksRequest.builder()
.cluster(clusterName)
.tasks(taskArn)
.build(),
TestFixtures.waiterOverride(Duration.ofSeconds(60)));
}
@AfterAll
@@ -487,12 +487,18 @@ class EcsTests {
assertThat(started.get(0).taskArn()).isNotNull();
assertThat(started.get(0).containerInstanceArn()).isEqualTo(instanceArn);
// Stop the task
// Stop the task. StartTask answers before the launch, so the stop lands asynchronously;
// wait for it so the task no longer counts as running in the tests below.
if (!started.isEmpty()) {
ecs.stopTask(StopTaskRequest.builder()
.cluster(clusterName)
.task(started.get(0).taskArn())
.build());
ecs.waiter().waitUntilTasksStopped(DescribeTasksRequest.builder()
.cluster(clusterName)
.tasks(started.get(0).taskArn())
.build(),
TestFixtures.waiterOverride(Duration.ofSeconds(60)));
}
// Deregister
@@ -619,7 +625,16 @@ class EcsTests {
assertThat(task.taskArn()).isNotNull();
assertThat(task.clusterArn()).isEqualTo(cluster.clusterArn());
assertThat(task.taskDefinitionArn()).isEqualTo(taskDef.taskDefinitionArn());
assertThat(task.lastStatus()).isEqualTo("RUNNING");
// RunTask answers before the images are pulled, as AWS does; the task reaches RUNNING later.
assertThat(task.lastStatus()).isIn("PROVISIONING", "PENDING");
WaiterResponse<DescribeTasksResponse> running = ecs.waiter().waitUntilTasksRunning(
DescribeTasksRequest.builder()
.cluster(clusterName)
.tasks(task.taskArn())
.build(),
TestFixtures.waiterOverride(Duration.ofSeconds(60)));
assertThat(running.matched().response()).isPresent();
}
@Test
@@ -1127,6 +1142,15 @@ class EcsTests {
.task(taskArn)
.build());
}
// A task stopped while still launching lands STOPPED asynchronously, and a cluster with a
// task that has not stopped cannot be deleted.
if (!running.isEmpty()) {
ecs.waiter().waitUntilTasksStopped(DescribeTasksRequest.builder()
.cluster(clusterName)
.tasks(running)
.build(),
TestFixtures.waiterOverride(Duration.ofSeconds(60)));
}
Cluster deleted = ecs.deleteCluster(DeleteClusterRequest.builder()
.cluster(clusterName)
+19 -7
View File
@@ -38,8 +38,11 @@ eight documented counts split by launch type (`runningEC2TasksCount`, `runningFa
`pendingEC2TasksCount`, `pendingFargateTasksCount`, `activeEC2ServiceCount`,
`activeFargateServiceCount`, `drainingEC2ServiceCount`, `drainingFargateServiceCount`) as
name/value strings. The API reference spells one of those names `RunningFargateTasksCount`; Floci
follows the wire, which is lower camel case like the other seven. `ATTACHMENTS` is always an empty
list, because Floci creates no managed scaling policies to attach.
follows the wire, which is lower camel case like the other seven. The reference also describes
`pendingTasksCount` as tasks in the `PENDING` state, but ECS counts a task as pending from
`RunTask` until it runs, so Floci's count and the two pending statistics include a `PROVISIONING`
task too. `ATTACHMENTS` is always an empty list, because Floci creates no managed scaling policies
to attach.
`DescribeClusters` reports a cluster it cannot resolve as a `MISSING` entry in `failures` rather
than dropping it, as `DescribeServices` and `DescribeTasks` do. `ListClusters` pages with
@@ -125,9 +128,10 @@ default) keeps both. It pages with `maxResults` and `nextToken` the same way.
At launch, a container's `dependsOn` decides the start order, and a `COMPLETE`, `SUCCESS` or
`HEALTHY` condition holds the dependent container until the dependency gets there. The wait is
bounded by the dependent container's `startTimeout`, defaulting to 60 seconds rather than AWS's
longer agent default, because `RunTask` here answers synchronously. A container's `cpu` becomes its
CPU shares, its `memory` its hard limit, and a container without a `memory` of its own is capped at
the task's; the task's `cpu` becomes a CPU quota. `stopTimeout` is the grace period the container gets
longer agent default, because the service scheduler starts a service's tasks on its own thread,
which a long wait holds up. A container's `cpu` becomes its CPU shares, its `memory` its hard
limit, and a container without a `memory` of its own is capped at the task's; the task's `cpu`
becomes a CPU quota. `stopTimeout` is the grace period the container gets
on teardown; a container that does not ask for one gets 5 seconds rather than AWS's 30, because
`StopTask` here answers synchronously and most containers ignore SIGTERM as PID 1. A container
still running when its grace period is up is killed, so its exit code is always reported.
@@ -312,6 +316,14 @@ converging reports none. Each `deployments` entry carries the placement it runs
service-only option; `TASK_DEFINITION` copies the task definition's tags onto each task.
`StartTask` requires the `containerInstances` it places onto, at most 10 of them.
`RunTask` and `StartTask` answer before the task's images are pulled, as AWS does. An `awsvpc` task
comes back `PROVISIONING` with its ENI attachment `PRECREATED`, and any other task `PENDING`, each
with its containers `PENDING`. The task then moves to `RUNNING` in the background. A launch that
fails, on an image that cannot be pulled for example, shows in `DescribeTasks` as `STOPPED` with
`stopCode` `TaskFailedToStart`. A `StopTask` on a task still launching answers with the task's status
unchanged and `desiredStatus` `STOPPED`; the task then stops without its containers ever starting,
or as soon as they have.
`ListTasks` filters by `cluster`, `family`, `desiredStatus`, `launchType`, `containerInstance`,
`serviceName` and `startedBy`, and pages with `maxResults` and `nextToken` (100 per page by
default). The default filter is a desired status of `RUNNING`, so a listing that has not asked for
@@ -879,7 +891,7 @@ Every `awsvpc` task receives an ENI in its subnet. With `FLOCI_NETWORK_SECURITY_
| Variable | Default | Description |
|---|---|---|
| `FLOCI_SERVICES_ECS_ENABLED` | `true` | Enable or disable the ECS service |
| `FLOCI_SERVICES_ECS_MOCK` | `false` | Skip Docker; tasks go straight to `RUNNING` (useful for CI) |
| `FLOCI_SERVICES_ECS_MOCK` | `false` | Skip Docker; tasks reach `RUNNING` with nothing running behind them (useful for CI) |
| `FLOCI_SERVICES_ECS_DOCKER_NETWORK` | *(unset)* | Docker network for task containers |
| `FLOCI_SERVICES_ECS_DEFAULT_MEMORY_MB` | `512` | Default memory (MB) when the task definition omits it |
| `FLOCI_SERVICES_ECS_DEFAULT_CPU_UNITS` | `256` | Default CPU units when the task definition omits it |
@@ -1045,7 +1057,7 @@ Unlike [real EFS user enforcement](https://docs.aws.amazon.com/efs/latest/ug/enf
### Mock mode
Set `FLOCI_SERVICES_ECS_MOCK=true` to run without Docker. In this mode tasks skip container launch and immediately transition to `RUNNING`, then to `STOPPED` when stopped. The task still reports a container per container definition and, for `awsvpc`, a real ENI, so a client reading `containers[]` or waiting on the task's address behaves as it does against AWS; nothing is running behind those containers, so ECS Exec answers `TargetNotConnectedException` and no logs are streamed. This is the recommended mode for unit/integration tests and CI pipelines where Docker-in-Docker is unavailable.
Set `FLOCI_SERVICES_ECS_MOCK=true` to run without Docker. In this mode tasks skip container launch and reach `RUNNING` right after `RunTask` answers, then `STOPPED` when stopped. The task still reports a container per container definition and, for `awsvpc`, a real ENI, so a client reading `containers[]` or waiting on the task's address behaves as it does against AWS; nothing is running behind those containers, so ECS Exec answers `TargetNotConnectedException` and no logs are streamed. This is the recommended mode for unit/integration tests and CI pipelines where Docker-in-Docker is unavailable.
```yaml
# docker-compose.yml — CI / test environment
@@ -98,7 +98,7 @@ public class EcsResponseWriter {
n.put("status", c.getStatus());
n.put("registeredContainerInstancesCount", c.getRegisteredContainerInstancesCount());
n.put("runningTasksCount", c.getRunningTasksCount());
n.put("pendingTasksCount", c.getPendingTasksCount());
n.put("pendingTasksCount", service.pendingTasksCount(c));
n.put("activeServicesCount", c.getActiveServicesCount());
if (include.contains("SETTINGS") && c.getSettings() != null && !c.getSettings().isEmpty()) {
ArrayNode settings = objectMapper.createArrayNode();
@@ -150,9 +150,14 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
* unrelated services take turns behind one slow task.
*/
private static final int TASK_STOP_CONCURRENCY = 8;
/** How long a container teardown waits for the launches it interrupted to land their tasks. */
private static final long LAUNCHER_SHUTDOWN_SECONDS = 30;
// Runs the service scheduler's Docker stops (see stopInBackground). A container teardown drains
// and shuts it down, and afterReset() replaces it, as with the reconciler.
private volatile ExecutorService taskStopper = newTaskStopper();
// Runs RunTask's and StartTask's launches after the call has answered. A container teardown
// interrupts and shuts it down, and afterReset() replaces it, as with the task stopper.
private volatile ExecutorService taskLauncher = newTaskLauncher();
private final Object reconcilerLock = new Object();
private final Object reconciliationPassLock = new Object();
// False until a previous run's task containers are confirmed gone; no task starts before.
@@ -231,10 +236,15 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
public static final String STATUS_ACTIVE = "ACTIVE";
public static final String STATUS_INACTIVE = "INACTIVE";
public static final String STATUS_DELETE_IN_PROGRESS = "DELETE_IN_PROGRESS";
private static final String ATTACHMENT_STATUS_PRECREATED = "PRECREATED";
private static final String ATTACHMENT_STATUS_ATTACHED = "ATTACHED";
/** The attribute every task carries, naming the architecture it actually runs on. */
private static final String CPU_ARCHITECTURE_ATTRIBUTE = "ecs.cpu-architecture";
/** The two built-in capacity providers, which place Fargate tasks rather than EC2 ones. */
private static final Set<String> FARGATE_CAPACITY_PROVIDERS = Set.of("FARGATE", "FARGATE_SPOT");
private static final Set<String> RUNNING_TASK_STATUSES = Set.of("RUNNING");
/** ECS counts a task as pending from RunTask until it runs, through PROVISIONING and PENDING. */
private static final Set<String> PENDING_TASK_STATUSES = Set.of("PROVISIONING", "PENDING");
/** The bounds the ECS model puts on a capacity provider strategy and on its entries. */
private static final int MAX_CAPACITY_PROVIDERS_PER_STRATEGY = 20;
private static final int MAX_CAPACITY_PROVIDER_WEIGHT = 1000;
@@ -378,6 +388,10 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
return stopper;
}
private static ExecutorService newTaskLauncher() {
return Executors.newThreadPerTaskExecutor(Thread.ofVirtual().name("ecs-task-launcher-", 0).factory());
}
void initializeStorage() {
if (storageFactory == null) {
return; // keeps non-CDI unit tests working
@@ -438,9 +452,10 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
* state reset. Task state is transient (memory-only), so without this the containers
* outlive the process as orphans. The reconciler is shut down first, and any in-flight
* tick awaited, so it cannot restart drained tasks between this teardown and the final
* storage flush. A reset brings it back in {@link #afterReset()}. The stops the task stopper
* already has are let finish, since each owns its task's handle until it lands. The remaining
* handles are claimed atomically to avoid racing an explicit StopTask.
* storage flush. A reset brings it back in {@link #afterReset()}. The task launcher is then
* interrupted and its launches awaited, so each lands its task before the sweep below. The
* stops the task stopper already has are let finish, since each owns its task's handle until
* it lands. The remaining handles are claimed atomically to avoid racing an explicit StopTask.
*/
@Override
public void stopManagedContainers() {
@@ -451,6 +466,17 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
// An interrupted launch fails into its own catch block, which lands the task STOPPED and
// keeps a partial launch's handle, so the sweep below claims what it started.
ExecutorService launcher = taskLauncher;
launcher.shutdownNow();
try {
if (!launcher.awaitTermination(LAUNCHER_SHUTDOWN_SECONDS, TimeUnit.SECONDS)) {
LOG.warnv("ECS task launches still running after {0} seconds of teardown", LAUNCHER_SHUTDOWN_SECONDS);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
drainTaskStopper();
for (String taskArn : new ArrayList<>(taskHandles.keySet())) {
if (taskStops.containsKey(taskArn)) {
@@ -515,15 +541,18 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
/**
* Runs at the end of every state reset, never on shutdown. The reset's teardown stopped the
* reconciler and the task stopper, so without new ones no service would be reconciled again,
* nor any of its tasks stopped, until the emulator restarted. This hook rather than
* {@code clear()} because the controller runs it even when the storage wipe or another
* service's {@code clear()} threw, and a failed reset must not leave ECS without a reconciler
* for good. The stopper comes back first, so the new reconciler's first tick has one.
* reconciler, the task launcher and the task stopper, so without new ones no service would be
* reconciled again, nor any task launched or stopped, until the emulator restarted. This hook
* rather than {@code clear()} because the controller runs it even when the storage wipe or
* another service's {@code clear()} threw, and a failed reset must not leave ECS without a
* reconciler for good. The stopper comes back first, so the new reconciler's first tick has one.
*/
@Override
public void afterReset() {
synchronized (reconcilerLock) {
if (taskLauncher.isShutdown()) {
taskLauncher = newTaskLauncher();
}
if (taskStopper.isShutdown()) {
taskStopper = newTaskStopper();
}
@@ -800,10 +829,10 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
.filter(s -> clusterArn.equals(s.getClusterArn()))
.toList();
return List.of(
statistic("runningEC2TasksCount", countTasks(clusterTasks, "RUNNING", LaunchType.EC2)),
statistic("runningFargateTasksCount", countTasks(clusterTasks, "RUNNING", LaunchType.FARGATE)),
statistic("pendingEC2TasksCount", countTasks(clusterTasks, "PENDING", LaunchType.EC2)),
statistic("pendingFargateTasksCount", countTasks(clusterTasks, "PENDING", LaunchType.FARGATE)),
statistic("runningEC2TasksCount", countTasks(clusterTasks, RUNNING_TASK_STATUSES, LaunchType.EC2)),
statistic("runningFargateTasksCount", countTasks(clusterTasks, RUNNING_TASK_STATUSES, LaunchType.FARGATE)),
statistic("pendingEC2TasksCount", countTasks(clusterTasks, PENDING_TASK_STATUSES, LaunchType.EC2)),
statistic("pendingFargateTasksCount", countTasks(clusterTasks, PENDING_TASK_STATUSES, LaunchType.FARGATE)),
statistic("activeEC2ServiceCount", countServices(clusterServices, STATUS_ACTIVE, LaunchType.EC2)),
statistic("activeFargateServiceCount", countServices(clusterServices, STATUS_ACTIVE, LaunchType.FARGATE)),
statistic("drainingEC2ServiceCount", countServices(clusterServices, "DRAINING", LaunchType.EC2)),
@@ -814,9 +843,18 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
return new KeyValuePair(name, String.valueOf(value));
}
private static long countTasks(List<EcsTask> clusterTasks, String status, LaunchType launchType) {
/** DescribeClusters' pendingTasksCount: like ECS, a task still launching counts as pending. */
public long pendingTasksCount(EcsCluster cluster) {
String clusterArn = cluster.getClusterArn();
return tasks.values().stream()
.filter(t -> clusterArn.equals(t.getClusterArn()))
.filter(t -> PENDING_TASK_STATUSES.contains(t.getLastStatus()))
.count();
}
private static long countTasks(List<EcsTask> clusterTasks, Set<String> statuses, LaunchType launchType) {
return clusterTasks.stream()
.filter(t -> status.equals(t.getLastStatus()))
.filter(t -> statuses.contains(t.getLastStatus()))
.filter(t -> launchType == effectiveLaunchType(t.getLaunchType()))
.count();
}
@@ -1616,12 +1654,16 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
task.setGroup(request.getGroup() != null ? request.getGroup() : "family:" + taskDef.getFamily());
task.setStartedBy(request.getStartedBy());
task.setOwningServiceArn(owningServiceArn);
task.setLastStatus(TaskStatus.PENDING.name());
// AWS answers an awsvpc task PROVISIONING, its ENI PRECREATED, until the ENI is attached.
boolean awsvpc = taskDef.getNetworkMode() == NetworkMode.awsvpc;
task.setLastStatus(awsvpc ? TaskStatus.PROVISIONING.name() : TaskStatus.PENDING.name());
if (awsvpc) {
task.setAttachmentStatus(ATTACHMENT_STATUS_PRECREATED);
}
task.setDesiredStatus(TaskStatus.RUNNING.name());
task.setCpu(effectiveCpu(taskDef, request));
task.setMemory(effectiveMemory(taskDef, request));
task.setCreatedAt(Instant.now());
task.setContainers(List.of());
task.setContainerInstanceArn(containerInstanceArn);
task.setNetworkConfiguration(networkConfiguration);
task.setOverrides(request.getOverrides());
@@ -1638,61 +1680,45 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
// subnet, say) never existed, the way AWS rejects the request rather than placing it.
containerManager.attachTaskNetwork(task, taskDef, region);
task.setContainers(mockContainers(task, taskDef, region, TaskStatus.PENDING));
if (owningServiceArn != null) {
// The service scheduler counts only RUNNING tasks, so its launch stays inline.
tasks.put(taskArn, task);
launchTask(cluster, task, taskDef, containerOverrides, region);
launched.add(task);
continue;
}
// Taken before the task is visible, with containers of its own, so the response shows
// the task as the call left it whatever the launch does meanwhile.
EcsTask response = new EcsTask(task);
response.setContainers(mockContainers(task, taskDef, region, TaskStatus.PENDING));
tasks.put(taskArn, task);
submitLaunch(cluster, task, taskDef, containerOverrides, region);
launched.add(response);
}
return launched;
}
if (dockerMode) {
try {
if (!leftoverContainersCleared()) {
throw new IllegalStateException(
"the containers a previous run of Floci left on the Docker daemon could not be removed yet");
}
task.setPullStartedAt(Instant.now());
EcsTaskHandle handle = containerManager.startTask(task, taskDef, containerOverrides, region);
task.setPullStoppedAt(Instant.now());
boolean stopRequested;
synchronized (task) {
taskHandles.put(taskArn, handle);
markTaskRunning(task);
adjustRunningTasksCount(cluster, 1);
LOG.infov("Started ECS task (docker): {0}", taskArn);
stopRequested = TaskStatus.STOPPED.name().equals(task.getDesiredStatus());
if (!stopRequested) {
registerTaskWithLoadBalancers(task, cluster, region);
registerTaskForServiceDiscovery(task, cluster, region);
evictStaleRegistrationsAt(task, 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) {
if (e instanceof EcsTaskLaunchException failedLaunch) {
retainPendingCleanupHandle(taskArn, failedLaunch.getHandle());
}
LOG.errorv("Failed to start ECS task {0}: {1}", taskArn, e.getMessage());
task.setLastStatus(TaskStatus.STOPPED.name());
task.setDesiredStatus(TaskStatus.STOPPED.name());
// A ResourceInitializationError is already AWS's exact stopped-reason wording
// (e.g. a secret that could not be resolved), so pass it through verbatim.
// Other start failures keep the generic prefix.
boolean resourceInitError = e instanceof AwsException ae
&& "ResourceInitializationError".equals(ae.getErrorCode());
task.setStoppedReason(resourceInitError
? e.getMessage()
: "Failed to start: " + e.getMessage());
task.setStopCode(STOP_CODE_TASK_FAILED_TO_START);
task.setStoppedAt(Instant.now());
task.bumpVersion();
containerManager.releaseTaskNetwork(task, region);
if (eventPublisher != null) {
eventPublisher.emitTaskLadder(task, TaskStatus.PENDING, TaskStatus.STOPPED, region);
}
}
} else {
task.setContainers(mockContainers(task, taskDef, region));
/**
* Pulls and starts a task's containers, or in mock mode just marks it RUNNING. RunTask and
* StartTask run this on the task launcher once they have answered; the service scheduler runs
* it inline. A StopTask that came first lands the task STOPPED without starting anything.
*/
private void launchTask(EcsCluster cluster, EcsTask task, TaskDefinition taskDef,
List<ContainerOverride> containerOverrides, String region) {
String taskArn = task.getTaskArn();
synchronized (task) {
if (TaskStatus.STOPPED.name().equals(task.getDesiredStatus())) {
landUnstartedTask(task, region);
return;
}
if (TaskStatus.PROVISIONING.name().equals(task.getLastStatus())) {
task.setLastStatus(TaskStatus.PENDING.name());
task.setAttachmentStatus(ATTACHMENT_STATUS_ATTACHED);
task.bumpVersion();
}
if (!dockerMode) {
task.setContainers(mockContainers(task, taskDef, region, TaskStatus.RUNNING));
markTaskRunning(task);
adjustRunningTasksCount(cluster, 1);
LOG.infov("Started ECS task (mock): {0}", taskArn);
@@ -1700,19 +1726,118 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
eventPublisher.emitTaskLadder(task, TaskStatus.PENDING, TaskStatus.RUNNING, region);
}
}
launched.add(task);
}
if (dockerMode) {
try {
if (!leftoverContainersCleared()) {
throw new IllegalStateException(
"the containers a previous run of Floci left on the Docker daemon could not be removed yet");
}
task.setPullStartedAt(Instant.now());
EcsTaskHandle handle = containerManager.startTask(task, taskDef, containerOverrides, region);
task.setPullStoppedAt(Instant.now());
boolean stopRequested;
synchronized (task) {
taskHandles.put(taskArn, handle);
markTaskRunning(task);
adjustRunningTasksCount(cluster, 1);
LOG.infov("Started ECS task (docker): {0}", taskArn);
stopRequested = TaskStatus.STOPPED.name().equals(task.getDesiredStatus());
if (!stopRequested) {
registerTaskWithLoadBalancers(task, cluster, region);
registerTaskForServiceDiscovery(task, cluster, region);
evictStaleRegistrationsAt(task, 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) {
if (e instanceof EcsTaskLaunchException failedLaunch) {
retainPendingCleanupHandle(taskArn, failedLaunch.getHandle());
}
LOG.errorv("Failed to start ECS task {0}: {1}", taskArn, e.getMessage());
// A ResourceInitializationError is already AWS's exact stopped-reason wording
// (e.g. a secret that could not be resolved), so pass it through verbatim.
// Other start failures keep the generic prefix.
boolean resourceInitError = e instanceof AwsException ae
&& "ResourceInitializationError".equals(ae.getErrorCode());
failLaunch(task, resourceInitError ? e.getMessage() : "Failed to start: " + e.getMessage(), region);
// It never counted as running, so the cluster has nothing new to persist.
return;
}
}
persistCluster(region, cluster);
return launched;
}
private void failLaunch(EcsTask task, String reason, String region) {
synchronized (task) {
// A StopTask that came first keeps its own reason and UserInitiated code.
if (!TaskStatus.STOPPED.name().equals(task.getDesiredStatus())) {
task.setStoppedReason(reason);
task.setStopCode(STOP_CODE_TASK_FAILED_TO_START);
}
landUnstartedTask(task, region);
}
}
/**
* The container models a mock-mode task reports. Nothing is running behind them, so they carry
* no runtime id, but a task with an empty {@code containers} list is unlike anything AWS
* returns and breaks every client that reads the list.
* Lands a task that never started: STOPPED with its containers, its ENI released. It never
* counted as running, so the cluster's count stays as it is. Called holding the task's monitor.
*/
private List<Container> mockContainers(EcsTask task, TaskDefinition taskDef, String region) {
private void landUnstartedTask(EcsTask task, String region) {
Instant now = Instant.now();
task.setLastStatus(TaskStatus.STOPPED.name());
task.setDesiredStatus(TaskStatus.STOPPED.name());
if (task.getStoppingAt() == null) {
task.setStoppingAt(now);
}
task.setStoppedAt(now);
task.setExecutionStoppedAt(now);
if (task.getContainers() != null) {
task.getContainers().forEach(container -> container.setLastStatus(TaskStatus.STOPPED.name()));
}
task.bumpVersion();
containerManager.releaseTaskNetwork(task, region);
if (eventPublisher != null) {
eventPublisher.emitTaskLadder(task, TaskStatus.PENDING, TaskStatus.STOPPED, region);
}
}
/**
* Hands a RunTask or StartTask launch to the task launcher, so the call answers before the
* images are pulled, as AWS does. A launcher thread has no request context, and account-aware
* storage reads the account from it.
*/
private void submitLaunch(EcsCluster cluster, EcsTask task, TaskDefinition taskDef,
List<ContainerOverride> containerOverrides, String region) {
String accountId = taskAccountId(task.getTaskArn());
try {
taskLauncher.execute(() -> {
try {
RequestScopes.runAs(accountId, () -> launchTask(cluster, task, taskDef, containerOverrides, region));
} catch (RuntimeException e) {
LOG.warnv(e, "Could not launch ECS task {0}: {1}", task.getTaskArn(), e.getMessage());
}
});
} catch (RejectedExecutionException e) {
// Only while a container teardown has the launcher shut down: fail the launch rather
// than leave the task waiting for a launch that never comes.
failLaunch(task, "Failed to start: the ECS task launcher is shut down", region);
}
}
/**
* The container models a task reports before Docker has started any, and a mock-mode task's
* for its whole life. Nothing is running behind them, so they carry no runtime id, but a task
* with an empty {@code containers} list is unlike anything AWS returns and breaks every client
* that reads the list.
*/
private List<Container> mockContainers(EcsTask task, TaskDefinition taskDef, String region,
TaskStatus status) {
String taskId = task.getTaskArn().substring(task.getTaskArn().lastIndexOf('/') + 1);
List<Container> containers = new ArrayList<>();
for (ContainerDefinition def : taskDef.getContainerDefinitions()) {
@@ -1720,7 +1845,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
container.setTaskArn(task.getTaskArn());
container.setName(def.getName());
container.setImage(def.getImage());
container.setLastStatus(TaskStatus.RUNNING.name());
container.setLastStatus(status.name());
container.setContainerArn(regionResolver.buildArn("ecs", region,
"container/" + taskId + "/" + def.getName()));
container.setNetworkBindings(List.of());
@@ -1730,12 +1855,17 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
if (def.getMemory() != null) {
container.setMemory(String.valueOf(def.getMemory()));
}
if (def.getMemoryReservation() != null) {
container.setMemoryReservation(String.valueOf(def.getMemoryReservation()));
}
if (task.getNetworkInterfaceId() != null) {
container.setNetworkInterfaces(List.of(new TaskNetworkInterface(
task.getAttachmentId(), task.getPrivateIpAddress(), null)));
}
if (task.isEnableExecuteCommand()) {
container.setManagedAgents(List.of(ManagedAgent.executeCommandAgent(Instant.now())));
container.setManagedAgents(List.of(status == TaskStatus.RUNNING
? ManagedAgent.executeCommandAgent(Instant.now())
: new ManagedAgent(ManagedAgent.EXECUTE_COMMAND_AGENT, ManagedAgent.PENDING, null, null)));
}
containers.add(container);
}
@@ -2114,6 +2244,17 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
if (TaskStatus.STOPPED.name().equals(task.getLastStatus())) {
return task;
}
if (TaskStatus.PROVISIONING.name().equals(task.getLastStatus())
|| TaskStatus.PENDING.name().equals(task.getLastStatus())) {
// Still launching. AWS answers with the stop recorded and the task where it was; the
// launch lands it, before starting anything or, once Docker has started it, by stopping it.
task.setDesiredStatus(TaskStatus.STOPPED.name());
task.setStoppingAt(Instant.now());
task.setStoppedReason(reason != null ? reason : "Stopped by user");
task.setStopCode(stopCode);
task.bumpVersion();
return task;
}
if (!TaskStatus.STOPPING.name().equals(task.getLastStatus())) {
task.setDesiredStatus(TaskStatus.STOPPED.name());
task.setLastStatus(TaskStatus.STOPPING.name());
@@ -651,9 +651,6 @@ public class EcsContainerManager {
containersInDefinitionOrder.forEach(container -> container.setManagedAgents(agents));
}
task.setContainers(containersInDefinitionOrder);
task.setLastStatus(TaskStatus.RUNNING.name());
task.setDesiredStatus(TaskStatus.RUNNING.name());
task.setStartedAt(Instant.now());
return new EcsTaskHandle(task.getTaskArn(), containerIds, logStreamsByContainerId,
firelensVolumeName,
@@ -739,8 +736,8 @@ public class EcsContainerManager {
*
* <p>The wait is bounded by the dependent container's {@code startTimeout}, defaulting to
* {@value #DEPENDENCY_WAIT_SECONDS} seconds rather than AWS's longer agent default, because
* RunTask here is synchronous and a caller is holding the request open. A dependency that does
* not get there in time fails the task.
* the service scheduler starts a service's tasks on its own thread, which a long wait holds up.
* A dependency that does not get there in time fails the task.
*/
private void awaitDependencies(ContainerDefinition definition, Map<String, String> startedContainerIds) {
if (definition.getDependsOn() == null || definition.getDependsOn().isEmpty()) {
@@ -2486,7 +2483,4 @@ public class EcsContainerManager {
hostVolumePolicy.validate(hostPath, HostVolumePolicy.DEVICE_HOST_PATH);
}
}
// Inner enum to avoid import cycle — mirrors model.TaskStatus for readability
private enum TaskStatus {RUNNING}
}
@@ -72,10 +72,9 @@ public class EcsTask {
}
/**
* Shallow copy, used to synthesize a phase ladder of lifecycle events without mutating the
* shared task instance held in the live task map — that instance stays visible to concurrent
* DescribeTasks/ListTasks calls for the whole synthesis, so events must be built from a
* snapshot instead of toggling {@link #lastStatus} back and forth on the original.
* Shallow copy, used where a task must be shown as it was at one moment without mutating the
* shared task instance held in the live task map: the phases of a lifecycle event ladder, and
* the RunTask response, which the launch would otherwise move on while it is written.
*/
public EcsTask(EcsTask other) {
this.taskArn = other.taskArn;
@@ -15,6 +15,7 @@ import java.time.Instant;
public record ManagedAgent(String name, String lastStatus, String reason, Instant lastStartedAt) {
public static final String EXECUTE_COMMAND_AGENT = "ExecuteCommandAgent";
public static final String PENDING = "PENDING";
public static final String RUNNING = "RUNNING";
public static final String STOPPED = "STOPPED";
@@ -22,11 +22,13 @@ import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import static io.floci.aws.testing.EcsTaskWaits.awaitLastStatus;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -87,7 +89,10 @@ class EcsAwsvpcTaskAddressDockerIntegrationTest {
String network = null;
String probe = null;
try {
EcsTask described = ecsService.describeTasks(clusterName, List.of(task.getTaskArn()), REGION).getFirst();
String taskArn = task.getTaskArn();
EcsTask described = awaitLastStatus(
() -> ecsService.describeTasks(clusterName, List.of(taskArn), REGION).getFirst(),
EcsTask::getLastStatus, Duration.ofMinutes(2), "RUNNING", "STOPPED");
assertEquals("RUNNING", described.getLastStatus(), "the task must start: " + described.getStoppedReason());
String address = described.getPrivateIpAddress();
assertNotNull(address, "an awsvpc task must report its ENI address");
@@ -0,0 +1,78 @@
package io.floci.aws.services.ecs;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.services.ecs.container.EcsContainerManager;
import io.floci.aws.services.ecs.container.EcsTaskHandle;
import io.floci.aws.services.ecs.model.ContainerDefinition;
import io.floci.aws.services.ecs.model.EcsTask;
import io.floci.aws.services.ecs.model.LaunchType;
import io.quarkus.test.InjectMock;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
import static io.floci.aws.testing.EcsTaskWaits.awaitLastStatus;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
/**
* RunTask's launch runs on the task launcher's own threads, which have no request context, and
* account-aware storage reads the account from that context. Only a running Arc container has one,
* so this runs in Quarkus, in Docker mode over a container manager that starts nothing for real.
*/
@QuarkusTest
@TestProfile(EcsBackgroundTaskStopIntegrationTest.DockerModeProfile.class)
class EcsBackgroundTaskLaunchIntegrationTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "111122223333";
@Inject
EcsService ecsService;
@Inject
RegionResolver regionResolver;
@InjectMock
EcsContainerManager containerManager;
@Test
void aTaskLaunchedInTheBackgroundLandsInItsOwnAccount() {
AtomicReference<String> startedAs = new AtomicReference<>();
when(containerManager.getExitCodeIfStopped(anyString())).thenReturn(null);
when(containerManager.startTask(any(), any(), any(), anyString())).thenAnswer(invocation -> {
startedAs.set(regionResolver.getAccountId());
EcsTask task = invocation.getArgument(0);
return new EcsTaskHandle(task.getTaskArn(), Map.of(), Map.of());
});
String cluster = "launcher-" + UUID.randomUUID().toString().substring(0, 8);
RequestScopes.runAs(ACCOUNT, () -> {
ecsService.createCluster(cluster, REGION);
ContainerDefinition app = new ContainerDefinition();
app.setName("app");
app.setImage("app:1");
ecsService.registerTaskDefinition(cluster, List.of(app), null, null, null,
null, null, List.of(), REGION);
});
String taskArn = RequestScopes.callAs(ACCOUNT, () -> ecsService.runTask(cluster, cluster, 1,
LaunchType.FARGATE, null, null, List.of(), null, REGION).getFirst().getTaskArn());
awaitLastStatus(() -> RequestScopes.callAs(ACCOUNT, () ->
ecsService.describeTasks(cluster, List.of(taskArn), REGION).getFirst()),
EcsTask::getLastStatus, Duration.ofSeconds(10), "RUNNING");
assertEquals(ACCOUNT, startedAs.get(), "the launch must start the task in its own account");
assertEquals(1, RequestScopes.callAs(ACCOUNT, () ->
ecsService.describeClusters(List.of(cluster), REGION).getFirst().getRunningTasksCount()));
}
}
@@ -12,9 +12,11 @@ import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ecs.EcsClient;
import software.amazon.awssdk.services.ecs.model.ListContainerInstancesRequest;
import java.time.Duration;
import java.util.List;
import java.util.Set;
import static io.floci.aws.testing.EcsTaskWaits.awaitLastStatus;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
@@ -88,8 +90,11 @@ class EcsContainerInstanceFilterIntegrationTest {
Response started = call("StartTask", "{\"cluster\":\"" + cluster + "\","
+ "\"containerInstances\":[\"" + excluded + "\"],"
+ "\"taskDefinition\":\"query-filter-task\"}");
started.then().body("tasks[0].lastStatus", equalTo("RUNNING"));
String task = started.jsonPath().getString("tasks[0].taskArn");
awaitLastStatus(
() -> call("DescribeTasks", "{\"cluster\":\"" + cluster + "\",\"tasks\":[\"" + task + "\"]}"),
r -> r.jsonPath().getString("tasks[0].lastStatus"), Duration.ofSeconds(10), "RUNNING")
.then().body("tasks[0].lastStatus", equalTo("RUNNING"));
call("DescribeContainerInstances", "{\"cluster\":\"" + cluster
+ "\",\"containerInstances\":[\"" + excluded + "\"]}")
.then().body("containerInstances[0].runningTasksCount", equalTo(1));
@@ -11,8 +11,10 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.net.URI;
import java.time.Duration;
import java.util.List;
import static io.floci.aws.testing.EcsTaskWaits.awaitLastStatus;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
@@ -59,10 +61,15 @@ class EcsExecuteCommandIntegrationTest {
+ "\"requiresCompatibilities\":[\"FARGATE\"],\"networkMode\":\"awsvpc\","
+ "\"cpu\":\"256\",\"memory\":\"512\",\"containerDefinitions\":"
+ "[{\"name\":\"app\",\"image\":\"nginx:latest\"}]}", 200);
return call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family
String taskArn = call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family
+ "\",\"launchType\":\"FARGATE\"," + NETWORK + ",\"enableExecuteCommand\":"
+ enableExecuteCommand + "}", 200)
.jsonPath().getString("tasks[0].taskArn");
// RunTask answers before the launch; the task reaches RUNNING in the background.
awaitLastStatus(
() -> call("DescribeTasks", "{\"cluster\":\"" + CLUSTER + "\",\"tasks\":[\"" + taskArn + "\"]}", 200),
r -> r.jsonPath().getString("tasks[0].lastStatus"), Duration.ofSeconds(10), "RUNNING");
return taskArn;
}
@ParameterizedTest
@@ -10,6 +10,7 @@ import java.time.Duration;
import java.util.List;
import java.util.Map;
import static io.floci.aws.testing.EcsTaskWaits.awaitLastStatus;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.containsString;
@@ -556,6 +557,9 @@ class EcsFargateEdgeCaseIntegrationTest {
String taskArn = call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\""
+ family + "\",\"launchType\":\"FARGATE\"," + NETWORK + "}", 200)
.jsonPath().getString("tasks[0].taskArn");
awaitLastStatus(
() -> call("DescribeTasks", "{\"cluster\":\"" + CLUSTER + "\",\"tasks\":[\"" + taskArn + "\"]}", 200),
r -> r.jsonPath().getString("tasks[0].lastStatus"), Duration.ofSeconds(10), "RUNNING");
Response stopped = call("StopTask", "{\"cluster\":\"" + CLUSTER + "\",\"task\":\""
+ taskArn + "\",\"reason\":\"edge\"}", 200);
@@ -1014,8 +1018,12 @@ class EcsFargateEdgeCaseIntegrationTest {
String cluster = "edge-stats-cluster";
call("CreateCluster", "{\"clusterName\":\"" + cluster + "\"}", 200);
registerSize("edge-stats", "256", "512", 200);
call("RunTask", "{\"cluster\":\"" + cluster + "\",\"taskDefinition\":\"edge-stats\","
+ "\"launchType\":\"FARGATE\"," + NETWORK + "}", 200);
String taskArn = call("RunTask", "{\"cluster\":\"" + cluster + "\",\"taskDefinition\":\"edge-stats\","
+ "\"launchType\":\"FARGATE\"," + NETWORK + "}", 200)
.jsonPath().getString("tasks[0].taskArn");
awaitLastStatus(
() -> call("DescribeTasks", "{\"cluster\":\"" + cluster + "\",\"tasks\":[\"" + taskArn + "\"]}", 200),
r -> r.jsonPath().getString("tasks[0].lastStatus"), Duration.ofSeconds(10), "RUNNING");
List<Map<String, String>> statistics = call("DescribeClusters",
"{\"clusters\":[\"" + cluster + "\"],\"include\":[\"STATISTICS\"]}", 200)
@@ -7,8 +7,10 @@ import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.List;
import static io.floci.aws.testing.EcsTaskWaits.awaitLastStatus;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
@@ -63,10 +65,16 @@ class EcsFargateTaskIntegrationTest {
+ "\"launchType\":\"FARGATE\"," + NETWORK + extraMembers + "}", 200);
}
private static Response describe(String taskArn) {
return call("DescribeTasks", "{\"cluster\":\"" + CLUSTER + "\",\"tasks\":[\"" + taskArn + "\"]}", 200);
}
@Test
void runTaskReportsThePlatformAndConnectivityMembersOfAFargateTask() {
String family = seed("fargate-task-platform");
Response response = runTask(family, "");
String taskArn = runTask(family, "").jsonPath().getString("tasks[0].taskArn");
Response response = awaitLastStatus(() -> describe(taskArn),
r -> r.jsonPath().getString("tasks[0].lastStatus"), Duration.ofSeconds(10), "RUNNING");
response.then()
.body("tasks", hasSize(1))
@@ -89,7 +97,9 @@ class EcsFargateTaskIntegrationTest {
@Test
void runTaskGivesAnAwsvpcTaskItsOwnEni() {
String family = seed("fargate-task-eni");
Response response = runTask(family, "");
String taskArn = runTask(family, "").jsonPath().getString("tasks[0].taskArn");
Response response = awaitLastStatus(() -> describe(taskArn),
r -> r.jsonPath().getString("tasks[0].lastStatus"), Duration.ofSeconds(10), "RUNNING");
// The ENI is what a client waits on to find a Fargate task's address, so it is reported
// whether or not security-group enforcement is on and whether or not Docker is in play.
@@ -121,7 +131,6 @@ class EcsFargateTaskIntegrationTest {
// task has none in the account.
.body(not(containsString("<attachment>")));
String taskArn = response.jsonPath().getString("tasks[0].taskArn");
call("StopTask", "{\"cluster\":\"" + CLUSTER + "\",\"task\":\"" + taskArn + "\"}", 200)
.then().body("task.attachments[0].status", equalTo("DELETED"));
@@ -189,8 +198,9 @@ class EcsFargateTaskIntegrationTest {
@Test
void stopTaskReportsTheStopCodeAndAdvancesTheVersion() {
String family = seed("fargate-task-stop");
Response launched = runTask(family, "");
String taskArn = launched.jsonPath().getString("tasks[0].taskArn");
String taskArn = runTask(family, "").jsonPath().getString("tasks[0].taskArn");
Response launched = awaitLastStatus(() -> describe(taskArn),
r -> r.jsonPath().getString("tasks[0].lastStatus"), Duration.ofSeconds(10), "RUNNING");
long versionWhenRunning = launched.jsonPath().getLong("tasks[0].version");
call("StopTask", "{\"cluster\":\"" + CLUSTER + "\",\"task\":\"" + taskArn
@@ -14,9 +14,11 @@ import io.floci.aws.services.ecs.model.TaskDefinition;
import io.floci.aws.services.ecs.model.TaskStatus;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import static io.floci.aws.testing.EcsTaskWaits.awaitLastStatus;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -119,7 +121,11 @@ class EcsFirelensS3ConfigTest {
List<EcsTask> tasks = service.runTask("test-cluster", "ec2-s3", 1,
LaunchType.EC2, null, null, List.of(), null, "us-east-1");
EcsTask task = tasks.getFirst();
// RunTask answers before the launch; the failure lands on the task in the background.
String taskArn = tasks.getFirst().getTaskArn();
EcsTask task = awaitLastStatus(
() -> service.describeTasks("test-cluster", List.of(taskArn), "us-east-1").getFirst(),
EcsTask::getLastStatus, Duration.ofSeconds(5), "STOPPED");
assertEquals(TaskStatus.STOPPED.name(), task.getLastStatus());
assertEquals("Unable to download firelens s3 config file: unable to download s3 config "
+ "extra.conf from bucket firelens-configs: The specified key does not exist.",
@@ -30,6 +30,7 @@ import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -37,6 +38,7 @@ import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static io.floci.aws.testing.EcsTaskWaits.awaitLastStatus;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
@@ -145,7 +147,10 @@ class EcsImagePullDockerIntegrationTest {
EcsTask task = ecsService.runTask(clusterName, taskDef.getTaskDefinitionArn(), 1,
null, null, null, null, null, REGION).getFirst();
taskArns.add(task.getTaskArn());
EcsTask described = ecsService.describeTasks(clusterName, List.of(task.getTaskArn()), REGION).getFirst();
// RunTask answers before the launch; wait for it to land the task RUNNING or STOPPED.
EcsTask described = awaitLastStatus(
() -> ecsService.describeTasks(clusterName, List.of(task.getTaskArn()), REGION).getFirst(),
EcsTask::getLastStatus, Duration.ofMinutes(2), "RUNNING", "STOPPED");
assertEquals("RUNNING", described.getLastStatus(), "the container must be up: " + described.getStoppedReason());
return described;
}
@@ -19,11 +19,13 @@ import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.floci.aws.testing.EcsTaskWaits.awaitLastStatus;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -77,8 +79,12 @@ class EcsLeftoverContainersDockerIntegrationTest {
String foreignId = null;
String previousRunId = null;
try {
String taskContainerId = task.getContainers().getFirst().getDockerId();
assertNotNull(taskContainerId, "the task must have started a container: " + task.getStoppedReason());
// RunTask answers before the launch; wait for it to land the task RUNNING or STOPPED.
EcsTask launched = awaitLastStatus(
() -> ecsService.describeTasks(clusterName, List.of(task.getTaskArn()), REGION).getFirst(),
EcsTask::getLastStatus, Duration.ofMinutes(2), "RUNNING", "STOPPED");
String taskContainerId = launched.getContainers().getFirst().getDockerId();
assertNotNull(taskContainerId, "the task must have started a container: " + launched.getStoppedReason());
assertEquals(ContainerStorageHelper.ownerIdentity(config), labels(taskContainerId)
.get(ContainerStorageHelper.OWNER_LABEL), "a task container must carry its owner");
@@ -20,11 +20,13 @@ import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.floci.aws.testing.EcsTaskWaits.awaitLastStatus;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -119,7 +121,9 @@ class EcsLinuxParametersDockerIntegrationTest {
EcsTask task = ecsService.runTask(clusterName, taskDefinitionArn, 1,
null, null, null, null, null, REGION).getFirst();
taskArn = task.getTaskArn();
EcsTask described = ecsService.describeTasks(clusterName, List.of(taskArn), REGION).getFirst();
EcsTask described = awaitLastStatus(
() -> ecsService.describeTasks(clusterName, List.of(taskArn), REGION).getFirst(),
EcsTask::getLastStatus, Duration.ofMinutes(2), "RUNNING", "STOPPED");
assertEquals("RUNNING", described.getLastStatus(), "the container must be up: " + described.getStoppedReason());
String containerId = described.getContainers().getFirst().getRuntimeId();
@@ -166,7 +170,9 @@ class EcsLinuxParametersDockerIntegrationTest {
EcsTask task = ecsService.runTask(clusterName, taskDefinitionArn, 1,
null, null, null, null, null, REGION).getFirst();
taskArn = task.getTaskArn();
EcsTask described = ecsService.describeTasks(clusterName, List.of(taskArn), REGION).getFirst();
EcsTask described = awaitLastStatus(
() -> ecsService.describeTasks(clusterName, List.of(taskArn), REGION).getFirst(),
EcsTask::getLastStatus, Duration.ofMinutes(2), "RUNNING", "STOPPED");
assertEquals("RUNNING", described.getLastStatus(), "the container must be up: " + described.getStoppedReason());
String containerId = described.getContainers().getFirst().getRuntimeId();
@@ -0,0 +1,424 @@
package io.floci.aws.services.ecs;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.services.ecs.container.EcsContainerManager;
import io.floci.aws.services.ecs.container.EcsTaskHandle;
import io.floci.aws.services.ecs.model.AwsVpcConfiguration;
import io.floci.aws.services.ecs.model.Container;
import io.floci.aws.services.ecs.model.ContainerDefinition;
import io.floci.aws.services.ecs.model.EcsCluster;
import io.floci.aws.services.ecs.model.EcsTask;
import io.floci.aws.services.ecs.model.LaunchType;
import io.floci.aws.services.ecs.model.ManagedAgent;
import io.floci.aws.services.ecs.model.NetworkConfiguration;
import io.floci.aws.services.ecs.model.NetworkMode;
import io.floci.aws.services.ecs.model.RunTaskRequest;
import io.floci.aws.testing.InMemoryStorageFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static io.floci.aws.testing.EcsTaskWaits.awaitLastStatus;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* RunTask answers before the task's images are pulled, as AWS does: the task comes back
* PROVISIONING (awsvpc) or PENDING and moves on in the background.
*/
class EcsRunTaskAsyncLaunchServiceTest {
private static final String REGION = "us-east-1";
private static final Duration LAUNCH_BUDGET = Duration.ofSeconds(5);
private final EcsContainerManager containerManager = mock(EcsContainerManager.class);
private final CountDownLatch startEntered = new CountDownLatch(1);
private final CountDownLatch releaseStart = new CountDownLatch(1);
private final List<EcsService> services = new ArrayList<>();
@BeforeEach
void stubContainers() {
// Mockito answers 0 for an Integer, which reads as "every container exited".
when(containerManager.getExitCodeIfStopped(anyString())).thenReturn(null);
// The image pull holds until the test releases it.
when(containerManager.startTask(any(), any(), any(), anyString())).thenAnswer(invocation -> {
EcsTask task = invocation.getArgument(0);
startEntered.countDown();
if (!releaseStart.await(10, TimeUnit.SECONDS)) {
throw new IllegalStateException("the image pull was never released");
}
return started(task);
});
when(containerManager.stopTaskAndCollectExitCodes(any())).thenAnswer(invocation -> {
EcsTaskHandle handle = invocation.getArgument(0);
handle.getContainerIds().keySet().forEach(handle::recordContainerRemoved);
return Map.of("app", 0);
});
}
@AfterEach
void tearDown() {
releaseStart.countDown();
services.forEach(EcsService::stopManagedContainers);
}
@Test
void runTaskAnswersPendingBeforeTheImageIsPulled() throws Exception {
EcsService service = newService(false);
registerTaskDefinition(service, "pending");
EcsTask response = run(service, "pending");
assertEquals("PENDING", response.getLastStatus());
assertEquals("RUNNING", response.getDesiredStatus());
assertNull(response.getStartedAt());
assertEquals(List.of("PENDING"), containerStatuses(response));
assertTrue(startEntered.await(5, TimeUnit.SECONDS));
assertEquals("PENDING", describe(service, response).getLastStatus());
releaseStart.countDown();
awaitLastStatus(() -> describe(service, response), EcsTask::getLastStatus, LAUNCH_BUDGET, "RUNNING");
assertEquals("PENDING", response.getLastStatus(), "the RunTask response is a snapshot");
assertEquals(1, runningTasksCount(service));
}
@Test
void runTaskAnswersProvisioningForAnAwsvpcTask() throws Exception {
EcsService service = newService(false);
ContainerDefinition container = new ContainerDefinition();
container.setName("app");
container.setImage("busybox:latest");
service.registerTaskDefinition("vpc", List.of(container), NetworkMode.awsvpc, "256", "512",
null, null, List.of("FARGATE"), REGION);
AwsVpcConfiguration vpc = new AwsVpcConfiguration();
vpc.setSubnets(List.of("subnet-12345678"));
NetworkConfiguration network = new NetworkConfiguration();
network.setAwsvpcConfiguration(vpc);
CountDownLatch monitorHeld = new CountDownLatch(1);
CountDownLatch releaseMonitor = new CountDownLatch(1);
// Holds the new task's monitor so its launch cannot move it past PROVISIONING until released.
doAnswer(invocation -> {
EcsTask live = invocation.getArgument(0);
new Thread(() -> {
synchronized (live) {
monitorHeld.countDown();
try {
releaseMonitor.await(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}).start();
assertTrue(monitorHeld.await(5, TimeUnit.SECONDS));
return null;
}).when(containerManager).attachTaskNetwork(any(), any(), anyString());
EcsTask response = assertTimeoutPreemptively(Duration.ofSeconds(2), () -> service.runTask(
null, "vpc", 1, LaunchType.FARGATE, null, null, List.of(), network, REGION).getFirst());
assertEquals("PROVISIONING", response.getLastStatus());
assertEquals("PRECREATED", response.getAttachmentStatus());
assertEquals("PROVISIONING", describe(service, response).getLastStatus());
// ECS counts a task as pending while it is PROVISIONING as well as PENDING.
assertPendingCounts(service, 1);
releaseMonitor.countDown();
assertTrue(startEntered.await(5, TimeUnit.SECONDS));
EcsTask launching = describe(service, response);
assertEquals("PENDING", launching.getLastStatus());
assertEquals("ATTACHED", launching.getAttachmentStatus());
assertTrue(launching.getVersion() > response.getVersion());
assertPendingCounts(service, 1);
releaseStart.countDown();
awaitLastStatus(() -> describe(service, response), EcsTask::getLastStatus, LAUNCH_BUDGET, "RUNNING");
assertPendingCounts(service, 0);
}
@Test
void mockModeAnswersPendingAndRunsInTheBackground() {
EcsService service = newService(true);
registerTaskDefinition(service, "mock");
EcsTask response = run(service, "mock");
assertEquals("PENDING", response.getLastStatus());
assertEquals(List.of("PENDING"), containerStatuses(response));
EcsTask running = awaitLastStatus(() -> describe(service, response), EcsTask::getLastStatus,
LAUNCH_BUDGET, "RUNNING");
assertEquals(List.of("RUNNING"), containerStatuses(running));
assertEquals(1, runningTasksCount(service));
verify(containerManager, never()).startTask(any(), any(), any(), anyString());
}
@Test
void theResponseCarriesTheContainersMemoryReservation() {
EcsService service = newService(false);
ContainerDefinition container = new ContainerDefinition();
container.setName("app");
container.setImage("busybox:latest");
container.setMemoryReservation(128);
service.registerTaskDefinition("reserved", List.of(container), null, null, null,
null, null, List.of(), REGION);
EcsTask response = run(service, "reserved");
assertEquals("128", response.getContainers().getFirst().getMemoryReservation());
}
@Test
void theExecAgentIsPendingUntilTheTaskRuns() {
EcsService service = newService(true);
registerTaskDefinition(service, "exec");
RunTaskRequest request = new RunTaskRequest();
request.setTaskDefinition("exec");
request.setEnableExecuteCommand(true);
EcsTask response = assertTimeoutPreemptively(Duration.ofSeconds(2),
() -> service.runTask(request, REGION).getFirst());
ManagedAgent pending = response.getContainers().getFirst().getManagedAgents().getFirst();
assertEquals("ExecuteCommandAgent", pending.name());
assertEquals("PENDING", pending.lastStatus());
assertNull(pending.lastStartedAt());
EcsTask launched = awaitLastStatus(() -> describe(service, response), EcsTask::getLastStatus,
LAUNCH_BUDGET, "RUNNING");
ManagedAgent running = launched.getContainers().getFirst().getManagedAgents().getFirst();
assertEquals("RUNNING", running.lastStatus());
assertNotNull(running.lastStartedAt());
}
@Test
void aFailedPullDuringAStopKeepsTheUsersReason() throws Exception {
doAnswer(invocation -> {
startEntered.countDown();
assertTrue(releaseStart.await(5, TimeUnit.SECONDS));
throw new IllegalStateException("CannotPullContainerError: pull access denied");
}).when(containerManager).startTask(any(), any(), any(), anyString());
EcsService service = newService(false);
registerTaskDefinition(service, "stop-then-fail");
EcsTask response = run(service, "stop-then-fail");
assertTrue(startEntered.await(5, TimeUnit.SECONDS));
service.stopTask(null, response.getTaskArn(), "scaling in", REGION);
releaseStart.countDown();
EcsTask stopped = awaitLastStatus(() -> describe(service, response), EcsTask::getLastStatus,
LAUNCH_BUDGET, "STOPPED");
assertEquals("UserInitiated", stopped.getStopCode());
assertEquals("scaling in", stopped.getStoppedReason());
}
@Test
void aFailedPullShowsOnDescribeTasksNotInTheResponse() {
doThrow(new IllegalStateException("CannotPullContainerError: pull access denied"))
.when(containerManager).startTask(any(), any(), any(), anyString());
EcsService service = newService(false);
registerTaskDefinition(service, "bad-image");
EcsTask response = run(service, "bad-image");
assertEquals("PENDING", response.getLastStatus());
EcsTask stopped = awaitLastStatus(() -> describe(service, response), EcsTask::getLastStatus,
LAUNCH_BUDGET, "STOPPED");
assertEquals("STOPPED", stopped.getDesiredStatus());
assertEquals("TaskFailedToStart", stopped.getStopCode());
assertEquals("Failed to start: CannotPullContainerError: pull access denied", stopped.getStoppedReason());
assertNull(stopped.getStartedAt());
assertNotNull(stopped.getStoppingAt());
assertNotNull(stopped.getStoppedAt());
assertNotNull(stopped.getExecutionStoppedAt());
assertEquals(List.of("STOPPED"), containerStatuses(stopped));
assertEquals(0, runningTasksCount(service));
}
@Test
void stopTaskDuringThePullAnswersWithTheTaskStillLaunching() throws Exception {
EcsService service = newService(false);
registerTaskDefinition(service, "stop-during-pull");
EcsTask response = run(service, "stop-during-pull");
assertTrue(startEntered.await(5, TimeUnit.SECONDS));
EcsTask stopping = service.stopTask(null, response.getTaskArn(), null, REGION);
assertEquals("PENDING", stopping.getLastStatus());
assertEquals("STOPPED", stopping.getDesiredStatus());
assertEquals("UserInitiated", stopping.getStopCode());
assertNotNull(stopping.getStoppingAt());
releaseStart.countDown();
awaitLastStatus(() -> describe(service, response), EcsTask::getLastStatus, LAUNCH_BUDGET, "STOPPED");
verify(containerManager).stopTaskAndCollectExitCodes(any());
assertEquals(0, runningTasksCount(service));
}
@Test
void stopTaskBeforeTheLaunchLandsTheTaskWithoutStartingIt() {
EcsService service = newService(false);
registerTaskDefinition(service, "stop-first");
CountDownLatch monitorHeld = new CountDownLatch(1);
CountDownLatch runTaskAnswered = new CountDownLatch(1);
AtomicReference<String> statusStopTaskAnswered = new AtomicReference<>();
// Holds the new task's monitor from before the launch is handed over until a StopTask has
// been answered, so the launch can only begin after the stop.
doAnswer(invocation -> {
EcsTask live = invocation.getArgument(0);
Thread stopper = new Thread(() -> {
synchronized (live) {
monitorHeld.countDown();
try {
runTaskAnswered.await(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
statusStopTaskAnswered.set(service.stopTask(null, live.getTaskArn(), null, REGION).getLastStatus());
}
});
stopper.start();
assertTrue(monitorHeld.await(5, TimeUnit.SECONDS));
return null;
}).when(containerManager).attachTaskNetwork(any(), any(), anyString());
EcsTask response = run(service, "stop-first");
runTaskAnswered.countDown();
EcsTask stopped = awaitLastStatus(() -> describe(service, response), EcsTask::getLastStatus,
LAUNCH_BUDGET, "STOPPED");
assertEquals("PENDING", statusStopTaskAnswered.get());
assertEquals("UserInitiated", stopped.getStopCode());
assertNull(stopped.getStartedAt());
assertEquals(List.of("STOPPED"), containerStatuses(stopped));
assertEquals(0, runningTasksCount(service));
verify(containerManager, never()).startTask(any(), any(), any(), anyString());
}
@Test
void teardownInterruptsAPullAndAfterResetLaunchesAgain() throws Exception {
doAnswer(invocation -> {
startEntered.countDown();
try {
// A pull that only the teardown's interrupt ends.
new CountDownLatch(1).await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("image pull interrupted", e);
}
throw new IllegalStateException("the pull ended without an interrupt");
}).when(containerManager).startTask(any(), any(), any(), anyString());
EcsService service = newService(false);
registerTaskDefinition(service, "teardown");
EcsTask response = run(service, "teardown");
assertTrue(startEntered.await(5, TimeUnit.SECONDS));
assertTimeoutPreemptively(LAUNCH_BUDGET, service::stopManagedContainers);
EcsTask stopped = describe(service, response);
assertEquals("STOPPED", stopped.getLastStatus());
assertEquals("TaskFailedToStart", stopped.getStopCode());
doAnswer(invocation -> started(invocation.getArgument(0)))
.when(containerManager).startTask(any(), any(), any(), anyString());
service.afterReset();
EcsTask again = run(service, "teardown");
awaitLastStatus(() -> describe(service, again), EcsTask::getLastStatus, LAUNCH_BUDGET, "RUNNING");
}
@Test
void aLaunchDuringTeardownFailsToStartInsteadOfStayingPending() {
EcsService service = newService(false);
registerTaskDefinition(service, "after-teardown");
service.stopManagedContainers();
EcsTask response = run(service, "after-teardown");
assertEquals("PENDING", response.getLastStatus());
EcsTask stopped = describe(service, response);
assertEquals("STOPPED", stopped.getLastStatus());
assertEquals("TaskFailedToStart", stopped.getStopCode());
verify(containerManager, never()).startTask(any(), any(), any(), anyString());
}
private EcsService newService(boolean mockMode) {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().ecs().mock()).thenReturn(mockMode);
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
EcsService service = new EcsService(new RegionResolver(REGION, "000000000000"), containerManager,
config, mock(EcsLoadBalancerRegistrar.class), new InMemoryStorageFactory("000000000000"), null);
service.initializeStorage();
services.add(service);
return service;
}
private static void registerTaskDefinition(EcsService service, String family) {
ContainerDefinition container = new ContainerDefinition();
container.setName("app");
container.setImage("busybox:latest");
service.registerTaskDefinition(family, List.of(container), null, null, null,
null, null, List.of(), REGION);
}
/** RunTask, failing rather than hanging if it waits for the launch. */
private static EcsTask run(EcsService service, String family) {
return assertTimeoutPreemptively(Duration.ofSeconds(2), () -> service.runTask(null, family, 1,
LaunchType.FARGATE, null, null, List.of(), null, REGION).getFirst(),
"RunTask waited for the task's launch");
}
private static EcsTaskHandle started(EcsTask task) {
Container container = new Container();
container.setName("app");
container.setRuntimeId("docker-app");
task.setContainers(List.of(container));
return new EcsTaskHandle(task.getTaskArn(), Map.of("app", "docker-app"), Map.of());
}
private static EcsTask describe(EcsService service, EcsTask task) {
return service.describeTasks(null, List.of(task.getTaskArn()), REGION).getFirst();
}
private static int runningTasksCount(EcsService service) {
return service.describeClusters(List.of("default"), REGION).getFirst().getRunningTasksCount();
}
/** DescribeClusters' pendingTasksCount and its Fargate statistic, as rendered, which must agree. */
private static void assertPendingCounts(EcsService service, long expected) {
EcsCluster cluster = service.describeClusters(List.of("default"), REGION).getFirst();
ObjectNode rendered = new EcsResponseWriter(service, new ObjectMapper())
.clusterNode(cluster, Set.of("STATISTICS"));
assertEquals(expected, rendered.get("pendingTasksCount").asLong());
String pendingFargate = null;
for (JsonNode statistic : rendered.get("statistics")) {
if ("pendingFargateTasksCount".equals(statistic.get("name").asText())) {
pendingFargate = statistic.get("value").asText();
}
}
assertEquals(String.valueOf(expected), pendingFargate);
}
private static List<String> containerStatuses(EcsTask task) {
return task.getContainers().stream().map(Container::getLastStatus).toList();
}
}
@@ -12,8 +12,10 @@ import io.floci.aws.services.ecs.model.Secret;
import io.floci.aws.services.ecs.model.TaskStatus;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.List;
import static io.floci.aws.testing.EcsTaskWaits.awaitLastStatus;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -53,7 +55,11 @@ class EcsServiceContainerSecretsTest {
LaunchType.EC2, null, null, List.of(), null, "us-east-1");
assertEquals(1, tasks.size());
EcsTask task = tasks.getFirst();
// RunTask answers before the launch; the failure lands on the task in the background.
String taskArn = tasks.getFirst().getTaskArn();
EcsTask task = awaitLastStatus(
() -> service.describeTasks("test-cluster", List.of(taskArn), "us-east-1").getFirst(),
EcsTask::getLastStatus, Duration.ofSeconds(5), "STOPPED");
assertEquals(TaskStatus.STOPPED.name(), task.getLastStatus());
assertEquals(TaskStatus.STOPPED.name(), task.getDesiredStatus());
// A ResourceInitializationError is AWS's exact stopped-reason wording, so it must be
@@ -21,12 +21,14 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import static io.floci.aws.testing.EcsTaskWaits.awaitLastStatus;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -35,6 +37,7 @@ import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -65,8 +68,11 @@ class EcsServiceRestartLeftoversTest {
});
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();
String taskArn = restarted.runTask("app-cluster", "web", 1,
LaunchType.EC2, null, null, null, null, REGION).getFirst().getTaskArn();
EcsTask task = awaitLastStatus(
() -> restarted.describeTasks("app-cluster", List.of(taskArn), REGION).getFirst(),
EcsTask::getLastStatus, Duration.ofSeconds(5), "RUNNING", "STOPPED");
assertEquals("RUNNING", task.getLastStatus());
restarted.reconcileServices();
verify(manager, times(2)).startTask(any(), any(), any(), anyString());
@@ -100,7 +106,10 @@ class EcsServiceRestartLeftoversTest {
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);
String taskArn = restarted.runTask(null, "web", 1, LaunchType.EC2, null, null, null, null, REGION)
.getFirst().getTaskArn();
awaitLastStatus(() -> restarted.describeTasks(null, List.of(taskArn), REGION).getFirst(),
EcsTask::getLastStatus, Duration.ofSeconds(5), "RUNNING", "STOPPED");
restarted.reconcile();
restarted.reconcile();
restarted.reconcile();
@@ -166,14 +175,20 @@ class EcsServiceRestartLeftoversTest {
null, null, List.of(), REGION);
restarted.releasePreviousRunLeftovers();
EcsTask blocked = restarted.runTask("app-cluster", "web", 1, LaunchType.EC2, null, null,
null, null, REGION).getFirst();
String blockedArn = restarted.runTask("app-cluster", "web", 1,
LaunchType.EC2, null, null, null, null, REGION).getFirst().getTaskArn();
EcsTask blocked = awaitLastStatus(
() -> restarted.describeTasks("app-cluster", List.of(blockedArn), REGION).getFirst(),
EcsTask::getLastStatus, Duration.ofSeconds(5), "RUNNING", "STOPPED");
assertEquals("STOPPED", blocked.getLastStatus());
assertThat(blocked.getStoppedReason(), containsString("previous run"));
verify(containerManager, never()).startTask(any(), any(), any(), anyString());
restarted.runTask("app-cluster", "web", 1, LaunchType.EC2, null, null, null, null, REGION);
String taskArn = restarted.runTask("app-cluster", "web", 1, LaunchType.EC2, null, null, null, null, REGION)
.getFirst().getTaskArn();
awaitLastStatus(() -> restarted.describeTasks("app-cluster", List.of(taskArn), REGION).getFirst(),
EcsTask::getLastStatus, Duration.ofSeconds(5), "RUNNING", "STOPPED");
verify(containerManager, times(3)).removeLeftoverContainers();
verify(containerManager).startTask(any(), any(), any(), anyString());
@@ -215,7 +230,10 @@ class EcsServiceRestartLeftoversTest {
null, null, List.of(), REGION);
restarted.releasePreviousRunLeftovers();
restarted.runTask("app-cluster", "web", 1, LaunchType.EC2, null, null, null, null, REGION);
String taskArn = restarted.runTask("app-cluster", "web", 1, LaunchType.EC2, null, null, null, null, REGION)
.getFirst().getTaskArn();
awaitLastStatus(() -> restarted.describeTasks("app-cluster", List.of(taskArn), REGION).getFirst(),
EcsTask::getLastStatus, Duration.ofSeconds(5), "RUNNING", "STOPPED");
verify(containerManager, never()).removeLeftoverContainers();
verify(containerManager, never()).removeLeftoverTaskVolumes();
@@ -275,14 +293,18 @@ class EcsServiceRestartLeftoversTest {
ecs.createService("app-cluster", "alpha", "web", 0, LaunchType.EC2, List.of(lb), null, REGION);
// A task of no service at all: any container can take the address a stale entry points at.
EcsTask task = ecs.runTask("app-cluster", "web", 1, LaunchType.EC2, null, null, null, null, REGION)
.getFirst();
String taskArn = ecs.runTask("app-cluster", "web", 1, LaunchType.EC2, null, null, null, null, REGION)
.getFirst().getTaskArn();
EcsTask task = awaitLastStatus(
() -> ecs.describeTasks("app-cluster", List.of(taskArn), REGION).getFirst(),
EcsTask::getLastStatus, Duration.ofSeconds(5), "RUNNING", "STOPPED");
assertEquals("RUNNING", task.getLastStatus());
// A target only on the ports the container serves, and never at the VPC-scoped ENI address.
verify(lbRegistrar).evictUnrecordedTargets(task, Set.of(TARGET_GROUP_ARN),
// The launch evicts them just after it marks the task RUNNING.
verify(lbRegistrar, timeout(5000)).evictUnrecordedTargets(task, Set.of(TARGET_GROUP_ARN),
Set.of(new EcsTaskAddress(host, targetPort)), REGION);
verify(discoveryRegistrar).evictUnrecordedInstances(task, Set.of("srv-alpha"),
verify(discoveryRegistrar, timeout(5000)).evictUnrecordedInstances(task, Set.of("srv-alpha"),
Set.of(new EcsTaskAddress("10.0.1.5", null, "vpc-app"), new EcsTaskAddress("172.19.0.4", null)),
REGION);
}
@@ -24,6 +24,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static io.floci.aws.testing.EcsTaskWaits.awaitLastStatus;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
@@ -62,6 +63,7 @@ class EcsServiceTaskOwnershipTest {
EcsTask intruder = service.runTask("own-cluster", "own-fam", 1, LaunchType.FARGATE,
"web", "me", null, null, REGION).getFirst();
awaitLastStatus(() -> reload(service, intruder), EcsTask::getLastStatus, Duration.ofSeconds(5), "RUNNING");
// Two ticks: the first launches the service's own task, the second publishes the
// resulting runningCount (the reconciler counts before it launches).
@@ -92,6 +94,7 @@ class EcsServiceTaskOwnershipTest {
EcsTask intruder = service.runTask("scale-cluster", "own-fam", 1, LaunchType.FARGATE,
"api", "me", null, null, REGION).getFirst();
awaitLastStatus(() -> reload(service, intruder), EcsTask::getLastStatus, Duration.ofSeconds(5), "RUNNING");
service.updateService("scale-cluster", "api", null, 0, null, REGION);
service.reconcileServices();
@@ -289,6 +292,7 @@ class EcsServiceTaskOwnershipTest {
EcsTask intruder = service.startTask("daemon-own", List.of(instance.getContainerInstanceArn()),
"own-fam", "agent", "me", REGION).getFirst();
awaitLastStatus(() -> reload(service, intruder), EcsTask::getLastStatus, Duration.ofSeconds(5), "RUNNING");
service.reconcileServices();
@@ -313,6 +317,7 @@ class EcsServiceTaskOwnershipTest {
EcsTask intruder = service.runTask("delete-cluster", "own-fam", 1, LaunchType.FARGATE,
"worker", "me", null, null, REGION).getFirst();
awaitLastStatus(() -> reload(service, intruder), EcsTask::getLastStatus, Duration.ofSeconds(5), "RUNNING");
service.deleteService("delete-cluster", "worker", true, REGION);
@@ -30,6 +30,7 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static io.floci.aws.testing.EcsTaskWaits.awaitLastStatus;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -88,6 +89,8 @@ class EcsServiceTeardownTest {
null, null, List.of(), REGION);
String taskArn = service.runTask(null, "volume-retry", 1, LaunchType.FARGATE, null, null,
List.of(), null, REGION).getFirst().getTaskArn();
awaitLastStatus(() -> service.describeTasks(null, List.of(taskArn), REGION).getFirst(),
EcsTask::getLastStatus, Duration.ofSeconds(5), "RUNNING");
if (exitsNaturally) {
service.reconcile();
@@ -126,8 +129,10 @@ class EcsServiceTeardownTest {
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();
String taskArn = service.runTask(null, "failed-volume-launch", 1, LaunchType.FARGATE, null, null,
List.of(), null, REGION).getFirst().getTaskArn();
EcsTask task = awaitLastStatus(() -> service.describeTasks(null, List.of(taskArn), REGION).getFirst(),
EcsTask::getLastStatus, Duration.ofSeconds(5), "STOPPED");
assertEquals("STOPPED", task.getLastStatus());
assertEquals("Failed to start: launch failed", task.getStoppedReason());
assertTrue(partial.hasTaskVolumes());
@@ -184,9 +189,11 @@ class EcsServiceTeardownTest {
CountDownLatch startEntered = new CountDownLatch(1);
CountDownLatch finishStart = new CountDownLatch(1);
AtomicReference<EcsTask> startingTask = new AtomicReference<>();
AtomicReference<Thread> startingThread = new AtomicReference<>();
when(containerManager.startTask(any(), any(), any(), anyString())).thenAnswer(invocation -> {
EcsTask task = invocation.getArgument(0);
startingTask.set(task);
startingThread.set(Thread.currentThread());
startEntered.countDown();
if (!finishStart.await(5, TimeUnit.SECONDS)) {
throw new IllegalStateException("container startup was not released");
@@ -214,15 +221,19 @@ class EcsServiceTeardownTest {
launch.start();
try {
assertTrue(startEntered.await(5, TimeUnit.SECONDS));
// The launch runs on the task launcher's thread.
Thread starter = startingThread.get();
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");
while (starter.getState() != Thread.State.BLOCKED) {
assertTrue(starter.isAlive(), "startup finished without acquiring the task lock");
assertTrue(System.nanoTime() < deadline, "startup did not wait for the task lock");
Thread.onSpinWait();
}
}
starter.join(5000);
assertFalse(starter.isAlive());
launch.join(5000);
assertFalse(launch.isAlive());
assertNull(launchFailure.get());
@@ -276,13 +287,19 @@ class EcsServiceTeardownTest {
List.of(), null, REGION));
try {
assertTrue(startEntered.await(5, TimeUnit.SECONDS));
assertEquals("STOPPING", service.stopTask(null, taskArn.get(), null, REGION).getLastStatus());
// Still launching: the stop is recorded and the launch lands it once the handle arrives.
EcsTask stopping = service.stopTask(null, taskArn.get(), null, REGION);
assertEquals("PENDING", stopping.getLastStatus());
assertEquals("STOPPED", stopping.getDesiredStatus());
} finally {
finishStart.countDown();
}
launch.get(5, TimeUnit.SECONDS);
assertEquals("STOPPED", service.describeTasks(null, List.of(taskArn.get()), REGION).getFirst().getLastStatus());
EcsTask stopped = awaitLastStatus(
() -> service.describeTasks(null, List.of(taskArn.get()), REGION).getFirst(),
EcsTask::getLastStatus, Duration.ofSeconds(5), "STOPPED");
assertEquals("STOPPED", stopped.getLastStatus());
verify(containerManager).stopTaskAndCollectExitCodes(handle);
service.stopManagedContainers();
}
@@ -367,6 +384,8 @@ class EcsServiceTeardownTest {
null, null, List.of(), REGION);
String taskArn = service.runTask(null, "retry-removal", 1, LaunchType.FARGATE, null, null,
List.of(), null, REGION).getFirst().getTaskArn();
awaitLastStatus(() -> service.describeTasks(null, List.of(taskArn), REGION).getFirst(),
EcsTask::getLastStatus, Duration.ofSeconds(5), "RUNNING");
service.stopTask(null, taskArn, null, REGION);
assertEquals("STOPPING", service.describeTasks(null, List.of(taskArn), REGION).getFirst().getLastStatus());
@@ -410,6 +429,8 @@ class EcsServiceTeardownTest {
null, null, List.of(), REGION);
String taskArn = service.runTask(null, "unknown-exit", 1, LaunchType.FARGATE, null, null,
List.of(), null, REGION).getFirst().getTaskArn();
awaitLastStatus(() -> service.describeTasks(null, List.of(taskArn), REGION).getFirst(),
EcsTask::getLastStatus, Duration.ofSeconds(5), "RUNNING");
EcsTask stopped = service.stopTask(null, taskArn, null, REGION);
assertEquals("STOPPED", stopped.getLastStatus());
@@ -449,6 +470,8 @@ class EcsServiceTeardownTest {
null, null, List.of(), REGION);
String taskArn = service.runTask(null, "concurrent-stop", 1, LaunchType.FARGATE, null, null,
List.of(), null, REGION).getFirst().getTaskArn();
awaitLastStatus(() -> service.describeTasks(null, List.of(taskArn), REGION).getFirst(),
EcsTask::getLastStatus, Duration.ofSeconds(5), "RUNNING");
CompletableFuture<EcsTask> first = CompletableFuture.supplyAsync(() ->
service.stopTask(null, taskArn, null, REGION));
@@ -586,6 +609,8 @@ class EcsServiceTeardownTest {
null, null, List.of(), REGION);
String taskArn = service.runTask(null, "retry-fam", 1, LaunchType.FARGATE, null, null,
List.of(), null, REGION).getFirst().getTaskArn();
awaitLastStatus(() -> service.describeTasks(null, List.of(taskArn), REGION).getFirst(),
EcsTask::getLastStatus, Duration.ofSeconds(5), "RUNNING");
service.stopTask(null, taskArn, null, REGION);
verify(containerManager, times(1)).stopTaskAndCollectExitCodes(handle);
@@ -28,6 +28,7 @@ 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.assertNotNull;
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;
@@ -198,6 +199,24 @@ class EcsContainerManagerAwsBaselineTest {
assertEquals(id, task.getContainers().getFirst().getMetadataId());
}
@Test
void startTaskLeavesTheTasksStatusToTheService() {
TaskDefinition taskDef = new TaskDefinition();
taskDef.setFamily("test-family");
taskDef.setContainerDefinitions(List.of(containerDef("app", "app:latest", List.of())));
EcsTask task = new EcsTask();
task.setTaskArn("arn:aws:ecs:us-east-1:000000000000:task/test-cluster/abc123");
task.setLastStatus("PENDING");
// A StopTask that arrived while the images were pulled.
task.setDesiredStatus("STOPPED");
manager.startTask(task, taskDef, null, "us-east-1");
assertEquals("PENDING", task.getLastStatus());
assertEquals("STOPPED", task.getDesiredStatus());
assertNull(task.getStartedAt());
}
private static ContainerDefinition containerDef(String name, String image, List<KeyValuePair> env) {
ContainerDefinition def = new ContainerDefinition();
def.setName(name);
@@ -0,0 +1,31 @@
package io.floci.aws.testing;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.function.Function;
import static org.awaitility.Awaitility.await;
/**
* RunTask and StartTask answer before the launch, which lands the task on the task launcher's
* thread. A test that looks at the task right after the answer races it.
*/
public final class EcsTaskWaits {
private EcsTaskWaits() {
}
/**
* Waits until the last status of what {@code describe} returns is one of {@code statuses} and
* returns that description. RUNNING or STOPPED waits for the launch whichever way it lands; a
* stop during the launch passes RUNNING on its way to STOPPED, so a test expecting the stop
* names STOPPED alone.
*/
public static <T> T awaitLastStatus(Callable<T> describe, Function<? super T, String> lastStatus,
Duration timeout, String... statuses) {
List<String> wanted = List.of(statuses);
return await("the task to reach " + wanted).atMost(timeout)
.until(describe, described -> wanted.contains(lastStatus.apply(described)));
}
}