fix(cloudwatch): implement tagging support for metrics and alarms (#320)

This commit is contained in:
Hector Ventura authored and GitHub committed 2026-04-09 21:45:54 -05:00
1 parent 202d6eb824
commit c426e805fe
10 files changed
+319 -8

No files matched your search

@@ -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")
@@ -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(
@@ -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;
@@ -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<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;
}
@@ -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) {
@@ -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; }
}