mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(applicationautoscaling): evaluate target-tracking and step-scaling policies against ECS (#2692)
Adds a generic CloudWatch alarm evaluator plus an ECS CapacityAdjuster, so a firing policy calls UpdateService to change desiredCount instead of sitting inert. Adds DescribeScalingActivities to observe the result. Closes #2565 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
This commit is contained in:
1 parent
cf6fede453
commit
2a7c94b04d
20 files changed
+1720
-10
No files matched your search
+146
@@ -0,0 +1,146 @@
|
||||
package io.github.hectorvent.floci.services.applicationautoscaling;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.greaterThan;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
|
||||
/**
|
||||
* End-to-end coverage for the control loop that closes floci-io/floci#2565: a
|
||||
* TargetTrackingScaling policy's CloudWatch alarm actually gets evaluated, and a breach
|
||||
* changes the ECS service's {@code desiredCount} via {@code UpdateService}.
|
||||
*
|
||||
* <p>The alarm's period is fixed at 60s with 3 evaluation periods for the high alarm
|
||||
* (matching real AWS's target-tracking defaults), and the evaluator's lookback window is
|
||||
* period-aligned. Datapoints are pushed with explicit historical {@code Timestamp}s spanning
|
||||
* six consecutive periods rather than exactly three, so whichever period boundary the
|
||||
* evaluator's tick lands on, its 3-period aligned window is still fully covered — without a
|
||||
* 3-minute real wait for fresh data to accrue.</p>
|
||||
*
|
||||
* <p>Because the pushed metric never responds to the resulting capacity change (unlike a real
|
||||
* AWS metric), and AWS's own documented cooldown semantics let a scale-out that computes to a
|
||||
* <em>larger</em> capacity than the last one proceed immediately, the service converges across
|
||||
* several ticks — 2 desiredCount to 4, 4 to 8, 8 to 10 (clamped at {@code MaxCapacity}) — rather
|
||||
* than settling after a single action. It stops there because the next recompute
|
||||
* ({@code ceil(10 * 90 / 50) = 18}, clamped back to 10) no longer differs from the current
|
||||
* capacity.</p>
|
||||
*/
|
||||
@QuarkusTest
|
||||
class ApplicationAutoScalingEcsControlLoopIntegrationTest {
|
||||
|
||||
private static final String ECS_TARGET = "AmazonEC2ContainerServiceV20141113.";
|
||||
private static final String AAS_TARGET = "AnyScaleFrontendService.";
|
||||
private static final String CW_TARGET = "GraniteServiceVersion20100801.";
|
||||
private static final String CT = "application/x-amz-json-1.1";
|
||||
private static final String CLOUDWATCH_JSON_CONTENT_TYPE = "application/x-amz-json-1.0";
|
||||
|
||||
private static final String CLUSTER = "aas-loop-cluster";
|
||||
private static final String SERVICE = "aas-loop-svc";
|
||||
private static final String RESOURCE_ID = "service/" + CLUSTER + "/" + SERVICE;
|
||||
|
||||
@BeforeAll
|
||||
static void configure() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
private static Response call(String target, String action, String body) {
|
||||
return call(target, action, body, CT);
|
||||
}
|
||||
|
||||
private static Response call(String target, String action, String body, String contentType) {
|
||||
RequestSpecification spec = given().contentType(contentType).header("X-Amz-Target", target + action);
|
||||
if (body != null) {
|
||||
spec = spec.body(body);
|
||||
}
|
||||
return spec.when().post("/").then().statusCode(200).extract().response();
|
||||
}
|
||||
|
||||
@Test
|
||||
void breachingMetricAdjustsEcsDesiredCount() {
|
||||
call(ECS_TARGET, "CreateCluster", "{\"clusterName\":\"" + CLUSTER + "\"}");
|
||||
call(ECS_TARGET, "RegisterTaskDefinition", "{\"family\":\"aas-loop-td\","
|
||||
+ "\"containerDefinitions\":[{\"name\":\"web\",\"image\":\"nginx\",\"memory\":128}]}");
|
||||
call(ECS_TARGET, "CreateService", "{\"cluster\":\"" + CLUSTER + "\",\"serviceName\":\"" + SERVICE + "\","
|
||||
+ "\"taskDefinition\":\"aas-loop-td\",\"desiredCount\":2}");
|
||||
|
||||
call(AAS_TARGET, "RegisterScalableTarget", """
|
||||
{
|
||||
"ServiceNamespace": "ecs",
|
||||
"ResourceId": "%s",
|
||||
"ScalableDimension": "ecs:service:DesiredCount",
|
||||
"MinCapacity": 1,
|
||||
"MaxCapacity": 10
|
||||
}
|
||||
""".formatted(RESOURCE_ID));
|
||||
|
||||
call(AAS_TARGET, "PutScalingPolicy", """
|
||||
{
|
||||
"PolicyName": "aas-loop-cpu",
|
||||
"PolicyType": "TargetTrackingScaling",
|
||||
"ServiceNamespace": "ecs",
|
||||
"ResourceId": "%s",
|
||||
"ScalableDimension": "ecs:service:DesiredCount",
|
||||
"TargetTrackingScalingPolicyConfiguration": {
|
||||
"TargetValue": 50.0,
|
||||
"PredefinedMetricSpecification": {
|
||||
"PredefinedMetricType": "ECSServiceAverageCPUUtilization"
|
||||
},
|
||||
"ScaleOutCooldown": 300
|
||||
}
|
||||
}
|
||||
""".formatted(RESOURCE_ID));
|
||||
|
||||
long now = Instant.now().getEpochSecond();
|
||||
StringBuilder metricData = new StringBuilder("[");
|
||||
for (int i = 5; i >= 0; i--) {
|
||||
if (i != 5) {
|
||||
metricData.append(",");
|
||||
}
|
||||
metricData.append("""
|
||||
{
|
||||
"MetricName": "ECSServiceAverageCPUUtilization",
|
||||
"Value": 90.0,
|
||||
"Unit": "Percent",
|
||||
"Timestamp": %d,
|
||||
"Dimensions": [
|
||||
{"Name": "ClusterName", "Value": "%s"},
|
||||
{"Name": "ServiceName", "Value": "%s"}
|
||||
]
|
||||
}
|
||||
""".formatted(now - (60L * i), CLUSTER, SERVICE));
|
||||
}
|
||||
metricData.append("]");
|
||||
call(CW_TARGET, "PutMetricData",
|
||||
"{\"Namespace\":\"AWS/ECS\",\"MetricData\":" + metricData + "}", CLOUDWATCH_JSON_CONTENT_TYPE);
|
||||
|
||||
int maxCapacity = 10;
|
||||
await().atMost(Duration.ofSeconds(60)).untilAsserted(() ->
|
||||
call(ECS_TARGET, "DescribeServices",
|
||||
"{\"cluster\":\"" + CLUSTER + "\",\"services\":[\"" + SERVICE + "\"]}")
|
||||
.then().body("services[0].desiredCount", equalTo(maxCapacity)));
|
||||
|
||||
await().during(Duration.ofSeconds(15)).atMost(Duration.ofSeconds(20)).untilAsserted(() ->
|
||||
call(ECS_TARGET, "DescribeServices",
|
||||
"{\"cluster\":\"" + CLUSTER + "\",\"services\":[\"" + SERVICE + "\"]}")
|
||||
.then().body("services[0].desiredCount", equalTo(maxCapacity)));
|
||||
|
||||
call(AAS_TARGET, "DescribeScalingActivities", """
|
||||
{ "ServiceNamespace": "ecs", "ResourceId": "%s" }
|
||||
""".formatted(RESOURCE_ID))
|
||||
.then()
|
||||
.body("ScalingActivities", hasSize(greaterThan(0)))
|
||||
.body("ScalingActivities[0].StatusCode", equalTo("Successful"))
|
||||
.body("ScalingActivities[0].ResourceId", equalTo(RESOURCE_ID));
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -57,7 +57,8 @@ class ApplicationAutoScalingServiceTest {
|
||||
}).when(cloudWatch).deleteAlarms(any(), anyString());
|
||||
|
||||
service = new ApplicationAutoScalingService(
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), regionResolver, cloudWatch);
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
regionResolver, cloudWatch);
|
||||
}
|
||||
|
||||
private ScalableTarget register() {
|
||||
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package io.github.hectorvent.floci.services.applicationautoscaling;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.ecs.EcsService;
|
||||
import io.github.hectorvent.floci.services.ecs.model.EcsServiceModel;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class EcsCapacityAdjusterTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String RESOURCE_ID = "service/my-cluster/my-service";
|
||||
|
||||
private final EcsService ecsService = mock(EcsService.class);
|
||||
private final EcsCapacityAdjuster adjuster = new EcsCapacityAdjuster(ecsService);
|
||||
|
||||
@Test
|
||||
void supportsOnlyEcsDesiredCountDimension() {
|
||||
assertTrue(adjuster.supports("ecs:service:DesiredCount"));
|
||||
assertEquals(false, adjuster.supports("dynamodb:table:ReadCapacityUnits"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsCurrentDesiredCountFromParsedClusterAndService() {
|
||||
EcsServiceModel svc = new EcsServiceModel();
|
||||
svc.setDesiredCount(4);
|
||||
when(ecsService.describeServices("my-cluster", List.of("my-service"), REGION))
|
||||
.thenReturn(List.of(svc));
|
||||
|
||||
assertEquals(4, adjuster.getCurrentCapacity(RESOURCE_ID, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void writesDesiredCountViaUpdateServiceLeavingOtherFieldsUntouched() {
|
||||
adjuster.setCapacity(RESOURCE_ID, 7, REGION);
|
||||
|
||||
verify(ecsService).updateService("my-cluster", "my-service", null, 7, null, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsResourceIdNotShapedLikeAnEcsService() {
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> adjuster.setCapacity("not-a-valid-id", 1, REGION));
|
||||
assertEquals("ValidationException", e.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void throwsWhenServiceNotFound() {
|
||||
when(ecsService.describeServices("my-cluster", List.of("my-service"), REGION))
|
||||
.thenReturn(List.of());
|
||||
|
||||
assertThrows(AwsException.class, () -> adjuster.getCurrentCapacity(RESOURCE_ID, REGION));
|
||||
}
|
||||
}
|
||||
+352
@@ -0,0 +1,352 @@
|
||||
package io.github.hectorvent.floci.services.applicationautoscaling;
|
||||
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.ScalableTarget;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.ScalingPolicy;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.StepAdjustment;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.StepScalingConfiguration;
|
||||
import io.github.hectorvent.floci.services.applicationautoscaling.model.TargetTrackingConfiguration;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class ScalingPolicyAlarmActionHandlerTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String RESOURCE_ID = "service/my-cluster/my-service";
|
||||
private static final String POLICY_ARN =
|
||||
"arn:aws:autoscaling:us-east-1:000000000000:scalingPolicy:x:resource/ecs/y:policyName/z";
|
||||
|
||||
private final ApplicationAutoScalingService service = mock(ApplicationAutoScalingService.class);
|
||||
private final CapacityAdjuster adjuster = mock(CapacityAdjuster.class);
|
||||
@SuppressWarnings("unchecked")
|
||||
private final Instance<CapacityAdjuster> adjusters = mock(Instance.class);
|
||||
private ScalingPolicyAlarmActionHandler handler;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
when(adjusters.iterator()).thenAnswer(inv -> List.of(adjuster).iterator());
|
||||
when(adjuster.supports("ecs:service:DesiredCount")).thenReturn(true);
|
||||
handler = new ScalingPolicyAlarmActionHandler(service, adjusters);
|
||||
}
|
||||
|
||||
private static ScalingPolicy targetTrackingPolicy(double targetValue, Boolean disableScaleIn) {
|
||||
ScalingPolicy policy = new ScalingPolicy();
|
||||
policy.setPolicyName("cpu-target-tracking");
|
||||
policy.setPolicyArn(POLICY_ARN);
|
||||
policy.setPolicyType("TargetTrackingScaling");
|
||||
policy.setServiceNamespace("ecs");
|
||||
policy.setResourceId(RESOURCE_ID);
|
||||
policy.setScalableDimension("ecs:service:DesiredCount");
|
||||
TargetTrackingConfiguration config = new TargetTrackingConfiguration();
|
||||
config.setTargetValue(targetValue);
|
||||
config.setDisableScaleIn(disableScaleIn);
|
||||
policy.setTargetTrackingConfiguration(config);
|
||||
return policy;
|
||||
}
|
||||
|
||||
private static ScalableTarget target(int min, int max) {
|
||||
ScalableTarget target = new ScalableTarget();
|
||||
target.setServiceNamespace("ecs");
|
||||
target.setResourceId(RESOURCE_ID);
|
||||
target.setScalableDimension("ecs:service:DesiredCount");
|
||||
target.setMinCapacity(min);
|
||||
target.setMaxCapacity(max);
|
||||
return target;
|
||||
}
|
||||
|
||||
private static MetricAlarm alarm(String comparisonOperator, double threshold) {
|
||||
MetricAlarm alarm = new MetricAlarm();
|
||||
alarm.setAlarmName("TargetTracking-svc-AlarmHigh-abc");
|
||||
alarm.setComparisonOperator(comparisonOperator);
|
||||
alarm.setThreshold(threshold);
|
||||
return alarm;
|
||||
}
|
||||
|
||||
private void stub(ScalingPolicy policy, ScalableTarget target, int currentCapacity) {
|
||||
when(service.findPolicyByArn(POLICY_ARN, REGION)).thenReturn(Optional.of(policy));
|
||||
when(service.findTarget(REGION, "ecs", RESOURCE_ID, "ecs:service:DesiredCount"))
|
||||
.thenReturn(Optional.of(target));
|
||||
when(adjuster.getCurrentCapacity(RESOURCE_ID, REGION)).thenReturn(currentCapacity);
|
||||
}
|
||||
|
||||
@Test
|
||||
void scalesOutProportionallyToTargetRatio() {
|
||||
ScalingPolicy policy = targetTrackingPolicy(50.0, null);
|
||||
stub(policy, target(1, 10), 4);
|
||||
|
||||
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 80.0, REGION);
|
||||
|
||||
verify(adjuster).setCapacity(RESOURCE_ID, 7, REGION);
|
||||
assertTrue(policy.getLastScaleOutTime() > 0);
|
||||
verify(service).savePolicy(policy, REGION);
|
||||
verify(service).recordScalingActivity(eq(policy), anyString(), anyString(), eq(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void clampsToMaxCapacity() {
|
||||
ScalingPolicy policy = targetTrackingPolicy(50.0, null);
|
||||
stub(policy, target(1, 5), 4);
|
||||
|
||||
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 80.0, REGION);
|
||||
|
||||
verify(adjuster).setCapacity(RESOURCE_ID, 5, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void disableScaleInSuppressesScaleInAction() {
|
||||
ScalingPolicy policy = targetTrackingPolicy(50.0, true);
|
||||
stub(policy, target(1, 10), 4);
|
||||
|
||||
handler.handle(POLICY_ARN, alarm("LessThanThreshold", 50.0), 10.0, REGION);
|
||||
|
||||
verify(adjuster, never()).setCapacity(anyString(), anyInt(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void disableScaleInChecksTheComputedResultNotTheAlarmDirection() {
|
||||
ScalingPolicy policy = targetTrackingPolicy(50.0, true);
|
||||
stub(policy, target(1, 20), 10);
|
||||
|
||||
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 30.0), 40.0, REGION);
|
||||
|
||||
verify(adjuster, never()).setCapacity(anyString(), anyInt(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void disableScaleInSuppressesADecreaseCausedByMaxCapacityClamp() {
|
||||
ScalingPolicy policy = targetTrackingPolicy(50.0, true);
|
||||
stub(policy, target(1, 10), 15);
|
||||
|
||||
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 80.0, REGION);
|
||||
|
||||
verify(adjuster, never()).setCapacity(anyString(), anyInt(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void suspendedScaleOutDirectionSkipsAction() {
|
||||
ScalingPolicy policy = targetTrackingPolicy(50.0, null);
|
||||
ScalableTarget target = target(1, 10);
|
||||
target.getSuspendedState().setDynamicScalingOutSuspended(true);
|
||||
stub(policy, target, 4);
|
||||
|
||||
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 80.0, REGION);
|
||||
|
||||
verify(adjuster, never()).setCapacity(anyString(), anyInt(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void cooldownSuppressesRepeatedScaleIn() {
|
||||
ScalingPolicy policy = targetTrackingPolicy(50.0, null);
|
||||
policy.getTargetTrackingConfiguration().setScaleInCooldown(300);
|
||||
policy.setLastScaleInTime(System.currentTimeMillis() / 1000.0);
|
||||
stub(policy, target(1, 10), 8);
|
||||
|
||||
handler.handle(POLICY_ARN, alarm("LessThanThreshold", 50.0), 20.0, REGION);
|
||||
|
||||
verify(adjuster, never()).setCapacity(anyString(), anyInt(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void interveningScaleInDoesNotCorruptTheScaleOutCooldownReference() {
|
||||
ScalingPolicy policy = targetTrackingPolicy(50.0, null);
|
||||
policy.getTargetTrackingConfiguration().setScaleOutCooldown(300);
|
||||
policy.setLastScaleOutCapacity(10);
|
||||
policy.setLastAppliedCapacity(6);
|
||||
policy.setLastScaleOutTime(System.currentTimeMillis() / 1000.0);
|
||||
stub(policy, target(1, 20), 6);
|
||||
|
||||
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 60.0, REGION);
|
||||
|
||||
verify(adjuster, never()).setCapacity(anyString(), anyInt(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void continuesScalingOutAcrossCallsAsCapacityConvergesTowardTheCeiling() {
|
||||
ScalingPolicy policy = targetTrackingPolicy(50.0, null);
|
||||
stub(policy, target(1, 10), 4);
|
||||
|
||||
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 80.0, REGION);
|
||||
verify(adjuster).setCapacity(RESOURCE_ID, 7, REGION);
|
||||
|
||||
when(adjuster.getCurrentCapacity(RESOURCE_ID, REGION)).thenReturn(7);
|
||||
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 80.0, REGION);
|
||||
verify(adjuster).setCapacity(RESOURCE_ID, 10, REGION);
|
||||
|
||||
when(adjuster.getCurrentCapacity(RESOURCE_ID, REGION)).thenReturn(10);
|
||||
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 80.0, REGION);
|
||||
verify(adjuster, times(2)).setCapacity(anyString(), anyInt(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void firesAgainWhenTheMetricValueChanges() {
|
||||
ScalingPolicy policy = targetTrackingPolicy(50.0, null);
|
||||
stub(policy, target(1, 20), 4);
|
||||
|
||||
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 80.0, REGION);
|
||||
verify(adjuster).setCapacity(RESOURCE_ID, 7, REGION);
|
||||
|
||||
when(adjuster.getCurrentCapacity(RESOURCE_ID, REGION)).thenReturn(7);
|
||||
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 95.0, REGION);
|
||||
|
||||
verify(adjuster).setCapacity(RESOURCE_ID, 14, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deferredScaleInStillFiresLaterOnceCooldownClears() {
|
||||
ScalingPolicy policy = targetTrackingPolicy(50.0, null);
|
||||
policy.getTargetTrackingConfiguration().setScaleInCooldown(300);
|
||||
policy.setLastScaleInTime(System.currentTimeMillis() / 1000.0);
|
||||
stub(policy, target(1, 10), 8);
|
||||
|
||||
handler.handle(POLICY_ARN, alarm("LessThanThreshold", 50.0), 20.0, REGION);
|
||||
verify(adjuster, never()).setCapacity(anyString(), anyInt(), anyString());
|
||||
|
||||
policy.setLastScaleInTime(0);
|
||||
handler.handle(POLICY_ARN, alarm("LessThanThreshold", 50.0), 20.0, REGION);
|
||||
|
||||
verify(adjuster).setCapacity(RESOURCE_ID, 4, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void noAdjusterRegisteredForDimensionIsNoOp() {
|
||||
when(adjuster.supports("ecs:service:DesiredCount")).thenReturn(false);
|
||||
ScalingPolicy policy = targetTrackingPolicy(50.0, null);
|
||||
stub(policy, target(1, 10), 4);
|
||||
|
||||
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 80.0, REGION);
|
||||
|
||||
verify(adjuster, never()).setCapacity(anyString(), anyInt(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void stepScalingExactCapacityAppliesMatchingStepDirectly() {
|
||||
ScalingPolicy policy = new ScalingPolicy();
|
||||
policy.setPolicyName("step-policy");
|
||||
policy.setPolicyArn(POLICY_ARN);
|
||||
policy.setPolicyType("StepScaling");
|
||||
policy.setServiceNamespace("ecs");
|
||||
policy.setResourceId(RESOURCE_ID);
|
||||
policy.setScalableDimension("ecs:service:DesiredCount");
|
||||
StepScalingConfiguration config = new StepScalingConfiguration();
|
||||
config.setAdjustmentType("ExactCapacity");
|
||||
StepAdjustment step = new StepAdjustment();
|
||||
step.setMetricIntervalLowerBound(0.0);
|
||||
step.setScalingAdjustment(9);
|
||||
config.setStepAdjustments(List.of(step));
|
||||
policy.setStepScalingConfiguration(config);
|
||||
stub(policy, target(1, 10), 4);
|
||||
|
||||
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 80.0, REGION);
|
||||
|
||||
verify(adjuster).setCapacity(RESOURCE_ID, 9, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void suspensionChecksTheComputedDirectionNotTheAlarmDirection() {
|
||||
ScalingPolicy policy = new ScalingPolicy();
|
||||
policy.setPolicyName("step-policy");
|
||||
policy.setPolicyArn(POLICY_ARN);
|
||||
policy.setPolicyType("StepScaling");
|
||||
policy.setServiceNamespace("ecs");
|
||||
policy.setResourceId(RESOURCE_ID);
|
||||
policy.setScalableDimension("ecs:service:DesiredCount");
|
||||
StepScalingConfiguration config = new StepScalingConfiguration();
|
||||
config.setAdjustmentType("ChangeInCapacity");
|
||||
StepAdjustment step = new StepAdjustment();
|
||||
step.setMetricIntervalLowerBound(0.0);
|
||||
step.setScalingAdjustment(-2);
|
||||
config.setStepAdjustments(List.of(step));
|
||||
policy.setStepScalingConfiguration(config);
|
||||
|
||||
ScalableTarget target = target(1, 10);
|
||||
target.getSuspendedState().setDynamicScalingInSuspended(true);
|
||||
stub(policy, target, 4);
|
||||
|
||||
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 80.0, REGION);
|
||||
|
||||
verify(adjuster, never()).setCapacity(anyString(), anyInt(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void nanMetricValueNudgesCapacityByOneInTheAlarmsDirection() {
|
||||
ScalingPolicy policy = targetTrackingPolicy(50.0, null);
|
||||
stub(policy, target(1, 10), 4);
|
||||
|
||||
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), Double.NaN, REGION);
|
||||
|
||||
verify(adjuster).setCapacity(RESOURCE_ID, 5, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void nanMetricValueForStepScalingResolvesTheZeroDeltaStep() {
|
||||
ScalingPolicy policy = new ScalingPolicy();
|
||||
policy.setPolicyName("step-policy");
|
||||
policy.setPolicyArn(POLICY_ARN);
|
||||
policy.setPolicyType("StepScaling");
|
||||
policy.setServiceNamespace("ecs");
|
||||
policy.setResourceId(RESOURCE_ID);
|
||||
policy.setScalableDimension("ecs:service:DesiredCount");
|
||||
StepScalingConfiguration config = new StepScalingConfiguration();
|
||||
config.setAdjustmentType("ChangeInCapacity");
|
||||
StepAdjustment step = new StepAdjustment();
|
||||
step.setMetricIntervalLowerBound(0.0);
|
||||
step.setScalingAdjustment(3);
|
||||
config.setStepAdjustments(List.of(step));
|
||||
policy.setStepScalingConfiguration(config);
|
||||
stub(policy, target(1, 10), 4);
|
||||
|
||||
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), Double.NaN, REGION);
|
||||
|
||||
verify(adjuster).setCapacity(RESOURCE_ID, 7, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void reconciliationContinuesWhenCapacityDriftsHigherExternally() {
|
||||
ScalingPolicy policy = targetTrackingPolicy(50.0, null);
|
||||
stub(policy, target(1, 30), 4);
|
||||
|
||||
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 80.0, REGION);
|
||||
verify(adjuster).setCapacity(RESOURCE_ID, 7, REGION);
|
||||
|
||||
when(adjuster.getCurrentCapacity(RESOURCE_ID, REGION)).thenReturn(9);
|
||||
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 80.0, REGION);
|
||||
|
||||
verify(adjuster).setCapacity(RESOURCE_ID, 15, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void reconciliationBypassesCooldownWhenCapacityDriftsLowerExternally() {
|
||||
ScalingPolicy policy = targetTrackingPolicy(50.0, null);
|
||||
policy.getTargetTrackingConfiguration().setScaleOutCooldown(300);
|
||||
policy.setLastAppliedCapacity(10);
|
||||
policy.setLastScaleOutTime(System.currentTimeMillis() / 1000.0);
|
||||
stub(policy, target(1, 20), 3);
|
||||
|
||||
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 80.0, REGION);
|
||||
|
||||
verify(adjuster).setCapacity(RESOURCE_ID, 5, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownPolicyArnIsNoOp() {
|
||||
when(service.findPolicyByArn(POLICY_ARN, REGION)).thenReturn(Optional.empty());
|
||||
|
||||
handler.handle(POLICY_ARN, alarm("GreaterThanThreshold", 50.0), 80.0, REGION);
|
||||
|
||||
verify(adjuster, never()).setCapacity(anyString(), anyInt(), anyString());
|
||||
}
|
||||
}
|
||||
+249
@@ -0,0 +1,249 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyDouble;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class AlarmEvaluatorTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String POLICY_ARN =
|
||||
"arn:aws:autoscaling:us-east-1:000000000000:scalingPolicy:x:resource/ecs/y:policyName/z";
|
||||
|
||||
private final CloudWatchMetricsService metricsService = mock(CloudWatchMetricsService.class);
|
||||
@SuppressWarnings("unchecked")
|
||||
private final Instance<AlarmActionHandler> handlers = mock(Instance.class);
|
||||
private final AlarmActionHandler handler = mock(AlarmActionHandler.class);
|
||||
private final AlarmEvaluator evaluator = new AlarmEvaluator(metricsService, handlers);
|
||||
|
||||
private static MetricAlarm alarm() {
|
||||
MetricAlarm alarm = new MetricAlarm();
|
||||
alarm.setAlarmName("TargetTracking-svc-AlarmHigh-abc");
|
||||
alarm.setRegion(REGION);
|
||||
alarm.setNamespace("AWS/ECS");
|
||||
alarm.setMetricName("CPUUtilization");
|
||||
alarm.setStatistic("Average");
|
||||
alarm.setPeriod(60);
|
||||
alarm.setEvaluationPeriods(3);
|
||||
alarm.setThreshold(50.0);
|
||||
alarm.setComparisonOperator("GreaterThanThreshold");
|
||||
alarm.setActionsEnabled(true);
|
||||
alarm.setAlarmActions(List.of(POLICY_ARN));
|
||||
return alarm;
|
||||
}
|
||||
|
||||
private static List<CloudWatchMetricsService.Datapoint> datapoints(double... values) {
|
||||
List<CloudWatchMetricsService.Datapoint> points = new ArrayList<>();
|
||||
Instant now = Instant.now();
|
||||
for (int i = 0; i < values.length; i++) {
|
||||
points.add(new CloudWatchMetricsService.Datapoint(
|
||||
now.minusSeconds(60L * (values.length - i)),
|
||||
1, values[i], values[i], values[i], values[i], "Percent"));
|
||||
}
|
||||
return points;
|
||||
}
|
||||
|
||||
private void stubMetrics(List<CloudWatchMetricsService.Datapoint> points) {
|
||||
when(metricsService.getMetricStatistics(
|
||||
any(), any(), any(), any(), any(), anyInt(), any(), any(), anyString()))
|
||||
.thenReturn(points);
|
||||
}
|
||||
|
||||
@Test
|
||||
void transitionsToAlarmAndDispatchesWhenThresholdBreachedForAllPeriods() {
|
||||
stubMetrics(datapoints(80, 85, 90));
|
||||
when(handlers.iterator()).thenAnswer(inv -> List.of(handler).iterator());
|
||||
when(handler.supports(POLICY_ARN)).thenReturn(true);
|
||||
|
||||
MetricAlarm alarm = alarm();
|
||||
evaluator.evaluate(alarm);
|
||||
|
||||
verify(metricsService).setAlarmState(
|
||||
eq(alarm.getAlarmName()), eq("ALARM"), anyString(), any(), eq(REGION));
|
||||
verify(handler).handle(eq(POLICY_ARN), eq(alarm), eq(90.0), eq(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void redispatchesOnEveryTickWhileStillInAlarm() {
|
||||
stubMetrics(datapoints(80, 85, 90));
|
||||
when(handlers.iterator()).thenAnswer(inv -> List.of(handler).iterator());
|
||||
when(handler.supports(POLICY_ARN)).thenReturn(true);
|
||||
|
||||
MetricAlarm alarm = alarm();
|
||||
alarm.setStateValue("ALARM");
|
||||
evaluator.evaluate(alarm);
|
||||
|
||||
verify(handler).handle(eq(POLICY_ARN), eq(alarm), eq(90.0), eq(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void insufficientDataWhenFewerDatapointsThanEvaluationPeriods() {
|
||||
stubMetrics(datapoints(80));
|
||||
|
||||
MetricAlarm alarm = alarm();
|
||||
alarm.setStateValue("OK");
|
||||
evaluator.evaluate(alarm);
|
||||
|
||||
verify(metricsService).setAlarmState(
|
||||
eq(alarm.getAlarmName()), eq("INSUFFICIENT_DATA"), anyString(), any(), eq(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void transitionsBackToOkWhenNoLongerBreaching() {
|
||||
stubMetrics(datapoints(10, 15, 20));
|
||||
|
||||
MetricAlarm alarm = alarm();
|
||||
alarm.setStateValue("ALARM");
|
||||
evaluator.evaluate(alarm);
|
||||
|
||||
verify(metricsService).setAlarmState(
|
||||
eq(alarm.getAlarmName()), eq("OK"), anyString(), any(), eq(REGION));
|
||||
verify(handler, never()).handle(anyString(), any(), anyDouble(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void skipsAlarmsMissingEvaluableConfig() {
|
||||
MetricAlarm alarm = new MetricAlarm();
|
||||
alarm.setAlarmName("hand-created-no-metric-config");
|
||||
alarm.setRegion(REGION);
|
||||
|
||||
evaluator.evaluate(alarm);
|
||||
|
||||
verify(metricsService, never()).getMetricStatistics(
|
||||
any(), any(), any(), any(), any(), anyInt(), any(), any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void evaluateAllSurvivesAllAlarmsThrowing() {
|
||||
when(metricsService.allAlarms()).thenThrow(new RuntimeException("storage hiccup"));
|
||||
|
||||
assertDoesNotThrow(evaluator::evaluateAll);
|
||||
}
|
||||
|
||||
@Test
|
||||
void actionsDisabledSuppressesDispatchEvenOnBreach() {
|
||||
stubMetrics(datapoints(80, 85, 90));
|
||||
|
||||
MetricAlarm alarm = alarm();
|
||||
alarm.setActionsEnabled(false);
|
||||
evaluator.evaluate(alarm);
|
||||
|
||||
verify(handler, never()).handle(anyString(), any(), anyDouble(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void dispatchesTheMostRecentBreachingValueEvenWhenTheLatestDatapointDoesNot() {
|
||||
stubMetrics(datapoints(90, 85, 20));
|
||||
when(handlers.iterator()).thenAnswer(inv -> List.of(handler).iterator());
|
||||
when(handler.supports(POLICY_ARN)).thenReturn(true);
|
||||
|
||||
MetricAlarm alarm = alarm();
|
||||
alarm.setDatapointsToAlarm(2);
|
||||
evaluator.evaluate(alarm);
|
||||
|
||||
verify(handler).handle(eq(POLICY_ARN), eq(alarm), eq(85.0), eq(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void treatMissingDataBreachingCountsGapsAsBreaching() {
|
||||
stubMetrics(datapoints(80));
|
||||
when(handlers.iterator()).thenAnswer(inv -> List.<AlarmActionHandler>of().iterator());
|
||||
|
||||
MetricAlarm alarm = alarm();
|
||||
alarm.setStateValue("OK");
|
||||
alarm.setTreatMissingData("breaching");
|
||||
evaluator.evaluate(alarm);
|
||||
|
||||
verify(metricsService).setAlarmState(
|
||||
eq(alarm.getAlarmName()), eq("ALARM"), anyString(), any(), eq(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingDataAlarmWithNoRealBreachingDatapointDispatchesNaN() {
|
||||
stubMetrics(datapoints(20));
|
||||
when(handlers.iterator()).thenAnswer(inv -> List.of(handler).iterator());
|
||||
when(handler.supports(POLICY_ARN)).thenReturn(true);
|
||||
|
||||
MetricAlarm alarm = alarm();
|
||||
alarm.setStateValue("OK");
|
||||
alarm.setTreatMissingData("breaching");
|
||||
alarm.setDatapointsToAlarm(2);
|
||||
evaluator.evaluate(alarm);
|
||||
|
||||
verify(metricsService).setAlarmState(
|
||||
eq(alarm.getAlarmName()), eq("ALARM"), anyString(), any(), eq(REGION));
|
||||
verify(handler).handle(eq(POLICY_ARN), eq(alarm), eq(Double.NaN), eq(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void treatMissingDataNotBreachingDoesNotCountGapsTowardAlarm() {
|
||||
stubMetrics(datapoints(80));
|
||||
|
||||
MetricAlarm alarm = alarm();
|
||||
alarm.setStateValue("ALARM");
|
||||
alarm.setTreatMissingData("notBreaching");
|
||||
evaluator.evaluate(alarm);
|
||||
|
||||
verify(metricsService).setAlarmState(
|
||||
eq(alarm.getAlarmName()), eq("OK"), anyString(), any(), eq(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void queriesAPeriodAlignedWindowRegardlessOfWhenTheTickFires() {
|
||||
stubMetrics(datapoints(80, 85, 90));
|
||||
when(handlers.iterator()).thenAnswer(inv -> List.<AlarmActionHandler>of().iterator());
|
||||
|
||||
evaluator.evaluate(alarm());
|
||||
|
||||
ArgumentCaptor<Instant> startCaptor = ArgumentCaptor.forClass(Instant.class);
|
||||
verify(metricsService).getMetricStatistics(
|
||||
any(), any(), any(), startCaptor.capture(), any(), anyInt(), any(), any(), anyString());
|
||||
assertEquals(0, startCaptor.getValue().getEpochSecond() % 60);
|
||||
}
|
||||
|
||||
@Test
|
||||
void treatMissingDataIgnoreLeavesStateUntouched() {
|
||||
stubMetrics(datapoints(80));
|
||||
|
||||
MetricAlarm alarm = alarm();
|
||||
alarm.setStateValue("OK");
|
||||
alarm.setTreatMissingData("ignore");
|
||||
evaluator.evaluate(alarm);
|
||||
|
||||
verify(metricsService, never()).setAlarmState(
|
||||
anyString(), anyString(), anyString(), any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void treatMissingDataIgnoreStillRetriesDispatchWhileAlreadyInAlarm() {
|
||||
stubMetrics(datapoints(80));
|
||||
when(handlers.iterator()).thenAnswer(inv -> List.of(handler).iterator());
|
||||
when(handler.supports(POLICY_ARN)).thenReturn(true);
|
||||
|
||||
MetricAlarm alarm = alarm();
|
||||
alarm.setStateValue("ALARM");
|
||||
alarm.setTreatMissingData("ignore");
|
||||
evaluator.evaluate(alarm);
|
||||
|
||||
verify(metricsService, never()).setAlarmState(
|
||||
anyString(), anyString(), anyString(), any(), anyString());
|
||||
verify(handler).handle(eq(POLICY_ARN), eq(alarm), eq(80.0), eq(REGION));
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
/**
|
||||
* The JSON 1.0 handler defaults {@code ActionsEnabled} to {@code true} when omitted, matching
|
||||
* AWS's documented default for {@code PutMetricAlarm}. This handler must do the same over the
|
||||
* Query protocol — a mismatch here would silently disable {@link AlarmEvaluator} dispatch for
|
||||
* any hand-created alarm (e.g. behind a StepScaling policy) that doesn't explicitly pass the
|
||||
* parameter, since {@code Boolean.parseBoolean(null)} defaults to {@code false}.
|
||||
*/
|
||||
class CloudWatchMetricsQueryHandlerTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
private final CloudWatchMetricsService metricsService = mock(CloudWatchMetricsService.class);
|
||||
private final CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(metricsService);
|
||||
|
||||
@Test
|
||||
void putMetricAlarmDefaultsActionsEnabledToTrueWhenOmitted() {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("AlarmName", "TestAlarm");
|
||||
params.putSingle("MetricName", "M");
|
||||
params.putSingle("Namespace", "NS");
|
||||
|
||||
handler.handle("PutMetricAlarm", params, REGION);
|
||||
|
||||
ArgumentCaptor<MetricAlarm> captor = ArgumentCaptor.forClass(MetricAlarm.class);
|
||||
verify(metricsService).putMetricAlarm(captor.capture(), anyString());
|
||||
assertTrue(captor.getValue().isActionsEnabled());
|
||||
}
|
||||
|
||||
@Test
|
||||
void putMetricAlarmRespectsExplicitActionsEnabledFalse() {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("AlarmName", "TestAlarm");
|
||||
params.putSingle("MetricName", "M");
|
||||
params.putSingle("Namespace", "NS");
|
||||
params.putSingle("ActionsEnabled", "false");
|
||||
|
||||
handler.handle("PutMetricAlarm", params, REGION);
|
||||
|
||||
ArgumentCaptor<MetricAlarm> captor = ArgumentCaptor.forClass(MetricAlarm.class);
|
||||
verify(metricsService).putMetricAlarm(captor.capture(), anyString());
|
||||
assertFalse(captor.getValue().isActionsEnabled());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user