feat(ecs): publish Container Insights task counts (#6054)

* feat(ecs): publish Container Insights task counts

A service on a cluster whose containerInsights setting is enabled or enhanced publishes RunningTaskCount, PendingTaskCount and DesiredTaskCount to ECS/ContainerInsights once a minute, with ClusterName and ServiceName dimensions, while it has a running task. The AWS::ECS::Cluster provisioner applies ClusterSettings and restores the prior settings when a stack update rolls back.

* fix(ecs): resolve ClusterSettings as a whole before reading it

A ClusterSettings list wrapped in Fn::If was iterated unresolved and stored a setting with no name or value. Resolve the property node first, as the provisioner does for its other list properties.

* fix(ecs): resolve ClusterSettings before creating the cluster

A ClusterSettings value that failed to resolve left a cluster the stack did not track. Resolve first, and skip an entry that resolved to AWS::NoValue.

* fix(ecs): date Container Insights counts by the minute they were observed

* fix(ecs): count Container Insights tasks when they are published

The task counts came from the service's cached runningCount, which the
reconcile sets before it scales the service in or out, and from a
pendingCount nothing ever sets. They are now counted from the service's
own tasks after the tick has started and stopped them, so a scale-in is
reported in the tick that stops the task and a PENDING task is counted.

A committed in-place cluster update now drops its settings snapshot in
completeUpdate: the engine only calls clearUpdate after a replacement,
so the snapshot outlived the update it belonged to.

* docs(ecs): note that removing ClusterSettings keeps the cluster's settings

* test(ecs): cover restoring null cluster settings and read the latest metric bucket

A stack update that adds ClusterSettings to a cluster created without any rolls back to null settings, through the JSON null in the snapshot; the rollback test now covers that case alongside a prior disabled setting.

The scale-in test reads the latest one-minute bucket, so a minute rollover between its two reconciles no longer splits the samples into two buckets and fails the test.

* fix(ecs): log a failed Container Insights write as a warning

The publish ran inside the reconcile's catch, which logs only the message at debug level, so a failed metric write left the minute's sample missing without a trace. It now has its own try and logs the exception at warn.

* perf(ecs): write a Container Insights sample only when a count changes

The reconciler ticks every five seconds and wrote all three counts each time, and a persistent metric store rewrites its file on every put. The last sample written per account and service is kept, and the minute's sample is written again only when a count changes. A reset clears it, since it wipes the samples too.

* fix(cloudformation): restore ECS cluster settings when their own update fails

A failed provision puts back the resource the stack held before the attempt, which never carried the settings snapshot, so the rollback walker skipped it and the new settings stayed. The provisioner now restores the snapshot itself, as the other in-place provisioners do, and records a restore that fails as a rollback failure. The physical id is set before the settings call, so the restore and a create rollback both find the cluster.

* fix(ecs): repeat a Container Insights write that failed partway

The last sample written was kept until the next one replaced it, so when one count landed and the next write failed, and the counts then went back to the ones last written, the next tick skipped the minute and left the partial value in place. The record is now dropped before writing and set again only once all three counts are written.

* fix(cloudformation): keep an ECS settings snapshot whose restore failed

When a cluster's settings update and its own restore both failed, the snapshot stayed on the attempted resource, and the engine put back the prior resource without it. The first rollback reported the failure, and ContinueUpdateRollback then found no snapshot and reported the rollback complete with the new settings still live. The snapshot is now carried onto the restored resource, so the continuation retries the restore.

* fix(cloudformation): create an ECS cluster with its settings

A new cluster was created and then given its ClusterSettings in a second call. When that call failed, on a stack create or a rename, nothing tracked the cluster: the create rollback skips a CREATE_FAILED resource it does not own, and a rename never reached the replacement record. The settings now go into CreateCluster itself, so a new cluster is never left without them. A cluster the idempotent create returned, which the stack did not create, still has them applied separately and is not deleted when that fails.

* fix(cloudformation): set an ECS cluster's id only once its settings apply

The physical id was set before the settings call. When an update added a cluster under the name of one created outside the stack, the idempotent create returned that cluster, and if its settings then failed, the update rollback deleted the added resource and with it a cluster the stack never created. The id is set after the settings again; an update of the resource's own cluster already carries its prior id for the restore.

* fix(cloudformation): restore the settings of an ECS cluster the stack found

Only a resource's own cluster had its prior settings put back when the settings call failed. A cluster the idempotent create returned for a resource the stack creates or adds kept whatever a failed call left on it, while the rollback, which drops the resource, reported a clean finish. A cluster whose settings still differ after CreateCluster existed before, so its prior settings are now captured and restored either way; the snapshot attribute for the rollback walker stays on the resource's own cluster only.

* test(ecs): date Container Insights samples by a clock the test pins

publishContainerInsights read the minute from the wall clock, so the test of an unchanged sample skipped itself when the minute rolled over between its ticks. The minute now comes from a Clock given to a package-private constructor, which the injected one calls with Clock.systemUTC(); the test pins it and asserts the sample is dated by it.

* test(ecs): drive the reconciler instead of waiting on its ticks

The CloudFormation integration test waited up to 30 seconds for the background reconciler to launch the task and publish its count. It now calls reconcileServices twice, as the other ECS integration tests do.
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-10-21 06:59:33 -04:00
1 parent 538a81d871
commit 1b15299228
7 files changed
+872 -12

No files matched your search

@@ -265,6 +265,12 @@ public final class CfnRollback {
*/
public static final String ASG_UPDATE_SNAPSHOT_ATTR = "__FlociAsgUpdateSnapshot";
/**
* Holds the settings an ECS cluster carried before an in-place update changed its
* {@code ClusterSettings}, so a failed stack update can restore them.
*/
public static final String ECS_CLUSTER_SETTINGS_SNAPSHOT_ATTR = "__FlociEcsClusterSettingsSnapshot";
/**
* Holds the version a launch template created during an in-place update and the prior version,
* so a failed stack update can roll it back.
@@ -1,11 +1,16 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.ecs.EcsService;
import io.github.hectorvent.floci.services.ecs.model.AwsVpcConfiguration;
import io.github.hectorvent.floci.services.ecs.model.ClusterSetting;
import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
import io.github.hectorvent.floci.services.ecs.model.EcsCluster;
import io.github.hectorvent.floci.services.ecs.model.EcsLoadBalancer;
@@ -43,6 +48,8 @@ public class EcsCfnProvisioner implements CfnResourceProvisioner {
private static final String CLUSTER = "AWS::ECS::Cluster";
private static final String TASK_DEFINITION = "AWS::ECS::TaskDefinition";
private static final String SERVICE = "AWS::ECS::Service";
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final TypeReference<List<ClusterSetting>> SETTINGS = new TypeReference<>() { };
private final EcsService ecsService;
@@ -101,6 +108,7 @@ public class EcsCfnProvisioner implements CfnResourceProvisioner {
@Override
public UpdateCleanupResult completeUpdate(StackResource resource) {
resource.getAttributes().remove(CfnRollback.ECS_CLUSTER_SETTINGS_SNAPSHOT_ATTR);
return ReplacementCleanup.complete(resource, this::delete);
}
@@ -110,33 +118,127 @@ public class EcsCfnProvisioner implements CfnResourceProvisioner {
}
/**
* A replacement is undone through the cleanup record. Without one, a cluster has nothing to put
* back: its only property is the create-only name, so an update that kept it re-issued the
* idempotent create and changed nothing. A service without a record was updated in place, and
* putting that back needs a snapshot this provisioner does not keep, so the engine reports it as
* not rolled back, as it did for the switch.
* When a settings update and its own restore both failed, the snapshot is left on the attempted
* resource only, and the engine puts back the resource it held before. Carried over, it lets
* ContinueUpdateRollback retry the restore through {@link #rollbackUpdate} instead of finding
* nothing to put back. A restore that succeeded removed it, so it is here only after a failed one.
*/
@Override
public void mergeFailedUpdateResourceTracking(StackResource previous, StackResource attempted) {
String snapshot = attempted.getAttributes().get(CfnRollback.ECS_CLUSTER_SETTINGS_SNAPSHOT_ATTR);
if (snapshot != null) {
previous.getAttributes().put(CfnRollback.ECS_CLUSTER_SETTINGS_SNAPSHOT_ATTR, snapshot);
}
}
/**
* A replacement is undone through the cleanup record. Without one, a cluster puts back the
* settings snapshot its update took; with no snapshot the update changed no settings, and the
* name is create-only, so the idempotent create changed nothing. A service without a record was
* updated in place, and putting that back needs a snapshot this provisioner does not keep, so the
* engine reports it as not rolled back, as it did for the switch.
*/
@Override
public boolean rollbackUpdate(StackResource resource) {
if (ReplacementCleanup.rollback(resource, this::delete)) {
return true;
}
restoreSettingsSnapshot(resource);
return CLUSTER.equals(resource.getResourceType());
}
private void restoreSettingsSnapshot(StackResource resource) {
String rawSnapshot = resource.getAttributes().get(CfnRollback.ECS_CLUSTER_SETTINGS_SNAPSHOT_ATTR);
if (rawSnapshot == null) {
return;
}
JsonNode snapshot;
try {
snapshot = MAPPER.readTree(rawSnapshot);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Unreadable ECS cluster settings snapshot for "
+ resource.getLogicalId(), e);
}
ecsService.updateClusterSettings(resource.getPhysicalId(),
MAPPER.convertValue(snapshot.get("settings"), SETTINGS), snapshot.get("region").asText());
resource.getAttributes().remove(CfnRollback.ECS_CLUSTER_SETTINGS_SNAPSHOT_ATTR);
}
/**
* The cluster name is create-only and the physical id, so an unnamed cluster keeps the name its
* first execution generated. createCluster is idempotent, which is what makes an unchanged
* update a no-op here.
* update a no-op here. A new cluster is created with its declared {@code ClusterSettings}; an
* existing one has them applied when they differ, and an update snapshots the prior ones for
* its rollback.
*/
private void provisionCluster(StackResource r, JsonNode props, ProvisionContext ctx) {
r.getAttributes().remove(CfnRollback.ECS_CLUSTER_SETTINGS_SNAPSHOT_ATTR);
String clusterName = ctx.stablePhysicalName(ctx.resolveOptional(props, "ClusterName"),
r.getLogicalId(), 255, false);
EcsCluster cluster = ecsService.createCluster(clusterName, ctx.region());
List<ClusterSetting> settings = new ArrayList<>();
JsonNode declared = props != null ? props.get("ClusterSettings") : null;
JsonNode resolved = declared != null ? ctx.engine().resolveNode(declared) : null;
if (resolved != null && resolved.isArray()) {
for (JsonNode item : resolved) {
// An entry that resolved to AWS::NoValue is not an object.
if (item.isObject()) {
settings.add(new ClusterSetting(item.path("Name").asText(null), item.path("Value").asText(null)));
}
}
}
// A new cluster takes its settings at creation, so no later call can fail and leave it
// behind; an existing one (this resource's own on an update, or one the idempotent create
// returned) has them applied below.
EcsCluster cluster = ecsService.createCluster(clusterName, null, settings, ctx.region());
if (!settings.isEmpty() && !settings.equals(cluster.getSettings())) {
List<ClusterSetting> prior = cluster.getSettings() == null ? null : List.copyOf(cluster.getSettings());
if (ctx.reusesPriorEntity(clusterName)) {
ObjectNode snapshot = MAPPER.createObjectNode().put("region", ctx.region());
snapshot.set("settings", MAPPER.valueToTree(prior));
r.getAttributes().put(CfnRollback.ECS_CLUSTER_SETTINGS_SNAPSHOT_ATTR, snapshot.toString());
}
// Before the id is set: a cluster the idempotent create returned for a resource this
// update adds was not created by the stack, and a failed update deletes an added
// resource that carries an id. An update of this resource's own cluster keeps its id.
try {
ecsService.updateClusterSettings(clusterName, settings, ctx.region());
} catch (RuntimeException failure) {
unwindSettings(r, clusterName, prior, ctx.region(), failure);
throw failure;
}
}
r.setPhysicalId(cluster.getClusterName());
r.getAttributes().put("Arn", cluster.getClusterArn());
}
/**
* Puts back the settings an existing cluster had before a settings call that failed, which may
* have changed them before failing. For this resource's own cluster the engine restores the
* resource it held before the attempt, which never carried the snapshot, so the rollback walker
* would skip {@link #rollbackUpdate}; a cluster the stack found rather than created is not
* restored by anything else. A restore that fails too is recorded as a rollback failure, which
* ends an update in UPDATE_ROLLBACK_FAILED for the resource's own cluster, and is attached to
* the original failure. The restore repeats the call that just failed, so it can come back
* with that very exception, which cannot be suppressed under itself.
*/
private void unwindSettings(StackResource r, String clusterName, List<ClusterSetting> prior, String region,
RuntimeException failure) {
try {
ecsService.updateClusterSettings(clusterName, prior, region);
r.getAttributes().remove(CfnRollback.ECS_CLUSTER_SETTINGS_SNAPSHOT_ATTR);
} catch (RuntimeException unwindFailure) {
String reason = "Could not restore the settings of ECS cluster " + clusterName + ": "
+ unwindFailure.getMessage();
// ponytail: a cluster the stack found has no id here, so the engine drops the resource
// and nothing retries this; carrying it would need engine-side tracking for added resources.
LOG.warnv("{0}", reason);
r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR, reason);
if (unwindFailure != failure) {
failure.addSuppressed(unwindFailure);
}
}
}
/**
* Every property of a task definition is create-only, so an update registers a fresh revision
* under the same family, as CloudFormation does on AWS; the physical id is the new revision's
@@ -16,7 +16,9 @@ import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackedMap;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
import io.github.hectorvent.floci.services.ecs.container.EcsContainerManager;
import io.github.hectorvent.floci.services.ecs.container.EcsLinuxParameters;
import io.github.hectorvent.floci.services.ecs.container.EcsTaskHandle;
@@ -79,8 +81,10 @@ import org.jboss.logging.Logger;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
@@ -125,6 +129,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
// what every such caller already expects.
private final EcsServiceDiscoveryRegistrar discoveryRegistrar;
private final CloudWatchMetricsService cloudWatchMetricsService;
private final Clock clock;
private final boolean dockerMode;
private final boolean sweepLeftoverContainers;
private final String baseUrl;
@@ -229,6 +234,8 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
private final Map<String, ServiceDeployment> serviceDeployments = new ConcurrentHashMap<>();
// serviceRevisionArn → ServiceRevision
private final Map<String, ServiceRevision> serviceRevisions = new ConcurrentHashMap<>();
// accountId::serviceKey → the Container Insights sample last written for that service
private final Map<String, InsightsSample> publishedInsights = new ConcurrentHashMap<>();
// targetArn → List<Attribute>
private Map<String, List<Attribute>> attributes = new ConcurrentHashMap<>();
// name → value (account-level settings)
@@ -248,6 +255,17 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
EcsExecSessionRegistry execSessions,
EcsServiceDiscoveryRegistrar discoveryRegistrar,
CloudWatchMetricsService cloudWatchMetricsService) {
this(regionResolver, containerManager, config, lbRegistrar, storageFactory, eventPublisher,
execSessions, discoveryRegistrar, cloudWatchMetricsService, Clock.systemUTC());
}
/** With the clock that dates Container Insights samples, which a test pins. */
EcsService(RegionResolver regionResolver, EcsContainerManager containerManager,
EmulatorConfig config, EcsLoadBalancerRegistrar lbRegistrar,
StorageFactory storageFactory, EcsEventPublisher eventPublisher,
EcsExecSessionRegistry execSessions,
EcsServiceDiscoveryRegistrar discoveryRegistrar,
CloudWatchMetricsService cloudWatchMetricsService, Clock clock) {
this.regionResolver = regionResolver;
this.containerManager = containerManager;
this.dockerMode = !config.services().ecs().mock();
@@ -260,6 +278,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
this.execSessions = execSessions;
this.discoveryRegistrar = discoveryRegistrar;
this.cloudWatchMetricsService = cloudWatchMetricsService;
this.clock = clock;
}
public EcsService(RegionResolver regionResolver, EcsContainerManager containerManager,
@@ -425,8 +444,10 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
@Override
public void clear() {
// The stores hold the ECS state and afterReset() restarts the reconciler.
// The stores hold the ECS state and afterReset() restarts the reconciler. The reset also
// wipes CloudWatch, so the Container Insights samples it held must be written again.
launchFailures.clear();
publishedInsights.clear();
}
/**
@@ -5227,9 +5248,72 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
} catch (Exception e) {
LOG.debugv("Error reconciling ECS service {0}: {1}", entry.getKey(), e.getMessage());
}
try {
publishContainerInsights(entry.getKey(), entry.getValue());
} catch (Exception e) {
LOG.warnv(e, "Could not publish Container Insights task counts for ECS service {0}", entry.getKey());
}
}
}
/**
* Container Insights task counts for a service on a cluster whose own {@code containerInsights}
* setting is enabled or enhanced, one sample per minute, counted from the service's tasks once
* the tick has started and stopped them. As in AWS, nothing is published while the service has
* no RUNNING task, so an alarm sees missing data rather than a zero.
*/
private void publishContainerInsights(String key, EcsServiceModel svc) {
if (cloudWatchMetricsService == null || !STATUS_ACTIVE.equals(svc.getStatus())) {
return;
}
String region = extractRegionFromServiceKey(key);
String clusterName = extractClusterNameFromServiceKey(key);
EcsCluster cluster = clusters.get(clusterKey(region, clusterName));
if (cluster == null || cluster.getSettings() == null || cluster.getSettings().stream().noneMatch(s ->
"containerInsights".equals(s.name())
&& ("enabled".equals(s.value()) || "enhanced".equals(s.value())))) {
return;
}
List<String> statuses = tasks.values().stream()
.filter(t -> ownedBy(t, svc, cluster))
.map(EcsTask::getLastStatus)
.toList();
int running = Collections.frequency(statuses, TaskStatus.RUNNING.name());
if (running < 1) {
return;
}
long minute = clock.instant().truncatedTo(ChronoUnit.MINUTES).getEpochSecond();
Map<String, Integer> counts = Map.of("RunningTaskCount", running,
"PendingTaskCount", Collections.frequency(statuses, TaskStatus.PENDING.name()),
"DesiredTaskCount", svc.getDesiredCount());
String accountId = regionResolver.getAccountId();
String sampleKey = accountId + "::" + key;
InsightsSample sample = new InsightsSample(minute, counts);
// A persistent metric store rewrites its file on every put, and the reconciler ticks every
// five seconds, so the minute's sample is written again only when a count changes.
if (sample.equals(publishedInsights.get(sampleKey))) {
return;
}
// Forgotten before writing, so a write that fails partway is repeated on the next tick
// even when the counts are back to the ones last written in full.
publishedInsights.remove(sampleKey);
for (Map.Entry<String, Integer> count : counts.entrySet()) {
MetricDatum datum = new MetricDatum();
datum.setMetricName(count.getKey());
datum.setUnit("Count");
datum.setDimensions(List.of(new Dimension("ClusterName", clusterName),
new Dimension("ServiceName", svc.getServiceName())));
datum.setTimestamp(minute);
datum.setValue(count.getValue());
cloudWatchMetricsService.publishMetricForAccount(accountId, "ECS/ContainerInsights",
datum, region, "ecs-container-insights");
}
publishedInsights.put(sampleKey, sample);
}
private record InsightsSample(long minute, Map<String, Integer> counts) {
}
/**
* Whether a task is genuinely owned by {@code svc}. Both halves matter: {@code
* owningServiceArn} is stamped only by {@link #launchServiceTask} and so cannot be forged