fix(cloudformation): wait for a stable ECS service (#4880)

AWS CloudFormation reports an AWS::ECS::Service CREATE_COMPLETE or
UPDATE_COMPLETE only once the service is stable: it polls
DescribeServices until the desired number of tasks of the current
task definition are running. Floci reported the resource complete as
soon as CreateService or UpdateService returned. The tasks were
started later by the ECS reconciler, every five seconds, and the
service's runningCount only caught up a tick after that, so a client
reading the service right after the stack operation saw runningCount
0.

EcsService.awaitServiceStable now waits, like
Ec2Service.awaitContainerLaunch, for runningCount to equal
desiredCount, for the current deployment to run that many tasks, and
for no task of an earlier deployment to be running. Instead of idling
until the next tick it submits up to three reconcile passes to the
single reconciler thread, so they never overlap a scheduled tick.
After five minutes it fails with "Service <arn> did not stabilize.".

The wait ends at once when the service's tasks cannot start. The
reconciler now keeps, in memory, why its last attempt to launch a
task for a service failed, for example an unknown subnet, and the
deployment it was launching for. Only a failure of the deployment
being awaited ends the wait, so a pass that began before an update
cannot fail the update. The record is cleared on a successful launch,
on DeleteService and on a state reset. A task that stops with
TaskFailedToStart during the wait ends it too. A task the reconciler
launches is stamped with the deployment read before its task
definition, not after the launch, so a launch that an update overtakes
counts as the earlier deployment's and is replaced.

The ECS provisioner calls the wait after an in-place update and after
a create. A created service stays marked as owned by the stack while
it waits, so the create rollback deletes it. A replacement created by
a stack update is deleted when it does not stabilize. A service
updated in place that does not stabilize is put back on the task
definition, desired count and network configuration it had, and the
provisioner waits for that to stabilize too, as CloudFormation's
rollback does. A restore that fails or does not stabilize is reported
as a rollback failure, so a rolled-back stack does not claim the prior
configuration is running when it is not.

The ECS service test in CloudFormationIntegrationTest used subnets
and a security group that do not exist, so its tasks could never
start. It now uses the default VPC's.
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-10-09 10:05:39 -04:00
1 parent 3b36a4d0d8
commit 0ec64add2d
7 files changed
+1152 -11

No files matched your search

@@ -168,7 +168,9 @@ public class EcsCfnProvisioner implements CfnResourceProvisioner {
* create time is read back from the {@code Name} attribute rather than the prior id. An update
* that keeps the name and the cluster updates the service in place; a changed name or a
* changed cluster (both create-only) is a replacement: the new service is created and the
* displaced one deleted once the stack update commits, through the replacement cleanup.
* displaced one deleted once the stack update commits, through the replacement cleanup. Either
* way the resource completes only once the service is stable, as CloudFormation's does; an
* in-place update that does not stabilize is put back on the prior configuration.
*/
private void provisionService(StackResource r, JsonNode props, ProvisionContext ctx) {
String clusterRef = ctx.resolveOptional(props, "Cluster");
@@ -190,8 +192,14 @@ public class EcsCfnProvisioner implements CfnResourceProvisioner {
}
EcsServiceModel svc;
if (ctx.isUpdate() && serviceName.equals(priorName)
&& clusterName(clusterRef).equals(clusterOfServiceArn(ctx.priorPhysicalId()))) {
boolean inPlace = ctx.isUpdate() && serviceName.equals(priorName)
&& clusterName(clusterRef).equals(clusterOfServiceArn(ctx.priorPhysicalId()));
// Read before updateService, which changes this same model in place.
EcsServiceModel prior = inPlace ? ecsService.serviceByArn(ctx.priorPhysicalId()) : null;
String priorTaskDefinition = prior != null ? prior.getTaskDefinition() : null;
Integer priorDesiredCount = prior != null ? prior.getDesiredCount() : null;
NetworkConfiguration priorNetworkConfiguration = prior != null ? prior.getNetworkConfiguration() : null;
if (inPlace) {
svc = ecsService.updateService(clusterRef, serviceName, taskDefinition,
desiredCount, networkConfiguration, ctx.region());
} else {
@@ -202,6 +210,73 @@ public class EcsCfnProvisioner implements CfnResourceProvisioner {
r.setPhysicalId(svc.getServiceArn());
r.getAttributes().put("Name", svc.getServiceName());
r.getAttributes().put("ServiceArn", svc.getServiceArn());
if (inPlace) {
try {
ecsService.awaitServiceStable(svc);
} catch (RuntimeException failure) {
restoreInPlace(r, failure, () -> ecsService.awaitServiceStable(ecsService.updateService(clusterRef,
svc.getServiceName(), priorTaskDefinition, priorDesiredCount, priorNetworkConfiguration,
ctx.region())));
throw failure;
}
} else {
awaitCreatedServiceStable(r, svc, ctx);
}
}
/**
* Puts a service updated in place back on the task definition, desired count and network
* configuration it had, when the update does not stabilize, and waits for the restored
* configuration to stabilize, as CloudFormation's rollback does. CloudFormationService restores
* the prior resource record and reports the rollback complete unless told otherwise, so without
* this the stack would claim a rollback while ECS still runs the failed configuration. A
* restore that fails or does not stabilize is attached to the original failure and recorded as
* a rollback failure.
*/
private void restoreInPlace(StackResource r, RuntimeException failure, Runnable restore) {
try {
restore.run();
} catch (RuntimeException restoreFailure) {
String reason = "Could not restore " + r.getPhysicalId() + " after a failed update: "
+ restoreFailure.getMessage();
LOG.warnv("{0}", reason);
r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR, reason);
if (restoreFailure != failure) {
failure.addSuppressed(restoreFailure);
}
}
}
/**
* Waits for a service this provision created to stabilize, as CloudFormation does before it
* reports the resource complete. The resource is marked as owned meanwhile, so a service that
* never stabilizes is deleted by the create rollback. A replacement created by a stack update
* is removed here instead: the engine restores the prior resource and never learns the new ARN.
*/
private void awaitCreatedServiceStable(StackResource r, EcsServiceModel svc, ProvisionContext ctx) {
r.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true");
try {
ecsService.awaitServiceStable(svc);
} catch (RuntimeException failure) {
if (ctx.isUpdate()) {
unwindReplacement(r, ctx.region(), failure);
}
throw failure;
}
r.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR);
}
private void unwindReplacement(StackResource r, String region, RuntimeException failure) {
try {
deleteService(r.getPhysicalId(), region);
r.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR);
} catch (RuntimeException cleanupFailure) {
failure.addSuppressed(cleanupFailure);
String reason = "Could not remove " + r.getPhysicalId() + ", the replacement created for "
+ r.getLogicalId() + " by a failed update: " + cleanupFailure.getMessage();
LOG.warnv("{0}", reason);
r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR, reason);
}
}
/** The cluster name a template value addresses: a name, an ARN's last segment, or the default. */
@@ -73,6 +73,7 @@ import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
@@ -91,6 +92,8 @@ import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
@@ -179,6 +182,15 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
public static final int MAX_TASKS_PER_RUN = 10;
/** A listing returns at most a hundred ARNs per page. */
private static final int MAX_LIST_RESULTS = 100;
/** How long a CloudFormation-provisioned service may take to reach a steady state. */
private static final Duration SERVICE_STABLE_TIMEOUT = Duration.ofMinutes(5);
private static final long SERVICE_STABLE_POLL_MILLIS = 50;
/**
* Reconcile passes a steady-state wait runs at once instead of waiting for ticks. A pass
* reports the running count it found before it acted, so a deployment that both starts tasks
* and drains the previous deployment's reads as settled after the third.
*/
private static final int SERVICE_STABLE_PASSES = 3;
/** ListServices answers with ten ARNs per page when the request names no maxResults. */
private static final int DEFAULT_SERVICE_PAGE_SIZE = 10;
public static final String STATUS_ACTIVE = "ACTIVE";
@@ -210,6 +222,9 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
private Map<String, String> accountSettings = new ConcurrentHashMap<>();
// deploymentIds for which SERVICE_DEPLOYMENT_IN_PROGRESS has already been emitted this process.
private final Set<String> inProgressEmitted = java.util.concurrent.ConcurrentHashMap.newKeySet();
// serviceArn → why the reconciler's last attempt to launch one of its tasks failed, and for which
// deployment. Memory-only.
private final Map<String, LaunchFailure> launchFailures = new ConcurrentHashMap<>();
@Inject
public EcsService(RegionResolver regionResolver, EcsContainerManager containerManager,
@@ -385,7 +400,8 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
@Override
public void clear() {
// Nothing to wipe: the stores hold the ECS state and afterReset() restarts the reconciler.
// The stores hold the ECS state and afterReset() restarts the reconciler.
launchFailures.clear();
}
/**
@@ -426,6 +442,150 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
return reconciler.isShutdown();
}
// ── Steady state ─────────────────────────────────────────────────────────
/**
* Waits until a service reaches a steady state, which is what CloudFormation waits for before
* it reports an {@code AWS::ECS::Service} CREATE_COMPLETE or UPDATE_COMPLETE. CloudFormation
* reads it off {@code DescribeServices}, so the service must report {@code runningCount}
* equal to {@code desiredCount}, its current deployment must run that many tasks, and no task
* of an earlier deployment may still be running. A {@code desiredCount} of 0 with nothing
* running is stable at once.
*
* <p>Rather than sit idle until the next tick, the wait runs reconcile passes at once on the
* reconciler's own single thread, so a pass never overlaps a scheduled tick.
*
* @throws AwsException when the reconciler could not launch a task for the service, when a task
* launched for it during the wait failed to start, or when the service does not stabilize
* within the timeout
*/
public void awaitServiceStable(EcsServiceModel svc) {
awaitServiceStable(svc, SERVICE_STABLE_TIMEOUT);
}
void awaitServiceStable(EcsServiceModel svc, Duration timeout) {
String serviceArn = svc.getServiceArn();
recordLaunchFailure(svc, null, null);
Instant waitStarted = Instant.now();
long deadline = System.nanoTime() + timeout.toNanos();
Future<?> pass = null;
int passes = 0;
while (true) {
// Checked before the service is read, so a finished pass's writes are visible to the read.
boolean passRunning = pass != null && !pass.isDone();
EcsServiceModel current = serviceByArn(serviceArn);
if (current == null || !STATUS_ACTIVE.equals(current.getStatus())) {
throw notStabilized(serviceArn, " The service is no longer ACTIVE.");
}
if (!passRunning) {
failIfTasksCannotStart(current, waitStarted);
}
if (isSteady(current)) {
return;
}
if (!passRunning && passes < SERVICE_STABLE_PASSES) {
pass = reconcileNow();
passes++;
}
if (System.nanoTime() - deadline >= 0) {
throw notStabilized(serviceArn, "");
}
try {
Thread.sleep(SERVICE_STABLE_POLL_MILLIS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new AwsException("InternalError", "Interrupted while waiting for ECS service "
+ serviceArn + " to stabilize", 500);
}
}
}
/**
* Runs one reconcile pass now on the reconciler's single thread. Null when the reconciler is
* shut down, which only happens on shutdown and for the length of a state reset.
*/
private Future<?> reconcileNow() {
try {
return reconciler.submit(this::reconcile);
} catch (RejectedExecutionException e) {
LOG.debugv("ECS reconciler is shut down, waiting for the next scheduled tick: {0}", e.getMessage());
return null;
}
}
private boolean isSteady(EcsServiceModel svc) {
if (svc.getRunningCount() != svc.getDesiredCount()) {
return false;
}
EcsCluster cluster = resolveClusterByArn(svc.getClusterArn());
if (cluster == null) {
return svc.getDesiredCount() == 0;
}
String currentDeploymentId = deploymentId(svc);
String taskDefinitionArn = resolvedTaskDefinitionArn(svc, serviceRegion(svc));
long current = 0;
for (EcsTask task : tasks.values()) {
if (!ownedBy(task, svc, cluster) || !TaskStatus.RUNNING.name().equals(task.getLastStatus())) {
continue;
}
if (isStaleForDeployment(task, currentDeploymentId, taskDefinitionArn)) {
return false;
}
current++;
}
return current == svc.getDesiredCount();
}
/**
* Ends a wait that cannot succeed: the reconciler could not launch a task for the service's
* current deployment, or a task launched for it since {@code since} stopped before it ever ran.
*/
private void failIfTasksCannotStart(EcsServiceModel svc, Instant since) {
String currentDeploymentId = deploymentId(svc);
LaunchFailure launchFailure = launchFailures.get(svc.getServiceArn());
if (launchFailure != null && currentDeploymentId.equals(launchFailure.deploymentId())) {
throw notStabilized(svc.getServiceArn(), " Task launch failed: " + launchFailure.message());
}
EcsCluster cluster = resolveClusterByArn(svc.getClusterArn());
if (cluster == null) {
return;
}
String taskDefinitionArn = resolvedTaskDefinitionArn(svc, serviceRegion(svc));
for (EcsTask task : tasks.values()) {
if (ownedBy(task, svc, cluster)
&& TaskStatus.STOPPED.name().equals(task.getLastStatus())
&& STOP_CODE_TASK_FAILED_TO_START.equals(task.getStopCode())
&& task.getCreatedAt() != null && !task.getCreatedAt().isBefore(since)
&& !isStaleForDeployment(task, currentDeploymentId, taskDefinitionArn)) {
throw notStabilized(svc.getServiceArn(),
" Task " + task.getTaskArn() + " stopped: " + task.getStoppedReason());
}
}
}
/** AWS's wording when a service does not reach a steady state, followed by any detail. */
private static AwsException notStabilized(String serviceArn, String detail) {
return new AwsException("NotStabilized", "Service " + serviceArn + " did not stabilize." + detail, 500);
}
private record LaunchFailure(String deploymentId, String message) {}
/** Records why the reconciler could not launch a task for {@code svc}'s {@code deploymentId}; null clears it. */
private void recordLaunchFailure(EcsServiceModel svc, String deploymentId, String failure) {
if (svc.getServiceArn() == null) {
return;
}
if (failure == null) {
launchFailures.remove(svc.getServiceArn());
} else {
launchFailures.put(svc.getServiceArn(), new LaunchFailure(deploymentId, failure));
}
}
boolean hasLaunchFailure(String serviceArn) {
return launchFailures.containsKey(serviceArn);
}
// ── Clusters ─────────────────────────────────────────────────────────────
public EcsCluster createCluster(String clusterName, String region) {
@@ -1480,13 +1640,15 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
*/
private EcsTask launchServiceTask(EcsCluster cluster, EcsServiceModel svc, LaunchType launchType,
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(svc));
request.setStartedBy(deploymentId);
request.setNetworkConfiguration(svc.getNetworkConfiguration());
request.setPlatformVersion(svc.getPlatformVersion());
request.setEnableExecuteCommand(svc.isEnableExecuteCommand());
@@ -1503,7 +1665,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
}
EcsTask task = launchTasks(cluster, taskDef, request, containerInstanceArn,
svc.getServiceArn(), region).getFirst();
task.setDeploymentId(deploymentId(svc));
task.setDeploymentId(deploymentId);
return task;
}
@@ -2775,6 +2937,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()));
launchFailures.remove(serviceArn);
}
return svc;
}
@@ -5084,12 +5247,14 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
for (int i = 0; i < toStart; i++) {
try {
EcsTask launched = launchServiceTask(cluster, svc, svc.getLaunchType(), null, region);
recordLaunchFailure(svc, null, null);
LOG.infov("Service reconciler started task {0} for service {1}",
launched.getTaskArn(), svc.getServiceName());
if (countLaunch(svc, deployment, launched)) {
break;
}
} catch (Exception e) {
recordLaunchFailure(svc, currentDeploymentId, String.valueOf(e.getMessage()));
LOG.warnv("Service reconciler failed to start task for {0}: {1}",
svc.getServiceName(), e.getMessage());
}