diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchDescribeAlarmsFiltersTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchDescribeAlarmsFiltersTest.java new file mode 100644 index 0000000000..50838f119d --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchDescribeAlarmsFiltersTest.java @@ -0,0 +1,196 @@ +package com.floci.test; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.cloudwatch.CloudWatchClient; +import software.amazon.awssdk.services.cloudwatch.model.AlarmType; +import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException; +import software.amazon.awssdk.services.cloudwatch.model.ComparisonOperator; +import software.amazon.awssdk.services.cloudwatch.model.CompositeAlarm; +import software.amazon.awssdk.services.cloudwatch.model.DescribeAlarmsRequest; +import software.amazon.awssdk.services.cloudwatch.model.DescribeAlarmsResponse; +import software.amazon.awssdk.services.cloudwatch.model.MetricAlarm; +import software.amazon.awssdk.services.cloudwatch.model.PutMetricAlarmRequest; +import software.amazon.awssdk.services.cloudwatch.model.StateValue; +import software.amazon.awssdk.services.cloudwatch.model.Statistic; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Consumer; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@DisplayName("CloudWatch - DescribeAlarms filters") +class CloudWatchDescribeAlarmsFiltersTest { + + private CloudWatchClient cloudWatch; + private String prefix; + private final List created = new ArrayList<>(); + + @BeforeEach + void setup() { + cloudWatch = TestFixtures.cloudWatchClient(); + prefix = TestFixtures.uniqueName("sdk-describe-filters"); + } + + @AfterEach + void cleanup() { + try { + for (int index = created.size() - 1; index >= 0; index--) { + String name = created.get(index); + cloudWatch.deleteAlarms(request -> request.alarmNames(name)); + } + } finally { + cloudWatch.close(); + } + } + + @Test + @DisplayName("StateValue and ActionPrefix narrow metric and composite alarms") + void stateValueAndActionPrefixNarrowBothAlarmKinds() { + String topic = "arn:aws:sns:us-east-1:000000000000:" + prefix; + String alarm = putMetricAlarm("alarm", request -> request.alarmActions(topic + "-page")); + String ok = putMetricAlarm("ok", request -> request.okActions(topic + "-info")); + String unknown = putMetricAlarm("unknown", request -> request.insufficientDataActions(topic + "-info")); + setState(alarm, StateValue.ALARM); + setState(ok, StateValue.OK); + String compositeAlarm = putCompositeAlarm("composite-alarm", "TRUE", topic + "-page"); + String compositeOk = putCompositeAlarm("composite-ok", "FALSE", null); + + DescribeAlarmsResponse inAlarm = cloudWatch.describeAlarms(request -> request.alarmNamePrefix(prefix) + .stateValue(StateValue.ALARM).alarmTypes(AlarmType.METRIC_ALARM, AlarmType.COMPOSITE_ALARM)); + assertThat(inAlarm.metricAlarms()).extracting(MetricAlarm::alarmName).containsExactly(alarm); + assertThat(inAlarm.compositeAlarms()).extracting(CompositeAlarm::alarmName).containsExactly(compositeAlarm); + + DescribeAlarmsResponse okAlarms = cloudWatch.describeAlarms(request -> request.alarmNamePrefix(prefix) + .stateValue(StateValue.OK).alarmTypes(AlarmType.METRIC_ALARM, AlarmType.COMPOSITE_ALARM)); + assertThat(okAlarms.metricAlarms()).extracting(MetricAlarm::alarmName).containsExactly(ok); + assertThat(okAlarms.compositeAlarms()).extracting(CompositeAlarm::alarmName).containsExactly(compositeOk); + + DescribeAlarmsResponse pageAction = cloudWatch.describeAlarms(request -> request.actionPrefix(topic + "-page") + .alarmTypes(AlarmType.METRIC_ALARM, AlarmType.COMPOSITE_ALARM)); + assertThat(pageAction.metricAlarms()).extracting(MetricAlarm::alarmName).containsExactly(alarm); + assertThat(pageAction.compositeAlarms()).extracting(CompositeAlarm::alarmName).containsExactly(compositeAlarm); + + assertThat(cloudWatch.describeAlarms(request -> request.actionPrefix(topic + "-info")).metricAlarms()) + .extracting(MetricAlarm::alarmName).containsExactlyInAnyOrder(ok, unknown); + assertThat(cloudWatch.describeAlarms(request -> request.actionPrefix(topic) + .stateValue(StateValue.INSUFFICIENT_DATA)).metricAlarms()) + .extracting(MetricAlarm::alarmName).containsExactly(unknown); + } + + @Test + @DisplayName("ChildrenOfAlarmName and ParentsOfAlarmName return the related alarms' names and ARNs") + void childrenAndParentsReturnTheRelatedAlarms() { + String cpu = putMetricAlarm("cpu", request -> { }); + String disk = putMetricAlarm("disk", request -> { }); + setState(cpu, StateValue.ALARM); + String diskArn = cloudWatch.describeAlarms(request -> request.alarmNames(disk)).metricAlarms().get(0) + .alarmArn(); + String host = putCompositeAlarm("host", "ALARM(" + cpu + ") OR ALARM(\"" + diskArn + "\")", null); + String fleet = putCompositeAlarm("fleet", "ALARM(" + host + ") AND NOT OK(" + cpu + ")", null); + + DescribeAlarmsResponse hostChildren = cloudWatch.describeAlarms(request -> request.childrenOfAlarmName(host)); + assertThat(hostChildren.metricAlarms()).extracting(MetricAlarm::alarmName).containsExactlyInAnyOrder(cpu, disk); + assertThat(hostChildren.compositeAlarms()).isEmpty(); + MetricAlarm cpuChild = hostChildren.metricAlarms().stream() + .filter(child -> child.alarmName().equals(cpu)).findFirst().orElseThrow(); + assertThat(cpuChild.stateValue()).isEqualTo(StateValue.ALARM); + assertThat(cpuChild.stateUpdatedTimestamp()).isNotNull(); + assertThat(cpuChild.alarmArn()).endsWith(":alarm:" + cpu); + assertThat(cpuChild.stateReason()).isNull(); + assertThat(cpuChild.metricName()).isNull(); + assertThat(cpuChild.hasAlarmActions()).isFalse(); + + DescribeAlarmsResponse fleetChildren = cloudWatch.describeAlarms(request -> request + .childrenOfAlarmName(fleet).maxRecords(10)); + assertThat(fleetChildren.metricAlarms()).extracting(MetricAlarm::alarmName).containsExactly(cpu); + assertThat(fleetChildren.compositeAlarms()).extracting(CompositeAlarm::alarmName).containsExactly(host); + assertThat(fleetChildren.compositeAlarms().get(0).alarmRule()).isNull(); + + DescribeAlarmsResponse cpuParents = cloudWatch.describeAlarms(request -> request.parentsOfAlarmName(cpu)); + assertThat(cpuParents.metricAlarms()).isEmpty(); + assertThat(cpuParents.compositeAlarms()).extracting(CompositeAlarm::alarmName) + .containsExactlyInAnyOrder(host, fleet); + CompositeAlarm hostParent = cpuParents.compositeAlarms().stream() + .filter(parent -> parent.alarmName().equals(host)).findFirst().orElseThrow(); + assertThat(hostParent.alarmArn()).endsWith(":alarm:" + host); + assertThat(hostParent.stateValue()).isNull(); + assertThat(hostParent.alarmRule()).isNull(); + + assertThat(cloudWatch.describeAlarms(request -> request.parentsOfAlarmName(disk)).compositeAlarms()) + .extracting(CompositeAlarm::alarmName).containsExactly(host); + assertThat(cloudWatch.describeAlarms(request -> request.parentsOfAlarmName(fleet)).compositeAlarms()).isEmpty(); + } + + @Test + @DisplayName("ChildrenOfAlarmName and ParentsOfAlarmName refuse any other filter") + void childrenAndParentsRefuseOtherFilters() { + assertRefused("ChildrenOfAlarmName", request -> request.childrenOfAlarmName(prefix).stateValue(StateValue.OK)); + assertRefused("ChildrenOfAlarmName", request -> request.childrenOfAlarmName(prefix) + .alarmTypes(AlarmType.COMPOSITE_ALARM)); + assertRefused("ChildrenOfAlarmName", request -> request.childrenOfAlarmName(prefix).parentsOfAlarmName(prefix)); + assertRefused("ParentsOfAlarmName", request -> request.parentsOfAlarmName(prefix).alarmNames(prefix)); + assertRefused("ParentsOfAlarmName", request -> request.parentsOfAlarmName(prefix).actionPrefix("arn:")); + } + + @Test + @DisplayName("A StateValue outside OK, ALARM and INSUFFICIENT_DATA is refused") + void unknownStateValueIsRefused() { + assertThatThrownBy(() -> cloudWatch.describeAlarms(request -> request.stateValue("BOGUS"))) + .isInstanceOf(CloudWatchException.class) + .satisfies(error -> { + CloudWatchException exception = (CloudWatchException) error; + assertThat(exception.statusCode()).isEqualTo(400); + assertThat(exception.awsErrorDetails().errorCode()).isEqualTo("ValidationError"); + assertThat(exception.awsErrorDetails().errorMessage()).isEqualTo("1 validation error detected: " + + "Value 'BOGUS' at 'stateValue' failed to satisfy constraint: Member must satisfy enum " + + "value set: [INSUFFICIENT_DATA, ALARM, OK]"); + }); + } + + private void assertRefused(String named, Consumer request) { + assertThatThrownBy(() -> cloudWatch.describeAlarms(request)) + .isInstanceOf(CloudWatchException.class) + .satisfies(error -> { + CloudWatchException exception = (CloudWatchException) error; + assertThat(exception.statusCode()).isEqualTo(400); + assertThat(exception.awsErrorDetails().errorCode()).isEqualTo("ValidationError"); + assertThat(exception.awsErrorDetails().errorMessage()).isEqualTo("If you specify " + named + + ", you cannot specify any other parameters in the request except for MaxRecords and " + + "NextToken."); + }); + } + + private String putMetricAlarm(String suffix, Consumer actions) { + String name = prefix + "-" + suffix; + cloudWatch.putMetricAlarm(request -> { + request.alarmName(name).namespace("SdkDescribeFilters").metricName(name).statistic(Statistic.AVERAGE) + .period(60).evaluationPeriods(1).threshold(1.0) + .comparisonOperator(ComparisonOperator.GREATER_THAN_THRESHOLD) + .treatMissingData("ignore").actionsEnabled(false); + actions.accept(request); + }); + created.add(name); + return name; + } + + private String putCompositeAlarm(String suffix, String rule, String alarmAction) { + String name = prefix + "-" + suffix; + cloudWatch.putCompositeAlarm(request -> { + request.alarmName(name).alarmRule(rule).actionsEnabled(false); + if (alarmAction != null) { + request.alarmActions(alarmAction); + } + }); + created.add(name); + return name; + } + + private void setState(String name, StateValue state) { + cloudWatch.setAlarmState(request -> request.alarmName(name).stateValue(state).stateReason("sdk test")); + } +} diff --git a/docs/services/cloudwatch.md b/docs/services/cloudwatch.md index 14c25f41bf..b18199acc9 100644 --- a/docs/services/cloudwatch.md +++ b/docs/services/cloudwatch.md @@ -495,6 +495,21 @@ metric does not retain the previous definition. This is management-plane support: the alarm evaluator currently evaluates only single-metric alarms, not metric-math expressions. `SetAlarmState` remains available for manual transitions. +### DescribeAlarms filters {#describealarms-filters} + +`DescribeAlarms` applies every filter a request gives: `AlarmNames` or `AlarmNamePrefix`, +`AlarmTypes`, `StateValue` and `ActionPrefix`. `StateValue` and `ActionPrefix` narrow metric and +composite alarms alike. The API reference calls `ActionPrefix` a prefix for any action, so an alarm +matches when one of its `AlarmActions`, `OKActions` or `InsufficientDataActions` starts with it. + +`ChildrenOfAlarmName` lists the metric and composite alarms a composite alarm's rule names, by name +or ARN, with only their name, ARN, `StateValue` and `StateUpdatedTimestamp`. `ParentsOfAlarmName` +lists the composite alarms whose rules name an alarm, with only their name and ARN. Neither lists +the alarm it names. Either one with any other member except `MaxRecords` and `NextToken` is refused +with `ValidationError`, as is a `StateValue` outside `OK`, `ALARM` and `INSUFFICIENT_DATA`, an +empty or over-long `ActionPrefix`, and an empty or over-long alarm name in either member. +`MaxRecords` and `NextToken` are accepted, but every match comes back in one response. + ### Alarm history {#alarm-history} `DescribeAlarmHistory` lists two kinds of items, newest first unless `ScanBy` is diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java index bd97aa2e0b..b10d675f74 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java @@ -45,9 +45,11 @@ public class CloudWatchMetricsJsonHandler { /** * The operations served through the console's {@code CloudWatchVersion20130116.} target, each - * with the request members accepted there: the ones this handler honours, plus + * with the request members accepted there: some of the ones this handler honours, plus * {@code NextToken} and {@code MaxRecords}, which change nothing because every result comes - * back at once. + * back at once. DescribeAlarms' {@code StateValue}, {@code ActionPrefix}, + * {@code ChildrenOfAlarmName} and {@code ParentsOfAlarmName} stay refused here until the + * console's API is known to give them the same shapes. */ private static final Map> CONSOLE_TARGET_OPERATIONS = Map.of( "ListMetrics", Set.of("Namespace", "MetricName", "Dimensions", "NextToken"), @@ -304,18 +306,26 @@ public class CloudWatchMetricsJsonHandler { if (namesNode.isArray()) { namesNode.forEach(n -> alarmNames.add(n.asText())); } - String prefix = request.has("AlarmNamePrefix") ? request.path("AlarmNamePrefix").asText() : null; + String prefix = request.path("AlarmNamePrefix").asText(null); List types = new ArrayList<>(); request.path("AlarmTypes").forEach(value -> types.add(value.asText())); - metricsService.validateAlarmTypes(types); - List alarms = types.isEmpty() || types.contains("MetricAlarm") - ? metricsService.describeAlarms(alarmNames, prefix, region) : List.of(); + String childrenOf = request.path("ChildrenOfAlarmName").asText(null); + String parentsOf = request.path("ParentsOfAlarmName").asText(null); + CloudWatchMetricsService.DescribedAlarms alarms = metricsService.describeAlarms( + new CloudWatchMetricsService.AlarmFilter(alarmNames, prefix, types, + request.path("StateValue").asText(null), request.path("ActionPrefix").asText(null), + childrenOf, parentsOf), region); + boolean related = childrenOf != null || parentsOf != null; ObjectNode response = objectMapper.createObjectNode(); ArrayNode arr = response.putArray("MetricAlarms"); - for (MetricAlarm a : alarms) { + for (MetricAlarm a : alarms.metricAlarms()) { ObjectNode node = arr.addObject(); + if (related) { + relatedAlarmFields(node, a, childrenOf != null); + continue; + } describeAlarmFields(node, a); if (!a.getMetrics().isEmpty()) { node.set("Metrics", objectMapper.valueToTree(a.getMetrics())); @@ -352,9 +362,11 @@ public class CloudWatchMetricsJsonHandler { } ArrayNode composites = response.putArray("CompositeAlarms"); - if (types.contains("CompositeAlarm")) { - for (CompositeAlarm alarm : metricsService.describeCompositeAlarms(alarmNames, prefix, region)) { - ObjectNode node = composites.addObject(); + for (CompositeAlarm alarm : alarms.compositeAlarms()) { + ObjectNode node = composites.addObject(); + if (related) { + relatedAlarmFields(node, alarm, childrenOf != null); + } else { describeAlarmFields(node, alarm); node.put("AlarmRule", alarm.getAlarmRule()); } @@ -363,6 +375,23 @@ public class CloudWatchMetricsJsonHandler { return Response.ok(response).build(); } + /** + * An alarm as DescribeAlarms lists it for ChildrenOfAlarmName, with only its name, ARN, state value and + * state update time, or for ParentsOfAlarmName, with only its name and ARN. + */ + private static void relatedAlarmFields(ObjectNode node, Alarm a, boolean withState) { + node.put("AlarmName", a.getAlarmName()); + if (a.getAlarmArn() != null) { + node.put("AlarmArn", a.getAlarmArn()); + } + if (withState) { + if (a.getStateValue() != null) { + node.put("StateValue", a.getStateValue()); + } + node.put("StateUpdatedTimestamp", a.getStateUpdatedTimestamp()); + } + } + private void describeAlarmFields(ObjectNode node, Alarm a) { node.put("AlarmName", a.getAlarmName()); if (a.getAlarmArn() != null) { diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsQueryHandler.java index e7cf176530..1f2eb693cf 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsQueryHandler.java @@ -278,20 +278,27 @@ public class CloudWatchMetricsQueryHandler { if (name == null) break; alarmNames.add(name); } - String prefix = params.getFirst("AlarmNamePrefix"); - - List types = alarmMembers(params, "AlarmTypes"); - metricsService.validateAlarmTypes(types); - List alarms = types.isEmpty() || types.contains("MetricAlarm") - ? metricsService.describeAlarms(alarmNames, prefix, region) : List.of(); + String childrenOf = params.getFirst("ChildrenOfAlarmName"); + String parentsOf = params.getFirst("ParentsOfAlarmName"); + CloudWatchMetricsService.DescribedAlarms alarms = metricsService.describeAlarms( + new CloudWatchMetricsService.AlarmFilter(alarmNames, params.getFirst("AlarmNamePrefix"), + alarmMembers(params, "AlarmTypes"), params.getFirst("StateValue"), + params.getFirst("ActionPrefix"), childrenOf, parentsOf), region); + boolean related = childrenOf != null || parentsOf != null; XmlBuilder xml = new XmlBuilder().start("MetricAlarms"); - for (MetricAlarm a : alarms) { - toAlarmXml(xml, a); + for (MetricAlarm a : alarms.metricAlarms()) { + if (related) { + relatedAlarmXml(xml, a, childrenOf != null); + } else { + toAlarmXml(xml, a); + } } xml.end("MetricAlarms").start("CompositeAlarms"); - if (types.contains("CompositeAlarm")) { - for (CompositeAlarm alarm : metricsService.describeCompositeAlarms(alarmNames, prefix, region)) { + for (CompositeAlarm alarm : alarms.compositeAlarms()) { + if (related) { + relatedAlarmXml(xml, alarm, childrenOf != null); + } else { xml.start("member"); describeAlarmFields(xml, alarm); xml.elem("AlarmRule", alarm.getAlarmRule()).end("member"); @@ -301,6 +308,19 @@ public class CloudWatchMetricsQueryHandler { return Response.ok(AwsQueryResponse.envelope("DescribeAlarms", null, xml.build())).build(); } + /** + * An alarm as DescribeAlarms lists it for ChildrenOfAlarmName, with only its name, ARN, state value and + * state update time, or for ParentsOfAlarmName, with only its name and ARN. + */ + private void relatedAlarmXml(XmlBuilder xml, Alarm a, boolean withState) { + xml.start("member").elem("AlarmName", a.getAlarmName()).elem("AlarmArn", a.getAlarmArn()); + if (withState) { + xml.elem("StateValue", a.getStateValue()) + .elem("StateUpdatedTimestamp", Instant.ofEpochSecond(a.getStateUpdatedTimestamp()).toString()); + } + xml.end("member"); + } + private Response handleDeleteAlarms(MultivaluedMap params, String region) { List alarmNames = new ArrayList<>(); for (int i = 1; ; i++) { diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsService.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsService.java index e64cbffb1d..75157a716a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsService.java @@ -60,6 +60,8 @@ public class CloudWatchMetricsService { private static final Logger LOG = Logger.getLogger(CloudWatchMetricsService.class); private static final List ALARM_TYPES = List.of("CompositeAlarm", "MetricAlarm", "LogAlarm"); + /** DescribeAlarms' StateValue enum, in the order AWS lists it when it refuses another value. */ + private static final List STATE_VALUES = List.of("INSUFFICIENT_DATA", "ALARM", "OK"); private static final List HISTORY_ALARM_TYPES = List.of("MetricAlarm", "CompositeAlarm"); private static final List HISTORY_ITEM_TYPES = List.of("AlarmContributorAction", "AlarmContributorStateUpdate", "Action", "StateUpdate", "ConfigurationUpdate"); @@ -508,11 +510,97 @@ public class CloudWatchMetricsService { .map(MetricAlarm.class::cast).toList(); } - public void validateAlarmTypes(List types) { - if (!ALARM_TYPES.containsAll(types)) { - throw SmithyValidationErrors.validationError( - SmithyValidationErrors.notAllInEnum(types, "alarmTypes", ALARM_TYPES)); + /** The DescribeAlarms members that choose the alarms it lists: a null string or an empty list when left out. */ + public record AlarmFilter(List alarmNames, String alarmNamePrefix, List alarmTypes, + String stateValue, String actionPrefix, String childrenOfAlarmName, + String parentsOfAlarmName) {} + + /** The metric and composite alarms a DescribeAlarms request lists. */ + public record DescribedAlarms(List metricAlarms, List compositeAlarms) {} + + /** + * The alarms a DescribeAlarms request lists: the kinds {@code AlarmTypes} names, metric alarms when it + * names none, narrowed by name, by {@code StateValue} and by {@code ActionPrefix}, which an alarm, OK or + * insufficient-data action may start with. {@code ChildrenOfAlarmName} lists instead the alarms a + * composite alarm's rule names, and {@code ParentsOfAlarmName} the composite alarms whose rules name the + * alarm; neither lists the alarm it names, and either one is refused with any other member except + * {@code MaxRecords} and {@code NextToken}. + */ + public DescribedAlarms describeAlarms(AlarmFilter filter, String region) { + validate(filter); + if (filter.childrenOfAlarmName() != null) { + return childrenOf(filter.childrenOfAlarmName(), region); } + if (filter.parentsOfAlarmName() != null) { + return parentsOf(filter.parentsOfAlarmName(), region); + } + List types = filter.alarmTypes().isEmpty() ? List.of("MetricAlarm") : filter.alarmTypes(); + String actionPrefix = filter.actionPrefix(); + return byKind(matchingAlarms(filter.alarmNames(), filter.alarmNamePrefix(), region).stream() + .filter(alarm -> types.contains(alarm.getAlarmType())) + .filter(alarm -> filter.stateValue() == null || filter.stateValue().equals(alarm.getStateValue())) + .filter(alarm -> actionPrefix == null || Stream.of(alarm.getAlarmActions(), alarm.getOkActions(), + alarm.getInsufficientDataActions()).flatMap(List::stream) + .anyMatch(action -> action.startsWith(actionPrefix))) + .toList()); + } + + /** + * Refuses an {@code AlarmTypes}, {@code ChildrenOfAlarmName}, {@code ParentsOfAlarmName}, {@code StateValue} + * or {@code ActionPrefix} outside its modeled shape, all reported together as Smithy does, and then + * ChildrenOfAlarmName or ParentsOfAlarmName given with another filter. + */ + private static void validate(AlarmFilter filter) { + List violations = Stream.of( + ALARM_TYPES.containsAll(filter.alarmTypes()) ? null + : SmithyValidationErrors.notAllInEnum(filter.alarmTypes(), "alarmTypes", ALARM_TYPES), + filter.childrenOfAlarmName() == null ? null : SmithyValidationErrors.lengthOutOfRange( + "childrenOfAlarmName", filter.childrenOfAlarmName(), 1, 255), + filter.parentsOfAlarmName() == null ? null : SmithyValidationErrors.lengthOutOfRange( + "parentsOfAlarmName", filter.parentsOfAlarmName(), 1, 255), + filter.stateValue() == null || STATE_VALUES.contains(filter.stateValue()) ? null + : SmithyValidationErrors.notInEnum(filter.stateValue(), "stateValue", STATE_VALUES), + filter.actionPrefix() == null ? null + : SmithyValidationErrors.lengthOutOfRange("actionPrefix", filter.actionPrefix(), 1, 1024)) + .filter(Objects::nonNull).toList(); + if (!violations.isEmpty()) { + throw SmithyValidationErrors.validationError(violations); + } + String related = filter.childrenOfAlarmName() != null ? "ChildrenOfAlarmName" + : filter.parentsOfAlarmName() != null ? "ParentsOfAlarmName" : null; + boolean combined = filter.childrenOfAlarmName() != null && filter.parentsOfAlarmName() != null + || !filter.alarmNames().isEmpty() || filter.alarmNamePrefix() != null + || !filter.alarmTypes().isEmpty() || filter.stateValue() != null || filter.actionPrefix() != null; + if (related != null && combined) { + throw new AwsException("ValidationError", "If you specify " + related + ", you cannot specify any other " + + "parameters in the request except for MaxRecords and NextToken.", 400); + } + } + + /** The alarms a composite alarm's rule names, by name or ARN; none for a metric alarm or a missing one. */ + private DescribedAlarms childrenOf(String name, String region) { + if (!(alarmStore.get(region + "::" + name).orElse(null) instanceof CompositeAlarm parent)) { + return new DescribedAlarms(List.of(), List.of()); + } + Set children = alarmReferences(parent, region); + return byKind(alarmStore.scan(k -> k.startsWith(region + "::")).stream() + .filter(alarm -> !alarm.getAlarmName().equals(name) && children.contains(alarm.getAlarmArn())) + .toList()); + } + + /** The composite alarms whose rules name the alarm, by name or ARN, whether or not it still exists. */ + private DescribedAlarms parentsOf(String name, String region) { + String arn = regionResolver.buildArn("cloudwatch", region, "alarm:" + name); + return byKind(alarmStore.scan(k -> k.startsWith(region + "::")).stream() + .filter(alarm -> alarm instanceof CompositeAlarm composite && !composite.getAlarmName().equals(name) + && alarmReferences(composite, region).contains(arn)) + .toList()); + } + + private static DescribedAlarms byKind(List alarms) { + return new DescribedAlarms( + alarms.stream().filter(MetricAlarm.class::isInstance).map(MetricAlarm.class::cast).toList(), + alarms.stream().filter(CompositeAlarm.class::isInstance).map(CompositeAlarm.class::cast).toList()); } public List describeCompositeAlarms(List names, String prefix, String region) { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchDescribeAlarmsFiltersHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchDescribeAlarmsFiltersHandlerTest.java new file mode 100644 index 0000000000..696b3f0f84 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchDescribeAlarmsFiltersHandlerTest.java @@ -0,0 +1,120 @@ +package io.github.hectorvent.floci.services.cloudwatch.metrics; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +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.metrics.model.Alarm; +import io.github.hectorvent.floci.services.cloudwatch.metrics.model.CompositeAlarm; +import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm; +import io.github.hectorvent.floci.services.cloudwatch.metricstreams.CloudWatchMetricStreamsService; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * ChildrenOfAlarmName and ParentsOfAlarmName over rules the API's own checks might refuse to store, so + * those rules are written to the alarm store directly. + */ +class CloudWatchDescribeAlarmsFiltersHandlerTest { + private static final String REGION = "us-east-1"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private final RegionResolver regionResolver = new RegionResolver(REGION, "000000000000"); + private final InMemoryStorage alarms = new InMemoryStorage<>(); + private final CloudWatchMetricsService service = new CloudWatchMetricsService(new InMemoryStorage<>(), alarms, + regionResolver); + private final CloudWatchMetricsJsonHandler handler = new CloudWatchMetricsJsonHandler(service, + new CloudWatchDashboardsService(new InMemoryStorage<>(), regionResolver), + new CloudWatchMetricStreamsService(new InMemoryStorage<>(), regionResolver), MAPPER); + + @Test + void anAlarmIsNeverListedAsItsOwnChildOrParent() { + putMetric("source", REGION); + putMetric("unrelated", REGION); + storeComposite("self", "ALARM(self) OR ALARM(\"" + arn("source") + "\")"); + storeComposite("watcher", "ALARM(self)"); + + assertEquals(List.of("source"), names(describe("ChildrenOfAlarmName", "self", REGION), "MetricAlarms")); + assertEquals(List.of(), names(describe("ChildrenOfAlarmName", "self", REGION), "CompositeAlarms")); + assertEquals(List.of("watcher"), names(describe("ParentsOfAlarmName", "self", REGION), "CompositeAlarms")); + } + + @Test + void referencesToMissingAlarmsAreNotListedAsChildrenButStillHaveParents() { + putMetric("present", REGION); + putMetric("unrelated", REGION); + storeComposite("stale", "ALARM(present) OR ALARM(\"" + arn("gone") + "\")"); + + assertEquals(List.of("present"), names(describe("ChildrenOfAlarmName", "stale", REGION), "MetricAlarms")); + assertEquals(List.of("stale"), names(describe("ParentsOfAlarmName", "gone", REGION), "CompositeAlarms")); + assertEquals(List.of("stale"), names(describe("ParentsOfAlarmName", "present", REGION), "CompositeAlarms")); + } + + @Test + void relativesAreLookedUpInTheRequestRegionOnly() { + putMetric("shared", REGION); + putMetric("shared", "us-west-2"); + putMetric("unrelated", REGION); + storeComposite("aggregate", "ALARM(shared)"); + + JsonNode children = describe("ChildrenOfAlarmName", "aggregate", REGION); + assertEquals(1, children.path("MetricAlarms").size()); + assertEquals(arn("shared"), children.path("MetricAlarms").path(0).path("AlarmArn").asText()); + assertEquals(List.of(), names(describe("ParentsOfAlarmName", "shared", "us-west-2"), "CompositeAlarms")); + } + + @Test + void jsonNullMembersAreLeftOut() { + putMetric("source", REGION); + storeComposite("aggregate", "ALARM(source)"); + + ObjectNode children = MAPPER.createObjectNode().put("ChildrenOfAlarmName", "aggregate"); + children.putNull("AlarmNamePrefix"); + children.putNull("StateValue"); + assertEquals(List.of("source"), names(describe(children, REGION), "MetricAlarms")); + ObjectNode unfiltered = MAPPER.createObjectNode(); + unfiltered.putNull("AlarmNamePrefix"); + unfiltered.putNull("ActionPrefix"); + unfiltered.putNull("ParentsOfAlarmName"); + assertEquals(List.of("source"), names(describe(unfiltered, REGION), "MetricAlarms")); + } + + private String arn(String name) { + return regionResolver.buildArn("cloudwatch", REGION, "alarm:" + name); + } + + private void putMetric(String name, String region) { + MetricAlarm alarm = new MetricAlarm(); + alarm.setAlarmName(name); + service.putMetricAlarm(alarm, region); + } + + private void storeComposite(String name, String rule) { + CompositeAlarm alarm = new CompositeAlarm(); + alarm.setAlarmName(name); + alarm.setAlarmArn(arn(name)); + alarm.setAlarmRule(rule); + alarm.setRegion(REGION); + alarms.put(REGION + "::" + name, alarm); + } + + private JsonNode describe(String member, String value, String region) { + return describe(MAPPER.createObjectNode().put(member, value), region); + } + + private JsonNode describe(ObjectNode request, String region) { + return MAPPER.valueToTree(handler.handle("DescribeAlarms", request, region).getEntity()); + } + + private static List names(JsonNode response, String kind) { + List names = new ArrayList<>(); + response.path(kind).forEach(alarm -> names.add(alarm.path("AlarmName").asText())); + return names.stream().sorted().toList(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchDescribeAlarmsFiltersIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchDescribeAlarmsFiltersIntegrationTest.java new file mode 100644 index 0000000000..4997369961 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchDescribeAlarmsFiltersIntegrationTest.java @@ -0,0 +1,294 @@ +package io.github.hectorvent.floci.services.cloudwatch.metrics; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.testing.PartitionCleanup; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.path.xml.element.Node; +import io.restassured.response.Response; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.net.URI; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** DescribeAlarms' StateValue, ActionPrefix, ChildrenOfAlarmName and ParentsOfAlarmName over Query and JSON. */ +@QuarkusTest +class CloudWatchDescribeAlarmsFiltersIntegrationTest { + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String SCOPE = + "AWS4-HMAC-SHA256 Credential=test/20261027/us-east-1/monitoring/aws4_request"; + private static final List BOTH_KINDS = List.of("MetricAlarm", "CompositeAlarm"); + + @TestHTTPResource + URI baseUri; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void stateValueAndActionPrefixNarrowMetricAndCompositeAlarms(boolean json) throws Exception { + String prefix = unique("filtered"); + String topic = "arn:aws:sns:us-east-1:000000000000:" + prefix; + String alarm = prefix + "-alarm"; + String ok = prefix + "-ok"; + String unknown = prefix + "-unknown"; + String compositeAlarm = prefix + "-composite-alarm"; + String compositeOk = prefix + "-composite-ok"; + putMetricAlarm(json, alarm, Map.of("AlarmActions", List.of(topic + "-page"))); + putMetricAlarm(json, ok, Map.of("OKActions", List.of(topic + "-info"))); + putMetricAlarm(json, unknown, Map.of("InsufficientDataActions", List.of(topic + "-info"))); + setState(json, alarm, "ALARM"); + setState(json, ok, "OK"); + putCompositeAlarm(json, compositeAlarm, "TRUE", Map.of("AlarmActions", List.of(topic + "-page"))); + putCompositeAlarm(json, compositeOk, "FALSE", Map.of("OKActions", List.of(topic + "-info"))); + + assertEquals(listed(List.of(alarm), List.of(compositeAlarm)), names(json, + Map.of("AlarmNamePrefix", prefix, "StateValue", "ALARM", "AlarmTypes", BOTH_KINDS))); + assertEquals(listed(List.of(ok), List.of(compositeOk)), names(json, + Map.of("AlarmNamePrefix", prefix, "StateValue", "OK", "AlarmTypes", BOTH_KINDS))); + assertEquals(listed(List.of(unknown), List.of()), names(json, + Map.of("AlarmNamePrefix", prefix, "StateValue", "INSUFFICIENT_DATA", "AlarmTypes", BOTH_KINDS))); + assertEquals(listed(List.of(ok), List.of()), names(json, + Map.of("AlarmNamePrefix", prefix, "StateValue", "OK"))); + + assertEquals(listed(List.of(alarm), List.of(compositeAlarm)), names(json, + Map.of("ActionPrefix", topic + "-page", "AlarmTypes", BOTH_KINDS))); + assertEquals(listed(List.of(ok, unknown), List.of(compositeOk)), names(json, + Map.of("ActionPrefix", topic + "-info", "AlarmTypes", BOTH_KINDS))); + assertEquals(listed(List.of(alarm, ok, unknown), List.of()), names(json, Map.of("ActionPrefix", topic))); + assertEquals(listed(List.of(unknown), List.of()), names(json, + Map.of("ActionPrefix", topic, "StateValue", "INSUFFICIENT_DATA", "AlarmTypes", BOTH_KINDS))); + assertEquals(listed(List.of(ok), List.of()), names(json, + Map.of("ActionPrefix", topic, "AlarmNames", List.of(ok, compositeOk)))); + assertEquals(listed(List.of(), List.of()), names(json, + Map.of("ActionPrefix", topic + "-page", "StateValue", "OK", "AlarmTypes", BOTH_KINDS))); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void childrenAndParentsListTheRelatedAlarmsWithAwsMembers(boolean json) throws Exception { + String prefix = unique("related"); + String cpu = prefix + "-cpu"; + String disk = prefix + "-disk"; + String host = prefix + "-host"; + String fleet = prefix + "-fleet"; + putMetricAlarm(json, cpu, Map.of()); + putMetricAlarm(json, disk, Map.of()); + setState(json, cpu, "ALARM"); + String diskArn = arnOf(json, disk, "MetricAlarm"); + putCompositeAlarm(json, host, "ALARM(" + cpu + ") OR ALARM(\"" + diskArn + "\")", Map.of()); + putCompositeAlarm(json, fleet, "ALARM(\"" + host + "\") AND NOT OK(" + cpu + ")", Map.of()); + + Response hostChildren = describe(json, Map.of("ChildrenOfAlarmName", host)); + assertEquals(listed(List.of(cpu, disk), List.of()), names(json, hostChildren)); + Map cpuChild = members(json, hostChildren, "MetricAlarms", cpu); + assertEquals(List.of("AlarmArn", "AlarmName", "StateUpdatedTimestamp", "StateValue"), + List.copyOf(cpuChild.keySet())); + assertEquals(arnOf(json, cpu, "MetricAlarm"), cpuChild.get("AlarmArn")); + assertEquals("ALARM", cpuChild.get("StateValue")); + assertEquals("INSUFFICIENT_DATA", members(json, hostChildren, "MetricAlarms", disk).get("StateValue")); + + Response fleetChildren = describe(json, Map.of("ChildrenOfAlarmName", fleet, "MaxRecords", 10)); + assertEquals(listed(List.of(cpu), List.of(host)), names(json, fleetChildren)); + Map hostChild = members(json, fleetChildren, "CompositeAlarms", host); + assertEquals(List.of("AlarmArn", "AlarmName", "StateUpdatedTimestamp", "StateValue"), + List.copyOf(hostChild.keySet())); + assertEquals("ALARM", hostChild.get("StateValue")); + + Response cpuParents = describe(json, Map.of("ParentsOfAlarmName", cpu)); + assertEquals(listed(List.of(), List.of(fleet, host)), names(json, cpuParents)); + Map hostParent = members(json, cpuParents, "CompositeAlarms", host); + assertEquals(List.of("AlarmArn", "AlarmName"), List.copyOf(hostParent.keySet())); + assertEquals(arnOf(json, host, "CompositeAlarm"), hostParent.get("AlarmArn")); + assertEquals(listed(List.of(), List.of(host)), names(json, Map.of("ParentsOfAlarmName", disk))); + assertEquals(listed(List.of(), List.of(fleet)), names(json, + Map.of("ParentsOfAlarmName", host, "MaxRecords", 10))); + + assertEquals(listed(List.of(), List.of()), names(json, Map.of("ParentsOfAlarmName", fleet))); + assertEquals(listed(List.of(), List.of()), names(json, Map.of("ChildrenOfAlarmName", cpu))); + assertEquals(listed(List.of(), List.of()), names(json, Map.of("ChildrenOfAlarmName", prefix + "-missing"))); + assertEquals(listed(List.of(), List.of()), names(json, Map.of("ParentsOfAlarmName", prefix + "-missing"))); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void childrenAndParentsRefuseEveryOtherFilter(boolean json) throws Exception { + String name = unique("combined"); + List> others = List.of(Map.entry("AlarmNames", List.of(name)), + Map.entry("AlarmNamePrefix", name), Map.entry("AlarmTypes", List.of("CompositeAlarm")), + Map.entry("StateValue", "OK"), Map.entry("ActionPrefix", "arn:")); + for (String related : List.of("ChildrenOfAlarmName", "ParentsOfAlarmName")) { + for (Map.Entry other : others) { + assertRefused(json, related, Map.of(related, name, other.getKey(), other.getValue())); + } + } + assertRefused(json, "ChildrenOfAlarmName", Map.of("ChildrenOfAlarmName", name, "ParentsOfAlarmName", name)); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void filterValuesOutsideTheModelUseSmithyValidation(boolean json) throws Exception { + assertValidationError(json, Map.of("StateValue", "BOGUS"), "1 validation error detected: Value 'BOGUS' at " + + "'stateValue' failed to satisfy constraint: Member must satisfy enum value set: " + + "[INSUFFICIENT_DATA, ALARM, OK]"); + assertValidationError(json, Map.of("ActionPrefix", ""), "1 validation error detected: Value '' at " + + "'actionPrefix' failed to satisfy constraint: Member must have length greater than or equal to 1"); + String tooLong = "x".repeat(256); + assertValidationError(json, Map.of("ChildrenOfAlarmName", tooLong), "1 validation error detected: Value '" + + tooLong + "' at 'childrenOfAlarmName' failed to satisfy constraint: " + + "Member must have length less than or equal to 255"); + assertValidationError(json, Map.of("ParentsOfAlarmName", ""), "1 validation error detected: Value '' at " + + "'parentsOfAlarmName' failed to satisfy constraint: " + + "Member must have length greater than or equal to 1"); + assertValidationError(json, Map.of("AlarmTypes", List.of("Unknown"), "StateValue", "alarm"), + "2 validation errors detected: Value '[Unknown]' at 'alarmTypes' failed to satisfy constraint: " + + "Member must satisfy constraint: [Member must satisfy enum value set: " + + "[CompositeAlarm, MetricAlarm, LogAlarm]]; Value 'alarm' at 'stateValue' failed to satisfy " + + "constraint: Member must satisfy enum value set: [INSUFFICIENT_DATA, ALARM, OK]"); + } + + private void assertRefused(boolean json, String named, Map request) throws Exception { + assertValidationError(json, request, "If you specify " + named + ", you cannot specify any other parameters " + + "in the request except for MaxRecords and NextToken."); + } + + private void assertValidationError(boolean json, Map request, String message) throws Exception { + Response error = describe(json, request); + assertEquals(400, error.statusCode(), request + ": " + error.asString()); + if (json) { + assertEquals("ValidationError;Sender", error.header("x-amzn-query-error"), request.toString()); + assertEquals(message, error.jsonPath().getString("message"), request.toString()); + } else { + assertEquals("ValidationError", error.xmlPath().getString("ErrorResponse.Error.Code"), request.toString()); + assertEquals(message, error.xmlPath().getString("ErrorResponse.Error.Message"), request.toString()); + } + } + + /** The ARN DescribeAlarms reports for an alarm of {@code kind}, so no partition is spelled out here. */ + private String arnOf(boolean json, String name, String kind) throws Exception { + Response response = describe(json, Map.of("AlarmNames", List.of(name), "AlarmTypes", List.of(kind))); + return members(json, response, kind + "s", name).get("AlarmArn"); + } + + private static Map> listed(List metricAlarms, List compositeAlarms) { + return Map.of("MetricAlarms", metricAlarms.stream().sorted().toList(), + "CompositeAlarms", compositeAlarms.stream().sorted().toList()); + } + + private Map> names(boolean json, Map request) throws Exception { + return names(json, describe(json, request)); + } + + private static Map> names(boolean json, Response response) { + assertEquals(200, response.statusCode(), response.asString()); + Map> names = new LinkedHashMap<>(); + for (String kind : List.of("MetricAlarms", "CompositeAlarms")) { + List listedNames = json ? response.jsonPath().getList(kind + ".AlarmName", String.class) + : response.xmlPath().getList("DescribeAlarmsResponse.DescribeAlarmsResult." + kind + + ".member.AlarmName", String.class); + names.put(kind, listedNames.stream().sorted().toList()); + } + return names; + } + + /** The members one listed alarm carries, by name, each with its value as text. */ + private static Map members(boolean json, Response response, String kind, String alarmName) { + Map members = new TreeMap<>(); + if (json) { + List> alarms = response.jsonPath().getList(kind); + Map alarm = alarms.stream().filter(a -> alarmName.equals(a.get("AlarmName"))) + .findFirst().orElseThrow(); + alarm.forEach((key, value) -> members.put(key, String.valueOf(value))); + } else { + List alarms = response.xmlPath().getList( + "DescribeAlarmsResponse.DescribeAlarmsResult." + kind + ".member", Node.class); + Node alarm = alarms.stream().filter(a -> alarmName.equals(a.getNode("AlarmName").value())) + .findFirst().orElseThrow(); + alarm.children().list().forEach(child -> members.put(child.name(), child.value())); + } + assertTrue(members.containsKey("AlarmName"), members.toString()); + return members; + } + + private void putMetricAlarm(boolean json, String name, Map actions) throws Exception { + Map request = new LinkedHashMap<>(Map.of("AlarmName", name, "Namespace", "Filters", + "MetricName", name, "Statistic", "Average", "Period", 60, "EvaluationPeriods", 1, + "Threshold", 1, "ComparisonOperator", "GreaterThanThreshold", "TreatMissingData", "ignore")); + request.put("ActionsEnabled", false); + request.putAll(actions); + put(json, "PutMetricAlarm", request); + } + + private void putCompositeAlarm(boolean json, String name, String rule, Map actions) + throws Exception { + Map request = new LinkedHashMap<>(Map.of("AlarmName", name, "AlarmRule", rule, + "ActionsEnabled", false)); + request.putAll(actions); + put(json, "PutCompositeAlarm", request); + } + + private void put(boolean json, String operation, Map request) throws Exception { + call(json, operation, request).then().statusCode(200); + String name = request.get("AlarmName").toString(); + cleanup.register(() -> { + try { + call(true, "DeleteAlarms", Map.of("AlarmNames", List.of(name))).then().statusCode(200); + } catch (JsonProcessingException e) { + throw new IllegalStateException(e); + } + }); + } + + private void setState(boolean json, String name, String state) throws Exception { + call(json, "SetAlarmState", Map.of("AlarmName", name, "StateValue", state, "StateReason", "test")) + .then().statusCode(200); + } + + private Response describe(boolean json, Map request) throws Exception { + return call(json, "DescribeAlarms", request); + } + + private static String unique(String prefix) { + return "describe-" + prefix + "-" + Long.toString(System.nanoTime(), 36); + } + + private Response call(boolean json, String operation, Map body) throws JsonProcessingException { + if (json) { + return given().port(baseUri.getPort()).contentType("application/x-amz-json-1.0") + .header("Authorization", SCOPE) + .header("X-Amz-Target", "GraniteServiceVersion20100801." + operation) + .body(MAPPER.writeValueAsString(body)).post("/"); + } + Map form = new LinkedHashMap<>(); + form.put("Action", operation); + body.forEach((key, value) -> { + if (value instanceof List values) { + for (int index = 0; index < values.size(); index++) { + form.put(key + ".member." + (index + 1), values.get(index)); + } + } else { + form.put(key, value); + } + }); + return given().port(baseUri.getPort()).contentType("application/x-www-form-urlencoded") + .header("Authorization", SCOPE).formParams(form).post("/"); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsQueryHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsQueryHandlerTest.java index 103ff3d3db..88e1532fd5 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsQueryHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CloudWatchMetricsQueryHandlerTest.java @@ -244,7 +244,8 @@ class CloudWatchMetricsQueryHandlerTest { @Test void describeAlarmsReturnsEmptyCompositeAndLogAlarmCollections() { - when(metricsService.describeAlarms(any(), any(), eq(REGION))).thenReturn(List.of()); + when(metricsService.describeAlarms(any(CloudWatchMetricsService.AlarmFilter.class), eq(REGION))) + .thenReturn(new CloudWatchMetricsService.DescribedAlarms(List.of(), List.of())); String xml = (String) handler.handle("DescribeAlarms", new MultivaluedHashMap<>(), REGION).getEntity();