mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(cloudwatch): implement the dashboard operations on both protocols (#2888)
* feat(cloudwatch): implement the dashboard operations on both protocols
CloudWatch served no dashboard operations at all, so terraform-aws-monitoring's
cloudwatch-dashboard example failed on apply with "api error UnsupportedOperation:
Operation PutDashboard is not supported by CloudWatch Query" - the Query
handler's default branch, reached because PutDashboard had no case.
Adds PutDashboard, GetDashboard, ListDashboards and DeleteDashboards, backed by
a new CloudWatchDashboardsService. Dashboards are pure metadata: the
DashboardBody is stored opaquely and returned verbatim, matching AWS. Put
overwrites an existing name, Get on a missing name is ResourceNotFound,
ListDashboards honours DashboardNamePrefix, DeleteDashboards checks every name
before deleting any so it is all-or-nothing, and responses carry DashboardArn.
Both CloudWatch protocols are wired, since which one a caller uses depends on
its SDK: the Terraform provider sends the Query protocol (form-encoded Action,
routed by credential scope through AwsQueryController), while the AWS CLI and
SDK v3 send JSON 1.0 with X-Amz-Target: GraniteServiceVersion20100801.*, routed
by AwsJsonController. The monitoring service descriptor already declared both,
so no new dispatch was needed - only the four cases in each handler, plus the
new action names in AwsQueryController's CLOUDWATCH_ACTIONS so the no-auth
action-inference path resolves them to CloudWatch too.
* fix(cloudwatch): reject a dashboard body that is not a JSON object
PutDashboard checked only that a body was present, so a malformed document was
stored and answered with success. AWS parses the body and returns
InvalidParameterInput, and the difference matters: a client that sends broken
JSON otherwise learns nothing until the dashboard renders as nothing.
The body is still stored and returned verbatim; this validates that it parses
and is an object, and does not inspect what is inside it.
* fix(cloudwatch): reject a dashboard body with trailing content
readTree stops at the end of the first value, so a body of "{} and then some"
validated as the leading object and the rest was dropped, storing a document AWS
rejects. FAIL_ON_TRAILING_TOKENS makes the reader require exactly one document.
* fix(cloudwatch): make DeleteDashboards best effort, as AWS documents it
The all-or-nothing behaviour was backwards. AWS says the opposite, verbatim: "If
there is an error during this call, the operation attempts to delete as many
dashboards as possible." Deleting ["a", "missing"] where a exists removes a and
errors on missing; this removed neither, so a caller retrying with the same
batch made no progress.
Every name is now attempted, including ones after the first miss, and the first
missing name is reported afterwards. Whether a missing name errors at all is the
part that stays uncertain: DeleteDashboards' own Errors list does not name
ResourceNotFound the way GetDashboard's does, which hints at a silent skip
without establishing one, so the error is kept as the conservative reading.
* feat(cloudwatch): support PutDashboard's Tags, and tag ops on a dashboard ARN
Tags were accepted and dropped, which is the failure mode this emulator is meant
not to have. They are now stored on the dashboard, and CloudWatch's own tag
operations reach it: ListTagsForResource, TagResource and UntagResource take one
ARN for every taggable resource CloudWatch owns, so both protocol handlers route
a dashboard ARN to the dashboards service instead of the alarm store that
answered before.
Tags apply on create only, as AWS documents. A Put that replaces an existing
dashboard keeps the tags that dashboard already had, so an update cannot retag a
resource sideways through an operation that is not a tag operation. More than 50
tags is refused.
This commit is contained in:
1 parent
3a212d8360
commit
e8eb4f2ff0
10 files changed
+842
-13
No files matched your search
@@ -498,7 +498,8 @@ public class AwsQueryController {
|
||||
private static final Set<String> CLOUDWATCH_ACTIONS = Set.of(
|
||||
"PutMetricData", "ListMetrics", "GetMetricStatistics", "GetMetricData",
|
||||
"PutMetricAlarm", "DescribeAlarms", "DeleteAlarms", "SetAlarmState",
|
||||
"ListTagsForResource", "TagResource", "UntagResource"
|
||||
"ListTagsForResource", "TagResource", "UntagResource",
|
||||
"PutDashboard", "GetDashboard", "ListDashboards", "DeleteDashboards"
|
||||
);
|
||||
|
||||
private static final Set<String> ELASTIC_BEANSTALK_ACTIONS = Set.of(
|
||||
|
||||
+213
@@ -0,0 +1,213 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.dashboards;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.ObjectReader;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.dashboards.model.Dashboard;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* CloudWatch dashboards. Dashboards are pure metadata: the DashboardBody is an opaque JSON
|
||||
* document that AWS stores and hands back verbatim, so there is no backing behaviour here.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class CloudWatchDashboardsService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CloudWatchDashboardsService.class);
|
||||
|
||||
// FAIL_ON_TRAILING_TOKENS matters here: without it a body of "{} garbage" parses as the
|
||||
// leading object and the rest is silently dropped, so a document AWS rejects would be stored.
|
||||
/** AWS's documented ceiling for PutDashboard's Tags. */
|
||||
private static final int MAX_TAGS = 50;
|
||||
|
||||
private static final ObjectReader JSON = new ObjectMapper()
|
||||
.enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
|
||||
.readerFor(JsonNode.class);
|
||||
|
||||
private final StorageBackend<String, Dashboard> dashboardStore;
|
||||
private final RegionResolver regionResolver;
|
||||
|
||||
@Inject
|
||||
public CloudWatchDashboardsService(StorageFactory storageFactory, RegionResolver regionResolver) {
|
||||
this.dashboardStore = storageFactory.create("cloudwatchmetrics", "cwdashboards.json",
|
||||
new TypeReference<Map<String, Dashboard>>() {});
|
||||
this.regionResolver = regionResolver;
|
||||
}
|
||||
|
||||
// Public rather than package-private so handler tests in the metrics package can build
|
||||
// the service over an InMemoryStorage without standing up Quarkus.
|
||||
public CloudWatchDashboardsService(StorageBackend<String, Dashboard> dashboardStore,
|
||||
RegionResolver regionResolver) {
|
||||
this.dashboardStore = dashboardStore;
|
||||
this.regionResolver = regionResolver;
|
||||
}
|
||||
|
||||
/** Creates the dashboard, or replaces it wholesale when the name is already taken. */
|
||||
public Dashboard putDashboard(String dashboardName, String dashboardBody, String region) {
|
||||
return putDashboard(dashboardName, dashboardBody, Map.of(), region);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the dashboard, or replaces it wholesale when the name is already taken.
|
||||
*
|
||||
* <p>Tags apply on create only, as AWS documents: a Put that replaces an existing dashboard
|
||||
* keeps the tags that dashboard already had rather than taking the ones on this request, so
|
||||
* an update cannot quietly retag a resource through an operation that is not a tag operation.
|
||||
*/
|
||||
public Dashboard putDashboard(String dashboardName, String dashboardBody,
|
||||
Map<String, String> tags, String region) {
|
||||
if (dashboardName == null || dashboardName.isBlank()) {
|
||||
throw new AwsException("InvalidParameterValue", "DashboardName is required.", 400);
|
||||
}
|
||||
if (dashboardBody == null) {
|
||||
throw new AwsException("InvalidParameterValue", "DashboardBody is required.", 400);
|
||||
}
|
||||
validateDashboardBody(dashboardBody);
|
||||
|
||||
Dashboard existing = dashboardStore.get(key(region, dashboardName)).orElse(null);
|
||||
Dashboard dashboard = new Dashboard(dashboardName,
|
||||
regionResolver.buildArn("cloudwatch", region, "dashboard/" + dashboardName),
|
||||
dashboardBody);
|
||||
dashboard.setLastModified(Instant.now().getEpochSecond());
|
||||
if (existing != null) {
|
||||
dashboard.setTags(new LinkedHashMap<>(existing.getTags()));
|
||||
} else if (tags != null && !tags.isEmpty()) {
|
||||
if (tags.size() > MAX_TAGS) {
|
||||
throw new AwsException("InvalidParameterInput",
|
||||
"A dashboard can have at most " + MAX_TAGS + " tags.", 400);
|
||||
}
|
||||
dashboard.setTags(new LinkedHashMap<>(tags));
|
||||
}
|
||||
|
||||
// put() overwrites, which is exactly PutDashboard's semantics: an existing name is
|
||||
// replaced in full rather than merged.
|
||||
dashboardStore.put(key(region, dashboardName), dashboard);
|
||||
LOG.debugv("PutDashboard: {0} in {1}", dashboardName, region);
|
||||
return dashboard;
|
||||
}
|
||||
|
||||
/**
|
||||
* The body is stored opaquely, but it is not accepted blindly: AWS parses it and answers
|
||||
* InvalidParameterInput when it is not a JSON object, so a client that sends a malformed
|
||||
* document gets an error rather than a success and a dashboard that renders as nothing.
|
||||
*/
|
||||
private static void validateDashboardBody(String dashboardBody) {
|
||||
JsonNode parsed;
|
||||
try {
|
||||
parsed = JSON.readValue(dashboardBody);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new AwsException("InvalidParameterInput",
|
||||
"The dashboard body is invalid: " + e.getOriginalMessage(), 400);
|
||||
}
|
||||
if (parsed == null || !parsed.isObject()) {
|
||||
throw new AwsException("InvalidParameterInput",
|
||||
"The dashboard body is invalid: it must be a JSON object.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
public Dashboard getDashboard(String dashboardName, String region) {
|
||||
return dashboardStore.get(key(region, dashboardName))
|
||||
.orElseThrow(() -> notFound(dashboardName));
|
||||
}
|
||||
|
||||
public List<Dashboard> listDashboards(String dashboardNamePrefix, String region) {
|
||||
String keyPrefix = region + "::";
|
||||
List<Dashboard> all = dashboardStore.scan(k -> k.startsWith(keyPrefix));
|
||||
if (dashboardNamePrefix != null && !dashboardNamePrefix.isBlank()) {
|
||||
all = new ArrayList<>(all.stream()
|
||||
.filter(d -> d.getDashboardName().startsWith(dashboardNamePrefix))
|
||||
.toList());
|
||||
}
|
||||
all.sort(Comparator.comparing(Dashboard::getDashboardName));
|
||||
return all;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes as many of the named dashboards as it can, then reports the first name that was not
|
||||
* there. AWS documents this as best effort, verbatim: "If there is an error during this call,
|
||||
* the operation attempts to delete as many dashboards as possible." So a batch naming one
|
||||
* missing dashboard still deletes the others, rather than leaving every one of them in place.
|
||||
*
|
||||
* <p>Whether a missing name errors at all is the part that is not settled: DeleteDashboards'
|
||||
* own Errors list does not name ResourceNotFound the way GetDashboard's does, which hints at a
|
||||
* silent skip but does not establish one. Reporting it is the conservative reading, since a
|
||||
* caller that names a dashboard which is not there has a problem worth hearing about, and it
|
||||
* is the smaller departure from what this already did.
|
||||
*/
|
||||
public void deleteDashboards(List<String> dashboardNames, String region) {
|
||||
if (dashboardNames == null || dashboardNames.isEmpty()) {
|
||||
throw new AwsException("InvalidParameterValue", "DashboardNames is required.", 400);
|
||||
}
|
||||
String firstMissing = null;
|
||||
for (String name : dashboardNames) {
|
||||
if (dashboardStore.get(key(region, name)).isEmpty()) {
|
||||
if (firstMissing == null) {
|
||||
firstMissing = name;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
dashboardStore.delete(key(region, name));
|
||||
}
|
||||
LOG.debugv("DeleteDashboards: {0} in {1}", dashboardNames, region);
|
||||
if (firstMissing != null) {
|
||||
throw notFound(firstMissing);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an ARN names a dashboard. CloudWatch's tag operations take one ARN for every
|
||||
* taggable resource it owns, so the handler needs to know which service should answer.
|
||||
*/
|
||||
public static boolean isDashboardArn(String resourceArn) {
|
||||
return resourceArn != null && resourceArn.contains(":dashboard/");
|
||||
}
|
||||
|
||||
public Map<String, String> listTagsForResource(String resourceArn, String region) {
|
||||
return findByArn(resourceArn, region).map(Dashboard::getTags).orElse(Map.of());
|
||||
}
|
||||
|
||||
public void tagResource(String resourceArn, Map<String, String> tags, String region) {
|
||||
findByArn(resourceArn, region).ifPresent(dashboard -> {
|
||||
dashboard.getTags().putAll(tags);
|
||||
dashboardStore.put(key(region, dashboard.getDashboardName()), dashboard);
|
||||
});
|
||||
}
|
||||
|
||||
public void untagResource(String resourceArn, List<String> tagKeys, String region) {
|
||||
findByArn(resourceArn, region).ifPresent(dashboard -> {
|
||||
tagKeys.forEach(dashboard.getTags()::remove);
|
||||
dashboardStore.put(key(region, dashboard.getDashboardName()), dashboard);
|
||||
});
|
||||
}
|
||||
|
||||
private java.util.Optional<Dashboard> findByArn(String resourceArn, String region) {
|
||||
return dashboardStore.scan(k -> k.startsWith(region + "::")).stream()
|
||||
.filter(d -> d.getDashboardArn() != null && d.getDashboardArn().equals(resourceArn))
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
private static String key(String region, String dashboardName) {
|
||||
return region + "::" + dashboardName;
|
||||
}
|
||||
|
||||
private static AwsException notFound(String dashboardName) {
|
||||
return new AwsException("ResourceNotFound",
|
||||
"Dashboard does not exist: " + dashboardName, 404);
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.dashboards.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* A CloudWatch dashboard. AWS stores the body as an opaque JSON document and returns it
|
||||
* verbatim, so nothing here interprets the widget structure.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class Dashboard {
|
||||
|
||||
private String dashboardName;
|
||||
private String dashboardArn;
|
||||
private String dashboardBody;
|
||||
private long lastModified;
|
||||
private Map<String, String> tags = new LinkedHashMap<>();
|
||||
|
||||
public Dashboard() {
|
||||
this.lastModified = Instant.now().getEpochSecond();
|
||||
}
|
||||
|
||||
public Dashboard(String dashboardName, String dashboardArn, String dashboardBody) {
|
||||
this();
|
||||
this.dashboardName = dashboardName;
|
||||
this.dashboardArn = dashboardArn;
|
||||
this.dashboardBody = dashboardBody;
|
||||
}
|
||||
|
||||
public String getDashboardName() { return dashboardName; }
|
||||
public void setDashboardName(String dashboardName) { this.dashboardName = dashboardName; }
|
||||
|
||||
public String getDashboardArn() { return dashboardArn; }
|
||||
public void setDashboardArn(String dashboardArn) { this.dashboardArn = dashboardArn; }
|
||||
|
||||
public String getDashboardBody() { return dashboardBody; }
|
||||
public void setDashboardBody(String dashboardBody) { this.dashboardBody = dashboardBody; }
|
||||
|
||||
public Map<String, String> getTags() { return tags; }
|
||||
public void setTags(Map<String, String> tags) { this.tags = tags != null ? tags : new LinkedHashMap<>(); }
|
||||
|
||||
public long getLastModified() { return lastModified; }
|
||||
public void setLastModified(long lastModified) { this.lastModified = lastModified; }
|
||||
|
||||
/** Byte length of the body, which is what ListDashboards reports as Size. */
|
||||
public long getSize() {
|
||||
return dashboardBody == null ? 0 : dashboardBody.getBytes(StandardCharsets.UTF_8).length;
|
||||
}
|
||||
}
|
||||
+83
-4
@@ -5,6 +5,8 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.dashboards.CloudWatchDashboardsService;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.dashboards.model.Dashboard;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
|
||||
@@ -27,11 +29,15 @@ public class CloudWatchMetricsJsonHandler {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CloudWatchMetricsJsonHandler.class);
|
||||
private final CloudWatchMetricsService metricsService;
|
||||
private final CloudWatchDashboardsService dashboardsService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public CloudWatchMetricsJsonHandler(CloudWatchMetricsService metricsService, ObjectMapper objectMapper) {
|
||||
public CloudWatchMetricsJsonHandler(CloudWatchMetricsService metricsService,
|
||||
CloudWatchDashboardsService dashboardsService,
|
||||
ObjectMapper objectMapper) {
|
||||
this.metricsService = metricsService;
|
||||
this.dashboardsService = dashboardsService;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@@ -49,6 +55,10 @@ public class CloudWatchMetricsJsonHandler {
|
||||
case "TagResource" -> handleTagResource(request, region);
|
||||
case "UntagResource" -> handleUntagResource(request, region);
|
||||
case "GetMetricData" -> handleGetMetricData(request, region);
|
||||
case "PutDashboard" -> handlePutDashboard(request, region);
|
||||
case "GetDashboard" -> handleGetDashboard(request, region);
|
||||
case "ListDashboards" -> handleListDashboards(request, region);
|
||||
case "DeleteDashboards" -> handleDeleteDashboards(request, region);
|
||||
default -> Response.status(400)
|
||||
.entity(new AwsErrorResponse("UnsupportedOperation", "Operation " + action + " is not supported by CloudWatch JSON."))
|
||||
.build();
|
||||
@@ -233,7 +243,9 @@ public class CloudWatchMetricsJsonHandler {
|
||||
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);
|
||||
Map<String, String> tags = CloudWatchDashboardsService.isDashboardArn(arn)
|
||||
? dashboardsService.listTagsForResource(arn, region)
|
||||
: 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();
|
||||
@@ -248,7 +260,11 @@ public class CloudWatchMetricsJsonHandler {
|
||||
if (tagsNode.isArray()) {
|
||||
tagsNode.forEach(t -> tags.put(t.path("Key").asText(), t.path("Value").asText()));
|
||||
}
|
||||
metricsService.tagResource(arn, tags, region);
|
||||
if (CloudWatchDashboardsService.isDashboardArn(arn)) {
|
||||
dashboardsService.tagResource(arn, tags, region);
|
||||
} else {
|
||||
metricsService.tagResource(arn, tags, region);
|
||||
}
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
@@ -261,7 +277,11 @@ public class CloudWatchMetricsJsonHandler {
|
||||
if (keysNode.isArray()) {
|
||||
keysNode.forEach(k -> keys.add(k.asText()));
|
||||
}
|
||||
metricsService.untagResource(arn, keys, region);
|
||||
if (CloudWatchDashboardsService.isDashboardArn(arn)) {
|
||||
dashboardsService.untagResource(arn, keys, region);
|
||||
} else {
|
||||
metricsService.untagResource(arn, keys, region);
|
||||
}
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
@@ -322,6 +342,65 @@ public class CloudWatchMetricsJsonHandler {
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
// ──────────────────────────── Dashboards ────────────────────────────
|
||||
|
||||
private Response handlePutDashboard(JsonNode request, String region) {
|
||||
Map<String, String> tags = new LinkedHashMap<>();
|
||||
JsonNode tagsNode = request.path("Tags");
|
||||
if (tagsNode.isArray()) {
|
||||
tagsNode.forEach(t -> tags.put(t.path("Key").asText(), t.path("Value").asText()));
|
||||
}
|
||||
dashboardsService.putDashboard(
|
||||
request.path("DashboardName").asText(null),
|
||||
request.path("DashboardBody").asText(null),
|
||||
tags,
|
||||
region);
|
||||
// DashboardValidationMessages is optional on the response shape, but AWS always
|
||||
// sends the list. It stays empty here: the body is stored opaquely, so nothing
|
||||
// inspects it and no validation warning can be produced.
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.putArray("DashboardValidationMessages");
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleGetDashboard(JsonNode request, String region) {
|
||||
Dashboard dashboard = dashboardsService.getDashboard(
|
||||
request.path("DashboardName").asText(null), region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("DashboardArn", dashboard.getDashboardArn());
|
||||
response.put("DashboardName", dashboard.getDashboardName());
|
||||
response.put("DashboardBody", dashboard.getDashboardBody());
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleListDashboards(JsonNode request, String region) {
|
||||
String prefix = request.has("DashboardNamePrefix")
|
||||
? request.path("DashboardNamePrefix").asText() : null;
|
||||
List<Dashboard> dashboards = dashboardsService.listDashboards(prefix, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode entries = response.putArray("DashboardEntries");
|
||||
for (Dashboard d : dashboards) {
|
||||
ObjectNode node = entries.addObject();
|
||||
node.put("DashboardName", d.getDashboardName());
|
||||
node.put("DashboardArn", d.getDashboardArn());
|
||||
node.put("LastModified", d.getLastModified());
|
||||
node.put("Size", d.getSize());
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteDashboards(JsonNode request, String region) {
|
||||
List<String> names = new ArrayList<>();
|
||||
JsonNode namesNode = request.path("DashboardNames");
|
||||
if (namesNode.isArray()) {
|
||||
namesNode.forEach(n -> names.add(n.asText()));
|
||||
}
|
||||
dashboardsService.deleteDashboards(names, region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private List<MetricDatum> parseMetricDataJson(JsonNode node) {
|
||||
List<MetricDatum> datums = new ArrayList<>();
|
||||
if (!node.isArray()) return datums;
|
||||
|
||||
+84
-4
@@ -3,6 +3,8 @@ package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
import io.github.hectorvent.floci.core.common.AwsNamespaces;
|
||||
import io.github.hectorvent.floci.core.common.AwsQueryResponse;
|
||||
import io.github.hectorvent.floci.core.common.XmlBuilder;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.dashboards.CloudWatchDashboardsService;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.dashboards.model.Dashboard;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
|
||||
@@ -24,10 +26,13 @@ public class CloudWatchMetricsQueryHandler {
|
||||
private static final Logger LOG = Logger.getLogger(CloudWatchMetricsQueryHandler.class);
|
||||
|
||||
private CloudWatchMetricsService metricsService;
|
||||
private final CloudWatchDashboardsService dashboardsService;
|
||||
|
||||
@Inject
|
||||
public CloudWatchMetricsQueryHandler(CloudWatchMetricsService metricsService) {
|
||||
public CloudWatchMetricsQueryHandler(CloudWatchMetricsService metricsService,
|
||||
CloudWatchDashboardsService dashboardsService) {
|
||||
this.metricsService = metricsService;
|
||||
this.dashboardsService = dashboardsService;
|
||||
}
|
||||
|
||||
public Response handle(String action, MultivaluedMap<String, String> params, String region) {
|
||||
@@ -44,6 +49,10 @@ public class CloudWatchMetricsQueryHandler {
|
||||
case "ListTagsForResource" -> handleListTagsForResource(params, region);
|
||||
case "TagResource" -> handleTagResource(params, region);
|
||||
case "UntagResource" -> handleUntagResource(params, region);
|
||||
case "PutDashboard" -> handlePutDashboard(params, region);
|
||||
case "GetDashboard" -> handleGetDashboard(params, region);
|
||||
case "ListDashboards" -> handleListDashboards(params, region);
|
||||
case "DeleteDashboards" -> handleDeleteDashboards(params, region);
|
||||
default -> AwsQueryResponse.error("UnsupportedOperation",
|
||||
"Operation " + action + " is not supported by CloudWatch Query.", AwsNamespaces.CW, 400);
|
||||
};
|
||||
@@ -254,7 +263,9 @@ public class CloudWatchMetricsQueryHandler {
|
||||
|
||||
private Response handleListTagsForResource(MultivaluedMap<String, String> params, String region) {
|
||||
String arn = params.getFirst("ResourceARN");
|
||||
Map<String, String> tags = metricsService.listTagsForResource(arn, region);
|
||||
Map<String, String> tags = CloudWatchDashboardsService.isDashboardArn(arn)
|
||||
? dashboardsService.listTagsForResource(arn, region)
|
||||
: 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");
|
||||
@@ -269,7 +280,11 @@ public class CloudWatchMetricsQueryHandler {
|
||||
if (key == null) break;
|
||||
tags.put(key, params.getFirst("Tags.member." + i + ".Value"));
|
||||
}
|
||||
metricsService.tagResource(arn, tags, region);
|
||||
if (CloudWatchDashboardsService.isDashboardArn(arn)) {
|
||||
dashboardsService.tagResource(arn, tags, region);
|
||||
} else {
|
||||
metricsService.tagResource(arn, tags, region);
|
||||
}
|
||||
return Response.ok(AwsQueryResponse.envelopeNoResult("TagResource", null)).build();
|
||||
}
|
||||
|
||||
@@ -281,10 +296,75 @@ public class CloudWatchMetricsQueryHandler {
|
||||
if (key == null) break;
|
||||
keys.add(key);
|
||||
}
|
||||
metricsService.untagResource(arn, keys, region);
|
||||
if (CloudWatchDashboardsService.isDashboardArn(arn)) {
|
||||
dashboardsService.untagResource(arn, keys, region);
|
||||
} else {
|
||||
metricsService.untagResource(arn, keys, region);
|
||||
}
|
||||
return Response.ok(AwsQueryResponse.envelopeNoResult("UntagResource", null)).build();
|
||||
}
|
||||
|
||||
// ──────────────────────────── Dashboards ────────────────────────────
|
||||
|
||||
private Response handlePutDashboard(MultivaluedMap<String, String> params, String region) {
|
||||
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"));
|
||||
}
|
||||
dashboardsService.putDashboard(params.getFirst("DashboardName"),
|
||||
params.getFirst("DashboardBody"), tags, region);
|
||||
// DashboardValidationMessages is optional on the response shape, but AWS always
|
||||
// sends the list. It stays empty: the body is stored opaquely, so nothing here
|
||||
// inspects it and no validation warning can be produced.
|
||||
String xml = new XmlBuilder()
|
||||
.start("DashboardValidationMessages").end("DashboardValidationMessages")
|
||||
.build();
|
||||
return Response.ok(AwsQueryResponse.envelope("PutDashboard", null, xml)).build();
|
||||
}
|
||||
|
||||
private Response handleGetDashboard(MultivaluedMap<String, String> params, String region) {
|
||||
Dashboard dashboard = dashboardsService.getDashboard(params.getFirst("DashboardName"), region);
|
||||
String xml = new XmlBuilder()
|
||||
.elem("DashboardArn", dashboard.getDashboardArn())
|
||||
.elem("DashboardName", dashboard.getDashboardName())
|
||||
.elem("DashboardBody", dashboard.getDashboardBody())
|
||||
.build();
|
||||
return Response.ok(AwsQueryResponse.envelope("GetDashboard", null, xml)).build();
|
||||
}
|
||||
|
||||
private Response handleListDashboards(MultivaluedMap<String, String> params, String region) {
|
||||
List<Dashboard> dashboards =
|
||||
dashboardsService.listDashboards(params.getFirst("DashboardNamePrefix"), region);
|
||||
|
||||
DateTimeFormatter fmt = DateTimeFormatter.ISO_INSTANT;
|
||||
var xml = new XmlBuilder().start("DashboardEntries");
|
||||
for (Dashboard d : dashboards) {
|
||||
xml.start("member")
|
||||
.elem("DashboardName", d.getDashboardName())
|
||||
.elem("DashboardArn", d.getDashboardArn())
|
||||
.elem("LastModified", fmt.format(Instant.ofEpochSecond(d.getLastModified())))
|
||||
.elem("Size", d.getSize())
|
||||
.end("member");
|
||||
}
|
||||
xml.end("DashboardEntries");
|
||||
return Response.ok(AwsQueryResponse.envelope("ListDashboards", null, xml.build())).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteDashboards(MultivaluedMap<String, String> params, String region) {
|
||||
List<String> names = new ArrayList<>();
|
||||
for (int i = 1; ; i++) {
|
||||
String name = params.getFirst("DashboardNames.member." + i);
|
||||
if (name == null) break;
|
||||
names.add(name);
|
||||
}
|
||||
dashboardsService.deleteDashboards(names, region);
|
||||
return Response.ok(AwsQueryResponse.envelopeEmptyResult("DeleteDashboards", null)).build();
|
||||
}
|
||||
|
||||
// ──────────────────────────── Parsing Helpers ────────────────────────────
|
||||
|
||||
private List<MetricDatum> parseMetricData(MultivaluedMap<String, String> params) {
|
||||
|
||||
+226
@@ -0,0 +1,226 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.dashboards;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.RestAssured;
|
||||
import io.restassured.config.EncoderConfig;
|
||||
import io.restassured.http.ContentType;
|
||||
import io.restassured.parsing.Parser;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
|
||||
/**
|
||||
* The dashboard operations reach the emulator over the Query protocol - that is what the
|
||||
* Terraform AWS provider speaks to CloudWatch, and the route that used to answer
|
||||
* "Operation PutDashboard is not supported by CloudWatch Query".
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CloudWatchDashboardsIntegrationTest {
|
||||
|
||||
private static final String CW_SCOPE =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/monitoring/aws4_request";
|
||||
|
||||
private static final String JSON_1_0 = "application/x-amz-json-1.0";
|
||||
|
||||
@BeforeAll
|
||||
static void registerJsonParser() {
|
||||
RestAssured.registerParser(JSON_1_0, Parser.JSON);
|
||||
}
|
||||
|
||||
// RestAssured has no built-in serializer for the x-amz-json content types; send raw text.
|
||||
private static RequestSpecification json(String target, String body) {
|
||||
return given()
|
||||
.config(RestAssured.config().encoderConfig(EncoderConfig.encoderConfig()
|
||||
.encodeContentTypeAs(JSON_1_0, ContentType.TEXT)))
|
||||
.contentType(JSON_1_0)
|
||||
.header("X-Amz-Target", "GraniteServiceVersion20100801." + target)
|
||||
.body(body);
|
||||
}
|
||||
|
||||
private static final String BODY =
|
||||
"{\"widgets\":[{\"type\":\"metric\",\"properties\":{\"title\":\"a > b\"}}]}";
|
||||
|
||||
private void putDashboard(String name, String body) {
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CW_SCOPE)
|
||||
.formParam("Action", "PutDashboard")
|
||||
.formParam("DashboardName", name)
|
||||
.formParam("DashboardBody", body)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.contentType("application/xml");
|
||||
}
|
||||
|
||||
@Test
|
||||
void putThenGetReturnsTheBodyVerbatim() {
|
||||
putDashboard("query-round-trip", BODY);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CW_SCOPE)
|
||||
.formParam("Action", "GetDashboard")
|
||||
.formParam("DashboardName", "query-round-trip")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("GetDashboardResponse.GetDashboardResult.DashboardBody", equalTo(BODY))
|
||||
.body("GetDashboardResponse.GetDashboardResult.DashboardArn",
|
||||
containsString(":dashboard/query-round-trip"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getUnknownDashboardReturnsResourceNotFound() {
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CW_SCOPE)
|
||||
.formParam("Action", "GetDashboard")
|
||||
.formParam("DashboardName", "no-such-dashboard")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("ErrorResponse.Error.Code", equalTo("ResourceNotFound"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listDashboardsHonoursTheNamePrefix() {
|
||||
putDashboard("prefixed-one", BODY);
|
||||
putDashboard("prefixed-two", BODY);
|
||||
putDashboard("unprefixed", BODY);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CW_SCOPE)
|
||||
.formParam("Action", "ListDashboards")
|
||||
.formParam("DashboardNamePrefix", "prefixed-")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("ListDashboardsResponse.ListDashboardsResult.DashboardEntries.member.DashboardName",
|
||||
hasItem("prefixed-one"))
|
||||
.body("ListDashboardsResponse.ListDashboardsResult.DashboardEntries.member.DashboardName",
|
||||
not(hasItem("unprefixed")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteDashboardsRemovesEveryNamedDashboard() {
|
||||
putDashboard("delete-a", BODY);
|
||||
putDashboard("delete-b", BODY);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CW_SCOPE)
|
||||
.formParam("Action", "DeleteDashboards")
|
||||
.formParam("DashboardNames.member.1", "delete-a")
|
||||
.formParam("DashboardNames.member.2", "delete-b")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CW_SCOPE)
|
||||
.formParam("Action", "GetDashboard")
|
||||
.formParam("DashboardName", "delete-a")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(404);
|
||||
}
|
||||
|
||||
// The AWS CLI and SDK v3 send the same operations as JSON with an X-Amz-Target header,
|
||||
// which the emulator dispatches to CloudWatchMetricsJsonHandler instead.
|
||||
@Test
|
||||
void theSameOperationsAreServedOverTheJsonProtocol() {
|
||||
json("PutDashboard", "{\"DashboardName\": \"json-round-trip\", \"DashboardBody\": \"{}\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
json("GetDashboard", "{\"DashboardName\": \"json-round-trip\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("DashboardBody", equalTo("{}"));
|
||||
}
|
||||
/**
|
||||
* Tags supplied on PutDashboard have to be readable afterwards, and CloudWatch's tag
|
||||
* operations take one ARN for every resource it owns, so the handler has to route a dashboard
|
||||
* ARN to the dashboards service rather than the alarm store that answered before.
|
||||
*/
|
||||
@Test
|
||||
void tagsSuppliedOnPutAreReadableThroughListTagsForResource() {
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CW_SCOPE)
|
||||
.formParam("Action", "PutDashboard")
|
||||
.formParam("DashboardName", "tagged")
|
||||
.formParam("DashboardBody", BODY)
|
||||
.formParam("Tags.member.1.Key", "team")
|
||||
.formParam("Tags.member.1.Value", "platform")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
String arn = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CW_SCOPE)
|
||||
.formParam("Action", "GetDashboard")
|
||||
.formParam("DashboardName", "tagged")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().path("GetDashboardResponse.GetDashboardResult.DashboardArn");
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CW_SCOPE)
|
||||
.formParam("Action", "ListTagsForResource")
|
||||
.formParam("ResourceARN", arn)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<Key>team</Key>"))
|
||||
.body(containsString("<Value>platform</Value>"));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CW_SCOPE)
|
||||
.formParam("Action", "UntagResource")
|
||||
.formParam("ResourceARN", arn)
|
||||
.formParam("TagKeys.member.1", "team")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CW_SCOPE)
|
||||
.formParam("Action", "ListTagsForResource")
|
||||
.formParam("ResourceARN", arn)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(not(containsString("<Key>team</Key>")));
|
||||
}
|
||||
|
||||
}
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.dashboards;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.dashboards.model.Dashboard;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class CloudWatchDashboardsServiceTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String BODY = "{\"widgets\":[{\"type\":\"metric\",\"width\":6}]}";
|
||||
|
||||
private CloudWatchDashboardsService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new CloudWatchDashboardsService(
|
||||
new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000")
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void putAndGetReturnsBodyVerbatim() {
|
||||
service.putDashboard("ops", BODY, REGION);
|
||||
|
||||
Dashboard dashboard = service.getDashboard("ops", REGION);
|
||||
assertEquals(BODY, dashboard.getDashboardBody());
|
||||
assertEquals("ops", dashboard.getDashboardName());
|
||||
assertEquals("arn:aws:cloudwatch:us-east-1:000000000000:dashboard/ops",
|
||||
dashboard.getDashboardArn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void putOnExistingNameOverwrites() {
|
||||
service.putDashboard("ops", BODY, REGION);
|
||||
service.putDashboard("ops", "{\"widgets\":[]}", REGION);
|
||||
|
||||
assertEquals("{\"widgets\":[]}", service.getDashboard("ops", REGION).getDashboardBody());
|
||||
assertEquals(1, service.listDashboards(null, REGION).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getMissingDashboardThrowsResourceNotFound() {
|
||||
AwsException e = assertThrows(AwsException.class, () -> service.getDashboard("nope", REGION));
|
||||
assertEquals("ResourceNotFound", e.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void putRejectsNullBody() {
|
||||
assertThrows(AwsException.class, () -> service.putDashboard("ops", null, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void putRejectsAMalformedBody() {
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> service.putDashboard("ops", "{\"widgets\": [", REGION));
|
||||
assertEquals("InvalidParameterInput", e.getErrorCode());
|
||||
assertEquals(400, e.getHttpStatus());
|
||||
}
|
||||
|
||||
/** A leading object followed by anything else is still a malformed document, not a dashboard. */
|
||||
@Test
|
||||
void putRejectsABodyWithTrailingContentAfterTheObject() {
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> service.putDashboard("ops", "{\"widgets\": []} and then some", REGION));
|
||||
assertEquals("InvalidParameterInput", e.getErrorCode());
|
||||
}
|
||||
|
||||
/** A body that parses but is not an object is equally unusable as a dashboard. */
|
||||
@Test
|
||||
void putRejectsABodyThatIsNotAJsonObject() {
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> service.putDashboard("ops", "[]", REGION));
|
||||
assertEquals("InvalidParameterInput", e.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listDashboardsFiltersByNamePrefix() {
|
||||
service.putDashboard("prod-api", BODY, REGION);
|
||||
service.putDashboard("prod-web", BODY, REGION);
|
||||
service.putDashboard("staging-api", BODY, REGION);
|
||||
|
||||
List<Dashboard> filtered = service.listDashboards("prod-", REGION);
|
||||
assertEquals(List.of("prod-api", "prod-web"),
|
||||
filtered.stream().map(Dashboard::getDashboardName).toList());
|
||||
assertEquals(3, service.listDashboards(null, REGION).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listDashboardsIsScopedToRegion() {
|
||||
service.putDashboard("ops", BODY, REGION);
|
||||
service.putDashboard("ops", BODY, "eu-west-1");
|
||||
|
||||
assertEquals(1, service.listDashboards(null, REGION).size());
|
||||
assertEquals(1, service.listDashboards(null, "eu-west-1").size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteDashboardsRemovesEveryNamedDashboard() {
|
||||
service.putDashboard("a", BODY, REGION);
|
||||
service.putDashboard("b", BODY, REGION);
|
||||
service.putDashboard("c", BODY, REGION);
|
||||
|
||||
service.deleteDashboards(List.of("a", "b"), REGION);
|
||||
|
||||
assertEquals(List.of("c"),
|
||||
service.listDashboards(null, REGION).stream().map(Dashboard::getDashboardName).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagsGivenOnCreateAreReadableByArn() {
|
||||
service.putDashboard("ops", BODY, java.util.Map.of("team", "platform"), REGION);
|
||||
String arn = service.getDashboard("ops", REGION).getDashboardArn();
|
||||
|
||||
assertEquals(java.util.Map.of("team", "platform"), service.listTagsForResource(arn, REGION));
|
||||
assertTrue(CloudWatchDashboardsService.isDashboardArn(arn));
|
||||
}
|
||||
|
||||
/**
|
||||
* AWS documents Tags on PutDashboard as create-only, so replacing a dashboard keeps the tags
|
||||
* it already had: an update must not be able to retag a resource sideways.
|
||||
*/
|
||||
@Test
|
||||
void tagsOnAReplacingPutDoNotOverwriteTheExistingOnes() {
|
||||
service.putDashboard("ops", BODY, java.util.Map.of("team", "platform"), REGION);
|
||||
String arn = service.getDashboard("ops", REGION).getDashboardArn();
|
||||
|
||||
service.putDashboard("ops", BODY, java.util.Map.of("team", "someone-else"), REGION);
|
||||
|
||||
assertEquals(java.util.Map.of("team", "platform"), service.listTagsForResource(arn, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagAndUntagResourceReachDashboards() {
|
||||
service.putDashboard("ops", BODY, REGION);
|
||||
String arn = service.getDashboard("ops", REGION).getDashboardArn();
|
||||
|
||||
service.tagResource(arn, java.util.Map.of("env", "dev"), REGION);
|
||||
assertEquals(java.util.Map.of("env", "dev"), service.listTagsForResource(arn, REGION));
|
||||
|
||||
service.untagResource(arn, List.of("env"), REGION);
|
||||
assertEquals(java.util.Map.of(), service.listTagsForResource(arn, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteDashboardsIsBestEffortWhenOneNameIsMissing() {
|
||||
service.putDashboard("a", BODY, REGION);
|
||||
service.putDashboard("b", BODY, REGION);
|
||||
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> service.deleteDashboards(List.of("a", "missing", "b"), REGION));
|
||||
assertEquals("ResourceNotFound", e.getErrorCode());
|
||||
// AWS attempts to delete as many dashboards as possible, so the two that existed are
|
||||
// gone even though the batch errored, and a name after the missing one is still tried.
|
||||
assertEquals(0, service.listDashboards(null, REGION).size());
|
||||
}
|
||||
}
|
||||
+6
-1
@@ -9,6 +9,7 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
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.dashboards.CloudWatchDashboardsService;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Instant;
|
||||
@@ -41,7 +42,11 @@ class CloudWatchMetricsJsonHandlerTest {
|
||||
new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000")
|
||||
);
|
||||
handler = new CloudWatchMetricsJsonHandler(service, MAPPER);
|
||||
CloudWatchDashboardsService dashboardsService = new CloudWatchDashboardsService(
|
||||
new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000")
|
||||
);
|
||||
handler = new CloudWatchMetricsJsonHandler(service, dashboardsService, MAPPER);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+4
-1
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
|
||||
import io.github.hectorvent.floci.services.cloudwatch.dashboards.CloudWatchDashboardsService;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
@@ -24,7 +25,9 @@ class CloudWatchMetricsQueryHandlerTest {
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
private final CloudWatchMetricsService metricsService = mock(CloudWatchMetricsService.class);
|
||||
private final CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(metricsService);
|
||||
// The alarm cases below never reach a dashboard operation; the handler simply routes both.
|
||||
private final CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(
|
||||
metricsService, mock(CloudWatchDashboardsService.class));
|
||||
|
||||
@Test
|
||||
void putMetricAlarmDefaultsActionsEnabledToTrueWhenOmitted() {
|
||||
|
||||
+5
-2
@@ -4,6 +4,7 @@ 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.dashboards.CloudWatchDashboardsService;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
@@ -31,8 +32,10 @@ class CloudWatchMetricsTagsTest {
|
||||
new InMemoryStorage<>(),
|
||||
new RegionResolver("us-east-1", "000000000000")
|
||||
);
|
||||
queryHandler = new CloudWatchMetricsQueryHandler(service);
|
||||
jsonHandler = new CloudWatchMetricsJsonHandler(service, objectMapper);
|
||||
CloudWatchDashboardsService dashboardsService = new CloudWatchDashboardsService(
|
||||
new InMemoryStorage<>(), new RegionResolver("us-east-1", "000000000000"));
|
||||
queryHandler = new CloudWatchMetricsQueryHandler(service, dashboardsService);
|
||||
jsonHandler = new CloudWatchMetricsJsonHandler(service, dashboardsService, objectMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
Reference in new issue
Block a user