mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(cloudwatch): store and serve metric stream definitions (#3214)
* feat(cloudwatch): store and serve metric stream definitions PutMetricStream, GetMetricStream, ListMetricStreams, DeleteMetricStream, StartMetricStreams and StopMetricStreams work over Query and JSON. A stream is a definition with a running or stopped state, and nothing is delivered to the Firehose delivery stream it names. The service lives in its own metricstreams package next to dashboards and is injected into both handlers, and the tag operations route a metric-stream ARN to it. Ported from lex00/floci#42. * fix(cloudwatch): validate nested metric stream members, page ListMetricStreams, keep batches atomic StartMetricStreams and StopMetricStreams resolve every requested name before changing any, so a batch naming a missing stream fails as a whole. PutMetricStream now checks the nested members: a filter needs a Namespace, an IncludeMetrics entry needs a Namespace and a MetricName, and a statistics configuration needs non-empty IncludeMetrics and AdditionalStatistics. ListMetricStreams pages through the shared Pagination helper with MaxResults and NextToken over both protocols. * fix(cloudwatch): answer an unknown name on StartMetricStreams and StopMetricStreams with InvalidParameterValue The model declares ResourceNotFoundException on GetMetricStream alone. Start and Stop declare InvalidParameterValue, so an unknown name in the batch answers that, still after resolving every name before any change.
This commit is contained in:
1 parent
f77cf4da77
commit
5b7c2c4a62
14 files changed
+1580
-12
No files matched your search
+231
@@ -0,0 +1,231 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.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.CloudWatchDashboardsService;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metricstreams.CloudWatchMetricStreamsService;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metricstreams.model.MetricStream;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Both CloudWatch handlers must serve the metric stream operations with the same semantics,
|
||||
* since the Terraform provider speaks Query and the CLI and SDK v3 speak JSON.
|
||||
*/
|
||||
class CloudWatchMetricStreamsHandlerTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private CloudWatchMetricStreamsService streamsService;
|
||||
private CloudWatchMetricsQueryHandler queryHandler;
|
||||
private CloudWatchMetricsJsonHandler jsonHandler;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
RegionResolver resolver = new RegionResolver(REGION, "000000000000");
|
||||
CloudWatchMetricsService metricsService = new CloudWatchMetricsService(
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), resolver);
|
||||
CloudWatchDashboardsService dashboardsService =
|
||||
new CloudWatchDashboardsService(new InMemoryStorage<>(), resolver);
|
||||
streamsService = new CloudWatchMetricStreamsService(new InMemoryStorage<>(), resolver);
|
||||
queryHandler = new CloudWatchMetricsQueryHandler(metricsService, dashboardsService, streamsService);
|
||||
jsonHandler = new CloudWatchMetricsJsonHandler(metricsService, dashboardsService, streamsService, MAPPER);
|
||||
}
|
||||
|
||||
private static MultivaluedMap<String, String> putParams(String name) {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.add("Name", name);
|
||||
params.add("FirehoseArn", "arn:aws:firehose:us-east-1:000000000000:deliverystream/metrics");
|
||||
params.add("RoleArn", "arn:aws:iam::000000000000:role/metric-stream-role");
|
||||
params.add("OutputFormat", "json");
|
||||
params.add("ExcludeFilters.member.1.Namespace", "AWS/S3");
|
||||
params.add("ExcludeFilters.member.1.MetricNames.member.1", "BucketSizeBytes");
|
||||
params.add("StatisticsConfigurations.member.1.IncludeMetrics.member.1.Namespace", "AWS/EC2");
|
||||
params.add("StatisticsConfigurations.member.1.IncludeMetrics.member.1.MetricName", "CPUUtilization");
|
||||
params.add("StatisticsConfigurations.member.1.AdditionalStatistics.member.1", "p99");
|
||||
return params;
|
||||
}
|
||||
|
||||
private String query(String action, MultivaluedMap<String, String> params) {
|
||||
Response response = queryHandler.handle(action, params, REGION);
|
||||
assertEquals(200, response.getStatus());
|
||||
return (String) response.getEntity();
|
||||
}
|
||||
|
||||
@Test
|
||||
void queryPutParsesTheNestedMembersAndAnswersWithTheArn() {
|
||||
String xml = query("PutMetricStream", putParams("stream-a"));
|
||||
|
||||
assertTrue(xml.contains("<PutMetricStreamResult>"));
|
||||
assertTrue(xml.contains("<Arn>arn:aws:cloudwatch:us-east-1:000000000000:metric-stream/stream-a</Arn>"));
|
||||
|
||||
MetricStream stored = streamsService.getMetricStream("stream-a", REGION);
|
||||
assertEquals("AWS/S3", stored.getExcludeFilters().get(0).getNamespace());
|
||||
assertEquals(List.of("BucketSizeBytes"), stored.getExcludeFilters().get(0).getMetricNames());
|
||||
assertEquals("CPUUtilization",
|
||||
stored.getStatisticsConfigurations().get(0).getIncludeMetrics().get(0).metricName());
|
||||
assertEquals(List.of("p99"), stored.getStatisticsConfigurations().get(0).getAdditionalStatistics());
|
||||
}
|
||||
|
||||
@Test
|
||||
void queryGetRendersFiltersAndStatisticsConfigurations() {
|
||||
query("PutMetricStream", putParams("stream-b"));
|
||||
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.add("Name", "stream-b");
|
||||
String xml = query("GetMetricStream", params);
|
||||
|
||||
assertTrue(xml.contains("<GetMetricStreamResult>"));
|
||||
assertTrue(xml.contains("<Name>stream-b</Name>"));
|
||||
assertTrue(xml.contains("<State>running</State>"));
|
||||
assertTrue(xml.contains("<IncludeLinkedAccountsMetrics>false</IncludeLinkedAccountsMetrics>"));
|
||||
assertTrue(xml.contains("<ExcludeFilters><member><Namespace>AWS/S3</Namespace>"
|
||||
+ "<MetricNames><member>BucketSizeBytes</member></MetricNames></member></ExcludeFilters>"));
|
||||
assertTrue(xml.contains("<AdditionalStatistics><member>p99</member></AdditionalStatistics>"));
|
||||
assertFalse(xml.contains("<IncludeFilters>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void queryListStopStartAndDeleteRoundTrip() {
|
||||
query("PutMetricStream", putParams("stream-c"));
|
||||
query("PutMetricStream", putParams("stream-d"));
|
||||
|
||||
String list = query("ListMetricStreams", new MultivaluedHashMap<>());
|
||||
assertTrue(list.contains("<Entries><member><Arn>"));
|
||||
assertTrue(list.contains("<Name>stream-c</Name>"));
|
||||
assertTrue(list.contains("<Name>stream-d</Name>"));
|
||||
|
||||
MultivaluedMap<String, String> names = new MultivaluedHashMap<>();
|
||||
names.add("Names.member.1", "stream-c");
|
||||
names.add("Names.member.2", "stream-d");
|
||||
assertTrue(query("StopMetricStreams", names).contains("<StopMetricStreamsResult"));
|
||||
assertEquals(MetricStream.STATE_STOPPED, streamsService.getMetricStream("stream-d", REGION).getState());
|
||||
assertTrue(query("StartMetricStreams", names).contains("<StartMetricStreamsResult"));
|
||||
assertEquals(MetricStream.STATE_RUNNING, streamsService.getMetricStream("stream-d", REGION).getState());
|
||||
|
||||
MultivaluedMap<String, String> delete = new MultivaluedHashMap<>();
|
||||
delete.add("Name", "stream-c");
|
||||
assertTrue(query("DeleteMetricStream", delete).contains("<DeleteMetricStreamResult"));
|
||||
assertEquals(1, streamsService.listMetricStreams(REGION).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void bothProtocolsPageTheListWithMaxResultsAndNextToken() throws Exception {
|
||||
query("PutMetricStream", putParams("page-a"));
|
||||
query("PutMetricStream", putParams("page-b"));
|
||||
query("PutMetricStream", putParams("page-c"));
|
||||
|
||||
MultivaluedMap<String, String> first = new MultivaluedHashMap<>();
|
||||
first.add("MaxResults", "2");
|
||||
String xml = query("ListMetricStreams", first);
|
||||
assertTrue(xml.contains("<Name>page-a</Name>"));
|
||||
assertTrue(xml.contains("<Name>page-b</Name>"));
|
||||
assertFalse(xml.contains("<Name>page-c</Name>"));
|
||||
String token = xml.substring(xml.indexOf("<NextToken>") + "<NextToken>".length(), xml.indexOf("</NextToken>"));
|
||||
|
||||
JsonNode second = MAPPER.valueToTree(jsonHandler.handle("ListMetricStreams",
|
||||
MAPPER.readTree("{\"MaxResults\": 2, \"NextToken\": \"" + token + "\"}"), REGION).getEntity());
|
||||
assertEquals(1, second.path("Entries").size());
|
||||
assertEquals("page-c", second.path("Entries").get(0).path("Name").asText());
|
||||
assertFalse(second.has("NextToken"));
|
||||
|
||||
// The Query controller renders AwsException as the XML error envelope.
|
||||
AwsException bad = assertThrows(AwsException.class,
|
||||
() -> queryHandler.handle("ListMetricStreams", withToken("not base64!"), REGION));
|
||||
assertEquals("InvalidNextToken", bad.getErrorCode());
|
||||
}
|
||||
|
||||
private static MultivaluedMap<String, String> withToken(String token) {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.add("NextToken", token);
|
||||
return params;
|
||||
}
|
||||
|
||||
@Test
|
||||
void queryTagOperationsRouteAMetricStreamArn() {
|
||||
MultivaluedMap<String, String> params = putParams("stream-e");
|
||||
params.add("Tags.member.1.Key", "team");
|
||||
params.add("Tags.member.1.Value", "platform");
|
||||
query("PutMetricStream", params);
|
||||
String arn = streamsService.getMetricStream("stream-e", REGION).getArn();
|
||||
|
||||
MultivaluedMap<String, String> tag = new MultivaluedHashMap<>();
|
||||
tag.add("ResourceARN", arn);
|
||||
tag.add("Tags.member.1.Key", "owner");
|
||||
tag.add("Tags.member.1.Value", "ops");
|
||||
query("TagResource", tag);
|
||||
|
||||
MultivaluedMap<String, String> list = new MultivaluedHashMap<>();
|
||||
list.add("ResourceARN", arn);
|
||||
String xml = query("ListTagsForResource", list);
|
||||
assertTrue(xml.contains("<Key>team</Key><Value>platform</Value>"));
|
||||
assertTrue(xml.contains("<Key>owner</Key><Value>ops</Value>"));
|
||||
|
||||
MultivaluedMap<String, String> untag = new MultivaluedHashMap<>();
|
||||
untag.add("ResourceARN", arn);
|
||||
untag.add("TagKeys.member.1", "team");
|
||||
query("UntagResource", untag);
|
||||
assertFalse(query("ListTagsForResource", list).contains("<Key>team</Key>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void jsonHandlerRoundTripsAStream() throws Exception {
|
||||
JsonNode request = MAPPER.readTree("""
|
||||
{
|
||||
"Name": "json-stream",
|
||||
"FirehoseArn": "arn:aws:firehose:us-east-1:000000000000:deliverystream/metrics",
|
||||
"RoleArn": "arn:aws:iam::000000000000:role/metric-stream-role",
|
||||
"OutputFormat": "opentelemetry1.0",
|
||||
"IncludeLinkedAccountsMetrics": true,
|
||||
"IncludeFilters": [{"Namespace": "AWS/Lambda", "MetricNames": ["Errors"]}],
|
||||
"StatisticsConfigurations": [
|
||||
{"IncludeMetrics": [{"Namespace": "AWS/EC2", "MetricName": "CPUUtilization"}],
|
||||
"AdditionalStatistics": ["p99"]}
|
||||
],
|
||||
"Tags": [{"Key": "team", "Value": "platform"}]
|
||||
}
|
||||
""");
|
||||
JsonNode put = MAPPER.valueToTree(jsonHandler.handle("PutMetricStream", request, REGION).getEntity());
|
||||
assertEquals("arn:aws:cloudwatch:us-east-1:000000000000:metric-stream/json-stream", put.path("Arn").asText());
|
||||
|
||||
JsonNode get = MAPPER.valueToTree(jsonHandler.handle("GetMetricStream",
|
||||
MAPPER.readTree("{\"Name\": \"json-stream\"}"), REGION).getEntity());
|
||||
assertEquals("json-stream", get.path("Name").asText());
|
||||
assertEquals("running", get.path("State").asText());
|
||||
assertEquals("opentelemetry1.0", get.path("OutputFormat").asText());
|
||||
assertTrue(get.path("IncludeLinkedAccountsMetrics").asBoolean());
|
||||
assertTrue(get.path("CreationDate").isNumber());
|
||||
assertEquals("AWS/Lambda", get.path("IncludeFilters").get(0).path("Namespace").asText());
|
||||
assertEquals("Errors", get.path("IncludeFilters").get(0).path("MetricNames").get(0).asText());
|
||||
assertFalse(get.has("ExcludeFilters"));
|
||||
assertEquals("p99",
|
||||
get.path("StatisticsConfigurations").get(0).path("AdditionalStatistics").get(0).asText());
|
||||
|
||||
JsonNode tags = MAPPER.valueToTree(jsonHandler.handle("ListTagsForResource",
|
||||
MAPPER.readTree("{\"ResourceARN\": \"" + put.path("Arn").asText() + "\"}"), REGION).getEntity());
|
||||
assertEquals("team", tags.path("Tags").get(0).path("Key").asText());
|
||||
|
||||
jsonHandler.handle("StopMetricStreams", MAPPER.readTree("{\"Names\": [\"json-stream\"]}"), REGION);
|
||||
JsonNode list = MAPPER.valueToTree(jsonHandler.handle("ListMetricStreams",
|
||||
MAPPER.createObjectNode(), REGION).getEntity());
|
||||
assertEquals(1, list.path("Entries").size());
|
||||
assertEquals("stopped", list.path("Entries").get(0).path("State").asText());
|
||||
|
||||
jsonHandler.handle("DeleteMetricStream", MAPPER.readTree("{\"Name\": \"json-stream\"}"), REGION);
|
||||
assertTrue(streamsService.listMetricStreams(REGION).isEmpty());
|
||||
}
|
||||
}
|
||||
+4
-1
@@ -10,6 +10,7 @@ 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 io.github.hectorvent.floci.services.cloudwatch.metricstreams.CloudWatchMetricStreamsService;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Instant;
|
||||
@@ -46,7 +47,9 @@ class CloudWatchMetricsJsonHandlerTest {
|
||||
new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000")
|
||||
);
|
||||
handler = new CloudWatchMetricsJsonHandler(service, dashboardsService, MAPPER);
|
||||
CloudWatchMetricStreamsService metricStreamsService = new CloudWatchMetricStreamsService(
|
||||
new InMemoryStorage<>(), new RegionResolver(REGION, "000000000000"));
|
||||
handler = new CloudWatchMetricsJsonHandler(service, dashboardsService, metricStreamsService, MAPPER);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+3
-1
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
|
||||
import io.github.hectorvent.floci.services.cloudwatch.dashboards.CloudWatchDashboardsService;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metricstreams.CloudWatchMetricStreamsService;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
@@ -27,7 +28,8 @@ class CloudWatchMetricsQueryHandlerTest {
|
||||
private final CloudWatchMetricsService metricsService = mock(CloudWatchMetricsService.class);
|
||||
// The alarm cases below never reach a dashboard operation; the handler simply routes both.
|
||||
private final CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(
|
||||
metricsService, mock(CloudWatchDashboardsService.class));
|
||||
metricsService, mock(CloudWatchDashboardsService.class),
|
||||
mock(CloudWatchMetricStreamsService.class));
|
||||
|
||||
@Test
|
||||
void putMetricAlarmDefaultsActionsEnabledToTrueWhenOmitted() {
|
||||
|
||||
+5
-2
@@ -5,6 +5,7 @@ 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.metricstreams.CloudWatchMetricStreamsService;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
@@ -34,8 +35,10 @@ class CloudWatchMetricsTagsTest {
|
||||
);
|
||||
CloudWatchDashboardsService dashboardsService = new CloudWatchDashboardsService(
|
||||
new InMemoryStorage<>(), new RegionResolver("us-east-1", "000000000000"));
|
||||
queryHandler = new CloudWatchMetricsQueryHandler(service, dashboardsService);
|
||||
jsonHandler = new CloudWatchMetricsJsonHandler(service, dashboardsService, objectMapper);
|
||||
CloudWatchMetricStreamsService metricStreamsService = new CloudWatchMetricStreamsService(
|
||||
new InMemoryStorage<>(), new RegionResolver("us-east-1", "000000000000"));
|
||||
queryHandler = new CloudWatchMetricsQueryHandler(service, dashboardsService, metricStreamsService);
|
||||
jsonHandler = new CloudWatchMetricsJsonHandler(service, dashboardsService, metricStreamsService, objectMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+300
@@ -0,0 +1,300 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metricstreams;
|
||||
|
||||
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.hasSize;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
|
||||
/**
|
||||
* Metric streams reach the emulator over the Query protocol from the Terraform AWS provider
|
||||
* and over JSON with an X-Amz-Target header from the CLI and SDK v3. Both routes are covered.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CloudWatchMetricStreamsIntegrationTest {
|
||||
|
||||
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";
|
||||
|
||||
private static final String FIREHOSE_ARN =
|
||||
"arn:aws:firehose:us-east-1:000000000000:deliverystream/metrics";
|
||||
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/metric-stream-role";
|
||||
|
||||
@BeforeAll
|
||||
static void registerJsonParser() {
|
||||
RestAssured.registerParser(JSON_1_0, Parser.JSON);
|
||||
}
|
||||
|
||||
private static RequestSpecification query(String action) {
|
||||
return given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CW_SCOPE)
|
||||
.formParam("Action", action);
|
||||
}
|
||||
|
||||
// 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 String putStream(String name) {
|
||||
return query("PutMetricStream")
|
||||
.formParam("Name", name)
|
||||
.formParam("FirehoseArn", FIREHOSE_ARN)
|
||||
.formParam("RoleArn", ROLE_ARN)
|
||||
.formParam("OutputFormat", "json")
|
||||
.formParam("ExcludeFilters.member.1.Namespace", "AWS/S3")
|
||||
.formParam("ExcludeFilters.member.1.MetricNames.member.1", "BucketSizeBytes")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.contentType("application/xml")
|
||||
.body("PutMetricStreamResponse.PutMetricStreamResult.Arn",
|
||||
equalTo("arn:aws:cloudwatch:us-east-1:000000000000:metric-stream/" + name))
|
||||
.extract().path("PutMetricStreamResponse.PutMetricStreamResult.Arn");
|
||||
}
|
||||
|
||||
@Test
|
||||
void putThenGetReturnsTheDefinition() {
|
||||
putStream("query-round-trip");
|
||||
|
||||
query("GetMetricStream")
|
||||
.formParam("Name", "query-round-trip")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("GetMetricStreamResponse.GetMetricStreamResult.Name", equalTo("query-round-trip"))
|
||||
.body("GetMetricStreamResponse.GetMetricStreamResult.FirehoseArn", equalTo(FIREHOSE_ARN))
|
||||
.body("GetMetricStreamResponse.GetMetricStreamResult.RoleArn", equalTo(ROLE_ARN))
|
||||
.body("GetMetricStreamResponse.GetMetricStreamResult.State", equalTo("running"))
|
||||
.body("GetMetricStreamResponse.GetMetricStreamResult.OutputFormat", equalTo("json"))
|
||||
.body("GetMetricStreamResponse.GetMetricStreamResult.CreationDate", containsString("T"))
|
||||
.body("GetMetricStreamResponse.GetMetricStreamResult.ExcludeFilters.member.Namespace",
|
||||
equalTo("AWS/S3"))
|
||||
.body("GetMetricStreamResponse.GetMetricStreamResult.ExcludeFilters.member.MetricNames.member",
|
||||
equalTo("BucketSizeBytes"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getUnknownStreamReturnsResourceNotFoundException() {
|
||||
query("GetMetricStream")
|
||||
.formParam("Name", "no-such-stream")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("ErrorResponse.Error.Code", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stoppingAnUnknownStreamIsInvalidParameterValue() {
|
||||
query("StopMetricStreams")
|
||||
.formParam("Names.member.1", "no-such-stream")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("ErrorResponse.Error.Code", equalTo("InvalidParameterValue"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void putWithoutARoleIsMissingParameter() {
|
||||
query("PutMetricStream")
|
||||
.formParam("Name", "incomplete")
|
||||
.formParam("FirehoseArn", FIREHOSE_ARN)
|
||||
.formParam("OutputFormat", "json")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("ErrorResponse.Error.Code", equalTo("MissingParameter"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listStopStartAndDeleteOverQuery() {
|
||||
putStream("lifecycle-one");
|
||||
putStream("lifecycle-two");
|
||||
|
||||
query("ListMetricStreams")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("ListMetricStreamsResponse.ListMetricStreamsResult.Entries.member.Name",
|
||||
hasItem("lifecycle-one"))
|
||||
.body("ListMetricStreamsResponse.ListMetricStreamsResult.Entries.member.Name",
|
||||
hasItem("lifecycle-two"));
|
||||
|
||||
query("StopMetricStreams")
|
||||
.formParam("Names.member.1", "lifecycle-one")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
query("GetMetricStream")
|
||||
.formParam("Name", "lifecycle-one")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("GetMetricStreamResponse.GetMetricStreamResult.State", equalTo("stopped"));
|
||||
|
||||
query("StartMetricStreams")
|
||||
.formParam("Names.member.1", "lifecycle-one")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
query("GetMetricStream")
|
||||
.formParam("Name", "lifecycle-one")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("GetMetricStreamResponse.GetMetricStreamResult.State", equalTo("running"));
|
||||
|
||||
query("DeleteMetricStream")
|
||||
.formParam("Name", "lifecycle-one")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
query("GetMetricStream")
|
||||
.formParam("Name", "lifecycle-one")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
void listPagesOverBothProtocols() {
|
||||
putStream("paged-a");
|
||||
putStream("paged-b");
|
||||
|
||||
String token = query("ListMetricStreams")
|
||||
.formParam("MaxResults", "1")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("ListMetricStreamsResponse.ListMetricStreamsResult.NextToken", notNullValue())
|
||||
.extract().path("ListMetricStreamsResponse.ListMetricStreamsResult.NextToken");
|
||||
|
||||
json("ListMetricStreams", "{\"MaxResults\": 1, \"NextToken\": \"" + token + "\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Entries", hasSize(1));
|
||||
|
||||
query("ListMetricStreams")
|
||||
.formParam("NextToken", "not base64!")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("ErrorResponse.Error.Code", equalTo("InvalidNextToken"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagsSuppliedOnPutAreReadableThroughListTagsForResource() {
|
||||
String arn = query("PutMetricStream")
|
||||
.formParam("Name", "tagged")
|
||||
.formParam("FirehoseArn", FIREHOSE_ARN)
|
||||
.formParam("RoleArn", ROLE_ARN)
|
||||
.formParam("OutputFormat", "json")
|
||||
.formParam("Tags.member.1.Key", "team")
|
||||
.formParam("Tags.member.1.Value", "platform")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().path("PutMetricStreamResponse.PutMetricStreamResult.Arn");
|
||||
|
||||
query("ListTagsForResource")
|
||||
.formParam("ResourceARN", arn)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<Key>team</Key>"))
|
||||
.body(containsString("<Value>platform</Value>"));
|
||||
|
||||
query("UntagResource")
|
||||
.formParam("ResourceARN", arn)
|
||||
.formParam("TagKeys.member.1", "team")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
query("ListTagsForResource")
|
||||
.formParam("ResourceARN", arn)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(not(containsString("<Key>team</Key>")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSameOperationsAreServedOverTheJsonProtocol() {
|
||||
json("PutMetricStream", "{\"Name\": \"json-round-trip\", \"FirehoseArn\": \"" + FIREHOSE_ARN
|
||||
+ "\", \"RoleArn\": \"" + ROLE_ARN + "\", \"OutputFormat\": \"opentelemetry1.0\","
|
||||
+ " \"IncludeFilters\": [{\"Namespace\": \"AWS/Lambda\", \"MetricNames\": [\"Errors\"]}]}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Arn", equalTo("arn:aws:cloudwatch:us-east-1:000000000000:metric-stream/json-round-trip"));
|
||||
|
||||
json("GetMetricStream", "{\"Name\": \"json-round-trip\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Name", equalTo("json-round-trip"))
|
||||
.body("State", equalTo("running"))
|
||||
.body("OutputFormat", equalTo("opentelemetry1.0"))
|
||||
.body("IncludeFilters[0].Namespace", equalTo("AWS/Lambda"))
|
||||
.body("IncludeFilters[0].MetricNames[0]", equalTo("Errors"));
|
||||
|
||||
json("ListMetricStreams", "{}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Entries.Name", hasItem("json-round-trip"));
|
||||
|
||||
json("GetMetricStream", "{\"Name\": \"json-missing\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("__type", containsString("ResourceNotFoundException"));
|
||||
}
|
||||
}
|
||||
+235
@@ -0,0 +1,235 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metricstreams;
|
||||
|
||||
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.metricstreams.model.MetricStream;
|
||||
import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metricstreams.model.MetricStreamFilter;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metricstreams.model.MetricStreamStatisticsConfiguration;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class CloudWatchMetricStreamsServiceTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
private CloudWatchMetricStreamsService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new CloudWatchMetricStreamsService(
|
||||
new InMemoryStorage<>(), new RegionResolver(REGION, "000000000000"));
|
||||
}
|
||||
|
||||
private static MetricStream stream(String name) {
|
||||
MetricStream stream = new MetricStream();
|
||||
stream.setName(name);
|
||||
stream.setFirehoseArn("arn:aws:firehose:us-east-1:000000000000:deliverystream/metrics");
|
||||
stream.setRoleArn("arn:aws:iam::000000000000:role/metric-stream-role");
|
||||
stream.setOutputFormat("json");
|
||||
return stream;
|
||||
}
|
||||
|
||||
@Test
|
||||
void putStoresTheDefinitionRunningWithAnArn() {
|
||||
MetricStream stored = service.putMetricStream(stream("ops"), REGION);
|
||||
|
||||
assertEquals("arn:aws:cloudwatch:us-east-1:000000000000:metric-stream/ops", stored.getArn());
|
||||
assertEquals(MetricStream.STATE_RUNNING, stored.getState());
|
||||
assertTrue(stored.getCreationDate() > 0);
|
||||
assertEquals(stored.getCreationDate(), stored.getLastUpdateDate());
|
||||
assertEquals("json", service.getMetricStream("ops", REGION).getOutputFormat());
|
||||
}
|
||||
|
||||
@Test
|
||||
void putOnExistingNameUpdatesTheDefinitionAndKeepsCreationStateAndTags() {
|
||||
MetricStream first = stream("ops");
|
||||
first.setTags(new LinkedHashMap<>(Map.of("env", "dev")));
|
||||
long createdAt = service.putMetricStream(first, REGION).getCreationDate();
|
||||
service.stopMetricStreams(List.of("ops"), REGION);
|
||||
|
||||
MetricStream update = stream("ops");
|
||||
update.setOutputFormat("opentelemetry1.0");
|
||||
update.setTags(new LinkedHashMap<>(Map.of("env", "prod")));
|
||||
service.putMetricStream(update, REGION);
|
||||
|
||||
MetricStream stored = service.getMetricStream("ops", REGION);
|
||||
assertEquals(createdAt, stored.getCreationDate());
|
||||
assertEquals("opentelemetry1.0", stored.getOutputFormat());
|
||||
assertEquals(MetricStream.STATE_STOPPED, stored.getState());
|
||||
assertEquals("dev", stored.getTags().get("env"));
|
||||
assertEquals(1, service.listMetricStreams(REGION).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void putRequiresTheDocumentedParameters() {
|
||||
MetricStream missingRole = stream("ops");
|
||||
missingRole.setRoleArn(null);
|
||||
AwsException e = assertThrows(AwsException.class, () -> service.putMetricStream(missingRole, REGION));
|
||||
assertEquals("MissingParameter", e.getErrorCode());
|
||||
assertEquals(400, e.getHttpStatus());
|
||||
|
||||
MetricStream badFormat = stream("ops");
|
||||
badFormat.setOutputFormat("csv");
|
||||
assertEquals("InvalidParameterValue",
|
||||
assertThrows(AwsException.class, () -> service.putMetricStream(badFormat, REGION)).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void putRejectsIncludeAndExcludeFiltersTogether() {
|
||||
MetricStream both = stream("ops");
|
||||
both.setIncludeFilters(List.of(new MetricStreamFilter("AWS/EC2", List.of())));
|
||||
both.setExcludeFilters(List.of(new MetricStreamFilter("AWS/S3", List.of())));
|
||||
|
||||
AwsException e = assertThrows(AwsException.class, () -> service.putMetricStream(both, REGION));
|
||||
assertEquals("InvalidParameterCombination", e.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getMissingStreamThrowsResourceNotFoundException() {
|
||||
AwsException e = assertThrows(AwsException.class, () -> service.getMetricStream("nope", REGION));
|
||||
assertEquals("ResourceNotFoundException", e.getErrorCode());
|
||||
assertEquals(404, e.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listIsScopedToTheRegionAndSortedByName() {
|
||||
service.putMetricStream(stream("zeta"), REGION);
|
||||
service.putMetricStream(stream("alpha"), REGION);
|
||||
service.putMetricStream(stream("other-region"), "eu-west-1");
|
||||
|
||||
List<MetricStream> streams = service.listMetricStreams(REGION);
|
||||
assertEquals(List.of("alpha", "zeta"), streams.stream().map(MetricStream::getName).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopAndStartToggleTheState() {
|
||||
service.putMetricStream(stream("ops"), REGION);
|
||||
|
||||
service.stopMetricStreams(List.of("ops"), REGION);
|
||||
assertEquals(MetricStream.STATE_STOPPED, service.getMetricStream("ops", REGION).getState());
|
||||
|
||||
service.startMetricStreams(List.of("ops"), REGION);
|
||||
assertEquals(MetricStream.STATE_RUNNING, service.getMetricStream("ops", REGION).getState());
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopRequiresNamesAndReportsAMissingStream() {
|
||||
assertEquals("MissingParameter",
|
||||
assertThrows(AwsException.class, () -> service.stopMetricStreams(List.of(), REGION)).getErrorCode());
|
||||
// The model declares ResourceNotFoundException on GetMetricStream alone.
|
||||
assertEquals("InvalidParameterValue",
|
||||
assertThrows(AwsException.class, () -> service.stopMetricStreams(List.of("nope"), REGION)).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBatchNamingAMissingStreamChangesNothing() {
|
||||
service.putMetricStream(stream("ops"), REGION);
|
||||
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> service.stopMetricStreams(List.of("ops", "nope"), REGION));
|
||||
|
||||
assertEquals("InvalidParameterValue", e.getErrorCode());
|
||||
assertEquals(MetricStream.STATE_RUNNING, service.getMetricStream("ops", REGION).getState());
|
||||
}
|
||||
|
||||
@Test
|
||||
void putRejectsAFilterWithoutANamespace() {
|
||||
MetricStream bad = stream("ops");
|
||||
bad.setExcludeFilters(List.of(new MetricStreamFilter(null, List.of("Errors"))));
|
||||
|
||||
AwsException e = assertThrows(AwsException.class, () -> service.putMetricStream(bad, REGION));
|
||||
assertEquals("MissingParameter", e.getErrorCode());
|
||||
assertThrows(AwsException.class, () -> service.getMetricStream("ops", REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void putRejectsAnIncompleteStatisticsConfiguration() {
|
||||
MetricStreamStatisticsConfiguration noMetrics = new MetricStreamStatisticsConfiguration();
|
||||
noMetrics.setAdditionalStatistics(List.of("p99"));
|
||||
MetricStream first = stream("ops");
|
||||
first.setStatisticsConfigurations(List.of(noMetrics));
|
||||
assertEquals("InvalidParameterValue",
|
||||
assertThrows(AwsException.class, () -> service.putMetricStream(first, REGION)).getErrorCode());
|
||||
|
||||
MetricStreamStatisticsConfiguration noStatistics = new MetricStreamStatisticsConfiguration();
|
||||
noStatistics.setIncludeMetrics(List.of(
|
||||
new MetricStreamStatisticsConfiguration.IncludeMetric("AWS/EC2", "CPUUtilization")));
|
||||
MetricStream second = stream("ops");
|
||||
second.setStatisticsConfigurations(List.of(noStatistics));
|
||||
assertEquals("InvalidParameterValue",
|
||||
assertThrows(AwsException.class, () -> service.putMetricStream(second, REGION)).getErrorCode());
|
||||
|
||||
MetricStreamStatisticsConfiguration blankMetric = new MetricStreamStatisticsConfiguration();
|
||||
blankMetric.setIncludeMetrics(List.of(
|
||||
new MetricStreamStatisticsConfiguration.IncludeMetric("AWS/EC2", null)));
|
||||
blankMetric.setAdditionalStatistics(List.of("p99"));
|
||||
MetricStream third = stream("ops");
|
||||
third.setStatisticsConfigurations(List.of(blankMetric));
|
||||
assertEquals("MissingParameter",
|
||||
assertThrows(AwsException.class, () -> service.putMetricStream(third, REGION)).getErrorCode());
|
||||
assertTrue(service.listMetricStreams(REGION).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listPagesInNameOrderWithAnOpaqueToken() {
|
||||
for (String name : List.of("c", "a", "b")) {
|
||||
service.putMetricStream(stream(name), REGION);
|
||||
}
|
||||
|
||||
PaginatedResult<MetricStream> first = service.listMetricStreams(2, null, REGION);
|
||||
assertEquals(List.of("a", "b"), first.items().stream().map(MetricStream::getName).toList());
|
||||
assertNotNull(first.nextToken());
|
||||
|
||||
PaginatedResult<MetricStream> second = service.listMetricStreams(2, first.nextToken(), REGION);
|
||||
assertEquals(List.of("c"), second.items().stream().map(MetricStream::getName).toList());
|
||||
assertNull(second.nextToken());
|
||||
|
||||
assertEquals("InvalidNextToken",
|
||||
assertThrows(AwsException.class,
|
||||
() -> service.listMetricStreams(2, "not base64!", REGION)).getErrorCode());
|
||||
assertEquals("InvalidNextToken",
|
||||
assertThrows(AwsException.class,
|
||||
() -> service.listMetricStreams(0, null, REGION)).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteRemovesTheStreamAndToleratesAMissingOne() {
|
||||
service.putMetricStream(stream("ops"), REGION);
|
||||
|
||||
service.deleteMetricStream("ops", REGION);
|
||||
service.deleteMetricStream("ops", REGION);
|
||||
|
||||
assertTrue(service.listMetricStreams(REGION).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagsRoundTripByArn() {
|
||||
MetricStream tagged = stream("ops");
|
||||
tagged.setTags(new LinkedHashMap<>(Map.of("team", "platform")));
|
||||
String arn = service.putMetricStream(tagged, REGION).getArn();
|
||||
|
||||
assertTrue(CloudWatchMetricStreamsService.isMetricStreamArn(arn));
|
||||
assertFalse(CloudWatchMetricStreamsService.isMetricStreamArn(
|
||||
"arn:aws:cloudwatch:us-east-1:000000000000:alarm:ops"));
|
||||
assertEquals("platform", service.listTagsForResource(arn, REGION).get("team"));
|
||||
|
||||
service.tagResource(arn, Map.of("owner", "ops"), REGION);
|
||||
assertEquals("ops", service.listTagsForResource(arn, REGION).get("owner"));
|
||||
|
||||
service.untagResource(arn, List.of("team"), REGION);
|
||||
assertFalse(service.listTagsForResource(arn, REGION).containsKey("team"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user