diff --git a/src/main/java/io/floci/aws/services/cloudwatch/metrics/AlarmEvaluator.java b/src/main/java/io/floci/aws/services/cloudwatch/metrics/AlarmEvaluator.java index 77923c8f6b..a99e5c07c2 100644 --- a/src/main/java/io/floci/aws/services/cloudwatch/metrics/AlarmEvaluator.java +++ b/src/main/java/io/floci/aws/services/cloudwatch/metrics/AlarmEvaluator.java @@ -282,6 +282,7 @@ public class AlarmEvaluator { && alarm.getMetrics().isEmpty() && alarm.getNamespace() != null && !alarm.getNamespace().isBlank() && alarm.getMetricName() != null && !alarm.getMetricName().isBlank() + && alarm.getStatistic() != null && !alarm.getStatistic().isBlank() && alarm.getPeriod() != null && alarm.getPeriod() > 0 && alarm.getEvaluationPeriods() > 0 && alarm.getComparisonOperator() != null; diff --git a/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java b/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java index cc5f15c0a4..0bd72c8a0c 100644 --- a/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java +++ b/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java @@ -335,6 +335,7 @@ public class CloudWatchMetricsJsonHandler { alarm.setMetricName(request.path("MetricName").asText(null)); alarm.setNamespace(request.path("Namespace").asText(null)); alarm.setStatistic(request.path("Statistic").asText(null)); + alarm.setExtendedStatistic(request.path("ExtendedStatistic").asText(null)); JsonNode metrics = request.path("Metrics"); if (metrics.isArray()) { for (JsonNode query : metrics) { @@ -449,6 +450,9 @@ public class CloudWatchMetricsJsonHandler { if (a.getStatistic() != null) { node.put("Statistic", a.getStatistic()); } + if (a.getExtendedStatistic() != null) { + node.put("ExtendedStatistic", a.getExtendedStatistic()); + } ArrayNode dimensions = node.putArray("Dimensions"); a.getDimensions().forEach(d -> { ObjectNode dimNode = dimensions.addObject(); diff --git a/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsQueryHandler.java b/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsQueryHandler.java index 38e6b8a781..175daf8386 100644 --- a/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsQueryHandler.java +++ b/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsQueryHandler.java @@ -827,6 +827,7 @@ public class CloudWatchMetricsQueryHandler { a.setMetricName(params.getFirst("MetricName")); a.setNamespace(params.getFirst("Namespace")); a.setStatistic(params.getFirst("Statistic")); + a.setExtendedStatistic(params.getFirst("ExtendedStatistic")); a.setMetrics(parseAlarmMetricQueries(params)); a.setPeriod(a.getMetrics().isEmpty() ? parseIntParam(params, "Period", 60) : null); a.setUnit(params.getFirst("Unit")); @@ -924,6 +925,7 @@ public class CloudWatchMetricsQueryHandler { .elem("MetricName", a.getMetricName()) .elem("Namespace", a.getNamespace()) .elem("Statistic", a.getStatistic()) + .elem("ExtendedStatistic", a.getExtendedStatistic()) .elem("Period", a.getPeriod() == null ? null : a.getPeriod().toString()) .elem("Unit", a.getUnit()); } diff --git a/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsService.java b/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsService.java index d7f9792c52..7f664738ed 100644 --- a/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsService.java +++ b/src/main/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsService.java @@ -436,6 +436,12 @@ public class CloudWatchMetricsService { rejectEvaluationInterval(alarm.getAlarmName(), evaluationInterval, alarm.getMetricName() != null || !alarm.getMetrics().isEmpty()); } + if (alarm.getStatistic() != null && !alarm.getStatistic().isBlank() + && alarm.getExtendedStatistic() != null && !alarm.getExtendedStatistic().isBlank()) { + throw new AwsException("ValidationError", + "PutMetricAlarm request can not be made with both Statistic and ExtendedStatistic parameters. " + + "Only one of them should be present", 400); + } boolean created = alarmStore.get(region + "::" + alarm.getAlarmName()).isEmpty(); putAlarm(alarm, region); if (created) { diff --git a/src/main/java/io/floci/aws/services/cloudwatch/metrics/model/MetricAlarm.java b/src/main/java/io/floci/aws/services/cloudwatch/metrics/model/MetricAlarm.java index 56f5808096..3b5510efa6 100644 --- a/src/main/java/io/floci/aws/services/cloudwatch/metrics/model/MetricAlarm.java +++ b/src/main/java/io/floci/aws/services/cloudwatch/metrics/model/MetricAlarm.java @@ -15,6 +15,7 @@ public class MetricAlarm extends Alarm { private String metricName; private String namespace; private String statistic; + private String extendedStatistic; private List dimensions = new ArrayList<>(); /** Single-metric period; absent for alarms whose periods are defined in Metrics. */ private Integer period; @@ -43,6 +44,9 @@ public class MetricAlarm extends Alarm { public String getStatistic() { return statistic; } public void setStatistic(String statistic) { this.statistic = statistic; } + public String getExtendedStatistic() { return extendedStatistic; } + public void setExtendedStatistic(String extendedStatistic) { this.extendedStatistic = extendedStatistic; } + public List getDimensions() { return dimensions; } public void setDimensions(List dimensions) { this.dimensions = dimensions; } diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/AlarmEvaluatorTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/AlarmEvaluatorTest.java index 7b012f6cd7..706bca001e 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/metrics/AlarmEvaluatorTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/AlarmEvaluatorTest.java @@ -179,6 +179,25 @@ class AlarmEvaluatorTest { any(), any(), any(), any(), any(), anyInt(), any(), any(), anyString()); } + @Test + void skipsAlarmsConfiguredWithExtendedStatisticOnly() { + MetricAlarm alarm = new MetricAlarm(); + alarm.setAlarmName("p99-only-alarm"); + alarm.setRegion(REGION); + alarm.setNamespace("AWS/ApplicationELB"); + alarm.setMetricName("TargetResponseTime"); + alarm.setExtendedStatistic("p99"); + alarm.setPeriod(300); + alarm.setEvaluationPeriods(1); + alarm.setThreshold(1.0); + alarm.setComparisonOperator("GreaterThanThreshold"); + + assertDoesNotThrow(() -> evaluator.evaluate(alarm)); + + verify(metricsService, never()).getMetricStatistics( + any(), any(), any(), any(), any(), anyInt(), any(), any(), anyString()); + } + @Test void evaluateAllSurvivesAllAlarmsThrowing() { when(metricsService.allAlarms()).thenThrow(new RuntimeException("storage hiccup")); diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchAlarmExtendedStatisticIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchAlarmExtendedStatisticIntegrationTest.java new file mode 100644 index 0000000000..063e1723cd --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchAlarmExtendedStatisticIntegrationTest.java @@ -0,0 +1,150 @@ +package io.floci.aws.services.cloudwatch.metrics; + +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.PartitionCleanup; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.cloudwatch.CloudWatchClient; +import software.amazon.awssdk.services.cloudwatch.model.MetricAlarm; + +import java.net.URI; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** PutMetricAlarm and DescribeAlarms preserve ExtendedStatistic across Query, JSON, and the Java SDK. */ +@QuarkusTest +class CloudWatchAlarmExtendedStatisticIntegrationTest { + + private static final String SCOPE = + "AWS4-HMAC-SHA256 Credential=test/20261121/us-east-1/monitoring/aws4_request"; + private static final String XML_ALARM = + "DescribeAlarmsResponse.DescribeAlarmsResult.MetricAlarms.member[0]."; + + @TestHTTPResource + URI baseUri; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + private CloudWatchClient cloudWatch; + private String suffix; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @BeforeEach + void setUp() { + cloudWatch = AwsTestClients.create(CloudWatchClient.builder(), "test", Region.US_EAST_1); + cleanup.register(cloudWatch::close); + suffix = Long.toString(System.nanoTime(), 36); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void bothProtocolsRoundTripExtendedStatistic(boolean json) throws Exception { + String name = "wire-ext-stat-" + (json ? "json-" : "query-") + suffix; + cleanup.register(() -> CloudWatchTestRequests.deleteAlarmJson(baseUri, SCOPE, name)); + + Map putBody = new LinkedHashMap<>(); + putBody.put("AlarmName", name); + putBody.put("Namespace", "AWS/ApplicationELB"); + putBody.put("MetricName", "TargetResponseTime"); + putBody.put("ExtendedStatistic", "p99"); + putBody.put("Period", 300); + putBody.put("EvaluationPeriods", 1); + putBody.put("Threshold", 1); + putBody.put("ComparisonOperator", "GreaterThanThreshold"); + CloudWatchTestRequests.call(baseUri, SCOPE, json, "PutMetricAlarm", putBody).then().statusCode(200); + + Response described = CloudWatchTestRequests.call(baseUri, SCOPE, json, "DescribeAlarms", + Map.of("AlarmNames", List.of(name))); + described.then().statusCode(200); + if (json) { + assertEquals("p99", described.jsonPath().getString("MetricAlarms[0].ExtendedStatistic")); + assertNull(described.jsonPath().get("MetricAlarms[0].Statistic")); + } else { + assertEquals("p99", described.xmlPath().getString(XML_ALARM + "ExtendedStatistic")); + assertFalse(described.asString().contains("")); + } + + Map updateBody = new LinkedHashMap<>(putBody); + updateBody.remove("ExtendedStatistic"); + updateBody.put("Statistic", "Average"); + CloudWatchTestRequests.call(baseUri, SCOPE, json, "PutMetricAlarm", updateBody).then().statusCode(200); + + Response updated = CloudWatchTestRequests.call(baseUri, SCOPE, json, "DescribeAlarms", + Map.of("AlarmNames", List.of(name))); + updated.then().statusCode(200); + if (json) { + assertEquals("Average", updated.jsonPath().getString("MetricAlarms[0].Statistic")); + assertNull(updated.jsonPath().get("MetricAlarms[0].ExtendedStatistic")); + } else { + assertEquals("Average", updated.xmlPath().getString(XML_ALARM + "Statistic")); + assertFalse(updated.asString().contains("")); + } + } + + @Test + void sdkRoundTripsExtendedStatistic() { + String name = "sdk-ext-stat-" + suffix; + cleanup.register(() -> cloudWatch.deleteAlarms(r -> r.alarmNames(name))); + + cloudWatch.putMetricAlarm(r -> r.alarmName(name) + .namespace("AWS/ApplicationELB") + .metricName("TargetResponseTime") + .extendedStatistic("p99") + .period(300) + .evaluationPeriods(1) + .threshold(1.0) + .comparisonOperator("GreaterThanThreshold")); + + MetricAlarm stored = cloudWatch.describeAlarms(r -> r.alarmNames(name)).metricAlarms().getFirst(); + assertEquals("p99", stored.extendedStatistic()); + assertNull(stored.statisticAsString()); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void bothProtocolsRejectStatisticAndExtendedStatisticTogether(boolean json) throws Exception { + String name = "wire-both-stat-" + (json ? "json-" : "query-") + suffix; + cleanup.register(() -> CloudWatchTestRequests.deleteAlarmJson(baseUri, SCOPE, name)); + + Map body = new LinkedHashMap<>(); + body.put("AlarmName", name); + body.put("Namespace", "AWS/ApplicationELB"); + body.put("MetricName", "TargetResponseTime"); + body.put("Statistic", "Average"); + body.put("ExtendedStatistic", "p99"); + body.put("Period", 300); + body.put("EvaluationPeriods", 1); + body.put("Threshold", 1); + body.put("ComparisonOperator", "GreaterThanThreshold"); + + Response refused = CloudWatchTestRequests.call(baseUri, SCOPE, json, "PutMetricAlarm", body); + refused.then().statusCode(400); + assertEquals("ValidationError", + json ? refused.jsonPath().getString("__type") + : refused.xmlPath().getString("ErrorResponse.Error.Code")); + assertEquals("PutMetricAlarm request can not be made with both Statistic and ExtendedStatistic parameters. " + + "Only one of them should be present", + json ? refused.jsonPath().getString("message") + : refused.xmlPath().getString("ErrorResponse.Error.Message")); + assertEquals(0, cloudWatch.describeAlarms(r -> r.alarmNames(name)).metricAlarms().size()); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchAlarmQueryHandlerTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchAlarmQueryHandlerTest.java index 5ac59abbc7..5ed44d7a58 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchAlarmQueryHandlerTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchAlarmQueryHandlerTest.java @@ -117,6 +117,71 @@ class CloudWatchAlarmQueryHandlerTest { error.getMessage()); } + @Test + void putAndDescribeMetricAlarmPreservesExtendedStatistic() { + String region = "us-east-1"; + CloudWatchMetricsService service = new CloudWatchMetricsService(new InMemoryStorage<>(), + new InMemoryStorage<>(), new RegionResolver(region, "123456789012")); + CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(service, null, null); + MultivaluedMap put = new MultivaluedHashMap<>(); + put.putSingle("AlarmName", "p99-query"); + put.putSingle("Namespace", "AWS/ApplicationELB"); + put.putSingle("MetricName", "TargetResponseTime"); + put.putSingle("ExtendedStatistic", "p99"); + put.putSingle("Period", "300"); + put.putSingle("EvaluationPeriods", "1"); + put.putSingle("Threshold", "1"); + put.putSingle("ComparisonOperator", "GreaterThanThreshold"); + assertEquals(200, handler.handle("PutMetricAlarm", put, region).getStatus()); + + MultivaluedMap describe = new MultivaluedHashMap<>(); + describe.putSingle("AlarmNames.member.1", "p99-query"); + String xml = (String) handler.handle("DescribeAlarms", describe, region).getEntity(); + assertTrue(xml.contains("p99"), xml); + assertFalse(xml.contains(""), xml); + + MultivaluedMap update = new MultivaluedHashMap<>(); + update.putSingle("AlarmName", "p99-query"); + update.putSingle("Namespace", "AWS/ApplicationELB"); + update.putSingle("MetricName", "TargetResponseTime"); + update.putSingle("Statistic", "Average"); + update.putSingle("Period", "300"); + update.putSingle("EvaluationPeriods", "1"); + update.putSingle("Threshold", "1"); + update.putSingle("ComparisonOperator", "GreaterThanThreshold"); + assertEquals(200, handler.handle("PutMetricAlarm", update, region).getStatus()); + + String updatedXml = (String) handler.handle("DescribeAlarms", describe, region).getEntity(); + assertTrue(updatedXml.contains("Average"), updatedXml); + assertFalse(updatedXml.contains(""), updatedXml); + } + + @Test + void putMetricAlarmRejectsStatisticAndExtendedStatisticTogether() { + String region = "us-east-1"; + CloudWatchMetricsService service = new CloudWatchMetricsService(new InMemoryStorage<>(), + new InMemoryStorage<>(), new RegionResolver(region, "123456789012")); + CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(service, null, null); + MultivaluedMap put = new MultivaluedHashMap<>(); + put.putSingle("AlarmName", "both-stats-query"); + put.putSingle("Namespace", "AWS/ApplicationELB"); + put.putSingle("MetricName", "TargetResponseTime"); + put.putSingle("Statistic", "Average"); + put.putSingle("ExtendedStatistic", "p99"); + put.putSingle("Period", "300"); + put.putSingle("EvaluationPeriods", "1"); + put.putSingle("Threshold", "1"); + put.putSingle("ComparisonOperator", "GreaterThanThreshold"); + + AwsException error = assertThrows(AwsException.class, + () -> handler.handle("PutMetricAlarm", put, region)); + assertEquals("ValidationError", error.getErrorCode()); + assertEquals("PutMetricAlarm request can not be made with both Statistic and ExtendedStatistic parameters. " + + "Only one of them should be present", error.getMessage()); + assertEquals(400, error.getHttpStatus()); + assertTrue(service.describeAlarms(List.of("both-stats-query"), null, region).isEmpty()); + } + private static NodeList elements(Document document, String name) { return document.getElementsByTagNameNS(AwsNamespaces.CW, name); } diff --git a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsJsonHandlerTest.java b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsJsonHandlerTest.java index a0b80e5711..ff35f14d7c 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsJsonHandlerTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/metrics/CloudWatchMetricsJsonHandlerTest.java @@ -434,6 +434,42 @@ class CloudWatchMetricsJsonHandlerTest { assertEquals("Count", alarm.get("Unit").asText()); } + @Test + void describeAlarms_returnsExtendedStatisticWhenSetAndOmitsWhenUnset() { + ObjectNode req = alarmRequest("P99Alarm"); + req.put("ExtendedStatistic", "p99"); + + JsonNode alarm = describeFirstAlarm(req); + + assertEquals("p99", alarm.get("ExtendedStatistic").asText()); + assertFalse(alarm.has("Statistic")); + + ObjectNode updatedReq = alarmRequest("P99Alarm"); + updatedReq.put("Statistic", "Average"); + + JsonNode updatedAlarm = describeFirstAlarm(updatedReq); + + assertEquals("Average", updatedAlarm.get("Statistic").asText()); + assertFalse(updatedAlarm.has("ExtendedStatistic")); + } + + @Test + void putMetricAlarm_rejectsStatisticAndExtendedStatisticTogether() { + ObjectNode req = alarmRequest("BothStatsAlarm"); + req.put("Statistic", "Average"); + req.put("ExtendedStatistic", "p99"); + + AwsException error = assertThrows(AwsException.class, + () -> handler.handle("PutMetricAlarm", req, REGION)); + + assertEquals("ValidationError", error.getErrorCode()); + assertEquals("ValidationError", error.jsonType()); + assertEquals("PutMetricAlarm request can not be made with both Statistic and ExtendedStatistic parameters. " + + "Only one of them should be present", error.getMessage()); + assertEquals(400, error.getHttpStatus()); + assertTrue(service.describeAlarms(List.of("BothStatsAlarm"), null, REGION).isEmpty()); + } + @Test void describeAlarms_reportsStateTransitionedTimestampForBothAlarmKinds() { handler.handle("PutMetricAlarm", alarmRequest("TransitionedMetric"), REGION);