diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchCompositeAlarmTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchCompositeAlarmTest.java new file mode 100644 index 0000000000..7f5a1eb811 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchCompositeAlarmTest.java @@ -0,0 +1,141 @@ +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.StateValue; +import software.amazon.awssdk.services.cloudwatch.model.Statistic; + +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@DisplayName("CloudWatch - Composite alarm evaluation") +class CloudWatchCompositeAlarmTest { + + private CloudWatchClient cloudWatch; + private final List composites = new ArrayList<>(); + private final List metricAlarms = new ArrayList<>(); + + @BeforeEach + void setup() { + cloudWatch = TestFixtures.cloudWatchClient(); + } + + @AfterEach + void cleanup() { + try { + // Parents first: CloudWatch refuses to delete an alarm a composite alarm still references. + for (int index = composites.size() - 1; index >= 0; index--) { + String name = composites.get(index); + cloudWatch.deleteAlarms(request -> request.alarmNames(name)); + } + if (!metricAlarms.isEmpty()) { + cloudWatch.deleteAlarms(request -> request.alarmNames(metricAlarms)); + } + } finally { + cloudWatch.close(); + } + } + + @Test + @DisplayName("Reasons and triggering alarms follow creation, child transitions and updates") + void stateReasonsFollowCreationTransitionsAndUpdates() { + String a = metricAlarm("sdk-composite-a"); + String b = metricAlarm("sdk-composite-b"); + String both = composite("sdk-composite-both", "ALARM(\"" + a + "\") AND ALARM(\"" + b + "\")"); + + CompositeAlarm created = describe(both); + assertThat(created.stateValue()).isEqualTo(StateValue.OK); + assertThat(created.stateReason()).isEqualTo(created.alarmArn() + " was created and its alarm rule evaluates to OK"); + assertThat(created.stateReasonData()).startsWith("{\"triggeringAlarms\":[{\"arn\":\"") + .contains(arn(a), arn(b)); + + cloudWatch.setAlarmState(request -> request.alarmName(a).stateValue(StateValue.ALARM).stateReason("test")); + assertThat(describe(both).stateReason()).isEqualTo(created.stateReason()); + cloudWatch.setAlarmState(request -> request.alarmName(b).stateValue(StateValue.ALARM).stateReason("test")); + CompositeAlarm transitioned = describe(both); + assertThat(transitioned.stateValue()).isEqualTo(StateValue.ALARM); + assertThat(transitioned.stateReason()).matches("\\Q" + arn(b) + " transitioned to ALARM at \\E" + + "[A-Z][a-z]+day \\d{2} [A-Z][a-z]+, \\d{4} \\d{2}:\\d{2}:\\d{2} UTC"); + assertThat(transitioned.stateReasonData()).startsWith("{\"triggeringAlarms\":[{\"arn\":\"" + arn(b) + "\"") + .contains(arn(a)); + + cloudWatch.putCompositeAlarm(request -> request.alarmName(both).alarmRule("ALARM(" + a + ") AND OK(" + b + ")") + .actionsEnabled(false)); + CompositeAlarm updated = describe(both); + assertThat(updated.stateValue()).isEqualTo(StateValue.OK); + assertThat(updated.stateReason()).isEqualTo(updated.alarmArn() + " was updated and its new alarm rule evaluates to OK"); + assertThat(updated.stateReasonData()).matches("\\Q{\"triggeringAlarms\":[{\"arn\":\"" + arn(b) + + "\",\"state\":{\"value\":\"ALARM\",\"timestamp\":\"\\E" + + "\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}\\+0000\\Q\"}}]}\\E"); + } + + @Test + @DisplayName("Unknown children and deleting referenced alarms fail with CloudWatch's messages") + void refusalsMatchCloudWatch() { + String child = metricAlarm("sdk-composite-child"); + String parent = composite("sdk-composite-parent", "OK(" + child + ")"); + String other = composite("sdk-composite-other", "TRUE"); + + assertValidationError(() -> cloudWatch.deleteAlarms(request -> request.alarmNames(child)), + "Cannot delete " + child + " as there are composite alarm(s) depending on it."); + assertValidationError(() -> cloudWatch.deleteAlarms(request -> request.alarmNames(child, parent)), + "Cannot delete " + child + " as there are composite alarm(s) depending on it."); + assertValidationError(() -> cloudWatch.deleteAlarms(request -> request.alarmNames(parent, other)), + "Cannot delete [2] Composite Alarms as only one composite alarm delete is allowed in single request"); + String missing = TestFixtures.uniqueName("sdk-composite-missing"); + assertValidationError(() -> cloudWatch.putCompositeAlarm(request -> request + .alarmName(TestFixtures.uniqueName("sdk-composite-orphan")).alarmRule("ALARM(" + missing + ")")), + "Could not save the composite alarm as alarms [" + arn(missing) + "] in the alarm rule do not exist"); + assertThat(describe(parent).alarmRule()).isEqualTo("OK(" + child + ")"); + assertThat(cloudWatch.describeAlarms(request -> request.alarmNames(child)).metricAlarms()).hasSize(1); + } + + private void assertValidationError(Runnable call, String message) { + assertThatThrownBy(call::run).isInstanceOfSatisfying(CloudWatchException.class, error -> { + assertThat(error.statusCode()).isEqualTo(400); + assertThat(error.awsErrorDetails().errorCode()).isEqualTo("ValidationError"); + assertThat(error.awsErrorDetails().errorMessage()).isEqualTo(message); + }); + } + + /** TreatMissingData=ignore keeps the emulator's alarm evaluator from resetting the states these tests set. */ + private String metricAlarm(String prefix) { + String name = TestFixtures.uniqueName(prefix); + cloudWatch.putMetricAlarm(request -> request.alarmName(name).namespace("Compat/Composite") + .metricName("Errors").statistic(Statistic.SUM).period(3600).evaluationPeriods(1).threshold(1.0) + .comparisonOperator(ComparisonOperator.GREATER_THAN_THRESHOLD).treatMissingData("ignore") + .actionsEnabled(false)); + metricAlarms.add(name); + return name; + } + + private String composite(String prefix, String rule) { + String name = TestFixtures.uniqueName(prefix); + cloudWatch.putCompositeAlarm(request -> request.alarmName(name).alarmRule(rule).actionsEnabled(false)); + composites.add(name); + return name; + } + + private CompositeAlarm describe(String name) { + List found = cloudWatch.describeAlarms(request -> request.alarmNames(name) + .alarmTypes(AlarmType.COMPOSITE_ALARM)).compositeAlarms(); + assertThat(found).hasSize(1); + return found.get(0); + } + + private String arn(String name) { + String any = cloudWatch.describeAlarms(request -> request.alarmNames(metricAlarms.get(0))) + .metricAlarms().get(0).alarmArn(); + return any.substring(0, any.lastIndexOf(':') + 1) + name; + } +} diff --git a/docs/services/cloudwatch.md b/docs/services/cloudwatch.md index dd81dfc3bc..14c25f41bf 100644 --- a/docs/services/cloudwatch.md +++ b/docs/services/cloudwatch.md @@ -445,6 +445,36 @@ Alarms stored before Floci recorded it report their last state update. `StateReason` and 4000 characters for `StateReasonData` before changing alarm state. Length checks count Unicode code points and preserve empty and whitespace values. +### Composite alarm evaluation + +A composite alarm is evaluated when it is created, when `PutCompositeAlarm` updates it, and when +one of its children changes state, up through nested composite alarms. `PutMetricAlarm` on an +existing child, or a `SetAlarmState` to the state a child already has, is not a change of state, +so a composite alarm set with `SetAlarmState` keeps that state until a child really changes. An +update that leaves the state unchanged also keeps the state reason, reason data and timestamps. +A composite alarm on a cycle of rules is not evaluated, not even by the update that closes the +cycle, where CloudWatch evaluates that alarm and the ones after it. One above a cycle is still +evaluated when one of its children changes state. A change of state records the `StateReason` +CloudWatch writes: + +- ` was created and its alarm rule evaluates to OK` when the alarm is created, +- ` was updated and its new alarm rule evaluates to ALARM` when an update changes it, +- ` transitioned to ALARM at Monday 14 September, 2026 06:29:58 UTC` when a child does. + +`StateReasonData` lists under `triggeringAlarms` the children whose state agrees with the new one, +the most recently changed first, each with its state and when it took it. After a child's change +it lists only the children that changed state since the composite alarm last did. The list stops +before the 4000 characters `StateReasonData` can hold, counted in Unicode code points like the +length checks. Floci keeps state times to the second, so the timestamps end in `.000`. + +Every alarm a rule names must exist, or `PutCompositeAlarm` fails with `ValidationError` and +`Could not save the composite alarm as alarms [] in the alarm rule do not exist`. +`DeleteAlarms` deletes nothing when it names more than one composite alarm +(`Cannot delete [2] Composite Alarms as only one composite alarm delete is allowed in single request`) +or an alarm that a composite alarm's rule names, even when it deletes that composite alarm too +(`Cannot delete as there are composite alarm(s) depending on it.`), so delete composite +alarms before their children. Names that match no alarm are ignored. + ### SNS alarm actions State transitions publish to same-account standard SNS topics in `AlarmActions`, `OKActions`, or diff --git a/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingService.java b/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingService.java index 9305d33efc..3689913131 100644 --- a/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingService.java +++ b/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingService.java @@ -408,16 +408,18 @@ public class ApplicationAutoScalingService { return alarms; } + /** + * Deletes the policy's alarms one at a time: CloudWatch refuses a whole DeleteAlarms request + * that names an alarm a composite alarm still names, and the others should go regardless. + */ private void deleteAlarms(ScalingPolicy policy, String region) { - List names = policy.getAlarms().stream().map(Alarm::getAlarmName).toList(); - if (names.isEmpty()) { - return; - } - try { - cloudWatchMetricsService.deleteAlarms(names, region); - } catch (RuntimeException e) { - // Alarm cleanup is best-effort: a user may have deleted them out of band. - LOG.debugv(e, "Could not delete target-tracking alarms {0} in {1}", names, region); + for (Alarm alarm : policy.getAlarms()) { + try { + cloudWatchMetricsService.deleteAlarms(List.of(alarm.getAlarmName()), region); + } catch (RuntimeException e) { + // Alarm cleanup is best-effort: a composite alarm may still name this one. + LOG.debugv(e, "Could not delete target-tracking alarm {0} in {1}", alarm.getAlarmName(), region); + } } } 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 5a55cf25c5..e64cbffb1d 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 @@ -6,6 +6,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.NullNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.TextNode; @@ -48,6 +49,7 @@ import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.UUID; +import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -66,6 +68,11 @@ public class CloudWatchMetricsService { /** The form of {@code java.util.Date#toString} in UTC, which AWS's date range error prints. */ private static final DateTimeFormatter HISTORY_DATE_FORMAT = DateTimeFormatter .ofPattern("EEE MMM dd HH:mm:ss 'UTC' yyyy", Locale.ROOT).withZone(ZoneOffset.UTC); + /** A child's transition time in a composite alarm's StateReason: "Monday 14 September, 2026 06:29:58 UTC". */ + private static final DateTimeFormatter REASON_TIME = DateTimeFormatter + .ofPattern("EEEE dd MMMM, yyyy HH:mm:ss 'UTC'", Locale.ENGLISH).withZone(ZoneOffset.UTC); + /** The most StateReasonData can hold, in Unicode code points as SetAlarmState's length check counts them. */ + private static final int MAX_STATE_REASON_DATA = 4000; private static final ObjectMapper MAPPER = new ObjectMapper() .setSerializationInclusion(JsonInclude.Include.NON_NULL) .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); @@ -373,9 +380,17 @@ public class CloudWatchMetricsService { }; } + /** + * Creates or updates a metric alarm. An update keeps the alarm's state, so composite alarms + * above it are not evaluated: one set with SetAlarmState returns to its actual state only once + * a child changes state. + */ public synchronized void putMetricAlarm(MetricAlarm alarm, String region) { + boolean created = alarmStore.get(region + "::" + alarm.getAlarmName()).isEmpty(); putAlarm(alarm, region); - evaluateComposites(region, Set.of(alarm.getAlarmName()), null); + if (created) { + evaluateComposites(region, Set.of(alarm.getAlarmName())); + } } public void putCompositeAlarm(CompositeAlarm alarm, String region) { @@ -399,18 +414,23 @@ public class CloudWatchMetricsService { throw new AwsException("LimitExceeded", "An alarm can be referenced by at most 150 composite alarms", 400); } } + Map alarms = alarmIndex(region); + List missing = references.stream().filter(reference -> !alarms.containsKey(reference)).toList(); + if (!missing.isEmpty()) { + throw new AwsException("ValidationError", "Could not save the composite alarm as alarms " + missing + + " in the alarm rule do not exist", 400); + } boolean created = alarmStore.get(region + "::" + alarm.getAlarmName()).isEmpty(); putAlarm(alarm, region); - if (created) { - evaluateComposites(region, Set.of(), alarm.getAlarmName()); - } + evaluateComposites(region, Set.of(), alarm.getAlarmName(), created); } + /** The ARN of each alarm the rule names, in the order it first names them. */ private Set alarmReferences(CompositeAlarm alarm, String region) { return CompositeAlarmRule.parse(alarm.getAlarmRule()).references().stream() .map(reference -> AwsArnUtils.isArn(reference) ? reference : regionResolver.buildArn("cloudwatch", region, "alarm:" + reference)) - .collect(Collectors.toSet()); + .collect(Collectors.toCollection(LinkedHashSet::new)); } private void putAlarm(Alarm alarm, String region) { @@ -448,7 +468,7 @@ public class CloudWatchMetricsService { ObjectNode data = MAPPER.createObjectNode().put("version", "1.0"); if (before == null) { data.put("type", "Create").set("createdAlarm", after); - recordHistory(alarm, region, "ConfigurationUpdate", "Alarm \"" + name + "\" created", data); + recordHistory(alarm, region, "ConfigurationUpdate", createdSummary(name), data); } else { data.put("type", "Update").set("updatedAlarm", after); ObjectNode original = data.putObject("originalUpdatedFields"); @@ -515,7 +535,17 @@ public class CloudWatchMetricsService { return alarms; } - private void evaluateComposites(String region, Set changedAlarmNames, String newAlarm) { + private void evaluateComposites(String region, Set changedAlarmNames) { + evaluateComposites(region, changedAlarmNames, null, false); + } + + /** + * Evaluates {@code newAlarm}, a composite alarm just created or updated, and the composite alarms + * above it and above {@code changedAlarmNames}, each after its composite children and only when + * one of its children changed. A composite alarm on a cycle is not evaluated; those above it + * still are. A change of state carries the reason and the triggering children CloudWatch reports. + */ + private void evaluateComposites(String region, Set changedAlarmNames, String newAlarm, boolean created) { if (changedAlarmNames.isEmpty() && newAlarm == null) { return; } @@ -549,6 +579,16 @@ public class CloudWatchMetricsService { } while (discovered); Set cycles = pending.keySet().stream() .filter(name -> isCyclic(name, alarms)).collect(Collectors.toSet()); + if (!cycles.isEmpty()) { + // Not evaluated, and no longer pending, so the composite alarms above them still are. + LOG.debugv("Composite alarms on a cycle are not evaluated: {0}", cycles); + pending.keySet().removeAll(cycles); + } + Function states = reference -> { + Alarm child = alarms.get(reference); + return child == null ? null : child.getStateValue(); + }; + Map stateOrder = null; boolean progress; do { progress = false; @@ -557,7 +597,7 @@ public class CloudWatchMetricsService { Map.Entry next = iterator.next(); boolean blocked = next.getValue().references().stream().map(alarms::get) .anyMatch(child -> child != null && pending.containsKey(child.getAlarmName())); - if (blocked || cycles.contains(next.getKey())) { + if (blocked) { continue; } if (!next.getKey().equals(newAlarm) @@ -567,48 +607,145 @@ public class CloudWatchMetricsService { continue; } Alarm alarm = alarms.get(next.getKey()); - boolean triggered = next.getValue().evaluate(reference -> { - Alarm child = alarms.get(reference); - return child == null ? null : child.getStateValue(); - }); + CompositeAlarmRule.Rule rule = next.getValue(); + boolean triggered = rule.evaluate(states); String state = triggered ? "ALARM" : "OK"; if (!state.equals(alarm.getStateValue())) { - changeState(alarm, region, state, "AlarmRule evaluated to " + state, null); - changed.add(alarm.getAlarmName()); - changed.add(alarm.getAlarmArn()); + if (stateOrder == null) { + stateOrder = stateOrder(region); + } + String reason = null; + Long since = null; + if (next.getKey().equals(newAlarm)) { + reason = alarm.getAlarmArn() + (created ? " was created and its alarm rule evaluates to " + : " was updated and its new alarm rule evaluates to ") + state; + } else { + Alarm trigger = latestChangedChild(rule, alarms, changed, stateOrder); + if (trigger != null) { + reason = trigger.getAlarmArn() + " transitioned to " + trigger.getStateValue() + " at " + + REASON_TIME.format(Instant.ofEpochSecond(trigger.lastTransitionTimestamp())); + since = orderOf(alarm, stateOrder); + } + } + // Only a changed child stored under another ARN, which no API call writes, fails to + // resolve: nothing then explains a change, so the alarm keeps its state. + if (reason != null) { + String data = triggeringAlarms(rule.agreeing(states, triggered), alarms, stateOrder, since); + changeState(alarm, region, state, reason, data); + // The transition is now the newest history entry. + stateOrder.put(alarm.getAlarmName(), lastHistorySequence); + changed.add(alarm.getAlarmName()); + changed.add(alarm.getAlarmArn()); + } } iterator.remove(); progress = true; } } while (progress && !pending.isEmpty()); if (!pending.isEmpty()) { - LOG.debugv("Composite alarm evaluation stopped at cyclic dependencies: {0}", pending.keySet()); + // A cycle the name lookup above misses, as when an alarm is named like another's ARN. + LOG.debugv("Composite alarm evaluation stopped with alarms still pending: {0}", pending.keySet()); } } + /** The child {@code rule} names that changed state most recently in this evaluation, or null if none resolves. */ + private static Alarm latestChangedChild(CompositeAlarmRule.Rule rule, Map alarms, Set changed, + Map stateOrder) { + return rule.references().stream().map(alarms::get).filter(Objects::nonNull) + .filter(child -> changed.contains(child.getAlarmName()) || changed.contains(child.getAlarmArn())) + .max(Comparator.comparingLong(child -> orderOf(child, stateOrder))).orElse(null); + } + + /** + * The StateReasonData of a composite alarm's change of state: the {@code agreeing} children, + * the one whose state is newest first, each with its state and when it took it, within what + * StateReasonData can hold. For a change a child caused, CloudWatch lists only the children that + * changed state after the composite alarm last did, which was at {@code since}. + */ + private static String triggeringAlarms(Set agreeing, Map alarms, + Map stateOrder, Long since) { + Map children = new LinkedHashMap<>(); + for (String reference : agreeing) { + Alarm child = alarms.get(reference); + if (child != null && (since == null || orderOf(child, stateOrder) > since)) { + children.putIfAbsent(child.getAlarmName(), child); + } + } + List newestFirst = new ArrayList<>(children.values()); + newestFirst.sort(Comparator.comparingLong((Alarm child) -> orderOf(child, stateOrder)).reversed()); + ObjectNode data = MAPPER.createObjectNode(); + ArrayNode list = data.putArray("triggeringAlarms"); + for (Alarm child : newestFirst) { + ObjectNode entry = list.addObject().put("arn", child.getAlarmArn()); + entry.putObject("state").put("value", child.getStateValue()).put("timestamp", + AlarmSnsNotifier.TIMESTAMP_FORMAT.format(Instant.ofEpochSecond(child.lastTransitionTimestamp()))); + String serialized = data.toString(); + if (serialized.codePointCount(0, serialized.length()) > MAX_STATE_REASON_DATA) { + list.remove(list.size() - 1); + break; + } + } + return data.toString(); + } + + /** + * The order in which the region's alarms took their current states, as alarm history sequences: + * each alarm's latest StateUpdate entry, or its creation if its state never changed. History + * orders state changes to the microsecond, where alarms keep their state times to the second. + */ + private Map stateOrder(String region) { + Map order = new HashMap<>(); + for (AlarmHistoryItem item : historyStore.scan(k -> k.startsWith(region + "::"))) { + if ("StateUpdate".equals(item.historyItemType()) + || createdSummary(item.alarmName()).equals(item.historySummary())) { + order.merge(item.alarmName(), item.sequence(), Math::max); + } + } + return order; + } + + /** Where {@code alarm} falls in {@link #stateOrder}; one whose entries aged out of history, at its last transition. */ + private static long orderOf(Alarm alarm, Map stateOrder) { + Long sequence = stateOrder.get(alarm.getAlarmName()); + return sequence != null ? sequence : epochMicros(Instant.ofEpochSecond(alarm.lastTransitionTimestamp())); + } + + private static String createdSummary(String name) { + return "Alarm \"" + name + "\" created"; + } + + /** + * Deletes the named alarms, or none of them: CloudWatch refuses a request that names more than one + * composite alarm, or an alarm that a composite alarm's rule names, even when the request deletes + * that composite alarm too. Names that match no alarm are ignored. + */ public synchronized void deleteAlarms(List alarmNames, String region) { - Map alarms = alarmIndex(region); - long composites = alarmNames.stream().map(alarms::get).filter(CompositeAlarm.class::isInstance).count(); + List existing = alarmNames.stream().distinct() + .map(name -> alarmStore.get(region + "::" + name).orElse(null)).filter(Objects::nonNull).toList(); + long composites = existing.stream().filter(CompositeAlarm.class::isInstance).count(); if (composites > 1) { - throw new AwsException("ValidationError", "DeleteAlarms accepts at most one composite alarm", 400); + throw new AwsException("ValidationError", "Cannot delete [" + composites + + "] Composite Alarms as only one composite alarm delete is allowed in single request", 400); } - for (String name : alarmNames) { - if (isCyclic(name, alarms)) { - throw new AwsException("ValidationError", "Break the composite alarm cycle before deleting " + name, 400); + Map alarms = alarmIndex(region); + Set referenced = new HashSet<>(); + for (Alarm alarm : new HashSet<>(alarms.values())) { + if (alarm instanceof CompositeAlarm composite) { + CompositeAlarmRule.parse(composite.getAlarmRule()).references().stream().map(alarms::get) + .filter(Objects::nonNull).forEach(child -> referenced.add(child.getAlarmName())); } } - Set deletedNames = new HashSet<>(); - for (String name : alarmNames) { - Alarm existing = alarmStore.get(region + "::" + name).orElse(null); - if (existing != null) { - deletedNames.add(name); - ObjectNode data = MAPPER.createObjectNode().put("version", "1.0").put("type", "Delete"); - data.set("deletedAlarm", snapshot(existing)); - recordHistory(existing, region, "ConfigurationUpdate", "Alarm \"" + name + "\" deleted", data); - } - alarmStore.delete(region + "::" + name); + List blocked = existing.stream().map(Alarm::getAlarmName).filter(referenced::contains).toList(); + if (!blocked.isEmpty()) { + throw new AwsException("ValidationError", "Cannot delete " + String.join(",", blocked) + + " as there are composite alarm(s) depending on " + (blocked.size() == 1 ? "it." : "them."), 400); + } + for (Alarm alarm : existing) { + ObjectNode data = MAPPER.createObjectNode().put("version", "1.0").put("type", "Delete"); + data.set("deletedAlarm", snapshot(alarm)); + recordHistory(alarm, region, "ConfigurationUpdate", "Alarm \"" + alarm.getAlarmName() + "\" deleted", data); + alarmStore.delete(region + "::" + alarm.getAlarmName()); } - evaluateComposites(region, deletedNames, null); LOG.infov("Deleted alarms: {0} in {1}", alarmNames, region); } @@ -648,7 +785,7 @@ public class CloudWatchMetricsService { throw SmithyValidationErrors.validationError(reasonViolation); } String dataViolation = stateReasonData == null ? null - : SmithyValidationErrors.lengthOutOfRange("stateReasonData", stateReasonData, 0, 4000); + : SmithyValidationErrors.lengthOutOfRange("stateReasonData", stateReasonData, 0, MAX_STATE_REASON_DATA); if (dataViolation != null) { throw SmithyValidationErrors.validationError(dataViolation); } @@ -660,7 +797,9 @@ public class CloudWatchMetricsService { String oldState = alarm.getStateValue(); changeState(alarm, region, stateValue, stateReason, stateReasonData); - evaluateComposites(region, Set.of(alarmName), null); + if (!stateValue.equals(oldState)) { + evaluateComposites(region, Set.of(alarmName)); + } LOG.infov("SetAlarmState: {0} -> {1}", alarmName, stateValue); if (alarmSnsNotifier != null && alarm instanceof MetricAlarm metricAlarm) { notifications = alarmSnsNotifier.prepareTransition(metricAlarm, oldState); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CompositeAlarmRule.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CompositeAlarmRule.java index 444cadb3d5..9de658f4b4 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CompositeAlarmRule.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CompositeAlarmRule.java @@ -3,14 +3,15 @@ package io.github.hectorvent.floci.services.cloudwatch.metrics; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.SmithyValidationErrors; -import java.util.HashSet; +import java.util.Collections; +import java.util.LinkedHashSet; import java.util.Set; import java.util.function.Function; /** CloudWatch's boolean alarm language, parsed completely before any alarm is stored. */ final class CompositeAlarmRule { private final String input; - private final Set references = new HashSet<>(); + private final Set references = new LinkedHashSet<>(); private int offset; private int elements; @@ -33,15 +34,13 @@ final class CompositeAlarmRule { if (parser.offset != input.length()) { throw invalid("Invalid AlarmRule"); } - return new Rule(expression, Set.copyOf(parser.references)); + return new Rule(expression, Collections.unmodifiableSet(parser.references)); } private Expression or() { Expression left = and(); while (word("OR")) { - Expression prior = left; - Expression right = and(); - left = states -> prior.evaluate(states) || right.evaluate(states); + left = new Or(left, and()); } return left; } @@ -49,9 +48,7 @@ final class CompositeAlarmRule { private Expression and() { Expression left = atom(); while (word("AND")) { - Expression prior = left; - Expression right = atom(); - left = states -> prior.evaluate(states) && right.evaluate(states); + left = new And(left, atom()); } return left; } @@ -62,7 +59,7 @@ final class CompositeAlarmRule { negate = !negate; } Expression operand = primary(); - return negate ? states -> !operand.evaluate(states) : operand; + return negate ? new Not(operand) : operand; } private Expression primary() { @@ -74,10 +71,10 @@ final class CompositeAlarmRule { return nested; } if (word("TRUE")) { - return states -> true; + return new Constant(true); } if (word("FALSE")) { - return states -> false; + return new Constant(false); } String state; if (word("ALARM")) { @@ -128,7 +125,7 @@ final class CompositeAlarmRule { } require(')'); references.add(name); - return states -> state.equals(states.apply(name)); + return new StateOf(state, name); } private void element() { @@ -175,13 +172,91 @@ final class CompositeAlarmRule { return new AwsException("ValidationError", message, 400); } + /** A parsed rule; {@code references} holds each alarm name or ARN once, in the order the rule first names it. */ record Rule(Expression expression, Set references) { boolean evaluate(Function states) { return expression.evaluate(states); } + + /** + * The references whose state test agrees with {@code result}: under an odd number of NOTs a test + * agrees when it is false. CloudWatch names these, among a composite alarm's children, as the + * alarms that triggered its change to that result. In rule order. + */ + Set agreeing(Function states, boolean result) { + Set agreeing = new LinkedHashSet<>(); + expression.collectAgreeing(states, result, agreeing); + return agreeing; + } } - interface Expression { + sealed interface Expression permits Constant, StateOf, Not, And, Or { boolean evaluate(Function states); + + void collectAgreeing(Function states, boolean result, Set agreeing); + } + + record Constant(boolean value) implements Expression { + @Override + public boolean evaluate(Function states) { + return value; + } + + @Override + public void collectAgreeing(Function states, boolean result, Set agreeing) { + // TRUE and FALSE name no alarm. + } + } + + record StateOf(String state, String reference) implements Expression { + @Override + public boolean evaluate(Function states) { + return state.equals(states.apply(reference)); + } + + @Override + public void collectAgreeing(Function states, boolean result, Set agreeing) { + if (evaluate(states) == result) { + agreeing.add(reference); + } + } + } + + record Not(Expression operand) implements Expression { + @Override + public boolean evaluate(Function states) { + return !operand.evaluate(states); + } + + @Override + public void collectAgreeing(Function states, boolean result, Set agreeing) { + operand.collectAgreeing(states, !result, agreeing); + } + } + + record And(Expression left, Expression right) implements Expression { + @Override + public boolean evaluate(Function states) { + return left.evaluate(states) && right.evaluate(states); + } + + @Override + public void collectAgreeing(Function states, boolean result, Set agreeing) { + left.collectAgreeing(states, result, agreeing); + right.collectAgreeing(states, result, agreeing); + } + } + + record Or(Expression left, Expression right) implements Expression { + @Override + public boolean evaluate(Function states) { + return left.evaluate(states) || right.evaluate(states); + } + + @Override + public void collectAgreeing(Function states, boolean result, Set agreeing) { + left.collectAgreeing(states, result, agreeing); + right.collectAgreeing(states, result, agreeing); + } } } diff --git a/src/test/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingServiceTest.java index a140602d75..59363adb8f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingServiceTest.java @@ -39,6 +39,7 @@ class ApplicationAutoScalingServiceTest { private static final String DIMENSION = "ecs:service:DesiredCount"; private ApplicationAutoScalingService service; + private CloudWatchMetricsService cloudWatch; /** Alarm names currently registered in the stubbed CloudWatch. */ private final Set alarmsInCloudWatch = new LinkedHashSet<>(); @@ -48,7 +49,7 @@ class ApplicationAutoScalingServiceTest { RegionResolver regionResolver = new RegionResolver(REGION, "000000000000"); alarmsInCloudWatch.clear(); - CloudWatchMetricsService cloudWatch = mock(CloudWatchMetricsService.class); + cloudWatch = mock(CloudWatchMetricsService.class); doAnswer(invocation -> { MetricAlarm alarm = invocation.getArgument(0); alarm.setAlarmArn("arn:aws:cloudwatch:" + REGION + ":000000000000:alarm:" + alarm.getAlarmName()); @@ -427,6 +428,32 @@ class ApplicationAutoScalingServiceTest { assertEquals("ObjectNotFoundException", e.getErrorCode()); } + /** + * CloudWatch refuses a whole DeleteAlarms request that names an alarm a composite alarm still + * names, so the cleanup deletes the policy's alarms one by one and only the named one stays. + */ + @Test + void policyCleanupKeepsOnlyTheAlarmACompositeAlarmNames() { + register(); + ScalingPolicy policy = service.putScalingPolicy("cpu", "TargetTrackingScaling", NAMESPACE, RESOURCE_ID, + DIMENSION, targetTracking(65.0, "ECSServiceAverageCPUUtilization", null), null, REGION); + String referenced = policy.getAlarms().getFirst().getAlarmName(); + doAnswer(invocation -> { + List names = invocation.getArgument(0); + if (names.contains(referenced)) { + throw new AwsException("ValidationError", + "Cannot delete " + referenced + " as there are composite alarm(s) depending on it.", 400); + } + alarmsInCloudWatch.removeAll(names); + return null; + }).when(cloudWatch).deleteAlarms(any(), anyString()); + + service.deleteScalingPolicy("cpu", NAMESPACE, RESOURCE_ID, DIMENSION, REGION); + + assertEquals(0, service.describeScalingPolicies(NAMESPACE, null, null, null, REGION).size()); + assertEquals(Set.of(referenced), alarmsInCloudWatch); + } + @Test void deleteScalingPolicyRemovesItsAlarms() { register(); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCompositeAlarmIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCompositeAlarmIntegrationTest.java index 42d8805a37..abba523359 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCompositeAlarmIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCompositeAlarmIntegrationTest.java @@ -126,6 +126,47 @@ class CloudFormationCompositeAlarmIntegrationTest { cw("DeleteAlarms", Map.of("AlarmNames", List.of(name))).then().statusCode(200); } + /** The composite alarm comes first in the template: only its rule's reference orders it after its child. */ + @Test + void aCompositeAlarmOverTheStacksMetricAlarmIsCreatedAfterItAndDeletedBeforeIt() throws Exception { + String stack = unique("composite-child"); + String child = stack + "-child"; + String parent = stack + "-parent"; + cleanup.register(() -> cw("DeleteAlarms", Map.of("AlarmNames", List.of(child))).then().statusCode(200)); + cleanup.register(() -> cw("DeleteAlarms", Map.of("AlarmNames", List.of(parent))).then().statusCode(200)); + Map resources = new LinkedHashMap<>(); + resources.put("Parent", Map.of("Type", "AWS::CloudWatch::CompositeAlarm", "Properties", Map.of( + "AlarmName", parent, "AlarmRule", Map.of("Fn::Sub", "ALARM(\"${Child}\")")))); + resources.put("Child", Map.of("Type", "AWS::CloudWatch::Alarm", "Properties", Map.of("AlarmName", child, + "Namespace", "Cfn/Composite", "MetricName", "Errors", "Statistic", "Sum", "Period", 60, + "EvaluationPeriods", 1, "Threshold", 1, "ComparisonOperator", "GreaterThanThreshold"))); + deploy("CreateStack", stack, MAPPER.writeValueAsString(Map.of("Resources", resources))); + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack).status()); + Map created = alarm(parent); + assertEquals(created.get("AlarmArn") + " was created and its alarm rule evaluates to OK", + created.get("StateReason")); + deleteStack(stack); + assertMissing(parent); + assertEquals(List.of(), cw("DescribeAlarms", Map.of("AlarmNames", List.of(child))).then().statusCode(200) + .extract().jsonPath().getList("MetricAlarms")); + } + + @Test + void aRuleNamingAMissingAlarmFailsTheStackWithCloudWatchsMessage() throws Exception { + String stack = unique("composite-orphan"); + String parent = stack + "-parent"; + cleanup.register(() -> cw("DeleteAlarms", Map.of("AlarmNames", List.of(parent))).then().statusCode(200)); + deploy("CreateStack", stack, MAPPER.writeValueAsString(Map.of("Resources", Map.of("Parent", Map.of( + "Type", "AWS::CloudWatch::CompositeAlarm", "Properties", Map.of("AlarmName", parent, + "AlarmRule", "ALARM(" + stack + "-missing)")))))); + assertEquals("ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stack).status()); + String reason = CfnStackWaits.failedResourceReason(stack); + assertTrue(reason.contains("Could not save the composite alarm as alarms [arn:aws:cloudwatch:us-east-1:" + + "000000000000:alarm:" + stack + "-missing] in the alarm rule do not exist"), reason); + assertMissing(parent); + deleteStack(stack); + } + private String template(String name, String rule, Map tags, boolean fail, boolean retain) throws JsonProcessingException { cleanup.register(() -> cw("DeleteAlarms", Map.of("AlarmNames", List.of(name))).then().statusCode(200)); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CompositeAlarmIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CompositeAlarmIntegrationTest.java index 71af54d875..6be4c7b299 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CompositeAlarmIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CompositeAlarmIntegrationTest.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.cloudwatch.metrics; import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.testing.PartitionCleanup; import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; @@ -208,13 +209,83 @@ class CompositeAlarmIntegrationTest { } } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void evaluationReasonsAndRefusalsUseCloudWatchTexts(boolean json) throws Exception { + String prefix = "wire-fidelity-" + Long.toString(System.nanoTime(), 36); + String child = prefix + "-child"; + String parent = prefix + "-parent"; + String other = prefix + "-other"; + String arn = "arn:aws-cn:cloudwatch:cn-north-1:000000000000:alarm:"; + // TreatMissingData=ignore keeps the alarm evaluator from resetting the state this test sets. + call(json, "PutMetricAlarm", Map.of("AlarmName", child, "Namespace", "Wire/Fidelity", "MetricName", "Errors", + "Statistic", "Sum", "Period", 60, "EvaluationPeriods", 1, "Threshold", 1, + "ComparisonOperator", "GreaterThanThreshold", "TreatMissingData", "ignore")).then().statusCode(200); + call(json, "PutCompositeAlarm", Map.of("AlarmName", parent, "AlarmRule", "ALARM(\"" + child + "\")")) + .then().statusCode(200); + Map created = composite(json, parent); + assertEquals("OK", created.get("StateValue")); + assertEquals(arn + parent + " was created and its alarm rule evaluates to OK", created.get("StateReason")); + JsonNode triggering = MAPPER.readTree(created.get("StateReasonData")).path("triggeringAlarms"); + assertEquals(1, triggering.size(), created.get("StateReasonData")); + assertEquals(arn + child, triggering.path(0).path("arn").asText()); + assertEquals("INSUFFICIENT_DATA", triggering.path(0).path("state").path("value").asText()); + assertTrue(triggering.path(0).path("state").path("timestamp").asText() + .matches("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}\\+0000"), created.get("StateReasonData")); + + call(json, "SetAlarmState", Map.of("AlarmName", child, "StateValue", "ALARM", "StateReason", "breached")) + .then().statusCode(200); + Map transitioned = composite(json, parent); + assertEquals("ALARM", transitioned.get("StateValue")); + assertTrue(transitioned.get("StateReason").matches("\\Q" + arn + child + " transitioned to ALARM at \\E" + + "[A-Z][a-z]+day \\d{2} [A-Z][a-z]+, \\d{4} \\d{2}:\\d{2}:\\d{2} UTC"), transitioned.get("StateReason")); + + call(json, "PutCompositeAlarm", Map.of("AlarmName", parent, "AlarmRule", "OK(\"" + child + "\")")) + .then().statusCode(200); + Map updated = composite(json, parent); + assertEquals("OK", updated.get("StateValue")); + assertEquals(arn + parent + " was updated and its new alarm rule evaluates to OK", updated.get("StateReason")); + + Response missing = call(json, "PutCompositeAlarm", Map.of("AlarmName", other, + "AlarmRule", "ALARM(" + prefix + "-missing)")); + missing.then().statusCode(400); + assertEquals("Could not save the composite alarm as alarms [" + arn + prefix + + "-missing] in the alarm rule do not exist", errorMessage(json, missing)); + Response referenced = call(json, "DeleteAlarms", Map.of("AlarmNames", List.of(child))); + referenced.then().statusCode(400); + assertEquals("Cannot delete " + child + " as there are composite alarm(s) depending on it.", + errorMessage(json, referenced)); + call(json, "PutCompositeAlarm", Map.of("AlarmName", other, "AlarmRule", "TRUE")).then().statusCode(200); + Response two = call(json, "DeleteAlarms", Map.of("AlarmNames", List.of(parent, other))); + two.then().statusCode(400); + assertEquals("Cannot delete [2] Composite Alarms as only one composite alarm delete is allowed in single request", + errorMessage(json, two)); + assertEquals("OK", composite(json, parent).get("StateValue")); + for (String name : List.of(parent, other, child)) { + call(json, "DeleteAlarms", Map.of("AlarmNames", List.of(name))).then().statusCode(200); + } + } + + private Map composite(boolean json, String name) throws JsonProcessingException { + Response response = call(json, "DescribeAlarms", Map.of("AlarmNames", List.of(name), + "AlarmTypes", List.of("CompositeAlarm"))); + response.then().statusCode(200); + Map fields = new LinkedHashMap<>(); + for (String field : List.of("StateValue", "StateReason", "StateReasonData")) { + fields.put(field, json ? response.jsonPath().getString("CompositeAlarms[0]." + field) + : response.xmlPath().getString("DescribeAlarmsResponse.DescribeAlarmsResult.CompositeAlarms.member." + + field)); + } + return fields; + } + private String errorMessage(boolean json, Response response) { return json ? response.jsonPath().getString("message") : response.xmlPath().getString("ErrorResponse.Error.Message"); } private Response call(boolean json, String operation, Map body) throws JsonProcessingException { - if ("PutCompositeAlarm".equals(operation)) { + if ("PutCompositeAlarm".equals(operation) || "PutMetricAlarm".equals(operation)) { String name = body.get("AlarmName").toString(); cleanup.register(() -> given().port(baseUri.getPort()).contentType("application/x-amz-json-1.0") .header("Authorization", SCOPE) diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CompositeAlarmServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CompositeAlarmServiceTest.java index 9d03922a23..9a1371dc71 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CompositeAlarmServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/metrics/CompositeAlarmServiceTest.java @@ -15,8 +15,14 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; @@ -26,11 +32,18 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import java.util.stream.IntStream; +import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.*; class CompositeAlarmServiceTest { private static final String REGION = "cn-north-1"; + /** A child's transition time in a composite alarm's StateReason, as CloudWatch prints it. */ + private static final DateTimeFormatter REASON_TIME = DateTimeFormatter + .ofPattern("EEEE dd MMMM, yyyy HH:mm:ss 'UTC'", Locale.ENGLISH).withZone(ZoneOffset.UTC); + /** A child's state time in triggeringAlarms, as CloudWatch writes it. */ + private static final DateTimeFormatter DATA_TIME = DateTimeFormatter + .ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.ROOT).withZone(ZoneOffset.UTC); private final CloudWatchMetricsService service = new CloudWatchMetricsService( new InMemoryStorage<>(), new InMemoryStorage<>(), new RegionResolver(REGION, "123456789012")); @@ -39,6 +52,7 @@ class CompositeAlarmServiceTest { MetricAlarm metric = new MetricAlarm(); metric.setAlarmName("latency"); service.putMetricAlarm(metric, REGION); + put("maintenance", "FALSE"); put("combined", "ALARM(\"" + metric.getAlarmArn() + "\") AND NOT ALARM(\"maintenance\")"); put("outer", "ALARM(combined) OR (TRUE AND FALSE)"); assertEquals("OK", state("outer")); @@ -103,18 +117,21 @@ class CompositeAlarmServiceTest { } @Test - void creationAndDeletionReevaluateOnlyReferencingComposites() { - MetricAlarm metric = new MetricAlarm(); - metric.setAlarmName("late"); + void aRuleMustNameExistingAlarmsWhichThenCannotBeDeleted() { + assertRejected("Could not save the composite alarm as alarms [" + arn("late") + + "] in the alarm rule do not exist", () -> put("watcher", "INSUFFICIENT_DATA(late)")); + assertTrue(service.describeCompositeAlarms(List.of("watcher"), null, REGION).isEmpty()); + metric("late"); put("watcher", "INSUFFICIENT_DATA(late)"); put("outer", "ALARM(watcher)"); - assertEquals("OK", state("watcher")); - service.putMetricAlarm(metric, REGION); assertEquals("ALARM", state("watcher")); assertEquals("ALARM", state("outer")); - service.deleteAlarms(List.of("late"), REGION); - assertEquals("OK", state("watcher")); - assertEquals("OK", state("outer")); + assertRejected("Cannot delete late as there are composite alarm(s) depending on it.", () -> delete("late")); + assertRejected("Cannot delete watcher as there are composite alarm(s) depending on it.", + () -> delete("watcher")); + assertEquals(1, service.describeAlarms(List.of("late"), null, REGION).size()); + assertEquals("ALARM", state("watcher")); + assertEquals("ALARM", state("outer")); } @Test @@ -130,10 +147,11 @@ class CompositeAlarmServiceTest { @Test void cyclesStopEvaluationEvenBehindShortCircuitAndMustBeBrokenBeforeDelete() { - put("a", "FALSE AND ALARM(b)"); + put("a", "FALSE"); put("b", "ALARM(a)"); + put("a", "FALSE AND ALARM(b)"); service.setAlarmState("b", "ALARM", "manual", null, REGION); - assertThrows(AwsException.class, () -> service.deleteAlarms(List.of("a"), REGION)); + assertRejected("Cannot delete a as there are composite alarm(s) depending on it.", () -> delete("a")); assertEquals(2, service.describeCompositeAlarms(null, null, REGION).size()); put("a", "FALSE"); service.deleteAlarms(List.of("b"), REGION); @@ -144,12 +162,16 @@ class CompositeAlarmServiceTest { @Test void manuallyChangingOneMemberDoesNotResumeACyclicDependency() { + put("b", "FALSE"); put("a", "ALARM(b)"); put("b", "ALARM(a)"); assertEquals("OK", state("a")); service.setAlarmState("b", "ALARM", "manual", null, REGION); assertEquals("OK", state("a")); put("b", "TRUE"); + service.setAlarmState("b", "ALARM", "same state", null, REGION); + assertEquals("OK", state("a")); + service.setAlarmState("b", "OK", "cycle broken", null, REGION); service.setAlarmState("b", "ALARM", "cycle broken", null, REGION); assertEquals("ALARM", state("a")); } @@ -323,8 +345,323 @@ class CompositeAlarmServiceTest { "parent:Alarm updated from INSUFFICIENT_DATA to OK"), items.stream().map(item -> item.alarmName() + ":" + item.historySummary()).toList()); JsonNode data = new ObjectMapper().readTree(items.getFirst().historyData()); - assertEquals("AlarmRule evaluated to ALARM", data.path("newState").path("stateReason").asText()); - assertEquals("AlarmRule evaluated to OK", data.path("oldState").path("stateReason").asText()); + assertEquals(arn("child") + " transitioned to ALARM at " + reasonTime("child"), + data.path("newState").path("stateReason").asText()); + assertEquals(arn("child"), data.path("newState").path("stateReasonData") + .path("triggeringAlarms").path(0).path("arn").asText()); + assertEquals(arn("parent") + " was created and its alarm rule evaluates to OK", + data.path("oldState").path("stateReason").asText()); + assertEquals("INSUFFICIENT_DATA", data.path("oldState").path("stateReasonData") + .path("triggeringAlarms").path(0).path("state").path("value").asText()); + } + + /** + * Replays a published probe of CloudWatch in eu-central-1, leaving out its AT_LEAST rules: at every + * step the composite alarms take the state, StateReason and triggeringAlarms that CloudWatch + * reported. The probe and its two runs of 2026-10-15, with the same results, are at + * https://github.com/ministackorg/ministack/pull/2260. + */ + @Test + void evaluationMatchesWhatCloudWatchReportedForTheSameSteps() { + for (String name : List.of("m-a", "m-b", "m-c")) { + metric(name); + } + Map rules = new LinkedHashMap<>(); + rules.put("c-and", "ALARM(\"m-a\") AND ALARM(\"m-b\")"); + rules.put("c-or", "ALARM(" + arn("m-a") + ") OR ALARM(m-b)"); + rules.put("c-not", "NOT ALARM(\"m-a\")"); + rules.put("c-ok", "OK(\"m-a\")"); + rules.put("c-ins", "INSUFFICIENT_DATA(\"m-b\")"); + rules.put("c-true", "TRUE"); + rules.put("c-false", "FALSE"); + rules.put("c-nest", "ALARM(\"c-or\")"); + rules.put("c-mix", "(ALARM(\"m-a\") OR OK(\"m-b\")) AND NOT INSUFFICIENT_DATA(\"m-b\")"); + rules.put("c-rev", "ALARM(\"m-b\") AND ALARM(\"m-a\")"); + rules.put("c-prec", "TRUE OR TRUE AND FALSE"); + rules.put("c-notprec", "NOT TRUE AND FALSE"); + rules.forEach(this::put); + + assertStates("c-and OK, c-false OK, c-ins ALARM, c-mix OK, c-nest OK, c-not ALARM, c-notprec OK, c-ok OK, " + + "c-or OK, c-prec ALARM, c-rev OK, c-true ALARM"); + for (String name : rules.keySet()) { + assertEquals(arn(name) + " was created and its alarm rule evaluates to " + state(name), + alarm(name).getStateReason()); + } + assertTriggering("c-and", "m-b INSUFFICIENT_DATA", "m-a INSUFFICIENT_DATA"); + assertTriggering("c-false"); + assertTriggering("c-ins", "m-b INSUFFICIENT_DATA"); + assertTriggering("c-mix", "m-b INSUFFICIENT_DATA", "m-a INSUFFICIENT_DATA"); + assertTriggering("c-nest", "c-or OK"); + assertTriggering("c-not", "m-a INSUFFICIENT_DATA"); + assertTriggering("c-ok", "m-a INSUFFICIENT_DATA"); + assertTriggering("c-or", "m-b INSUFFICIENT_DATA", "m-a INSUFFICIENT_DATA"); + assertTriggering("c-rev", "m-b INSUFFICIENT_DATA", "m-a INSUFFICIENT_DATA"); + assertTriggering("c-true"); + + set("m-a", "ALARM"); + assertStates("c-and OK, c-mix OK, c-nest ALARM, c-not OK, c-ok OK, c-or ALARM, c-rev OK"); + assertTransitionedBecause("c-or", "m-a", "m-a ALARM"); + assertTransitionedBecause("c-nest", "c-or", "c-or ALARM"); + assertTransitionedBecause("c-not", "m-a", "m-a ALARM"); + assertEquals(arn("c-and") + " was created and its alarm rule evaluates to OK", alarm("c-and").getStateReason()); + + set("m-b", "ALARM"); + assertStates("c-and ALARM, c-ins OK, c-mix ALARM, c-nest ALARM, c-or ALARM, c-rev ALARM"); + assertTransitionedBecause("c-and", "m-b", "m-b ALARM", "m-a ALARM"); + assertTransitionedBecause("c-ins", "m-b", "m-b ALARM"); + assertTransitionedBecause("c-mix", "m-b", "m-b ALARM", "m-a ALARM"); + assertTransitionedBecause("c-rev", "m-b", "m-b ALARM", "m-a ALARM"); + + set("m-a", "OK"); + assertStates("c-and OK, c-mix OK, c-nest ALARM, c-not ALARM, c-ok ALARM, c-or ALARM, c-rev OK"); + for (String name : List.of("c-and", "c-mix", "c-not", "c-ok", "c-rev")) { + assertTransitionedBecause(name, "m-a", "m-a OK"); + } + + set("m-b", "OK"); + assertStates("c-and OK, c-ins OK, c-mix ALARM, c-nest OK, c-or OK, c-rev OK"); + assertTransitionedBecause("c-mix", "m-b", "m-b OK"); + assertTransitionedBecause("c-nest", "c-or", "c-or OK"); + assertTransitionedBecause("c-or", "m-b", "m-b OK", "m-a OK"); + + set("m-a", "ALARM"); + put("c-late", "ALARM(\"m-a\")"); + assertEquals("ALARM", state("c-late")); + assertTriggering("c-late", "m-a ALARM"); + + set("c-true", "OK"); + assertEquals("probe", alarm("c-true").getStateReason()); + assertNull(alarm("c-true").getStateReasonData()); + + set("c-and", "ALARM"); + set("m-b", "INSUFFICIENT_DATA"); + assertEquals("OK", state("c-and")); + assertTransitionedBecause("c-and", "m-b", "m-b INSUFFICIENT_DATA"); + + put("c-false", "TRUE"); + assertEquals("ALARM", state("c-false")); + assertEquals(arn("c-false") + " was updated and its new alarm rule evaluates to ALARM", + alarm("c-false").getStateReason()); + assertTriggering("c-false"); + + Alarm sameState = alarm("c-ok"); + String reason = sameState.getStateReason(); + String data = sameState.getStateReasonData(); + long updated = sameState.getStateUpdatedTimestamp(); + put("c-ok", "NOT ALARM(\"m-a\")"); + assertEquals("OK", state("c-ok")); + assertEquals(reason, alarm("c-ok").getStateReason()); + assertEquals(data, alarm("c-ok").getStateReasonData()); + assertEquals(updated, alarm("c-ok").getStateUpdatedTimestamp()); + + put("c-not", "ALARM(\"m-a\") OR ALARM(\"m-b\")"); + assertEquals("ALARM", state("c-not")); + assertEquals(arn("c-not") + " was updated and its new alarm rule evaluates to ALARM", + alarm("c-not").getStateReason()); + assertTriggering("c-not", "m-a ALARM"); + + set("m-b", "OK"); + set("m-a", "OK"); + put("c-dist", "ALARM(\"m-a\") OR ALARM(\"m-b\")"); + put("c-ord", "ALARM(\"m-b\") AND ALARM(\"m-a\")"); + assertTriggering("c-dist", "m-a OK", "m-b OK"); + assertTriggering("c-ord", "m-a OK", "m-b OK"); + set("m-b", "INSUFFICIENT_DATA"); + assertEquals(arn("c-dist") + " was created and its alarm rule evaluates to OK", alarm("c-dist").getStateReason()); + set("m-a", "ALARM"); + assertEquals("ALARM", state("c-dist")); + assertTransitionedBecause("c-dist", "m-a", "m-a ALARM"); + assertEquals("OK", state("c-ord")); + + assertRejected("Could not save the composite alarm as alarms [" + arn("does-not-exist") + + "] in the alarm rule do not exist", () -> put("c-bad1", "ALARM(\"does-not-exist\")")); + assertTrue(service.describeCompositeAlarms(List.of("c-bad1"), null, REGION).isEmpty()); + + put("c-or", "ALARM(\"c-nest\")"); + assertStates("c-nest ALARM, c-or ALARM"); + assertRejected("Cannot delete m-a as there are composite alarm(s) depending on it.", () -> delete("m-a")); + assertRejected("Cannot delete c-or as there are composite alarm(s) depending on it.", () -> delete("c-or")); + assertRejected("Cannot delete [2] Composite Alarms as only one composite alarm delete is allowed in single " + + "request", () -> delete("c-true", "c-false")); + delete("does-not-exist", "c-ok"); + assertTrue(service.describeCompositeAlarms(List.of("c-ok"), null, REGION).isEmpty()); + delete("does-not-exist"); + assertRejected("Cannot delete [2] Composite Alarms as only one composite alarm delete is allowed in single " + + "request", () -> delete("c-nest", "c-or")); + put("c-solo", "ALARM(\"m-c\")"); + assertRejected("Cannot delete m-c as there are composite alarm(s) depending on it.", () -> delete("m-c", "c-solo")); + assertEquals(1, service.describeAlarms(List.of("m-c"), null, REGION).size()); + assertEquals("ALARM(\"m-c\")", ((CompositeAlarm) alarm("c-solo")).getAlarmRule()); + } + + @Test + void deletingSeveralReferencedAlarmsNamesThemAllAndDeletesNothing() { + metric("x"); + metric("y"); + metric("free"); + put("both", "ALARM(x) OR ALARM(\"" + arn("y") + "\")"); + assertRejected("Cannot delete x,y as there are composite alarm(s) depending on them.", + () -> delete("free", "x", "y", "x")); + assertEquals(3, service.describeAlarms(null, null, REGION).size()); + assertRejected("Cannot delete y as there are composite alarm(s) depending on it.", () -> delete("y", "both")); + delete(arn("both")); + assertEquals(1, service.describeCompositeAlarms(null, null, REGION).size()); + delete("both", "both"); + delete("x", "y", "free"); + assertTrue(service.describeAlarms(null, null, REGION).isEmpty()); + } + + @Test + void aRuleNamingMissingAlarmsIsRefusedWithTheirArnsInRuleOrder() { + metric("present"); + assertRejected("Could not save the composite alarm as alarms [" + arn("first") + ", " + arn("second") + + "] in the alarm rule do not exist", () -> put("orphan", "ALARM(first) OR ALARM(present) OR OK(\"" + + arn("second") + "\") OR ALARM(\"first\")")); + assertTrue(service.describeCompositeAlarms(null, null, REGION).isEmpty()); + + put("kept", "ALARM(present)"); + assertRejected("Could not save the composite alarm as alarms [" + arn("gone") + + "] in the alarm rule do not exist", () -> put("kept", "ALARM(gone)")); + assertEquals("ALARM(present)", ((CompositeAlarm) alarm("kept")).getAlarmRule()); + } + + @Test + void anUpdateIsEvaluatedAndATransitionReachesItsParents() { + metric("child"); + set("child", "ALARM"); + put("middle", "OK(child)"); + put("top", "ALARM(middle)"); + assertEquals("OK", state("middle")); + assertEquals("OK", state("top")); + + put("middle", "ALARM(child)"); + assertEquals("ALARM", state("middle")); + assertEquals(arn("middle") + " was updated and its new alarm rule evaluates to ALARM", + alarm("middle").getStateReason()); + assertTriggering("middle", "child ALARM"); + assertEquals("ALARM", state("top")); + assertTransitionedBecause("top", "middle", "middle ALARM"); + + Alarm before = alarm("top"); + String reason = before.getStateReason(); + long transitioned = before.getStateTransitionedTimestamp(); + put("top", "ALARM(middle) OR ALARM(child)"); + assertEquals(reason, alarm("top").getStateReason()); + assertEquals(transitioned, alarm("top").getStateTransitionedTimestamp()); + + set("top", "OK"); + put("top", "ALARM(middle) OR ALARM(child)"); + assertEquals("ALARM", state("top")); + assertEquals(arn("top") + " was updated and its new alarm rule evaluates to ALARM", alarm("top").getStateReason()); + assertTriggering("top", "middle ALARM", "child ALARM"); + } + + /** + * A composite alarm set with SetAlarmState "returns to its actual state only once any of its + * children alarms change state" + * (https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_SetAlarmState.html): + * a metric alarm child's update or a SetAlarmState to the state it already has does not change + * its state. + */ + @Test + void aManualStateHoldsThroughAChildsUpdateAndSameStateSet() { + metric("m"); + set("m", "ALARM"); + put("c", "ALARM(m)"); + set("c", "OK"); + MetricAlarm update = new MetricAlarm(); + update.setAlarmName("m"); + update.setThreshold(5); + service.putMetricAlarm(update, REGION); + set("m", "ALARM"); + assertEquals("OK", state("c")); + assertEquals("probe", alarm("c").getStateReason()); + + set("m", "OK"); + set("m", "ALARM"); + assertEquals("ALARM", state("c")); + assertTransitionedBecause("c", "m", "m ALARM"); + } + + /** The cycle between c and d is not evaluated, but p above it follows its other child. */ + @Test + void aCompositeAlarmAboveACycleIsStillEvaluated() { + metric("m"); + put("c", "ALARM(m)"); + put("d", "ALARM(c)"); + put("c", "ALARM(d) OR ALARM(m)"); + put("p", "ALARM(c) OR ALARM(m)"); + set("m", "ALARM"); + assertEquals("ALARM", state("p")); + assertTransitionedBecause("p", "m", "m ALARM"); + } + + /** Rules saved before missing children were refused can name an alarm that is created later. */ + @Test + void aCompositeAlarmStoredOverAMissingAlarmIsEvaluatedWhenThatAlarmIsCreated() { + InMemoryStorage alarms = new InMemoryStorage<>(); + CloudWatchMetricsService stored = new CloudWatchMetricsService(new InMemoryStorage<>(), alarms, + new RegionResolver(REGION, "123456789012")); + CompositeAlarm watcher = new CompositeAlarm(); + watcher.setAlarmName("watcher"); + watcher.setAlarmArn(arn("watcher")); + watcher.setAlarmRule("INSUFFICIENT_DATA(late)"); + watcher.setRegion(REGION); + watcher.setStateValue("OK"); + alarms.put(REGION + "::watcher", watcher); + MetricAlarm late = new MetricAlarm(); + late.setAlarmName("late"); + stored.putMetricAlarm(late, REGION); + CompositeAlarm evaluated = stored.describeCompositeAlarms(List.of("watcher"), null, REGION).getFirst(); + assertEquals("ALARM", evaluated.getStateValue()); + assertTrue(evaluated.getStateReason().startsWith(arn("late") + " transitioned to INSUFFICIENT_DATA at "), + evaluated.getStateReason()); + } + + @Test + void aParentOfTwoChildrenThatChangedTogetherNamesTheLastOfThem() { + metric("m"); + put("c", "ALARM(m)"); + put("p", "ALARM(c) OR ALARM(m)"); + set("m", "ALARM"); + assertTransitionedBecause("c", "m", "m ALARM"); + assertTransitionedBecause("p", "c", "c ALARM", "m ALARM"); + } + + @Test + void stateReasonDataStaysWithinItsDocumentedLengthAndKeepsTheNewestChildren() throws Exception { + String prefix = "child-with-a-long-name-to-fill-state-reason-data-"; + IntStream.range(0, 100).forEach(index -> metric(prefix + index)); + put("wide", IntStream.range(0, 100).mapToObj(index -> "ALARM(" + prefix + index + ")") + .collect(Collectors.joining(" OR "))); + String data = alarm("wide").getStateReasonData(); + assertTrue(data.length() <= 4000, "StateReasonData is " + data.length() + " characters"); + List listed = triggering("wide"); + assertTrue(listed.size() > 10 && listed.size() < 100, listed.size() + " children listed"); + assertEquals(prefix + "99 INSUFFICIENT_DATA", listed.getFirst()); + } + + /** + * StateReasonData's 4000 is counted in Unicode code points, as its length check counts it. An emoji is one + * code point but two UTF-16 units, so each emoji child here adds 347 code points to the list, its comma + * included, but 547 units. The newest child's 17-character name brings 12 entries to exactly 4000 code + * points, which still fit; counted in units, only 7 entries would. + */ + @Test + void stateReasonDataCountsCodePointsAsItsLengthLimitDoes() { + String emoji = "\uD83D\uDE00"; + List names = new ArrayList<>(IntStream.range(0, 15) + .mapToObj(index -> emoji.repeat(200) + String.format("-%02d", index)).toList()); + names.add("exactly-4000-edge"); + names.forEach(this::metric); + put("wide", names.stream().map(name -> "ALARM(\"" + name + "\")").collect(Collectors.joining(" OR "))); + List listed = triggering("wide"); + assertEquals(12, listed.size(), "children listed"); + assertEquals("exactly-4000-edge INSUFFICIENT_DATA", listed.getFirst()); + assertEquals(names.get(4) + " INSUFFICIENT_DATA", listed.getLast()); + String data = alarm("wide").getStateReasonData(); + assertEquals(4000, data.codePointCount(0, data.length())); + assertTrue(data.length() > 4000, data.length() + " UTF-16 units"); } private CompositeAlarm put(String name, String rule) { @@ -339,4 +676,80 @@ class CompositeAlarmServiceTest { private String state(String name) { return service.describeCompositeAlarms(List.of(name), null, REGION).getFirst().getStateValue(); } + + private void metric(String name) { + MetricAlarm alarm = new MetricAlarm(); + alarm.setAlarmName(name); + service.putMetricAlarm(alarm, REGION); + } + + private void set(String name, String state) { + service.setAlarmState(name, state, "probe", null, REGION); + } + + private void delete(String... names) { + service.deleteAlarms(List.of(names), REGION); + } + + private Alarm alarm(String name) { + return Stream.concat(service.describeAlarms(List.of(name), null, REGION).stream(), + service.describeCompositeAlarms(List.of(name), null, REGION).stream()).findFirst().orElseThrow(); + } + + private static String arn(String name) { + return "arn:aws-cn:cloudwatch:" + REGION + ":123456789012:alarm:" + name; + } + + /** The child's last transition as a composite alarm's StateReason prints it, "Monday 14 September, 2026 06:29:58 UTC". */ + private String reasonTime(String child) { + return REASON_TIME.format(Instant.ofEpochSecond(alarm(child).getStateTransitionedTimestamp())); + } + + private void assertStates(String expected) { + Map wanted = new LinkedHashMap<>(); + for (String entry : expected.split(",")) { + String[] parts = entry.trim().split(" "); + wanted.put(parts[0], parts[1]); + } + Map actual = new LinkedHashMap<>(); + wanted.keySet().forEach(name -> actual.put(name, state(name))); + assertEquals(wanted, actual); + } + + /** The composite last changed state because {@code child} did, and lists these triggering children. */ + private void assertTransitionedBecause(String name, String child, String... triggering) { + assertEquals(arn(child) + " transitioned to " + alarm(child).getStateValue() + " at " + reasonTime(child), + alarm(name).getStateReason()); + assertTriggering(name, triggering); + } + + private void assertTriggering(String name, String... expected) { + assertEquals(List.of(expected), triggering(name)); + } + + /** The StateReasonData children, newest first, each as "name STATE" after checking its timestamp. */ + private List triggering(String name) { + JsonNode data; + try { + data = new ObjectMapper().readTree(alarm(name).getStateReasonData()); + } catch (Exception e) { + throw new AssertionError("StateReasonData of " + name + " is not JSON", e); + } + List children = new ArrayList<>(); + for (JsonNode child : data.path("triggeringAlarms")) { + String childArn = child.path("arn").asText(); + String childName = childArn.substring(childArn.lastIndexOf(':') + 1); + assertEquals(DATA_TIME.format(Instant.ofEpochSecond(alarm(childName).getStateTransitionedTimestamp())), + child.path("state").path("timestamp").asText(), data.toString()); + children.add(childName + " " + child.path("state").path("value").asText()); + } + return children; + } + + private static void assertRejected(String message, Runnable call) { + AwsException error = assertThrows(AwsException.class, call::run); + assertEquals("ValidationError", error.getErrorCode()); + assertEquals(400, error.getHttpStatus()); + assertEquals(message, error.getMessage()); + } }