mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
fix(cloudwatch): report StateTransitionedTimestamp and AWS's StateValue enum order (#6719)
This commit is contained in:
1 parent
0c44312101
commit
64069f9ccd
8 files changed
+168
-10
No files matched your search
@@ -432,11 +432,15 @@ rejected with `ValidationError`.
|
||||
|
||||
### Metric alarm updates
|
||||
|
||||
Updating a metric alarm preserves its current state, state reason, state timestamp and tags.
|
||||
Updating a metric alarm preserves its current state, state reason, state timestamps and tags.
|
||||
Tags supplied to `PutMetricAlarm` apply only when creating an alarm; use `TagResource` and
|
||||
`UntagResource` to change existing tags. `SetAlarmState` requires `StateReason` and rejects
|
||||
missing or unknown state values before changing the alarm.
|
||||
|
||||
`StateTransitionedTimestamp` records when an alarm's `StateValue` last changed, while
|
||||
`StateUpdatedTimestamp` moves on every state update, including one that keeps the value.
|
||||
Alarms stored before Floci recorded it report their last state update.
|
||||
|
||||
`SetAlarmState` enforces the modeled maximum lengths of 1023 characters for
|
||||
`StateReason` and 4000 characters for `StateReasonData` before changing alarm state.
|
||||
Length checks count Unicode code points and preserve empty and whitespace values.
|
||||
|
||||
+1
@@ -388,6 +388,7 @@ public class CloudWatchMetricsJsonHandler {
|
||||
node.put("StateReasonData", a.getStateReasonData());
|
||||
}
|
||||
node.put("StateUpdatedTimestamp", a.getStateUpdatedTimestamp());
|
||||
node.put("StateTransitionedTimestamp", a.lastTransitionTimestamp());
|
||||
node.put("AlarmConfigurationUpdatedTimestamp", a.getAlarmConfigurationUpdatedTimestamp());
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -879,7 +879,8 @@ public class CloudWatchMetricsQueryHandler {
|
||||
xml.elem("StateValue", a.getStateValue())
|
||||
.elem("StateReason", a.getStateReason())
|
||||
.elem("StateReasonData", a.getStateReasonData())
|
||||
.elem("StateUpdatedTimestamp", Instant.ofEpochSecond(a.getStateUpdatedTimestamp()).toString());
|
||||
.elem("StateUpdatedTimestamp", Instant.ofEpochSecond(a.getStateUpdatedTimestamp()).toString())
|
||||
.elem("StateTransitionedTimestamp", Instant.ofEpochSecond(a.lastTransitionTimestamp()).toString());
|
||||
}
|
||||
|
||||
private void toAlarmMetricsXml(XmlBuilder xml, List<AlarmMetricDataQuery> metrics) {
|
||||
|
||||
+21
-5
@@ -433,7 +433,10 @@ public class CloudWatchMetricsService {
|
||||
alarm.setStateReason(previous.getStateReason());
|
||||
alarm.setStateReasonData(previous.getStateReasonData());
|
||||
alarm.setStateUpdatedTimestamp(previous.getStateUpdatedTimestamp());
|
||||
alarm.setStateTransitionedTimestamp(previous.getStateTransitionedTimestamp());
|
||||
alarm.setTags(new HashMap<>(previous.getTags()));
|
||||
} else {
|
||||
alarm.setStateTransitionedTimestamp(alarm.getStateUpdatedTimestamp());
|
||||
}
|
||||
if (alarm.getAlarmArn() == null) {
|
||||
alarm.setAlarmArn(regionResolver.buildArn("cloudwatch", region, "alarm:" + name));
|
||||
@@ -465,7 +468,8 @@ public class CloudWatchMetricsService {
|
||||
/** The alarm as history items show it: AWS's timestamp strings, without state reasons, tags or Floci's bookkeeping. */
|
||||
private static ObjectNode snapshot(Alarm alarm) {
|
||||
ObjectNode node = MAPPER.valueToTree(alarm);
|
||||
node.remove(List.of("region", "tags", "stateReason", "stateReasonData", "alarmType"));
|
||||
node.remove(List.of("region", "tags", "stateReason", "stateReasonData", "alarmType",
|
||||
"stateTransitionedTimestamp"));
|
||||
node.put("alarmConfigurationUpdatedTimestamp", AlarmSnsNotifier.TIMESTAMP_FORMAT.format(
|
||||
Instant.ofEpochSecond(alarm.getAlarmConfigurationUpdatedTimestamp())));
|
||||
node.put("stateUpdatedTimestamp", AlarmSnsNotifier.TIMESTAMP_FORMAT.format(
|
||||
@@ -630,7 +634,7 @@ public class CloudWatchMetricsService {
|
||||
}
|
||||
|
||||
public void setAlarmState(String alarmName, String stateValue, String stateReason, String stateReasonData, String region) {
|
||||
List<String> states = List.of("OK", "ALARM", "INSUFFICIENT_DATA");
|
||||
List<String> states = List.of("INSUFFICIENT_DATA", "ALARM", "OK");
|
||||
if (stateValue == null || !states.contains(stateValue)) {
|
||||
throw SmithyValidationErrors.validationError(stateValue == null ? SmithyValidationErrors.notNull("stateValue")
|
||||
: SmithyValidationErrors.notInEnum(stateValue, "stateValue", states));
|
||||
@@ -672,13 +676,21 @@ public class CloudWatchMetricsService {
|
||||
ObjectNode data = MAPPER.createObjectNode().put("version", "1.0");
|
||||
data.set("oldState", stateNode(oldState, alarm.getStateReason(), alarm.getStateReasonData()));
|
||||
data.set("newState", stateNode(state, reason, reasonData));
|
||||
Instant now = Instant.now();
|
||||
alarm.setStateValue(state);
|
||||
alarm.setStateReason(reason);
|
||||
alarm.setStateReasonData(reasonData);
|
||||
alarm.setStateUpdatedTimestamp(Instant.now().getEpochSecond());
|
||||
if (alarm.getStateTransitionedTimestamp() == 0) {
|
||||
// Stored before transitions were recorded: its last state update is the best known transition.
|
||||
alarm.setStateTransitionedTimestamp(alarm.getStateUpdatedTimestamp());
|
||||
}
|
||||
alarm.setStateUpdatedTimestamp(now.getEpochSecond());
|
||||
if (!state.equals(oldState)) {
|
||||
alarm.setStateTransitionedTimestamp(now.getEpochSecond());
|
||||
}
|
||||
alarmStore.put(region + "::" + alarm.getAlarmName(), alarm);
|
||||
if (!state.equals(oldState)) {
|
||||
recordHistory(alarm, region, "StateUpdate", "Alarm updated from " + oldState + " to " + state, data);
|
||||
recordHistory(alarm, region, "StateUpdate", "Alarm updated from " + oldState + " to " + state, data, now);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -699,7 +711,11 @@ public class CloudWatchMetricsService {
|
||||
|
||||
/** Called only under this service's monitor, which also guards the sequence and the prune deadline. */
|
||||
private void recordHistory(Alarm alarm, String region, String type, String summary, ObjectNode data) {
|
||||
Instant now = Instant.now();
|
||||
recordHistory(alarm, region, type, summary, data, Instant.now());
|
||||
}
|
||||
|
||||
/** As above, stamped with {@code now}: a state change passes the instant it gave the alarm. */
|
||||
private void recordHistory(Alarm alarm, String region, String type, String summary, ObjectNode data, Instant now) {
|
||||
if (!now.isBefore(nextHistoryPrune)) {
|
||||
long cutoffMillis = now.minus(HISTORY_RETENTION).toEpochMilli();
|
||||
deleteInEveryAccount(historyStore, item -> item.timestamp() < cutoffMillis);
|
||||
|
||||
@@ -30,6 +30,7 @@ public abstract class Alarm {
|
||||
private String stateReason = "Unchecked";
|
||||
private String stateReasonData;
|
||||
private long stateUpdatedTimestamp;
|
||||
private long stateTransitionedTimestamp;
|
||||
private Map<String, String> tags = new HashMap<>();
|
||||
private String region;
|
||||
|
||||
@@ -78,6 +79,15 @@ public abstract class Alarm {
|
||||
public long getStateUpdatedTimestamp() { return stateUpdatedTimestamp; }
|
||||
public void setStateUpdatedTimestamp(long stateUpdatedTimestamp) { this.stateUpdatedTimestamp = stateUpdatedTimestamp; }
|
||||
|
||||
/** When StateValue last changed; 0 for an alarm stored before this was recorded. */
|
||||
public long getStateTransitionedTimestamp() { return stateTransitionedTimestamp; }
|
||||
public void setStateTransitionedTimestamp(long timestamp) { this.stateTransitionedTimestamp = timestamp; }
|
||||
|
||||
/** The StateTransitionedTimestamp to report: an alarm stored without one reports its last state update. */
|
||||
public long lastTransitionTimestamp() {
|
||||
return stateTransitionedTimestamp > 0 ? stateTransitionedTimestamp : stateUpdatedTimestamp;
|
||||
}
|
||||
|
||||
public Map<String, String> getTags() { return tags; }
|
||||
public void setTags(Map<String, String> tags) { this.tags = tags; }
|
||||
|
||||
|
||||
+12
@@ -49,6 +49,18 @@ class CloudWatchAlarmQueryHandlerTest {
|
||||
assertEquals(List.of("ok-action"), alarm.getOkActions());
|
||||
assertEquals(List.of("missing-action"), alarm.getInsufficientDataActions());
|
||||
assertEquals(Map.of("team", "metrics"), alarm.getTags());
|
||||
|
||||
MultivaluedMap<String, String> describe = new MultivaluedHashMap<>();
|
||||
describe.putSingle("AlarmTypes.member.1", "MetricAlarm");
|
||||
describe.putSingle("AlarmTypes.member.2", "CompositeAlarm");
|
||||
String xml = (String) handler.handle("DescribeAlarms", describe, region).getEntity();
|
||||
String updated = Instant.ofEpochSecond(alarm.getStateUpdatedTimestamp()).toString();
|
||||
assertTrue(xml.contains("<StateTransitionedTimestamp>" + updated + "</StateTransitionedTimestamp>"), xml);
|
||||
|
||||
alarm.setStateTransitionedTimestamp(100);
|
||||
xml = (String) handler.handle("DescribeAlarms", describe, region).getEntity();
|
||||
assertTrue(xml.contains("<StateUpdatedTimestamp>" + updated + "</StateUpdatedTimestamp>"), xml);
|
||||
assertTrue(xml.contains("<StateTransitionedTimestamp>1970-01-01T00:01:40Z</StateTransitionedTimestamp>"), xml);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+29
-1
@@ -41,10 +41,11 @@ class CloudWatchMetricsJsonHandlerTest {
|
||||
private static final Instant EPOCH_OLD = EPOCH_NOW.minusSeconds(86400);
|
||||
|
||||
private CloudWatchMetricsJsonHandler handler;
|
||||
private CloudWatchMetricsService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
CloudWatchMetricsService service = new CloudWatchMetricsService(
|
||||
service = new CloudWatchMetricsService(
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000")
|
||||
@@ -347,6 +348,33 @@ class CloudWatchMetricsJsonHandlerTest {
|
||||
assertEquals("Count", alarm.get("Unit").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeAlarms_reportsStateTransitionedTimestampForBothAlarmKinds() {
|
||||
handler.handle("PutMetricAlarm", alarmRequest("TransitionedMetric"), REGION);
|
||||
ObjectNode composite = MAPPER.createObjectNode();
|
||||
composite.put("AlarmName", "TransitionedComposite");
|
||||
composite.put("AlarmRule", "ALARM(TransitionedMetric)");
|
||||
handler.handle("PutCompositeAlarm", composite, REGION);
|
||||
ObjectNode describe = MAPPER.createObjectNode();
|
||||
describe.putArray("AlarmTypes").add("MetricAlarm").add("CompositeAlarm");
|
||||
|
||||
ObjectNode response = (ObjectNode) handler.handle("DescribeAlarms", describe, REGION).getEntity();
|
||||
|
||||
for (String kind : List.of("MetricAlarms", "CompositeAlarms")) {
|
||||
JsonNode alarm = response.get(kind).get(0);
|
||||
assertTrue(alarm.has("StateTransitionedTimestamp"), kind + ": " + alarm);
|
||||
assertEquals(alarm.get("StateUpdatedTimestamp").asLong(), alarm.get("StateTransitionedTimestamp").asLong());
|
||||
}
|
||||
|
||||
service.describeAlarms(List.of("TransitionedMetric"), null, REGION).getFirst().setStateTransitionedTimestamp(100);
|
||||
service.describeCompositeAlarms(List.of("TransitionedComposite"), null, REGION).getFirst()
|
||||
.setStateTransitionedTimestamp(100);
|
||||
response = (ObjectNode) handler.handle("DescribeAlarms", describe, REGION).getEntity();
|
||||
for (String kind : List.of("MetricAlarms", "CompositeAlarms")) {
|
||||
assertEquals(100, response.get(kind).get(0).get("StateTransitionedTimestamp").asLong(), kind);
|
||||
}
|
||||
}
|
||||
|
||||
// AWS sends every alarm collection even when it is empty. The CLI's text output writes a
|
||||
// None line for each paginator result key missing from the page (floci-io/floci#6362).
|
||||
@Test
|
||||
|
||||
+88
-2
@@ -7,7 +7,9 @@ import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Alarm;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.AlarmHistoryItem;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.CompositeAlarm;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
|
||||
@@ -67,6 +69,77 @@ class CloudWatchMetricsServiceTest {
|
||||
assertNotSame(original.getTags(), result.getTags());
|
||||
}
|
||||
|
||||
// AWS: StateTransitionedTimestamp is when StateValue last changed; StateUpdatedTimestamp moves
|
||||
// on any state update, even one that keeps the value.
|
||||
@Test
|
||||
void stateTransitionedTimestampMovesOnlyWhenTheStateValueChanges() throws Exception {
|
||||
MetricAlarm alarm = new MetricAlarm();
|
||||
alarm.setAlarmName("transitions");
|
||||
service.putMetricAlarm(alarm, REGION);
|
||||
assertEquals(alarm.getStateUpdatedTimestamp(), alarm.getStateTransitionedTimestamp());
|
||||
|
||||
alarm.setStateUpdatedTimestamp(100);
|
||||
alarm.setStateTransitionedTimestamp(100);
|
||||
service.setAlarmState("transitions", "INSUFFICIENT_DATA", "same state", null, REGION);
|
||||
assertTrue(alarm.getStateUpdatedTimestamp() > 100);
|
||||
assertEquals(100, alarm.getStateTransitionedTimestamp());
|
||||
|
||||
service.setAlarmState("transitions", "ALARM", "breached", null, REGION);
|
||||
long transitioned = alarm.getStateTransitionedTimestamp();
|
||||
assertTrue(transitioned > 100);
|
||||
|
||||
alarm.setStateTransitionedTimestamp(200);
|
||||
MetricAlarm replacement = new MetricAlarm();
|
||||
replacement.setAlarmName("transitions");
|
||||
service.putMetricAlarm(replacement, REGION);
|
||||
assertEquals(200, service.describeAlarms(List.of("transitions"), null, REGION).getFirst()
|
||||
.getStateTransitionedTimestamp());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCompositeTransitionMovesItsStateTransitionedTimestamp() {
|
||||
MetricAlarm child = new MetricAlarm();
|
||||
child.setAlarmName("child");
|
||||
service.putMetricAlarm(child, REGION);
|
||||
CompositeAlarm parent = new CompositeAlarm();
|
||||
parent.setAlarmName("parent");
|
||||
parent.setAlarmRule("ALARM(child)");
|
||||
service.putCompositeAlarm(parent, REGION);
|
||||
CompositeAlarm stored = service.describeCompositeAlarms(List.of("parent"), null, REGION).getFirst();
|
||||
assertEquals("OK", stored.getStateValue());
|
||||
stored.setStateTransitionedTimestamp(100);
|
||||
|
||||
service.setAlarmState("child", "ALARM", "breached", null, REGION);
|
||||
assertEquals("ALARM", stored.getStateValue());
|
||||
assertTrue(stored.getStateTransitionedTimestamp() > 100);
|
||||
}
|
||||
|
||||
// A stored alarm without a transition time keeps reporting its last state update as the
|
||||
// transition when a same-state SetAlarmState moves StateUpdatedTimestamp.
|
||||
@Test
|
||||
void aSameStateUpdateOfAnAlarmStoredWithoutATransitionKeepsItsLastTransition() {
|
||||
MetricAlarm alarm = new MetricAlarm();
|
||||
alarm.setAlarmName("legacy");
|
||||
service.putMetricAlarm(alarm, REGION);
|
||||
service.setAlarmState("legacy", "ALARM", "breached", null, REGION);
|
||||
alarm.setStateTransitionedTimestamp(0);
|
||||
alarm.setStateUpdatedTimestamp(1000);
|
||||
|
||||
service.setAlarmState("legacy", "ALARM", "still breached", null, REGION);
|
||||
|
||||
assertTrue(alarm.getStateUpdatedTimestamp() > 1000);
|
||||
assertEquals(1000, alarm.lastTransitionTimestamp());
|
||||
}
|
||||
|
||||
// Alarms stored before StateTransitionedTimestamp existed report their last state update.
|
||||
@Test
|
||||
void anAlarmStoredWithoutATransitionTimestampReportsItsLastStateUpdate() throws Exception {
|
||||
Alarm legacy = new ObjectMapper().readValue(
|
||||
"{\"alarmType\":\"MetricAlarm\",\"alarmName\":\"old\",\"stateUpdatedTimestamp\":123}", Alarm.class);
|
||||
assertEquals(0, legacy.getStateTransitionedTimestamp());
|
||||
assertEquals(123, legacy.lastTransitionTimestamp());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@NullSource
|
||||
@ValueSource(strings = {"", "alarm", "UNKNOWN"})
|
||||
@@ -82,7 +155,7 @@ class CloudWatchMetricsServiceTest {
|
||||
assertEquals(value == null
|
||||
? "1 validation error detected: Value null at 'stateValue' failed to satisfy constraint: Member must not be null"
|
||||
: "1 validation error detected: Value '" + value + "' at 'stateValue' failed to satisfy constraint: "
|
||||
+ "Member must satisfy enum value set: [OK, ALARM, INSUFFICIENT_DATA]", error.getMessage());
|
||||
+ "Member must satisfy enum value set: [INSUFFICIENT_DATA, ALARM, OK]", error.getMessage());
|
||||
assertEquals("OK", alarm.getStateValue());
|
||||
assertEquals("preserved", alarm.getStateReason());
|
||||
assertEquals("{}", alarm.getStateReasonData());
|
||||
@@ -477,7 +550,8 @@ class CloudWatchMetricsServiceTest {
|
||||
assertEquals("INSUFFICIENT_DATA", createdAlarm.path("stateValue").asText());
|
||||
assertEquals(created, createdAlarm.path("alarmConfigurationUpdatedTimestamp").asText());
|
||||
assertTrue(created.endsWith("+0000"));
|
||||
for (String hidden : List.of("region", "tags", "stateReason", "stateReasonData", "alarmType", "unit")) {
|
||||
for (String hidden : List.of("region", "tags", "stateReason", "stateReasonData", "alarmType", "unit",
|
||||
"stateTransitionedTimestamp")) {
|
||||
assertFalse(createdAlarm.has(hidden), hidden);
|
||||
}
|
||||
|
||||
@@ -519,6 +593,18 @@ class CloudWatchMetricsServiceTest {
|
||||
.items().isEmpty());
|
||||
}
|
||||
|
||||
// A state change's history entry and the alarm's StateTransitionedTimestamp come from the same instant.
|
||||
@Test
|
||||
void aStateUpdateHistoryEntryIsStampedWithTheAlarmsTransitionTime() {
|
||||
putAlarm("stamped");
|
||||
service.setAlarmState("stamped", "ALARM", "breached", null, REGION);
|
||||
|
||||
MetricAlarm alarm = service.describeAlarms(List.of("stamped"), null, REGION).getFirst();
|
||||
AlarmHistoryItem entry = history("stamped", null, "StateUpdate", null, null, null, null).getFirst();
|
||||
assertEquals(alarm.getStateTransitionedTimestamp(), entry.timestamp() / 1000);
|
||||
assertEquals(alarm.getStateUpdatedTimestamp(), entry.timestamp() / 1000);
|
||||
}
|
||||
|
||||
@Test
|
||||
void historyPagesFollowNextTokenInBothDirections() {
|
||||
putAlarm("paged");
|
||||
|
||||
Reference in new issue
Block a user