fix(applicationautoscaling): target-tracking alarms watch the real metric, not the policy type name (#6902)

* fix(applicationautoscaling): target-tracking alarms watch the real metric, not the policy type name

CustomizedMetricSpecification passes Namespace, MetricName, Dimensions,
Statistic and Unit onto the AlarmHigh and AlarmLow alarms as given, and
the ECSServiceAverageCPUUtilization, ECSServiceAverageMemoryUtilization
and ALBRequestCountPerTarget predefined types map onto the documented
AWS/ECS and AWS/ApplicationELB metric identities, so the alarms see data
published the way AWS (or the caller) publishes it.

Closes #6853

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* fix(applicationautoscaling): read ALB target-tracking alarms through Sum

RequestCountPerTarget data points already carry the per-minute average
across the target group, and CloudWatch names Sum as the only valid
statistic for the metric, so an Average alarm compares the target
against a second average and misses scale-outs (two samples of 600
read 600 instead of 1200 against a target of 1000). The statistic now
travels with each predefined metric mapping, keeping Average for the
ECS utilisation gauges.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

---------

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
Co-authored-by: Priamo Germosen <6233424+pgermosen@users.noreply.github.com>
This commit is contained in:
Matheus OliveiraandPriamo Germosen authored and GitHub committed 2026-10-31 05:30:43 -04:00
1 parent 6d32605370
commit 2ad35bba1d
5 files changed
+371 -15

No files matched your search

@@ -115,7 +115,7 @@ class ApplicationAutoScalingEcsControlLoopIntegrationTest {
}
metricData.append("""
{
"MetricName": "ECSServiceAverageCPUUtilization",
"MetricName": "CPUUtilization",
"Value": 90.0,
"Unit": "Percent",
"Timestamp": %d,
@@ -35,8 +35,13 @@ class ApplicationAutoScalingIntegrationTest {
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String TARGET_PREFIX = "AnyScaleFrontendService.";
private static final String CLOUDWATCH_TARGET = "GraniteServiceVersion20100801.";
private static final String CLOUDWATCH_JSON_CONTENT_TYPE = "application/x-amz-json-1.0";
private static final String RESOURCE_ID = "service/aas-it-cluster/aas-it-service";
private static final String PAGED_RESOURCE_ID = "service/aas-it-cluster/aas-it-service-paged";
private static final String ALARM_RESOURCE_ID = "service/aas-it-cluster/aas-it-alarm-service";
private static final String ALARM_CLUSTER = "aas-it-cluster";
private static final String ALARM_SERVICE = "aas-it-alarm-service";
private static final String DIMENSION = "ecs:service:DesiredCount";
private static String scalableTargetArn;
@@ -50,6 +55,10 @@ class ApplicationAutoScalingIntegrationTest {
return given().header("X-Amz-Target", TARGET_PREFIX + action).contentType(CONTENT_TYPE);
}
private static RequestSpecification cloudwatchCall(String action) {
return given().header("X-Amz-Target", CLOUDWATCH_TARGET + action).contentType(CLOUDWATCH_JSON_CONTENT_TYPE);
}
@Test
@Order(1)
void registerScalableTargetReturnsScalableTargetArn() {
@@ -217,6 +226,14 @@ class ApplicationAutoScalingIntegrationTest {
.body("Alarms", hasSize(2))
.body("Alarms[0].AlarmName", startsWith("TargetTracking-" + RESOURCE_ID))
.body("Alarms[0].AlarmARN", startsWith("arn:aws:cloudwatch:"));
cloudwatchCall("DescribeAlarms")
.body("{ \"AlarmNamePrefix\": \"TargetTracking-" + RESOURCE_ID + "\" }")
.when().post("/").then().statusCode(200)
.body("MetricAlarms.find { it.MetricName == 'RequestCountPerTarget' }.Namespace",
equalTo("AWS/ApplicationELB"))
.body("MetricAlarms.find { it.MetricName == 'RequestCountPerTarget' }.Statistic",
equalTo("Sum"));
}
@Test
@@ -408,4 +425,132 @@ class ApplicationAutoScalingIntegrationTest {
.when().post("/").then().statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@Test
@Order(18)
void customizedTargetTrackingAlarmsWatchTheMetricIdentityTheCallerGave() {
call("RegisterScalableTarget")
.body("""
{
"ServiceNamespace": "ecs",
"ResourceId": "%s",
"ScalableDimension": "%s",
"MinCapacity": 1,
"MaxCapacity": 3
}
""".formatted(ALARM_RESOURCE_ID, DIMENSION))
.when().post("/").then().statusCode(200);
call("PutScalingPolicy")
.body("""
{
"PolicyName": "aas-it-custom-metric",
"PolicyType": "TargetTrackingScaling",
"ServiceNamespace": "ecs",
"ResourceId": "%s",
"ScalableDimension": "%s",
"TargetTrackingScalingPolicyConfiguration": {
"TargetValue": 10.0,
"CustomizedMetricSpecification": {
"Namespace": "App/Workers",
"MetricName": "JobsPerTask",
"Statistic": "Average",
"Dimensions": [{ "Name": "ServiceName", "Value": "web" }]
}
}
}
""".formatted(ALARM_RESOURCE_ID, DIMENSION))
.when().post("/").then().statusCode(200);
cloudwatchCall("DescribeAlarms")
.body("{ \"AlarmNamePrefix\": \"TargetTracking-" + ALARM_RESOURCE_ID + "\" }")
.when().post("/").then().statusCode(200)
.body("MetricAlarms.findAll { it.MetricName == 'JobsPerTask' }.size()", equalTo(2))
.body("MetricAlarms.find { it.MetricName == 'JobsPerTask' }.Namespace", equalTo("App/Workers"))
.body("MetricAlarms.find { it.MetricName == 'JobsPerTask' }.Statistic", equalTo("Average"))
.body("MetricAlarms.find { it.MetricName == 'JobsPerTask' }.Dimensions.size()", equalTo(1))
.body("MetricAlarms.find { it.MetricName == 'JobsPerTask' }.Dimensions[0].Name", equalTo("ServiceName"))
.body("MetricAlarms.find { it.MetricName == 'JobsPerTask' }.Dimensions[0].Value", equalTo("web"))
// The metric the alarm watches must be the caller's, not the ECS-shaped fallback.
.body("MetricAlarms.findAll { it.Namespace == 'AWS/ECS' }.size()", equalTo(0));
call("DeregisterScalableTarget")
.body("""
{ "ServiceNamespace": "ecs", "ResourceId": "%s", "ScalableDimension": "%s" }
""".formatted(ALARM_RESOURCE_ID, DIMENSION))
.when().post("/").then().statusCode(200);
}
@Test
@Order(19)
void ecsPredefinedTargetTrackingAlarmsWatchTheRealMetricTheServicePublishes() {
call("RegisterScalableTarget")
.body("""
{
"ServiceNamespace": "ecs",
"ResourceId": "%s",
"ScalableDimension": "%s",
"MinCapacity": 1,
"MaxCapacity": 3
}
""".formatted(ALARM_RESOURCE_ID, DIMENSION))
.when().post("/").then().statusCode(200);
for (String policy : List.of("""
{
"PolicyName": "aas-it-cpu",
"PolicyType": "TargetTrackingScaling",
"ServiceNamespace": "ecs",
"ResourceId": "%s",
"ScalableDimension": "%s",
"TargetTrackingScalingPolicyConfiguration": {
"TargetValue": 70.0,
"PredefinedMetricSpecification": {
"PredefinedMetricType": "ECSServiceAverageCPUUtilization"
}
}
}
""", """
{
"PolicyName": "aas-it-memory",
"PolicyType": "TargetTrackingScaling",
"ServiceNamespace": "ecs",
"ResourceId": "%s",
"ScalableDimension": "%s",
"TargetTrackingScalingPolicyConfiguration": {
"TargetValue": 80.0,
"PredefinedMetricSpecification": {
"PredefinedMetricType": "ECSServiceAverageMemoryUtilization"
}
}
}
""")) {
call("PutScalingPolicy").body(policy.formatted(ALARM_RESOURCE_ID, DIMENSION))
.when().post("/").then().statusCode(200);
}
cloudwatchCall("DescribeAlarms")
.body("{ \"AlarmNamePrefix\": \"TargetTracking-" + ALARM_RESOURCE_ID + "\" }")
.when().post("/").then().statusCode(200)
.body("MetricAlarms.findAll { it.MetricName == 'CPUUtilization' }.size()", equalTo(2))
.body("MetricAlarms.find { it.MetricName == 'CPUUtilization' }.Namespace", equalTo("AWS/ECS"))
.body("MetricAlarms.find { it.MetricName == 'CPUUtilization' }.Dimensions.size()", equalTo(2))
.body("MetricAlarms.find { it.MetricName == 'CPUUtilization' }.Dimensions[0].Name", equalTo("ClusterName"))
.body("MetricAlarms.find { it.MetricName == 'CPUUtilization' }.Dimensions[0].Value", equalTo(ALARM_CLUSTER))
.body("MetricAlarms.find { it.MetricName == 'CPUUtilization' }.Dimensions[1].Name", equalTo("ServiceName"))
.body("MetricAlarms.find { it.MetricName == 'CPUUtilization' }.Dimensions[1].Value", equalTo(ALARM_SERVICE))
.body("MetricAlarms.findAll { it.MetricName == 'MemoryUtilization' }.size()", equalTo(2))
.body("MetricAlarms.find { it.MetricName == 'MemoryUtilization' }.Namespace", equalTo("AWS/ECS"))
.body("MetricAlarms.find { it.MetricName == 'MemoryUtilization' }.Dimensions[0].Name", equalTo("ClusterName"))
.body("MetricAlarms.find { it.MetricName == 'MemoryUtilization' }.Dimensions[1].Name", equalTo("ServiceName"))
// Nothing watches the policy type name itself, as real AWS would never publish it.
.body("MetricAlarms.findAll { it.MetricName == 'ECSServiceAverageCPUUtilization' }.size()", equalTo(0))
.body("MetricAlarms.findAll { it.MetricName == 'ECSServiceAverageMemoryUtilization' }.size()", equalTo(0));
call("DeregisterScalableTarget")
.body("""
{ "ServiceNamespace": "ecs", "ResourceId": "%s", "ScalableDimension": "%s" }
""".formatted(ALARM_RESOURCE_ID, DIMENSION))
.when().post("/").then().statusCode(200);
}
}
@@ -9,12 +9,14 @@ import io.github.hectorvent.floci.services.applicationautoscaling.model.Scalable
import io.github.hectorvent.floci.services.applicationautoscaling.model.ScalingPolicy;
import io.github.hectorvent.floci.services.applicationautoscaling.model.TargetTrackingConfiguration;
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 org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.LinkedHashSet;
import java.util.List;
@@ -44,16 +46,21 @@ class ApplicationAutoScalingServiceTest {
/** Alarm names currently registered in the stubbed CloudWatch. */
private final Set<String> alarmsInCloudWatch = new LinkedHashSet<>();
/** Alarm objects currently registered in the stubbed CloudWatch, in creation order. */
private final List<MetricAlarm> createdAlarms = new ArrayList<>();
@BeforeEach
void setUp() {
RegionResolver regionResolver = new RegionResolver(REGION, "000000000000");
alarmsInCloudWatch.clear();
createdAlarms.clear();
cloudWatch = mock(CloudWatchMetricsService.class);
doAnswer(invocation -> {
MetricAlarm alarm = invocation.getArgument(0);
alarm.setAlarmArn("arn:aws:cloudwatch:" + REGION + ":000000000000:alarm:" + alarm.getAlarmName());
alarmsInCloudWatch.add(alarm.getAlarmName());
createdAlarms.add(alarm);
return null;
}).when(cloudWatch).putMetricAlarm(any(MetricAlarm.class), anyString());
doAnswer(invocation -> {
@@ -406,6 +413,100 @@ class ApplicationAutoScalingServiceTest {
assertNotNull(policy.getAlarms().get(0).getAlarmArn());
}
@Test
void customizedMetricAlarmsWatchTheMetricIdentityTheCallerGave() {
register();
TargetTrackingConfiguration config = new TargetTrackingConfiguration();
config.setTargetValue(10.0d);
config.setCustomizedMetricSpecification(Map.of(
"Namespace", "App/Workers",
"MetricName", "JobsPerTask",
"Statistic", "Maximum",
"Unit", "Count",
"Dimensions", List.of(
Map.of("Name", "ServiceName", "Value", "web"),
Map.of("Name", "Queue", "Value", "jobs"))));
service.putScalingPolicy("custom", "TargetTrackingScaling",
NAMESPACE, RESOURCE_ID, DIMENSION, config, null, REGION);
assertEquals(2, createdAlarms.size());
for (MetricAlarm alarm : createdAlarms) {
assertEquals("App/Workers", alarm.getNamespace(), "the caller's namespace must reach the alarm");
assertEquals("JobsPerTask", alarm.getMetricName(), "the caller's metric name must reach the alarm");
assertEquals("Maximum", alarm.getStatistic(), "the caller's statistic must reach the alarm");
assertEquals("Count", alarm.getUnit(), "the caller's unit must reach the alarm");
assertEquals(List.of(new Dimension("ServiceName", "web"), new Dimension("Queue", "jobs")),
alarm.getDimensions(), "the caller's dimensions must reach the alarm");
}
}
@Test
void customizedMetricWithoutAStatisticKeepsTheAlarmDefaultAverage() {
register();
TargetTrackingConfiguration config = new TargetTrackingConfiguration();
config.setTargetValue(10.0d);
config.setCustomizedMetricSpecification(Map.of(
"Namespace", "App/Workers",
"MetricName", "JobsPerTask"));
service.putScalingPolicy("custom", "TargetTrackingScaling",
NAMESPACE, RESOURCE_ID, DIMENSION, config, null, REGION);
assertEquals("Average", createdAlarms.get(0).getStatistic());
assertNull(createdAlarms.get(0).getUnit());
}
@Test
void ecsCpuPredefinedAlarmsWatchTheRealAwsEcsMetricIdentity() {
register();
service.putScalingPolicy("cpu", "TargetTrackingScaling",
NAMESPACE, RESOURCE_ID, DIMENSION,
targetTracking(65.0, "ECSServiceAverageCPUUtilization", null), null, REGION);
for (MetricAlarm alarm : createdAlarms) {
assertEquals("AWS/ECS", alarm.getNamespace());
assertEquals("CPUUtilization", alarm.getMetricName(),
"the alarm must watch the metric ECS publishes, not the policy type name");
assertEquals(List.of(new Dimension("ClusterName", "my-cluster"), new Dimension("ServiceName", "my-service")),
alarm.getDimensions());
assertEquals("Average", alarm.getStatistic());
}
}
@Test
void ecsMemoryPredefinedAlarmsWatchTheRealAwsEcsMetricIdentity() {
register();
service.putScalingPolicy("memory", "TargetTrackingScaling",
NAMESPACE, RESOURCE_ID, DIMENSION,
targetTracking(70.0, "ECSServiceAverageMemoryUtilization", null), null, REGION);
for (MetricAlarm alarm : createdAlarms) {
assertEquals("AWS/ECS", alarm.getNamespace());
assertEquals("MemoryUtilization", alarm.getMetricName(),
"the alarm must watch the metric ECS publishes, not the policy type name");
assertEquals(List.of(new Dimension("ClusterName", "my-cluster"), new Dimension("ServiceName", "my-service")),
alarm.getDimensions());
}
}
@Test
void albPredefinedAlarmsWatchThePerTargetMetricInsideTheResourceLabel() {
register();
service.putScalingPolicy("alb", "TargetTrackingScaling", NAMESPACE, RESOURCE_ID, DIMENSION,
targetTracking(1000.0, "ALBRequestCountPerTarget", "app/my-lb/abc123/targetgroup/my-tg/def456"),
null, REGION);
for (MetricAlarm alarm : createdAlarms) {
assertEquals("AWS/ApplicationELB", alarm.getNamespace());
assertEquals("RequestCountPerTarget", alarm.getMetricName());
assertEquals(List.of(
new Dimension("LoadBalancer", "app/my-lb/abc123"),
new Dimension("TargetGroup", "targetgroup/my-tg/def456")),
alarm.getDimensions());
assertEquals("Sum", alarm.getStatistic(),
"RequestCountPerTarget's only valid CloudWatch statistic is Sum");
}
}
@Test
void deregisterCascadesToPoliciesAndAlarms() {
register();