diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java index a43ac5c08e..2f11479c68 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java @@ -46,11 +46,11 @@ public class CloudWatchMetricsJsonHandler { /** * The operations served through the console's {@code CloudWatchVersion20130116.} target, each - * with the request members accepted there: some of the ones this handler honours, plus - * {@code NextToken} and {@code MaxRecords}, which change nothing because every result comes - * back at once. DescribeAlarms' {@code StateValue}, {@code ActionPrefix}, - * {@code ChildrenOfAlarmName} and {@code ParentsOfAlarmName} stay refused here until the - * console's API is known to give them the same shapes. + * with the request members accepted there: some of the ones this handler honours. ListMetrics + * honours {@code NextToken}; DescribeAlarms' {@code MaxRecords} and {@code NextToken} still + * change nothing because every alarm comes back at once. DescribeAlarms' {@code StateValue}, + * {@code ActionPrefix}, {@code ChildrenOfAlarmName} and {@code ParentsOfAlarmName} + * stay refused here until the console's API is known to give them the same shapes. */ private static final Map> CONSOLE_TARGET_OPERATIONS = Map.of( "ListMetrics", Set.of("Namespace", "MetricName", "Dimensions", "NextToken"), @@ -177,12 +177,17 @@ public class CloudWatchMetricsJsonHandler { String metricName = request.has("MetricName") ? request.path("MetricName").asText() : null; List dimensions = parseDimensionsJson(request.path("Dimensions")); - List metrics = - metricsService.listMetrics(namespace, metricName, dimensions, region); + JsonNode tokenNode = request.get("NextToken"); + if (tokenNode != null && !tokenNode.isNull() && !tokenNode.isTextual()) { + throw CloudWatchMetricsException.invalidParameterValue("Invalid NextToken."); + } + String nextToken = tokenNode == null || tokenNode.isNull() ? null : tokenNode.textValue(); + PaginatedResult page = + metricsService.listMetricsPage(namespace, metricName, dimensions, nextToken, region); ObjectNode response = objectMapper.createObjectNode(); ArrayNode metricsArray = response.putArray("Metrics"); - for (CloudWatchMetricsService.MetricIdentity m : metrics) { + for (CloudWatchMetricsService.MetricIdentity m : page.items()) { ObjectNode mNode = metricsArray.addObject(); mNode.put("Namespace", m.namespace()); mNode.put("MetricName", m.metricName()); @@ -193,6 +198,9 @@ public class CloudWatchMetricsJsonHandler { } } } + if (page.nextToken() != null) { + response.put("NextToken", page.nextToken()); + } return Response.ok(response).build(); } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsQueryHandler.java index 1f2eb693cf..32dfb887a5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsQueryHandler.java @@ -98,11 +98,11 @@ public class CloudWatchMetricsQueryHandler { String metricName = params.getFirst("MetricName"); List dimensions = parseDimensionFilters(params); - List metrics = - metricsService.listMetrics(namespace, metricName, dimensions, region); + PaginatedResult page = + metricsService.listMetricsPage(namespace, metricName, dimensions, params.getFirst("NextToken"), region); XmlBuilder xml = new XmlBuilder().start("Metrics"); - for (CloudWatchMetricsService.MetricIdentity m : metrics) { + for (CloudWatchMetricsService.MetricIdentity m : page.items()) { XmlBuilder member = xml.start("member") .elem("Namespace", m.namespace()) .elem("MetricName", m.metricName()) @@ -116,6 +116,9 @@ public class CloudWatchMetricsQueryHandler { xml.end("Dimensions").end("member"); } xml.end("Metrics"); + if (page.nextToken() != null) { + xml.elem("NextToken", page.nextToken()); + } return Response.ok(AwsQueryResponse.envelope("ListMetrics", null, xml.build())).build(); } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsService.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsService.java index 75157a716a..2a3b88a8cf 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsService.java @@ -12,6 +12,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.TextNode; import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.Digests; import io.github.hectorvent.floci.core.common.PaginatedResult; import io.github.hectorvent.floci.core.common.Pagination; import io.github.hectorvent.floci.core.common.RegionResolver; @@ -75,6 +76,7 @@ public class CloudWatchMetricsService { .ofPattern("EEEE dd MMMM, yyyy HH:mm:ss 'UTC'", Locale.ENGLISH).withZone(ZoneOffset.UTC); /** The most StateReasonData can hold, in Unicode code points as SetAlarmState's length check counts them. */ private static final int MAX_STATE_REASON_DATA = 4000; + private static final int LIST_METRICS_PAGE_SIZE = 500; private static final ObjectMapper MAPPER = new ObjectMapper() .setSerializationInclusion(JsonInclude.Include.NON_NULL) .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); @@ -243,6 +245,35 @@ public class CloudWatchMetricsService { return new ArrayList<>(deduped.values()); } + public PaginatedResult listMetricsPage(String namespace, String metricName, + List dimensions, String nextToken, + String region) { + String accountId = metricStore instanceof AccountAwareStorageBackend aware + ? aware.accountId() : regionResolver.getAccountId(); + ArrayNode scope = MAPPER.createArrayNode(); + scope.add(accountId).add(region).add(namespace).add(metricName); + appendMetricDimensions(scope, dimensions); + return Pagination.paginate(listMetrics(namespace, metricName, dimensions, region), + CloudWatchMetricsService::metricCursor, LIST_METRICS_PAGE_SIZE, nextToken, + "cloudwatch-list-metrics-" + Digests.sha256Hex(scope.toString()), + token -> CloudWatchMetricsException.invalidParameterValue("Invalid NextToken.")); + } + + static String metricCursor(MetricIdentity metric) { + String identity = metric.namespace() + "::" + metric.metricName() + "::" + buildDimKey(metric.dimensions()); + return Digests.sha256Hex(identity); + } + + private static void appendMetricDimensions(ArrayNode key, List dimensions) { + if (dimensions == null) { + return; + } + dimensions.stream().sorted(Comparator.comparing(Dimension::name, + Comparator.nullsFirst(String::compareTo)) + .thenComparing(Dimension::value, Comparator.nullsFirst(String::compareTo))) + .forEach(dimension -> key.addArray().add(dimension.name()).add(dimension.value())); + } + public record Datapoint(Instant timestamp, double sampleCount, double sum, double average, double minimum, double maximum, String unit) {} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchJsonTargetIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchJsonTargetIntegrationTest.java index 5e3d879c4f..796769ab04 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchJsonTargetIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchJsonTargetIntegrationTest.java @@ -196,7 +196,7 @@ class CloudWatchJsonTargetIntegrationTest { @ParameterizedTest @CsvSource(delimiter = '|', textBlock = """ - ListMetrics | {"Namespace":"json-target-none","MetricName":"Requests","Dimensions":[{"Name":"Host","Value":"a"}],"NextToken":"t"} + ListMetrics | {"Namespace":"json-target-none","MetricName":"Requests","Dimensions":[{"Name":"Host","Value":"a"}]} DescribeAlarms | {"AlarmNames":["json-target-none"],"MaxRecords":10,"NextToken":"t"} DescribeAlarms | {"AlarmNamePrefix":"json-target-none-","MaxRecords":10} GetMetricStatistics | {"Namespace":"json-target-none","MetricName":"Requests","Dimensions":[{"Name":"Host","Value":"a"}],"StartTime":1761091200,"EndTime":1761094800,"Period":60,"Statistics":["Sum"],"Unit":"Count"} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchListMetricsPaginationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchListMetricsPaginationIntegrationTest.java new file mode 100644 index 0000000000..8c4654dc3e --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchListMetricsPaginationIntegrationTest.java @@ -0,0 +1,124 @@ +package io.github.hectorvent.floci.services.cloudwatch.metrics; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.RestAssured; +import io.restassured.config.EncoderConfig; +import io.restassured.http.ContentType; +import io.restassured.response.Response; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; + +import java.time.Instant; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +@QuarkusTest +class CloudWatchListMetricsPaginationIntegrationTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String ACCOUNT = "111111111111"; + private static final String REGION = "us-east-1"; + private static final String CURRENT_TARGET = "GraniteServiceVersion20100801."; + private static final String CONSOLE_TARGET = "CloudWatchVersion20130116."; + + @Test + void listMetricsPaginatesQueryAndBothJsonTargets() throws Exception { + String namespace = "Issue/Pagination/" + UUID.randomUUID(); + ObjectNode putRequest = MAPPER.createObjectNode(); + putRequest.put("Namespace", namespace); + ArrayNode metrics = putRequest.putArray("MetricData"); + long now = Instant.now().getEpochSecond(); + for (int i = 0; i < 501; i++) { + ObjectNode metric = metrics.addObject(); + metric.put("MetricName", "Requests"); + metric.put("Value", 1); + metric.put("Timestamp", now); + metric.putArray("Dimensions").addObject().put("Name", "Host").put("Value", "host-" + i); + } + metrics.addObject().put("MetricName", "Other").put("Value", 1); + json(CURRENT_TARGET + "PutMetricData", putRequest, ACCOUNT, REGION).then().statusCode(200); + + Response queryFirst = query(namespace, "Requests", null, ACCOUNT, REGION).then().statusCode(200).extract() + .response(); + String queryToken = queryFirst.xmlPath().getString("ListMetricsResponse.ListMetricsResult.NextToken"); + assertEquals(500, queryFirst.xmlPath().getList("ListMetricsResponse.ListMetricsResult.Metrics.member").size()); + assertNotNull(queryToken); + Response querySecond = query(namespace, "Requests", queryToken, ACCOUNT, REGION) + .then().statusCode(200).extract().response(); + assertEquals(1, querySecond.xmlPath().getList("ListMetricsResponse.ListMetricsResult.Metrics.member").size()); + assertFalse(querySecond.asString().contains("")); + + for (String target : new String[]{CURRENT_TARGET, CONSOLE_TARGET}) { + ObjectNode listRequest = MAPPER.createObjectNode().put("Namespace", namespace) + .put("MetricName", "Requests"); + JsonNode first = MAPPER.readTree(json(target + "ListMetrics", listRequest, ACCOUNT, REGION) + .then().statusCode(200).extract().asString()); + assertEquals(500, first.path("Metrics").size()); + String token = first.path("NextToken").asText(null); + assertNotNull(token); + listRequest.put("NextToken", token); + JsonNode second = MAPPER.readTree(json(target + "ListMetrics", listRequest, ACCOUNT, REGION) + .then().statusCode(200).extract().asString()); + assertEquals(1, second.path("Metrics").size()); + assertFalse(second.has("NextToken")); + Set hosts = new HashSet<>(); + for (JsonNode page : new JsonNode[]{first, second}) { + for (JsonNode metric : page.path("Metrics")) { + assertEquals("Requests", metric.path("MetricName").asText()); + hosts.add(metric.path("Dimensions").get(0).path("Value").asText()); + } + } + assertEquals(501, hosts.size()); + listRequest.put("NextToken", 123); + json(target + "ListMetrics", listRequest, ACCOUNT, REGION).then().statusCode(400) + .body("__type", equalTo("InvalidParameterValueException")); + } + + for (Response invalid : new Response[]{ + query(namespace, "Requests", queryToken, "222222222222", REGION), + query(namespace, "Requests", queryToken, ACCOUNT, "us-west-2"), + query(namespace, "Other", queryToken, ACCOUNT, REGION), + query(namespace, "Requests", "not-a-token", ACCOUNT, REGION)}) { + invalid.then().statusCode(400).body("ErrorResponse.Error.Code", equalTo("InvalidParameterValue")); + } + } + + private static Response query(String namespace, String metricName, String token, String account, String region) { + RequestSpecification request = given().header("Authorization", authorization(account, region)) + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "ListMetrics") + .formParam("Version", "2010-08-01") + .formParam("Namespace", namespace) + .formParam("MetricName", metricName); + if (token != null) { + request.formParam("NextToken", token); + } + return request.post("/"); + } + + private static Response json(String target, ObjectNode body, String account, String region) { + return given() + .header("Authorization", authorization(account, region)) + .contentType("application/x-amz-json-1.0") + .config(RestAssured.config().encoderConfig(EncoderConfig.encoderConfig() + .encodeContentTypeAs("application/x-amz-json-1.0", ContentType.TEXT))) + .header("X-Amz-Target", target) + .body(body.toString()) + .post("/"); + } + + private static String authorization(String account, String region) { + return "AWS4-HMAC-SHA256 Credential=" + account + "/20261101/" + region + "/monitoring/aws4_request"; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsServiceTest.java index 5d98460f9c..ce731a18bb 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsServiceTest.java @@ -281,6 +281,95 @@ class CloudWatchMetricsServiceTest { assertEquals(1, result.size()); } + @Test + void listMetricsPagesDistinctDimensionsAndScopesTheCursor() { + List datums = new ArrayList<>(); + for (int i = 0; i < 501; i++) { + MetricDatum datum = datum("Latency", 1); + datum.setDimensions(List.of(new Dimension("A", "one"), new Dimension("B", "two"), + new Dimension("C", "host-" + i))); + datums.add(datum); + } + service.putMetricData(NAMESPACE, datums, REGION); + + List filters = List.of(new Dimension("A", "one"), new Dimension("B", "two")); + PaginatedResult first = + service.listMetricsPage(NAMESPACE, "Latency", filters, null, REGION); + assertEquals(500, first.items().size()); + assertNotNull(first.nextToken()); + PaginatedResult second = + service.listMetricsPage(NAMESPACE, "Latency", List.of(filters.get(1), filters.get(0)), + first.nextToken(), REGION); + assertEquals(1, second.items().size()); + assertNull(second.nextToken()); + List all = new ArrayList<>(first.items()); + all.addAll(second.items()); + assertEquals(501, all.stream().map(metric -> metric.dimensions().get(2).value()).distinct().count()); + + PaginatedResult filtered = service.listMetricsPage( + NAMESPACE, "Latency", List.of(new Dimension("C", "host-500")), null, REGION); + assertEquals(1, filtered.items().size()); + assertNull(filtered.nextToken()); + AwsException changedFilter = assertThrows(AwsException.class, () -> service.listMetricsPage( + NAMESPACE, "Latency", List.of(new Dimension("A", "other")), first.nextToken(), REGION)); + assertEquals("InvalidParameterValue", changedFilter.getErrorCode()); + AwsException changedRegion = assertThrows(AwsException.class, () -> service.listMetricsPage( + NAMESPACE, "Latency", filters, first.nextToken(), "us-west-2")); + assertEquals("InvalidParameterValue", changedRegion.getErrorCode()); + AwsException malformed = assertThrows(AwsException.class, () -> service.listMetricsPage( + NAMESPACE, "Latency", filters, "not-a-token", REGION)); + assertEquals("InvalidParameterValue", malformed.getErrorCode()); + } + + @Test + void listMetricsPageBoundaryPreservesDifferentOrdersOfRepeatedDimensionNames() { + List firstDimensions = List.of(new Dimension("A", "one"), new Dimension("A", "two")); + List secondDimensions = firstDimensions.reversed(); + String metricName = "repeated-dimension"; + CloudWatchMetricsService.MetricIdentity firstIdentity = + new CloudWatchMetricsService.MetricIdentity(NAMESPACE, metricName, firstDimensions); + while (CloudWatchMetricsService.metricCursor(firstIdentity).charAt(0) < '8') { + metricName += "-next"; + firstIdentity = new CloudWatchMetricsService.MetricIdentity(NAMESPACE, metricName, firstDimensions); + } + CloudWatchMetricsService.MetricIdentity secondIdentity = + new CloudWatchMetricsService.MetricIdentity(NAMESPACE, metricName, secondDimensions); + String boundaryCursor = CloudWatchMetricsService.metricCursor(firstIdentity); + assertNotEquals(boundaryCursor, CloudWatchMetricsService.metricCursor(secondIdentity)); + + List datums = new ArrayList<>(); + MetricDatum first = datum(metricName, 1); + first.setDimensions(firstDimensions); + datums.add(first); + MetricDatum second = datum(metricName, 1); + second.setDimensions(secondDimensions); + datums.add(second); + for (int i = 0; datums.size() < 501; i++) { + String fillerName = "filler-" + i; + CloudWatchMetricsService.MetricIdentity filler = + new CloudWatchMetricsService.MetricIdentity(NAMESPACE, fillerName, List.of()); + if (CloudWatchMetricsService.metricCursor(filler).compareTo(boundaryCursor) < 0) { + datums.add(datum(fillerName, 1)); + } + } + service.putMetricData(NAMESPACE, datums, REGION); + + PaginatedResult firstPage = + service.listMetricsPage(NAMESPACE, null, null, null, REGION); + PaginatedResult secondPage = + service.listMetricsPage(NAMESPACE, null, null, firstPage.nextToken(), REGION); + assertEquals(500, firstPage.items().size()); + assertEquals(1, secondPage.items().size()); + assertNull(secondPage.nextToken()); + assertEquals(metricName, secondPage.items().getFirst().metricName()); + } + + @Test + void listMetricsFilterScopeAllowsMissingValuesForRepeatedNames() { + List filters = List.of(new Dimension("A", null), new Dimension("A", "one")); + assertTrue(service.listMetricsPage(NAMESPACE, null, filters, null, REGION).items().isEmpty()); + } + @Test void putMetricDataWithStatisticValues() { MetricDatum d = new MetricDatum();