mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(cloudwatch): record alarm history and serve DescribeAlarmHistory (#6670)
This commit is contained in:
1 parent
ed77a1d4ee
commit
989f714c21
17 files changed
+1037
-48
No files matched your search
+3
-9
@@ -5,7 +5,6 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
|
||||
@@ -14,6 +13,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.LogsMetri
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.ProvisionContext;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.model.MetricFilter;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;
|
||||
import io.github.hectorvent.floci.testing.StorageFactories;
|
||||
import jakarta.enterprise.event.Event;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
@@ -178,16 +178,10 @@ class CloudWatchLogsMetricFilterStorageReloadTest {
|
||||
}
|
||||
|
||||
private Services open(String mode, String account) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.defaultAccountId()).thenReturn(account);
|
||||
when(config.storage().persistentPath()).thenReturn(directory.toString());
|
||||
when(config.storage().wal().compactionIntervalMs()).thenReturn(3_600_000L);
|
||||
EmulatorConfig config = StorageFactories.config(directory, account);
|
||||
when(config.services().cloudwatchlogs().maxEventsPerQuery()).thenReturn(10_000);
|
||||
when(config.services().cloudwatchlogs().maxStoredEvents()).thenReturn(10_000);
|
||||
ServiceConfigAccess access = mock(ServiceConfigAccess.class);
|
||||
when(access.storageMode(anyString())).thenReturn(mode);
|
||||
when(access.storageFlushInterval(anyString())).thenReturn(3_600_000L);
|
||||
return new Services(new StorageFactory(config, access), config, account);
|
||||
return new Services(StorageFactories.open(config, mode), config, account);
|
||||
}
|
||||
|
||||
private static class Services implements AutoCloseable {
|
||||
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.testing.PartitionCleanup;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.net.URI;
|
||||
import java.time.Instant;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@QuarkusTest
|
||||
class CloudWatchAlarmHistoryIntegrationTest {
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String SCOPE =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261026/us-east-1/monitoring/aws4_request";
|
||||
private static final String RESULT = "DescribeAlarmHistoryResponse.DescribeAlarmHistoryResult.";
|
||||
|
||||
@TestHTTPResource
|
||||
URI baseUri;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void bothProtocolsListManualTransitionsNewestFirst(boolean json) throws Exception {
|
||||
String name = "wire-history-" + Long.toString(System.nanoTime(), 36);
|
||||
call(json, "PutMetricAlarm", Map.of("AlarmName", name, "MetricName", "Depth", "Namespace", "Floci/History",
|
||||
"Statistic", "Maximum", "Period", 60, "EvaluationPeriods", 1, "Threshold", 1,
|
||||
"ComparisonOperator", "GreaterThanOrEqualToThreshold", "TreatMissingData", "ignore"))
|
||||
.then().statusCode(200);
|
||||
for (String state : List.of("OK", "ALARM", "OK")) {
|
||||
call(json, "SetAlarmState", Map.of("AlarmName", name, "StateValue", state, "StateReason", "manual"))
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
Response history = call(json, "DescribeAlarmHistory", Map.of("AlarmName", name,
|
||||
"HistoryItemType", "StateUpdate"));
|
||||
history.then().statusCode(200);
|
||||
assertEquals(List.of("Alarm updated from ALARM to OK", "Alarm updated from OK to ALARM",
|
||||
"Alarm updated from INSUFFICIENT_DATA to OK"), json
|
||||
? history.jsonPath().getList("AlarmHistoryItems.HistorySummary")
|
||||
: history.xmlPath().getList(RESULT + "AlarmHistoryItems.member.HistorySummary"));
|
||||
String type = json ? history.jsonPath().getString("AlarmHistoryItems[0].AlarmType")
|
||||
: history.xmlPath().getString(RESULT + "AlarmHistoryItems.member[0].AlarmType");
|
||||
assertEquals("MetricAlarm", type);
|
||||
|
||||
Response first = call(json, "DescribeAlarmHistory", Map.of("AlarmName", name, "MaxRecords", 1));
|
||||
first.then().statusCode(200);
|
||||
String token = json ? first.jsonPath().getString("NextToken")
|
||||
: first.xmlPath().getString(RESULT + "NextToken");
|
||||
assertFalse(token == null || token.isEmpty());
|
||||
Response second = call(json, "DescribeAlarmHistory", Map.of("AlarmName", name, "MaxRecords", 1,
|
||||
"NextToken", token));
|
||||
assertEquals("Alarm updated from OK to ALARM", json
|
||||
? second.jsonPath().getString("AlarmHistoryItems[0].HistorySummary")
|
||||
: second.xmlPath().getString(RESULT + "AlarmHistoryItems.member.HistorySummary"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void errorsCarryEachProtocolsCode(boolean json) throws Exception {
|
||||
Instant start = Instant.parse("2026-10-26T16:21:49.900Z");
|
||||
Instant end = Instant.parse("2026-10-26T16:21:49.500Z");
|
||||
Response reversed = call(json, "DescribeAlarmHistory", json
|
||||
? Map.of("StartDate", start.toEpochMilli() / 1000.0, "EndDate", end.toEpochMilli() / 1000.0)
|
||||
: Map.of("StartDate", start.toString(), "EndDate", end.toString()));
|
||||
reversed.then().statusCode(400);
|
||||
assertEquals(json ? "InvalidParameterValueException" : "InvalidParameterValue", errorCode(json, reversed));
|
||||
assertEquals("Start date Mon Oct 26 16:21:49 UTC 2026 must be before end date Mon Oct 26 16:21:49 UTC 2026",
|
||||
errorMessage(json, reversed));
|
||||
|
||||
Response malformed = call(json, "DescribeAlarmHistory", Map.of("MaxRecords", "abc"));
|
||||
malformed.then().statusCode(400);
|
||||
assertEquals("MalformedInput", errorCode(json, malformed));
|
||||
|
||||
Response token = call(json, "DescribeAlarmHistory", Map.of("NextToken", "bogus"));
|
||||
token.then().statusCode(400);
|
||||
assertEquals("InvalidNextToken", errorCode(json, token));
|
||||
assertEquals("Invalid NextToken : bogus", errorMessage(json, token));
|
||||
|
||||
Response scan = call(json, "DescribeAlarmHistory", Map.of("ScanBy", "Bogus"));
|
||||
scan.then().statusCode(400);
|
||||
assertEquals("1 validation error detected: Value 'Bogus' at 'scanBy' failed to satisfy constraint: "
|
||||
+ "Member must satisfy enum value set: [TimestampAscending, TimestampDescending]",
|
||||
errorMessage(json, scan));
|
||||
}
|
||||
|
||||
private String errorCode(boolean json, Response response) {
|
||||
return json ? response.jsonPath().getString("__type") : response.xmlPath().getString("ErrorResponse.Error.Code");
|
||||
}
|
||||
|
||||
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<String, ?> body)
|
||||
throws JsonProcessingException {
|
||||
if ("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)
|
||||
.header("X-Amz-Target", "GraniteServiceVersion20100801.DeleteAlarms")
|
||||
.body(MAPPER.valueToTree(Map.of("AlarmNames", List.of(name))).toString())
|
||||
.post("/").then().statusCode(200));
|
||||
}
|
||||
if (json) {
|
||||
return given().contentType("application/x-amz-json-1.0").header("Authorization", SCOPE)
|
||||
.header("X-Amz-Target", "GraniteServiceVersion20100801." + operation)
|
||||
.body(MAPPER.writeValueAsString(body)).post("/");
|
||||
}
|
||||
Map<String, Object> form = new LinkedHashMap<>();
|
||||
form.put("Action", operation);
|
||||
form.putAll(body);
|
||||
return given().contentType("application/x-www-form-urlencoded").header("Authorization", SCOPE)
|
||||
.formParams(form).post("/");
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.AlarmHistoryItem;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import io.github.hectorvent.floci.testing.StorageFactories;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class CloudWatchAlarmHistoryStorageReloadTest {
|
||||
private static final String ACCOUNT = "111111111111";
|
||||
private static final String REGION = "eu-west-1";
|
||||
|
||||
@TempDir Path directory;
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"persistent", "hybrid", "wal"})
|
||||
void historyOfADeletedAlarmSurvivesReloadAndKeepsAppendingAndPaging(String mode) {
|
||||
StorageFactory first = StorageFactories.open(directory, mode, ACCOUNT);
|
||||
MetricAlarm alarm = new MetricAlarm();
|
||||
alarm.setAlarmName("reloaded");
|
||||
List<AlarmHistoryItem> before;
|
||||
try {
|
||||
CloudWatchMetricsService service = new CloudWatchMetricsService(first, new RegionResolver(REGION, ACCOUNT));
|
||||
service.putMetricAlarm(alarm, REGION);
|
||||
service.setAlarmState("reloaded", "ALARM", "breached", "{\"x\":1}", REGION);
|
||||
service.deleteAlarms(List.of("reloaded"), REGION);
|
||||
before = service.describeAlarmHistory("reloaded", null, null, null, null, null, null, null, REGION).items();
|
||||
} finally {
|
||||
first.shutdownAll();
|
||||
}
|
||||
assertEquals(3, before.size());
|
||||
|
||||
StorageFactory second = StorageFactories.open(directory, mode, ACCOUNT);
|
||||
List<AlarmHistoryItem> pages = new ArrayList<>();
|
||||
try {
|
||||
CloudWatchMetricsService service = new CloudWatchMetricsService(second, new RegionResolver(REGION, ACCOUNT));
|
||||
service.putMetricAlarm(alarm, REGION);
|
||||
String token = null;
|
||||
do {
|
||||
PaginatedResult<AlarmHistoryItem> page = service.describeAlarmHistory(
|
||||
"reloaded", null, null, null, null, 2, token, null, REGION);
|
||||
pages.addAll(page.items());
|
||||
token = page.nextToken();
|
||||
} while (token != null);
|
||||
} finally {
|
||||
second.shutdownAll();
|
||||
}
|
||||
|
||||
assertEquals(4, pages.size());
|
||||
assertEquals("Alarm \"reloaded\" created", pages.getFirst().historySummary());
|
||||
assertEquals(before, pages.subList(1, 4));
|
||||
}
|
||||
}
|
||||
+70
@@ -1,13 +1,21 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.AwsNamespaces;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.XmlParser;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Alarm;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.NodeList;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -42,4 +50,66 @@ class CloudWatchAlarmQueryHandlerTest {
|
||||
assertEquals(List.of("missing-action"), alarm.getInsufficientDataActions());
|
||||
assertEquals(Map.of("team", "metrics"), alarm.getTags());
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeAlarmHistoryRendersXmlItemsAndPages() throws Exception {
|
||||
String region = "us-east-1";
|
||||
CloudWatchMetricsService service = new CloudWatchMetricsService(new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new RegionResolver(region, "123456789012"));
|
||||
CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(service, null, null);
|
||||
MultivaluedMap<String, String> put = new MultivaluedHashMap<>();
|
||||
put.putSingle("AlarmName", "query-history");
|
||||
handler.handle("PutMetricAlarm", put, region);
|
||||
for (String state : List.of("OK", "ALARM")) {
|
||||
MultivaluedMap<String, String> set = new MultivaluedHashMap<>();
|
||||
set.putSingle("AlarmName", "query-history");
|
||||
set.putSingle("StateValue", state);
|
||||
set.putSingle("StateReason", "manual");
|
||||
handler.handle("SetAlarmState", set, region);
|
||||
}
|
||||
MultivaluedMap<String, String> request = new MultivaluedHashMap<>();
|
||||
request.putSingle("AlarmName", "query-history");
|
||||
request.putSingle("AlarmTypes.member.1", "MetricAlarm");
|
||||
request.putSingle("HistoryItemType", "StateUpdate");
|
||||
request.putSingle("MaxRecords", "1");
|
||||
|
||||
Document first = XmlParser.parseDocument((String) handler.handle("DescribeAlarmHistory", request, region)
|
||||
.getEntity());
|
||||
assertEquals(AwsNamespaces.CW, first.getDocumentElement().getNamespaceURI());
|
||||
assertEquals("DescribeAlarmHistoryResponse", first.getDocumentElement().getLocalName());
|
||||
assertEquals(1, elements(first, "AlarmHistoryItems").getLength());
|
||||
assertEquals(1, elements(first, "member").getLength());
|
||||
assertEquals("query-history", text(first, "AlarmName"));
|
||||
assertEquals("MetricAlarm", text(first, "AlarmType"));
|
||||
assertEquals("StateUpdate", text(first, "HistoryItemType"));
|
||||
assertEquals("Alarm updated from OK to ALARM", text(first, "HistorySummary"));
|
||||
assertTrue(text(first, "HistoryData").startsWith("{\"version\":\"1.0\""));
|
||||
Instant timestamp = Instant.parse(text(first, "Timestamp"));
|
||||
assertTrue(Duration.between(timestamp, Instant.now()).abs().toSeconds() < 60);
|
||||
String token = text(first, "NextToken");
|
||||
assertFalse(token.isEmpty());
|
||||
|
||||
request.putSingle("NextToken", token);
|
||||
Document last = XmlParser.parseDocument((String) handler.handle("DescribeAlarmHistory", request, region)
|
||||
.getEntity());
|
||||
assertEquals("Alarm updated from INSUFFICIENT_DATA to OK", text(last, "HistorySummary"));
|
||||
assertEquals(0, elements(last, "NextToken").getLength());
|
||||
|
||||
MultivaluedMap<String, String> reversed = new MultivaluedHashMap<>();
|
||||
reversed.putSingle("StartDate", "2026-10-26T16:23:10Z");
|
||||
reversed.putSingle("EndDate", "2026-10-26T16:22:10Z");
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> handler.handle("DescribeAlarmHistory", reversed, region));
|
||||
assertEquals("InvalidParameterValue", error.getErrorCode());
|
||||
assertEquals("Start date Mon Oct 26 16:23:10 UTC 2026 must be before end date Mon Oct 26 16:22:10 UTC 2026",
|
||||
error.getMessage());
|
||||
}
|
||||
|
||||
private static NodeList elements(Document document, String name) {
|
||||
return document.getElementsByTagNameNS(AwsNamespaces.CW, name);
|
||||
}
|
||||
|
||||
private static String text(Document document, String name) {
|
||||
return elements(document, name).item(0).getTextContent();
|
||||
}
|
||||
}
|
||||
+59
@@ -456,4 +456,63 @@ class CloudWatchMetricsJsonHandlerTest {
|
||||
assertTrue(body.get("MetricDataResults").get(0).get("Values").size() > 0,
|
||||
"an explicit JSON null Unit must not filter every datapoint out");
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeAlarmHistoryReturnsAwsShapedItemsAndPages() {
|
||||
handler.handle("PutMetricAlarm", MAPPER.createObjectNode().put("AlarmName", "json-history"), REGION);
|
||||
for (String state : List.of("OK", "ALARM", "OK")) {
|
||||
handler.handle("SetAlarmState", MAPPER.createObjectNode().put("AlarmName", "json-history")
|
||||
.put("StateValue", state).put("StateReason", "manual"), REGION);
|
||||
}
|
||||
ObjectNode request = MAPPER.createObjectNode().put("AlarmName", "json-history")
|
||||
.put("HistoryItemType", "StateUpdate").put("MaxRecords", 2);
|
||||
request.putArray("AlarmTypes").add("MetricAlarm");
|
||||
|
||||
Response response = handler.handle("DescribeAlarmHistory", request, REGION);
|
||||
assertEquals(200, response.getStatus());
|
||||
ObjectNode body = (ObjectNode) response.getEntity();
|
||||
JsonNode items = body.get("AlarmHistoryItems");
|
||||
assertEquals(2, items.size());
|
||||
JsonNode newest = items.get(0);
|
||||
List<String> fields = new ArrayList<>();
|
||||
newest.fieldNames().forEachRemaining(fields::add);
|
||||
assertEquals(List.of("AlarmName", "AlarmType", "HistoryData", "HistoryItemType", "HistorySummary", "Timestamp"),
|
||||
fields);
|
||||
assertEquals("json-history", newest.get("AlarmName").asText());
|
||||
assertEquals("MetricAlarm", newest.get("AlarmType").asText());
|
||||
assertEquals("StateUpdate", newest.get("HistoryItemType").asText());
|
||||
assertEquals("Alarm updated from ALARM to OK", newest.get("HistorySummary").asText());
|
||||
assertTrue(newest.get("HistoryData").asText().startsWith("{\"version\":\"1.0\",\"oldState\""));
|
||||
assertTrue(newest.get("Timestamp").isDouble());
|
||||
assertTrue(Math.abs(newest.get("Timestamp").asDouble() - Instant.now().getEpochSecond()) < 60);
|
||||
assertTrue(body.get("NextToken").isTextual());
|
||||
|
||||
request.put("NextToken", body.get("NextToken").asText());
|
||||
ObjectNode last = (ObjectNode) handler.handle("DescribeAlarmHistory", request, REGION).getEntity();
|
||||
assertEquals("Alarm updated from INSUFFICIENT_DATA to OK",
|
||||
last.get("AlarmHistoryItems").get(0).get("HistorySummary").asText());
|
||||
assertFalse(last.has("NextToken"));
|
||||
|
||||
ObjectNode future = MAPPER.createObjectNode().put("AlarmName", "json-history")
|
||||
.put("StartDate", sdkTimestamp(Instant.now().plusSeconds(3600)));
|
||||
assertEquals(0, ((ObjectNode) handler.handle("DescribeAlarmHistory", future, REGION).getEntity())
|
||||
.get("AlarmHistoryItems").size());
|
||||
|
||||
ObjectNode distant = MAPPER.createObjectNode().put("AlarmName", "json-history")
|
||||
.put("HistoryItemType", "StateUpdate").put("EndDate", 253402300799L);
|
||||
assertEquals(3, ((ObjectNode) handler.handle("DescribeAlarmHistory", distant, REGION).getEntity())
|
||||
.get("AlarmHistoryItems").size(), "9999-12-31 is after every item");
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeAlarmHistoryRejectsAStartDateAfterTheEndDate() {
|
||||
ObjectNode request = MAPPER.createObjectNode()
|
||||
.put("StartDate", sdkTimestamp(Instant.parse("2026-10-26T16:23:10Z")))
|
||||
.put("EndDate", sdkTimestamp(Instant.parse("2026-10-26T16:22:10Z")));
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> handler.handle("DescribeAlarmHistory", request, REGION));
|
||||
assertEquals("InvalidParameterValueException", e.jsonType());
|
||||
assertEquals("Start date Mon Oct 26 16:23:10 UTC 2026 must be before end date Mon Oct 26 16:22:10 UTC 2026",
|
||||
e.getMessage());
|
||||
}
|
||||
}
|
||||
+300
@@ -1,9 +1,13 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
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.AlarmHistoryItem;
|
||||
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;
|
||||
@@ -13,7 +17,9 @@ import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.NullSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -24,6 +30,7 @@ class CloudWatchMetricsServiceTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String NAMESPACE = "MyApp/Metrics";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private CloudWatchMetricsService service;
|
||||
|
||||
@@ -400,6 +407,299 @@ class CloudWatchMetricsServiceTest {
|
||||
assertEquals("Threshold breached", updated.getStateReason());
|
||||
}
|
||||
|
||||
// ──────────────────────────── Alarm history ────────────────────────────
|
||||
|
||||
@Test
|
||||
void stateTransitionsAreRecordedNewestFirst() {
|
||||
putAlarm("history");
|
||||
service.setAlarmState("history", "OK", "initial", null, REGION);
|
||||
service.setAlarmState("history", "ALARM", "breached", "{\"value\":3}", REGION);
|
||||
service.setAlarmState("history", "OK", "recovered", null, REGION);
|
||||
|
||||
List<AlarmHistoryItem> items = history("history", null, "StateUpdate", null, null, null, null);
|
||||
assertEquals(List.of("Alarm updated from ALARM to OK", "Alarm updated from OK to ALARM",
|
||||
"Alarm updated from INSUFFICIENT_DATA to OK"), summaries(items));
|
||||
assertEquals("MetricAlarm", items.getFirst().alarmType());
|
||||
assertEquals("history", items.getFirst().alarmName());
|
||||
assertEquals("{\"version\":\"1.0\",\"oldState\":{\"stateValue\":\"OK\",\"stateReason\":\"initial\"},"
|
||||
+ "\"newState\":{\"stateValue\":\"ALARM\",\"stateReason\":\"breached\",\"stateReasonData\":{\"value\":3}}}",
|
||||
items.get(1).historyData());
|
||||
assertEquals("{\"version\":\"1.0\",\"oldState\":{\"stateValue\":\"ALARM\",\"stateReason\":\"breached\","
|
||||
+ "\"stateReasonData\":{\"value\":3}},\"newState\":{\"stateValue\":\"OK\",\"stateReason\":\"recovered\"}}",
|
||||
items.getFirst().historyData());
|
||||
assertTrue(items.get(0).timestamp() >= items.get(1).timestamp());
|
||||
}
|
||||
|
||||
@Test
|
||||
void settingTheCurrentStateRecordsNothingButUpdatesTheReason() {
|
||||
putAlarm("steady");
|
||||
service.setAlarmState("steady", "OK", "first", "not json", REGION);
|
||||
service.setAlarmState("steady", "OK", "again", null, REGION);
|
||||
|
||||
List<AlarmHistoryItem> items = history("steady", null, "StateUpdate", null, null, null, null);
|
||||
assertEquals(1, items.size());
|
||||
assertEquals("{\"version\":\"1.0\",\"oldState\":{\"stateValue\":\"INSUFFICIENT_DATA\",\"stateReason\":\"Unchecked\"},"
|
||||
+ "\"newState\":{\"stateValue\":\"OK\",\"stateReason\":\"first\",\"stateReasonData\":\"not json\"}}",
|
||||
items.getFirst().historyData());
|
||||
assertEquals("again", service.describeAlarms(List.of("steady"), null, REGION).getFirst().getStateReason());
|
||||
}
|
||||
|
||||
@Test
|
||||
void configurationChangesAreRecordedAndSurviveDeletion() throws Exception {
|
||||
MetricAlarm original = new MetricAlarm();
|
||||
original.setAlarmName("config");
|
||||
original.setAlarmDescription("original");
|
||||
original.setThreshold(1.0);
|
||||
original.setTags(new HashMap<>(Map.of("team", "metrics")));
|
||||
service.putMetricAlarm(original, REGION);
|
||||
String created = AlarmSnsNotifier.TIMESTAMP_FORMAT.format(
|
||||
Instant.ofEpochSecond(original.getAlarmConfigurationUpdatedTimestamp()));
|
||||
MetricAlarm updated = new MetricAlarm();
|
||||
updated.setAlarmName("config");
|
||||
updated.setAlarmDescription("updated");
|
||||
updated.setThreshold(2.0);
|
||||
updated.setUnit("Count");
|
||||
service.putMetricAlarm(updated, REGION);
|
||||
service.deleteAlarms(List.of("config", "never-existed"), REGION);
|
||||
|
||||
assertTrue(service.describeAlarms(List.of("config"), null, REGION).isEmpty());
|
||||
List<AlarmHistoryItem> items = history("config", null, "ConfigurationUpdate", null, null, null, null);
|
||||
assertEquals(List.of("Alarm \"config\" deleted", "Alarm \"config\" updated", "Alarm \"config\" created"),
|
||||
summaries(items));
|
||||
assertTrue(history("never-existed", null, null, null, null, null, null).isEmpty());
|
||||
|
||||
JsonNode create = MAPPER.readTree(items.get(2).historyData());
|
||||
assertEquals("1.0", create.path("version").asText());
|
||||
assertEquals("Create", create.path("type").asText());
|
||||
JsonNode createdAlarm = create.path("createdAlarm");
|
||||
assertEquals("original", createdAlarm.path("alarmDescription").asText());
|
||||
assertEquals(original.getAlarmArn(), createdAlarm.path("alarmArn").asText());
|
||||
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")) {
|
||||
assertFalse(createdAlarm.has(hidden), hidden);
|
||||
}
|
||||
|
||||
JsonNode update = MAPPER.readTree(items.get(1).historyData());
|
||||
assertEquals("Update", update.path("type").asText());
|
||||
assertEquals(2.0, update.path("updatedAlarm").path("threshold").asDouble());
|
||||
JsonNode originalFields = update.path("originalUpdatedFields");
|
||||
assertEquals("original", originalFields.path("alarmDescription").asText());
|
||||
assertEquals(1.0, originalFields.path("threshold").asDouble());
|
||||
assertTrue(originalFields.path("unit").isNull());
|
||||
assertFalse(originalFields.has("alarmName"));
|
||||
assertFalse(originalFields.has("stateValue"));
|
||||
|
||||
JsonNode delete = MAPPER.readTree(items.getFirst().historyData());
|
||||
assertEquals("Delete", delete.path("type").asText());
|
||||
assertEquals("updated", delete.path("deletedAlarm").path("alarmDescription").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void historyFiltersByItemTypeAndScansInEitherDirection() {
|
||||
putAlarm("filtered");
|
||||
service.setAlarmState("filtered", "OK", "initial", null, REGION);
|
||||
service.setAlarmState("filtered", "ALARM", "breached", null, REGION);
|
||||
|
||||
List<String> newestFirst = List.of("Alarm updated from OK to ALARM",
|
||||
"Alarm updated from INSUFFICIENT_DATA to OK", "Alarm \"filtered\" created");
|
||||
assertEquals(newestFirst, summaries(history("filtered", null, null, null, null, null, null)));
|
||||
assertEquals(newestFirst, summaries(history("filtered", List.of("MetricAlarm"), null, null, null, null,
|
||||
"TimestampDescending")));
|
||||
assertEquals(newestFirst.reversed(), summaries(history("filtered", null, null, null, null, null,
|
||||
"TimestampAscending")));
|
||||
assertEquals(List.of("Alarm \"filtered\" created"),
|
||||
summaries(history("filtered", null, "ConfigurationUpdate", null, null, null, null)));
|
||||
for (String neverRecorded : List.of("Action", "AlarmContributorStateUpdate", "AlarmContributorAction")) {
|
||||
assertTrue(history("filtered", null, neverRecorded, null, null, null, null).isEmpty());
|
||||
}
|
||||
assertTrue(history("filtered", List.of("CompositeAlarm"), null, null, null, null, null).isEmpty());
|
||||
assertTrue(service.describeAlarmHistory("filtered", null, null, null, null, null, null, null, "eu-west-1")
|
||||
.items().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void historyPagesFollowNextTokenInBothDirections() {
|
||||
putAlarm("paged");
|
||||
for (int i = 0; i < 55; i++) {
|
||||
service.setAlarmState("paged", i % 2 == 0 ? "ALARM" : "OK", "toggle " + i, null, REGION);
|
||||
}
|
||||
PaginatedResult<AlarmHistoryItem> first = service.describeAlarmHistory("paged", null, null, null, null,
|
||||
null, null, null, REGION);
|
||||
assertEquals(50, first.items().size());
|
||||
assertNotNull(first.nextToken());
|
||||
|
||||
for (String scanBy : List.of("TimestampDescending", "TimestampAscending")) {
|
||||
List<AlarmHistoryItem> collected = new ArrayList<>();
|
||||
String token = null;
|
||||
do {
|
||||
PaginatedResult<AlarmHistoryItem> page = service.describeAlarmHistory("paged", null, null, null, null,
|
||||
7, token, scanBy, REGION);
|
||||
assertTrue(page.items().size() <= 7);
|
||||
collected.addAll(page.items());
|
||||
token = page.nextToken();
|
||||
} while (token != null);
|
||||
List<AlarmHistoryItem> all = history("paged", null, null, null, null, 100, scanBy);
|
||||
assertEquals(56, all.size());
|
||||
assertEquals(all, collected);
|
||||
}
|
||||
assertEquals("Alarm \"paged\" created", history("paged", null, null, null, null, 1, "TimestampAscending")
|
||||
.getFirst().historySummary());
|
||||
}
|
||||
|
||||
@Test
|
||||
void foreignOrInvalidTokensAreHandledLikeAws() {
|
||||
putAlarm("tokens");
|
||||
service.setAlarmState("tokens", "OK", "initial", null, REGION);
|
||||
String descending = service.describeAlarmHistory("tokens", null, null, null, null, 1, null,
|
||||
null, REGION).nextToken();
|
||||
String ascending = service.describeAlarmHistory("tokens", null, null, null, null, 1, null,
|
||||
"TimestampAscending", REGION).nextToken();
|
||||
|
||||
PaginatedResult<AlarmHistoryItem> crossed = service.describeAlarmHistory("tokens", null, null, null, null,
|
||||
1, descending, "TimestampAscending", REGION);
|
||||
assertTrue(crossed.items().isEmpty());
|
||||
assertNull(crossed.nextToken());
|
||||
assertTrue(service.describeAlarmHistory("tokens", null, null, null, null, 1, ascending, null, REGION)
|
||||
.items().isEmpty());
|
||||
|
||||
AwsException error = assertThrows(AwsException.class, () -> service.describeAlarmHistory("tokens", null,
|
||||
null, null, null, null, "bogus", null, REGION));
|
||||
assertEquals("InvalidNextToken", error.getErrorCode());
|
||||
assertEquals("InvalidNextToken", error.jsonType());
|
||||
assertEquals("Invalid NextToken : bogus", error.getMessage());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void historyRequestsAreValidatedWithSmithyMessages() {
|
||||
String prefix = "1 validation error detected: ";
|
||||
assertHistoryRejected(prefix + "Value '0' at 'maxRecords' failed to satisfy constraint: "
|
||||
+ "Member must have value greater than or equal to 1", null, null, null, 0, null);
|
||||
assertHistoryRejected(prefix + "Value '101' at 'maxRecords' failed to satisfy constraint: "
|
||||
+ "Member must have value less than or equal to 100", null, null, null, 101, null);
|
||||
assertHistoryRejected(prefix + "Value 'Bogus' at 'historyItemType' failed to satisfy constraint: "
|
||||
+ "Member must satisfy enum value set: [AlarmContributorAction, AlarmContributorStateUpdate, Action, "
|
||||
+ "StateUpdate, ConfigurationUpdate]", null, null, "Bogus", null, null);
|
||||
assertHistoryRejected(prefix + "Value 'Bogus' at 'scanBy' failed to satisfy constraint: "
|
||||
+ "Member must satisfy enum value set: [TimestampAscending, TimestampDescending]",
|
||||
null, null, null, null, "Bogus");
|
||||
assertHistoryRejected(prefix + "Value '[Bogus]' at 'alarmTypes' failed to satisfy constraint: "
|
||||
+ "Member must satisfy constraint: [Member must satisfy enum value set: [MetricAlarm, CompositeAlarm]]",
|
||||
null, List.of("Bogus"), null, null, null);
|
||||
assertHistoryRejected(prefix + "Value '[LogAlarm]' at 'alarmTypes' failed to satisfy constraint: "
|
||||
+ "Member must satisfy constraint: [Member must satisfy enum value set: [MetricAlarm, CompositeAlarm]]",
|
||||
null, List.of("LogAlarm"), null, null, null);
|
||||
assertHistoryRejected(prefix + "Value '' at 'alarmName' failed to satisfy constraint: "
|
||||
+ "Member must have length greater than or equal to 1", "", null, null, null, null);
|
||||
assertHistoryRejected("2 validation errors detected: Value '' at 'alarmName' failed to satisfy constraint: "
|
||||
+ "Member must have length greater than or equal to 1; Value 'Bogus' at 'scanBy' failed to satisfy "
|
||||
+ "constraint: Member must satisfy enum value set: [TimestampAscending, TimestampDescending]",
|
||||
"", null, null, null, "Bogus");
|
||||
assertHistoryRejected("Alarm name must be provided to query history for alarm contributors.",
|
||||
null, null, "AlarmContributorStateUpdate", null, null);
|
||||
assertHistoryRejected("Alarm name must be provided to query history for alarm contributors.",
|
||||
null, null, "AlarmContributorAction", null, null);
|
||||
assertTrue(history("unknown", null, "AlarmContributorStateUpdate", null, null, null, null).isEmpty());
|
||||
}
|
||||
|
||||
private void assertHistoryRejected(String message, String name, List<String> types, String itemType,
|
||||
Integer max, String scanBy) {
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> service.describeAlarmHistory(name, types, itemType, null, null, max, null, scanBy, REGION));
|
||||
assertEquals("ValidationError", error.getErrorCode());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
assertEquals(message, error.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void startDateAfterEndDateIsAnInvalidParameterValue() {
|
||||
AwsException error = assertThrows(AwsException.class, () -> history(null, null, null,
|
||||
Instant.parse("2026-10-26T16:23:10Z"), Instant.parse("2026-10-26T16:22:10Z"), null, null));
|
||||
assertEquals("InvalidParameterValue", error.getErrorCode());
|
||||
assertEquals("InvalidParameterValueException", error.jsonType());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
assertEquals("Start date Mon Oct 26 16:23:10 UTC 2026 must be before end date Mon Oct 26 16:22:10 UTC 2026",
|
||||
error.getMessage());
|
||||
assertTrue(history(null, null, null, Instant.parse("2026-10-26T16:26:55.549900Z"),
|
||||
Instant.parse("2026-10-26T16:26:55.549100Z"), null, null).isEmpty(), "AWS compares whole milliseconds");
|
||||
}
|
||||
|
||||
@Test
|
||||
void datesFilterRecordedTimestampsAndExpiredHistoryIsDropped() {
|
||||
InMemoryStorage<String, AlarmHistoryItem> store = new InMemoryStorage<>();
|
||||
Instant now = Instant.now();
|
||||
String expiredKey = null;
|
||||
for (int daysAgo : List.of(40, 3, 2, 1)) {
|
||||
Instant at = now.minus(Duration.ofDays(daysAgo));
|
||||
long sequence = at.getEpochSecond() * 1_000_000 + at.getNano() / 1_000;
|
||||
String key = REGION + "::" + String.format("%020d", sequence);
|
||||
store.put(key, new AlarmHistoryItem(sequence, "dated",
|
||||
"MetricAlarm", at.toEpochMilli(), "StateUpdate", daysAgo + " days ago", "{}"));
|
||||
if (daysAgo == 40) {
|
||||
expiredKey = key;
|
||||
}
|
||||
}
|
||||
service = new CloudWatchMetricsService(new InMemoryStorage<>(), new InMemoryStorage<>(), store,
|
||||
new RegionResolver(REGION, "000000000000"), null);
|
||||
|
||||
assertEquals(List.of("1 days ago", "2 days ago", "3 days ago"),
|
||||
summaries(history("dated", null, null, null, null, null, null)));
|
||||
assertEquals(4, store.keys().size(), "a read hides expired history without deleting it");
|
||||
assertTrue(store.keys().contains(expiredKey));
|
||||
assertEquals(List.of("2 days ago"), summaries(history("dated", null, null,
|
||||
now.minus(Duration.ofDays(2)).minusSeconds(60), now.minus(Duration.ofDays(1)).minusSeconds(60),
|
||||
null, null)));
|
||||
assertEquals(List.of("1 days ago"), summaries(history("dated", null, null,
|
||||
now.minus(Duration.ofDays(1)).minusSeconds(60), null, null, null)));
|
||||
assertEquals(List.of("2 days ago", "3 days ago"), summaries(history("dated", null, null,
|
||||
null, now.minus(Duration.ofDays(2)).plusSeconds(60), null, null)));
|
||||
|
||||
putAlarm("pruner");
|
||||
assertFalse(store.keys().contains(expiredKey), "a write prunes expired history");
|
||||
assertEquals(4, store.keys().size());
|
||||
|
||||
store.put(expiredKey, new AlarmHistoryItem(0, "dated", "MetricAlarm",
|
||||
now.minus(Duration.ofDays(40)).toEpochMilli(), "StateUpdate", "40 days ago", "{}"));
|
||||
putAlarm("within-the-hour");
|
||||
assertTrue(store.keys().contains(expiredKey), "pruning runs at most once an hour");
|
||||
assertEquals(List.of("1 days ago", "2 days ago", "3 days ago"),
|
||||
summaries(history("dated", null, null, null, null, null, null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWriteInOneAccountPrunesExpiredHistoryOfEveryAccount() {
|
||||
InMemoryStorage<String, AlarmHistoryItem> raw = new InMemoryStorage<>();
|
||||
String foreignKey = "111111111111/" + REGION + "::00000000000000000001";
|
||||
raw.put(foreignKey, new AlarmHistoryItem(1, "foreign", "MetricAlarm",
|
||||
Instant.now().minus(Duration.ofDays(40)).toEpochMilli(), "StateUpdate", "expired", "{}"));
|
||||
service = new CloudWatchMetricsService(new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new AccountAwareStorageBackend<>(raw, null, "000000000000"),
|
||||
new RegionResolver(REGION, "000000000000"), null);
|
||||
|
||||
putAlarm("writer");
|
||||
|
||||
assertFalse(raw.keys().contains(foreignKey));
|
||||
assertEquals(1, raw.keys().size());
|
||||
}
|
||||
|
||||
private MetricAlarm putAlarm(String name) {
|
||||
MetricAlarm alarm = new MetricAlarm();
|
||||
alarm.setAlarmName(name);
|
||||
service.putMetricAlarm(alarm, REGION);
|
||||
return alarm;
|
||||
}
|
||||
|
||||
private List<AlarmHistoryItem> history(String name, List<String> types, String itemType,
|
||||
Instant start, Instant end, Integer max, String scanBy) {
|
||||
return service.describeAlarmHistory(name, types, itemType, start, end, max, null, scanBy, REGION).items();
|
||||
}
|
||||
|
||||
private static List<String> summaries(List<AlarmHistoryItem> items) {
|
||||
return items.stream().map(AlarmHistoryItem::historySummary).toList();
|
||||
}
|
||||
|
||||
@Test
|
||||
void setAlarmStateOnNonexistentAlarmThrowsResourceNotFound() {
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
|
||||
+35
@@ -1,11 +1,13 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
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.MetricAlarm;
|
||||
import io.github.hectorvent.floci.testing.ThreadStates;
|
||||
@@ -292,6 +294,39 @@ class CompositeAlarmServiceTest {
|
||||
() -> CompositeAlarmRule.parse(null)).getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void compositeHistoryIsListedOnlyForTheCompositeAlarmType() {
|
||||
put("aggregate", "TRUE");
|
||||
assertTrue(service.describeAlarmHistory("aggregate", null, null, null, null, null, null, null, REGION)
|
||||
.items().isEmpty());
|
||||
List<AlarmHistoryItem> items = service.describeAlarmHistory("aggregate", List.of("CompositeAlarm"), null,
|
||||
null, null, null, null, null, REGION).items();
|
||||
assertEquals(List.of("Alarm updated from INSUFFICIENT_DATA to ALARM", "Alarm \"aggregate\" created"),
|
||||
items.stream().map(AlarmHistoryItem::historySummary).toList());
|
||||
assertEquals(List.of("CompositeAlarm", "CompositeAlarm"), items.stream().map(AlarmHistoryItem::alarmType).toList());
|
||||
assertEquals(List.of("Alarm \"aggregate\" created", "Alarm updated from INSUFFICIENT_DATA to ALARM"),
|
||||
service.describeAlarmHistory("aggregate", List.of("CompositeAlarm"), null, null, null, null, null,
|
||||
"TimestampAscending", REGION).items().stream().map(AlarmHistoryItem::historySummary).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void childTransitionsRecordCompositeStateUpdates() throws Exception {
|
||||
MetricAlarm metric = new MetricAlarm();
|
||||
metric.setAlarmName("child");
|
||||
service.putMetricAlarm(metric, REGION);
|
||||
put("parent", "ALARM(child)");
|
||||
service.setAlarmState("child", "ALARM", "breached", null, REGION);
|
||||
|
||||
List<AlarmHistoryItem> items = service.describeAlarmHistory(null, List.of("MetricAlarm", "CompositeAlarm"),
|
||||
"StateUpdate", null, null, null, null, null, REGION).items();
|
||||
assertEquals(List.of("parent:Alarm updated from OK to ALARM", "child:Alarm updated from INSUFFICIENT_DATA to ALARM",
|
||||
"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());
|
||||
}
|
||||
|
||||
private CompositeAlarm put(String name, String rule) {
|
||||
CompositeAlarm alarm = new CompositeAlarm();
|
||||
alarm.setAlarmName(name);
|
||||
|
||||
+5
-21
@@ -2,12 +2,11 @@ package io.github.hectorvent.floci.services.identitystore;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.identitystore.model.Group;
|
||||
import io.github.hectorvent.floci.services.identitystore.model.Membership;
|
||||
import io.github.hectorvent.floci.services.identitystore.model.User;
|
||||
import io.github.hectorvent.floci.testing.StorageFactories;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
@@ -25,10 +24,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class IdentityStorePersistenceTest {
|
||||
private static final String STORE = "d-1234567890";
|
||||
@@ -36,17 +31,6 @@ class IdentityStorePersistenceTest {
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
private StorageFactory newFactory(Path dir, String mode) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.defaultAccountId()).thenReturn(GLOBAL_PARTITION);
|
||||
when(config.storage().persistentPath()).thenReturn(dir.toString());
|
||||
when(config.storage().wal().compactionIntervalMs()).thenReturn(3_600_000L);
|
||||
ServiceConfigAccess access = mock(ServiceConfigAccess.class);
|
||||
when(access.storageMode(anyString())).thenReturn(mode);
|
||||
when(access.storageFlushInterval(anyString())).thenReturn(3_600_000L);
|
||||
return new StorageFactory(config, access);
|
||||
}
|
||||
|
||||
private ObjectNode idRequest(String idField, String id) {
|
||||
ObjectNode request = mapper.createObjectNode();
|
||||
request.put("IdentityStoreId", STORE);
|
||||
@@ -114,13 +98,13 @@ class IdentityStorePersistenceTest {
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"persistent", "hybrid", "wal"})
|
||||
void usersGroupsAndMembershipsSurviveRestart(String mode, @TempDir Path dir) {
|
||||
StorageFactory firstFactory = newFactory(dir, mode);
|
||||
StorageFactory firstFactory = StorageFactories.open(dir, mode, GLOBAL_PARTITION);
|
||||
IdentityStoreService first = new IdentityStoreService(firstFactory, mapper);
|
||||
Seeded seeded = seed(first);
|
||||
|
||||
firstFactory.shutdownAll();
|
||||
|
||||
StorageFactory reopenedFactory = newFactory(dir, mode);
|
||||
StorageFactory reopenedFactory = StorageFactories.open(dir, mode, GLOBAL_PARTITION);
|
||||
IdentityStoreService reopened = new IdentityStoreService(reopenedFactory, mapper);
|
||||
assertReloaded(reopened, seeded);
|
||||
reopenedFactory.shutdownAll();
|
||||
@@ -129,7 +113,7 @@ class IdentityStorePersistenceTest {
|
||||
@Test
|
||||
void usersGroupsAndMembershipsSurviveWalReplayAfterCrash(@TempDir Path dirA, @TempDir Path dirB)
|
||||
throws IOException {
|
||||
StorageFactory crashedFactory = newFactory(dirA, "wal");
|
||||
StorageFactory crashedFactory = StorageFactories.open(dirA, "wal", GLOBAL_PARTITION);
|
||||
StorageFactory recoveredFactory = null;
|
||||
try {
|
||||
IdentityStoreService crashed = new IdentityStoreService(crashedFactory, mapper);
|
||||
@@ -152,7 +136,7 @@ class IdentityStorePersistenceTest {
|
||||
}
|
||||
}
|
||||
|
||||
recoveredFactory = newFactory(dirB, "wal");
|
||||
recoveredFactory = StorageFactories.open(dirB, "wal", GLOBAL_PARTITION);
|
||||
IdentityStoreService recovered = new IdentityStoreService(recoveredFactory, mapper);
|
||||
assertReloaded(recovered, seeded);
|
||||
} finally {
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package io.github.hectorvent.floci.testing;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Real {@link StorageFactory} instances over a test directory, for tests that shut one down and open
|
||||
* another on the same directory to see what a storage mode keeps. The WAL compaction and flush intervals
|
||||
* are an hour, so neither timer fires during a test.
|
||||
*/
|
||||
public final class StorageFactories {
|
||||
|
||||
private static final long AN_HOUR_MS = 3_600_000L;
|
||||
|
||||
private StorageFactories() {
|
||||
}
|
||||
|
||||
/** A factory whose every store uses {@code mode} under {@code directory}, scoped to {@code account}. */
|
||||
public static StorageFactory open(Path directory, String mode, String account) {
|
||||
return open(config(directory, account), mode);
|
||||
}
|
||||
|
||||
/** The deep-stubbed config {@link #open(Path, String, String)} uses, for a test that stubs more of it. */
|
||||
public static EmulatorConfig config(Path directory, String account) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.defaultAccountId()).thenReturn(account);
|
||||
when(config.storage().persistentPath()).thenReturn(directory.toString());
|
||||
when(config.storage().wal().compactionIntervalMs()).thenReturn(AN_HOUR_MS);
|
||||
return config;
|
||||
}
|
||||
|
||||
public static StorageFactory open(EmulatorConfig config, String mode) {
|
||||
ServiceConfigAccess access = mock(ServiceConfigAccess.class);
|
||||
when(access.storageMode(anyString())).thenReturn(mode);
|
||||
when(access.storageFlushInterval(anyString())).thenReturn(AN_HOUR_MS);
|
||||
return new StorageFactory(config, access);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user