mirror of
https://github.com/floci-io/floci.git
synced 2026-12-04 10:38:00 -05:00
feat(cloudwatch): create, read, update and delete resource metrics configurations (#10164)
Add CreateResourceMetricsConfiguration, GetResourceMetricsConfiguration,
UpdateResourceMetricsConfiguration and DeleteResourceMetricsConfiguration
over Query, JSON 1.0 and CBOR: at most one detailed monitoring
configuration per resource ARN, kept per account and Region. Floci stores
the configuration; collecting the selected metrics comes next.
The model is checked first, every violation in AWS's form, the metric
selection list quoted as AWS writes it. Then the ARN must name a resource
type ("ARN is missing resource type") and one with detailed monitoring
("Unsupported resource type"): the guides document only ElastiCache
replication groups. These refusals are ValidationError, the JSON body
naming com.amazon.coral.validate#ValidationException, as recorded from
AWS. A second create is ConflictException (409) and a missing
configuration ResourceNotFoundException (404), each with its exception's
model documentation, as AWS quotes no message. An update replaces the
selections, and one without them collects every metric.
DeleteReplicationGroup fires a ReplicationGroupDeleted event, and the
configuration of the deleted group is deleted with it, as the ElastiCache
user guide says. SmithyValidationErrors.Violations gains sizeOutOfRange, the quoted
twin of the list-size violation.
Part of #7030.
This commit is contained in:
1 parent
1f5c7abaaf
commit
bece631041
28 files changed
+1044
-33
No files matched your search
+82
@@ -0,0 +1,82 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.services.cloudwatch.CloudWatchClient;
|
||||
import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;
|
||||
import software.amazon.awssdk.services.cloudwatch.model.ConflictException;
|
||||
import software.amazon.awssdk.services.cloudwatch.model.ResourceMetricSelection;
|
||||
import software.amazon.awssdk.services.cloudwatch.model.ResourceMetricsConfiguration;
|
||||
import software.amazon.awssdk.services.cloudwatch.model.ResourceNotFoundException;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
@DisplayName("CloudWatch resource metrics configuration")
|
||||
class CloudWatchResourceMetricsConfigurationTest {
|
||||
|
||||
// An account of its own, so no other test class touches the same configurations.
|
||||
private static final String ACCOUNT_ID = "797979797979";
|
||||
private static final StaticCredentialsProvider ACCOUNT =
|
||||
StaticCredentialsProvider.create(AwsBasicCredentials.create(ACCOUNT_ID, "test"));
|
||||
|
||||
@Test
|
||||
@DisplayName("creates, reads, replaces and deletes the configuration of a replication group")
|
||||
void configurationLifecycle() {
|
||||
try (CloudWatchClient cloudWatch = client()) {
|
||||
String arn = "arn:aws:elasticache:" + TestFixtures.region() + ":" + ACCOUNT_ID
|
||||
+ ":replicationgroup:compat-lifecycle";
|
||||
ResourceMetricSelection memory = ResourceMetricSelection.builder()
|
||||
.includeMetrics("valkey.memory.used").build();
|
||||
|
||||
ResourceMetricsConfiguration created = cloudWatch.createResourceMetricsConfiguration(request -> request
|
||||
.resourceArn(arn).metricSelections(memory)).resourceMetricsConfiguration();
|
||||
try {
|
||||
assertThat(created.resourceArn()).isEqualTo(arn);
|
||||
assertThat(created.metricSelections()).singleElement()
|
||||
.satisfies(selection -> assertThat(selection.includeMetrics())
|
||||
.containsExactly("valkey.memory.used"));
|
||||
assertThat(created.createdAt()).isNotNull();
|
||||
assertThatThrownBy(() -> cloudWatch.createResourceMetricsConfiguration(request -> request
|
||||
.resourceArn(arn))).isInstanceOf(ConflictException.class);
|
||||
|
||||
ResourceMetricsConfiguration replaced = cloudWatch.updateResourceMetricsConfiguration(request ->
|
||||
request.resourceArn(arn)).resourceMetricsConfiguration();
|
||||
assertThat(replaced.hasMetricSelections()).isFalse();
|
||||
assertThat(replaced.createdAt()).isEqualTo(created.createdAt());
|
||||
assertThat(cloudWatch.getResourceMetricsConfiguration(request -> request.resourceArn(arn))
|
||||
.resourceMetricsConfiguration().hasMetricSelections()).isFalse();
|
||||
} finally {
|
||||
cloudWatch.deleteResourceMetricsConfiguration(request -> request.resourceArn(arn));
|
||||
}
|
||||
|
||||
assertThatThrownBy(() -> cloudWatch.getResourceMetricsConfiguration(request -> request.resourceArn(arn)))
|
||||
.isInstanceOf(ResourceNotFoundException.class)
|
||||
.hasMessageContaining("The named resource does not exist.");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("refuses a resource type without detailed monitoring as a ValidationError")
|
||||
void unsupportedResourceType() {
|
||||
try (CloudWatchClient cloudWatch = client()) {
|
||||
String table = "arn:aws:dynamodb:" + TestFixtures.region() + ":" + ACCOUNT_ID + ":table/compat";
|
||||
|
||||
assertThatThrownBy(() -> cloudWatch.getResourceMetricsConfiguration(request -> request.resourceArn(table)))
|
||||
.isInstanceOf(CloudWatchException.class)
|
||||
.hasMessageContaining("Unsupported resource type")
|
||||
.satisfies(e -> {
|
||||
CloudWatchException refused = (CloudWatchException) e;
|
||||
assertThat(refused.statusCode()).isEqualTo(400);
|
||||
assertThat(refused.awsErrorDetails().errorCode()).isEqualTo("ValidationError");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private static CloudWatchClient client() {
|
||||
return CloudWatchClient.builder().endpointOverride(TestFixtures.endpoint())
|
||||
.region(TestFixtures.region()).credentialsProvider(ACCOUNT).build();
|
||||
}
|
||||
}
|
||||
@@ -561,6 +561,10 @@ returns HTTP 404.
|
||||
| `GetOTelEnrichment` | Read the Region's OTel enrichment status and configuration |
|
||||
| `UpdateOTelEnrichment` | Replace the filters and tag setting of running OTel enrichment |
|
||||
| `StopOTelEnrichment` | Stop OTel enrichment in the Region |
|
||||
| `CreateResourceMetricsConfiguration` | Create the detailed monitoring configuration of a resource (see [Resource metrics configuration](#resource-metrics-configuration)) |
|
||||
| `GetResourceMetricsConfiguration` | Read a resource's detailed monitoring configuration |
|
||||
| `UpdateResourceMetricsConfiguration` | Replace the metric selections of a resource's configuration |
|
||||
| `DeleteResourceMetricsConfiguration` | Delete a resource's detailed monitoring configuration |
|
||||
| `PutDashboard` | Create a dashboard, or replace its body when the name is taken (tags apply on create only) |
|
||||
| `GetDashboard` | Read a dashboard body and ARN |
|
||||
| `ListDashboards` | List dashboards, optionally by name prefix |
|
||||
@@ -1007,6 +1011,35 @@ and the `ACUUtilization` and `CPUUtilization` a paused Aurora Serverless v2 inst
|
||||
only, and the Redshift cluster metrics by `ClusterIdentifier` and `NodeID`, while Floci publishes
|
||||
them by the cluster's identifier alone.
|
||||
|
||||
### Resource metrics configuration {#resource-metrics-configuration}
|
||||
|
||||
`CreateResourceMetricsConfiguration`, `GetResourceMetricsConfiguration`,
|
||||
`UpdateResourceMetricsConfiguration` and `DeleteResourceMetricsConfiguration` keep the detailed
|
||||
monitoring configuration of one AWS resource, which "can have at most one
|
||||
ResourceMetricsConfiguration", keyed by the resource's ARN in the account's Region, over Query, JSON and
|
||||
CBOR. Floci stores the configuration only: no detailed metrics are collected from the resource yet.
|
||||
|
||||
The one resource the guides document is an ElastiCache Valkey replication group, so an ARN of another
|
||||
type answers `ValidationError` (400) `Unsupported resource type`, and an ARN whose resource part names
|
||||
no type answers `ARN is missing resource type`, as AWS does, every operation alike. Over JSON the
|
||||
body's `__type` is `com.amazon.coral.validate#ValidationException`. The model is checked first, every
|
||||
violation listed in AWS's form: `ResourceArn` is 20 to 2048 characters matching
|
||||
`arn:[a-zA-Z0-9-]+:[a-zA-Z0-9-]+:[a-zA-Z0-9-]*:\d{12}:.+`, and `MetricSelections` holds exactly one
|
||||
selection whose `IncludeMetrics` lists 1 to 500 names of 1 to 255 characters each. So two selections
|
||||
are refused even for an ARN no configuration can take, with `1 validation error detected: Value
|
||||
'[ResourceMetricSelection(includeMetrics=[CPUUtilization]),
|
||||
ResourceMetricSelection(includeMetrics=[DiskReadOps])]' at 'metricSelections' failed to satisfy
|
||||
constraint: Member must have length less than or equal to 1`. AWS documents no refusal for an ARN
|
||||
that names no existing replication group, so Floci makes none.
|
||||
|
||||
A create for an ARN that has a configuration answers `ConflictException` (409), and the other three
|
||||
operations answer `ResourceNotFoundException` (404) for one that has none. AWS quotes no message for
|
||||
either, so each message is its exception's documentation in the model. An update replaces the
|
||||
selections, and one without `MetricSelections` removes the filter, so that every detailed metric is
|
||||
collected and the configuration answers without `MetricSelections`. "When you delete a replication
|
||||
group, its resource metrics configuration is deleted automatically", and `DeleteReplicationGroup`
|
||||
does so in Floci.
|
||||
|
||||
### Composite alarm evaluation
|
||||
|
||||
A composite alarm is evaluated when it is created, when `PutCompositeAlarm` updates it, and when
|
||||
|
||||
@@ -131,6 +131,9 @@ without authentication relays these commands to the engine as sent.
|
||||
| `DeleteSnapshot` | Delete a snapshot and its RDB archive |
|
||||
<!-- floci:actions:end -->
|
||||
|
||||
`DeleteReplicationGroup` also deletes the group's CloudWatch
|
||||
[resource metrics configuration](cloudwatch.md#resource-metrics-configuration), as AWS does.
|
||||
|
||||
### Serverless caches and user groups
|
||||
|
||||
`CreateServerlessCache`, `DescribeServerlessCaches`, `ModifyServerlessCache` and
|
||||
|
||||
@@ -64,7 +64,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
|
||||
| [CloudWatch OAM](oam.md) | REST paths such as `POST /CreateSink` and `POST /CreateLink` | REST JSON | 15 |
|
||||
| [CloudWatch Observability Admin](observabilityadmin.md) | `POST /StartTelemetryEnrichment`, `POST /StopTelemetryEnrichment`, `POST /GetTelemetryEnrichmentStatus` | REST JSON | 3 |
|
||||
| [CloudWatch Logs](cloudwatch.md) | `POST /` + `X-Amz-Target: Logs.*` | JSON 1.1 | 54 |
|
||||
| [CloudWatch Metrics](cloudwatch.md#metrics) | `POST /` with `Action=` or JSON 1.1 | Query / JSON | 30 |
|
||||
| [CloudWatch Metrics](cloudwatch.md#metrics) | `POST /` with `Action=` or JSON 1.1 | Query / JSON | 34 |
|
||||
| [CloudWatch RUM](rum.md) | `/appmonitor`, `/appmonitor/{name}`, `/appmonitors` | REST JSON | 5 |
|
||||
| [X-Ray](xray.md) | `/TraceSegments`, `/Traces`, `/TraceSummaries`, `/ServiceGraph`, `/TraceGraph`, `/GetSamplingRules`, `/CreateSamplingRule`, `/SamplingTargets`, `/TelemetryRecords`, `/TagResource`, `/UntagResource`, `/ListTagsForResource` | REST JSON | 14 |
|
||||
| [GuardDuty](guardduty.md) | `/detector`, `/detector/{detectorId}`, `/detector/{detectorId}/admin`, `/admin/*`, `/tags/*` | REST JSON | 25 |
|
||||
|
||||
@@ -255,6 +255,21 @@ public final class SmithyValidationErrors {
|
||||
: constraint(path, value, "Member must have length less than or equal to " + max);
|
||||
}
|
||||
|
||||
/**
|
||||
* The violation for a list of {@code size} members outside {@code min}..{@code max}, or null for one inside.
|
||||
* {@code value} is the list as the service writes it, which a form that quotes its values carries:
|
||||
* "Value '[a, b]' at 'names' failed to satisfy constraint: Member must have length less than or equal to 1".
|
||||
*/
|
||||
public String sizeOutOfRange(String path, String value, int size, int min, int max) {
|
||||
if (size < min) {
|
||||
return constraint(path, value, "Member must have length greater than or equal to " + min);
|
||||
}
|
||||
if (size > max) {
|
||||
return constraint(path, value, "Member must have length less than or equal to " + max);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The violation for a string under {@code min} characters, an empty one included. */
|
||||
public String lengthTooShort(String path, String value, int min) {
|
||||
return constraint(path, value, "Member must have length greater than or equal to " + min);
|
||||
|
||||
+10
@@ -31,6 +31,16 @@ class CloudWatchMetricsException extends AwsException {
|
||||
return new CloudWatchMetricsException("InvalidParameterValue", "InvalidParameterValueException", message, 400);
|
||||
}
|
||||
|
||||
/**
|
||||
* A request its operation's validation refuses, where the body names the shape in its Coral namespace,
|
||||
* {@code com.amazon.coral.validate#ValidationException}, as recorded for the resource metrics configuration
|
||||
* operations.
|
||||
*/
|
||||
static CloudWatchMetricsException validationError(String message) {
|
||||
return new CloudWatchMetricsException("ValidationError", "com.amazon.coral.validate#ValidationException",
|
||||
message, 400);
|
||||
}
|
||||
|
||||
static CloudWatchMetricsException invalidParameterCombination(String message) {
|
||||
return new CloudWatchMetricsException("InvalidParameterCombination", "InvalidParameterCombinationException",
|
||||
message, 400);
|
||||
|
||||
+60
-1
@@ -19,6 +19,8 @@ import io.floci.aws.services.cloudwatch.metrics.model.Dimension;
|
||||
import io.floci.aws.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import io.floci.aws.services.cloudwatch.metrics.model.MetricDatum;
|
||||
import io.floci.aws.services.cloudwatch.metrics.model.OTelEnrichment;
|
||||
import io.floci.aws.services.cloudwatch.metrics.model.ResourceMetricsConfiguration;
|
||||
import io.floci.aws.services.cloudwatch.metrics.model.ResourceMetricsConfiguration.ResourceMetricSelection;
|
||||
import io.floci.aws.services.cloudwatch.metricstreams.CloudWatchMetricStreamsService;
|
||||
import io.floci.aws.services.cloudwatch.metricstreams.model.MetricStream;
|
||||
import io.floci.aws.services.cloudwatch.metricstreams.model.MetricStreamFilter;
|
||||
@@ -79,18 +81,21 @@ public class CloudWatchMetricsJsonHandler {
|
||||
private final CloudWatchMetricStreamsService metricStreamsService;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final OTelEnrichmentService otelEnrichment;
|
||||
private final ResourceMetricsConfigurationService resourceMetrics;
|
||||
|
||||
@Inject
|
||||
public CloudWatchMetricsJsonHandler(CloudWatchMetricsService metricsService,
|
||||
CloudWatchDashboardsService dashboardsService,
|
||||
CloudWatchMetricStreamsService metricStreamsService,
|
||||
ObjectMapper objectMapper,
|
||||
OTelEnrichmentService otelEnrichment) {
|
||||
OTelEnrichmentService otelEnrichment,
|
||||
ResourceMetricsConfigurationService resourceMetrics) {
|
||||
this.metricsService = metricsService;
|
||||
this.dashboardsService = dashboardsService;
|
||||
this.metricStreamsService = metricStreamsService;
|
||||
this.objectMapper = objectMapper;
|
||||
this.otelEnrichment = otelEnrichment;
|
||||
this.resourceMetrics = resourceMetrics;
|
||||
}
|
||||
|
||||
public Response handle(String action, JsonNode request, String region) {
|
||||
@@ -126,6 +131,13 @@ public class CloudWatchMetricsJsonHandler {
|
||||
case "StartOTelEnrichment" -> handleStartOTelEnrichment(request, region);
|
||||
case "UpdateOTelEnrichment" -> handleUpdateOTelEnrichment(request, region);
|
||||
case "StopOTelEnrichment" -> handleStopOTelEnrichment(region);
|
||||
case "CreateResourceMetricsConfiguration" -> resourceMetricsConfigurationResponse(resourceMetrics.create(
|
||||
region, resourceArn(request), metricSelections(request.path("MetricSelections"))));
|
||||
case "GetResourceMetricsConfiguration" ->
|
||||
resourceMetricsConfigurationResponse(resourceMetrics.get(region, resourceArn(request)));
|
||||
case "UpdateResourceMetricsConfiguration" -> resourceMetricsConfigurationResponse(resourceMetrics.update(
|
||||
region, resourceArn(request), metricSelections(request.path("MetricSelections"))));
|
||||
case "DeleteResourceMetricsConfiguration" -> handleDeleteResourceMetricsConfiguration(request, region);
|
||||
default -> Response.status(400)
|
||||
.entity(new AwsErrorResponse("UnsupportedOperation", "Operation " + action + " is not supported by CloudWatch JSON."))
|
||||
.build();
|
||||
@@ -959,6 +971,53 @@ public class CloudWatchMetricsJsonHandler {
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteResourceMetricsConfiguration(JsonNode request, String region) {
|
||||
resourceMetrics.delete(region, resourceArn(request));
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private static String resourceArn(JsonNode request) {
|
||||
return JsonNodes.asText(request.path("ResourceArn"), null);
|
||||
}
|
||||
|
||||
/** The selections a request carries, null when it leaves them out: "all available detailed metrics". */
|
||||
private static List<ResourceMetricSelection> metricSelections(JsonNode node) {
|
||||
if (node.isMissingNode() || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
List<ResourceMetricSelection> selections = new ArrayList<>();
|
||||
for (JsonNode entry : listMember(node)) {
|
||||
JsonNode metrics = entry.path("IncludeMetrics");
|
||||
List<String> names = null;
|
||||
if (!metrics.isMissingNode() && !metrics.isNull()) {
|
||||
names = new ArrayList<>();
|
||||
for (JsonNode name : listMember(metrics)) {
|
||||
names.add(JsonNodes.asText(name, null));
|
||||
}
|
||||
}
|
||||
selections.add(new ResourceMetricSelection(names));
|
||||
}
|
||||
return selections;
|
||||
}
|
||||
|
||||
/** A configuration in the model's member order, its selections left out when it names none. */
|
||||
private Response resourceMetricsConfigurationResponse(ResourceMetricsConfiguration configuration) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("ResourceArn", configuration.resourceArn());
|
||||
node.put("CreatedAt", EpochSeconds.fromMillis(configuration.createdAt().toEpochMilli()));
|
||||
node.put("UpdatedAt", EpochSeconds.fromMillis(configuration.updatedAt().toEpochMilli()));
|
||||
if (configuration.metricSelections() != null) {
|
||||
ArrayNode selections = node.putArray("MetricSelections");
|
||||
for (ResourceMetricSelection selection : configuration.metricSelections()) {
|
||||
ArrayNode names = selections.addObject().putArray("IncludeMetrics");
|
||||
selection.includeMetrics().forEach(names::add);
|
||||
}
|
||||
}
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("ResourceMetricsConfiguration", node);
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
/** The members a running enrichment answers with, an empty filter list being left out as AWS omits it. */
|
||||
private ObjectNode otelEnrichmentNode(ObjectNode response, OTelEnrichment enrichment) {
|
||||
if (!enrichment.includeFilters().isEmpty()) {
|
||||
|
||||
+59
-1
@@ -20,6 +20,8 @@ import io.floci.aws.services.cloudwatch.metrics.model.Dimension;
|
||||
import io.floci.aws.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import io.floci.aws.services.cloudwatch.metrics.model.MetricDatum;
|
||||
import io.floci.aws.services.cloudwatch.metrics.model.OTelEnrichment;
|
||||
import io.floci.aws.services.cloudwatch.metrics.model.ResourceMetricsConfiguration;
|
||||
import io.floci.aws.services.cloudwatch.metrics.model.ResourceMetricsConfiguration.ResourceMetricSelection;
|
||||
import io.floci.aws.services.cloudwatch.metricstreams.CloudWatchMetricStreamsService;
|
||||
import io.floci.aws.services.cloudwatch.metricstreams.model.MetricStream;
|
||||
import io.floci.aws.services.cloudwatch.metricstreams.model.MetricStreamFilter;
|
||||
@@ -59,16 +61,19 @@ public class CloudWatchMetricsQueryHandler {
|
||||
private final CloudWatchDashboardsService dashboardsService;
|
||||
private final CloudWatchMetricStreamsService metricStreamsService;
|
||||
private final OTelEnrichmentService otelEnrichment;
|
||||
private final ResourceMetricsConfigurationService resourceMetrics;
|
||||
|
||||
@Inject
|
||||
public CloudWatchMetricsQueryHandler(CloudWatchMetricsService metricsService,
|
||||
CloudWatchDashboardsService dashboardsService,
|
||||
CloudWatchMetricStreamsService metricStreamsService,
|
||||
OTelEnrichmentService otelEnrichment) {
|
||||
OTelEnrichmentService otelEnrichment,
|
||||
ResourceMetricsConfigurationService resourceMetrics) {
|
||||
this.metricsService = metricsService;
|
||||
this.dashboardsService = dashboardsService;
|
||||
this.metricStreamsService = metricStreamsService;
|
||||
this.otelEnrichment = otelEnrichment;
|
||||
this.resourceMetrics = resourceMetrics;
|
||||
}
|
||||
|
||||
public Response handle(String action, MultivaluedMap<String, String> params, String region) {
|
||||
@@ -104,6 +109,13 @@ public class CloudWatchMetricsQueryHandler {
|
||||
case "StartOTelEnrichment" -> handleStartOTelEnrichment(params, region);
|
||||
case "UpdateOTelEnrichment" -> handleUpdateOTelEnrichment(params, region);
|
||||
case "StopOTelEnrichment" -> handleStopOTelEnrichment(region);
|
||||
case "CreateResourceMetricsConfiguration" -> resourceMetricsConfigurationResponse(action,
|
||||
resourceMetrics.create(region, params.getFirst("ResourceArn"), metricSelections(params)));
|
||||
case "GetResourceMetricsConfiguration" -> resourceMetricsConfigurationResponse(action,
|
||||
resourceMetrics.get(region, params.getFirst("ResourceArn")));
|
||||
case "UpdateResourceMetricsConfiguration" -> resourceMetricsConfigurationResponse(action,
|
||||
resourceMetrics.update(region, params.getFirst("ResourceArn"), metricSelections(params)));
|
||||
case "DeleteResourceMetricsConfiguration" -> handleDeleteResourceMetricsConfiguration(params, region);
|
||||
default -> AwsQueryResponse.error("UnsupportedOperation",
|
||||
"Operation " + action + " is not supported by CloudWatch Query.", AwsNamespaces.CW, 400);
|
||||
};
|
||||
@@ -681,6 +693,52 @@ public class CloudWatchMetricsQueryHandler {
|
||||
return Response.ok(AwsQueryResponse.envelopeEmptyResult("StopOTelEnrichment", AwsNamespaces.CW)).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteResourceMetricsConfiguration(MultivaluedMap<String, String> params, String region) {
|
||||
resourceMetrics.delete(region, params.getFirst("ResourceArn"));
|
||||
return Response.ok(AwsQueryResponse.envelopeEmptyResult("DeleteResourceMetricsConfiguration",
|
||||
AwsNamespaces.CW)).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* The selections a request carries, null when it leaves them out: "all available detailed metrics". Every index is
|
||||
* read, gaps included, as Query lists are read elsewhere. A list sent empty, {@code MetricSelections=}, is an empty
|
||||
* list, and so is a selection's {@code IncludeMetrics=}; a selection without {@code IncludeMetrics} has none.
|
||||
*/
|
||||
private static List<ResourceMetricSelection> metricSelections(MultivaluedMap<String, String> params) {
|
||||
List<AwsQueryLists.IndexedMember> members = AwsQueryLists.members(params, "MetricSelections", null);
|
||||
if (members.isEmpty() && !params.containsKey("MetricSelections")) {
|
||||
return null;
|
||||
}
|
||||
List<ResourceMetricSelection> selections = new ArrayList<>();
|
||||
for (AwsQueryLists.IndexedMember member : members) {
|
||||
String includeMetrics = member.prefix() + ".IncludeMetrics";
|
||||
List<AwsQueryLists.IndexedMember> names = AwsQueryLists.members(params, includeMetrics, null);
|
||||
selections.add(new ResourceMetricSelection(names.isEmpty() && !params.containsKey(includeMetrics) ? null
|
||||
: names.stream().map(name -> params.getFirst(name.prefix())).toList()));
|
||||
}
|
||||
return selections;
|
||||
}
|
||||
|
||||
/** A configuration in the model's member order, its selections left out when it names none. */
|
||||
private static Response resourceMetricsConfigurationResponse(String action,
|
||||
ResourceMetricsConfiguration configuration) {
|
||||
XmlBuilder xml = new XmlBuilder().start("ResourceMetricsConfiguration")
|
||||
.elem("ResourceArn", XmlBuilder.cleaned(configuration.resourceArn()))
|
||||
.elem("CreatedAt", DateTimeFormatter.ISO_INSTANT.format(configuration.createdAt()))
|
||||
.elem("UpdatedAt", DateTimeFormatter.ISO_INSTANT.format(configuration.updatedAt()));
|
||||
if (configuration.metricSelections() != null) {
|
||||
xml.start("MetricSelections");
|
||||
for (ResourceMetricSelection selection : configuration.metricSelections()) {
|
||||
xml.start("member").start("IncludeMetrics");
|
||||
selection.includeMetrics().forEach(name -> xml.elem("member", XmlBuilder.cleaned(name)));
|
||||
xml.end("IncludeMetrics").end("member");
|
||||
}
|
||||
xml.end("MetricSelections");
|
||||
}
|
||||
xml.end("ResourceMetricsConfiguration");
|
||||
return Response.ok(AwsQueryResponse.envelope(action, AwsNamespaces.CW, xml.build())).build();
|
||||
}
|
||||
|
||||
/** The members a running enrichment answers with, an empty filter list being left out as AWS omits it. */
|
||||
private XmlBuilder otelEnrichmentXml(XmlBuilder xml, OTelEnrichment enrichment) {
|
||||
appendStreamFilters(xml, "IncludeFilters", enrichment.includeFilters());
|
||||
|
||||
+217
@@ -0,0 +1,217 @@
|
||||
package io.floci.aws.services.cloudwatch.metrics;
|
||||
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.Resettable;
|
||||
import io.floci.aws.core.common.SmithyValidationErrors;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.cloudwatch.metrics.model.ResourceMetricsConfiguration;
|
||||
import io.floci.aws.services.cloudwatch.metrics.model.ResourceMetricsConfiguration.ResourceMetricSelection;
|
||||
import io.floci.aws.services.elasticache.ReplicationGroupDeleted;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.event.Observes;
|
||||
import jakarta.inject.Inject;
|
||||
import tools.jackson.core.type.TypeReference;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* CloudWatch detailed monitoring for OpenTelemetry metrics: "Each AWS resource identified by its ARN can have at most
|
||||
* one ResourceMetricsConfiguration", kept per Region of an account and keyed by the resource's ARN.
|
||||
*
|
||||
* <p>A request is checked against the model first, every violation listed in AWS's form, so a metric selection list
|
||||
* that is too long is refused even for an ARN no configuration can take. Then the ARN must name a resource type,
|
||||
* "ARN is missing resource type", and one that supports detailed monitoring, "Unsupported resource type". Each of these
|
||||
* refusals is a {@code ValidationError} whose body names {@code com.amazon.coral.validate#ValidationException}, as
|
||||
* AWS answers them. The one resource the guides document is a node-based Valkey
|
||||
* replication group of ElastiCache, "identified by its ARN", so {@code elasticache} {@code replicationgroup} is the
|
||||
* one type taken. AWS documents no refusal for an ARN naming no existing resource, so none is made.
|
||||
*
|
||||
* <p>"When you delete a replication group, its resource metrics configuration is deleted automatically."
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class ResourceMetricsConfigurationService implements Resettable {
|
||||
/**
|
||||
* The refusal of a create for an ARN that has a configuration. AWS quotes no message for it, so this one is the
|
||||
* documentation of the modeled {@code ConflictException}.
|
||||
*/
|
||||
static final String ALREADY_EXISTS = "This operation attempted to create a resource that already exists.";
|
||||
/** The refusal for an ARN without a configuration, from the modeled exception's documentation, as above. */
|
||||
static final String NOT_FOUND = "The named resource does not exist.";
|
||||
static final String MISSING_RESOURCE_TYPE = "ARN is missing resource type";
|
||||
static final String UNSUPPORTED_RESOURCE_TYPE = "Unsupported resource type";
|
||||
/** The model's pattern for {@code ResourceArn}, which AWS's message quotes as written here. */
|
||||
static final String ARN_PATTERN = "arn:[a-zA-Z0-9-]+:[a-zA-Z0-9-]+:[a-zA-Z0-9-]*:\\d{12}:.+";
|
||||
private static final Pattern ARN = Pattern.compile(ARN_PATTERN);
|
||||
/** The resource types that support detailed monitoring, as {@code <service>:<resource type>}. */
|
||||
private static final Set<String> SUPPORTED_TYPES = Set.of("elasticache:replicationgroup");
|
||||
private static final int MIN_ARN_LENGTH = 20;
|
||||
private static final int MAX_ARN_LENGTH = 2048;
|
||||
private static final int MAX_SELECTIONS = 1;
|
||||
private static final int MAX_METRICS = 500;
|
||||
private static final int MAX_METRIC_NAME_LENGTH = 255;
|
||||
|
||||
private final AccountAwareStorageBackend<ResourceMetricsConfiguration> configurations;
|
||||
private final Clock clock;
|
||||
|
||||
@Inject
|
||||
public ResourceMetricsConfigurationService(StorageFactory storageFactory) {
|
||||
this(storageFactory.create("cloudwatchmetrics", "cw-resource-metrics-configurations.json",
|
||||
new TypeReference<Map<String, ResourceMetricsConfiguration>>() {}), Clock.systemUTC());
|
||||
}
|
||||
|
||||
ResourceMetricsConfigurationService(AccountAwareStorageBackend<ResourceMetricsConfiguration> configurations,
|
||||
Clock clock) {
|
||||
this.configurations = configurations;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the configuration of {@code resourceArn} in {@code region}; {@code null} selections collect "all
|
||||
* available detailed metrics". An ARN that has one already answers {@code ConflictException} (409).
|
||||
*/
|
||||
public synchronized ResourceMetricsConfiguration create(String region, String resourceArn,
|
||||
List<ResourceMetricSelection> metricSelections) {
|
||||
validate(resourceArn, metricSelections);
|
||||
String key = key(region, resourceArn);
|
||||
if (configurations.get(key).isPresent()) {
|
||||
throw new AwsException("ConflictException", ALREADY_EXISTS, 409);
|
||||
}
|
||||
Instant now = clock.instant();
|
||||
ResourceMetricsConfiguration created = new ResourceMetricsConfiguration(resourceArn,
|
||||
copy(metricSelections), now, now);
|
||||
configurations.put(key, created);
|
||||
return created;
|
||||
}
|
||||
|
||||
/** The configuration of {@code resourceArn} in {@code region}. */
|
||||
public ResourceMetricsConfiguration get(String region, String resourceArn) {
|
||||
validate(resourceArn, null);
|
||||
return existing(key(region, resourceArn));
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the selections of {@code resourceArn}'s configuration: "The MetricSelections value that you provide
|
||||
* replaces any existing metric selections for the resource; it is not merged with them. If you omit
|
||||
* MetricSelections, Amazon CloudWatch removes any existing metric selection filter".
|
||||
*/
|
||||
public synchronized ResourceMetricsConfiguration update(String region, String resourceArn,
|
||||
List<ResourceMetricSelection> metricSelections) {
|
||||
validate(resourceArn, metricSelections);
|
||||
String key = key(region, resourceArn);
|
||||
ResourceMetricsConfiguration updated = new ResourceMetricsConfiguration(resourceArn, copy(metricSelections),
|
||||
existing(key).createdAt(), clock.instant());
|
||||
configurations.put(key, updated);
|
||||
return updated;
|
||||
}
|
||||
|
||||
/** Deletes the configuration of {@code resourceArn} in {@code region}. */
|
||||
public synchronized void delete(String region, String resourceArn) {
|
||||
validate(resourceArn, null);
|
||||
String key = key(region, resourceArn);
|
||||
existing(key);
|
||||
configurations.delete(key);
|
||||
}
|
||||
|
||||
/** Deletes the configuration of a replication group that is gone, in the Region its ARN names. */
|
||||
synchronized void onReplicationGroupDeleted(@Observes ReplicationGroupDeleted deleted) {
|
||||
configurations.delete(key(AwsArnUtils.parse(deleted.arn()).region(), deleted.arn()));
|
||||
}
|
||||
|
||||
private ResourceMetricsConfiguration existing(String key) {
|
||||
return configurations.get(key).orElseThrow(() ->
|
||||
new AwsException("ResourceNotFoundException", NOT_FOUND, 404));
|
||||
}
|
||||
|
||||
private static void validate(String resourceArn, List<ResourceMetricSelection> metricSelections) {
|
||||
List<String> violations = new ArrayList<>();
|
||||
if (resourceArn == null) {
|
||||
violations.add(SmithyValidationErrors.notNull("resourceArn"));
|
||||
} else {
|
||||
addIfPresent(violations, SmithyValidationErrors.lengthOutOfRange("resourceArn", resourceArn,
|
||||
MIN_ARN_LENGTH, MAX_ARN_LENGTH));
|
||||
if (!ARN.matcher(resourceArn).matches()) {
|
||||
violations.add(SmithyValidationErrors.pattern("resourceArn", resourceArn, ARN_PATTERN));
|
||||
}
|
||||
}
|
||||
if (metricSelections != null) {
|
||||
addIfPresent(violations, SmithyValidationErrors.Violations.QUOTED.sizeOutOfRange("metricSelections",
|
||||
render(metricSelections), metricSelections.size(), 1, MAX_SELECTIONS));
|
||||
for (int i = 0; i < metricSelections.size(); i++) {
|
||||
String path = "metricSelections." + (i + 1) + ".member.includeMetrics";
|
||||
List<String> names = metricSelections.get(i).includeMetrics();
|
||||
if (names == null) {
|
||||
violations.add(SmithyValidationErrors.notNull(path));
|
||||
continue;
|
||||
}
|
||||
addIfPresent(violations, SmithyValidationErrors.Violations.QUOTED.sizeOutOfRange(path,
|
||||
String.valueOf(names), names.size(), 1, MAX_METRICS));
|
||||
for (int j = 0; j < names.size(); j++) {
|
||||
String namePath = path + "." + (j + 1) + ".member";
|
||||
if (names.get(j) == null) {
|
||||
violations.add(SmithyValidationErrors.notNull(namePath));
|
||||
} else {
|
||||
addIfPresent(violations, SmithyValidationErrors.lengthOutOfRange(namePath, names.get(j), 1,
|
||||
MAX_METRIC_NAME_LENGTH));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!violations.isEmpty()) {
|
||||
throw CloudWatchMetricsException.validationError(SmithyValidationErrors.message(violations));
|
||||
}
|
||||
// The pattern holds, so the ARN parses, its last part being the resource.
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(resourceArn);
|
||||
String resource = arn.resource();
|
||||
int slash = resource.indexOf('/');
|
||||
int colon = resource.indexOf(':');
|
||||
int separator = slash < 0 ? colon : colon < 0 ? slash : Math.min(slash, colon);
|
||||
if (separator < 0) {
|
||||
throw CloudWatchMetricsException.validationError(MISSING_RESOURCE_TYPE);
|
||||
}
|
||||
if (!SUPPORTED_TYPES.contains(arn.service() + ":" + resource.substring(0, separator))) {
|
||||
throw CloudWatchMetricsException.validationError(UNSUPPORTED_RESOURCE_TYPE);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The selections as AWS's message writes them: "Value '[ResourceMetricSelection(includeMetrics=[CPUUtilization]),
|
||||
* ResourceMetricSelection(includeMetrics=[DiskReadOps])]' at 'metricSelections' failed to satisfy constraint:
|
||||
* Member must have length less than or equal to 1".
|
||||
*/
|
||||
private static String render(List<ResourceMetricSelection> metricSelections) {
|
||||
return metricSelections.stream()
|
||||
.map(selection -> "ResourceMetricSelection(includeMetrics=" + selection.includeMetrics() + ")")
|
||||
.collect(Collectors.joining(", ", "[", "]"));
|
||||
}
|
||||
|
||||
private static void addIfPresent(List<String> violations, String violation) {
|
||||
if (violation != null) {
|
||||
violations.add(violation);
|
||||
}
|
||||
}
|
||||
|
||||
/** The selections as stored, copies a caller's later change cannot reach. */
|
||||
private static List<ResourceMetricSelection> copy(List<ResourceMetricSelection> metricSelections) {
|
||||
return metricSelections == null ? null : metricSelections.stream()
|
||||
.map(selection -> new ResourceMetricSelection(List.copyOf(selection.includeMetrics())))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static String key(String region, String resourceArn) {
|
||||
return region + "::" + resourceArn;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
configurations.clear();
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package io.floci.aws.services.cloudwatch.metrics.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The detailed monitoring configuration of one AWS resource, identified by its ARN: "Each AWS resource identified by
|
||||
* its ARN can have at most one ResourceMetricsConfiguration. The resource ARN serves as the unique identifier for the
|
||||
* configuration."
|
||||
*
|
||||
* <p>{@code metricSelections} is null when the configuration names no metrics, in which case "CloudWatch collects all
|
||||
* available detailed metrics for the resource", and the field is left out of every answer.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public record ResourceMetricsConfiguration(String resourceArn, List<ResourceMetricSelection> metricSelections,
|
||||
Instant createdAt, Instant updatedAt) {
|
||||
|
||||
/** One selection: "Amazon CloudWatch collects only the metrics that you list here." */
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public record ResourceMetricSelection(List<String> includeMetrics) {
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,7 @@ import io.floci.aws.services.kms.model.KmsKeySpec;
|
||||
import io.floci.aws.services.kms.model.KmsKeyUsage;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.event.Event;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
import tools.jackson.core.type.TypeReference;
|
||||
@@ -166,6 +167,7 @@ public class ElastiCacheService implements ResourceProvider {
|
||||
* alone would let DeleteUserGroup remove a group that the new cache is about to use.
|
||||
*/
|
||||
private final Map<String, Integer> reservedUserGroups = new HashMap<>();
|
||||
private final Event<ReplicationGroupDeleted> groupDeleted;
|
||||
|
||||
@Inject
|
||||
public ElastiCacheService(ElastiCacheContainerManager containerManager,
|
||||
@@ -177,8 +179,10 @@ public class ElastiCacheService implements ResourceProvider {
|
||||
RegionResolver regionResolver,
|
||||
KmsService kmsService,
|
||||
CloudWatchLogsService logsService,
|
||||
ElastiCacheProvisioningIds provisioningIds) {
|
||||
ElastiCacheProvisioningIds provisioningIds,
|
||||
Event<ReplicationGroupDeleted> groupDeleted) {
|
||||
this.kmsService = kmsService;
|
||||
this.groupDeleted = groupDeleted;
|
||||
this.logsService = logsService;
|
||||
this.provisioningIds = provisioningIds;
|
||||
this.containerManager = containerManager;
|
||||
@@ -1403,6 +1407,7 @@ public class ElastiCacheService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
groups.delete(groupId);
|
||||
groupDeleted.fire(new ReplicationGroupDeleted(group.getArn()));
|
||||
LOG.infov("Replication group {0} deleted", groupId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
package io.floci.aws.services.elasticache;
|
||||
|
||||
/** Fired once {@code DeleteReplicationGroup} has removed the replication group whose ARN is {@code arn}. */
|
||||
public record ReplicationGroupDeleted(String arn) {}
|
||||
@@ -22,6 +22,18 @@ class SmithyValidationErrorsTest {
|
||||
SmithyValidationErrors.message(List.of("second", "first")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sizeOutOfRange_quotesTheListInTheQuotedFormOnly() {
|
||||
SmithyValidationErrors.Violations quoted = SmithyValidationErrors.Violations.QUOTED;
|
||||
assertEquals("Value '[]' at 'names' failed to satisfy constraint: Member must have length greater than or"
|
||||
+ " equal to 1", quoted.sizeOutOfRange("names", "[]", 0, 1, 2));
|
||||
assertEquals("Value '[a, b, c]' at 'names' failed to satisfy constraint: Member must have length less than"
|
||||
+ " or equal to 2", quoted.sizeOutOfRange("names", "[a, b, c]", 3, 1, 2));
|
||||
assertNull(quoted.sizeOutOfRange("names", "[a]", 1, 1, 2));
|
||||
assertEquals("Value at 'names' failed to satisfy constraint: Member must have length less than or equal to 2",
|
||||
SmithyValidationErrors.Violations.WITHOUT_VALUES.sizeOutOfRange("names", "[a, b, c]", 3, 1, 2));
|
||||
}
|
||||
|
||||
@Test
|
||||
void exception_carriesTheGivenCodeAsA400() {
|
||||
AwsException e = SmithyValidationErrors.exception("ValidationError", List.of("v"));
|
||||
|
||||
+4
-4
@@ -28,7 +28,7 @@ class CloudWatchAlarmQueryHandlerTest {
|
||||
String region = "us-east-1";
|
||||
CloudWatchMetricsService service = new CloudWatchMetricsService(new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new RegionResolver(region, "123456789012"));
|
||||
CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(service, null, null, null);
|
||||
CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(service, null, null, null, null);
|
||||
MultivaluedMap<String, String> request = new MultivaluedHashMap<>();
|
||||
request.putSingle("AlarmName", "shared");
|
||||
request.putSingle("AlarmRule", "FALSE");
|
||||
@@ -68,7 +68,7 @@ class CloudWatchAlarmQueryHandlerTest {
|
||||
String region = "us-east-1";
|
||||
CloudWatchMetricsService service = new CloudWatchMetricsService(new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new RegionResolver(region, "123456789012"));
|
||||
CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(service, null, null, null);
|
||||
CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(service, null, null, null, null);
|
||||
MultivaluedMap<String, String> put = new MultivaluedHashMap<>();
|
||||
put.putSingle("AlarmName", "query-history");
|
||||
handler.handle("PutMetricAlarm", put, region);
|
||||
@@ -122,7 +122,7 @@ class CloudWatchAlarmQueryHandlerTest {
|
||||
String region = "us-east-1";
|
||||
CloudWatchMetricsService service = new CloudWatchMetricsService(new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new RegionResolver(region, "123456789012"));
|
||||
CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(service, null, null, null);
|
||||
CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(service, null, null, null, null);
|
||||
MultivaluedMap<String, String> put = new MultivaluedHashMap<>();
|
||||
put.putSingle("AlarmName", "p99-query");
|
||||
put.putSingle("Namespace", "AWS/ApplicationELB");
|
||||
@@ -161,7 +161,7 @@ class CloudWatchAlarmQueryHandlerTest {
|
||||
String region = "us-east-1";
|
||||
CloudWatchMetricsService service = new CloudWatchMetricsService(new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new RegionResolver(region, "123456789012"));
|
||||
CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(service, null, null, null);
|
||||
CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(service, null, null, null, null);
|
||||
MultivaluedMap<String, String> put = new MultivaluedHashMap<>();
|
||||
put.putSingle("AlarmName", "both-stats-query");
|
||||
put.putSingle("Namespace", "AWS/ApplicationELB");
|
||||
|
||||
+1
-1
@@ -32,7 +32,7 @@ class CloudWatchDescribeAlarmsFiltersHandlerTest {
|
||||
regionResolver);
|
||||
private final CloudWatchMetricsJsonHandler handler = new CloudWatchMetricsJsonHandler(service,
|
||||
new CloudWatchDashboardsService(new InMemoryStorage<>(), regionResolver),
|
||||
new CloudWatchMetricStreamsService(new InMemoryStorage<>(), regionResolver), MAPPER, null);
|
||||
new CloudWatchMetricStreamsService(new InMemoryStorage<>(), regionResolver), MAPPER, null, null);
|
||||
|
||||
@Test
|
||||
void anAlarmIsNeverListedAsItsOwnChildOrParent() {
|
||||
|
||||
+1
-1
@@ -18,7 +18,7 @@ class CloudWatchMetricFilterQueryNamespaceTest {
|
||||
void metricFilterReadApisUseTheCloudWatchQueryNamespace(String action) throws Exception {
|
||||
CloudWatchMetricsService metrics = new CloudWatchMetricsService(new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new RegionResolver("us-east-1", "000000000000"));
|
||||
CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(metrics, null, null, null);
|
||||
CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(metrics, null, null, null, null);
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("Namespace", "MetricFilters");
|
||||
params.putSingle("MetricName", "Count");
|
||||
|
||||
+2
-2
@@ -48,8 +48,8 @@ class CloudWatchMetricMathAlarmTest {
|
||||
RegionResolver resolver = new RegionResolver(REGION, "000000000000");
|
||||
CloudWatchMetricsService service = new CloudWatchMetricsService(new InMemoryStorage<>(), alarmStore, resolver);
|
||||
CloudWatchDashboardsService dashboards = new CloudWatchDashboardsService(new InMemoryStorage<>(), resolver);
|
||||
jsonHandler = new CloudWatchMetricsJsonHandler(service, dashboards, null, MAPPER, null);
|
||||
queryHandler = new CloudWatchMetricsQueryHandler(service, dashboards, null, null);
|
||||
jsonHandler = new CloudWatchMetricsJsonHandler(service, dashboards, null, MAPPER, null, null);
|
||||
queryHandler = new CloudWatchMetricsQueryHandler(service, dashboards, null, null, null);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
|
||||
+2
-2
@@ -43,8 +43,8 @@ class CloudWatchMetricStreamsHandlerTest {
|
||||
CloudWatchDashboardsService dashboardsService =
|
||||
new CloudWatchDashboardsService(new InMemoryStorage<>(), resolver);
|
||||
streamsService = new CloudWatchMetricStreamsService(new InMemoryStorage<>(), resolver);
|
||||
queryHandler = new CloudWatchMetricsQueryHandler(metricsService, dashboardsService, streamsService, null);
|
||||
jsonHandler = new CloudWatchMetricsJsonHandler(metricsService, dashboardsService, streamsService, MAPPER, null);
|
||||
queryHandler = new CloudWatchMetricsQueryHandler(metricsService, dashboardsService, streamsService, null, null);
|
||||
jsonHandler = new CloudWatchMetricsJsonHandler(metricsService, dashboardsService, streamsService, MAPPER, null, null);
|
||||
}
|
||||
|
||||
private static MultivaluedMap<String, String> putParams(String name) {
|
||||
|
||||
+1
-1
@@ -111,7 +111,7 @@ class CloudWatchMetricsJsonHandlerTest {
|
||||
);
|
||||
CloudWatchMetricStreamsService metricStreamsService = new CloudWatchMetricStreamsService(
|
||||
new InMemoryStorage<>(), new RegionResolver(REGION, "000000000000"));
|
||||
handler = new CloudWatchMetricsJsonHandler(service, dashboardsService, metricStreamsService, MAPPER, null);
|
||||
handler = new CloudWatchMetricsJsonHandler(service, dashboardsService, metricStreamsService, MAPPER, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+1
-1
@@ -48,7 +48,7 @@ class CloudWatchMetricsQueryHandlerTest {
|
||||
// The alarm cases below never reach a dashboard operation; the handler simply routes both.
|
||||
private final CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(
|
||||
metricsService, mock(CloudWatchDashboardsService.class),
|
||||
mock(CloudWatchMetricStreamsService.class), null);
|
||||
mock(CloudWatchMetricStreamsService.class), null, null);
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
|
||||
+2
-2
@@ -39,8 +39,8 @@ class CloudWatchMetricsTagsTest {
|
||||
new InMemoryStorage<>(), new RegionResolver("us-east-1", "000000000000"));
|
||||
CloudWatchMetricStreamsService metricStreamsService = new CloudWatchMetricStreamsService(
|
||||
new InMemoryStorage<>(), new RegionResolver("us-east-1", "000000000000"));
|
||||
queryHandler = new CloudWatchMetricsQueryHandler(service, dashboardsService, metricStreamsService, null);
|
||||
jsonHandler = new CloudWatchMetricsJsonHandler(service, dashboardsService, metricStreamsService, objectMapper, null);
|
||||
queryHandler = new CloudWatchMetricsQueryHandler(service, dashboardsService, metricStreamsService, null, null);
|
||||
jsonHandler = new CloudWatchMetricsJsonHandler(service, dashboardsService, metricStreamsService, objectMapper, null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+2
-2
@@ -69,8 +69,8 @@ class CloudWatchPromQlAlarmTest {
|
||||
service = new CloudWatchMetricsService(new InMemoryStorage<>(), new InMemoryStorage<>(), regions,
|
||||
new AlarmSnsNotifier(sns, MAPPER));
|
||||
json = new CloudWatchMetricsJsonHandler(service, new CloudWatchDashboardsService(new InMemoryStorage<>(),
|
||||
regions), new CloudWatchMetricStreamsService(new InMemoryStorage<>(), regions), MAPPER, null);
|
||||
query = new CloudWatchMetricsQueryHandler(service, null, null, null);
|
||||
regions), new CloudWatchMetricStreamsService(new InMemoryStorage<>(), regions), MAPPER, null, null);
|
||||
query = new CloudWatchMetricsQueryHandler(service, null, null, null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+244
@@ -0,0 +1,244 @@
|
||||
package io.floci.aws.services.cloudwatch.metrics;
|
||||
|
||||
import io.floci.aws.core.common.JacksonConfig;
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.services.elasticache.ReplicationGroupDeleted;
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import jakarta.enterprise.event.Event;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import tools.jackson.databind.JsonNode;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.anEmptyMap;
|
||||
import static org.hamcrest.Matchers.contains;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasKey;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/** Resource metrics configurations over the three wires CloudWatch speaks, in one account of their own. */
|
||||
@QuarkusTest
|
||||
class CloudWatchResourceMetricsConfigurationIntegrationTest {
|
||||
private static final String ACCOUNT = "797979797979";
|
||||
private static final ObjectMapper CBOR = JacksonConfig.cborMapper();
|
||||
|
||||
@Inject
|
||||
Event<ReplicationGroupDeleted> groupDeleted;
|
||||
|
||||
@BeforeAll
|
||||
static void configureAwsJson() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aConfigurationIsCreatedReadReplacedAndDeletedOverJson() {
|
||||
String region = "eu-central-2";
|
||||
String arn = group(region, "json-lifecycle");
|
||||
json(region, "CreateResourceMetricsConfiguration", """
|
||||
{"ResourceArn":"%s","MetricSelections":[{"IncludeMetrics":["valkey.memory.used"]}]}
|
||||
""".formatted(arn))
|
||||
.then().statusCode(200)
|
||||
.body("ResourceMetricsConfiguration.ResourceArn", equalTo(arn))
|
||||
.body("ResourceMetricsConfiguration.MetricSelections[0].IncludeMetrics",
|
||||
contains("valkey.memory.used"))
|
||||
.body("ResourceMetricsConfiguration.CreatedAt", notNullValue())
|
||||
.body("ResourceMetricsConfiguration.UpdatedAt", notNullValue());
|
||||
json(region, "CreateResourceMetricsConfiguration", "{\"ResourceArn\":\"" + arn + "\"}")
|
||||
.then().statusCode(409)
|
||||
.body("__type", equalTo("ConflictException"))
|
||||
.body("message", equalTo("This operation attempted to create a resource that already exists."));
|
||||
|
||||
json(region, "UpdateResourceMetricsConfiguration", "{\"ResourceArn\":\"" + arn + "\"}")
|
||||
.then().statusCode(200)
|
||||
.body("ResourceMetricsConfiguration.ResourceArn", equalTo(arn))
|
||||
.body("ResourceMetricsConfiguration", not(hasKey("MetricSelections")));
|
||||
json(region, "GetResourceMetricsConfiguration", "{\"ResourceArn\":\"" + arn + "\"}")
|
||||
.then().statusCode(200)
|
||||
.body("ResourceMetricsConfiguration", not(hasKey("MetricSelections")));
|
||||
|
||||
json(region, "DeleteResourceMetricsConfiguration", "{\"ResourceArn\":\"" + arn + "\"}")
|
||||
.then().statusCode(200)
|
||||
.body("$", anEmptyMap());
|
||||
json(region, "GetResourceMetricsConfiguration", "{\"ResourceArn\":\"" + arn + "\"}")
|
||||
.then().statusCode(404)
|
||||
.header("x-amzn-query-error", "ResourceNotFoundException;Sender")
|
||||
.body("__type", equalTo("ResourceNotFoundException"))
|
||||
.body("message", equalTo("The named resource does not exist."));
|
||||
}
|
||||
|
||||
/** The refusals AWS was recorded answering over JSON, its body naming the validation shape by its Coral id. */
|
||||
@Test
|
||||
void anArnOfAnotherResourceTypeIsRefusedAsAwsAnswers() {
|
||||
String region = "us-west-2";
|
||||
String instance = "arn:aws:ec2:us-west-2:" + ACCOUNT + ":instance/i-0123456789abcdef0";
|
||||
for (String operation : List.of("CreateResourceMetricsConfiguration", "GetResourceMetricsConfiguration",
|
||||
"UpdateResourceMetricsConfiguration", "DeleteResourceMetricsConfiguration")) {
|
||||
assertValidationError(json(region, operation, "{\"ResourceArn\":\"" + instance + "\"}"),
|
||||
"Unsupported resource type");
|
||||
}
|
||||
assertValidationError(json(region, "CreateResourceMetricsConfiguration",
|
||||
"{\"ResourceArn\":\"arn:aws:sqs:us-west-2:" + ACCOUNT + ":no-type\","
|
||||
+ "\"MetricSelections\":[{\"IncludeMetrics\":[\"CPUUtilization\"]}]}"),
|
||||
"ARN is missing resource type");
|
||||
assertValidationError(json(region, "CreateResourceMetricsConfiguration", """
|
||||
{"ResourceArn":"%s","MetricSelections":[{"IncludeMetrics":["CPUUtilization"]},
|
||||
{"IncludeMetrics":["DiskReadOps"]}]}
|
||||
""".formatted(instance)), "1 validation error detected: Value '[ResourceMetricSelection("
|
||||
+ "includeMetrics=[CPUUtilization]), ResourceMetricSelection(includeMetrics=[DiskReadOps])]' at"
|
||||
+ " 'metricSelections' failed to satisfy constraint: Member must have length less than or equal to 1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theQueryWireAnswersTheSameConfiguration() {
|
||||
String region = "ap-northeast-3";
|
||||
String arn = group(region, "query-lifecycle");
|
||||
String created = "CreateResourceMetricsConfigurationResponse.CreateResourceMetricsConfigurationResult"
|
||||
+ ".ResourceMetricsConfiguration";
|
||||
query(region, Map.of("Action", "CreateResourceMetricsConfiguration", "ResourceArn", arn,
|
||||
"MetricSelections.member.1.IncludeMetrics.member.1", "valkey.memory.used",
|
||||
"MetricSelections.member.1.IncludeMetrics.member.2", "valkey.keyspace.hits"))
|
||||
.then().statusCode(200)
|
||||
.body(created + ".ResourceArn", equalTo(arn))
|
||||
.body(created + ".MetricSelections.member.IncludeMetrics.member",
|
||||
contains("valkey.memory.used", "valkey.keyspace.hits"))
|
||||
.body(created + ".CreatedAt", notNullValue());
|
||||
query(region, Map.of("Action", "GetResourceMetricsConfiguration", "ResourceArn", arn))
|
||||
.then().statusCode(200)
|
||||
.body("GetResourceMetricsConfigurationResponse.GetResourceMetricsConfigurationResult"
|
||||
+ ".ResourceMetricsConfiguration.ResourceArn", equalTo(arn));
|
||||
json(region, "GetResourceMetricsConfiguration", "{\"ResourceArn\":\"" + arn + "\"}")
|
||||
.then().statusCode(200)
|
||||
.body("ResourceMetricsConfiguration.MetricSelections[0].IncludeMetrics",
|
||||
contains("valkey.memory.used", "valkey.keyspace.hits"));
|
||||
|
||||
query(region, Map.of("Action", "UpdateResourceMetricsConfiguration", "ResourceArn", arn,
|
||||
"MetricSelections", ""))
|
||||
.then().statusCode(400)
|
||||
.body("ErrorResponse.Error.Code", equalTo("ValidationError"))
|
||||
.body("ErrorResponse.Error.Message", equalTo("1 validation error detected: Value '[]' at"
|
||||
+ " 'metricSelections' failed to satisfy constraint: Member must have length greater than"
|
||||
+ " or equal to 1"));
|
||||
|
||||
query(region, Map.of("Action", "DeleteResourceMetricsConfiguration", "ResourceArn", arn))
|
||||
.then().statusCode(200);
|
||||
query(region, Map.of("Action", "DeleteResourceMetricsConfiguration", "ResourceArn", arn))
|
||||
.then().statusCode(404)
|
||||
.body("ErrorResponse.Error.Code", equalTo("ResourceNotFoundException"))
|
||||
.body("ErrorResponse.Error.Message", equalTo("The named resource does not exist."));
|
||||
query(region, Map.of("Action", "GetResourceMetricsConfiguration",
|
||||
"ResourceArn", "arn:aws:dynamodb:ap-northeast-3:" + ACCOUNT + ":table/t"))
|
||||
.then().statusCode(400)
|
||||
.body("ErrorResponse.Error.Code", equalTo("ValidationError"))
|
||||
.body("ErrorResponse.Error.Message", equalTo("Unsupported resource type"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aQueryListWithGapsKeepsEveryIndexItSends() {
|
||||
String region = "me-south-1";
|
||||
String arn = group(region, "query-gaps");
|
||||
json(region, "CreateResourceMetricsConfiguration", """
|
||||
{"ResourceArn":"%s","MetricSelections":[{"IncludeMetrics":["valkey.memory.used"]}]}
|
||||
""".formatted(arn))
|
||||
.then().statusCode(200);
|
||||
|
||||
query(region, Map.of("Action", "UpdateResourceMetricsConfiguration", "ResourceArn", arn,
|
||||
"MetricSelections.member.2.IncludeMetrics.member.3", "valkey.keyspace.misses",
|
||||
"MetricSelections.member.2.IncludeMetrics.member.1", "valkey.keyspace.hits"))
|
||||
.then().statusCode(200)
|
||||
.body("UpdateResourceMetricsConfigurationResponse.UpdateResourceMetricsConfigurationResult"
|
||||
+ ".ResourceMetricsConfiguration.MetricSelections.member.IncludeMetrics.member",
|
||||
contains("valkey.keyspace.hits", "valkey.keyspace.misses"));
|
||||
json(region, "GetResourceMetricsConfiguration", "{\"ResourceArn\":\"" + arn + "\"}")
|
||||
.then().statusCode(200)
|
||||
.body("ResourceMetricsConfiguration.MetricSelections[0].IncludeMetrics",
|
||||
contains("valkey.keyspace.hits", "valkey.keyspace.misses"));
|
||||
|
||||
query(region, Map.of("Action", "DeleteResourceMetricsConfiguration", "ResourceArn", arn))
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCborWireAnswersTimestampsAsTimestamps() throws Exception {
|
||||
String region = "ap-southeast-4";
|
||||
String arn = group(region, "cbor");
|
||||
JsonNode created = CBOR.readTree(cbor(region, "CreateResourceMetricsConfiguration",
|
||||
Map.of("ResourceArn", arn, "MetricSelections", List.of(Map.of("IncludeMetrics",
|
||||
List.of("valkey.memory.used")))))
|
||||
.then().statusCode(200).extract().asByteArray()).path("ResourceMetricsConfiguration");
|
||||
assertTrue(created.path("CreatedAt").isNumber(), created.toString());
|
||||
assertEquals("valkey.memory.used", created.path("MetricSelections").path(0).path("IncludeMetrics").path(0)
|
||||
.asString(), created.toString());
|
||||
|
||||
JsonNode read = CBOR.readTree(cbor(region, "GetResourceMetricsConfiguration", Map.of("ResourceArn", arn))
|
||||
.then().statusCode(200).extract().asByteArray()).path("ResourceMetricsConfiguration");
|
||||
assertEquals(created.path("CreatedAt").asDouble(), read.path("CreatedAt").asDouble());
|
||||
|
||||
cbor(region, "DeleteResourceMetricsConfiguration", Map.of("ResourceArn", arn)).then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingTheReplicationGroupDeletesItsConfiguration() {
|
||||
String region = "eu-west-2";
|
||||
String arn = group(region, "deleted");
|
||||
String kept = group(region, "kept");
|
||||
for (String group : List.of(arn, kept)) {
|
||||
json(region, "CreateResourceMetricsConfiguration", "{\"ResourceArn\":\"" + group + "\"}")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
RequestScopes.runAs(ACCOUNT, region, () -> groupDeleted.fire(new ReplicationGroupDeleted(arn)));
|
||||
|
||||
json(region, "GetResourceMetricsConfiguration", "{\"ResourceArn\":\"" + arn + "\"}")
|
||||
.then().statusCode(404);
|
||||
json(region, "DeleteResourceMetricsConfiguration", "{\"ResourceArn\":\"" + kept + "\"}")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
private static String group(String region, String name) {
|
||||
return "arn:aws:elasticache:" + region + ":" + ACCOUNT + ":replicationgroup:" + name;
|
||||
}
|
||||
|
||||
private static void assertValidationError(Response response, String message) {
|
||||
response.then().statusCode(400)
|
||||
.header("x-amzn-query-error", "ValidationError;Sender")
|
||||
.body("__type", equalTo("com.amazon.coral.validate#ValidationException"))
|
||||
.body("message", equalTo(message));
|
||||
}
|
||||
|
||||
private static Response json(String region, String operation, String body) {
|
||||
return given().contentType("application/x-amz-json-1.0")
|
||||
.header("Authorization", auth(region))
|
||||
.header("X-Amz-Target", "GraniteServiceVersion20100801." + operation)
|
||||
.body(body).post("/");
|
||||
}
|
||||
|
||||
private static Response query(String region, Map<String, String> params) {
|
||||
return given().contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", auth(region))
|
||||
.formParams(params).formParam("Version", "2010-08-01")
|
||||
.post("/");
|
||||
}
|
||||
|
||||
private static Response cbor(String region, String operation, Map<String, Object> body) throws Exception {
|
||||
return given().contentType("application/cbor").accept("application/cbor")
|
||||
.header("smithy-protocol", "rpc-v2-cbor")
|
||||
.header("Authorization", auth(region))
|
||||
.body(CBOR.writeValueAsBytes(body))
|
||||
.post("/service/GraniteServiceVersion20100801/operation/" + operation);
|
||||
}
|
||||
|
||||
private static String auth(String region) {
|
||||
return "AWS4-HMAC-SHA256 Credential=" + ACCOUNT + "/20261204/" + region
|
||||
+ "/monitoring/aws4_request, SignedHeaders=host, Signature=abc";
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -30,9 +30,9 @@ class CloudWatchWeightedSummaryTest {
|
||||
private final CloudWatchMetricsService service = new CloudWatchMetricsService(
|
||||
store, new InMemoryStorage<>(), new RegionResolver(REGION, "123456789012"));
|
||||
private final CloudWatchMetricsJsonHandler json = new CloudWatchMetricsJsonHandler(
|
||||
service, mock(CloudWatchDashboardsService.class), mock(CloudWatchMetricStreamsService.class), MAPPER, null);
|
||||
service, mock(CloudWatchDashboardsService.class), mock(CloudWatchMetricStreamsService.class), MAPPER, null, null);
|
||||
private final CloudWatchMetricsQueryHandler query = new CloudWatchMetricsQueryHandler(
|
||||
service, mock(CloudWatchDashboardsService.class), mock(CloudWatchMetricStreamsService.class), null);
|
||||
service, mock(CloudWatchDashboardsService.class), mock(CloudWatchMetricStreamsService.class), null, null);
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
|
||||
+226
@@ -0,0 +1,226 @@
|
||||
package io.floci.aws.services.cloudwatch.metrics;
|
||||
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.services.cloudwatch.metrics.model.ResourceMetricsConfiguration;
|
||||
import io.floci.aws.services.cloudwatch.metrics.model.ResourceMetricsConfiguration.ResourceMetricSelection;
|
||||
import io.floci.aws.services.elasticache.ReplicationGroupDeleted;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
/** Resource metrics configurations in one Region of an account, and the refusals AWS was recorded answering. */
|
||||
class ResourceMetricsConfigurationServiceTest {
|
||||
private static final String REGION = "us-west-2";
|
||||
private static final String GROUP = "arn:aws:elasticache:us-west-2:000000000000:replicationgroup:my-cluster";
|
||||
|
||||
private Instant now = Instant.parse("2026-12-04T12:00:00Z");
|
||||
/** The time the service reads, which moves only when a test moves it. */
|
||||
private final Clock clock = new Clock() {
|
||||
@Override
|
||||
public ZoneId getZone() {
|
||||
return ZoneOffset.UTC;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Clock withZone(ZoneId zone) {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Instant instant() {
|
||||
return now;
|
||||
}
|
||||
};
|
||||
private ResourceMetricsConfigurationService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new ResourceMetricsConfigurationService(AccountAwareStorageBackend.inMemory("000000000000"), clock);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aConfigurationIsCreatedReadReplacedAndDeleted() {
|
||||
ResourceMetricsConfiguration created = service.create(REGION, GROUP, selections("valkey.memory.used"));
|
||||
assertEquals(GROUP, created.resourceArn());
|
||||
assertEquals(selections("valkey.memory.used"), created.metricSelections());
|
||||
assertEquals(now, created.createdAt());
|
||||
assertEquals(now, created.updatedAt());
|
||||
assertEquals(created, service.get(REGION, GROUP));
|
||||
|
||||
Instant createdAt = now;
|
||||
now = now.plus(Duration.ofMinutes(1));
|
||||
ResourceMetricsConfiguration replaced = service.update(REGION, GROUP, selections("valkey.keyspace.hits"));
|
||||
assertEquals(selections("valkey.keyspace.hits"), replaced.metricSelections());
|
||||
assertEquals(createdAt, replaced.createdAt());
|
||||
assertEquals(now, replaced.updatedAt());
|
||||
|
||||
assertNull(service.update(REGION, GROUP, null).metricSelections(),
|
||||
"an update without selections removes the filter, so every detailed metric is collected");
|
||||
|
||||
service.delete(REGION, GROUP);
|
||||
assertNotFound(() -> service.get(REGION, GROUP));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSecondCreateForTheSameArnConflictsAndChangesNothing() {
|
||||
ResourceMetricsConfiguration first = service.create(REGION, GROUP, null);
|
||||
|
||||
AwsException conflict = assertThrows(AwsException.class,
|
||||
() -> service.create(REGION, GROUP, selections("valkey.memory.used")));
|
||||
assertEquals("ConflictException", conflict.getErrorCode());
|
||||
assertEquals(409, conflict.getHttpStatus());
|
||||
assertEquals(ResourceMetricsConfigurationService.ALREADY_EXISTS, conflict.getMessage());
|
||||
assertEquals(first, service.get(REGION, GROUP));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anArnWithoutAConfigurationIsNotFoundForEveryOperationButCreate() {
|
||||
assertNotFound(() -> service.get(REGION, GROUP));
|
||||
assertNotFound(() -> service.update(REGION, GROUP, null));
|
||||
assertNotFound(() -> service.delete(REGION, GROUP));
|
||||
}
|
||||
|
||||
@Test
|
||||
void eachRegionKeepsItsOwnConfigurations() {
|
||||
service.create(REGION, GROUP, null);
|
||||
|
||||
assertNotFound(() -> service.get("us-east-1", GROUP));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingTheReplicationGroupDeletesItsConfiguration() {
|
||||
service.create(REGION, GROUP, null);
|
||||
String other = "arn:aws:elasticache:us-west-2:000000000000:replicationgroup:other";
|
||||
service.create(REGION, other, null);
|
||||
|
||||
service.onReplicationGroupDeleted(new ReplicationGroupDeleted(GROUP));
|
||||
|
||||
assertNotFound(() -> service.get(REGION, GROUP));
|
||||
assertEquals(other, service.get(REGION, other).resourceArn());
|
||||
service.onReplicationGroupDeleted(new ReplicationGroupDeleted(GROUP));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theStoredSelectionsAreCopies() {
|
||||
List<String> names = new ArrayList<>(List.of("valkey.memory.used"));
|
||||
service.create(REGION, GROUP, List.of(new ResourceMetricSelection(names)));
|
||||
|
||||
names.add("valkey.keyspace.hits");
|
||||
|
||||
assertEquals(selections("valkey.memory.used"), service.get(REGION, GROUP).metricSelections());
|
||||
}
|
||||
|
||||
/** The refusals of the recorded fixture and check, which every operation answers alike. */
|
||||
@ParameterizedTest
|
||||
@MethodSource("recordedRefusals")
|
||||
void aRecordedRefusalIsAValidationErrorWithAwsMessage(String arn, List<ResourceMetricSelection> selections,
|
||||
String message) {
|
||||
for (Runnable call : List.<Runnable>of(() -> service.create(REGION, arn, selections),
|
||||
() -> service.get(REGION, arn), () -> service.update(REGION, arn, selections),
|
||||
() -> service.delete(REGION, arn))) {
|
||||
AwsException refused = assertThrows(AwsException.class, call::run);
|
||||
assertEquals("ValidationError", refused.getErrorCode());
|
||||
assertEquals("com.amazon.coral.validate#ValidationException", refused.jsonType());
|
||||
assertEquals(400, refused.getHttpStatus());
|
||||
assertEquals(message, refused.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
static Stream<Arguments> recordedRefusals() {
|
||||
String instance = "arn:aws:ec2:us-west-2:000000000000:instance/i-0123456789abcdef0";
|
||||
String notArn = "sim2real-cw-rmc-0001-not-shaped-like-an-arn";
|
||||
return Stream.of(
|
||||
Arguments.of(instance, selections("CPUUtilization"), "Unsupported resource type"),
|
||||
Arguments.of("arn:aws:dynamodb:us-west-2:000000000000:table/sim2real-cw-rmc-0001", null,
|
||||
"Unsupported resource type"),
|
||||
Arguments.of("arn:aws:sqs:us-west-2:000000000000:sim2real-probe-cloudwatch-rmc-no-type",
|
||||
selections("CPUUtilization"), "ARN is missing resource type"),
|
||||
Arguments.of(notArn, null, "1 validation error detected: Value '" + notArn + "' at 'resourceArn'"
|
||||
+ " failed to satisfy constraint: Member must satisfy regular expression pattern:"
|
||||
+ " arn:[a-zA-Z0-9-]+:[a-zA-Z0-9-]+:[a-zA-Z0-9-]*:\\d{12}:.+"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theModelIsCheckedBeforeTheResourceType() {
|
||||
String instance = "arn:aws:ec2:us-west-2:000000000000:instance/i-0123456789abcdef0";
|
||||
List<ResourceMetricSelection> two = List.of(new ResourceMetricSelection(List.of("CPUUtilization")),
|
||||
new ResourceMetricSelection(List.of("DiskReadOps")));
|
||||
|
||||
assertValidationError("1 validation error detected: Value '[ResourceMetricSelection(includeMetrics="
|
||||
+ "[CPUUtilization]), ResourceMetricSelection(includeMetrics=[DiskReadOps])]' at 'metricSelections'"
|
||||
+ " failed to satisfy constraint: Member must have length less than or equal to 1",
|
||||
() -> service.create(REGION, instance, two));
|
||||
}
|
||||
|
||||
@Test
|
||||
void everySelectionConstraintIsChecked() {
|
||||
assertValidationError("1 validation error detected: Value '[]' at 'metricSelections' failed to satisfy"
|
||||
+ " constraint: Member must have length greater than or equal to 1",
|
||||
() -> service.create(REGION, GROUP, List.of()));
|
||||
assertValidationError("1 validation error detected: Value null at 'metricSelections.1.member.includeMetrics'"
|
||||
+ " failed to satisfy constraint: Member must not be null",
|
||||
() -> service.create(REGION, GROUP, List.of(new ResourceMetricSelection(null))));
|
||||
assertValidationError("1 validation error detected: Value '[]' at 'metricSelections.1.member.includeMetrics'"
|
||||
+ " failed to satisfy constraint: Member must have length greater than or equal to 1",
|
||||
() -> service.update(REGION, GROUP, List.of(new ResourceMetricSelection(List.of()))));
|
||||
List<String> tooMany = Collections.nCopies(501, "m");
|
||||
assertValidationError("1 validation error detected: Value '" + tooMany + "' at"
|
||||
+ " 'metricSelections.1.member.includeMetrics' failed to satisfy constraint: Member must have length"
|
||||
+ " less than or equal to 500",
|
||||
() -> service.create(REGION, GROUP, List.of(new ResourceMetricSelection(tooMany))));
|
||||
assertValidationError("1 validation error detected: Value '' at"
|
||||
+ " 'metricSelections.1.member.includeMetrics.2.member' failed to satisfy constraint: Member must"
|
||||
+ " have length greater than or equal to 1",
|
||||
() -> service.create(REGION, GROUP, List.of(new ResourceMetricSelection(List.of("m", "")))));
|
||||
assertValidationError("1 validation error detected: Value null at"
|
||||
+ " 'metricSelections.1.member.includeMetrics.1.member' failed to satisfy constraint: Member must"
|
||||
+ " not be null",
|
||||
() -> service.create(REGION, GROUP, List.of(new ResourceMetricSelection(Arrays.asList(
|
||||
(String) null)))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theArnIsRequiredWithinItsLengthBounds() {
|
||||
assertValidationError("1 validation error detected: Value null at 'resourceArn' failed to satisfy"
|
||||
+ " constraint: Member must not be null", () -> service.get(REGION, null));
|
||||
assertValidationError("2 validation errors detected: Value 'arn:aws' at 'resourceArn' failed to satisfy"
|
||||
+ " constraint: Member must have length greater than or equal to 20; Value 'arn:aws' at"
|
||||
+ " 'resourceArn' failed to satisfy constraint: Member must satisfy regular expression pattern: "
|
||||
+ ResourceMetricsConfigurationService.ARN_PATTERN, () -> service.get(REGION, "arn:aws"));
|
||||
}
|
||||
|
||||
private static List<ResourceMetricSelection> selections(String... names) {
|
||||
return List.of(new ResourceMetricSelection(List.of(names)));
|
||||
}
|
||||
|
||||
private static void assertNotFound(Runnable call) {
|
||||
AwsException missing = assertThrows(AwsException.class, call::run);
|
||||
assertEquals("ResourceNotFoundException", missing.getErrorCode());
|
||||
assertEquals(404, missing.getHttpStatus());
|
||||
assertEquals(ResourceMetricsConfigurationService.NOT_FOUND, missing.getMessage());
|
||||
}
|
||||
|
||||
private static void assertValidationError(String message, Runnable call) {
|
||||
AwsException refused = assertThrows(AwsException.class, call::run);
|
||||
assertEquals("ValidationError", refused.getErrorCode());
|
||||
assertEquals(message, refused.getMessage());
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -22,6 +22,7 @@ import io.floci.aws.services.elasticache.model.ServerlessCache;
|
||||
import io.floci.aws.services.elasticache.proxy.ElastiCacheAuthProxy;
|
||||
import io.floci.aws.services.elasticache.proxy.ElastiCacheProxyManager;
|
||||
import io.floci.aws.services.kms.KmsService;
|
||||
import jakarta.enterprise.event.Event;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -107,7 +108,7 @@ class ElastiCacheServerlessServiceTest {
|
||||
kms = mock(KmsService.class);
|
||||
when(kms.describeKey(anyString(), anyString())).thenThrow(new AwsException("NotFoundException", "Missing key", 400));
|
||||
runtime = new ElastiCacheService(containers, proxies, mock(ValkeyClusterFormation.class), factory,
|
||||
config, ec2, resolver, kms, mock(CloudWatchLogsService.class), new ElastiCacheProvisioningIds());
|
||||
config, ec2, resolver, kms, mock(CloudWatchLogsService.class), new ElastiCacheProvisioningIds(), mock(Event.class));
|
||||
memcached = new ElastiCacheMemcachedService(mock(ElastiCacheMemcachedContainerManager.class), factory,
|
||||
config, new ElastiCacheProvisioningIds(), resolver);
|
||||
service = new ElastiCacheServerlessService(factory, resolver, runtime, memcached);
|
||||
@@ -411,7 +412,7 @@ class ElastiCacheServerlessServiceTest {
|
||||
|
||||
private ElastiCacheService newRuntime(StorageFactory activeFactory) {
|
||||
return new ElastiCacheService(containers, proxies, mock(ValkeyClusterFormation.class), activeFactory,
|
||||
config, ec2, resolver, kms, mock(CloudWatchLogsService.class), new ElastiCacheProvisioningIds());
|
||||
config, ec2, resolver, kms, mock(CloudWatchLogsService.class), new ElastiCacheProvisioningIds(), mock(Event.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -12,6 +12,7 @@ import io.floci.aws.services.elasticache.container.ElastiCacheContainerManager;
|
||||
import io.floci.aws.services.elasticache.container.ValkeyClusterFormation;
|
||||
import io.floci.aws.services.elasticache.proxy.ElastiCacheProxyManager;
|
||||
import io.floci.aws.services.kms.KmsService;
|
||||
import jakarta.enterprise.event.Event;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -57,7 +58,7 @@ final class ElastiCacheServiceFixture {
|
||||
when(kmsService.describeKey(any(), any())).thenThrow(new AwsException("NotFoundException", "Key not found", 404));
|
||||
service = new ElastiCacheService(containerManager, proxyManager, mock(ValkeyClusterFormation.class),
|
||||
storageFactory, config, mock(Ec2Service.class), new RegionResolver("us-east-1", "000000000000"),
|
||||
kmsService, mock(CloudWatchLogsService.class), new ElastiCacheProvisioningIds());
|
||||
kmsService, mock(CloudWatchLogsService.class), new ElastiCacheProvisioningIds(), mock(Event.class));
|
||||
}
|
||||
|
||||
/** The container the group {@code groupId} gets. */
|
||||
|
||||
@@ -29,6 +29,7 @@ import io.floci.aws.services.elasticache.proxy.ElastiCacheAuthProxy;
|
||||
import io.floci.aws.services.elasticache.proxy.ElastiCacheProxyManager;
|
||||
import io.floci.aws.services.kms.KmsService;
|
||||
import io.floci.aws.services.kms.model.KmsKey;
|
||||
import jakarta.enterprise.event.Event;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -89,6 +90,7 @@ class ElastiCacheServiceTest {
|
||||
private ElastiCacheMemcachedContainerManager memcachedContainerManager;
|
||||
private Ec2Service ec2Service;
|
||||
private ElastiCacheProvisioningIds provisioningIds;
|
||||
private Event<ReplicationGroupDeleted> groupDeleted;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
@@ -124,9 +126,21 @@ class ElastiCacheServiceTest {
|
||||
when(kmsService.describeKey(any(), any())).thenThrow(
|
||||
new AwsException("NotFoundException", "Key not found", 404));
|
||||
clusterFormation = mock(ValkeyClusterFormation.class);
|
||||
groupDeleted = mock(Event.class);
|
||||
service = new ElastiCacheService(containerManager, proxyManager, clusterFormation,
|
||||
storageFactory, config, ec2Service, new RegionResolver("us-east-1", "000000000000"),
|
||||
kmsService, mock(CloudWatchLogsService.class), provisioningIds);
|
||||
kmsService, mock(CloudWatchLogsService.class), provisioningIds, groupDeleted);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingAReplicationGroupAnnouncesItsArn() {
|
||||
ReplicationGroup group = service.createReplicationGroup("grp", "test", AuthMode.PASSWORD, null, "us-east-1");
|
||||
|
||||
service.deleteReplicationGroup("grp");
|
||||
|
||||
verify(groupDeleted).fire(new ReplicationGroupDeleted(group.getArn()));
|
||||
assertThrows(AwsException.class, () -> service.deleteReplicationGroup("grp"));
|
||||
verify(groupDeleted, times(1)).fire(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -154,7 +168,7 @@ class ElastiCacheServiceTest {
|
||||
ElastiCacheService svc = new ElastiCacheService(cm, pm, mock(ValkeyClusterFormation.class),
|
||||
sf, cfg, mock(Ec2Service.class),
|
||||
new RegionResolver("us-east-1", "000000000000"),
|
||||
mock(KmsService.class), mock(CloudWatchLogsService.class), provisioningIds);
|
||||
mock(KmsService.class), mock(CloudWatchLogsService.class), provisioningIds, mock(Event.class));
|
||||
|
||||
svc.createReplicationGroup("g1", "d", AuthMode.PASSWORD, null, "us-east-1");
|
||||
|
||||
@@ -239,7 +253,7 @@ class ElastiCacheServiceTest {
|
||||
.thenAnswer(inv -> legacyUsers);
|
||||
ElastiCacheService withLegacy = new ElastiCacheService(containerManager, proxyManager, clusterFormation,
|
||||
legacyStorage, config, ec2Service, new RegionResolver("us-east-1", "000000000000"),
|
||||
kmsService, mock(CloudWatchLogsService.class), provisioningIds);
|
||||
kmsService, mock(CloudWatchLogsService.class), provisioningIds, mock(Event.class));
|
||||
|
||||
assertEquals(Map.of("team", "blue"), withLegacy.storedTags(legacy.getArn()));
|
||||
assertEquals(Set.of("legacy-user"), raw.keys());
|
||||
@@ -1270,7 +1284,7 @@ class ElastiCacheServiceTest {
|
||||
when(config.hostname()).thenReturn(Optional.of("localhost"));
|
||||
return new ElastiCacheService(containerManager, proxyManager, clusterFormation,
|
||||
storageFactory, config, mock(Ec2Service.class),
|
||||
new RegionResolver("us-east-1", "000000000000"), mock(KmsService.class), mock(CloudWatchLogsService.class), new ElastiCacheProvisioningIds());
|
||||
new RegionResolver("us-east-1", "000000000000"), mock(KmsService.class), mock(CloudWatchLogsService.class), new ElastiCacheProvisioningIds(), mock(Event.class));
|
||||
}
|
||||
|
||||
private static void stubPerNodeContainers(ElastiCacheContainerManager containerManager) {
|
||||
@@ -2022,7 +2036,7 @@ class ElastiCacheServiceTest {
|
||||
.thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000"));
|
||||
ElastiCacheService svc = new ElastiCacheService(containerManager, proxyManager, clusterFormation,
|
||||
factory, config, mock(Ec2Service.class),
|
||||
new RegionResolver("us-east-1", "000000000000"), kmsService, mock(CloudWatchLogsService.class), provisioningIds);
|
||||
new RegionResolver("us-east-1", "000000000000"), kmsService, mock(CloudWatchLogsService.class), provisioningIds, mock(Event.class));
|
||||
svc.createReplicationGroup("g1", "d", AuthMode.NO_AUTH, null, "us-east-1");
|
||||
|
||||
pausing.pauseOn(PausingStorageBackend.Call.PUT, "g1");
|
||||
@@ -2141,7 +2155,7 @@ class ElastiCacheServiceTest {
|
||||
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), requestContextInstance, "000000000000"));
|
||||
ElastiCacheService svc = new ElastiCacheService(containerManager, proxyManager, clusterFormation,
|
||||
factory, config, mock(Ec2Service.class),
|
||||
new RegionResolver("us-east-1", "000000000000"), kmsService, mock(CloudWatchLogsService.class), provisioningIds);
|
||||
new RegionResolver("us-east-1", "000000000000"), kmsService, mock(CloudWatchLogsService.class), provisioningIds, mock(Event.class));
|
||||
|
||||
CountDownLatch startedLatch = new CountDownLatch(1);
|
||||
CountDownLatch releaseLatch = new CountDownLatch(1);
|
||||
@@ -2191,7 +2205,7 @@ class ElastiCacheServiceTest {
|
||||
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), requestContextInstance, "000000000000"));
|
||||
ElastiCacheService svc = new ElastiCacheService(containerManager, proxyManager, clusterFormation,
|
||||
factory, config, mock(Ec2Service.class),
|
||||
new RegionResolver("us-east-1", "000000000000"), kmsService, mock(CloudWatchLogsService.class), provisioningIds);
|
||||
new RegionResolver("us-east-1", "000000000000"), kmsService, mock(CloudWatchLogsService.class), provisioningIds, mock(Event.class));
|
||||
|
||||
CountDownLatch startedLatch = new CountDownLatch(1);
|
||||
CountDownLatch releaseLatch = new CountDownLatch(1);
|
||||
@@ -2533,7 +2547,7 @@ class ElastiCacheServiceTest {
|
||||
private ElastiCacheService serviceAfterRestart() {
|
||||
return new ElastiCacheService(containerManager, proxyManager, clusterFormation,
|
||||
storageFactory, config, ec2Service, new RegionResolver("us-east-1", "000000000000"),
|
||||
kmsService, mock(CloudWatchLogsService.class), provisioningIds);
|
||||
kmsService, mock(CloudWatchLogsService.class), provisioningIds, mock(Event.class));
|
||||
}
|
||||
|
||||
private ElastiCacheMemcachedService memcachedService() {
|
||||
|
||||
Reference in new issue
Block a user