fix(ecs): create the initial CodeDeploy task set (#8464)

Creating an ECS service with the CODE_DEPLOY deployment controller now
creates its initial PRIMARY task set at 100 percent scale, as the ECS
guide describes. The set reuses the service scheduler's deployment ID, so
its running and pending counts follow the tasks the scheduler already
launches, and it reaches STEADY_STATE once they converge. CreateService,
DescribeServices and DescribeTaskSets return it, CODE_DEPLOY services
report an empty deployments list, and the set is removed with the
service. Task sets added through CreateTaskSet keep their simulated
counts.

Closes #8235
This commit is contained in:
Rashen Anupama authored and GitHub committed 2026-11-15 10:46:20 -04:00
1 parent 00fdb95ab5
commit 0a40ab728c
3 files changed
+154 -25

No files matched your search

+8 -4
View File
@@ -744,10 +744,14 @@ The task set round-trips `networkConfiguration` (defaulting to the service's), `
scale percentage, always rounded up: 3 desired at 50 percent is 2 tasks, not 1. `UpdateTaskSet`
recomputes it.
Floci places no tasks for a task set, so `runningCount` and `pendingCount` stay at 0 and
`stabilityStatus` is always `STEADY_STATE`. On AWS the status reaches `STEADY_STATE` once the
running count matches the computed one; reporting `STABILIZING` here would hang anything that
waits for the set to stabilise, since no count ever moves.
Creating a service with the `CODE_DEPLOY` controller creates an initial `PRIMARY` task set
at 100 percent scale. Its running and pending counts track the tasks launched by the service
scheduler. The set reaches `STEADY_STATE` when the running count matches its computed desired
count and no tasks are pending. `CreateService` and `DescribeServices` return the task set and an
empty `deployments` list for this controller.
Sets added through `CreateTaskSet` have simulated scheduling. Their running and pending counts
stay at zero, and they report `STEADY_STATE` so deployment tools can continue.
`DeleteTaskSet` refuses a task set that has not been scaled down to zero unless `force` is set.
`DescribeTaskSets` returns tags only for `include: ["TAGS"]` and reports a reference naming no
@@ -553,6 +553,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
// wipes CloudWatch, so the Container Insights samples it held must be written again.
launchFailures.clear();
publishedInsights.clear();
taskSets.clear();
}
/**
@@ -3081,6 +3082,9 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
svc.setTags(new LinkedHashMap<>(request.getTags()));
}
if ("CODE_DEPLOY".equals(controller)) {
createInitialTaskSet(svc, cluster, region);
}
services.put(key, svc);
cluster.setActiveServicesCount(cluster.getActiveServicesCount() + 1);
persistCluster(region, cluster);
@@ -3473,6 +3477,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
if (serviceArn != null) {
serviceDeployments.values().removeIf(d -> serviceArn.equals(d.getServiceArn()));
serviceRevisions.values().removeIf(r -> serviceArn.equals(r.getServiceArn()));
taskSets.values().removeIf(ts -> serviceArn.equals(ts.getServiceArn()));
launchFailures.remove(serviceArn);
}
return svc;
@@ -4429,16 +4434,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
"Invalid scale unit: " + request.getScaleUnit(), 400);
}
String setId = "ecs-svc/" + UUID.randomUUID().toString().replace("-", "");
String taskSetArn = regionResolver.buildArn("ecs", region, "task-set/"
+ cluster.getClusterName() + "/" + svc.getServiceName() + "/" + setId);
TaskSet ts = new TaskSet();
ts.setId(setId);
ts.setTaskSetArn(taskSetArn);
ts.setServiceArn(svc.getServiceArn());
ts.setClusterArn(cluster.getClusterArn());
ts.setTaskDefinition(taskDef.getTaskDefinitionArn());
TaskSet ts = newTaskSet(newDeploymentId(), svc, cluster, taskDef.getTaskDefinitionArn(), region);
ts.setStatus(STATUS_ACTIVE);
ts.setScaleValue(request.getScaleValue() != null ? request.getScaleValue() : 100.0);
ts.setScaleUnit(SCALE_UNIT_PERCENT);
@@ -4463,10 +4459,71 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
ts.setUpdatedAt(Instant.now());
applyTaskSetScale(ts, svc);
taskSets.put(taskSetArn, ts);
taskSets.put(ts.getTaskSetArn(), ts);
return ts;
}
private TaskSet newTaskSet(String id, EcsServiceModel svc, EcsCluster cluster,
String taskDefinition, String region) {
TaskSet ts = new TaskSet();
ts.setId(id);
ts.setTaskSetArn(regionResolver.buildArn("ecs", region, "task-set/"
+ cluster.getClusterName() + "/" + svc.getServiceName() + "/" + id));
ts.setServiceArn(svc.getServiceArn());
ts.setClusterArn(cluster.getClusterArn());
ts.setTaskDefinition(taskDefinition);
return ts;
}
private void createInitialTaskSet(EcsServiceModel svc, EcsCluster cluster, String region) {
// The service scheduler already starts these tasks under this deployment ID.
TaskSet ts = newTaskSet(svc.getDeploymentId(), svc, cluster, svc.getTaskDefinition(), region);
ts.setStatus("PRIMARY");
ts.setScaleUnit(SCALE_UNIT_PERCENT);
ts.setScaleValue(100.0);
ts.setCapacityProviderStrategy(svc.getCapacityProviderStrategy());
ts.setLaunchType(svc.getLaunchType());
ts.setNetworkConfiguration(svc.getNetworkConfiguration());
ts.setLoadBalancers(svc.getLoadBalancers());
ts.setServiceRegistries(svc.getServiceRegistries());
if (svc.getLaunchType() == LaunchType.FARGATE) {
ts.setPlatformVersion(resolvePlatformVersion(svc.getPlatformVersion()));
ts.setPlatformFamily(svc.getPlatformFamily());
}
ts.setCreatedAt(svc.getCreatedAt());
ts.setUpdatedAt(svc.getCreatedAt());
refreshScheduledTaskSet(ts, svc);
taskSets.put(ts.getTaskSetArn(), ts);
}
private void refreshScheduledTaskSet(TaskSet ts, EcsServiceModel svc) {
if (!"CODE_DEPLOY".equals(svc.getDeploymentController()) || !ts.getId().equals(deploymentId(svc))) {
return;
}
int running = 0;
int pending = 0;
for (EcsTask task : tasks.values()) {
if (!ts.getId().equals(task.getStartedBy())
|| !ts.getServiceArn().equals(task.getOwningServiceArn())) {
continue;
}
if (TaskStatus.RUNNING.name().equals(task.getLastStatus())) {
running++;
} else if (PENDING_TASK_STATUSES.contains(task.getLastStatus())) {
pending++;
}
}
int desired = (int) Math.ceil(svc.getDesiredCount() * ts.getScaleValue() / 100.0);
ts.setComputedDesiredCount(desired);
ts.setRunningCount(running);
ts.setPendingCount(pending);
String stability = running == desired && pending == 0 ? STABILITY_STATUS_STEADY_STATE : "STABILIZING";
if (!stability.equals(ts.getStabilityStatus())) {
ts.setStabilityStatus(stability);
ts.setStabilityStatusAt(Instant.now());
}
}
/**
* A task set that names neither a launch type nor a capacity provider strategy takes the
* cluster's default strategy, and falls back to EC2 when the cluster has none, as AWS does.
@@ -4491,10 +4548,8 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
* Stamps {@code computedDesiredCount}, which AWS derives from the service's desired count and
* the task set's scale percentage, always rounding up: a computed 1.2 becomes 2 tasks.
*
* <p>Floci places no tasks for a task set, so its running and pending counts stay at zero. A
* stability status derived from them would leave every set on a service with a desired count
* above zero in {@code STABILIZING} for ever, hanging anything that waits for the set to
* stabilise, so the set is reported {@code STEADY_STATE} until Floci tracks tasks for it.
* <p>Explicitly created task sets simulate scheduling and report {@code STEADY_STATE}.
* The initial CodeDeploy task set uses the service scheduler's real task counts.
*/
private void applyTaskSetScale(TaskSet ts, EcsServiceModel svc) {
ts.setComputedDesiredCount(
@@ -4516,6 +4571,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
ts.setScaleUnit(SCALE_UNIT_PERCENT);
ts.setUpdatedAt(Instant.now());
applyTaskSetScale(ts, svc);
refreshScheduledTaskSet(ts, svc);
return ts;
}
@@ -4554,11 +4610,13 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
if (svc == null) {
return List.of();
}
return taskSets.values().stream()
List<TaskSet> result = taskSets.values().stream()
.filter(ts -> svc.getServiceArn().equals(ts.getServiceArn()))
.sorted(Comparator.comparing(TaskSet::getCreatedAt,
Comparator.nullsLast(Comparator.naturalOrder())))
.toList();
result.forEach(ts -> refreshScheduledTaskSet(ts, svc));
return result;
}
public record DescribeTaskSetsResult(List<TaskSet> taskSets, List<Failure> failures) {}
@@ -4568,9 +4626,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
List<String> taskSetRefs, String region) {
EcsCluster cluster = resolveClusterOrDefault(clusterRef, region);
EcsServiceModel svc = resolveServiceOrThrow(cluster.getClusterName(), serviceRef, region);
List<TaskSet> ofService = taskSets.values().stream()
.filter(ts -> ts.getServiceArn().equals(svc.getServiceArn()))
.toList();
List<TaskSet> ofService = taskSetsFor(svc);
if (taskSetRefs == null || taskSetRefs.isEmpty()) {
return new DescribeTaskSetsResult(ofService, List.of());
}
@@ -4652,10 +4708,11 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
*
* <p>A task-definition change is applied in place rather than draining a previous
* deployment, so there is never a second ACTIVE entry beside the PRIMARY one. An INACTIVE
* service has no deployments.
* service has no deployments. CodeDeploy services report their rollout in taskSets.
*/
public List<Deployment> deploymentsFor(EcsServiceModel svc) {
if (svc == null || !"ACTIVE".equals(svc.getStatus())) {
if (svc == null || !"ACTIVE".equals(svc.getStatus())
|| "CODE_DEPLOY".equals(svc.getDeploymentController())) {
return List.of();
}
@@ -6439,6 +6496,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
if (ts == null) {
throw new AwsException("TaskSetNotFoundException", "Task set not found: " + ref, 400);
}
refreshScheduledTaskSet(ts, svc);
return ts;
}
@@ -8,8 +8,10 @@ import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import java.time.Duration;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo;
@@ -76,6 +78,71 @@ class EcsDescribeServicesIntegrationTest {
"{\"cluster\":\"" + cluster + "\",\"services\":[\"" + service + "\"]}");
}
@Test
void codeDeployServiceStartsWithAPrimaryTaskSet() {
seedClusterAndTaskDef("blue-cluster", "blue-task");
Response created = call("CreateService", """
{"cluster":"blue-cluster","serviceName":"blue-service",
"taskDefinition":"blue-task","desiredCount":0,
"deploymentController":{"type":"CODE_DEPLOY"}}
""");
String taskDefinition = created.path("service.taskDefinition");
Response described = describe("blue-cluster", "blue-service");
described.then()
.body("services[0].taskSets", hasSize(1))
.body("services[0].taskSets[0].status", equalTo("PRIMARY"))
.body("services[0].taskSets[0].taskDefinition", equalTo(taskDefinition))
.body("services[0].taskSets[0].computedDesiredCount", equalTo(0))
.body("services[0].deployments", hasSize(0));
String taskSetArn = described.path("services[0].taskSets[0].taskSetArn");
created.then().body("service.taskSets[0].taskSetArn", equalTo(taskSetArn));
call("DescribeTaskSets", """
{"cluster":"blue-cluster","service":"blue-service"}
""").then().body("taskSets[0].taskSetArn", equalTo(taskSetArn));
}
@Test
void codeDeployPrimaryTaskSetOwnsTheScheduledWorkload() {
call("CreateCluster", """
{"clusterName":"blue-running-cluster"}
""");
call("RegisterTaskDefinition", """
{"family":"blue-running-task","networkMode":"awsvpc",
"requiresCompatibilities":["FARGATE"],"cpu":"256","memory":"512",
"containerDefinitions":[{"name":"web","image":"nginx"}]}
""");
Response created = call("CreateService", """
{"cluster":"blue-running-cluster","serviceName":"blue-running-service",
"taskDefinition":"blue-running-task","desiredCount":1,"launchType":"FARGATE",
"networkConfiguration":{"awsvpcConfiguration":{"subnets":["subnet-default-us-east-1-a"]}},
"deploymentController":{"type":"CODE_DEPLOY"}}
""");
String primaryId = created.path("service.taskSets[0].id");
await().atMost(Duration.ofSeconds(30)).untilAsserted(() ->
describe("blue-running-cluster", "blue-running-service").then()
.body("services[0].runningCount", equalTo(1))
.body("services[0].taskSets", hasSize(1))
.body("services[0].taskSets[0].id", equalTo(primaryId))
.body("services[0].taskSets[0].computedDesiredCount", equalTo(1))
.body("services[0].taskSets[0].runningCount", equalTo(1))
.body("services[0].taskSets[0].pendingCount", equalTo(0))
.body("services[0].taskSets[0].stabilityStatus", equalTo("STEADY_STATE")));
Response listed = call("ListTasks", """
{"cluster":"blue-running-cluster","serviceName":"blue-running-service"}
""");
listed.then().body("taskArns", hasSize(1));
String taskArn = listed.path("taskArns[0]");
call("DescribeTasks", """
{"cluster":"blue-running-cluster","tasks":["%s"]}
""".formatted(taskArn)).then().body("tasks[0].startedBy", equalTo(primaryId));
call("DeleteService", """
{"cluster":"blue-running-cluster","service":"blue-running-service","force":true}
""").then().body("service.taskSets", hasSize(0));
}
@Test
void describeServicesReportsExactlyOnePrimaryDeployment() {
seedClusterAndTaskDef("dep-cluster-1", "dep-td-1");