From c426e805fea62d2b8f4a44e555d873d7dc2a76b4 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Thu, 9 Apr 2026 21:45:54 -0500 Subject: [PATCH] fix(cloudwatch): implement tagging support for metrics and alarms (#320) --- compatibility-tests/compat-terraform/main.tf | 21 +++ .../compat-terraform/provider.tf | 1 + .../compat-terraform/test/terraform.bats | 12 ++ .../core/common/AwsJsonCborController.java | 10 +- .../floci/core/common/AwsQueryController.java | 4 +- .../metrics/CloudWatchMetricsJsonHandler.java | 53 ++++++- .../CloudWatchMetricsQueryHandler.java | 53 ++++++- .../metrics/CloudWatchMetricsService.java | 31 ++++ .../cloudwatch/metrics/model/MetricAlarm.java | 6 + .../metrics/CloudWatchMetricsTagsTest.java | 136 ++++++++++++++++++ 10 files changed, 319 insertions(+), 8 deletions(-) create mode 100644 src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsTagsTest.java diff --git a/compatibility-tests/compat-terraform/main.tf b/compatibility-tests/compat-terraform/main.tf index 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.tf index 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.endpoint secretsmanager = var.endpoint cognitoidp = var.endpoint + cloudwatch = var.endpoint } } diff --git a/compatibility-tests/compat-terraform/test/terraform.bats b/compatibility-tests/compat-terraform/test/terraform.bats index 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_success assert_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.java index 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.java index 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 CLOUDWATCH_ACTIONS = Set.of( - "PutMetricData", "ListMetrics", "GetMetricStatistics", "GetMetricData" + "PutMetricData", "ListMetrics", "GetMetricStatistics", "GetMetricData", + "PutMetricAlarm", "DescribeAlarms", "DeleteAlarms", "SetAlarmState", + "ListTagsForResource", "TagResource", "UntagResource" ); private static final Set 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.java index 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 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 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 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 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 parseMetricDataJson(JsonNode node) { List 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.java index 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; @ApplicationScoped public class CloudWatchMetricsQueryHandler { @@ -30,8 +32,8 @@ public class CloudWatchMetricsQueryHandler { } public Response handle(String action, MultivaluedMap 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 params, String region) { + String arn = params.getFirst("ResourceARN"); + Map 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 params, String region) { + String arn = params.getFirst("ResourceARN"); + Map 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 params, String region) { + String arn = params.getFirst("ResourceARN"); + List 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 parseMetricData(MultivaluedMap params) { @@ -284,6 +322,15 @@ public class CloudWatchMetricsQueryHandler { a.getInsufficientDataActions().add(act); } + // Tags + Map 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.java index 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 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 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 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 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.java index 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 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 getTags() { return tags; } + public void setTags(Map 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.java new file mode 100644 index 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 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 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 tags = service.listTagsForResource(alarm.getAlarmArn(), REGION); + assertEquals(1, tags.size()); + assertEquals("prod", tags.get("env")); + assertNull(tags.get("team")); + } + + @Test + void tagsViaPutMetricAlarmQuery() { + MultivaluedMap 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 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 params = new MultivaluedHashMap<>(); + params.add("ResourceARN", alarm.getAlarmArn()); + + Response response = queryHandler.handle("ListTagsForResource", params, REGION); + String xml = (String) response.getEntity(); + + assertTrue(xml.contains("")); + assertTrue(xml.contains("")); + assertTrue(xml.contains("env")); + assertTrue(xml.contains("prod")); + } + + @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()); + } +}