mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
ddad6ddeb9
commit
c4b22b25bd
28 files changed
+1039
-143
No files matched your search
+6
-1
@@ -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()));
|
||||
}
|
||||
}
|
||||
+6
-1
@@ -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;
|
||||
}
|
||||
|
||||
+8
-2
@@ -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");
|
||||
|
||||
|
||||
+8
-2
@@ -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);
|
||||
|
||||
+19
@@ -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)));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user