Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(ecs): launch service tasks through capacity provider strategies (#5500)

Mohith431748f740a4
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EcsCapacityProviderServiceTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EcsCapacityProviderServiceTest.java
new file mode 100644
index 0000000000..e2db81d7c1
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EcsCapacityProviderServiceTest.java
@@ -0,0 +1,107 @@
+package com.floci.test;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import software.amazon.awssdk.core.waiters.WaiterOverrideConfiguration;
+import software.amazon.awssdk.services.ec2.Ec2Client;
+import software.amazon.awssdk.services.ecs.EcsClient;
+import software.amazon.awssdk.services.ecs.model.CapacityProviderStrategyItem;
+import software.amazon.awssdk.services.ecs.model.Compatibility;
+import software.amazon.awssdk.services.ecs.model.ContainerDefinition;
+import software.amazon.awssdk.services.ecs.model.DescribeServicesRequest;
+import software.amazon.awssdk.services.ecs.model.LaunchType;
+import software.amazon.awssdk.services.ecs.model.NetworkMode;
+import software.amazon.awssdk.services.ecs.model.Service;
+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 java.util.Map;
+import java.util.UUID;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+@DisplayName("ECS services scheduled through capacity providers")
+class EcsCapacityProviderServiceTest {
+
+ private static Stream<Arguments> providerStrategies() {
+ return Stream.of(
+ Arguments.of(List.of(CapacityProviderStrategyItem.builder()
+ .capacityProvider("FARGATE").weight(1).build()),
+ Map.of("FARGATE", 2L), Map.of("FARGATE", 4L)),
+ Arguments.of(List.of(CapacityProviderStrategyItem.builder()
+ .capacityProvider("FARGATE_SPOT").weight(1).build()),
+ Map.of("FARGATE_SPOT", 2L), Map.of("FARGATE_SPOT", 4L)),
+ Arguments.of(List.of(CapacityProviderStrategyItem.builder()
+ .capacityProvider("FARGATE").base(1).weight(0).build(),
+ CapacityProviderStrategyItem.builder()
+ .capacityProvider("FARGATE_SPOT").weight(1).build()),
+ Map.of("FARGATE", 1L, "FARGATE_SPOT", 1L),
+ Map.of("FARGATE", 1L, "FARGATE_SPOT", 3L)));
+ }
+
+ @ParameterizedTest
+ @MethodSource("providerStrategies")
+ void capacityProviderServiceReachesDesiredCountAndScalesOut(
+ List<CapacityProviderStrategyItem> strategy, Map<String, Long> initial, Map<String, Long> scaled) {
+ String name = "sdk-capacity-service-" + UUID.randomUUID().toString().substring(0, 8);
+ try (EcsClient ecs = TestFixtures.ecsClient(); Ec2Client ec2 = TestFixtures.ec2Client()) {
+ String subnet = ec2.describeSubnets().subnets().get(0).subnetId();
+ ecs.createCluster(request -> request.clusterName(name)
+ .capacityProviders(strategy.stream().map(CapacityProviderStrategyItem::capacityProvider).toList()));
+ TaskDefinition definition = ecs.registerTaskDefinition(request -> request.family(name)
+ .networkMode(NetworkMode.AWSVPC).requiresCompatibilities(Compatibility.FARGATE)
+ .cpu("256").memory("512")
+ .containerDefinitions(ContainerDefinition.builder()
+ .name("app").image("alpine:3").memory(128)
+ .command("sleep", "3600").essential(true).build())).taskDefinition();
+ try {
+ ecs.createService(request -> request.cluster(name).serviceName(name)
+ .taskDefinition(definition.taskDefinitionArn()).desiredCount(2)
+ .networkConfiguration(network -> network.awsvpcConfiguration(vpc -> vpc.subnets(subnet)))
+ .capacityProviderStrategy(strategy));
+ try {
+ assertStableProviderCounts(ecs, name, strategy, initial);
+ ecs.updateService(request -> request.cluster(name).service(name).desiredCount(4));
+ assertStableProviderCounts(ecs, name, strategy, scaled);
+ } finally {
+ ecs.deleteService(request -> request.cluster(name).service(name).force(true));
+ }
+ } finally {
+ ecs.deregisterTaskDefinition(request -> request.taskDefinition(definition.taskDefinitionArn()));
+ ecs.deleteCluster(request -> request.cluster(name));
+ }
+ }
+ }
+
+ private static void assertStableProviderCounts(EcsClient ecs, String name,
+ List<CapacityProviderStrategyItem> strategy,
+ Map<String, Long> expected) {
+ DescribeServicesRequest describe = DescribeServicesRequest.builder().cluster(name).services(name).build();
+ assertThat(ecs.waiter().waitUntilServicesStable(describe,
+ WaiterOverrideConfiguration.builder().waitTimeout(Duration.ofSeconds(30)).build())
+ .matched().response()).isPresent();
+
+ int count = expected.values().stream().mapToInt(Long::intValue).sum();
+ Service service = ecs.describeServices(describe).services().get(0);
+ assertThat(service.runningCount()).isEqualTo(count);
+ assertThat(service.pendingCount()).isZero();
+ assertThat(service.launchType()).isNull();
+ assertThat(service.capacityProviderStrategy()).extracting(CapacityProviderStrategyItem::capacityProvider)
+ .containsExactlyElementsOf(strategy.stream().map(CapacityProviderStrategyItem::capacityProvider).toList());
+ List<String> taskArns = ecs.listTasks(request -> request.cluster(name).serviceName(name)).taskArns();
+ assertThat(taskArns).hasSize(count);
+ List<Task> tasks = ecs.describeTasks(request -> request.cluster(name).tasks(taskArns)).tasks();
+ assertThat(tasks).hasSize(count).allSatisfy(task -> {
+ assertThat(task.launchType()).isEqualTo(LaunchType.FARGATE);
+ assertThat(task.lastStatus()).isEqualTo("RUNNING");
+ });
+ assertThat(tasks.stream().collect(Collectors.groupingBy(Task::capacityProviderName, Collectors.counting())))
+ .isEqualTo(expected);
+ }
+}
diff --git a/docs/services/ecs.md b/docs/services/ecs.md
index b6a0754e88..b7e9ad4835 100644
--- a/docs/services/ecs.md
+++ b/docs/services/ecs.md
@@ -304,6 +304,10 @@ provider resolves to. A service reports one or the other: `DescribeServices` omi
for a service created with a strategy, and omits `capacityProviderStrategy` for one created with a
launch type, which is what AWS documents for the `Service` shape.
+Service reconciliation calculates the provider split for the desired task count and fills deficits
+using the current deployment's running tasks. Scale-out and stopped-task replacement account for
+existing provider counts; tasks from a previous deployment do not cover the new deployment's targets.
+
With no launch type, no strategy and no cluster default, a task keeps Floci's `FARGATE` default: a
local cluster has no container instances, so an EC2 default would have nowhere to place it.
diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java
index 2fd6b15e06..71704a8242 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java
@@ -81,6 +81,7 @@ import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
+import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
@@ -1639,24 +1640,24 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
* reconciliation can recognize it as service-owned without trusting the caller-settable
* {@code group}. This is the only path that sets {@code owningServiceArn}.
*/
- private EcsTask launchServiceTask(EcsCluster cluster, EcsServiceModel svc, LaunchType launchType,
+ private EcsTask launchServiceTask(EcsCluster cluster, EcsServiceModel svc, Placement placement,
String containerInstanceArn, String region) {
// Read before the task definition: UpdateService sets it first, so a launch it overtakes is stamped stale.
String deploymentId = deploymentId(svc);
TaskDefinition taskDef = resolveTaskDefinitionOrThrow(svc.getTaskDefinition(), region);
RunTaskRequest request = new RunTaskRequest();
request.setCount(1);
- request.setLaunchType(launchType);
// AWS labels a service's tasks "service:<name>" and attributes them to the deployment.
request.setGroup("service:" + svc.getServiceName());
request.setStartedBy(deploymentId);
request.setNetworkConfiguration(svc.getNetworkConfiguration());
request.setPlatformVersion(svc.getPlatformVersion());
request.setEnableExecuteCommand(svc.isEnableExecuteCommand());
- // A service pinned to a capacity provider places its tasks through it, unless the
- // reconciler is placing a DAEMON task on a named container instance.
- if (containerInstanceArn == null) {
- request.setCapacityProviderStrategy(svc.getCapacityProviderStrategy());
+ if (placement.capacityProviderName() != null) {
+ request.setCapacityProviderStrategy(List.of(
+ new CapacityProviderStrategyItem(placement.capacityProviderName(), 1, 0)));
+ } else {
+ request.setLaunchType(placement.launchType());
}
if (EcsService.PROPAGATE_TAGS_SERVICE.equals(svc.getPropagateTags())) {
request.setTags(svc.getTags());
@@ -1673,6 +1674,31 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
/** Where a task runs: a launch type, or the capacity provider that chose one for it. */
private record Placement(LaunchType launchType, String capacityProviderName) {}
+ /** Fill provider deficits for the current deployment, without counting tasks it is replacing. */
+ private List<Placement> serviceTaskPlacements(EcsServiceModel svc, List<EcsTask> currentTasks, int count) {
+ List<CapacityProviderStrategyItem> strategy = svc.getCapacityProviderStrategy();
+ if (strategy == null || strategy.isEmpty()) {
+ return Collections.nCopies(count, new Placement(svc.getLaunchType(), null));
+ }
+ Map<String, Integer> existing = new HashMap<>();
+ for (EcsTask task : currentTasks) {
+ existing.merge(task.getCapacityProviderName(), 1, Integer::sum);
+ }
+ List<Placement> missing = new ArrayList<>();
+ for (Placement placement : distribute(strategy, svc.getDesiredCount())) {
+ int running = existing.getOrDefault(placement.capacityProviderName(), 0);
+ if (running > 0) {
+ existing.put(placement.capacityProviderName(), running - 1);
+ } else {
+ missing.add(placement);
+ if (missing.size() == count) {
+ break;
+ }
+ }
+ }
+ return missing;
+ }
+
/**
* Decides where each of {@code count} tasks runs, in request order.
*
@@ -5059,7 +5085,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
break;
}
try {
- EcsTask launched = launchServiceTask(cluster, svc, LaunchType.EC2,
+ EcsTask launched = launchServiceTask(cluster, svc, new Placement(LaunchType.EC2, null),
ci.getContainerInstanceArn(), region);
// A Docker start failure comes back already STOPPED: the slot stays uncovered and
// the next tick retries, and it must not count towards runningCount.
@@ -5242,9 +5268,12 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
}
deployment = deploymentRecordForCurrentWorkload(svc);
int toStart = svc.getDesiredCount() - (int) current;
- for (int i = 0; i < toStart; i++) {
+ List<EcsTask> currentTasks = runningTasks.stream()
+ .filter(task -> !isStaleForDeployment(task, currentDeploymentId, currentTaskDefinitionArn))
+ .toList();
+ for (Placement placement : serviceTaskPlacements(svc, currentTasks, toStart)) {
try {
- EcsTask launched = launchServiceTask(cluster, svc, svc.getLaunchType(), null, region);
+ EcsTask launched = launchServiceTask(cluster, svc, placement, null, region);
recordLaunchFailure(svc, null, null);
LOG.infov("Service reconciler started task {0} for service {1}",
launched.getTaskArn(), svc.getServiceName());
diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsFargateTaskIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsFargateTaskIntegrationTest.java
index 373fd4bc8f..8af69d0a98 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsFargateTaskIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsFargateTaskIntegrationTest.java
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.ecs;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
+import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
@@ -32,6 +33,9 @@ class EcsFargateTaskIntegrationTest {
private static final String NETWORK =
"\"networkConfiguration\":{\"awsvpcConfiguration\":{\"subnets\":[\"" + SUBNET + "\"]}}";
+ @Inject
+ EcsService ecsService;
+
@BeforeAll
static void configure() {
RestAssuredJsonUtils.configureAwsContentTypes();
@@ -278,14 +282,32 @@ class EcsFargateTaskIntegrationTest {
}
@Test
- void createServiceOnACapacityProviderStrategyReportsItInsteadOfALaunchType() {
+ void createServiceOnACapacityProviderStrategyStartsTasksAndReportsTheProvider() {
String family = seed("fargate-service-strategy");
call("CreateService", "{\"cluster\":\"" + CLUSTER + "\",\"serviceName\":\"fargate-spot-svc\","
- + "\"taskDefinition\":\"" + family + "\",\"desiredCount\":0," + NETWORK + ","
+ + "\"taskDefinition\":\"" + family + "\",\"desiredCount\":2," + NETWORK + ","
+ "\"capacityProviderStrategy\":[{\"capacityProvider\":\"FARGATE_SPOT\",\"weight\":1}]}", 200)
.then()
.body("service.capacityProviderStrategy[0].capacityProvider", equalTo("FARGATE_SPOT"))
.body("service.capacityProviderStrategy[0].weight", equalTo(1))
.body("service.launchType", nullValue());
+
+ ecsService.reconcileServices();
+ ecsService.reconcileServices();
+ call("DescribeServices", "{\"cluster\":\"" + CLUSTER
+ + "\",\"services\":[\"fargate-spot-svc\"]}", 200)
+ .then()
+ .body("services[0].runningCount", equalTo(2))
+ .body("services[0].pendingCount", equalTo(0))
+ .body("services[0].launchType", nullValue());
+ List<String> taskArns = call("ListTasks", "{\"cluster\":\"" + CLUSTER
+ + "\",\"serviceName\":\"fargate-spot-svc\"}", 200).path("taskArns");
+ assertEquals(2, taskArns.size());
+ call("DescribeTasks", "{\"cluster\":\"" + CLUSTER + "\",\"tasks\":[\""
+ + String.join("\",\"", taskArns) + "\"]}", 200)
+ .then()
+ .body("tasks.capacityProviderName", equalTo(List.of("FARGATE_SPOT", "FARGATE_SPOT")))
+ .body("tasks.launchType", equalTo(List.of("FARGATE", "FARGATE")))
+ .body("tasks.lastStatus", equalTo(List.of("RUNNING", "RUNNING")));
}
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceRolloutTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceRolloutTest.java
index a494c0e299..7a58881ab0 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceRolloutTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceRolloutTest.java
@@ -7,17 +7,25 @@ import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ecs.container.EcsContainerManager;
+import io.github.hectorvent.floci.services.ecs.model.CapacityProviderStrategyItem;
import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
+import io.github.hectorvent.floci.services.ecs.model.CreateServiceRequest;
import io.github.hectorvent.floci.services.ecs.model.EcsServiceModel;
import io.github.hectorvent.floci.services.ecs.model.EcsTask;
import io.github.hectorvent.floci.services.ecs.model.LaunchType;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import io.github.hectorvent.floci.services.ecs.model.TaskStatus;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
@@ -42,6 +50,99 @@ class EcsServiceRolloutTest {
private static final String REGION = "us-east-1";
+ private static Stream<Arguments> mixedCapacityProviderStrategies() {
+ return Stream.of(
+ Arguments.of(List.of(new CapacityProviderStrategyItem("FARGATE", 1, 0),
+ new CapacityProviderStrategyItem("FARGATE_SPOT", 1, 0)),
+ Map.of("FARGATE", 1L, "FARGATE_SPOT", 1L),
+ Map.of("FARGATE", 2L, "FARGATE_SPOT", 2L)),
+ Arguments.of(List.of(new CapacityProviderStrategyItem("FARGATE", 0, 1),
+ new CapacityProviderStrategyItem("FARGATE_SPOT", 1, 0)),
+ Map.of("FARGATE", 1L, "FARGATE_SPOT", 1L),
+ Map.of("FARGATE", 1L, "FARGATE_SPOT", 5L)),
+ Arguments.of(List.of(new CapacityProviderStrategyItem("FARGATE", 1, 1),
+ new CapacityProviderStrategyItem("FARGATE_SPOT", 3, 0)),
+ Map.of("FARGATE", 2L, "FARGATE_SPOT", 3L),
+ Map.of("FARGATE", 3L, "FARGATE_SPOT", 6L)));
+ }
+
+ @ParameterizedTest
+ @MethodSource("mixedCapacityProviderStrategies")
+ void mixedProviderServicesKeepTheirSplitOnScaleOutReplacementAndRollout(
+ List<CapacityProviderStrategyItem> strategy, Map<String, Long> initial, Map<String, Long> scaled) {
+ EcsService service = newMockModeService();
+ service.createCluster("roll-cluster", REGION);
+ registerTaskDef(service, "roll-fam", "app:1");
+ CreateServiceRequest request = new CreateServiceRequest();
+ request.setCluster("roll-cluster");
+ request.setServiceName("roll-svc");
+ request.setTaskDefinition("roll-fam");
+ request.setDesiredCount(initial.values().stream().mapToInt(Long::intValue).sum());
+ request.setCapacityProviderStrategy(strategy);
+ service.createService(request, REGION);
+
+ service.reconcileServices();
+ assertEquals(initial, providerCounts(service));
+
+ service.updateService("roll-cluster", "roll-svc", null,
+ scaled.values().stream().mapToInt(Long::intValue).sum(), null, REGION);
+ service.reconcileServices();
+ assertEquals(scaled, providerCounts(service));
+
+ for (String provider : scaled.keySet()) {
+ EcsTask stopped = runningTasks(service).stream()
+ .filter(task -> provider.equals(task.getCapacityProviderName())).findFirst().orElseThrow();
+ service.stopTask("roll-cluster", stopped.getTaskArn(), "replacement test", REGION);
+ service.reconcileServices();
+ assertEquals(scaled, providerCounts(service));
+ assertTrue(runningTasks(service).stream().noneMatch(task -> task.getTaskArn().equals(stopped.getTaskArn())));
+ }
+
+ TaskDefinition revision = registerTaskDef(service, "roll-fam", "app:2");
+ service.updateService("roll-cluster", "roll-svc", revision.getTaskDefinitionArn(), null, null, REGION);
+ service.reconcileServices();
+ service.reconcileServices();
+ assertEquals(scaled, providerCounts(service));
+ assertTrue(runningTasks(service).stream()
+ .allMatch(task -> revision.getTaskDefinitionArn().equals(task.getTaskDefinitionArn())));
+ }
+
+ private static Map<String, Long> providerCounts(EcsService service) {
+ return runningTasks(service).stream()
+ .collect(Collectors.groupingBy(EcsTask::getCapacityProviderName, Collectors.counting()));
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"FARGATE", "FARGATE_SPOT"})
+ void capacityProviderServiceStartsAndReplacesStoppedTasks(String provider) {
+ EcsService service = newMockModeService();
+ service.createCluster("roll-cluster", REGION);
+ registerTaskDef(service, "roll-fam", "app:1");
+ CreateServiceRequest request = new CreateServiceRequest();
+ request.setCluster("roll-cluster");
+ request.setServiceName("roll-svc");
+ request.setTaskDefinition("roll-fam");
+ request.setDesiredCount(2);
+ request.setCapacityProviderStrategy(List.of(new CapacityProviderStrategyItem(provider, 1, 0)));
+ EcsServiceModel svc = service.createService(request, REGION);
+
+ service.reconcileServices();
+ List<EcsTask> first = runningTasks(service);
+ assertEquals(2, first.size());
+ for (EcsTask task : first) {
+ assertEquals(provider, task.getCapacityProviderName());
+ assertEquals(LaunchType.FARGATE, task.getLaunchType());
+ assertEquals(svc.getServiceArn(), task.getOwningServiceArn());
+ }
+
+ service.stopTask("roll-cluster", first.getFirst().getTaskArn(), "replacement test", REGION);
+ service.reconcileServices();
+ List<EcsTask> after = runningTasks(service);
+ assertEquals(2, after.size());
+ assertTrue(after.stream().noneMatch(task -> task.getTaskArn().equals(first.getFirst().getTaskArn())));
+ assertTrue(after.stream().allMatch(task -> provider.equals(task.getCapacityProviderName())));
+ }
+
@Test
void updatedTaskDefinitionReplacesRunningTasksReplacementsFirst() {
EcsService service = newMockModeService();