Light, fluffy, and always free - The AWS Local Emulator alternative
fix(logs): paginate log group descriptions (#6142)
Aniket Shukla804b1d9597e2
diff --git a/docs/services/cloudwatch.md b/docs/services/cloudwatch.mdindex cce0f86ec7..ba2b301b00 100644--- a/docs/services/cloudwatch.md+++ b/docs/services/cloudwatch.md@@ -51,6 +51,10 @@ Floci supports both CloudWatch Logs and CloudWatch Metrics.| `GetQueryResults` | Get the status and results of a Logs Insights query || `StopQuery` | Stop a query that has not completed yet |+`DescribeLogGroups` returns names in ASCII order, with up to 50 groups per page by default.+Set `limit` to an integer from 1 to 50 and pass the returned `nextToken` with the same region+and name prefix to continue. The final page omits `nextToken`.+Log group deletion protection defaults to disabled and is persisted with the log group. When it isenabled, `DeleteLogGroup` returns `ValidationException` until protection is explicitly disabledwith `PutLogGroupDeletionProtection`.diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandler.javaindex b39144af49..00a91100b9 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandler.java@@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsErrorResponse;import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.PaginatedResult;import io.github.hectorvent.floci.services.cloudwatch.logs.model.AccountPolicy;import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogDestination;import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogEvent;@@ -127,11 +128,23 @@ public class CloudWatchLogsHandler {private Response handleDescribeLogGroups(JsonNode request, String region) {String prefix = request.path("logGroupNamePrefix").asText(null);- List<LogGroup> groups = logsService.describeLogGroups(prefix, region);+ int limit = 50;+ if (request.hasNonNull("limit")) {+ JsonNode value = request.get("limit");+ if (!value.isIntegralNumber() || !value.canConvertToInt()) {+ throw new AwsException("InvalidParameterException", "limit must be an integer.", 400);+ }+ limit = value.intValue();+ }+ String nextToken = request.path("nextToken").asText(null);+ if (request.hasNonNull("nextToken") && !request.get("nextToken").isTextual()) {+ throw CloudWatchLogsService.invalidNextToken();+ }+ PaginatedResult<LogGroup> page = logsService.describeLogGroups(prefix, region, limit, nextToken);ObjectNode response = objectMapper.createObjectNode();ArrayNode groupsArray = objectMapper.createArrayNode();- for (LogGroup g : groups) {+ for (LogGroup g : page.items()) {ObjectNode node = objectMapper.createObjectNode();node.put("logGroupName", g.getLogGroupName());node.put("creationTime", g.getCreatedTime());@@ -150,6 +163,9 @@ public class CloudWatchLogsHandler {groupsArray.add(node);}response.set("logGroups", groupsArray);+ 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/logs/CloudWatchLogsService.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.javaindex 129dfb4d04..07a2382a80 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java@@ -5,6 +5,8 @@ import io.github.hectorvent.floci.config.EmulatorConfig;import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.Base64Url;+import io.github.hectorvent.floci.core.common.PaginatedResult;+import io.github.hectorvent.floci.core.common.Pagination;import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.core.common.Resettable;import io.github.hectorvent.floci.core.common.SmithyValidationErrors;@@ -361,8 +363,28 @@ public class CloudWatchLogsService implements ResourceProvider, Resettable {}public List<LogGroup> describeLogGroups(String prefix, String region) {+ List<LogGroup> result = matchingLogGroups(prefix, region);+ result.sort(Comparator.comparing(LogGroup::getLogGroupName));+ return result;+ }++ PaginatedResult<LogGroup> describeLogGroups(String prefix, String region, int limit, String nextToken) {+ if (limit < 1 || limit > 50) {+ String constraint = limit < 1 ? "greater than or equal to 1" : "less than or equal to 50";+ throw SmithyValidationErrors.exception("InvalidParameterException",+ "Value '" + limit + "' at 'limit' failed to satisfy constraint: Member must have value " + constraint);+ }+ if (nextToken != null && nextToken.isEmpty()) {+ throw invalidNextToken();+ }+ return Pagination.paginate(matchingLogGroups(prefix, region), LogGroup::getLogGroupName, limit, nextToken,+ "DescribeLogGroups:" + region + ":" + (prefix == null ? "" : prefix),+ token -> invalidNextToken());+ }++ private List<LogGroup> matchingLogGroups(String prefix, String region) {String storagePrefix = groupKeyPrefix(region);- List<LogGroup> result = groupStore.scan(k -> {+ return groupStore.scan(k -> {if (!k.startsWith(storagePrefix)) {return false;}@@ -372,8 +394,6 @@ public class CloudWatchLogsService implements ResourceProvider, Resettable {String groupName = k.substring(storagePrefix.length());return groupName.startsWith(prefix);});- result.sort(Comparator.comparing(LogGroup::getLogGroupName));- return result;}public long getStoredBytesForLogGroup(String groupName, String region) {@@ -650,7 +670,7 @@ public class CloudWatchLogsService implements ResourceProvider, Resettable {return Base64Url.encode(raw);}- private static AwsException invalidNextToken() {+ static AwsException invalidNextToken() {return new AwsException("InvalidParameterException", "The specified nextToken is invalid.", 400);}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsGroupPageSortTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsGroupPageSortTest.javanew file mode 100644index 0000000000..52a4f5172c--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsGroupPageSortTest.java@@ -0,0 +1,71 @@+package io.github.hectorvent.floci.services.cloudwatch.logs;++import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ObjectNode;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.storage.InMemoryStorage;+import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogGroup;+import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;+import jakarta.ws.rs.core.Response;+import org.junit.jupiter.api.Test;++import java.util.ArrayList;+import java.util.List;+import java.util.concurrent.atomic.AtomicInteger;+import java.util.function.Predicate;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.Mockito.mock;++class CloudWatchLogsGroupPageSortTest {++ @Test+ void aLargePageStaysWithinOneSortsNameReadBudget() {+ AtomicInteger nameReads = new AtomicInteger();+ List<LogGroup> groups = new ArrayList<>();+ for (int i = 999; i >= 0; i--) {+ LogGroup group = new LogGroup() {+ @Override+ public String getLogGroupName() {+ nameReads.incrementAndGet();+ return super.getLogGroupName();+ }+ };+ group.setLogGroupName(String.format("group-%03d", i));+ groups.add(group);+ }+ InMemoryStorage<String, LogGroup> groupStore = new InMemoryStorage<>() {+ @Override+ public List<LogGroup> scan(Predicate<String> keyFilter) {+ return new ArrayList<>(groups);+ }+ };+ RegionResolver resolver = new RegionResolver("us-east-1", "000000000000");+ CloudWatchLogsService service = new CloudWatchLogsService(groupStore,+ new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),+ 10_000, resolver);+ ObjectMapper mapper = new ObjectMapper();+ CloudWatchLogsHandler handler = new CloudWatchLogsHandler(service,+ new CloudWatchLogsCrossAccountService(new InMemoryStorage<>(), new InMemoryStorage<>(), resolver, mapper),+ new CloudWatchLogsMetricFilterService(service, mock(CloudWatchMetricsService.class), resolver), mapper);+ List<Integer> measurements = new ArrayList<>();+ for (int sample = 0; sample < 3; sample++) {+ nameReads.set(0);+ try (Response response = handler.handle("DescribeLogGroups", mapper.createObjectNode(), "us-east-1")) {+ ObjectNode entity = (ObjectNode) response.getEntity();+ assertEquals(50, entity.path("logGroups").size());+ assertEquals("group-000", entity.path("logGroups").get(0).path("logGroupName").asText());+ assertEquals("group-049", entity.path("logGroups").get(49).path("logGroupName").asText());+ assertTrue(entity.has("nextToken"));+ }+ measurements.add(nameReads.get());+ }+ // A single TimSort run over 1000 reverse-ordered names takes about 2000 reads; allow page rendering too.+ assertTrue(measurements.stream().allMatch(reads -> reads < 3000),+ "Redundant full-list sorting exceeds the name-read budget: " + measurements);+ List<LogGroup> unpaged = service.describeLogGroups(null, "us-east-1");+ assertEquals("group-000", unpaged.getFirst().getLogGroupName());+ assertEquals("group-999", unpaged.getLast().getLogGroupName());+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsGroupPaginationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsGroupPaginationIntegrationTest.javanew file mode 100644index 0000000000..eda0f47131--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsGroupPaginationIntegrationTest.java@@ -0,0 +1,156 @@+package io.github.hectorvent.floci.services.cloudwatch.logs;++import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import io.restassured.response.Response;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.CsvSource;+import org.junit.jupiter.params.provider.ValueSource;++import java.util.ArrayList;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+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 CloudWatchLogsGroupPaginationIntegrationTest {++ private final String prefix = "/floci/group-pages/" + UUID.randomUUID() + "/";+ private final List<String> groups = new ArrayList<>();++ @BeforeAll+ static void configureContentTypes() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @AfterEach+ void deleteOwnedGroups() {+ for (String group : groups) {+ logs("DeleteLogGroup", Map.of("logGroupName", group)).then().statusCode(200);+ }+ }++ @Test+ void traversesAsciiSortedPagesWithoutRepeatingOrSkippingGroups() {+ createGroups(3);+ List<String> found = new ArrayList<>();+ String token = null;+ for (int page = 0; page < 3; page++) {+ Map<String, Object> request = new HashMap<>(Map.of("logGroupNamePrefix", prefix, "limit", 1));+ if (token != null) {+ request.put("nextToken", token);+ }+ Response response = logs("DescribeLogGroups", request).then().statusCode(200).extract().response();+ List<String> names = response.jsonPath().getList("logGroups.logGroupName", String.class);+ assertEquals(1, names.size());+ found.addAll(names);+ token = response.path("nextToken");+ if (page < 2) {+ assertNotNull(token);+ } else {+ assertFalse(response.jsonPath().getMap("$").containsKey("nextToken"));+ }+ }+ assertEquals(groups.stream().sorted().toList(), found);+ }++ @Test+ void defaultsToFiftyGroupsAndReturnsTheRemainder() {+ createGroups(51);+ Response first = logs("DescribeLogGroups", Map.of("logGroupNamePrefix", prefix))+ .then().statusCode(200).extract().response();+ assertEquals(50, first.jsonPath().getList("logGroups").size());+ String token = first.path("nextToken");+ assertNotNull(token);+ Response last = logs("DescribeLogGroups", Map.of("logGroupNamePrefix", prefix, "nextToken", token))+ .then().statusCode(200).extract().response();+ assertEquals(List.of(groups.stream().sorted().toList().get(50)),+ last.jsonPath().getList("logGroups.logGroupName", String.class));+ assertFalse(last.jsonPath().getMap("$").containsKey("nextToken"));+ }++ @ParameterizedTest+ @ValueSource(strings = {"0", "-1", "51", "1.5", "\"one\"", "999999999999999999999"})+ void rejectsInvalidLimits(String limit) {+ given().contentType("application/x-amz-json-1.1")+ .header("X-Amz-Target", "Logs_20140328.DescribeLogGroups")+ .body("{\"limit\":" + limit + "}").post("/").then().statusCode(400)+ .body("__type", equalTo("InvalidParameterException"));+ }++ @ParameterizedTest+ @CsvSource({"0, greater than or equal to 1", "51, less than or equal to 50"})+ void reportsOutOfRangeLimitsWithSmithyValidation(int limit, String constraint) {+ logs("DescribeLogGroups", Map.of("limit", limit)).then().statusCode(400)+ .body("__type", equalTo("InvalidParameterException"))+ .body("message", equalTo("1 validation error detected: Value '" + limit+ + "' at 'limit' failed to satisfy constraint: Member must have value " + constraint));+ }++ @ParameterizedTest+ @ValueSource(strings = {"\"not-base64!\"", "\"d3Jvbmctb3BlcmF0aW9u\"", "\"\"", "123", "{}"})+ void rejectsInvalidTokens(String token) {+ given().contentType("application/x-amz-json-1.1")+ .header("X-Amz-Target", "Logs_20140328.DescribeLogGroups")+ .body("{\"nextToken\":" + token + "}").post("/").then().statusCode(400)+ .body("__type", equalTo("InvalidParameterException"))+ .body("message", equalTo("The specified nextToken is invalid."));+ }++ @Test+ void reportsBadTokensLikeDescribeLogStreams() {+ createGroups(1);+ String group = groups.getFirst();+ logs("CreateLogStream", Map.of("logGroupName", group, "logStreamName", "stream"))+ .then().statusCode(200);+ String streamError = logs("DescribeLogStreams", Map.of("logGroupName", group, "nextToken", "bad!"))+ .then().statusCode(400).extract().path("message");+ logs("DescribeLogGroups", Map.of("nextToken", "bad!")).then().statusCode(400)+ .body("__type", equalTo("InvalidParameterException"))+ .body("message", equalTo(streamError));+ }++ @Test+ void resumesAfterADeletedCursorAndHandlesEmptyResults() {+ createGroups(3);+ Response first = logs("DescribeLogGroups", Map.of("logGroupNamePrefix", prefix, "limit", 1))+ .then().statusCode(200).extract().response();+ String cursorGroup = first.path("logGroups[0].logGroupName");+ String token = first.path("nextToken");+ assertNotNull(token);+ logs("DeleteLogGroup", Map.of("logGroupName", cursorGroup)).then().statusCode(200);+ groups.remove(cursorGroup);+ Response next = logs("DescribeLogGroups", Map.of("logGroupNamePrefix", prefix, "nextToken", token))+ .then().statusCode(200).extract().response();+ assertEquals(groups.stream().sorted().toList(),+ next.jsonPath().getList("logGroups.logGroupName", String.class));+ assertFalse(next.jsonPath().getMap("$").containsKey("nextToken"));+ Response empty = logs("DescribeLogGroups", Map.of("logGroupNamePrefix", prefix + "missing"))+ .then().statusCode(200).extract().response();+ assertEquals(List.of(), empty.jsonPath().getList("logGroups"));+ assertFalse(empty.jsonPath().getMap("$").containsKey("nextToken"));+ }++ private void createGroups(int count) {+ for (int i = count - 1; i >= 0; i--) {+ String group = prefix + String.format("%03d", i);+ logs("CreateLogGroup", Map.of("logGroupName", group)).then().statusCode(200);+ groups.add(group);+ }+ }++ private Response logs(String action, Map<String, ?> body) {+ return given().contentType("application/x-amz-json-1.1")+ .header("X-Amz-Target", "Logs_20140328." + action).body(body).post("/");+ }+}