mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(cloudwatch): filter DescribeAlarms by state, action, children and parents (#6862)
DescribeAlarms read only AlarmNames, AlarmNamePrefix and AlarmTypes. It ignored StateValue, ActionPrefix, ChildrenOfAlarmName and ParentsOfAlarmName, so each of them answered every alarm of the requested types, and combining them was never refused. StateValue and ActionPrefix now narrow metric and composite alarms alike. ActionPrefix matches an alarm, OK or insufficient-data action, since the API reference calls it a prefix for any action. ChildrenOfAlarmName lists the alarms a composite alarm's rule names, by name or ARN, and ParentsOfAlarmName the composite alarms whose rules name an alarm. Neither lists the alarm it names, and both return only the members the API reference lists: name, ARN, StateValue and StateUpdatedTimestamp for children, name and ARN for parents. As the API reference says, either one combined with any member except MaxRecords and NextToken is refused with ValidationError. A StateValue outside the enum and an empty or over-long ActionPrefix or alarm name are refused with Smithy's validation messages, reported together with an invalid AlarmTypes. Both handlers pass the request's filters to the service as one AlarmFilter, so Query, JSON and CBOR answer alike, and a JSON null member counts as left out, AlarmNamePrefix included, which read as the prefix "null" before. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
This commit is contained in:
1 parent
55c33d7ad3
commit
7b9f747fff
8 files changed
+788
-25
No files matched your search
+39
-10
@@ -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<String, Set<String>> 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<String> types = new ArrayList<>();
|
||||
request.path("AlarmTypes").forEach(value -> types.add(value.asText()));
|
||||
metricsService.validateAlarmTypes(types);
|
||||
List<MetricAlarm> 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) {
|
||||
|
||||
+30
-10
@@ -278,20 +278,27 @@ public class CloudWatchMetricsQueryHandler {
|
||||
if (name == null) break;
|
||||
alarmNames.add(name);
|
||||
}
|
||||
String prefix = params.getFirst("AlarmNamePrefix");
|
||||
|
||||
List<String> types = alarmMembers(params, "AlarmTypes");
|
||||
metricsService.validateAlarmTypes(types);
|
||||
List<MetricAlarm> 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<String, String> params, String region) {
|
||||
List<String> alarmNames = new ArrayList<>();
|
||||
for (int i = 1; ; i++) {
|
||||
|
||||
+92
-4
@@ -60,6 +60,8 @@ public class CloudWatchMetricsService {
|
||||
private static final Logger LOG = Logger.getLogger(CloudWatchMetricsService.class);
|
||||
|
||||
private static final List<String> 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<String> STATE_VALUES = List.of("INSUFFICIENT_DATA", "ALARM", "OK");
|
||||
private static final List<String> HISTORY_ALARM_TYPES = List.of("MetricAlarm", "CompositeAlarm");
|
||||
private static final List<String> 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<String> 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<String> alarmNames, String alarmNamePrefix, List<String> alarmTypes,
|
||||
String stateValue, String actionPrefix, String childrenOfAlarmName,
|
||||
String parentsOfAlarmName) {}
|
||||
|
||||
/** The metric and composite alarms a DescribeAlarms request lists. */
|
||||
public record DescribedAlarms(List<MetricAlarm> metricAlarms, List<CompositeAlarm> 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<String> 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<String> 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<String> 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<Alarm> 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<CompositeAlarm> describeCompositeAlarms(List<String> names, String prefix, String region) {
|
||||
|
||||
Reference in new issue
Block a user