fix(ecs): honor running task filters for container instances (#7032)

This commit is contained in:
Jimmy Liu Jia authored and GitHub committed 2026-10-30 18:23:44 -04:00
1 parent f48c3a9c01
commit e2562377bf
8 files changed
+363 -24

No files matched your search

+5 -1
View File
@@ -727,7 +727,11 @@ dropping it, so a later `DescribeContainerInstances` still answers for it, as on
`ListContainerInstances` defaults to every instance other than the `INACTIVE` ones, validates
`status` against the five documented values, and pages with `maxResults` (1 to 100) and
`nextToken`. The cluster query language `filter` is accepted and ignored.
`nextToken`. Its `filter` supports a single `runningTasksCount` numeric comparison with
`==`, `!=`, `>`, `>=`, `<`, `<=` or their named equivalents. Other cluster query subjects
and compound expressions are not implemented and return `InvalidParameterException`. The
running count in list filtering and `DescribeContainerInstances` includes tasks whose desired
status is `RUNNING`, even while their last status is `PENDING`.
`UpdateContainerInstancesState` sets only `ACTIVE` or `DRAINING`, takes at most 10 instances per
call, and refuses to drain an instance that is not `ACTIVE` first. It and
+6
View File
@@ -510,6 +510,12 @@
<version>${aws.sdk.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>ecs</artifactId>
<version>${aws.sdk.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-junit</artifactId>
@@ -894,7 +894,7 @@ public class EcsJsonHandler {
request.setTags(parseTagMap(req.path("tags")));
ContainerInstance instance = service.registerContainerInstance(request, region);
ObjectNode resp = objectMapper.createObjectNode();
resp.set("containerInstance", writer.containerInstanceNode(instance));
resp.set("containerInstance", writer.containerInstanceNode(instance, request.getCluster(), region));
return Response.ok(resp).build();
}
@@ -904,7 +904,7 @@ public class EcsJsonHandler {
boolean force = req.path("force").asBoolean(false);
ContainerInstance instance = service.deregisterContainerInstance(cluster, containerInstance, force, region);
ObjectNode resp = objectMapper.createObjectNode();
resp.set("containerInstance", writer.containerInstanceNode(instance));
resp.set("containerInstance", writer.containerInstanceNode(instance, cluster, region));
return Response.ok(resp).build();
}
@@ -918,10 +918,8 @@ public class EcsJsonHandler {
EcsService.DescribeContainerInstancesResult found =
service.describeContainerInstancesDetailed(cluster, instanceRefs, region);
ObjectNode resp = objectMapper.createObjectNode();
ArrayNode arr = objectMapper.createArrayNode();
found.instances().forEach(ci ->
arr.add(writer.containerInstanceNode(ci, includeTags, includeHealth)));
resp.set("containerInstances", arr);
resp.set("containerInstances", writer.containerInstanceNodes(
found.instances(), cluster, region, includeTags, includeHealth));
ArrayNode failures = objectMapper.createArrayNode();
found.failures().forEach(f -> failures.add(writer.failureNode(f)));
resp.set("failures", failures);
@@ -931,10 +929,11 @@ public class EcsJsonHandler {
private Response handleListContainerInstances(JsonNode req, String region) {
String cluster = req.has("cluster") ? req.path("cluster").asText() : null;
String status = parseChoice(req, "status", CONTAINER_INSTANCE_STATUSES);
String filter = req.hasNonNull("filter") ? req.path("filter").asText() : null;
Integer maxResults = req.hasNonNull("maxResults") ? req.path("maxResults").asInt() : null;
String nextToken = req.hasNonNull("nextToken") ? req.path("nextToken").asText() : null;
EcsService.ListPage page =
service.listContainerInstances(cluster, status, maxResults, nextToken, region);
service.listContainerInstances(cluster, status, filter, maxResults, nextToken, region);
ObjectNode resp = objectMapper.createObjectNode();
ArrayNode arr = objectMapper.createArrayNode();
page.arns().forEach(arr::add);
@@ -950,7 +949,7 @@ public class EcsJsonHandler {
String containerInstance = req.path("containerInstance").asText();
ContainerInstance instance = service.updateContainerAgent(cluster, containerInstance, region);
ObjectNode resp = objectMapper.createObjectNode();
resp.set("containerInstance", writer.containerInstanceNode(instance));
resp.set("containerInstance", writer.containerInstanceNode(instance, cluster, region));
return Response.ok(resp).build();
}
@@ -961,9 +960,8 @@ public class EcsJsonHandler {
EcsService.UpdateContainerInstancesStateResult updated =
service.updateContainerInstancesState(cluster, instanceRefs, status, region);
ObjectNode resp = objectMapper.createObjectNode();
ArrayNode arr = objectMapper.createArrayNode();
updated.instances().forEach(ci -> arr.add(writer.containerInstanceNode(ci)));
resp.set("containerInstances", arr);
resp.set("containerInstances", writer.containerInstanceNodes(
updated.instances(), cluster, region, true, true));
ArrayNode failures = objectMapper.createArrayNode();
updated.failures().forEach(f -> failures.add(writer.failureNode(f)));
resp.set("failures", failures);
@@ -798,8 +798,8 @@ public class EcsResponseWriter {
return n;
}
public ObjectNode containerInstanceNode(ContainerInstance ci) {
return containerInstanceNode(ci, true, true);
public ObjectNode containerInstanceNode(ContainerInstance ci, String clusterRef, String region) {
return containerInstanceNode(ci, clusterRef, region, true, true);
}
/**
@@ -809,14 +809,32 @@ public class EcsResponseWriter {
* omitted, tags and container instance health status aren't included in
* the response."
*/
public ObjectNode containerInstanceNode(ContainerInstance ci, boolean includeTags,
boolean includeHealth) {
public ObjectNode containerInstanceNode(ContainerInstance ci, String clusterRef, String region,
boolean includeTags, boolean includeHealth) {
return containerInstanceNode(ci, service.runningTaskCountForInstance(
clusterRef, ci.getContainerInstanceArn(), region), includeTags, includeHealth);
}
public ArrayNode containerInstanceNodes(List<ContainerInstance> instances, String clusterRef, String region,
boolean includeTags, boolean includeHealth) {
ArrayNode nodes = objectMapper.createArrayNode();
if (instances.isEmpty()) {
return nodes;
}
Map<String, Long> runningCounts = service.runningTaskCountsForCluster(clusterRef, region);
instances.forEach(ci -> nodes.add(containerInstanceNode(ci,
runningCounts.getOrDefault(ci.getContainerInstanceArn(), 0L), includeTags, includeHealth)));
return nodes;
}
private ObjectNode containerInstanceNode(ContainerInstance ci, long runningTaskCount,
boolean includeTags, boolean includeHealth) {
ObjectNode n = objectMapper.createObjectNode();
n.put("containerInstanceArn", ci.getContainerInstanceArn());
n.put("ec2InstanceId", ci.getEc2InstanceId());
n.put("status", ci.getStatus());
if (ci.getStatusReason() != null) { n.put("statusReason", ci.getStatusReason()); }
n.put("runningTasksCount", ci.getRunningTasksCount());
n.put("runningTasksCount", runningTaskCount);
n.put("pendingTasksCount", ci.getPendingTasksCount());
n.put("agentConnected", ci.isAgentConnected());
if (ci.getAgentUpdateStatus() != null) { n.put("agentUpdateStatus", ci.getAgentUpdateStatus()); }
@@ -107,7 +107,9 @@ import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.LongPredicate;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -3515,6 +3517,9 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
"ACTIVE", "DRAINING", "REGISTERING", "DEREGISTERING", "REGISTRATION_FAILED", "INACTIVE");
/** "The only valid values for this action are ACTIVE and DRAINING." */
private static final Set<String> UPDATABLE_CONTAINER_INSTANCE_STATUSES = Set.of("ACTIVE", "DRAINING");
private static final Pattern RUNNING_TASKS_COUNT_FILTER = Pattern.compile(
"^\\s*runningTasksCount\\s*(==|!=|>=|<=|>|<|equals|not_equals|greater_than_equal|"
+ "greater_than|less_than_equal|less_than)\\s*(-?\\d+)\\s*$");
/** "A list of up to 10 container instance IDs or full ARN entries." */
private static final int MAX_CONTAINER_INSTANCES_PER_UPDATE = 10;
/** What the agent reports when a registration carried no versionInfo of its own. */
@@ -3640,20 +3645,23 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
}
public List<String> listContainerInstances(String clusterRef, String status, String region) {
return listContainerInstances(clusterRef, status, null, null, region).arns();
return listContainerInstances(clusterRef, status, null, null, null, region).arns();
}
/**
* Lists container instance ARNs. A request that names no status gets every instance other than
* the {@code INACTIVE} ones, which is AWS's documented default rather than everything.
*/
public ListPage listContainerInstances(String clusterRef, String status, Integer maxResults,
String nextToken, String region) {
public ListPage listContainerInstances(String clusterRef, String status, String filter,
Integer maxResults, String nextToken, String region) {
EcsCluster cluster = resolveClusterOrDefault(clusterRef, region);
if (status != null && !CONTAINER_INSTANCE_STATUSES.contains(status)) {
throw new AwsException("InvalidParameterException",
"Invalid container instance status: " + status, 400);
}
LongPredicate query = containerInstanceCountFilter(filter);
Map<String, Long> runningCounts = filter == null ? Map.of()
: runningTaskCountsForClusterArn(cluster.getClusterArn());
String prefix = containerInstanceKey(cluster.getClusterArn(), "");
List<String> arns = containerInstances.entrySet().stream()
.filter(e -> e.getKey().startsWith(prefix))
@@ -3661,11 +3669,67 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
.filter(ci -> status != null
? status.equals(ci.getStatus())
: !STATUS_INACTIVE.equals(ci.getStatus()))
.filter(ci -> query.test(runningCounts.getOrDefault(ci.getContainerInstanceArn(), 0L)))
.map(ContainerInstance::getContainerInstanceArn)
.toList();
return paginate(arns, maxResults, nextToken);
}
long runningTaskCountForInstance(String clusterRef, String instanceArn, String region) {
if (instanceArn == null) {
return 0;
}
String clusterArn = resolveClusterOrDefault(clusterRef, region).getClusterArn();
return tasks.values().stream()
.filter(EcsService::countsTowardRunningTasks)
.filter(task -> clusterArn.equals(task.getClusterArn()))
.filter(task -> instanceArn.equals(task.getContainerInstanceArn()))
.count();
}
Map<String, Long> runningTaskCountsForCluster(String clusterRef, String region) {
return runningTaskCountsForClusterArn(resolveClusterOrDefault(clusterRef, region).getClusterArn());
}
private Map<String, Long> runningTaskCountsForClusterArn(String clusterArn) {
return tasks.values().stream()
.filter(task -> clusterArn.equals(task.getClusterArn()))
.filter(EcsService::countsTowardRunningTasks)
.collect(Collectors.groupingBy(EcsTask::getContainerInstanceArn, Collectors.counting()));
}
private static boolean countsTowardRunningTasks(EcsTask task) {
return task.getContainerInstanceArn() != null
&& TaskStatus.RUNNING.name().equals(task.getDesiredStatus());
}
private static LongPredicate containerInstanceCountFilter(String filter) {
if (filter == null) {
return count -> true;
}
Matcher matcher = RUNNING_TASKS_COUNT_FILTER.matcher(filter);
if (!matcher.matches()) {
throw new AwsException("InvalidParameterException",
"Unsupported or invalid container instance filter: " + filter, 400);
}
long count;
try {
count = Long.parseLong(matcher.group(2));
} catch (NumberFormatException e) {
throw new AwsException("InvalidParameterException",
"Invalid runningTasksCount in container instance filter: " + filter, 400);
}
return switch (matcher.group(1)) {
case "==", "equals" -> running -> running == count;
case "!=", "not_equals" -> running -> running != count;
case ">", "greater_than" -> running -> running > count;
case ">=", "greater_than_equal" -> running -> running >= count;
case "<", "less_than" -> running -> running < count;
case "<=", "less_than_equal" -> running -> running <= count;
default -> throw new IllegalStateException("Unmatched container instance filter operator");
};
}
public ContainerInstance updateContainerAgent(String clusterRef, String instanceRef, String region) {
EcsCluster cluster = resolveClusterOrDefault(clusterRef, region);
ContainerInstance instance = resolveContainerInstanceOrThrow(cluster.getClusterArn(), instanceRef);
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.ecs.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
@@ -9,12 +10,12 @@ import java.util.List;
import java.util.Map;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class ContainerInstance {
private String containerInstanceArn;
private String ec2InstanceId;
private String status;
private int runningTasksCount;
private int pendingTasksCount;
private String statusReason;
private boolean agentConnected;
@@ -38,9 +39,6 @@ public class ContainerInstance {
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public int getRunningTasksCount() { return runningTasksCount; }
public void setRunningTasksCount(int runningTasksCount) { this.runningTasksCount = runningTasksCount; }
public int getPendingTasksCount() { return pendingTasksCount; }
public void setPendingTasksCount(int pendingTasksCount) { this.pendingTasksCount = pendingTasksCount; }
@@ -0,0 +1,212 @@
package io.github.hectorvent.floci.services.ecs;
import io.github.hectorvent.floci.services.ecs.model.EcsTask;
import io.github.hectorvent.floci.testing.AwsTestClients;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.mockito.InjectSpy;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ecs.EcsClient;
import software.amazon.awssdk.services.ecs.model.ListContainerInstancesRequest;
import java.util.List;
import java.util.Set;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@QuarkusTest
class EcsContainerInstanceFilterIntegrationTest {
private static final String TARGET = "AmazonEC2ContainerServiceV20141113.";
@InjectSpy
EcsService service;
@BeforeAll
static void configure() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
private static Response call(String action, String body) {
return call(action, body, 200);
}
private static Response call(String action, String body, int expectedStatus) {
return given().contentType("application/x-amz-json-1.1")
.header("X-Amz-Target", TARGET + action)
.body(body)
.when().post("/")
.then().statusCode(expectedStatus)
.extract().response();
}
@Test
void listContainerInstancesHonorsRunningTaskCountFilter() {
String cluster = "query-filter-running-tasks";
call("CreateCluster", "{\"clusterName\":\"" + cluster + "\"}");
call("RegisterContainerInstance", "{\"cluster\":\"" + cluster + "\"}");
call("ListContainerInstances", "{\"cluster\":\"" + cluster
+ "\",\"filter\":\"runningTasksCount == 1\"}")
.then().body("containerInstanceArns", hasSize(0));
call("ListContainerInstances", "{\"cluster\":\"" + cluster
+ "\",\"filter\":\"runningTasksCount == 0\"}")
.then().body("containerInstanceArns", hasSize(1));
call("ListContainerInstances", "{\"cluster\":\"" + cluster
+ "\",\"filter\":\"runningTasksCount greater_than 0\"}")
.then().body("containerInstanceArns", hasSize(0));
call("ListContainerInstances", "{\"cluster\":\"" + cluster
+ "\",\"filter\":\"runningTasksCount <= 0\"}")
.then().body("containerInstanceArns", hasSize(1));
}
@Test
void filtersBeforePaginatingAndCombinesWithStatus() {
String cluster = "query-filter-pagination";
call("CreateCluster", "{\"clusterName\":\"" + cluster + "\"}");
String first = call("RegisterContainerInstance", "{\"cluster\":\"" + cluster + "\"}")
.jsonPath().getString("containerInstance.containerInstanceArn");
String excluded = call("RegisterContainerInstance", "{\"cluster\":\"" + cluster + "\"}")
.jsonPath().getString("containerInstance.containerInstanceArn");
String last = call("RegisterContainerInstance", "{\"cluster\":\"" + cluster + "\"}")
.jsonPath().getString("containerInstance.containerInstanceArn");
call("RegisterTaskDefinition", "{\"family\":\"query-filter-task\","
+ "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"}]}");
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");
call("DescribeContainerInstances", "{\"cluster\":\"" + cluster
+ "\",\"containerInstances\":[\"" + excluded + "\"]}")
.then().body("containerInstances[0].runningTasksCount", equalTo(1));
call("ListContainerInstances", "{\"cluster\":\"" + cluster
+ "\",\"filter\":\"runningTasksCount == 1\"}")
.then().body("containerInstanceArns", hasSize(1))
.body("containerInstanceArns[0]", equalTo(excluded));
try (EcsClient client = AwsTestClients.create(EcsClient.builder(), "test", Region.US_EAST_1)) {
assertEquals(List.of(excluded), client.listContainerInstances(ListContainerInstancesRequest.builder()
.cluster(cluster).filter("runningTasksCount == 1").build()).containerInstanceArns());
}
EcsTask taskModel = service.describeTasks(cluster, List.of(task), "us-east-1").getFirst();
taskModel.setLastStatus("PENDING");
call("ListContainerInstances", "{\"cluster\":\"" + cluster
+ "\",\"filter\":\"runningTasksCount == 1\"}")
.then().body("containerInstanceArns[0]", equalTo(excluded));
taskModel.setLastStatus("RUNNING");
taskModel.setDesiredStatus("STOPPED");
call("ListContainerInstances", "{\"cluster\":\"" + cluster
+ "\",\"filter\":\"runningTasksCount == 1\"}")
.then().body("containerInstanceArns", hasSize(0));
taskModel.setDesiredStatus("RUNNING");
String request = "{\"cluster\":\"" + cluster
+ "\",\"filter\":\"runningTasksCount == 0\",\"maxResults\":1";
Response firstPage = call("ListContainerInstances", request + "}");
firstPage.then().body("containerInstanceArns", hasSize(1))
.body("nextToken", notNullValue());
String nextToken = firstPage.jsonPath().getString("nextToken");
Response secondPage = call("ListContainerInstances", request
+ ",\"nextToken\":\"" + nextToken + "\"}");
secondPage.then().body("containerInstanceArns", hasSize(1))
.body("nextToken", nullValue());
assertEquals(Set.of(first, last), Set.of(
firstPage.jsonPath().getString("containerInstanceArns[0]"),
secondPage.jsonPath().getString("containerInstanceArns[0]")));
call("UpdateContainerInstancesState", "{\"cluster\":\"" + cluster
+ "\",\"containerInstances\":[\"" + last + "\"],\"status\":\"DRAINING\"}");
call("ListContainerInstances", "{\"cluster\":\"" + cluster
+ "\",\"status\":\"DRAINING\",\"filter\":\"runningTasksCount == 0\"}")
.then().body("containerInstanceArns", hasSize(1))
.body("containerInstanceArns[0]", equalTo(last));
call("StopTask", "{\"cluster\":\"" + cluster + "\",\"task\":\"" + task + "\"}");
call("ListContainerInstances", "{\"cluster\":\"" + cluster
+ "\",\"filter\":\"runningTasksCount == 0\"}")
.then().body("containerInstanceArns", hasSize(3));
call("DescribeContainerInstances", "{\"cluster\":\"" + cluster
+ "\",\"containerInstances\":[\"" + excluded + "\"]}")
.then().body("containerInstances[0].runningTasksCount", equalTo(0));
}
@Test
void describeContainerInstancesDoesNotScanTasksPerInstance() {
String cluster = "query-filter-describe-snapshot";
call("CreateCluster", "{\"clusterName\":\"" + cluster + "\"}");
String running = call("RegisterContainerInstance", "{\"cluster\":\"" + cluster + "\"}")
.jsonPath().getString("containerInstance.containerInstanceArn");
String idle = call("RegisterContainerInstance", "{\"cluster\":\"" + cluster + "\"}")
.jsonPath().getString("containerInstance.containerInstanceArn");
call("RegisterTaskDefinition", "{\"family\":\"query-filter-describe-task\","
+ "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"}]}");
call("StartTask", "{\"cluster\":\"" + cluster + "\","
+ "\"containerInstances\":[\"" + running + "\"],"
+ "\"taskDefinition\":\"query-filter-describe-task\"}");
clearInvocations(service);
call("DescribeContainerInstances", "{\"cluster\":\"" + cluster
+ "\",\"containerInstances\":[\"" + running + "\",\"" + idle + "\"]}")
.then().body("containerInstances", hasSize(2))
.body("containerInstances[0].runningTasksCount", equalTo(1))
.body("containerInstances[1].runningTasksCount", equalTo(0));
verify(service, never()).runningTaskCountForInstance(cluster, running, "us-east-1");
verify(service, never()).runningTaskCountForInstance(cluster, idle, "us-east-1");
verify(service, times(1)).runningTaskCountsForCluster(cluster, "us-east-1");
}
@Test
void describesCountWithinTheRequestedClusterWhenInstanceArnsAreReused() {
String firstCluster = "query-filter-owner-a";
String secondCluster = "query-filter-owner-b";
call("CreateCluster", "{\"clusterName\":\"" + firstCluster + "\"}");
call("CreateCluster", "{\"clusterName\":\"" + secondCluster + "\"}");
String instance = call("RegisterContainerInstance", "{\"cluster\":\"" + firstCluster + "\"}")
.jsonPath().getString("containerInstance.containerInstanceArn");
call("RegisterContainerInstance", "{\"cluster\":\"" + secondCluster
+ "\",\"containerInstanceArn\":\"" + instance + "\"}");
call("RegisterTaskDefinition", "{\"family\":\"query-filter-owner-task\","
+ "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"}]}");
call("StartTask", "{\"cluster\":\"" + firstCluster + "\","
+ "\"containerInstances\":[\"" + instance + "\"],"
+ "\"taskDefinition\":\"query-filter-owner-task\"}");
call("ListContainerInstances", "{\"cluster\":\"" + secondCluster
+ "\",\"filter\":\"runningTasksCount == 0\"}")
.then().body("containerInstanceArns", hasSize(1));
call("DescribeContainerInstances", "{\"cluster\":\"" + secondCluster
+ "\",\"containerInstances\":[\"" + instance + "\"]}")
.then().body("containerInstances[0].runningTasksCount", equalTo(0));
}
@Test
void rejectsUnsupportedAndMalformedFilters() {
String cluster = "query-filter-invalid";
call("CreateCluster", "{\"clusterName\":\"" + cluster + "\"}");
call("ListContainerInstances", "{\"cluster\":\"" + cluster
+ "\",\"filter\":\"runningTasksCount ==\"}", 400)
.then().body("message", containsString("container instance filter"));
call("ListContainerInstances", "{\"cluster\":\"" + cluster
+ "\",\"filter\":\"agentConnected == true\"}", 400)
.then().body("message", containsString("container instance filter"));
call("ListContainerInstances", "{\"cluster\":\"" + cluster
+ "\",\"filter\":\"runningTasksCount == 9223372036854775808\"}", 400)
.then().body("message", containsString("container instance filter"));
}
}
@@ -0,0 +1,39 @@
package io.github.hectorvent.floci.services.ecs;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.storage.PersistentStorage;
import io.github.hectorvent.floci.services.ecs.model.ContainerInstance;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
class EcsContainerInstancePersistenceCompatibilityTest {
@Test
void legacyRunningTaskCountLoadsButIsNotPersistedAgain(@TempDir Path dataDir) throws Exception {
Path file = dataDir.resolve("container-instances.json");
Files.writeString(file, """
{"instance":{"containerInstanceArn":"arn:example:ecs:instance/one",
"status":"ACTIVE","runningTasksCount":3}}
""");
PersistentStorage<String, ContainerInstance> storage = new PersistentStorage<>(file,
new TypeReference<Map<String, ContainerInstance>>() { });
storage.load();
ContainerInstance instance = storage.get("instance").orElseThrow();
assertEquals("arn:example:ecs:instance/one", instance.getContainerInstanceArn());
assertEquals("ACTIVE", instance.getStatus());
storage.flush();
JsonNode saved = new ObjectMapper().readTree(file.toFile()).path("instance");
assertFalse(saved.has("runningTasksCount"), "obsolete count must not be written again");
}
}