Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(ecs): report schedulingStrategy, deploymentController and availabilityZoneRebalancing on services (#2482)

hisham-coder13664e76935b
diff --git a/docs/services/ecs.md b/docs/services/ecs.md
index e4b946efca..5164a27c5c 100644
--- a/docs/services/ecs.md
+++ b/docs/services/ecs.md
@@ -81,8 +81,13 @@ Known differences from AWS:
revision start first, then the stale tasks are drained, one reconciler tick apart), but
the deployments list reports only the single `PRIMARY` throughout.
- `deployments` is reported for every service. AWS omits it for services that use the
- `CODE_DEPLOY` or `EXTERNAL` deployment controller, but Floci does not yet record
- `deploymentController`, and `ECS` is the AWS default.
+ `CODE_DEPLOY` or `EXTERNAL` deployment controller; Floci records and echoes
+ `deploymentController` (along with `schedulingStrategy` and
+ `availabilityZoneRebalancing`; AWS defaults `ECS` / `REPLICA` / `ENABLED` on create) but
+ still synthesises the `deployments` list regardless of the controller type.
+- `DAEMON` scheduling runs exactly one task per `ACTIVE` container instance and derives
+ `desiredCount` from that count; it is rejected for the Fargate launch type and for the
+ `CODE_DEPLOY` / `EXTERNAL` controllers, as on AWS. Placement constraints are not evaluated.
- `pendingCount` is always `0`, matching the top-level service field.
- `forceNewDeployment` does not mint a new deployment `id`.
- `updatedAt` equals `createdAt`. AWS advances it as a rollout progresses; Floci has no
diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandler.java
index ee9ad50db8..744af30a23 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandler.java
@@ -45,6 +45,7 @@ import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import java.util.Set;
@ApplicationScoped
public class EcsJsonHandler {
@@ -403,9 +404,14 @@ public class EcsJsonHandler {
List<EcsLoadBalancer> loadBalancers = parseLoadBalancers(req.path("loadBalancers"));
NetworkConfiguration networkConfiguration = parseNetworkConfiguration(req.path("networkConfiguration"));
Map<String, String> tags = parseTagMap(req.path("tags"));
+ String schedulingStrategy = parseChoice(req, "schedulingStrategy", SCHEDULING_STRATEGIES);
+ String deploymentControllerType = parseChoice(req.path("deploymentController"), "type",
+ "deploymentController.type", DEPLOYMENT_CONTROLLER_TYPES);
+ String availabilityZoneRebalancing = parseChoice(req, "availabilityZoneRebalancing", AZ_REBALANCING);
EcsServiceModel svc = service.createService(cluster, serviceName, taskDefinition,
- desiredCount, launchType, loadBalancers, networkConfiguration, tags, region);
+ desiredCount, launchType, loadBalancers, networkConfiguration, tags,
+ schedulingStrategy, deploymentControllerType, availabilityZoneRebalancing, region);
ObjectNode resp = objectMapper.createObjectNode();
resp.set("service", serviceNode(svc));
@@ -480,9 +486,10 @@ public class EcsJsonHandler {
String taskDefinition = req.has("taskDefinition") ? req.path("taskDefinition").asText() : null;
Integer desiredCount = req.has("desiredCount") ? req.path("desiredCount").asInt() : null;
NetworkConfiguration networkConfiguration = parseNetworkConfiguration(req.path("networkConfiguration"));
+ String availabilityZoneRebalancing = parseChoice(req, "availabilityZoneRebalancing", AZ_REBALANCING);
EcsServiceModel svc = service.updateService(cluster, serviceName, taskDefinition, desiredCount,
- networkConfiguration, region);
+ networkConfiguration, availabilityZoneRebalancing, region);
ObjectNode resp = objectMapper.createObjectNode();
resp.set("service", serviceNode(svc));
@@ -1162,6 +1169,28 @@ public class EcsJsonHandler {
return n;
}
+ private static final Set<String> SCHEDULING_STRATEGIES = Set.of("REPLICA", "DAEMON");
+ private static final Set<String> DEPLOYMENT_CONTROLLER_TYPES = Set.of("ECS", "CODE_DEPLOY", "EXTERNAL");
+ private static final Set<String> AZ_REBALANCING = Set.of("ENABLED", "DISABLED");
+
+ /** Optional enum-valued string field: absent → {@code null}; present but not in {@code allowed} → 400. */
+ private static String parseChoice(JsonNode node, String field, Set<String> allowed) {
+ return parseChoice(node, field, field, allowed);
+ }
+
+ private static String parseChoice(JsonNode node, String field, String displayName, Set<String> allowed) {
+ if (node == null || node.isMissingNode() || !node.hasNonNull(field)) {
+ return null;
+ }
+ String value = node.path(field).asText();
+ if (!allowed.contains(value)) {
+ throw new AwsException("InvalidParameterException",
+ "Invalid " + displayName + ": " + value + ". Valid values: "
+ + String.join(", ", new java.util.TreeSet<>(allowed)) + ".", 400);
+ }
+ return value;
+ }
+
private ObjectNode serviceNode(EcsServiceModel s) {
ObjectNode n = objectMapper.createObjectNode();
n.put("serviceArn", s.getServiceArn());
@@ -1175,6 +1204,13 @@ public class EcsJsonHandler {
if (s.getLaunchType() != null) { n.put("launchType", s.getLaunchType().name()); }
if (s.getCreatedAt() != null) { n.put("createdAt", s.getCreatedAt().toEpochMilli() / 1000.0); }
if (s.getNamespace() != null) { n.put("namespace", s.getNamespace()); }
+ // Services persisted before these fields existed read back with the AWS defaults.
+ n.put("schedulingStrategy", s.getSchedulingStrategy() != null
+ ? s.getSchedulingStrategy() : EcsService.DEFAULT_SCHEDULING_STRATEGY);
+ n.putObject("deploymentController").put("type", s.getDeploymentController() != null
+ ? s.getDeploymentController() : EcsService.DEFAULT_DEPLOYMENT_CONTROLLER);
+ n.put("availabilityZoneRebalancing", s.getAvailabilityZoneRebalancing() != null
+ ? s.getAvailabilityZoneRebalancing() : EcsService.DEFAULT_AZ_REBALANCING_UNSET);
if (s.getTags() != null && !s.getTags().isEmpty()) {
n.set("tags", tagsNode(s.getTags()));
}
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 ef3e3d5cd7..5fecde8bc9 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
@@ -42,6 +42,10 @@ import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.Set;
+import java.util.Comparator;
+import java.util.HashSet;
import java.util.UUID;
import java.util.function.Function;
@@ -54,7 +58,6 @@ import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
-import java.util.Set;
@ApplicationScoped
public class EcsService implements ContainerTeardown, ResourceProvider {
@@ -83,6 +86,14 @@ public class EcsService implements ContainerTeardown, ResourceProvider {
private final Map<String, EcsTaskHandle> taskHandles = new ConcurrentHashMap<>();
// region::clusterName/serviceName → EcsServiceModel
private Map<String, EcsServiceModel> services = new ConcurrentHashMap<>();
+
+ public static final String DEFAULT_SCHEDULING_STRATEGY = "REPLICA";
+ public static final String SCHEDULING_DAEMON = "DAEMON";
+ public static final String DEFAULT_DEPLOYMENT_CONTROLLER = "ECS";
+ /** CreateService defaults availabilityZoneRebalancing to ENABLED when omitted. */
+ public static final String DEFAULT_AZ_REBALANCING_ON_CREATE = "ENABLED";
+ /** A service that never had a value (persisted before the field existed) reads as DISABLED. */
+ public static final String DEFAULT_AZ_REBALANCING_UNSET = "DISABLED";
// region::clusterArn/instanceArn → ContainerInstance
private final Map<String, ContainerInstance> containerInstances = new ConcurrentHashMap<>();
// name → CapacityProvider (excludes built-ins FARGATE, FARGATE_SPOT)
@@ -697,6 +708,22 @@ public class EcsService implements ContainerTeardown, ResourceProvider {
List<EcsLoadBalancer> loadBalancers,
NetworkConfiguration networkConfiguration,
Map<String, String> tags, String region) {
+ return createService(clusterRef, serviceName, taskDefinition, desiredCount, launchType,
+ loadBalancers, networkConfiguration, tags, null, null, null, region);
+ }
+
+ /**
+ * @param schedulingStrategy {@code REPLICA} (default) or {@code DAEMON}
+ * @param deploymentControllerType {@code ECS} (default), {@code CODE_DEPLOY} or {@code EXTERNAL}
+ * @param availabilityZoneRebalancing {@code ENABLED} or {@code DISABLED} (default)
+ */
+ public EcsServiceModel createService(String clusterRef, String serviceName, String taskDefinition,
+ int desiredCount, LaunchType launchType,
+ List<EcsLoadBalancer> loadBalancers,
+ NetworkConfiguration networkConfiguration,
+ Map<String, String> tags, String schedulingStrategy,
+ String deploymentControllerType, String availabilityZoneRebalancing,
+ String region) {
EcsCluster cluster = resolveClusterOrDefault(clusterRef, region);
// AWS resolves family / family:revision at create time and stores the ARN; the
// reconciler compares it with each task's taskDefinitionArn, so pin it here.
@@ -725,6 +752,22 @@ public class EcsService implements ContainerTeardown, ResourceProvider {
svc.setDesiredCount(desiredCount);
svc.setLoadBalancers(loadBalancers);
svc.setNetworkConfiguration(networkConfiguration);
+ // AWS echoes these on every DescribeServices; clients that persist them (Terraform's
+ // aws_ecs_service reads all three, and schedulingStrategy is ForceNew) treat a missing
+ // value as drift and replace the service on every apply.
+ String strategy = schedulingStrategy != null ? schedulingStrategy : DEFAULT_SCHEDULING_STRATEGY;
+ String controller = deploymentControllerType != null
+ ? deploymentControllerType : DEFAULT_DEPLOYMENT_CONTROLLER;
+ if (SCHEDULING_DAEMON.equals(strategy)
+ && (svc.getLaunchType() == LaunchType.FARGATE || !DEFAULT_DEPLOYMENT_CONTROLLER.equals(controller))) {
+ throw new AwsException("InvalidParameterException",
+ "Tasks using the Fargate launch type or the CODE_DEPLOY or EXTERNAL deployment "
+ + "controller types don't support the DAEMON scheduling strategy.", 400);
+ }
+ svc.setSchedulingStrategy(strategy);
+ svc.setDeploymentController(controller);
+ svc.setAvailabilityZoneRebalancing(availabilityZoneRebalancing != null
+ ? availabilityZoneRebalancing : DEFAULT_AZ_REBALANCING_ON_CREATE);
svc.setStatus("ACTIVE");
svc.setCreatedAt(Instant.now());
svc.setLastDeploymentAt(svc.getCreatedAt());
@@ -743,6 +786,13 @@ public class EcsService implements ContainerTeardown, ResourceProvider {
public EcsServiceModel updateService(String clusterRef, String serviceName, String taskDefinition,
Integer desiredCount, NetworkConfiguration networkConfiguration,
String region) {
+ return updateService(clusterRef, serviceName, taskDefinition, desiredCount, networkConfiguration,
+ null, region);
+ }
+
+ public EcsServiceModel updateService(String clusterRef, String serviceName, String taskDefinition,
+ Integer desiredCount, NetworkConfiguration networkConfiguration,
+ String availabilityZoneRebalancing, String region) {
EcsCluster cluster = resolveClusterOrDefault(clusterRef, region);
serviceName = extractServiceName(serviceName);
@@ -765,6 +815,9 @@ public class EcsService implements ContainerTeardown, ResourceProvider {
if (networkConfiguration != null) {
svc.setNetworkConfiguration(networkConfiguration);
}
+ if (availabilityZoneRebalancing != null) {
+ svc.setAvailabilityZoneRebalancing(availabilityZoneRebalancing);
+ }
if (taskDefinition != null) {
taskDefinition = resolveTaskDefinitionOrThrow(taskDefinition, region).getTaskDefinitionArn();
svc.setTaskDefinition(taskDefinition);
@@ -1513,6 +1566,97 @@ public class EcsService implements ContainerTeardown, ResourceProvider {
}
}
+ /**
+ * DAEMON scheduling: exactly one task on each ACTIVE container instance of the cluster,
+ * none anywhere else. {@code desiredCount} is derived from the instance count, as AWS
+ * reports it; {@code runningCount} counts only tasks that are actually RUNNING.
+ * Placement constraints are not evaluated.
+ */
+ private void reconcileDaemonService(String key, EcsServiceModel svc, String clusterName, String region) {
+ EcsCluster cluster = resolveClusterOrDefault(clusterName, region);
+ String prefix = containerInstanceKey(cluster.getClusterArn(), "");
+ List<ContainerInstance> activeInstances = containerInstances.entrySet().stream()
+ .filter(e -> e.getKey().startsWith(prefix))
+ .map(Map.Entry::getValue)
+ .filter(ci -> "ACTIVE".equals(ci.getStatus()))
+ .toList();
+ Set<String> activeArns = activeInstances.stream()
+ .map(ContainerInstance::getContainerInstanceArn)
+ .collect(Collectors.toSet());
+
+ // Every task that still occupies its instance: RUNNING, PENDING (Docker start in
+ // flight) and STOPPING (teardown in flight, possibly stranded). Only STOPPED frees the
+ // slot — otherwise a stranded STOPPING task would get a duplicate next to it.
+ // RUNNING tasks are preferred as the instance's daemon when there are several.
+ List<EcsTask> liveTasks = tasks.values().stream()
+ .filter(t -> t.getClusterArn().endsWith(":cluster/" + clusterName))
+ .filter(t -> svc.getServiceArn().equals(t.getGroup())
+ || svc.getServiceName().equals(t.getGroup()))
+ .filter(t -> !TaskStatus.STOPPED.name().equals(t.getLastStatus()))
+ .sorted(Comparator.comparingInt(t -> daemonTaskRank(t.getLastStatus())))
+ .toList();
+
+ Set<String> covered = new HashSet<>();
+ int running = 0;
+ for (EcsTask t : liveTasks) {
+ String instanceArn = t.getContainerInstanceArn();
+ boolean keep = instanceArn != null && activeArns.contains(instanceArn) && covered.add(instanceArn);
+ if (keep) {
+ if (TaskStatus.RUNNING.name().equals(t.getLastStatus())) {
+ running++;
+ }
+ continue;
+ }
+ if (TaskStatus.STOPPING.name().equals(t.getLastStatus())) {
+ continue; // teardown already in flight
+ }
+ try {
+ stopTask(clusterName, t.getTaskArn(), instanceArn == null || !activeArns.contains(instanceArn)
+ ? "Daemon task's container instance is no longer active"
+ : "Daemon service already has a task on this container instance", region);
+ } catch (Exception e) {
+ LOG.warnv("Service reconciler failed to stop daemon task {0}: {1}", t.getTaskArn(), e.getMessage());
+ }
+ }
+ for (ContainerInstance ci : activeInstances) {
+ if (covered.contains(ci.getContainerInstanceArn())) {
+ continue;
+ }
+ try {
+ TaskDefinition taskDef = resolveTaskDefinitionOrThrow(svc.getTaskDefinition(), region);
+ EcsTask launched = launchTasks(cluster, taskDef, 1, LaunchType.EC2,
+ svc.getServiceName(), "ecs-svc", ci.getContainerInstanceArn(), null,
+ svc.getNetworkConfiguration(), region).getFirst();
+ // A Docker start failure comes back already STOPPED: the slot stays uncovered and
+ // the next tick retries, and it must not count towards runningCount.
+ if (!TaskStatus.STOPPED.name().equals(launched.getLastStatus())) {
+ covered.add(ci.getContainerInstanceArn());
+ if (TaskStatus.RUNNING.name().equals(launched.getLastStatus())) {
+ running++;
+ }
+ LOG.infov("Service reconciler started daemon task {0} for service {1} on {2}",
+ launched.getTaskArn(), svc.getServiceName(), ci.getContainerInstanceArn());
+ }
+ } catch (Exception e) {
+ LOG.warnv("Service reconciler failed to start daemon task for {0}: {1}",
+ svc.getServiceName(), e.getMessage());
+ }
+ }
+ svc.setDesiredCount(activeInstances.size());
+ svc.setRunningCount(running);
+ services.put(key, svc);
+ }
+
+ private static int daemonTaskRank(String lastStatus) {
+ if (TaskStatus.RUNNING.name().equals(lastStatus)) {
+ return 0;
+ }
+ if (TaskStatus.PENDING.name().equals(lastStatus)) {
+ return 1;
+ }
+ return 2;
+ }
+
/**
* The service's task definition as an ARN. Services created before the ARN was pinned at
* create/update time may still hold a raw {@code family} / {@code family:revision}
@@ -1553,6 +1697,11 @@ public class EcsService implements ContainerTeardown, ResourceProvider {
String region = extractRegionFromServiceKey(key);
String clusterName = extractClusterNameFromServiceKey(key);
+ if (SCHEDULING_DAEMON.equals(svc.getSchedulingStrategy())) {
+ reconcileDaemonService(key, svc, clusterName, region);
+ return;
+ }
+
List<EcsTask> runningTasks = tasks.values().stream()
.filter(t -> t.getClusterArn().endsWith(":cluster/" + clusterName))
.filter(t -> svc.getServiceArn().equals(t.getGroup())
diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsServiceModel.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsServiceModel.java
index 39eb4a4033..f50130b372 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsServiceModel.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsServiceModel.java
@@ -25,6 +25,8 @@ public class EcsServiceModel {
private Instant lastDeploymentAt;
private String namespace;
private String deploymentController;
+ private String schedulingStrategy;
+ private String availabilityZoneRebalancing;
private Map<String, String> tags = new HashMap<>();
private List<EcsLoadBalancer> loadBalancers = new ArrayList<>();
private NetworkConfiguration networkConfiguration;
@@ -67,6 +69,14 @@ public class EcsServiceModel {
public String getDeploymentController() { return deploymentController; }
public void setDeploymentController(String deploymentController) { this.deploymentController = deploymentController; }
+ public String getSchedulingStrategy() { return schedulingStrategy; }
+ public void setSchedulingStrategy(String schedulingStrategy) { this.schedulingStrategy = schedulingStrategy; }
+
+ public String getAvailabilityZoneRebalancing() { return availabilityZoneRebalancing; }
+ public void setAvailabilityZoneRebalancing(String availabilityZoneRebalancing) {
+ this.availabilityZoneRebalancing = availabilityZoneRebalancing;
+ }
+
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags; }
diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsDescribeServicesIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsDescribeServicesIntegrationTest.java
index 367f237ce2..9db0b6c0a8 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsDescribeServicesIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsDescribeServicesIntegrationTest.java
@@ -9,6 +9,7 @@ import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.endsWith;
+import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.startsWith;
@@ -239,4 +240,72 @@ class EcsDescribeServicesIntegrationTest {
.body("services[0].status", equalTo("INACTIVE"))
.body("services[0].deployments", hasSize(0));
}
+
+ @Test
+ void describeServicesReportsAwsDefaultsForSchedulingDeploymentControllerAndAzRebalancing() {
+ // AWS always echoes these three; Terraform's aws_ecs_service reads all of them and
+ // schedulingStrategy is ForceNew, so a missing value replaced the service on every apply.
+ seedClusterAndTaskDef("dep-cluster-20", "dep-td-20");
+ call("CreateService", "{\"cluster\":\"dep-cluster-20\",\"serviceName\":\"dep-svc-20\","
+ + "\"taskDefinition\":\"dep-td-20\",\"desiredCount\":0}");
+
+ // CreateService defaults availabilityZoneRebalancing to ENABLED (API reference); only a
+ // service that never had a value reads as DISABLED.
+ describe("dep-cluster-20", "dep-svc-20").then()
+ .body("services[0].schedulingStrategy", equalTo("REPLICA"))
+ .body("services[0].deploymentController.type", equalTo("ECS"))
+ .body("services[0].availabilityZoneRebalancing", equalTo("ENABLED"));
+ }
+
+ @Test
+ void createServiceRejectsDaemonOnFargateAndNonEcsControllers() {
+ seedClusterAndTaskDef("dep-cluster-23", "dep-td-23");
+ given().contentType(CT).header("X-Amz-Target", TARGET + "CreateService")
+ .body("{\"cluster\":\"dep-cluster-23\",\"serviceName\":\"dep-svc-23\","
+ + "\"taskDefinition\":\"dep-td-23\",\"schedulingStrategy\":\"DAEMON\"}")
+ .when().post("/")
+ .then().statusCode(400)
+ .body("__type", containsString("InvalidParameterException"))
+ .body("message", containsString("DAEMON"));
+ given().contentType(CT).header("X-Amz-Target", TARGET + "CreateService")
+ .body("{\"cluster\":\"dep-cluster-23\",\"serviceName\":\"dep-svc-23b\","
+ + "\"taskDefinition\":\"dep-td-23\",\"launchType\":\"EC2\","
+ + "\"schedulingStrategy\":\"DAEMON\",\"deploymentController\":{\"type\":\"EXTERNAL\"}}")
+ .when().post("/")
+ .then().statusCode(400)
+ .body("__type", containsString("InvalidParameterException"));
+ }
+
+ @Test
+ void createAndUpdateServiceEchoExplicitSchedulingDeploymentControllerAndAzRebalancing() {
+ seedClusterAndTaskDef("dep-cluster-21", "dep-td-21");
+ call("CreateService", "{\"cluster\":\"dep-cluster-21\",\"serviceName\":\"dep-svc-21\","
+ + "\"taskDefinition\":\"dep-td-21\",\"desiredCount\":0,\"launchType\":\"EC2\","
+ + "\"schedulingStrategy\":\"DAEMON\",\"deploymentController\":{\"type\":\"ECS\"},"
+ + "\"availabilityZoneRebalancing\":\"DISABLED\"}")
+ .then()
+ .body("service.schedulingStrategy", equalTo("DAEMON"))
+ .body("service.deploymentController.type", equalTo("ECS"))
+ .body("service.availabilityZoneRebalancing", equalTo("DISABLED"));
+
+ call("UpdateService", "{\"cluster\":\"dep-cluster-21\",\"service\":\"dep-svc-21\","
+ + "\"availabilityZoneRebalancing\":\"ENABLED\"}");
+
+ describe("dep-cluster-21", "dep-svc-21").then()
+ .body("services[0].schedulingStrategy", equalTo("DAEMON"))
+ .body("services[0].deploymentController.type", equalTo("ECS"))
+ .body("services[0].availabilityZoneRebalancing", equalTo("ENABLED"));
+ }
+
+ @Test
+ void createServiceRejectsUnknownSchedulingStrategy() {
+ seedClusterAndTaskDef("dep-cluster-22", "dep-td-22");
+ given().contentType(CT).header("X-Amz-Target", TARGET + "CreateService")
+ .body("{\"cluster\":\"dep-cluster-22\",\"serviceName\":\"dep-svc-22\","
+ + "\"taskDefinition\":\"dep-td-22\",\"desiredCount\":0,"
+ + "\"schedulingStrategy\":\"SOMETIMES\"}")
+ .when().post("/")
+ .then().statusCode(400)
+ .body("__type", containsString("InvalidParameterException"));
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceDaemonSchedulingTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceDaemonSchedulingTest.java
new file mode 100644
index 0000000000..ea4b45967a
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceDaemonSchedulingTest.java
@@ -0,0 +1,185 @@
+package io.github.hectorvent.floci.services.ecs;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+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.ContainerDefinition;
+import io.github.hectorvent.floci.services.ecs.model.ContainerInstance;
+import io.github.hectorvent.floci.services.ecs.model.EcsTask;
+import io.github.hectorvent.floci.services.ecs.model.LaunchType;
+import org.junit.jupiter.api.Test;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+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.mock;
+import static org.mockito.Mockito.when;
+
+/** DAEMON scheduling: one task per ACTIVE container instance, nothing else. */
+class EcsServiceDaemonSchedulingTest {
+
+ private static final String REGION = "us-east-1";
+
+ @Test
+ void daemonServiceRunsExactlyOneTaskPerActiveContainerInstance() {
+ EcsService service = newMockModeService();
+ service.createCluster("daemon-cluster", REGION);
+ ContainerInstance a = service.registerContainerInstance("daemon-cluster", null, List.of(), REGION);
+ ContainerInstance b = service.registerContainerInstance("daemon-cluster", null, List.of(), REGION);
+ registerTaskDef(service);
+ service.createService("daemon-cluster", "daemon-svc", "daemon-fam", 1, LaunchType.EC2,
+ List.of(), null, null, "DAEMON", null, null, REGION);
+
+ service.reconcileServices();
+ service.reconcileServices();
+
+ List<EcsTask> running = runningTasks(service);
+ assertEquals(2, running.size());
+ assertEquals(Set.of(a.getContainerInstanceArn(), b.getContainerInstanceArn()),
+ running.stream().map(EcsTask::getContainerInstanceArn).collect(Collectors.toSet()));
+ var svc = service.describeServices("daemon-cluster", List.of("daemon-svc"), REGION).getFirst();
+ assertEquals(2, svc.getDesiredCount(), "desiredCount follows the instance count, as AWS reports it");
+ assertEquals(2, svc.getRunningCount());
+
+ // A drained instance loses its daemon task; a new one gains one.
+ service.updateContainerInstancesState("daemon-cluster", List.of(a.getContainerInstanceArn()), "DRAINING", REGION);
+ ContainerInstance c = service.registerContainerInstance("daemon-cluster", null, List.of(), REGION);
+ service.reconcileServices();
+
+ running = runningTasks(service);
+ assertEquals(2, running.size());
+ assertEquals(Set.of(b.getContainerInstanceArn(), c.getContainerInstanceArn()),
+ running.stream().map(EcsTask::getContainerInstanceArn).collect(Collectors.toSet()));
+ }
+
+ @Test
+ void failedDaemonLaunchDoesNotCountAsRunningAndIsRetried() {
+ // Docker mode with a container manager that refuses to start anything: launchTasks
+ // hands back a task already STOPPED. That must neither cover the instance nor count
+ // towards runningCount, or ServicesStable would be satisfied by a dead daemon.
+ EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
+ when(config.services().ecs().mock()).thenReturn(false);
+ when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
+ EcsContainerManager containerManager = mock(EcsContainerManager.class);
+ when(containerManager.startTask(any(), any(), any(), anyString()))
+ .thenThrow(new RuntimeException("no docker here"));
+ EcsService service = new EcsService(new RegionResolver(REGION, "000000000000"), containerManager,
+ config, mock(EcsLoadBalancerRegistrar.class), new InMemoryStorageFactory());
+ service.initializeStorage();
+ service.createCluster("daemon-fail", REGION);
+ service.registerContainerInstance("daemon-fail", null, List.of(), REGION);
+ registerTaskDef(service);
+ service.createService("daemon-fail", "daemon-svc", "daemon-fam", 1, LaunchType.EC2,
+ List.of(), null, null, "DAEMON", null, null, REGION);
+
+ service.reconcileServices();
+ var svc = service.describeServices("daemon-fail", List.of("daemon-svc"), REGION).getFirst();
+ assertEquals(1, svc.getDesiredCount());
+ assertEquals(0, svc.getRunningCount(), "a task that failed to start is not running");
+ assertEquals(0, runningTasks(service).size());
+
+ service.reconcileServices();
+ long attempts = service.describeTasks(null, service.listTasks(null, null, null, null, REGION), REGION).size();
+ assertEquals(2, attempts, "the uncovered instance is retried on the next tick");
+ }
+
+ @Test
+ void strandedStoppingDaemonTaskStillHoldsItsInstance() {
+ EcsService service = newMockModeService();
+ service.createCluster("daemon-stopping", REGION);
+ ContainerInstance a = service.registerContainerInstance("daemon-stopping", null, List.of(), REGION);
+ registerTaskDef(service);
+ service.createService("daemon-stopping", "daemon-svc", "daemon-fam", 1, LaunchType.EC2,
+ List.of(), null, null, "DAEMON", null, null, REGION);
+ service.reconcileServices();
+ EcsTask task = runningTasks(service).getFirst();
+ assertEquals(a.getContainerInstanceArn(), task.getContainerInstanceArn());
+
+ // Teardown in flight (or stranded there): the slot is still taken, no duplicate.
+ task.setLastStatus("STOPPING");
+ service.reconcileServices();
+ List<EcsTask> all = service.describeTasks(null, service.listTasks(null, null, null, null, REGION), REGION);
+ assertEquals(1, all.size(), "no replacement next to a STOPPING daemon task");
+ assertEquals(0, service.describeServices("daemon-stopping", List.of("daemon-svc"), REGION)
+ .getFirst().getRunningCount());
+
+ // Once it is STOPPED the instance is uncovered and gets its daemon back.
+ task.setLastStatus("STOPPED");
+ service.reconcileServices();
+ List<EcsTask> running = runningTasks(service);
+ assertEquals(1, running.size());
+ assertEquals(a.getContainerInstanceArn(), running.getFirst().getContainerInstanceArn());
+ }
+
+ @Test
+ void daemonIsRejectedForFargateAndForNonEcsDeploymentControllers() {
+ EcsService service = newMockModeService();
+ service.createCluster("daemon-reject", REGION);
+ registerTaskDef(service);
+
+ AwsException fargate = assertThrows(AwsException.class, () -> service.createService("daemon-reject",
+ "s1", "daemon-fam", 1, LaunchType.FARGATE, List.of(), null, null, "DAEMON", null, null, REGION));
+ assertEquals("InvalidParameterException", fargate.getErrorCode());
+
+ AwsException external = assertThrows(AwsException.class, () -> service.createService("daemon-reject",
+ "s2", "daemon-fam", 1, LaunchType.EC2, List.of(), null, null, "DAEMON", "EXTERNAL", null, REGION));
+ assertEquals("InvalidParameterException", external.getErrorCode());
+ }
+
+ private static List<EcsTask> runningTasks(EcsService service) {
+ return service.describeTasks(null, service.listTasks(null, null, null, null, REGION), REGION).stream()
+ .filter(t -> "RUNNING".equals(t.getLastStatus()))
+ .toList();
+ }
+
+ private static void registerTaskDef(EcsService service) {
+ ContainerDefinition cd = new ContainerDefinition();
+ cd.setName("agent");
+ cd.setImage("agent:1");
+ service.registerTaskDefinition("daemon-fam", List.of(cd), null, null, null, null, null, List.of(), REGION);
+ }
+
+ private static EcsService newMockModeService() {
+ EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
+ when(config.services().ecs().mock()).thenReturn(true);
+ when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
+ EcsService service = new EcsService(
+ new RegionResolver(REGION, "000000000000"),
+ mock(EcsContainerManager.class),
+ config,
+ mock(EcsLoadBalancerRegistrar.class),
+ new InMemoryStorageFactory());
+ service.initializeStorage();
+ return service;
+ }
+
+ private static final class InMemoryStorageFactory extends StorageFactory {
+ private final Map<String, StorageBackend<String, ?>> stores = new HashMap<>();
+
+ private InMemoryStorageFactory() {
+ super(null, null);
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public <V> AccountAwareStorageBackend<V> create(String serviceName,
+ String fileName,
+ TypeReference<Map<String, V>> typeReference) {
+ return (AccountAwareStorageBackend<V>) stores.computeIfAbsent(fileName,
+ ignored -> AccountAwareStorageBackend.inMemory("000000000000"));
+ }
+ }
+}