Light, fluffy, and always free - The AWS Local Emulator alternative
fix(cloudwatch): implement tagging support for metrics and alarms (#320)
Hector Venturac426e805fea6
diff --git a/compatibility-tests/compat-terraform/main.tf b/compatibility-tests/compat-terraform/main.tfindex 97aa283aa6..916b8d5008 100644--- a/compatibility-tests/compat-terraform/main.tf+++ b/compatibility-tests/compat-terraform/main.tf@@ -174,3 +174,24 @@ output "user_pool_id" {output "user_pool_arn" {value = aws_cognito_user_pool.pool.arn}++# -- CloudWatch Alarms ---------------------------------------------------------+resource "aws_cloudwatch_metric_alarm" "cpu" {+ alarm_name = "floci-compat-cpu-alarm"+ comparison_operator = "GreaterThanThreshold"+ evaluation_periods = 1+ metric_name = "CPUUtilization"+ namespace = "AWS/EC2"+ period = 60+ statistic = "Average"+ threshold = 80+ alarm_description = "CPU alarm for compat test"++ tags = {+ env = "compat-test"+ }+}++output "alarm_arn" {+ value = aws_cloudwatch_metric_alarm.cpu.arn+}diff --git a/compatibility-tests/compat-terraform/provider.tf b/compatibility-tests/compat-terraform/provider.tfindex 32a995dd5a..e9430cb313 100644--- a/compatibility-tests/compat-terraform/provider.tf+++ b/compatibility-tests/compat-terraform/provider.tf@@ -35,5 +35,6 @@ provider "aws" {ssm = var.endpointsecretsmanager = var.endpointcognitoidp = var.endpoint+ cloudwatch = var.endpoint}}diff --git a/compatibility-tests/compat-terraform/test/terraform.bats b/compatibility-tests/compat-terraform/test/terraform.batsindex 6f9ccb6932..6d086e1d15 100644--- a/compatibility-tests/compat-terraform/test/terraform.bats+++ b/compatibility-tests/compat-terraform/test/terraform.bats@@ -95,3 +95,15 @@ setup() {assert_successassert_output --partial "floci-compat"}++@test "Terraform: CloudWatch alarm created with tags" {+ run aws_cmd cloudwatch describe-alarms --alarm-names floci-compat-cpu-alarm+ assert_success+ assert_output --partial "floci-compat-cpu-alarm"++ ALARM_ARN=$(aws_cmd cloudwatch describe-alarms --alarm-names floci-compat-cpu-alarm \+ --query 'MetricAlarms[0].AlarmArn' --output text)+ run aws_cmd cloudwatch list-tags-for-resource --resource-arn "$ALARM_ARN"+ assert_success+ assert_output --partial "compat-test"+}diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.javaindex 09e982e761..be4d3b65e1 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java@@ -147,7 +147,10 @@ public class AwsJsonCborController {return Response.status(404).build();}- byte[] cborBytes = nodeToSmithyCbor((JsonNode) delegated.getEntity());+ JsonNode responseNode = delegated.getEntity() instanceof JsonNode+ ? (JsonNode) delegated.getEntity()+ : objectMapper.valueToTree(delegated.getEntity());+ byte[] cborBytes = nodeToSmithyCbor(responseNode);return Response.status(delegated.getStatus()).header("Smithy-Protocol", "rpc-v2-cbor").type("application/cbor")@@ -224,7 +227,10 @@ public class AwsJsonCborController {return null;}- byte[] cborBytes = nodeToSmithyCbor((JsonNode) delegated.getEntity());+ JsonNode responseNode = delegated.getEntity() instanceof JsonNode+ ? (JsonNode) delegated.getEntity()+ : objectMapper.valueToTree(delegated.getEntity());+ byte[] cborBytes = nodeToSmithyCbor(responseNode);return Response.status(delegated.getStatus()).header("smithy-protocol", "rpc-v2-cbor").type("application/cbor")diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.javaindex b08d0cc256..1d5ef1d2af 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java@@ -227,7 +227,9 @@ public class AwsQueryController {);private static final Set<String> CLOUDWATCH_ACTIONS = Set.of(- "PutMetricData", "ListMetrics", "GetMetricStatistics", "GetMetricData"+ "PutMetricData", "ListMetrics", "GetMetricStatistics", "GetMetricData",+ "PutMetricAlarm", "DescribeAlarms", "DeleteAlarms", "SetAlarmState",+ "ListTagsForResource", "TagResource", "UntagResource");private static final Set<String> RDS_ACTIONS = Set.of(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.javaindex 58d57028ee..b5ff9cda7e 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@@ -14,7 +14,9 @@ import jakarta.ws.rs.core.Response;import java.time.Instant;import java.util.ArrayList;+import java.util.LinkedHashMap;import java.util.List;+import java.util.Map;/*** Handles CloudWatch Metrics requests via the JSON 1.0 protocol.@@ -33,7 +35,8 @@ public class CloudWatchMetricsJsonHandler {}public Response handle(String action, JsonNode request, String region) {- return switch (action) {+ String normalizedAction = action.substring(0, 1).toUpperCase() + action.substring(1);+ return switch (normalizedAction) {case "PutMetricData" -> handlePutMetricData(request, region);case "ListMetrics" -> handleListMetrics(request, region);case "GetMetricStatistics" -> handleGetMetricStatistics(request, region);@@ -41,9 +44,12 @@ public class CloudWatchMetricsJsonHandler {case "DescribeAlarms" -> handleDescribeAlarms(request, region);case "DeleteAlarms" -> handleDeleteAlarms(request, region);case "SetAlarmState" -> handleSetAlarmState(request, region);+ case "ListTagsForResource" -> handleListTagsForResource(request, region);+ case "TagResource" -> handleTagResource(request, region);+ case "UntagResource" -> handleUntagResource(request, region);case "GetMetricData" -> Response.ok(objectMapper.createObjectNode().putArray("MetricDataResults")).build();default -> Response.status(400)- .entity(new AwsErrorResponse("UnsupportedOperation", "Operation " + action + " is not supported."))+ .entity(new AwsErrorResponse("UnsupportedOperation", "Operation " + action + " is not supported by CloudWatch JSON.")).build();};}@@ -139,6 +145,13 @@ public class CloudWatchMetricsJsonHandler {okActions.forEach(a -> alarm.getOkActions().add(a.asText()));}+ JsonNode tagsNode = request.has("Tags") ? request.path("Tags") : request.path("tags");+ if (tagsNode.isArray()) {+ Map<String, String> tags = new LinkedHashMap<>();+ tagsNode.forEach(t -> tags.put(t.path("Key").asText(), t.path("Value").asText()));+ alarm.setTags(tags);+ }+metricsService.putMetricAlarm(alarm, region);return Response.ok(objectMapper.createObjectNode()).build();}@@ -192,6 +205,42 @@ public class CloudWatchMetricsJsonHandler {return Response.ok(objectMapper.createObjectNode()).build();}+ private Response handleListTagsForResource(JsonNode request, String region) {+ String arn = request.has("ResourceARN") ? request.path("ResourceARN").asText() : request.path("ResourceArn").asText();+ if (arn.isEmpty()) arn = request.path("resourceArn").asText();++ Map<String, String> tags = metricsService.listTagsForResource(arn, region);+ ArrayNode tagsArray = objectMapper.createArrayNode();+ tags.forEach((k, v) -> tagsArray.addObject().put("Key", k).put("Value", v));+ return Response.ok(objectMapper.createObjectNode().set("Tags", tagsArray)).build();+ }++ private Response handleTagResource(JsonNode request, String region) {+ String arn = request.has("ResourceARN") ? request.path("ResourceARN").asText() : request.path("ResourceArn").asText();+ if (arn.isEmpty()) arn = request.path("resourceArn").asText();++ Map<String, String> tags = new LinkedHashMap<>();+ JsonNode tagsNode = request.has("Tags") ? request.path("Tags") : request.path("tags");+ if (tagsNode.isArray()) {+ tagsNode.forEach(t -> tags.put(t.path("Key").asText(), t.path("Value").asText()));+ }+ metricsService.tagResource(arn, tags, region);+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ private Response handleUntagResource(JsonNode request, String region) {+ String arn = request.has("ResourceARN") ? request.path("ResourceARN").asText() : request.path("ResourceArn").asText();+ if (arn.isEmpty()) arn = request.path("resourceArn").asText();++ List<String> keys = new ArrayList<>();+ JsonNode keysNode = request.has("TagKeys") ? request.path("TagKeys") : request.path("tagKeys");+ if (keysNode.isArray()) {+ keysNode.forEach(k -> keys.add(k.asText()));+ }+ metricsService.untagResource(arn, keys, region);+ return Response.ok(objectMapper.createObjectNode()).build();+ }+private List<MetricDatum> parseMetricDataJson(JsonNode node) {List<MetricDatum> datums = new ArrayList<>();if (!node.isArray()) return datums;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.javaindex f8774be2da..dd9fedf10a 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@@ -15,7 +15,9 @@ import org.jboss.logging.Logger;import java.time.Instant;import java.time.format.DateTimeFormatter;import java.util.ArrayList;+import java.util.LinkedHashMap;import java.util.List;+import java.util.Map;@ApplicationScopedpublic class CloudWatchMetricsQueryHandler {@@ -30,8 +32,8 @@ public class CloudWatchMetricsQueryHandler {}public Response handle(String action, MultivaluedMap<String, String> params, String region) {- LOG.debugv("CloudWatch Metrics action: {0}", action);- return switch (action) {+ String normalizedAction = action.substring(0, 1).toUpperCase() + action.substring(1);+ return switch (normalizedAction) {case "PutMetricData" -> handlePutMetricData(params, region);case "ListMetrics" -> handleListMetrics(params, region);case "GetMetricStatistics" -> handleGetMetricStatistics(params, region);@@ -40,8 +42,11 @@ public class CloudWatchMetricsQueryHandler {case "DescribeAlarms" -> handleDescribeAlarms(params, region);case "DeleteAlarms" -> handleDeleteAlarms(params, region);case "SetAlarmState" -> handleSetAlarmState(params, region);+ case "ListTagsForResource" -> handleListTagsForResource(params, region);+ case "TagResource" -> handleTagResource(params, region);+ case "UntagResource" -> handleUntagResource(params, region);default -> AwsQueryResponse.error("UnsupportedOperation",- "Operation " + action + " is not supported by CloudWatch.", AwsNamespaces.CW, 400);+ "Operation " + action + " is not supported by CloudWatch Query.", AwsNamespaces.CW, 400);};}@@ -178,6 +183,39 @@ public class CloudWatchMetricsQueryHandler {return Response.ok(AwsQueryResponse.envelopeNoResult("SetAlarmState", null)).build();}+ private Response handleListTagsForResource(MultivaluedMap<String, String> params, String region) {+ String arn = params.getFirst("ResourceARN");+ Map<String, String> tags = metricsService.listTagsForResource(arn, region);+ XmlBuilder xml = new XmlBuilder().start("Tags");+ tags.forEach((k, v) -> xml.start("member").elem("Key", k).elem("Value", v).end("member"));+ xml.end("Tags");+ return Response.ok(AwsQueryResponse.envelope("ListTagsForResource", null, xml.build())).build();+ }++ private Response handleTagResource(MultivaluedMap<String, String> params, String region) {+ String arn = params.getFirst("ResourceARN");+ Map<String, String> tags = new LinkedHashMap<>();+ for (int i = 1; ; i++) {+ String key = params.getFirst("Tags.member." + i + ".Key");+ if (key == null) break;+ tags.put(key, params.getFirst("Tags.member." + i + ".Value"));+ }+ metricsService.tagResource(arn, tags, region);+ return Response.ok(AwsQueryResponse.envelopeNoResult("TagResource", null)).build();+ }++ private Response handleUntagResource(MultivaluedMap<String, String> params, String region) {+ String arn = params.getFirst("ResourceARN");+ List<String> keys = new ArrayList<>();+ for (int i = 1; ; i++) {+ String key = params.getFirst("TagKeys.member." + i);+ if (key == null) break;+ keys.add(key);+ }+ metricsService.untagResource(arn, keys, region);+ return Response.ok(AwsQueryResponse.envelopeNoResult("UntagResource", null)).build();+ }+// ──────────────────────────── Parsing Helpers ────────────────────────────private List<MetricDatum> parseMetricData(MultivaluedMap<String, String> params) {@@ -284,6 +322,15 @@ public class CloudWatchMetricsQueryHandler {a.getInsufficientDataActions().add(act);}+ // Tags+ Map<String, String> tags = new LinkedHashMap<>();+ for (int i = 1; ; i++) {+ String key = params.getFirst("Tags.member." + i + ".Key");+ if (key == null) break;+ tags.put(key, params.getFirst("Tags.member." + i + ".Value"));+ }+ a.setTags(tags);+return a;}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.javaindex e368b90c2e..a3d50b88d7 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@@ -202,6 +202,37 @@ public class CloudWatchMetricsService {LOG.infov("SetAlarmState: {0} -> {1}", alarmName, stateValue);}+ public Map<String, String> listTagsForResource(String resourceArn, String region) {+ return alarmStore.scan(k -> k.startsWith(region + "::"))+ .stream()+ .filter(a -> resourceArn.equals(a.getAlarmArn()))+ .findFirst()+ .map(MetricAlarm::getTags)+ .orElse(Map.of());+ }++ public void tagResource(String resourceArn, Map<String, String> tags, String region) {+ alarmStore.scan(k -> k.startsWith(region + "::"))+ .stream()+ .filter(a -> resourceArn.equals(a.getAlarmArn()))+ .findFirst()+ .ifPresent(alarm -> {+ alarm.getTags().putAll(tags);+ alarmStore.put(region + "::" + alarm.getAlarmName(), alarm);+ });+ }++ public void untagResource(String resourceArn, List<String> tagKeys, String region) {+ alarmStore.scan(k -> k.startsWith(region + "::"))+ .stream()+ .filter(a -> resourceArn.equals(a.getAlarmArn()))+ .findFirst()+ .ifPresent(alarm -> {+ tagKeys.forEach(alarm.getTags()::remove);+ alarmStore.put(region + "::" + alarm.getAlarmName(), alarm);+ });+ }+// ──────────────────────────── Helpers ────────────────────────────static String buildDimKey(List<Dimension> dimensions) {diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/model/MetricAlarm.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/model/MetricAlarm.javaindex 83e7fb647a..4c8e25f838 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/model/MetricAlarm.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/model/MetricAlarm.java@@ -5,7 +5,9 @@ import io.quarkus.runtime.annotations.RegisterForReflection;import java.time.Instant;import java.util.ArrayList;+import java.util.HashMap;import java.util.List;+import java.util.Map;@RegisterForReflection@JsonIgnoreProperties(ignoreUnknown = true)@@ -34,6 +36,7 @@ public class MetricAlarm {private String comparisonOperator;private String treatMissingData = "missing";private String evaluateLowSampleCountPercentile;+ private Map<String, String> tags = new HashMap<>();public MetricAlarm() {long now = Instant.now().getEpochSecond();@@ -112,4 +115,7 @@ public class MetricAlarm {public String getEvaluateLowSampleCountPercentile() { return evaluateLowSampleCountPercentile; }public void setEvaluateLowSampleCountPercentile(String percentile) { this.evaluateLowSampleCountPercentile = percentile; }++ public Map<String, String> getTags() { return tags; }+ public void setTags(Map<String, String> tags) { this.tags = tags; }}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsTagsTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsTagsTest.javanew file mode 100644index 0000000000..46ccb069f1--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsTagsTest.java@@ -0,0 +1,136 @@+package io.github.hectorvent.floci.services.cloudwatch.metrics;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.storage.InMemoryStorage;+import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;+import jakarta.ws.rs.core.MultivaluedHashMap;+import jakarta.ws.rs.core.MultivaluedMap;+import jakarta.ws.rs.core.Response;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.util.List;+import java.util.Map;++import static org.junit.jupiter.api.Assertions.*;++class CloudWatchMetricsTagsTest {++ private static final String REGION = "us-east-1";+ private CloudWatchMetricsService service;+ private CloudWatchMetricsQueryHandler queryHandler;+ private CloudWatchMetricsJsonHandler jsonHandler;+ private ObjectMapper objectMapper = new ObjectMapper();++ @BeforeEach+ void setUp() {+ service = new CloudWatchMetricsService(+ new InMemoryStorage<>(),+ new InMemoryStorage<>(),+ new RegionResolver("us-east-1", "000000000000")+ );+ queryHandler = new CloudWatchMetricsQueryHandler(service);+ jsonHandler = new CloudWatchMetricsJsonHandler(service, objectMapper);+ }++ @Test+ void listTagsReturnsEmptyForNoTags() {+ MetricAlarm alarm = new MetricAlarm();+ alarm.setAlarmName("test-alarm");+ alarm.setAlarmArn("arn:aws:cloudwatch:us-east-1:000000000000:alarm:test-alarm");+ service.putMetricAlarm(alarm, REGION);++ Map<String, String> tags = service.listTagsForResource(alarm.getAlarmArn(), REGION);+ assertTrue(tags.isEmpty());+ }++ @Test+ void tagAndListTags() {+ MetricAlarm alarm = new MetricAlarm();+ alarm.setAlarmName("test-alarm");+ alarm.setAlarmArn("arn:aws:cloudwatch:us-east-1:000000000000:alarm:test-alarm");+ service.putMetricAlarm(alarm, REGION);++ service.tagResource(alarm.getAlarmArn(), Map.of("env", "prod", "team", "ops"), REGION);++ Map<String, String> tags = service.listTagsForResource(alarm.getAlarmArn(), REGION);+ assertEquals(2, tags.size());+ assertEquals("prod", tags.get("env"));+ assertEquals("ops", tags.get("team"));+ }++ @Test+ void untagResource() {+ MetricAlarm alarm = new MetricAlarm();+ alarm.setAlarmName("test-alarm");+ alarm.setAlarmArn("arn:aws:cloudwatch:us-east-1:000000000000:alarm:test-alarm");+ service.putMetricAlarm(alarm, REGION);++ service.tagResource(alarm.getAlarmArn(), Map.of("env", "prod", "team", "ops"), REGION);+ service.untagResource(alarm.getAlarmArn(), List.of("team"), REGION);++ Map<String, String> tags = service.listTagsForResource(alarm.getAlarmArn(), REGION);+ assertEquals(1, tags.size());+ assertEquals("prod", tags.get("env"));+ assertNull(tags.get("team"));+ }++ @Test+ void tagsViaPutMetricAlarmQuery() {+ MultivaluedMap<String, String> params = new MultivaluedHashMap<>();+ params.add("AlarmName", "query-alarm");+ params.add("Tags.member.1.Key", "env");+ params.add("Tags.member.1.Value", "dev");+ params.add("Tags.member.2.Key", "app");+ params.add("Tags.member.2.Value", "floci");++ queryHandler.handle("PutMetricAlarm", params, REGION);++ MetricAlarm alarm = service.describeAlarms(List.of("query-alarm"), null, REGION).getFirst();+ Map<String, String> tags = service.listTagsForResource(alarm.getAlarmArn(), REGION);+ assertEquals("dev", tags.get("env"));+ assertEquals("floci", tags.get("app"));+ }++ @Test+ void listTagsQueryResponse() {+ MetricAlarm alarm = new MetricAlarm();+ alarm.setAlarmName("test-alarm");+ alarm.setAlarmArn("arn:aws:cloudwatch:us-east-1:000000000000:alarm:test-alarm");+ service.putMetricAlarm(alarm, REGION);+ service.tagResource(alarm.getAlarmArn(), Map.of("env", "prod"), REGION);++ MultivaluedMap<String, String> params = new MultivaluedHashMap<>();+ params.add("ResourceARN", alarm.getAlarmArn());++ Response response = queryHandler.handle("ListTagsForResource", params, REGION);+ String xml = (String) response.getEntity();++ assertTrue(xml.contains("<Tags>"));+ assertTrue(xml.contains("<member>"));+ assertTrue(xml.contains("<Key>env</Key>"));+ assertTrue(xml.contains("<Value>prod</Value>"));+ }++ @Test+ void listTagsJsonResponse() {+ MetricAlarm alarm = new MetricAlarm();+ alarm.setAlarmName("test-alarm");+ alarm.setAlarmArn("arn:aws:cloudwatch:us-east-1:000000000000:alarm:test-alarm");+ service.putMetricAlarm(alarm, REGION);+ service.tagResource(alarm.getAlarmArn(), Map.of("env", "prod"), REGION);++ JsonNode request = objectMapper.createObjectNode().put("ResourceARN", alarm.getAlarmArn());+ Response response = jsonHandler.handle("ListTagsForResource", request, REGION);+ JsonNode entity = (JsonNode) response.getEntity();++ assertTrue(entity.has("Tags"));+ JsonNode tags = entity.get("Tags");+ assertTrue(tags.isArray());+ assertEquals(1, tags.size());+ assertEquals("env", tags.get(0).get("Key").asText());+ assertEquals("prod", tags.get(0).get("Value").asText());+ }+}