feat: support one-off ECS scheduled scaling (#7895)

* feat: support one-off ECS scheduled scaling

* chore: cover application auto scaling scheduled actions with SDK

* fix: preserve scheduled action ordering and report failures

* test: cover scheduled suspension through the AWS SDK

* fix: validate scheduled action inputs and preserve explicit UTC

* test: tick explicitly when checking scheduled action rescheduling

* fix: reuse schedule parser and tighten scheduled scaling tests

* test: poll ECS cluster cleanup for late arriving tasks
This commit is contained in:
James McMahon authored and GitHub committed 2026-11-10 18:28:30 -04:00
1 parent da5c0d8b36
commit fe24f7736a
25 files changed
+1942 -107

No files matched your search

@@ -3,6 +3,7 @@ package io.floci.aws.core.common;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
import io.floci.aws.services.ec2instanceconnect.InstanceConnectKeys;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.PartitionCleanup;
import io.floci.aws.testing.PartitionMatrix;
import io.floci.aws.testing.PartitionMatrix.PartitionCase;
@@ -16,6 +17,9 @@ 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.MethodSource;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.applicationautoscaling.ApplicationAutoScalingClient;
import software.amazon.awssdk.services.applicationautoscaling.model.ScalableTargetAction;
import java.net.URI;
import java.nio.charset.StandardCharsets;
@@ -969,18 +973,26 @@ class PartitionCrossServiceSmokeIntegrationTest {
@MethodSource(PartitionMatrix.NON_COMMERCIAL_CASES)
void applicationAutoScalingScalableTargetArn(PartitionCase partitionCase) {
String region = offered(partitionCase, "application-autoscaling");
String resourceId = "table/" + unique("smoke-table", partitionCase);
String target = """
"ServiceNamespace": "dynamodb", "ResourceId": "%s",
"ScalableDimension": "dynamodb:table:ReadCapacityUnits"
""".formatted(resourceId);
String arn = json11(region, "application-autoscaling", "AnyScaleFrontendService.RegisterScalableTarget",
"{" + target + ", \"MinCapacity\": 1, \"MaxCapacity\": 5}")
.when().post("/").then().statusCode(200)
.extract().jsonPath().getString("ScalableTargetARN");
cleanup.register(() -> json11(region, "application-autoscaling",
"AnyScaleFrontendService.DeregisterScalableTarget", "{" + target + "}").when().post("/"));
PartitionMatrix.assertArnIn(partitionCase, arn);
String resourceId = "service/" + unique("smoke-cluster", partitionCase) + "/service";
try (ApplicationAutoScalingClient client = AwsTestClients.create(ApplicationAutoScalingClient.builder(),
"000000000000", Region.of(region))) {
String arn = client.registerScalableTarget(b -> b.serviceNamespace("ecs").resourceId(resourceId)
.scalableDimension("ecs:service:DesiredCount").minCapacity(1).maxCapacity(5)).scalableTargetARN();
try {
PartitionMatrix.assertArnIn(partitionCase, arn);
client.putScheduledAction(b -> b.serviceNamespace("ecs").resourceId(resourceId)
.scalableDimension("ecs:service:DesiredCount").scheduledActionName("partition-action")
.schedule("at(2099-01-01T00:00:00)")
.scalableTargetAction(ScalableTargetAction.builder().minCapacity(0).build()));
String actionArn = client.describeScheduledActions(b -> b.serviceNamespace("ecs").resourceId(resourceId))
.scheduledActions().getFirst().scheduledActionARN();
PartitionMatrix.assertArnIn(partitionCase, actionArn);
assertTrue(actionArn.contains(":autoscaling:" + region + ":000000000000:scheduledAction:"));
} finally {
client.deregisterScalableTarget(b -> b.serviceNamespace("ecs").resourceId(resourceId)
.scalableDimension("ecs:service:DesiredCount"));
}
}
}
@ParameterizedTest
@@ -2,6 +2,7 @@ package io.floci.aws.services.applicationautoscaling;
import io.floci.aws.services.cloudwatch.metrics.AlarmEvaluator;
import io.floci.aws.services.cloudwatch.metrics.AlarmEvaluatorTestAccess;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
@@ -9,6 +10,12 @@ import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.applicationautoscaling.ApplicationAutoScalingClient;
import software.amazon.awssdk.services.applicationautoscaling.model.ScalableTarget;
import software.amazon.awssdk.services.applicationautoscaling.model.ScheduledAction;
import software.amazon.awssdk.services.ecs.EcsClient;
import software.amazon.awssdk.services.ecs.model.ContainerDefinition;
import java.time.Duration;
import java.time.Instant;
@@ -18,6 +25,7 @@ import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* End-to-end coverage for the control loop that closes floci-io/floci#2565: a
@@ -55,6 +63,9 @@ class ApplicationAutoScalingEcsControlLoopIntegrationTest {
@Inject
AlarmEvaluator alarmEvaluator;
@Inject
ApplicationAutoScalingScheduledActionScheduler scheduledActionScheduler;
@BeforeAll
static void configure() {
RestAssuredJsonUtils.configureAwsContentTypes();
@@ -154,4 +165,84 @@ class ApplicationAutoScalingEcsControlLoopIntegrationTest {
.body("ScalingActivities[0].StatusCode", equalTo("Successful"))
.body("ScalingActivities[0].ResourceId", equalTo(RESOURCE_ID));
}
@Test
void scheduledActionClampsEcsAndRetainsCompletion() {
String cluster = "aas-scheduled-cluster";
String serviceName = "aas-scheduled-service";
String resource = "service/" + cluster + "/" + serviceName;
try (ApplicationAutoScalingClient scaling = AwsTestClients.create(ApplicationAutoScalingClient.builder(),
"000000000000", Region.US_EAST_1);
EcsClient ecs = AwsTestClients.create(EcsClient.builder(), "000000000000", Region.US_EAST_1)) {
ecs.createCluster(b -> b.clusterName(cluster));
ecs.registerTaskDefinition(b -> b.family("aas-scheduled-task")
.containerDefinitions(ContainerDefinition.builder().name("web").image("nginx").memory(128).build()));
ecs.createService(b -> b.cluster(cluster).serviceName(serviceName).taskDefinition("aas-scheduled-task").desiredCount(2));
ScheduledActionFixtures.register(scaling, resource, 1, 10);
try {
scaling.registerScalableTarget(b -> b.serviceNamespace("ecs").resourceId(resource)
.scalableDimension(ScheduledActionFixtures.DIMENSION)
.suspendedState(state -> state.scheduledScalingSuspended(true)));
Instant suspendedDeadline = Instant.now().plusSeconds(60);
scaling.putScheduledAction(ScheduledActionFixtures.put(resource, "clamp")
.timezone("UTC").schedule(ScheduledActionFixtures.schedule(suspendedDeadline))
.scalableTargetAction(ScheduledActionFixtures.bounds(0, 1)).build());
ScheduledAction identity = ScheduledActionFixtures.describe(scaling, resource).scheduledActions().getFirst();
assertEquals("UTC", identity.timezone());
ScheduledActionFixtures.register(scaling, resource, 1, 10);
ScalableTarget suspended = scaling.describeScalableTargets(b -> b.serviceNamespace("ecs")
.resourceIds(resource)).scalableTargets().getFirst();
assertEquals(true, suspended.suspendedState().scheduledScalingSuspended());
scheduledActionScheduler.tick(suspendedDeadline.plusSeconds(1));
assertScheduledCapacityUnchanged(scaling, ecs, resource, cluster, serviceName);
scaling.registerScalableTarget(b -> b.serviceNamespace("ecs").resourceId(resource)
.scalableDimension(ScheduledActionFixtures.DIMENSION)
.suspendedState(state -> state.scheduledScalingSuspended(false)));
scheduledActionScheduler.tick(suspendedDeadline.plusSeconds(2));
assertScheduledCapacityUnchanged(scaling, ecs, resource, cluster, serviceName);
Instant clampDeadline = Instant.now().plusSeconds(60);
scaling.putScheduledAction(ScheduledActionFixtures.put(resource, "clamp")
.schedule(ScheduledActionFixtures.schedule(clampDeadline)).build());
scheduledActionScheduler.tick(clampDeadline);
assertEquals(1, ecs.describeServices(b -> b.cluster(cluster).services(serviceName)).services().getFirst().desiredCount());
assertEquals("Successful", scaling.describeScalingActivities(b -> b.serviceNamespace("ecs").resourceId(resource))
.scalingActivities().getFirst().statusCodeAsString());
assertEquals("UTC", ScheduledActionFixtures.describe(scaling, resource).scheduledActions().getFirst().timezone());
scaling.putScheduledAction(ScheduledActionFixtures.put(resource, "clamp")
.scalableTargetAction(ScheduledActionFixtures.bounds(0, 0)).build());
scheduledActionScheduler.tick(Instant.now().plusSeconds(60));
assertEquals(1, ecs.describeServices(b -> b.cluster(cluster).services(serviceName)).services().getFirst().desiredCount());
Instant rescheduledDeadline = Instant.now().plusSeconds(60);
scaling.putScheduledAction(ScheduledActionFixtures.put(resource, "clamp")
.schedule(ScheduledActionFixtures.schedule(rescheduledDeadline)).build());
scheduledActionScheduler.tick(rescheduledDeadline);
assertEquals(0, ecs.describeServices(b -> b.cluster(cluster).services(serviceName)).services().getFirst().desiredCount());
ScheduledAction completed = ScheduledActionFixtures.describe(scaling, resource).scheduledActions().getFirst();
assertEquals(identity.scheduledActionARN(), completed.scheduledActionARN());
assertEquals(identity.creationTime(), completed.creationTime());
scaling.putScheduledAction(ScheduledActionFixtures.put(resource, "cancel")
.schedule(ScheduledActionFixtures.schedule(Instant.now().plusSeconds(60)))
.scalableTargetAction(ScheduledActionFixtures.bounds(4, 4)).build());
scaling.deleteScheduledAction(b -> b.serviceNamespace("ecs").resourceId(resource)
.scalableDimension(ScheduledActionFixtures.DIMENSION).scheduledActionName("cancel"));
scheduledActionScheduler.tick(Instant.now().plusSeconds(120));
assertEquals(0, ecs.describeServices(b -> b.cluster(cluster).services(serviceName)).services().getFirst().desiredCount());
} finally {
ScheduledActionFixtures.deregister(scaling, resource);
ecs.deleteService(b -> b.cluster(cluster).service(serviceName).force(true));
ecs.deleteCluster(b -> b.cluster(cluster));
}
}
}
private static void assertScheduledCapacityUnchanged(ApplicationAutoScalingClient scaling, EcsClient ecs,
String resource, String cluster, String serviceName) {
ScalableTarget target = scaling.describeScalableTargets(b -> b.serviceNamespace("ecs").resourceIds(resource))
.scalableTargets().getFirst();
assertEquals(1, target.minCapacity());
assertEquals(10, target.maxCapacity());
assertEquals(2, ecs.describeServices(b -> b.cluster(cluster).services(serviceName)).services().getFirst().desiredCount());
assertEquals(0, scaling.describeScalingActivities(b -> b.serviceNamespace("ecs").resourceId(resource))
.scalingActivities().size());
}
}
@@ -1,5 +1,6 @@
package io.floci.aws.services.applicationautoscaling;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
@@ -9,7 +10,16 @@ import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestMethodOrder;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.applicationautoscaling.ApplicationAutoScalingClient;
import software.amazon.awssdk.services.applicationautoscaling.model.DescribeScheduledActionsResponse;
import software.amazon.awssdk.services.applicationautoscaling.model.InvalidNextTokenException;
import software.amazon.awssdk.services.applicationautoscaling.model.ObjectNotFoundException;
import software.amazon.awssdk.services.applicationautoscaling.model.ScheduledAction;
import software.amazon.awssdk.services.applicationautoscaling.model.ValidationException;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import static io.restassured.RestAssured.given;
@@ -20,6 +30,7 @@ import static org.hamcrest.Matchers.matchesPattern;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.jupiter.api.Assertions.*;
/**
* Wire-level coverage for the Application Auto Scaling API.
@@ -580,4 +591,193 @@ class ApplicationAutoScalingIntegrationTest {
""".formatted(ALARM_RESOURCE_ID, DIMENSION))
.when().post("/").then().statusCode(200);
}
@Test
void scheduledActionSdkLifecycle() {
String resource = "service/scheduled-sdk/service";
Instant deadline = Instant.now().plusSeconds(3600).truncatedTo(ChronoUnit.SECONDS);
try (ApplicationAutoScalingClient client = AwsTestClients.create(ApplicationAutoScalingClient.builder(),
"000000000000", Region.US_EAST_1)) {
ScheduledActionFixtures.register(client, resource, 1, 10);
try {
client.putScheduledAction(ScheduledActionFixtures.put(resource, "once")
.timezone("UTC").schedule(ScheduledActionFixtures.schedule(deadline))
.scalableTargetAction(ScheduledActionFixtures.bounds(2, 8)).build());
ScheduledAction original = ScheduledActionFixtures.describe(client, resource).scheduledActions().getFirst();
assertNotNull(original.creationTime());
assertEquals("UTC", original.timezone());
assertTrue(original.scheduledActionARN().contains(":autoscaling:us-east-1:000000000000:scheduledAction:"));
client.putScheduledAction(ScheduledActionFixtures.put(resource, "once")
.scalableTargetAction(ScheduledActionFixtures.bounds(3, null)).build());
ScheduledAction replaced = ScheduledActionFixtures.describe(client, resource).scheduledActions().getFirst();
assertEquals(3, replaced.scalableTargetAction().minCapacity());
assertNull(replaced.scalableTargetAction().maxCapacity());
assertEquals(original.schedule(), replaced.schedule());
assertEquals("UTC", replaced.timezone());
client.putScheduledAction(ScheduledActionFixtures.put(resource, "once").build());
client.putScheduledAction(ScheduledActionFixtures.put(resource, "once")
.schedule(ScheduledActionFixtures.schedule(deadline.plusSeconds(60))).build());
ScheduledAction rescheduled = ScheduledActionFixtures.describe(client, resource).scheduledActions().getFirst();
assertEquals(original.scheduledActionARN(), rescheduled.scheduledActionARN());
assertEquals(original.creationTime(), rescheduled.creationTime());
assertEquals("UTC", rescheduled.timezone());
client.putScheduledAction(ScheduledActionFixtures.put(resource, "two")
.schedule(ScheduledActionFixtures.schedule(deadline))
.scalableTargetAction(ScheduledActionFixtures.bounds(null, 4)).build());
ScheduledAction omittedTimezone = client.describeScheduledActions(b -> b.serviceNamespace("ecs")
.resourceId(resource).scheduledActionNames("two")).scheduledActions().getFirst();
assertNull(omittedTimezone.timezone());
client.putScheduledAction(ScheduledActionFixtures.put(resource, "two").timezone("UTC").build());
assertEquals("UTC", client.describeScheduledActions(b -> b.serviceNamespace("ecs")
.resourceId(resource).scheduledActionNames("two")).scheduledActions().getFirst().timezone());
DescribeScheduledActionsResponse page = client.describeScheduledActions(b -> b.serviceNamespace("ecs")
.resourceId(resource).maxResults(1));
assertEquals(1, page.scheduledActions().size());
assertNotNull(page.nextToken());
assertEquals(1, client.describeScheduledActions(b -> b.serviceNamespace("ecs").resourceId(resource)
.nextToken(page.nextToken()).maxResults(1)).scheduledActions().size());
assertThrows(InvalidNextTokenException.class, () -> client.describeScheduledActions(b -> b.serviceNamespace("ecs")
.resourceId("service/other/service").nextToken(page.nextToken())));
assertTrue(client.describeScheduledActions(b -> b.serviceNamespace("ecs").resourceId(resource)
.scheduledActionNames("missing")).scheduledActions().isEmpty());
client.deleteScheduledAction(b -> b.serviceNamespace("ecs").resourceId(resource)
.scalableDimension(DIMENSION).scheduledActionName("once"));
assertThrows(ObjectNotFoundException.class, () -> client.deleteScheduledAction(b -> b.serviceNamespace("ecs")
.resourceId(resource).scalableDimension(DIMENSION).scheduledActionName("once")));
assertThrows(ValidationException.class, () -> client.putScheduledAction(ScheduledActionFixtures.put(resource, "two")
.schedule("rate(1 minute)").build()));
assertThrows(ValidationException.class, () -> client.putScheduledAction(ScheduledActionFixtures.put(resource, "two")
.timezone("Europe/London").build()));
assertThrows(ValidationException.class, () -> client.putScheduledAction(ScheduledActionFixtures.put(resource, "two")
.startTime(deadline).build()));
assertThrows(ValidationException.class, () -> client.putScheduledAction(ScheduledActionFixtures.put(resource, "two")
.endTime(deadline).build()));
assertThrows(ValidationException.class, () -> client.describeScheduledActions(b -> b.serviceNamespace("ecs")
.resourceId(resource).maxResults(51)));
assertThrows(ValidationException.class, () -> client.describeScheduledActions(b -> b.serviceNamespace("ecs")
.scalableDimension(DIMENSION)));
} finally {
ScheduledActionFixtures.deregister(client, resource);
}
assertTrue(ScheduledActionFixtures.describe(client, resource).scheduledActions().isEmpty());
assertThrows(ObjectNotFoundException.class, () -> client.putScheduledAction(ScheduledActionFixtures.put(resource, "absent")
.schedule(ScheduledActionFixtures.schedule(deadline)).scalableTargetAction(ScheduledActionFixtures.bounds(0, 0)).build()));
}
}
@Test
void scheduledActionsRejectInvalidDatesAndUnsupportedExpressionSyntax() {
String resource = "service/scheduled-invalid-expression/service";
String validSchedule = "at(2096-02-29T12:34:56)";
try (ApplicationAutoScalingClient client = AwsTestClients.create(ApplicationAutoScalingClient.builder(),
"000000000000", Region.US_EAST_1)) {
ScheduledActionFixtures.register(client, resource, 0, 10);
try {
client.putScheduledAction(ScheduledActionFixtures.put(resource, "once")
.schedule(validSchedule).scalableTargetAction(ScheduledActionFixtures.bounds(0, 0)).build());
for (String schedule : List.of("at(2099-02-29T12:34:56)", "at(2099-04-31T12:34:56)",
"at(2099-01-01T24:00:00)", "at(2099-01-01T00:00:00Z)",
"at(2099-01-01T00:00:00+00:00)", "at(2099-01-01T00:00:00.123)",
"at(2099-01-01T00:00:00)trailing", "AT(2099-01-01T00:00:00)",
" at(2099-01-01T00:00:00)", "at( 2099-01-01T00:00:00)",
"rate(1 minute)", "cron(0 0 * * ? *)")) {
assertThrows(ValidationException.class, () -> client.putScheduledAction(
ScheduledActionFixtures.put(resource, "once").schedule(schedule).build()), schedule);
}
assertEquals(validSchedule, ScheduledActionFixtures.describe(client, resource)
.scheduledActions().getFirst().schedule());
} finally {
ScheduledActionFixtures.deregister(client, resource);
}
}
}
@Test
void scheduledActionsAreIsolatedByAccountAndRegion() {
String resource = "service/scheduled-isolation/service";
try (ApplicationAutoScalingClient first = AwsTestClients.create(ApplicationAutoScalingClient.builder(),
"111111111111", Region.US_EAST_1);
ApplicationAutoScalingClient account = AwsTestClients.create(ApplicationAutoScalingClient.builder(),
"222222222222", Region.US_EAST_1);
ApplicationAutoScalingClient region = AwsTestClients.create(ApplicationAutoScalingClient.builder(),
"111111111111", Region.EU_WEST_1)) {
for (ApplicationAutoScalingClient client : List.of(first, account, region)) {
ScheduledActionFixtures.register(client, resource, 0, 10);
}
try {
int min = 1;
for (ApplicationAutoScalingClient client : List.of(first, account, region)) {
assertTrue(ScheduledActionFixtures.describe(client, resource).scheduledActions().isEmpty());
client.putScheduledAction(ScheduledActionFixtures.put(resource, "same-name")
.schedule("at(2099-01-01T00:00:00)").scalableTargetAction(ScheduledActionFixtures.bounds(min++, null)).build());
}
assertEquals(1, ScheduledActionFixtures.describe(first, resource).scheduledActions().getFirst().scalableTargetAction().minCapacity());
assertEquals(2, ScheduledActionFixtures.describe(account, resource).scheduledActions().getFirst().scalableTargetAction().minCapacity());
assertEquals(3, ScheduledActionFixtures.describe(region, resource).scheduledActions().getFirst().scalableTargetAction().minCapacity());
first.deleteScheduledAction(b -> b.serviceNamespace("ecs").resourceId(resource)
.scalableDimension(DIMENSION).scheduledActionName("same-name"));
assertEquals(1, ScheduledActionFixtures.describe(account, resource).scheduledActions().size());
assertEquals(1, ScheduledActionFixtures.describe(region, resource).scheduledActions().size());
} finally {
for (ApplicationAutoScalingClient client : List.of(first, account, region)) {
ScheduledActionFixtures.deregister(client, resource);
}
}
}
}
@Test
void scheduledActionNamesRejectMalformedFiltersWithoutReturningUnfilteredActions() {
String resource = "service/scheduled-name-filter/service";
try (ApplicationAutoScalingClient client = AwsTestClients.create(ApplicationAutoScalingClient.builder(),
"000000000000", Region.US_EAST_1)) {
ScheduledActionFixtures.register(client, resource, 0, 10);
try {
for (String name : List.of("wanted", "other")) {
client.putScheduledAction(ScheduledActionFixtures.put(resource, name)
.schedule("at(2099-01-01T00:00:00)")
.scalableTargetAction(ScheduledActionFixtures.bounds(0, 1)).build());
}
assertEquals(List.of("wanted"), client.describeScheduledActions(b -> b.serviceNamespace("ecs")
.resourceId(resource).scheduledActionNames("wanted")).scheduledActions().stream()
.map(ScheduledAction::scheduledActionName).toList());
assertEquals(2, ScheduledActionFixtures.describe(client, resource).scheduledActions().size());
String base = "\"ServiceNamespace\":\"ecs\",\"ResourceId\":\"" + resource + "\",\"ScheduledActionNames\":";
for (String names : List.of("\"wanted\"", "1", "true", "{}", "[1]", "[true]", "[{}]", "[[]]", "[null]",
"[\"wanted\",1]")) {
call("DescribeScheduledActions").body("{" + base + names + "}").post("/").then()
.statusCode(400).body("__type", equalTo("ValidationException"));
}
for (String names : List.of("[]", "null")) {
call("DescribeScheduledActions").body("{" + base + names + "}").post("/").then()
.statusCode(200).body("ScheduledActions", hasSize(2));
}
} finally {
ScheduledActionFixtures.deregister(client, resource);
}
}
}
@Test
void unsupportedScheduledTimezonesAreRejectedWithoutCoercion() {
String base = "\"ServiceNamespace\":\"ecs\",\"ResourceId\":\"service/malformed-timezone/service\","
+ "\"ScalableDimension\":\"ecs:service:DesiredCount\",\"ScheduledActionName\":\"bad\","
+ "\"Schedule\":\"at(2099-01-01T00:00:00)\",\"ScalableTargetAction\":{\"MinCapacity\":0},\"Timezone\":";
for (String timezone : List.of("\"Europe/London\"", "\"Etc/UTC\"", "\"utc\"", "\"\"", "1", "true", "{}", "[]", "null")) {
call("PutScheduledAction").body("{" + base + timezone + "}").post("/").then()
.statusCode(400).body("__type", equalTo("ValidationException"));
}
}
@Test
void malformedScheduledBoundsAreRejectedWithoutCoercion() {
String base = "\"ServiceNamespace\":\"ecs\",\"ResourceId\":\"service/malformed/service\","
+ "\"ScalableDimension\":\"ecs:service:DesiredCount\",\"ScheduledActionName\":\"bad\","
+ "\"Schedule\":\"at(2030-01-01T00:00:00)\",\"ScalableTargetAction\":";
for (String bounds : List.of("{}", "\"\"", "{\"MinCapacity\":1.5}", "{\"MinCapacity\":\"2\"}",
"{\"MaxCapacity\":2147483648}", "{\"MinCapacity\":null}")) {
call("PutScheduledAction").body("{" + base + bounds + "}").post("/").then()
.statusCode(400).body("__type", equalTo("ValidationException"));
}
}
}
@@ -0,0 +1,82 @@
package io.floci.aws.services.applicationautoscaling;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.testing.ThreadStates;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
class ApplicationAutoScalingScheduledActionSchedulerTest {
@Test
void disabledServiceDoesNotStartOrRecover() {
ApplicationAutoScalingService service = mock(ApplicationAutoScalingService.class);
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
ApplicationAutoScalingScheduledActionScheduler scheduler = new ApplicationAutoScalingScheduledActionScheduler(service, config);
scheduler.onStart(null);
assertFalse(scheduler.active());
verifyNoInteractions(service);
scheduler.onStop(null);
}
@Test
void shutdownDrainsActiveSweepAndPreventsFurtherTicks() throws Exception {
ApplicationAutoScalingService service = mock(ApplicationAutoScalingService.class);
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().applicationautoscaling().enabled()).thenReturn(true);
when(config.services().applicationautoscaling().scheduledActionIntervalSeconds()).thenReturn(3600L);
ApplicationAutoScalingScheduledActionScheduler scheduler = new ApplicationAutoScalingScheduledActionScheduler(service, config);
CountDownLatch entered = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
AtomicReference<Thread> stoppingThread = new AtomicReference<>();
doAnswer(call -> {
entered.countDown();
assertTrue(release.await(10, TimeUnit.SECONDS));
return null;
}).when(service).runScheduledActions(any());
scheduler.onStart(null);
assertTrue(scheduler.active());
verify(service).recoverScheduledActions(any());
try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
Future<?> tick = executor.submit(() -> scheduler.tick(Instant.now()));
assertTrue(entered.await(10, TimeUnit.SECONDS));
Future<?> stop = executor.submit(() -> {
stoppingThread.set(Thread.currentThread());
scheduler.onStop(null);
});
ThreadStates.awaitBlockedOrDone(stoppingThread, stop);
assertFalse(stop.isDone());
release.countDown();
tick.get(10, TimeUnit.SECONDS);
stop.get(10, TimeUnit.SECONDS);
scheduler.tick(Instant.now());
verify(service, times(1)).runScheduledActions(any());
} finally {
release.countDown();
scheduler.onStop(null);
}
}
@Test
void resetPausesAndResumesTicks() {
ApplicationAutoScalingService service = mock(ApplicationAutoScalingService.class);
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
ApplicationAutoScalingScheduledActionScheduler scheduler = new ApplicationAutoScalingScheduledActionScheduler(service, config);
scheduler.beforeReset();
scheduler.tick(Instant.now());
verifyNoInteractions(service);
scheduler.afterReset();
scheduler.tick(Instant.now());
verify(service).runScheduledActions(any());
scheduler.onStop(null);
}
}
@@ -0,0 +1,507 @@
package io.floci.aws.services.applicationautoscaling;
import com.fasterxml.jackson.core.type.TypeReference;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.applicationautoscaling.model.ScalableTarget;
import io.floci.aws.services.applicationautoscaling.model.ScalingActivity;
import io.floci.aws.services.applicationautoscaling.model.ScalingPolicy;
import io.floci.aws.services.applicationautoscaling.model.ScheduledAction;
import io.floci.aws.services.applicationautoscaling.model.ScheduledAction.State;
import io.floci.aws.services.applicationautoscaling.model.SuspendedState;
import io.floci.aws.services.applicationautoscaling.model.TargetTrackingConfiguration;
import io.floci.aws.services.cloudwatch.metrics.CloudWatchMetricsService;
import io.floci.aws.services.cloudwatch.metrics.model.MetricAlarm;
import io.floci.aws.testing.StorageFactories;
import io.floci.aws.testing.ThreadStates;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
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.time.Instant;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static io.floci.aws.services.applicationautoscaling.ScheduledActionFixtures.schedule;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
class ApplicationAutoScalingScheduledActionServiceTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
private static final String NAMESPACE = "ecs";
private static final String RESOURCE = "service/cluster/service";
private static final String DIMENSION = "ecs:service:DesiredCount";
private static final Instant NOW = Instant.parse("2030-01-01T00:00:00Z");
private ApplicationAutoScalingService service;
private EcsCapacityAdjuster adjuster;
private InMemoryStorage<String, ScheduledAction> actions;
private AtomicInteger capacity;
@BeforeEach
void setUp() {
actions = new InMemoryStorage<>();
capacity = new AtomicInteger(5);
adjuster = mock(EcsCapacityAdjuster.class);
when(adjuster.getCurrentCapacity(anyString(), anyString())).thenAnswer(call -> capacity.get());
doAnswer(call -> {
capacity.set(call.getArgument(1));
return null;
}).when(adjuster).setCapacity(anyString(), anyInt(), anyString());
service = new ApplicationAutoScalingService(new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), actions, new RegionResolver(REGION, ACCOUNT),
mock(CloudWatchMetricsService.class), adjuster);
register(null);
}
private void register(SuspendedState suspension) {
service.registerScalableTarget(NAMESPACE, RESOURCE, DIMENSION, 1, 10, null, suspension, null, REGION);
}
private ScheduledAction put(String name, Instant deadline, Integer min, Integer max) {
return service.putScheduledAction(NAMESPACE, RESOURCE, DIMENSION, name,
deadline == null ? null : schedule(deadline), true, min, max, null, REGION, NOW);
}
private List<ScheduledAction> describe() {
return service.describeScheduledActions(NAMESPACE, RESOURCE, DIMENSION, List.of(), null, null, REGION).items();
}
private ScheduledAction action(String name) {
return describe().stream().filter(a -> name.equals(a.getScheduledActionName())).findFirst().orElseThrow();
}
private void assertBounds(int min, int max, int desired) {
ScalableTarget target = service.describeScalableTargets(NAMESPACE, List.of(RESOURCE), DIMENSION, REGION).getFirst();
assertEquals(min, target.getMinCapacity());
assertEquals(max, target.getMaxCapacity());
assertEquals(desired, capacity.get());
}
@Test
void completedActionRetainsIdentityAndOnlyExplicitRescheduleRearms() {
ScheduledAction original = put("once", NOW.plusSeconds(1), 7, 9);
service.runScheduledActions(NOW.plusSeconds(1));
assertBounds(7, 9, 7);
assertEquals(State.SUCCEEDED, action("once").getState());
put("once", null, 0, null);
service.runScheduledActions(NOW.plusSeconds(2));
assertBounds(7, 9, 7);
ScheduledAction updated = service.putScheduledAction(NAMESPACE, RESOURCE, DIMENSION, "once",
schedule(NOW.plusSeconds(3)), false, null, null, null, REGION, NOW.plusSeconds(2));
assertEquals(original.getScheduledActionArn(), updated.getScheduledActionArn());
assertEquals(original.getCreationTime(), updated.getCreationTime());
service.runScheduledActions(NOW.plusSeconds(3));
assertBounds(0, 9, 7);
assertEquals(2, service.describeScalingActivities(NAMESPACE, RESOURCE, DIMENSION, REGION).size());
}
@Test
void updatesReplaceWholeActionAndPreserveOmittedFields() {
put("replace", NOW.plusSeconds(1), 2, 8);
put("replace", null, 3, null);
assertNull(action("replace").getMaxCapacity());
service.putScheduledAction(NAMESPACE, RESOURCE, DIMENSION, "replace", null, false, null, null, null, REGION, NOW);
assertEquals(schedule(NOW.plusSeconds(1)), action("replace").getSchedule());
service.runScheduledActions(NOW.plusSeconds(1));
assertBounds(3, 10, 5);
put("replace", NOW.plusSeconds(2), null, 4);
assertNull(action("replace").getMinCapacity());
service.runScheduledActions(NOW.plusSeconds(2));
assertBounds(3, 4, 4);
}
@Test
void executionUsesCurrentBoundsAndOrdersByDeadlineThenName() {
put("z", NOW.plusSeconds(1), 3, null);
put("b", NOW.plusSeconds(2), null, 2);
put("a", NOW.plusSeconds(2), 0, null);
service.runScheduledActions(NOW.plusSeconds(3));
assertBounds(0, 2, 2);
assertTrue(describe().stream().allMatch(a -> a.getState() == State.SUCCEEDED));
assertEquals(3, service.describeScalingActivities(NAMESPACE, RESOURCE, DIMENSION, REGION).size());
}
@Test
void invalidEffectiveBoundsFailWithoutTargetMutationAndDoNotStopOtherActions() {
put("bad", NOW.plusSeconds(1), 12, null);
put("good", NOW.plusSeconds(2), null, 4);
service.runScheduledActions(NOW.plusSeconds(2));
assertEquals(State.FAILED, action("bad").getState());
assertEquals(State.SUCCEEDED, action("good").getState());
assertBounds(1, 4, 4);
}
@Test
void unchangedBoundsStillRecordSuccessfulActivity() {
put("unchanged", NOW, 1, 10);
service.runScheduledActions(NOW);
assertBounds(1, 10, 5);
verify(adjuster, never()).setCapacity(anyString(), anyInt(), anyString());
assertEquals("Successful", service.describeScalingActivities(NAMESPACE, RESOURCE, DIMENSION, REGION)
.getFirst().getStatusCode());
}
@Test
void pastAcceptedInactiveAndCurrentSecondEligible() {
service.putScheduledAction(NAMESPACE, RESOURCE, DIMENSION, "past", schedule(NOW.minusSeconds(1)),
true, 0, 0, null, REGION, NOW.plusMillis(900));
service.putScheduledAction(NAMESPACE, RESOURCE, DIMENSION, "current", schedule(NOW),
true, 0, 4, null, REGION, NOW.plusMillis(900));
service.runScheduledActions(NOW.plusSeconds(1));
assertEquals(State.SKIPPED, action("past").getState());
assertEquals(State.SUCCEEDED, action("current").getState());
assertBounds(0, 4, 4);
}
@Test
void replacingPendingScheduleCancelsTheOriginalDeadline() {
put("move", NOW.plusSeconds(1), 0, 0);
put("move", NOW.plusSeconds(10), 2, 8);
service.runScheduledActions(NOW.plusSeconds(1));
assertBounds(1, 10, 5);
assertEquals(State.PENDING, action("move").getState());
service.runScheduledActions(NOW.plusSeconds(10));
assertBounds(2, 8, 5);
assertEquals(State.SUCCEEDED, action("move").getState());
}
@Test
void cancellationAndDeregistrationRemoveOccurrences() {
put("delete", NOW, 0, 0);
service.deleteScheduledAction(NAMESPACE, RESOURCE, DIMENSION, "delete", REGION);
service.runScheduledActions(NOW);
assertBounds(1, 10, 5);
put("target", NOW, 0, 0);
service.deregisterScalableTarget(NAMESPACE, RESOURCE, DIMENSION, REGION);
assertTrue(describe().isEmpty());
assertThrows(AwsException.class, () -> service.deleteScheduledAction(NAMESPACE, RESOURCE, DIMENSION, "target", REGION));
assertThrows(AwsException.class, () -> put("missing", NOW, 0, 0));
}
@Test
void suspensionBetweenTicksSettlesPriorStateAndConsumesMissedOccurrences() {
Instant realNow = Instant.now();
service.putScheduledAction(NAMESPACE, RESOURCE, DIMENSION, "before-suspend", schedule(realNow.minusSeconds(10)),
true, 2, null, null, REGION, realNow.minusSeconds(20));
SuspendedState state = new SuspendedState();
state.setScheduledScalingSuspended(true);
register(state);
assertEquals(State.SUCCEEDED, action("before-suspend").getState());
service.putScheduledAction(NAMESPACE, RESOURCE, DIMENSION, "during-suspend", schedule(realNow.minusSeconds(5)),
true, 0, 0, null, REGION, realNow.minusSeconds(20));
service.registerScalableTarget(NAMESPACE, RESOURCE, DIMENSION, null, null, null, null, null, REGION);
assertTrue(service.findTarget(REGION, NAMESPACE, RESOURCE, DIMENSION).orElseThrow()
.getSuspendedState().isScheduledScalingSuspended());
register(new SuspendedState());
assertEquals(State.SKIPPED, action("during-suspend").getState());
assertBounds(1, 10, 5);
}
@Test
void dynamicSuspensionDoesNotGateScheduledScaling() {
SuspendedState state = new SuspendedState();
state.setDynamicScalingInSuspended(true);
state.setDynamicScalingOutSuspended(true);
register(state);
put("scheduled", NOW, 7, 10);
service.runScheduledActions(NOW);
assertBounds(7, 10, 7);
}
@Test
void ecsFailureLeavesCommittedBoundsAndIsNotRetried() {
doThrow(new IllegalStateException("ECS failed")).when(adjuster).setCapacity(anyString(), anyInt(), anyString());
put("failure", NOW, 7, 10);
service.runScheduledActions(NOW);
service.runScheduledActions(NOW.plusSeconds(1));
assertBounds(7, 10, 5);
assertEquals(State.FAILED, action("failure").getState());
verify(adjuster).setCapacity(RESOURCE, 7, REGION);
ScalingActivity activity = service.describeScalingActivities(NAMESPACE, RESOURCE, DIMENSION, REGION).getFirst();
assertEquals("Failed", activity.getStatusCode());
assertEquals("ECS failed", activity.getStatusMessage());
}
@Test
void rescheduleBeforeExecutionReordersDueActionsUnderTargetLock() throws Exception {
put("first", NOW.plusSeconds(1), 0, 3);
put("second", NOW.plusSeconds(2), 0, 4);
AtomicReference<Thread> sweepThread = new AtomicReference<>();
try (ExecutorService executor = Executors.newSingleThreadExecutor()) {
Future<?> sweep;
synchronized (service.targetLock(REGION, NAMESPACE, RESOURCE, DIMENSION)) {
sweep = executor.submit(() -> {
sweepThread.set(Thread.currentThread());
service.runScheduledActions(NOW.plusSeconds(4));
});
ThreadStates.awaitBlockedOrDone(sweepThread, sweep);
assertFalse(sweep.isDone());
put("first", NOW.plusSeconds(3), 0, 8);
}
sweep.get(10, TimeUnit.SECONDS);
}
assertBounds(0, 8, 4);
assertTrue(describe().stream().allMatch(a -> a.getState() == State.SUCCEEDED));
}
@Test
void claimWriteFailureDoesNotMutateStoredActionOrApplyEffects() {
InMemoryStorage<String, ScheduledAction> failing = spy(actions);
service = new ApplicationAutoScalingService(new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), failing, new RegionResolver(REGION, ACCOUNT),
mock(CloudWatchMetricsService.class), adjuster);
register(null);
put("claim", NOW, 7, 10);
doThrow(new IllegalStateException("claim write failed")).when(failing).putAllAtomically(anyMap());
service.runScheduledActions(NOW);
assertEquals(State.PENDING, action("claim").getState());
assertBounds(1, 10, 5);
verifyNoInteractions(adjuster);
}
@Test
void mutationWaitsForClaimedExecutionAndDoesNotOverwriteNewBounds() throws Exception {
CountDownLatch entered = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
AtomicReference<Thread> mutationThread = new AtomicReference<>();
doAnswer(call -> {
entered.countDown();
assertTrue(release.await(10, TimeUnit.SECONDS));
capacity.set(call.getArgument(1));
return null;
}).when(adjuster).setCapacity(anyString(), anyInt(), anyString());
put("blocked", NOW, 7, 9);
try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
Future<?> execution = executor.submit(() -> service.runScheduledActions(NOW));
assertTrue(entered.await(10, TimeUnit.SECONDS));
Future<?> mutation = executor.submit(() -> {
mutationThread.set(Thread.currentThread());
service.tagResource(service.findTarget(REGION, NAMESPACE, RESOURCE, DIMENSION).orElseThrow()
.getScalableTargetArn(), Map.of("tag", "value"), REGION);
});
ThreadStates.awaitBlockedOrDone(mutationThread, mutation);
assertFalse(mutation.isDone());
release.countDown();
execution.get(10, TimeUnit.SECONDS);
mutation.get(10, TimeUnit.SECONDS);
} finally {
release.countDown();
}
assertBounds(7, 9, 7);
assertEquals(Map.of("tag", "value"), service.findTarget(REGION, NAMESPACE, RESOURCE, DIMENSION).orElseThrow().getTags());
}
@Test
void dynamicExecutionWaitsAndRecomputesUsingScheduledBounds() throws Exception {
TargetTrackingConfiguration config = new TargetTrackingConfiguration();
config.setTargetValue(50.0);
ScalingPolicy policy = service.putScalingPolicy("dynamic", "TargetTrackingScaling", NAMESPACE, RESOURCE,
DIMENSION, config, null, REGION);
ScalingPolicyAlarmActionHandler handler = dynamicHandler();
MetricAlarm alarm = new MetricAlarm();
alarm.setComparisonOperator("GreaterThanThreshold");
alarm.setThreshold(50.0);
CountDownLatch entered = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
AtomicReference<Thread> dynamicThread = new AtomicReference<>();
doAnswer(call -> {
entered.countDown();
assertTrue(release.await(10, TimeUnit.SECONDS));
capacity.set(call.getArgument(1));
return null;
}).when(adjuster).setCapacity(anyString(), anyInt(), anyString());
put("scheduled", NOW, 0, 3);
try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
Future<?> execution = executor.submit(() -> service.runScheduledActions(NOW));
assertTrue(entered.await(10, TimeUnit.SECONDS));
Future<?> dynamic = executor.submit(() -> {
dynamicThread.set(Thread.currentThread());
handler.handle(policy.getPolicyArn(), alarm, 100.0, REGION);
});
ThreadStates.awaitBlockedOrDone(dynamicThread, dynamic);
assertFalse(dynamic.isDone());
release.countDown();
execution.get(10, TimeUnit.SECONDS);
dynamic.get(10, TimeUnit.SECONDS);
} finally {
release.countDown();
}
assertBounds(0, 3, 3);
verify(adjuster, times(1)).setCapacity(RESOURCE, 3, REGION);
}
@SuppressWarnings("unchecked")
private ScalingPolicyAlarmActionHandler dynamicHandler() {
Instance<CapacityAdjuster> adjusters = mock(Instance.class);
when(adjusters.iterator()).thenAnswer(call -> List.<CapacityAdjuster>of(adjuster).iterator());
when(adjuster.supports(DIMENSION)).thenReturn(true);
return new ScalingPolicyAlarmActionHandler(service, adjusters);
}
@Test
void scheduledMinimumReductionPermitsLaterDynamicScaleInWithoutForcingIt() {
capacity.set(1);
TargetTrackingConfiguration config = new TargetTrackingConfiguration();
config.setTargetValue(50.0);
config.setScaleInCooldown(0);
ScalingPolicy policy = service.putScalingPolicy("idle", "TargetTrackingScaling", NAMESPACE, RESOURCE,
DIMENSION, config, null, REGION);
ScalingPolicyAlarmActionHandler handler = dynamicHandler();
MetricAlarm alarm = new MetricAlarm();
alarm.setComparisonOperator("LessThanThreshold");
alarm.setThreshold(50.0);
handler.handle(policy.getPolicyArn(), alarm, 0.0, REGION);
assertBounds(1, 10, 1);
put("lower-minimum", NOW, 0, null);
service.runScheduledActions(NOW);
assertBounds(0, 10, 1);
verify(adjuster, never()).setCapacity(anyString(), anyInt(), anyString());
handler.handle(policy.getPolicyArn(), alarm, 0.0, REGION);
assertBounds(0, 10, 0);
}
@ParameterizedTest
@ValueSource(strings = {"delete", "reschedule", "deregister"})
void mutationBeforeClaimPreventsStaleSweepExecution(String mutation) throws Exception {
put("pending", NOW.plusSeconds(1), 0, 0);
AtomicReference<Thread> sweepThread = new AtomicReference<>();
try (ExecutorService executor = Executors.newSingleThreadExecutor()) {
Future<?> sweep;
synchronized (service.targetLock(REGION, NAMESPACE, RESOURCE, DIMENSION)) {
sweep = executor.submit(() -> {
sweepThread.set(Thread.currentThread());
service.runScheduledActions(NOW.plusSeconds(2));
});
ThreadStates.awaitBlockedOrDone(sweepThread, sweep);
assertFalse(sweep.isDone());
switch (mutation) {
case "delete" -> service.deleteScheduledAction(NAMESPACE, RESOURCE, DIMENSION, "pending", REGION);
case "reschedule" -> put("pending", NOW.plusSeconds(10), 0, 0);
case "deregister" -> service.deregisterScalableTarget(NAMESPACE, RESOURCE, DIMENSION, REGION);
default -> throw new IllegalArgumentException(mutation);
}
}
sweep.get(10, TimeUnit.SECONDS);
}
assertEquals(5, capacity.get());
verifyNoInteractions(adjuster);
assertTrue(service.describeScalingActivities(NAMESPACE, RESOURCE, DIMENSION, REGION).isEmpty());
}
@Test
void activityWriteFailureAndTerminalWriteFailureCannotRepeatEffects() {
InMemoryStorage<String, ScalingActivity> activityStore = spy(new InMemoryStorage<>());
InMemoryStorage<String, ScheduledAction> actionStore = spy(actions);
service = new ApplicationAutoScalingService(new InMemoryStorage<>(), new InMemoryStorage<>(),
activityStore, actionStore, new RegionResolver(REGION, ACCOUNT), mock(CloudWatchMetricsService.class), adjuster);
register(null);
put("activity", NOW, 7, 9);
doThrow(new IllegalStateException("activity write failed")).when(activityStore).putAllAtomically(anyMap());
service.runScheduledActions(NOW);
assertEquals(State.SUCCEEDED, action("activity").getState());
doAnswer(call -> {
Map<String, ScheduledAction> entries = call.getArgument(0);
if (entries.values().stream().anyMatch(a -> a.getState() == State.SUCCEEDED || a.getState() == State.FAILED)) {
throw new IllegalStateException("terminal write failed");
}
return call.callRealMethod();
}).when(actionStore).putAllAtomically(anyMap());
put("terminal", NOW.plusSeconds(1), 8, 9);
service.runScheduledActions(NOW.plusSeconds(1));
assertEquals(State.CLAIMED, action("terminal").getState());
service.runScheduledActions(NOW.plusSeconds(2));
assertBounds(8, 9, 8);
verify(adjuster).setCapacity(RESOURCE, 7, REGION);
verify(adjuster).setCapacity(RESOURCE, 8, REGION);
}
@Test
void selectionScopedPaginationAndValidation() {
put("a", NOW, 0, 1);
put("b", NOW, 0, 2);
PaginatedResult<ScheduledAction> first = service.describeScheduledActions(NAMESPACE, RESOURCE, DIMENSION,
List.of(), 1, null, REGION);
assertEquals("a", first.items().getFirst().getScheduledActionName());
assertEquals("b", service.describeScheduledActions(NAMESPACE, RESOURCE, DIMENSION,
List.of(), 1, first.nextToken(), REGION).items().getFirst().getScheduledActionName());
assertThrows(AwsException.class, () -> service.describeScheduledActions(NAMESPACE, "other", DIMENSION,
List.of(), 1, first.nextToken(), REGION));
assertThrows(AwsException.class, () -> service.describeScheduledActions(NAMESPACE, null, DIMENSION,
List.of(), 1, null, REGION));
assertThrows(AwsException.class, () -> service.describeScheduledActions(NAMESPACE, RESOURCE, DIMENSION,
List.of(), 51, null, REGION));
assertThrows(AwsException.class, () -> service.describeScheduledActions(NAMESPACE, RESOURCE, DIMENSION,
Collections.nCopies(51, "a"), null, null, REGION));
assertTrue(service.describeScheduledActions(NAMESPACE, "missing", null, List.of(), null, null, REGION).items().isEmpty());
assertThrows(AwsException.class, () -> service.putScheduledAction(NAMESPACE, RESOURCE, DIMENSION, "a",
"at(2030-02-30T00:00:00)", false, null, null, null, REGION, NOW));
assertThrows(AwsException.class, () -> put("empty", NOW, null, null));
}
@ParameterizedTest
@ValueSource(strings = {"persistent", "hybrid", "wal"})
void restartPreservesFutureAndCompletedActionsAndSkipsOverdueAndClaimed(String mode, @TempDir Path directory) {
RegionResolver resolver = new RegionResolver(REGION, ACCOUNT);
CloudWatchMetricsService cloudWatch = mock(CloudWatchMetricsService.class);
StorageFactory first = StorageFactories.open(directory, mode, ACCOUNT);
try {
service = new ApplicationAutoScalingService(first, resolver, cloudWatch, adjuster);
register(null);
put("completed", NOW, 2, 8);
service.runScheduledActions(NOW);
put("overdue", NOW.plusSeconds(1), 0, 0);
service.putScheduledAction(NAMESPACE, RESOURCE, DIMENSION, "future", schedule(NOW.plusSeconds(10)),
true, 0, 4, "UTC", REGION, NOW);
put("future", null, 0, 4);
assertEquals("UTC", action("future").getTimezone());
put("claimed", NOW.plusSeconds(5), 0, 0);
first.create("applicationautoscaling", "application-autoscaling-scheduled-actions.json",
new TypeReference<Map<String, ScheduledAction>>() {})
.putAllAtomically(Map.of(REGION + "::ecs::" + DIMENSION + "::" + RESOURCE + "::claimed",
claimed(action("claimed"))));
first.flushAll();
} finally {
first.shutdownAll();
}
StorageFactory restored = StorageFactories.open(directory, mode, ACCOUNT);
try {
service = new ApplicationAutoScalingService(restored, resolver, cloudWatch, adjuster);
restored.loadAll();
service.recoverScheduledActions(NOW.plusSeconds(2));
assertEquals(State.SKIPPED, action("overdue").getState());
assertEquals(State.SKIPPED, action("claimed").getState());
assertEquals(State.SUCCEEDED, action("completed").getState());
assertEquals("UTC", action("future").getTimezone());
assertNull(action("completed").getTimezone());
service.runScheduledActions(NOW.plusSeconds(10));
assertEquals("UTC", action("future").getTimezone());
assertBounds(0, 4, 4);
assertEquals(2, service.describeScalingActivities(NAMESPACE, RESOURCE, DIMENSION, REGION).size());
} finally {
restored.shutdownAll();
}
}
private static ScheduledAction claimed(ScheduledAction action) {
action.setState(State.CLAIMED);
return action;
}
}
@@ -71,7 +71,7 @@ class ApplicationAutoScalingServiceTest {
service = new ApplicationAutoScalingService(
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
regionResolver, cloudWatch);
new InMemoryStorage<>(), regionResolver, cloudWatch, mock(EcsCapacityAdjuster.class));
}
private ScalableTarget register() {
@@ -38,6 +38,7 @@ class ScalingPolicyAlarmActionHandlerTest {
@BeforeEach
void setUp() {
when(service.targetLock(anyString(), anyString(), anyString(), anyString())).thenReturn(new Object());
when(adjusters.iterator()).thenAnswer(inv -> List.of(adjuster).iterator());
when(adjuster.supports("ecs:service:DesiredCount")).thenReturn(true);
handler = new ScalingPolicyAlarmActionHandler(service, adjusters);
@@ -0,0 +1,43 @@
package io.floci.aws.services.applicationautoscaling;
import software.amazon.awssdk.services.applicationautoscaling.ApplicationAutoScalingClient;
import software.amazon.awssdk.services.applicationautoscaling.model.DescribeScheduledActionsResponse;
import software.amazon.awssdk.services.applicationautoscaling.model.PutScheduledActionRequest;
import software.amazon.awssdk.services.applicationautoscaling.model.ScalableTargetAction;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
/** Shared SDK requests and UTC schedule formatting for scheduled-action tests. */
final class ScheduledActionFixtures {
static final String DIMENSION = "ecs:service:DesiredCount";
private ScheduledActionFixtures() {}
static String schedule(Instant instant) {
return "at(" + DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss").withZone(ZoneOffset.UTC).format(instant) + ")";
}
static void register(ApplicationAutoScalingClient client, String resource, int min, int max) {
client.registerScalableTarget(b -> b.serviceNamespace("ecs").resourceId(resource).scalableDimension(DIMENSION)
.minCapacity(min).maxCapacity(max));
}
static PutScheduledActionRequest.Builder put(String resource, String name) {
return PutScheduledActionRequest.builder().serviceNamespace("ecs").resourceId(resource)
.scalableDimension(DIMENSION).scheduledActionName(name);
}
static ScalableTargetAction bounds(Integer min, Integer max) {
return ScalableTargetAction.builder().minCapacity(min).maxCapacity(max).build();
}
static DescribeScheduledActionsResponse describe(ApplicationAutoScalingClient client, String resource) {
return client.describeScheduledActions(b -> b.serviceNamespace("ecs").resourceId(resource).scalableDimension(DIMENSION));
}
static void deregister(ApplicationAutoScalingClient client, String resource) {
client.deregisterScalableTarget(b -> b.serviceNamespace("ecs").resourceId(resource).scalableDimension(DIMENSION));
}
}
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
import io.floci.aws.services.redshift.model.Endpoint;
import io.floci.aws.services.redshiftserverless.RedshiftServerlessRuntime;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.EnforcementFixtures;
import io.floci.aws.testing.IamEnforcementProfile;
import io.floci.aws.testing.PartitionCleanup;
@@ -19,6 +20,11 @@ import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.applicationautoscaling.ApplicationAutoScalingClient;
import software.amazon.awssdk.services.applicationautoscaling.model.ApplicationAutoScalingException;
import software.amazon.awssdk.services.applicationautoscaling.model.PutScheduledActionRequest;
import software.amazon.awssdk.services.applicationautoscaling.model.ScalableTargetAction;
import java.io.IOException;
import java.io.UncheckedIOException;
@@ -36,6 +42,7 @@ import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.not;
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.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
@@ -1305,6 +1312,40 @@ class IamRequestResourceEnforcementIntegrationTest {
scaling(user, "DeregisterScalableTarget", other + "}").statusCode(200);
}
@Test
void scheduledActionWritesUseTargetArnAndDescribeRequiresWildcard() {
User user = user("res-scheduled-actions");
String resource = "service/res-" + suffix() + "/scheduled";
try (ApplicationAutoScalingClient adminClient = AwsTestClients.create(ApplicationAutoScalingClient.builder(), ADMIN, Region.US_EAST_1);
ApplicationAutoScalingClient client = AwsTestClients.create(ApplicationAutoScalingClient.builder(), user.accessKeyId(), Region.US_EAST_1)) {
String arn = adminClient.registerScalableTarget(b -> b.serviceNamespace("ecs").resourceId(resource)
.scalableDimension("ecs:service:DesiredCount").minCapacity(0).maxCapacity(2)).scalableTargetARN();
try {
PutScheduledActionRequest put = PutScheduledActionRequest.builder().serviceNamespace("ecs").resourceId(resource)
.scalableDimension("ecs:service:DesiredCount").scheduledActionName("scheduled")
.schedule("at(2099-01-01T00:00:00)")
.scalableTargetAction(ScalableTargetAction.builder().minCapacity(0).build()).build();
user.policy(allowOn("application-autoscaling:PutScheduledAction", TARGETS + "other"));
assertEquals("AccessDeniedException", assertThrows(ApplicationAutoScalingException.class,
() -> client.putScheduledAction(put)).awsErrorDetails().errorCode());
user.policy(allowOn("application-autoscaling:PutScheduledAction", arn));
client.putScheduledAction(put);
user.policy(allowOn("application-autoscaling:DescribeScheduledActions", arn));
assertThrows(ApplicationAutoScalingException.class, () -> client.describeScheduledActions(b -> b.serviceNamespace("ecs").resourceId(resource)));
user.policy(allowOn("application-autoscaling:DescribeScheduledActions", "*"));
assertEquals(1, client.describeScheduledActions(b -> b.serviceNamespace("ecs").resourceId(resource)).scheduledActions().size());
user.policy(allowOn("application-autoscaling:DeleteScheduledAction", TARGETS + "other"));
assertThrows(ApplicationAutoScalingException.class, () -> client.deleteScheduledAction(b -> b.serviceNamespace("ecs")
.resourceId(resource).scalableDimension("ecs:service:DesiredCount").scheduledActionName("scheduled")));
user.policy(allowOn("application-autoscaling:DeleteScheduledAction", arn));
client.deleteScheduledAction(b -> b.serviceNamespace("ecs").resourceId(resource)
.scalableDimension("ecs:service:DesiredCount").scheduledActionName("scheduled"));
} finally {
adminClient.deregisterScalableTarget(b -> b.serviceNamespace("ecs").resourceId(resource).scalableDimension("ecs:service:DesiredCount"));
}
}
}
/** The members naming an ECS service's desired count as a scalable target, an open JSON object. */
private static String scalableTarget(String resourceId) {
return "{\"ServiceNamespace\":\"ecs\",\"ResourceId\":\"" + resourceId + "\","