mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(cloudwatch): evaluate composite alarms with CloudWatch's reasons and refusals (#6987)
* fix(cloudwatch): evaluate composite alarms with CloudWatch's reasons and refusals
Composite alarms recorded "AlarmRule evaluated to <state>" with no
StateReasonData, were evaluated only when created, accepted a rule
naming an alarm that does not exist, and let DeleteAlarms remove an
alarm a composite alarm still names. Published CloudWatch captures
show each one differently.
- A change of state records the StateReason CloudWatch writes: "<arn>
was created and its alarm rule evaluates to OK", "<arn> was updated
and its new alarm rule evaluates to ALARM", or "<child arn>
transitioned to ALARM at Monday 14 September, 2026 06:29:58 UTC".
- StateReasonData lists triggeringAlarms: the children whose state
agrees with the new one, most recently changed first. After a child's
change only the children that changed since the composite alarm last
did are listed; the alarm history orders those changes.
- PutCompositeAlarm evaluates an alarm it updates, and its parents
follow the change.
- A rule naming a missing alarm is refused with "Could not save the
composite alarm as alarms [<arn>] in the alarm rule do not exist".
- DeleteAlarms deletes nothing when it names an alarm a composite alarm
references ("Cannot delete <name> as there are composite alarm(s)
depending on it.", or "a,b ... depending on them."), or more than one
composite alarm ("Cannot delete [2] Composite Alarms as only one
composite alarm delete is allowed in single request").
The new service, Query, JSON and SDK tests fail on main.
Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
* test(cloudformation): cover a composite alarm over its stack's metric alarm
A stack whose composite alarm names the stack's own metric alarm is
created child first and deleted parent first, so neither the new
refusal of unknown children nor the refusal to delete a referenced
alarm fails it. A stack whose rule names a missing alarm rolls back
with CloudWatch's message; that test fails on main.
Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
* fix(cloudwatch): evaluate composite alarms only when a child changes state
Review follow-ups to the composite alarm evaluation change.
- A child's PutMetricAlarm update, or a SetAlarmState to the state it
already has, no longer re-evaluates its parents. CloudWatch documents
that a composite alarm set with SetAlarmState "returns to its actual
state only once any of its children alarms change state"; such a
parent used to flip back with a reason naming an old transition.
- Application Auto Scaling deletes a policy's alarms one at a time, so
when a composite alarm names one of them only that one stays.
- A changed child that no longer resolves leaves its parent as it is
instead of failing the request.
- The docs say that an update closing a cycle is not evaluated, where
CloudWatch evaluates it.
- Tests: the wire and SDK tests ignore missing data so the alarm
evaluator cannot reset the states they set, one pins the reason when
two children change together, and the self-reference and cross-region
assertions, which pinned texts CloudWatch does not use, are gone.
The new manual-state and Application Auto Scaling tests fail without
this change.
Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
* fix(cloudwatch): evaluate composite alarms above a cycle
A composite alarm on a cycle stayed pending, which blocked every
composite alarm above it: one whose other child changed state was never
evaluated. Alarms on the cycle are still not evaluated, but they no
longer hold up the ones above them.
Also from the second review: the docs say only a metric alarm child's
update is not a change of state, and that alarms above a cycle are
evaluated; a test covers a rule stored before missing children were
refused, whose child is created later; a test docstring links the
SetAlarmState reference.
The test for an alarm above a cycle fails without this change.
Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
* chore(cloudwatch): log a composite evaluation that stops with alarms pending
The third review found one way the evaluation can still stop with
alarms pending: an alarm named like another alarm's ARN makes the cycle
check follow the wrong rule. The debug line removed in the previous
commit is back, so that case is visible again; the name lookup itself
predates this branch. The docs say an alarm above a cycle is evaluated
when one of its children changes state.
No behaviour change.
Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
* fix(cloudwatch): count composite StateReasonData in code points
triggeringAlarms stopped adding children once the serialized JSON
passed 4000 UTF-16 units, while the StateReasonData length check
counts Unicode code points, as Smithy's length constraint counts
Unicode scalar values. An emoji is two units but one code point, so
children whose entries still fit were dropped. The cap now counts code
points, shares its constant with SetAlarmState's length check, and the
docs say so.
The new test names fifteen children with emoji and a newest one with a
short name, so that twelve entries come to exactly 4000 code points. It
lists 7 of them before this change and all 12 after; an exclusive cap
would list 11.
Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
* test(cloudwatch): keep the composite alarm SDK test on Java 17 APIs
CloudWatchCompositeAlarmTest called List.getFirst(), which Java 21
added. compatibility-tests/sdk-test-java compiles for Java 17, and CI
builds it in maven:3.9-eclipse-temurin-17, so its test-compile failed
and took the sdk-test-java and ec2-containers jobs with it. The three
calls use get(0) now.
A test-compile of sdk-test-java with --release 17 fails on those three
lines before this change and passes after it. No other file of the
branch is outside the root module, which builds for Java 25.
Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
---------
Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
This commit is contained in:
1 parent
b4c4718c36
commit
6acadc3404
9 files changed
+1011
-72
No files matched your search
+11
-9
@@ -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<String> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+174
-35
@@ -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<String, Alarm> alarms = alarmIndex(region);
|
||||
List<String> 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<String> 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<String> changedAlarmNames, String newAlarm) {
|
||||
private void evaluateComposites(String region, Set<String> 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<String> changedAlarmNames, String newAlarm, boolean created) {
|
||||
if (changedAlarmNames.isEmpty() && newAlarm == null) {
|
||||
return;
|
||||
}
|
||||
@@ -549,6 +579,16 @@ public class CloudWatchMetricsService {
|
||||
} while (discovered);
|
||||
Set<String> 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<String, String> states = reference -> {
|
||||
Alarm child = alarms.get(reference);
|
||||
return child == null ? null : child.getStateValue();
|
||||
};
|
||||
Map<String, Long> stateOrder = null;
|
||||
boolean progress;
|
||||
do {
|
||||
progress = false;
|
||||
@@ -557,7 +597,7 @@ public class CloudWatchMetricsService {
|
||||
Map.Entry<String, CompositeAlarmRule.Rule> 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<String, Alarm> alarms, Set<String> changed,
|
||||
Map<String, Long> 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<String> agreeing, Map<String, Alarm> alarms,
|
||||
Map<String, Long> stateOrder, Long since) {
|
||||
Map<String, Alarm> 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<Alarm> 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<String, Long> stateOrder(String region) {
|
||||
Map<String, Long> 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<String, Long> 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<String> alarmNames, String region) {
|
||||
Map<String, Alarm> alarms = alarmIndex(region);
|
||||
long composites = alarmNames.stream().map(alarms::get).filter(CompositeAlarm.class::isInstance).count();
|
||||
List<Alarm> 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<String, Alarm> alarms = alarmIndex(region);
|
||||
Set<String> 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<String> 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<String> 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);
|
||||
|
||||
+89
-14
@@ -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<String> references = new HashSet<>();
|
||||
private final Set<String> 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<String> references) {
|
||||
boolean evaluate(Function<String, String> 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<String> agreeing(Function<String, String> states, boolean result) {
|
||||
Set<String> agreeing = new LinkedHashSet<>();
|
||||
expression.collectAgreeing(states, result, agreeing);
|
||||
return agreeing;
|
||||
}
|
||||
}
|
||||
|
||||
interface Expression {
|
||||
sealed interface Expression permits Constant, StateOf, Not, And, Or {
|
||||
boolean evaluate(Function<String, String> states);
|
||||
|
||||
void collectAgreeing(Function<String, String> states, boolean result, Set<String> agreeing);
|
||||
}
|
||||
|
||||
record Constant(boolean value) implements Expression {
|
||||
@Override
|
||||
public boolean evaluate(Function<String, String> states) {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void collectAgreeing(Function<String, String> states, boolean result, Set<String> agreeing) {
|
||||
// TRUE and FALSE name no alarm.
|
||||
}
|
||||
}
|
||||
|
||||
record StateOf(String state, String reference) implements Expression {
|
||||
@Override
|
||||
public boolean evaluate(Function<String, String> states) {
|
||||
return state.equals(states.apply(reference));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void collectAgreeing(Function<String, String> states, boolean result, Set<String> agreeing) {
|
||||
if (evaluate(states) == result) {
|
||||
agreeing.add(reference);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
record Not(Expression operand) implements Expression {
|
||||
@Override
|
||||
public boolean evaluate(Function<String, String> states) {
|
||||
return !operand.evaluate(states);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void collectAgreeing(Function<String, String> states, boolean result, Set<String> agreeing) {
|
||||
operand.collectAgreeing(states, !result, agreeing);
|
||||
}
|
||||
}
|
||||
|
||||
record And(Expression left, Expression right) implements Expression {
|
||||
@Override
|
||||
public boolean evaluate(Function<String, String> states) {
|
||||
return left.evaluate(states) && right.evaluate(states);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void collectAgreeing(Function<String, String> states, boolean result, Set<String> agreeing) {
|
||||
left.collectAgreeing(states, result, agreeing);
|
||||
right.collectAgreeing(states, result, agreeing);
|
||||
}
|
||||
}
|
||||
|
||||
record Or(Expression left, Expression right) implements Expression {
|
||||
@Override
|
||||
public boolean evaluate(Function<String, String> states) {
|
||||
return left.evaluate(states) || right.evaluate(states);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void collectAgreeing(Function<String, String> states, boolean result, Set<String> agreeing) {
|
||||
left.collectAgreeing(states, result, agreeing);
|
||||
right.collectAgreeing(states, result, agreeing);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user