mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cloudwatch): refuse EvaluationInterval on MetricName and Metrics alarms (#8863)
PutMetricAlarm now refuses EvaluationInterval on an alarm configured with MetricName or Metrics with InvalidParameterCombination, as the API reference documents, and refuses an integer outside 10 to 3600 or a value that is not an integer. AWS::CloudWatch::Alarm applies the same refusal on create and update, including a template that sets Metrics, which the provisioner reads only to detect it. ProvisionContext gains resolveOptionalBigInteger, sharing resolveOptionalInt's rule for what counts as absent. Closes #8894
This commit is contained in:
1 parent
c4d7499ca2
commit
bbc80c9b51
13 files changed
+527
-17
No files matched your search
+67
-2
@@ -2,14 +2,18 @@ package io.floci.aws.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.services.cloudformation.CloudFormationTemplateEngine;
|
||||
import io.floci.aws.services.cloudformation.model.StackResource;
|
||||
import io.floci.aws.services.cloudwatch.metrics.CloudWatchMetricsService;
|
||||
import io.floci.aws.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -17,10 +21,14 @@ import java.util.Map;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -62,7 +70,7 @@ class CloudWatchCfnProvisionerTest {
|
||||
r.setAttributes(new HashMap<>());
|
||||
provisioner.provision(r, props(json), ctx);
|
||||
ArgumentCaptor<MetricAlarm> alarm = ArgumentCaptor.forClass(MetricAlarm.class);
|
||||
verify(metrics).putMetricAlarm(alarm.capture(), eq(REGION));
|
||||
verify(metrics).putMetricAlarm(alarm.capture(), eq(REGION), isNull());
|
||||
return alarm.getValue();
|
||||
}
|
||||
|
||||
@@ -82,7 +90,7 @@ class CloudWatchCfnProvisionerTest {
|
||||
assertTrue(r.getAttributes().containsKey("Arn"), "aws-cloudwatch-alarm.json declares Arn read-only");
|
||||
|
||||
ArgumentCaptor<MetricAlarm> alarm = ArgumentCaptor.forClass(MetricAlarm.class);
|
||||
verify(metrics).putMetricAlarm(alarm.capture(), eq(REGION));
|
||||
verify(metrics).putMetricAlarm(alarm.capture(), eq(REGION), isNull());
|
||||
assertEquals("CPUUtilization", alarm.getValue().getMetricName());
|
||||
assertEquals("AWS/EC2", alarm.getValue().getNamespace());
|
||||
assertEquals(80.5, alarm.getValue().getThreshold());
|
||||
@@ -175,6 +183,63 @@ class CloudWatchCfnProvisionerTest {
|
||||
assertEquals(0.0, alarm.getThreshold());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource(delimiter = '|', value = {
|
||||
"60|60", "\"60\"|60", "\" 60 \"|60", "99999999999|99999999999",
|
||||
"\"99999999999999999999\"|99999999999999999999",
|
||||
"{\"Fn::If\": [\"C\", 60, {\"Ref\": \"AWS::NoValue\"}]}|NONE", "\"abc\"|FAIL", "60.0|FAIL", "\"\"|FAIL"})
|
||||
void evaluationIntervalIsReadAsAnIntegerOfAnySize(String literal, String expected) {
|
||||
StackResource r = new StackResource();
|
||||
r.setLogicalId("Alarm");
|
||||
r.setResourceType("AWS::CloudWatch::Alarm");
|
||||
r.setAttributes(new HashMap<>());
|
||||
JsonNode props = props("""
|
||||
{"AlarmName": "a", "MetricName": "Errors", "Namespace": "MyApp", "EvaluationInterval": %s}
|
||||
""".formatted(literal));
|
||||
|
||||
if ("FAIL".equals(expected)) {
|
||||
AwsException refused = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx));
|
||||
assertEquals("Value of property EvaluationInterval must be an integer.", refused.getMessage());
|
||||
verify(metrics, never()).putMetricAlarm(any(), anyString(), any());
|
||||
return;
|
||||
}
|
||||
provisioner.provision(r, props, ctx);
|
||||
|
||||
verify(metrics).putMetricAlarm(any(MetricAlarm.class), eq(REGION),
|
||||
"NONE".equals(expected) ? isNull() : eq(new BigInteger(expected)));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource(delimiter = '|', value = {
|
||||
"[{\"Id\": \"m1\", \"Expression\": \"1 + 1\"}]|60|REFUSED",
|
||||
"[{\"Id\": \"m1\", \"Expression\": \"1 + 1\"}]|NONE|STORED",
|
||||
"[]|60|STORED"})
|
||||
void anIntervalWithMetricsInTheTemplateIsRefusedOnCreateAndUpdate(String metricsJson, String interval,
|
||||
String expected) {
|
||||
StackResource r = new StackResource();
|
||||
r.setLogicalId("Alarm");
|
||||
r.setResourceType("AWS::CloudWatch::Alarm");
|
||||
r.setAttributes(new HashMap<>());
|
||||
JsonNode props = props("""
|
||||
{"AlarmName": "a", "Metrics": %s%s}
|
||||
""".formatted(metricsJson, "NONE".equals(interval) ? "" : ", \"EvaluationInterval\": " + interval));
|
||||
|
||||
if ("REFUSED".equals(expected)) {
|
||||
for (ProvisionContext context : List.of(ctx, ctx.withPriorPhysicalId("a"))) {
|
||||
AwsException refused = assertThrows(AwsException.class, () -> provisioner.provision(r, props, context));
|
||||
assertEquals("InvalidParameterCombination", refused.getErrorCode());
|
||||
assertEquals("EvaluationInterval cannot be specified for alarms configured with MetricName or "
|
||||
+ "Metrics.", refused.getMessage());
|
||||
}
|
||||
verify(metrics, never()).putMetricAlarm(any(), anyString(), any());
|
||||
return;
|
||||
}
|
||||
provisioner.provision(r, props, ctx);
|
||||
|
||||
verify(metrics).putMetricAlarm(any(MetricAlarm.class), eq(REGION),
|
||||
"NONE".equals(interval) ? isNull() : eq(new BigInteger(interval)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteReachesTheService() {
|
||||
provisioner.delete("AWS::CloudWatch::Alarm", "cpu-high", REGION);
|
||||
|
||||
+26
-1
@@ -10,10 +10,12 @@ import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
|
||||
import java.lang.reflect.RecordComponent;
|
||||
import java.math.BigInteger;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
@@ -283,7 +285,7 @@ class ProvisionContextTest {
|
||||
assertNull(ctx.resolveOptionalInt(null, "Port"), "no properties at all");
|
||||
assertNull(ctx.resolveOptionalInt(props("{\"Port\": {\"Ref\": \"AWS::NoValue\"}}"), "Port"),
|
||||
"an intrinsic that resolves to blank, as AWS::NoValue does");
|
||||
for (String literal : List.of("\"\"", "\"ten\"", "\"4.5\"", "4.5", "true")) {
|
||||
for (String literal : List.of("\"\"", "\"ten\"", "\"4.5\"", "4.5", "true", "99999999999")) {
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> ctx.resolveOptionalInt(props("{\"Port\": " + literal + "}"), "Port"), literal);
|
||||
assertEquals("ValidationError", e.getErrorCode(), literal);
|
||||
@@ -291,6 +293,29 @@ class ProvisionContextTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveOptionalBigIntegerReadsAnyWidthAndTakesTheAbsentRuleOfResolveOptionalInt() {
|
||||
ProvisionContext ctx = context(null);
|
||||
JsonNode size = props("{\"Ref\": \"Size\"}");
|
||||
when(engine.resolve(size)).thenReturn("3");
|
||||
Function<String, BigInteger> read = json -> ctx.resolveOptionalBigInteger(props(json), "Port");
|
||||
|
||||
assertEquals(BigInteger.valueOf(42), read.apply("{\"Port\": 42}"), "a number");
|
||||
assertEquals(new BigInteger("99999999999999999999"), read.apply("{\"Port\": \" 99999999999999999999 \"}"),
|
||||
"any width, trimmed");
|
||||
assertEquals(BigInteger.valueOf(3), read.apply("{\"Port\": {\"Ref\": \"Size\"}}"), "an intrinsic's result");
|
||||
assertNull(read.apply("{}"), "absent");
|
||||
assertNull(read.apply("{\"Port\": null}"), "explicitly null");
|
||||
assertNull(ctx.resolveOptionalBigInteger(null, "Port"), "no properties at all");
|
||||
assertNull(read.apply("{\"Port\": {\"Ref\": \"AWS::NoValue\"}}"),
|
||||
"an intrinsic that resolves to blank, as AWS::NoValue does");
|
||||
for (String literal : List.of("\"\"", "\"ten\"", "\"4.5\"", "4.5", "true")) {
|
||||
AwsException e = assertThrows(AwsException.class, () -> read.apply("{\"Port\": " + literal + "}"), literal);
|
||||
assertEquals("ValidationError", e.getErrorCode(), literal);
|
||||
assertEquals("Value of property Port must be an integer.", e.getMessage(), literal);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveOptionalBooleanReadsABooleanAndRefusesAnythingElse() {
|
||||
ProvisionContext ctx = context(null);
|
||||
|
||||
+33
@@ -15,6 +15,7 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Instant;
|
||||
@@ -372,6 +373,38 @@ class CloudWatchMetricsJsonHandlerTest {
|
||||
return ((ObjectNode) describeResp.getEntity()).get("MetricAlarms").get(0);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"\"60\"", "60.5", "true", "[60]", "4294967356"})
|
||||
void putMetricAlarm_refusesAnIntervalThatIsNoIntegerOrBeyondAnInt(String interval) throws Exception {
|
||||
ObjectNode request = alarmRequest("NoInteger");
|
||||
request.set("EvaluationInterval", MAPPER.readTree(interval));
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> handler.handle("PutMetricAlarm", request, REGION));
|
||||
|
||||
assertEquals("SerializationException", refused.getErrorCode());
|
||||
assertEquals(400, refused.getHttpStatus());
|
||||
assertTrue(service.describeAlarms(List.of("NoInteger"), null, REGION).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void putMetricAlarm_takesANullIntervalAsNone() {
|
||||
ObjectNode request = alarmRequest("NullInterval");
|
||||
request.putNull("EvaluationInterval");
|
||||
|
||||
assertEquals(200, handler.handle("PutMetricAlarm", request, REGION).getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void putMetricAlarm_passesTheIntervalToTheService() {
|
||||
ObjectNode request = alarmRequest("WithInterval").put("EvaluationInterval", 60);
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> handler.handle("PutMetricAlarm", request, REGION));
|
||||
|
||||
assertEquals("InvalidParameterCombinationException", refused.jsonType());
|
||||
}
|
||||
|
||||
private static ObjectNode alarmRequest(String name) {
|
||||
ObjectNode req = MAPPER.createObjectNode();
|
||||
req.put("AlarmName", name);
|
||||
|
||||
+43
-4
@@ -9,9 +9,11 @@ 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.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
@@ -23,6 +25,7 @@ import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.atMost;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
@@ -226,7 +229,7 @@ class CloudWatchMetricsQueryHandlerTest {
|
||||
handler.handle("PutMetricAlarm", params, REGION);
|
||||
|
||||
ArgumentCaptor<MetricAlarm> captor = ArgumentCaptor.forClass(MetricAlarm.class);
|
||||
verify(metricsService).putMetricAlarm(captor.capture(), anyString());
|
||||
verify(metricsService).putMetricAlarm(captor.capture(), anyString(), isNull());
|
||||
assertTrue(captor.getValue().isActionsEnabled());
|
||||
}
|
||||
|
||||
@@ -241,7 +244,7 @@ class CloudWatchMetricsQueryHandlerTest {
|
||||
handler.handle("PutMetricAlarm", params, REGION);
|
||||
|
||||
ArgumentCaptor<MetricAlarm> captor = ArgumentCaptor.forClass(MetricAlarm.class);
|
||||
verify(metricsService).putMetricAlarm(captor.capture(), anyString());
|
||||
verify(metricsService).putMetricAlarm(captor.capture(), anyString(), isNull());
|
||||
assertFalse(captor.getValue().isActionsEnabled());
|
||||
}
|
||||
|
||||
@@ -259,7 +262,7 @@ class CloudWatchMetricsQueryHandlerTest {
|
||||
handler.handle("PutMetricAlarm", params, REGION);
|
||||
|
||||
ArgumentCaptor<MetricAlarm> captor = ArgumentCaptor.forClass(MetricAlarm.class);
|
||||
verify(metricsService).putMetricAlarm(captor.capture(), anyString());
|
||||
verify(metricsService).putMetricAlarm(captor.capture(), anyString(), isNull());
|
||||
assertEquals(3, captor.getValue().getEvaluationPeriods());
|
||||
assertNull(captor.getValue().getDatapointsToAlarm());
|
||||
}
|
||||
@@ -276,10 +279,46 @@ class CloudWatchMetricsQueryHandlerTest {
|
||||
handler.handle("PutMetricAlarm", params, REGION);
|
||||
|
||||
ArgumentCaptor<MetricAlarm> captor = ArgumentCaptor.forClass(MetricAlarm.class);
|
||||
verify(metricsService).putMetricAlarm(captor.capture(), anyString());
|
||||
verify(metricsService).putMetricAlarm(captor.capture(), anyString(), isNull());
|
||||
assertEquals(2, captor.getValue().getDatapointsToAlarm());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource(nullValues = "-", value = {"abc, TestAlarm", "60.0, TestAlarm", "' ', TestAlarm", "abc, -"})
|
||||
void aValueThatIsNoIntegerIsAnInvalidParameterValue(String interval, String name) {
|
||||
MultivaluedMap<String, String> params = alarmParams(name, interval);
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> handler.handle("PutMetricAlarm", params, REGION));
|
||||
|
||||
assertEquals("InvalidParameterValue", refused.getErrorCode());
|
||||
assertEquals(400, refused.getHttpStatus());
|
||||
verify(metricsService, never()).putMetricAlarm(any(), anyString(), any());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource(nullValues = "-", value = {"-, -", "'', -", "60, 60", "' 60 ', 60",
|
||||
"99999999999999999999, 99999999999999999999"})
|
||||
void anIntegerReachesTheServiceAndAnEmptyValueIsNone(String interval, String expected) {
|
||||
handler.handle("PutMetricAlarm", alarmParams("TestAlarm", interval), REGION);
|
||||
|
||||
verify(metricsService).putMetricAlarm(any(MetricAlarm.class), eq(REGION),
|
||||
expected == null ? isNull() : eq(new BigInteger(expected)));
|
||||
}
|
||||
|
||||
private static MultivaluedMap<String, String> alarmParams(String name, String interval) {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
if (name != null) {
|
||||
params.putSingle("AlarmName", name);
|
||||
}
|
||||
params.putSingle("MetricName", "M");
|
||||
params.putSingle("Namespace", "NS");
|
||||
if (interval != null) {
|
||||
params.putSingle("EvaluationInterval", interval);
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
// The JSON handler forwards the Unit filter now; this pins the Query path to the same
|
||||
// contract so the two protocols cannot drift apart again.
|
||||
@Test
|
||||
|
||||
+49
@@ -9,6 +9,7 @@ import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.InMemoryStorage;
|
||||
import io.floci.aws.services.cloudwatch.metrics.model.Alarm;
|
||||
import io.floci.aws.services.cloudwatch.metrics.model.AlarmHistoryItem;
|
||||
import io.floci.aws.services.cloudwatch.metrics.model.AlarmMetricDataQuery;
|
||||
import io.floci.aws.services.cloudwatch.metrics.model.CompositeAlarm;
|
||||
import io.floci.aws.services.cloudwatch.metrics.model.Dimension;
|
||||
import io.floci.aws.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
@@ -16,9 +17,11 @@ import io.floci.aws.services.cloudwatch.metrics.model.MetricDatum;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.NullSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
@@ -914,4 +917,50 @@ class CloudWatchMetricsServiceTest {
|
||||
assertEquals(1, store.scan(k -> true).size(), "the default partition holds only the ambient put");
|
||||
assertEquals(2.0, store.scan(k -> true).getFirst().getValue());
|
||||
}
|
||||
|
||||
// M: MetricName, X: Metrics, C: neither (an EvaluationCriteria alarm); "-" is no interval
|
||||
@ParameterizedTest
|
||||
@CsvSource(nullValues = "-", value = {
|
||||
"5, M, true, LOW", "9, M, true, LOW", "9, C, true, LOW", "-99999999999999999999, C, true, LOW",
|
||||
"10, M, true, COMBINATION", "45, M, true, COMBINATION", "60, X, true, COMBINATION",
|
||||
"3600, M, true, COMBINATION", "3601, M, true, HIGH", "99999999999999999999, M, true, HIGH",
|
||||
"60, C, true, STORED", "3600, C, true, STORED", "-, M, true, STORED",
|
||||
"60, M, false, NAME", "60, C, false, NAME", "-, M, false, NAME",
|
||||
"5, M, false, NAME_LOW", "99999999999999999999, M, false, NAME_HIGH"})
|
||||
void evaluationIntervalIsCheckedAfterTheNameThenItsRangeThenTheAlarmKind(String interval, String kind,
|
||||
boolean named, String expected) {
|
||||
MetricAlarm alarm = new MetricAlarm();
|
||||
alarm.setAlarmName(named ? "a" : null);
|
||||
if ("M".equals(kind)) {
|
||||
alarm.setMetricName("Errors");
|
||||
} else if ("X".equals(kind)) {
|
||||
alarm.getMetrics().add(new AlarmMetricDataQuery("m1", "1 + 1", null, true, null, null, null));
|
||||
}
|
||||
BigInteger value = interval == null ? null : new BigInteger(interval);
|
||||
if ("STORED".equals(expected)) {
|
||||
service.putMetricAlarm(alarm, REGION, value);
|
||||
assertEquals(1, service.describeAlarms(List.of("a"), null, REGION).size());
|
||||
return;
|
||||
}
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> service.putMetricAlarm(alarm, REGION, value));
|
||||
|
||||
String nameOnly = named ? null
|
||||
: assertThrows(AwsException.class, () -> service.putMetricAlarm(alarm, REGION)).getMessage();
|
||||
String bound = expected.endsWith("LOW") ? "greater than or equal to 10" : "less than or equal to 3600";
|
||||
String range = "Value '" + interval + "' at 'evaluationInterval' failed to satisfy constraint: Member must "
|
||||
+ "have value " + bound;
|
||||
switch (expected) {
|
||||
case "COMBINATION" -> {
|
||||
assertEquals("InvalidParameterCombination", refused.getErrorCode());
|
||||
assertEquals("EvaluationInterval cannot be specified for alarms configured with MetricName or "
|
||||
+ "Metrics.", refused.getMessage());
|
||||
}
|
||||
case "NAME" -> assertEquals(nameOnly, refused.getMessage());
|
||||
case "LOW", "HIGH" -> assertEquals("1 validation error detected: " + range, refused.getMessage());
|
||||
default -> assertEquals("2 validation errors detected: " + nameOnly.substring(nameOnly.indexOf(": ") + 2)
|
||||
+ "; " + range, refused.getMessage());
|
||||
}
|
||||
assertTrue(service.describeAlarms(List.of("a"), null, REGION).isEmpty());
|
||||
}
|
||||
}
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
package io.floci.aws.services.cloudwatch.metrics;
|
||||
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.floci.aws.testing.CfnStackWaits;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.floci.aws.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.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
|
||||
import software.amazon.awssdk.services.cloudwatch.CloudWatchClient;
|
||||
import software.amazon.awssdk.services.cloudwatch.model.InvalidParameterCombinationException;
|
||||
import software.amazon.awssdk.services.cloudwatch.model.MetricAlarm;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/** An {@code EvaluationInterval} on a MetricName or Metrics alarm is refused, so a stack that sets it rolls back. */
|
||||
@QuarkusTest
|
||||
class CloudWatchPutMetricAlarmEvaluationIntervalIntegrationTest {
|
||||
|
||||
private static final String SCOPE =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261117/us-east-1/monitoring/aws4_request";
|
||||
private static final String COMBINATION =
|
||||
"EvaluationInterval cannot be specified for alarms configured with MetricName or Metrics.";
|
||||
|
||||
@TestHTTPResource
|
||||
URI baseUri;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
private CloudWatchClient cloudWatch;
|
||||
private CloudFormationClient cfn;
|
||||
private String suffix;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
cloudWatch = AwsTestClients.create(CloudWatchClient.builder(), "test", Region.US_EAST_1);
|
||||
cfn = AwsTestClients.create(CloudFormationClient.builder(), "test", Region.US_EAST_1);
|
||||
suffix = Long.toString(System.nanoTime(), 36);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void closeClients() {
|
||||
cloudWatch.close();
|
||||
cfn.close();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"false, InvalidParameterCombination", "true, InvalidParameterCombinationException"})
|
||||
void bothProtocolsRefuseTheIntervalOnAMetricNameAlarm(boolean json, String code) throws Exception {
|
||||
String name = "wire-interval-" + suffix;
|
||||
cleanup.register(() -> cloudWatch.deleteAlarms(r -> r.alarmNames(name)));
|
||||
Map<String, Object> body = new LinkedHashMap<>(Map.of("AlarmName", name, "Namespace", "MyApp",
|
||||
"MetricName", "MyMetric", "Statistic", "Sum", "Period", 60, "EvaluationPeriods", 1, "Threshold", 1,
|
||||
"ComparisonOperator", "GreaterThanOrEqualToThreshold", "EvaluationInterval", 60));
|
||||
|
||||
Response refused = CloudWatchTestRequests.call(baseUri, SCOPE, json, "PutMetricAlarm", body);
|
||||
|
||||
refused.then().statusCode(400);
|
||||
assertEquals(code, json ? refused.jsonPath().getString("__type")
|
||||
: refused.xmlPath().getString("ErrorResponse.Error.Code"));
|
||||
assertEquals(COMBINATION, json ? refused.jsonPath().getString("message")
|
||||
: refused.xmlPath().getString("ErrorResponse.Error.Message"));
|
||||
assertEquals(0, cloudWatch.describeAlarms(r -> r.alarmNames(name)).metricAlarms().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSdkRaisesTheTypedExceptionForTheIntervalOnAMetricNameAlarm() {
|
||||
InvalidParameterCombinationException refused = assertThrows(InvalidParameterCombinationException.class,
|
||||
() -> cloudWatch.putMetricAlarm(r -> r.alarmName("sdk-interval-" + suffix).metricName("MyMetric")
|
||||
.evaluationInterval(60)));
|
||||
|
||||
assertEquals(COMBINATION, refused.awsErrorDetails().errorMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAlarmWithEvaluationCriteriaTakesAnIntervalAndDoesNotReturnIt() {
|
||||
String name = "sdk-interval-criteria-" + suffix;
|
||||
cleanup.register(() -> cloudWatch.deleteAlarms(r -> r.alarmNames(name)));
|
||||
|
||||
cloudWatch.putMetricAlarm(r -> r.alarmName(name).evaluationInterval(60)
|
||||
.evaluationCriteria(c -> c.promQLCriteria(p -> p.query("up"))));
|
||||
|
||||
MetricAlarm stored = cloudWatch.describeAlarms(r -> r.alarmNames(name)).metricAlarms().getFirst();
|
||||
assertEquals(name, stored.alarmName());
|
||||
assertNull(stored.evaluationInterval());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"60", "99999999999"})
|
||||
void aStackWhoseAlarmSetsTheIntervalRollsBackWithTheReason(String interval) {
|
||||
String name = "stack-interval-" + suffix;
|
||||
String stack = "interval-create-" + suffix;
|
||||
String reason = "60".equals(interval) ? COMBINATION : "Value '" + interval + "' at 'evaluationInterval' "
|
||||
+ "failed to satisfy constraint: Member must have value less than or equal to 3600";
|
||||
|
||||
CfnStackWaits.StackState state = deploy(stack, alarmTemplate(name, 1, interval));
|
||||
|
||||
assertEquals("ROLLBACK_COMPLETE", state.status());
|
||||
assertEquals(0, cloudWatch.describeAlarms(r -> r.alarmNames(name)).metricAlarms().size());
|
||||
assertTrue(cfn.describeStackEvents(r -> r.stackName(stack)).stackEvents().stream()
|
||||
.anyMatch(e -> "CREATE_FAILED".equals(e.resourceStatusAsString())
|
||||
&& e.resourceStatusReason().contains(reason)), "no CREATE_FAILED event with: " + reason);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource(delimiter = '|', value = {
|
||||
"[{\"Id\":\"e1\",\"Expression\":\"1\"}]|ROLLBACK_COMPLETE",
|
||||
"{\"Fn::If\":[\"On\",[{\"Id\":\"e1\",\"Expression\":\"1\"}],{\"Ref\":\"AWS::NoValue\"}]}|ROLLBACK_COMPLETE",
|
||||
"{\"Fn::If\":[\"Off\",[{\"Id\":\"e1\",\"Expression\":\"1\"}],{\"Ref\":\"AWS::NoValue\"}]}|CREATE_COMPLETE"})
|
||||
void anIntervalWithMetricsRollsTheStackBackUnlessTheMetricsResolveToNoValue(String metrics, String expected) {
|
||||
String name = "stack-metrics-interval-" + suffix;
|
||||
String stack = "metrics-interval-" + suffix;
|
||||
boolean refused = "ROLLBACK_COMPLETE".equals(expected);
|
||||
|
||||
CfnStackWaits.StackState state = deploy(stack, """
|
||||
{"Conditions": {"On": {"Fn::Equals": ["a", "a"]}, "Off": {"Fn::Equals": ["a", "b"]}},
|
||||
"Resources": {"Alarm": {"Type": "AWS::CloudWatch::Alarm", "Properties": {
|
||||
"AlarmName": "%s", "EvaluationPeriods": 1, "Threshold": 1, "EvaluationInterval": 60,
|
||||
"ComparisonOperator": "GreaterThanOrEqualToThreshold",
|
||||
"Metrics": %s}}}}""".formatted(name, metrics));
|
||||
|
||||
assertEquals(expected, state.status(), state.reason());
|
||||
assertEquals(refused ? 0 : 1, cloudWatch.describeAlarms(r -> r.alarmNames(name)).metricAlarms().size());
|
||||
if (refused) {
|
||||
assertTrue(CfnStackWaits.failedResourceReason(stack).contains(COMBINATION));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUpdateThatAddsTheIntervalRollsBackAndLeavesTheAlarmAsItWas() {
|
||||
String name = "stack-interval-update-" + suffix;
|
||||
String stack = "interval-update-" + suffix;
|
||||
CfnStackWaits.StackState created = deploy(stack, alarmTemplate(name, 1, null));
|
||||
assertEquals("CREATE_COMPLETE", created.status(), created.reason());
|
||||
|
||||
CfnStackWaits.updateStack(cfn, stack, alarmTemplate(name, 5, "60"), "UPDATE_ROLLBACK_COMPLETE");
|
||||
|
||||
assertTrue(CfnStackWaits.failedResourceReason(stack).contains(COMBINATION));
|
||||
assertEquals(1.0, cloudWatch.describeAlarms(r -> r.alarmNames(name)).metricAlarms().getFirst().threshold());
|
||||
}
|
||||
|
||||
private CfnStackWaits.StackState deploy(String stack, String template) {
|
||||
cleanup.register(() -> cfn.deleteStack(r -> r.stackName(stack)));
|
||||
cfn.createStack(r -> r.stackName(stack).templateBody(template));
|
||||
return CfnStackWaits.awaitTerminal(stack);
|
||||
}
|
||||
|
||||
private static String alarmTemplate(String name, int threshold, String interval) {
|
||||
return """
|
||||
{"Resources": {"Alarm": {"Type": "AWS::CloudWatch::Alarm", "Properties": {
|
||||
"AlarmName": "%s", "Namespace": "MyApp", "MetricName": "MyMetric",
|
||||
"Statistic": "Sum", "Period": 60, "EvaluationPeriods": 1, "Threshold": %d,
|
||||
"ComparisonOperator": "GreaterThanOrEqualToThreshold"%s}}}}""".formatted(name, threshold,
|
||||
interval == null ? "" : ", \"EvaluationInterval\": " + interval);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user