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

+1 -1
View File
@@ -380,7 +380,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/
| AWS RAM | In-process | EnableSharingWithAwsOrganization opt-in |
| AWS Batch | In-process | Compute environments, job queues, job definitions, job submission and lifecycle |
| Auto Scaling | In-process with reconciler | Launch configs, ASGs, desired capacity reconciliation, lifecycle hooks |
| Application Auto Scaling | In-process | Scalable targets, target-tracking and step scaling policies, CloudWatch alarm creation, tagging (policies are stored but inert) |
| Application Auto Scaling | In-process | Scalable targets, dynamic ECS scaling, one-off UTC scheduled ECS scaling, CloudWatch alarms, tagging |
| Elastic Beanstalk | In-process | Applications, application versions, environments, configuration templates, platform and solution stack metadata |
| AWS Backup | In-process | Vaults, backup plans, selections, simulated job lifecycle, recovery points |
| Amazon Data Lifecycle Manager | In-process | Lifecycle policy and tag management; schedules are stored but do not create snapshots or AMIs |
@@ -538,6 +538,10 @@
<groupId>software.amazon.awssdk</groupId>
<artifactId>scheduler</artifactId>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>applicationautoscaling</artifactId>
</dependency>
<!-- Auto Scaling client -->
<dependency>
<groupId>software.amazon.awssdk</groupId>
@@ -21,6 +21,7 @@ import software.amazon.awssdk.services.apigatewayv2.ApiGatewayV2Client;
import software.amazon.awssdk.services.appconfig.AppConfigClient;
import software.amazon.awssdk.services.appconfigdata.AppConfigDataClient;
import software.amazon.awssdk.services.appintegrations.AppIntegrationsClient;
import software.amazon.awssdk.services.applicationautoscaling.ApplicationAutoScalingClient;
import software.amazon.awssdk.services.appsync.AppSyncClient;
import software.amazon.awssdk.services.athena.AthenaClient;
import software.amazon.awssdk.services.athena.model.GetQueryExecutionRequest;
@@ -1589,6 +1590,14 @@ public final class TestFixtures {
.build();
}
public static ApplicationAutoScalingClient applicationAutoScalingClient() {
return ApplicationAutoScalingClient.builder()
.endpointOverride(ENDPOINT)
.region(REGION)
.credentialsProvider(CREDENTIALS)
.build();
}
public static AutoScalingClient autoScalingClient() {
return AutoScalingClient.builder()
.endpointOverride(ENDPOINT)
@@ -0,0 +1,254 @@
package com.floci.test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
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.PutScheduledActionRequest;
import software.amazon.awssdk.services.applicationautoscaling.model.ScalableDimension;
import software.amazon.awssdk.services.applicationautoscaling.model.ScalableTarget;
import software.amazon.awssdk.services.applicationautoscaling.model.ScalingActivity;
import software.amazon.awssdk.services.applicationautoscaling.model.ScalingActivityStatusCode;
import software.amazon.awssdk.services.applicationautoscaling.model.ScheduledAction;
import software.amazon.awssdk.services.applicationautoscaling.model.ServiceNamespace;
import software.amazon.awssdk.services.ecs.EcsClient;
import software.amazon.awssdk.services.ecs.model.ClusterContainsTasksException;
import software.amazon.awssdk.services.ecs.model.ContainerDefinition;
import software.amazon.awssdk.services.ecs.model.DesiredStatus;
import software.amazon.awssdk.services.ecs.model.LaunchType;
import software.amazon.awssdk.services.ecs.model.TaskDefinition;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@DisplayName("Application Auto Scaling one-off ECS scheduled actions")
class ApplicationAutoScalingTest {
private static final ServiceNamespace NAMESPACE = ServiceNamespace.ECS;
private static final ScalableDimension DIMENSION = ScalableDimension.ECS_SERVICE_DESIRED_COUNT;
private static final DateTimeFormatter SCHEDULE_TIME =
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss").withZone(ZoneOffset.UTC);
private ApplicationAutoScalingClient scaling;
private String name;
private String resourceId;
private boolean targetRegistered;
@BeforeEach
void registerTarget() {
name = TestFixtures.uniqueName("sdk-scheduled");
resourceId = "service/" + name + "/" + name;
scaling = TestFixtures.applicationAutoScalingClient();
scaling.registerScalableTarget(r -> r.serviceNamespace(NAMESPACE).resourceId(resourceId)
.scalableDimension(DIMENSION).minCapacity(0).maxCapacity(4));
targetRegistered = true;
}
@AfterEach
void cleanup() {
if (scaling != null) {
try {
if (targetRegistered) {
scaling.deregisterScalableTarget(r -> r.serviceNamespace(NAMESPACE).resourceId(resourceId)
.scalableDimension(DIMENSION));
}
} finally {
scaling.close();
}
}
}
@Test
@DisplayName("Create, replace supplied bounds, preserve omitted fields, and delete")
void scheduledActionLifecycle() {
String schedule = at(Instant.now().plusSeconds(3600));
scaling.putScheduledAction(action(name).schedule(schedule)
.scalableTargetAction(b -> b.minCapacity(1).maxCapacity(3)).build());
ScheduledAction created = actionNamed(name);
assertThat(created.scheduledActionARN()).contains(":autoscaling:",
":resource/ecs/" + resourceId + ":scheduledActionName/" + name);
assertThat(created.creationTime()).isNotNull();
assertThat(created.serviceNamespace()).isEqualTo(NAMESPACE);
assertThat(created.scalableDimension()).isEqualTo(DIMENSION);
assertThat(created.resourceId()).isEqualTo(resourceId);
scaling.putScheduledAction(action(name).scalableTargetAction(b -> b.minCapacity(2)).build());
ScheduledAction minimumOnly = actionNamed(name);
assertThat(minimumOnly.schedule()).isEqualTo(schedule);
assertThat(minimumOnly.scalableTargetAction().minCapacity()).isEqualTo(2);
assertThat(minimumOnly.scalableTargetAction().maxCapacity()).isNull();
scaling.putScheduledAction(action(name).scalableTargetAction(b -> b.maxCapacity(3)).build());
ScheduledAction maximumOnly = actionNamed(name);
assertThat(maximumOnly.scalableTargetAction().minCapacity()).isNull();
assertThat(maximumOnly.scalableTargetAction().maxCapacity()).isEqualTo(3);
String replacementSchedule = at(Instant.now().plusSeconds(7200));
scaling.putScheduledAction(action(name).schedule(replacementSchedule).build());
scaling.putScheduledAction(action(name).build());
ScheduledAction updated = actionNamed(name);
assertThat(updated.schedule()).isEqualTo(replacementSchedule);
assertThat(updated.scalableTargetAction()).isEqualTo(maximumOnly.scalableTargetAction());
assertIdentity(updated, created);
scaling.deleteScheduledAction(r -> r.serviceNamespace(NAMESPACE).resourceId(resourceId)
.scalableDimension(DIMENSION).scheduledActionName(name));
assertThat(actions()).isEmpty();
assertThatThrownBy(() -> scaling.deleteScheduledAction(r -> r.serviceNamespace(NAMESPACE)
.resourceId(resourceId).scalableDimension(DIMENSION).scheduledActionName(name)))
.isInstanceOf(ObjectNotFoundException.class);
}
@Test
@DisplayName("Pages stay within the selected resource and names")
void pagingAndResourceIsolation() {
String otherResource = resourceId + "-other";
scaling.registerScalableTarget(r -> r.serviceNamespace(NAMESPACE).resourceId(otherResource)
.scalableDimension(DIMENSION).minCapacity(0).maxCapacity(4));
try {
String schedule = at(Instant.now().plusSeconds(3600));
for (String actionName : List.of("first", "second", "third")) {
scaling.putScheduledAction(action(actionName).schedule(schedule)
.scalableTargetAction(b -> b.minCapacity(0)).build());
}
scaling.putScheduledAction(action("foreign").resourceId(otherResource).schedule(schedule)
.scalableTargetAction(b -> b.minCapacity(0)).build());
DescribeScheduledActionsResponse first = scaling.describeScheduledActions(r -> r
.serviceNamespace(NAMESPACE).resourceId(resourceId).scalableDimension(DIMENSION)
.scheduledActionNames("first", "third").maxResults(1));
assertThat(first.scheduledActions()).hasSize(1);
assertThat(first.nextToken()).isNotBlank();
DescribeScheduledActionsResponse second = scaling.describeScheduledActions(r -> r
.serviceNamespace(NAMESPACE).resourceId(resourceId).scalableDimension(DIMENSION)
.scheduledActionNames("first", "third").maxResults(1).nextToken(first.nextToken()));
assertThat(second.scheduledActions()).hasSize(1);
assertThat(second.nextToken()).isNullOrEmpty();
assertThat(Stream.concat(first.scheduledActions().stream(), second.scheduledActions().stream())
.map(ScheduledAction::scheduledActionName).toList()).containsExactlyInAnyOrder("first", "third");
assertThat(actions()).extracting(ScheduledAction::scheduledActionName)
.containsExactlyInAnyOrder("first", "second", "third");
assertThatThrownBy(() -> scaling.describeScheduledActions(r -> r.serviceNamespace(NAMESPACE)
.resourceId(otherResource).scalableDimension(DIMENSION).maxResults(1)
.nextToken(first.nextToken()))).isInstanceOf(InvalidNextTokenException.class);
assertThat(scaling.describeScheduledActions(r -> r.serviceNamespace(NAMESPACE)
.resourceId(resourceId).scalableDimension(DIMENSION).scheduledActionNames("missing"))
.scheduledActions()).isEmpty();
} finally {
scaling.deregisterScalableTarget(r -> r.serviceNamespace(NAMESPACE).resourceId(otherResource)
.scalableDimension(DIMENSION));
}
}
@Test
@DisplayName("Autonomously execute bounds and retain completion with stable identity")
void autonomouslyExecuteAndRetainCompletedAction() throws InterruptedException {
try (EcsClient ecs = TestFixtures.ecsClient()) {
ecs.createCluster(r -> r.clusterName(name));
try {
TaskDefinition definition = ecs.registerTaskDefinition(r -> r.family(name)
.containerDefinitions(ContainerDefinition.builder().name("app").image("alpine:3")
.memory(128).build())).taskDefinition();
try {
ecs.createService(r -> r.cluster(name).serviceName(name).launchType(LaunchType.EC2)
.taskDefinition(definition.taskDefinitionArn()).desiredCount(2));
try {
scaling.registerScalableTarget(r -> r.serviceNamespace(NAMESPACE).resourceId(resourceId)
.scalableDimension(DIMENSION).minCapacity(2).maxCapacity(4)
.suspendedState(s -> s.dynamicScalingInSuspended(true)
.dynamicScalingOutSuspended(true).scheduledScalingSuspended(false)));
scaling.putScheduledAction(action(name).schedule(at(Instant.now().plusSeconds(2)))
.scalableTargetAction(b -> b.minCapacity(0).maxCapacity(1)).build());
ScheduledAction created = actionNamed(name);
awaitExecution(ecs, 1, 0, 1, 1);
assertBounds(0, 1);
assertThat(ecs.describeServices(r -> r.cluster(name).services(name))
.services().get(0).desiredCount()).isEqualTo(1);
ScheduledAction completed = actionNamed(name);
assertIdentity(completed, created);
assertThat(completed.scalableTargetAction().minCapacity()).isZero();
assertThat(completed.scalableTargetAction().maxCapacity()).isEqualTo(1);
} finally {
ecs.deleteService(r -> r.cluster(name).service(name).force(true));
}
} finally {
ecs.deregisterTaskDefinition(r -> r.taskDefinition(definition.taskDefinitionArn()));
}
} finally {
// An in-flight service reconciliation can add tasks after DeleteService returns.
TestFixtures.await(() -> {
List<String> tasks = Stream.of(DesiredStatus.RUNNING, DesiredStatus.STOPPED)
.flatMap(status -> ecs.listTasks(r -> r.cluster(name).desiredStatus(status)).taskArns().stream())
.distinct().toList();
for (String task : tasks) {
ecs.stopTask(r -> r.cluster(name).task(task));
}
try {
ecs.deleteCluster(r -> r.cluster(name));
return true;
} catch (ClusterContainsTasksException expected) {
// Re-list on the next pass to include tasks created after this snapshot.
return false;
}
}, name, "cluster deleted", Duration.ofSeconds(60).toNanos(), 200);
}
}
}
private PutScheduledActionRequest.Builder action(String actionName) {
return PutScheduledActionRequest.builder().serviceNamespace(NAMESPACE).resourceId(resourceId)
.scalableDimension(DIMENSION).scheduledActionName(actionName);
}
private List<ScheduledAction> actions() {
return scaling.describeScheduledActions(r -> r.serviceNamespace(NAMESPACE).resourceId(resourceId)
.scalableDimension(DIMENSION)).scheduledActions();
}
private ScheduledAction actionNamed(String actionName) {
List<ScheduledAction> found = scaling.describeScheduledActions(r -> r.serviceNamespace(NAMESPACE)
.resourceId(resourceId).scalableDimension(DIMENSION).scheduledActionNames(actionName))
.scheduledActions();
assertThat(found).hasSize(1);
return found.get(0);
}
private void awaitExecution(EcsClient ecs, int activities, int minimum, int maximum, int desired)
throws InterruptedException {
TestFixtures.await(() -> {
List<ScalableTarget> targets = scaling.describeScalableTargets(r -> r.serviceNamespace(NAMESPACE)
.resourceIds(resourceId).scalableDimension(DIMENSION)).scalableTargets();
long successful = scaling.describeScalingActivities(r -> r.serviceNamespace(NAMESPACE)
.resourceId(resourceId).scalableDimension(DIMENSION)).scalingActivities().stream()
.filter(a -> a.statusCode() == ScalingActivityStatusCode.SUCCESSFUL)
.map(ScalingActivity::activityId).distinct().count();
return successful >= activities && targets.size() == 1
&& targets.get(0).minCapacity() == minimum && targets.get(0).maxCapacity() == maximum
&& ecs.describeServices(r -> r.cluster(name).services(name)).services().get(0).desiredCount() == desired;
}, resourceId, "scheduled bounds and desired count", Duration.ofSeconds(30).toNanos(), 200);
}
private void assertBounds(int minimum, int maximum) {
List<ScalableTarget> targets = scaling.describeScalableTargets(r -> r.serviceNamespace(NAMESPACE)
.resourceIds(resourceId).scalableDimension(DIMENSION)).scalableTargets();
assertThat(targets).hasSize(1);
assertThat(targets.get(0).minCapacity()).isEqualTo(minimum);
assertThat(targets.get(0).maxCapacity()).isEqualTo(maximum);
}
private static void assertIdentity(ScheduledAction actual, ScheduledAction original) {
assertThat(actual.scheduledActionARN()).isEqualTo(original.scheduledActionARN());
assertThat(actual.creationTime()).isEqualTo(original.creationTime());
}
private static String at(Instant instant) {
return "at(" + SCHEDULE_TIME.format(instant) + ")";
}
}
+52 -11
View File
@@ -19,6 +19,9 @@ Auto Scaling groups over the Query protocol under the `autoscaling` signing name
| `RegisterScalableTarget` | Registers or updates a scalable target and returns its ARN |
| `DescribeScalableTargets` | Lists scalable targets in a namespace, optionally filtered |
| `DeregisterScalableTarget` | Deregisters a target and deletes its policies and alarms |
| `PutScheduledAction` | Creates or updates a one-off UTC scheduled action for ECS |
| `DescribeScheduledActions` | Lists scheduled actions with filters and pagination |
| `DeleteScheduledAction` | Deletes a scheduled action and cancels its pending occurrence |
| `PutScalingPolicy` | Creates or updates a scaling policy and its CloudWatch alarms |
| `DescribeScalingPolicies` | Lists scaling policies in a namespace, optionally filtered |
| `DeleteScalingPolicy` | Deletes a scaling policy and its CloudWatch alarms |
@@ -32,6 +35,8 @@ Auto Scaling groups over the Query protocol under the `autoscaling` signing name
`DescribeScalableTargets` accepts `MaxResults` from 1 to 50 and defaults to 50.
`DescribeScalingPolicies` accepts `MaxResults` from 1 to 10 and defaults to 10.
`DescribeScheduledActions` accepts `MaxResults` from 1 to 50 and defaults to 50.
It filters by resource, dimension, and up to 50 action names. A dimension requires a resource ID.
When more results remain, pass the returned `NextToken` with the same operation,
region, and filters to retrieve the next page. An invalid token returns
`InvalidNextTokenException`; an out-of-range page size returns `ValidationException`.
@@ -40,7 +45,7 @@ Tokens expire when the emulator restarts.
## Identity
A scalable target is keyed by the triple **(ServiceNamespace, ResourceId,
ScalableDimension)** — there is no separate identifier. `RegisterScalableTarget` is an
ScalableDimension)**. There is no separate identifier. `RegisterScalableTarget` is an
upsert on that triple: parameters you omit are left unchanged, matching AWS.
A scaling policy is keyed by that same triple plus `PolicyName`.
@@ -103,12 +108,12 @@ evaluates against.
## Control loop (ECS only)
A background evaluator (ticking every ~10s) evaluates every CloudWatch alarm with
metric-math configuration — the two alarms above, and any hand-created alarm behind a
`StepScaling` policy, since AWS does not auto-create alarms for those — against the
metric-math configuration, the two alarms above, and any hand-created alarm behind a
`StepScaling` policy, since AWS does not auto-create alarms for those, against the
metric data pushed via `PutMetricData`, transitioning `StateValue` the same way real
CloudWatch does, over the last `EvaluationPeriods` **complete** periods (the still-forming
current period is never counted, matching real CloudWatch). While an alarm is in `ALARM`,
its policy fires on every tick, not only the first transition — a scale-out blocked by
its policy fires on every tick, not only the first transition. A scale-out blocked by
cooldown on one tick is retried on a later one instead of being dropped. For
`ScalableDimension=ecs:service:DesiredCount`, Floci calls the ECS `UpdateService` action
to actually change `desiredCount`, respecting `MinCapacity`/`MaxCapacity` and
@@ -124,8 +129,8 @@ to actually change `desiredCount`, respecting `MinCapacity`/`MaxCapacity` and
- **Cooldown** (`ScaleInCooldown`/`ScaleOutCooldown` for target tracking, `Cooldown` for
step scaling) defaults to AWS's documented 300s ECS default when unset, not `0`. Per
AWS's own cooldown semantics, a scale-out blocked by cooldown still proceeds immediately
if the newly computed capacity is *larger* than what the last scale-out already applied
— cooldown exists to stop flapping on small repeated moves, not to cap a sustained
if the newly computed capacity is *larger* than what the last scale-out already applied.
Cooldown exists to stop flapping on small repeated moves, not to cap a sustained
breach's climb toward `MaxCapacity`. Scale-in has no such carve-out and is simply
blocked for the full cooldown window, same as AWS.
- When `TreatMissingData=breaching` reaches `ALARM` with no populated datapoint actually
@@ -134,10 +139,10 @@ to actually change `desiredCount`, respecting `MinCapacity`/`MaxCapacity` and
that's guaranteed not to reverse direction), and step scaling resolves the step at
`delta=0` (right at the alarm's own threshold).
- `TreatMissingData=ignore` keeps the alarm's current state rather than transitioning it,
but if that current state is already `ALARM`, a deferred action still retries — "ignore"
but if that current state is already `ALARM`, a deferred action still retries. "ignore"
only means "don't let this gap change my state," not "stop trying to act."
- Every capacity change is recorded and visible through `DescribeScalingActivities`.
- No metric data pushed for the alarm's window means `INSUFFICIENT_DATA` and no action —
- No metric data pushed for the alarm's window means `INSUFFICIENT_DATA` and no action.
Floci does not synthesize ECS CPU/memory metrics itself, so an operator (or a compat
test) has to push them to exercise the loop, the same way a real CloudWatch agent
would against real AWS.
@@ -145,6 +150,43 @@ to actually change `desiredCount`, respecting `MinCapacity`/`MaxCapacity` and
DynamoDB capacity, Lambda provisioned concurrency, ...) remain stored but inert, as
described below.
## Scheduled scaling (ECS only)
`PutScheduledAction` accepts `at(yyyy-MM-ddTHH:mm:ss)` in UTC for
`ecs:service:DesiredCount`. A new action requires a schedule and a nonempty
`ScalableTargetAction` with `MinCapacity`, `MaxCapacity`, or both. Updating an action
preserves omitted whole fields. Supplying `ScalableTargetAction` replaces its configured
bounds, so a minimum-only update removes any previously configured maximum.
When due, an action changes its configured bounds and preserves the target's other bound.
Desired count is clamped into the resulting range. An in-range count stays unchanged.
Every successful occurrence records a `Successful` scaling activity, including unchanged
bounds. Failed attempts record a `Failed` activity with the error message.
A conflicting effective range fails without changing the target.
Completed actions remain visible. An explicit future schedule rearms an action while
preserving its ARN and creation time. A capacity-only update does not rearm it.
Deleting an action cancels it. Deregistering a target removes its actions.
`ScheduledScalingSuspended` skips due occurrences independently of dynamic suspension
and cooldowns. Resuming does not replay missed actions.
The worker runs every `floci.services.applicationautoscaling.scheduled-action-interval-seconds`
seconds, default `1`. The environment variable is
`FLOCI_SERVICES_APPLICATIONAUTOSCALING_SCHEDULED_ACTION_INTERVAL_SECONDS`.
Past schedules are accepted and retained inactive. Floci compares the deadline with the
current whole second: the current second is eligible, earlier seconds are inactive.
This cutoff approximates AWS timing. It does not model an AWS scheduling grace period.
Pending future actions survive restart in persistent, hybrid, and WAL modes. On startup,
overdue pending actions are skipped. Claimed and terminal occurrences are never replayed.
Execution claims are stored before effects. If ECS fails after bounds are stored, the new
bounds remain and that occurrence fails without retry. Stores do not share a transaction,
so execution has no exactly-once guarantee across crashes. Hybrid durability depends on
flush. The scheduler drains before lifecycle storage flush and reset.
Scheduled action ARNs use the `autoscaling` service and this resource path:
`scheduledAction:<uuid>:resource/ecs/service/<cluster>/<service>:scheduledActionName/<name>`.
## Service-linked roles
When `RoleARN` is omitted, Floci synthesizes and returns a service-linked role ARN in the
@@ -162,8 +204,7 @@ arn:aws:iam::<account>:role/aws-service-role/<namespace>.application-autoscaling
evaluates its policies or adjusts its capacity. This matches the existing behavior of
EC2 Auto Scaling's `PutScalingPolicy` in Floci for those dimensions. The control plane
is faithful for all dimensions; the control loop is only emulated for ECS.
- `PutScheduledAction`, `DescribeScheduledActions`, and `DeleteScheduledAction` are not
implemented.
- Scheduled scaling supports only one-off UTC schedules for ECS desired count. `Timezone` accepts `UTC` or omission. Recurring schedules, other timezones, `StartTime`, and `EndTime` return `ValidationException`.
- `PredictiveScalingPolicyConfiguration` is accepted only insofar as `PolicyType` is
validated; the configuration block is not stored.
- **The evaluation range's exact width is an approximation.** Alarm evaluation follows
@@ -180,7 +221,7 @@ arn:aws:iam::<account>:role/aws-service-role/<namespace>.application-autoscaling
- **Scale-out cooldown rarely blocks a repeated scale-out in practice.** Its "proceed if
larger than the last applied capacity" carve-out (see above) is almost always satisfied
when nothing external has changed capacity, because both capacity formulas grow
monotonically with `current` — this matches AWS's documented intent for scale-out to add
monotonically with `current`. This matches AWS's documented intent for scale-out to add
capacity "as fast as it can," so cooldown's practical effect for this control loop is
mostly to gate scale-*in*, and to eventually halt scale-out once `MaxCapacity` is
reached (via the ordinary no-op-when-unchanged check, not the cooldown check itself).
+1 -1
View File
@@ -111,7 +111,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [ELB Classic (v1)](elb-classic.md) | `POST /` with `Action=` and `Version=2012-06-01` | Query | 20 |
| [WAF v2](wafv2.md) | `POST /` + `X-Amz-Target: AWSWAF_20190729.*` | JSON 1.1 | 35 |
| [Auto Scaling](autoscaling.md) | `POST /` with `Action=` param | Query | 55 |
| [Application Auto Scaling](applicationautoscaling.md) | `POST /` + `X-Amz-Target: AnyScaleFrontendService.*` | JSON 1.1 | 10 |
| [Application Auto Scaling](applicationautoscaling.md) | `POST /` + `X-Amz-Target: AnyScaleFrontendService.*` | JSON 1.1 | 13 |
| [Elastic Beanstalk](elastic-beanstalk.md) | `POST /` with `Action=` or `Operation=` param | Query | 14 |
| [CodeBuild](codebuild.md) | `POST /` + `X-Amz-Target: CodeBuild_20161006.*` | JSON 1.1 | 20 |
| [AWS Batch](batch.md) | `/v1/...` | REST JSON | 10 |
+6
View File
@@ -576,6 +576,12 @@
<version>${aws.sdk.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>applicationautoscaling</artifactId>
<version>${aws.sdk.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>autoscaling</artifactId>
@@ -1333,6 +1333,9 @@ public interface EmulatorConfig {
interface ApplicationAutoScalingServiceConfig {
@WithDefault("true")
boolean enabled();
@WithDefault("1")
long scheduledActionIntervalSeconds();
}
interface ElasticBeanstalkServiceConfig {
@@ -12,6 +12,7 @@ import io.floci.aws.services.applicationautoscaling.model.PredefinedMetricSpecif
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.StepAdjustment;
import io.floci.aws.services.applicationautoscaling.model.StepScalingConfiguration;
import io.floci.aws.services.applicationautoscaling.model.SuspendedState;
@@ -54,6 +55,9 @@ public class ApplicationAutoScalingJsonHandler {
case "RegisterScalableTarget" -> handleRegisterScalableTarget(request, region);
case "DescribeScalableTargets" -> handleDescribeScalableTargets(request, region);
case "DeregisterScalableTarget" -> handleDeregisterScalableTarget(request, region);
case "PutScheduledAction" -> handlePutScheduledAction(request, region);
case "DescribeScheduledActions" -> handleDescribeScheduledActions(request, region);
case "DeleteScheduledAction" -> handleDeleteScheduledAction(request, region);
case "PutScalingPolicy" -> handlePutScalingPolicy(request, region);
case "DescribeScalingPolicies" -> handleDescribeScalingPolicies(request, region);
case "DeleteScalingPolicy" -> handleDeleteScalingPolicy(request, region);
@@ -114,6 +118,101 @@ public class ApplicationAutoScalingJsonHandler {
return Response.ok(objectMapper.createObjectNode()).build();
}
private Response handlePutScheduledAction(JsonNode request, String region) {
for (String unsupported : List.of("StartTime", "EndTime")) {
if (request.has(unsupported)) {
throw new AwsException("ValidationException", unsupported + " is not supported for one-off UTC schedules.", 400);
}
}
JsonNode action = request.get("ScalableTargetAction");
if (action != null && !action.isObject()) {
throw new AwsException("ValidationException", "ScalableTargetAction must be an object.", 400);
}
service.putScheduledAction(text(request, "ServiceNamespace"), text(request, "ResourceId"),
text(request, "ScalableDimension"), text(request, "ScheduledActionName"),
strictText(request, "Schedule"), action != null,
strictInteger(action, "MinCapacity"), strictInteger(action, "MaxCapacity"),
strictText(request, "Timezone"), region);
return Response.ok(objectMapper.createObjectNode()).build();
}
private Response handleDeleteScheduledAction(JsonNode request, String region) {
service.deleteScheduledAction(text(request, "ServiceNamespace"), text(request, "ResourceId"),
text(request, "ScalableDimension"), text(request, "ScheduledActionName"), region);
return Response.ok(objectMapper.createObjectNode()).build();
}
private Response handleDescribeScheduledActions(JsonNode request, String region) {
PaginatedResult<ScheduledAction> result = service.describeScheduledActions(text(request, "ServiceNamespace"),
text(request, "ResourceId"), text(request, "ScalableDimension"),
scheduledActionNames(request.get("ScheduledActionNames")), optionalMaxResults(request), text(request, "NextToken"), region);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode actions = response.putArray("ScheduledActions");
for (ScheduledAction action : result.items()) {
ObjectNode node = actions.addObject();
node.put("ServiceNamespace", action.getServiceNamespace());
node.put("ResourceId", action.getResourceId());
node.put("ScalableDimension", action.getScalableDimension());
node.put("ScheduledActionName", action.getScheduledActionName());
node.put("ScheduledActionARN", action.getScheduledActionArn());
node.put("Schedule", action.getSchedule());
node.put("CreationTime", action.getCreationTime());
if (action.getTimezone() != null) {
node.put("Timezone", action.getTimezone());
}
ObjectNode bounds = node.putObject("ScalableTargetAction");
if (action.getMinCapacity() != null) {
bounds.put("MinCapacity", action.getMinCapacity());
}
if (action.getMaxCapacity() != null) {
bounds.put("MaxCapacity", action.getMaxCapacity());
}
}
if (result.nextToken() != null) {
response.put("NextToken", result.nextToken());
}
return Response.ok(response).build();
}
private static List<String> scheduledActionNames(JsonNode value) {
if (value == null || value.isNull()) {
return List.of();
}
if (!value.isArray()) {
throw new AwsException("ValidationException", "ScheduledActionNames must be an array of strings.", 400);
}
List<String> names = new ArrayList<>();
for (JsonNode name : value) {
if (!name.isTextual()) {
throw new AwsException("ValidationException", "ScheduledActionNames must contain only strings.", 400);
}
names.add(name.textValue());
}
return names;
}
private static String strictText(JsonNode request, String field) {
JsonNode value = request.get(field);
if (value == null) {
return null;
}
if (!value.isTextual()) {
throw new AwsException("ValidationException", field + " must be a string.", 400);
}
return value.textValue();
}
private static Integer strictInteger(JsonNode request, String field) {
JsonNode value = request == null ? null : request.get(field);
if (value == null) {
return null;
}
if (!value.isIntegralNumber() || !value.canConvertToInt()) {
throw new AwsException("ValidationException", field + " must be an integer.", 400);
}
return value.intValue();
}
// ---------------------------------------------------------------- scaling policies
private Response handlePutScalingPolicy(JsonNode request, String region) {
@@ -0,0 +1,43 @@
package io.floci.aws.services.applicationautoscaling;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.SweepScheduler;
import io.floci.aws.core.common.SweepWorker;
import io.quarkus.runtime.ShutdownEvent;
import io.quarkus.runtime.StartupEvent;
import jakarta.annotation.Priority;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import java.time.Instant;
/** Executes one-off actions after persisted storage and ECS runtime have been restored. */
@ApplicationScoped
public class ApplicationAutoScalingScheduledActionScheduler extends SweepScheduler {
private final ApplicationAutoScalingService service;
private final boolean enabled;
@Inject
public ApplicationAutoScalingScheduledActionScheduler(ApplicationAutoScalingService service, EmulatorConfig config) {
super(new SweepWorker("application-autoscaling-scheduled-actions", config.services().applicationautoscaling().enabled(),
config.services().applicationautoscaling().scheduledActionIntervalSeconds(), false, service::runScheduledActions));
this.service = service;
this.enabled = config.services().applicationautoscaling().enabled();
}
@Override
public void onStart(@Observes @Priority(3000) StartupEvent event) {
if (enabled) {
service.recoverScheduledActions(Instant.now());
}
super.onStart(event);
}
@Override
public void onStop(@Observes @Priority(1000) ShutdownEvent event) {
// SweepWorker.stop waits at most five seconds. Drain here before lifecycle storage flush.
beforeReset();
super.onStop(event);
}
}
@@ -5,9 +5,12 @@ import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.Pagination;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.core.common.ServicePrincipals;
import io.floci.aws.core.common.SignedMarkers;
import io.floci.aws.core.common.StoredResourceArns;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.AccountAwareStorageBackend.AccountEntry;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.applicationautoscaling.model.Alarm;
@@ -15,6 +18,8 @@ import io.floci.aws.services.applicationautoscaling.model.PredefinedMetricSpecif
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.StepScalingConfiguration;
import io.floci.aws.services.applicationautoscaling.model.SuspendedState;
import io.floci.aws.services.applicationautoscaling.model.TargetTrackingConfiguration;
@@ -22,28 +27,28 @@ import io.floci.aws.services.cloudwatch.metrics.CloudWatchMetricsService;
import io.floci.aws.services.cloudwatch.metrics.model.Dimension;
import io.floci.aws.services.cloudwatch.metrics.model.MetricAlarm;
import io.floci.aws.services.iam.ServiceLinkedRoles;
import io.floci.aws.services.scheduler.SchedulerExpressionParser;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Instant;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
/**
* Application Auto Scaling control plane.
*
* <p>Scalable targets and scaling policies are stored and described faithfully, but
* policies are <strong>inert</strong>: nothing evaluates them and no capacity is ever
* adjusted. This mirrors the existing EC2 Auto Scaling {@code PutScalingPolicy} behaviour
* and is documented in {@code docs/services/applicationautoscaling.md}.</p>
*
* @see <a href="https://docs.aws.amazon.com/autoscaling/application/APIReference/Welcome.html">Application Auto Scaling API Reference</a>
*/
@ApplicationScoped
@@ -90,6 +95,9 @@ public class ApplicationAutoScalingService implements StoredResourceArns {
private final StorageBackend<String, ScalableTarget> targets;
private final StorageBackend<String, ScalingPolicy> policies;
private final StorageBackend<String, ScalingActivity> activities;
private final StorageBackend<String, ScheduledAction> scheduledActions;
private final EcsCapacityAdjuster ecsCapacityAdjuster;
private final Object[] targetLocks = new Object[256];
private final RegionResolver regionResolver;
private final CloudWatchMetricsService cloudWatchMetricsService;
private final SignedMarkers pageTokens = new SignedMarkers();
@@ -97,22 +105,31 @@ public class ApplicationAutoScalingService implements StoredResourceArns {
@Inject
public ApplicationAutoScalingService(StorageFactory factory,
RegionResolver regionResolver,
CloudWatchMetricsService cloudWatchMetricsService) {
CloudWatchMetricsService cloudWatchMetricsService,
EcsCapacityAdjuster ecsCapacityAdjuster) {
this(factory.create("applicationautoscaling", "application-autoscaling-targets.json",
new TypeReference<Map<String, ScalableTarget>>() {}),
factory.create("applicationautoscaling", "application-autoscaling-policies.json",
new TypeReference<Map<String, ScalingPolicy>>() {}),
factory.create("applicationautoscaling", "application-autoscaling-activities.json",
new TypeReference<Map<String, ScalingActivity>>() {}),
regionResolver,
cloudWatchMetricsService);
factory.create("applicationautoscaling", "application-autoscaling-scheduled-actions.json",
new TypeReference<Map<String, ScheduledAction>>() {}),
regionResolver, cloudWatchMetricsService, ecsCapacityAdjuster);
}
ApplicationAutoScalingService(StorageBackend<String, ScalableTarget> targets,
StorageBackend<String, ScalingPolicy> policies,
StorageBackend<String, ScalingActivity> activities,
StorageBackend<String, ScheduledAction> scheduledActions,
RegionResolver regionResolver,
CloudWatchMetricsService cloudWatchMetricsService) {
CloudWatchMetricsService cloudWatchMetricsService,
EcsCapacityAdjuster ecsCapacityAdjuster) {
this.scheduledActions = scheduledActions;
this.ecsCapacityAdjuster = ecsCapacityAdjuster;
for (int i = 0; i < targetLocks.length; i++) {
targetLocks[i] = new Object();
}
this.targets = targets;
this.policies = policies;
this.activities = activities;
@@ -127,55 +144,62 @@ public class ApplicationAutoScalingService implements StoredResourceArns {
Integer maxCapacity, String roleArn,
SuspendedState suspendedState,
Map<String, String> tags, String region) {
validateTriple(serviceNamespace, resourceId, scalableDimension);
synchronized (targetLock(region, serviceNamespace, resourceId, scalableDimension)) {
validateTriple(serviceNamespace, resourceId, scalableDimension);
String key = targetKey(region, serviceNamespace, resourceId, scalableDimension);
ScalableTarget existing = targets.get(key).orElse(null);
String key = targetKey(region, serviceNamespace, resourceId, scalableDimension);
ScalableTarget existing = targets.get(key).map(ScalableTarget::new).orElse(null);
if (existing == null) {
if (minCapacity == null || maxCapacity == null) {
throw new AwsException("ValidationException",
"Min and max capacity are required when registering a new scalable target.", 400);
if (existing == null) {
if (minCapacity == null || maxCapacity == null) {
throw new AwsException("ValidationException",
"Min and max capacity are required when registering a new scalable target.", 400);
}
ScalableTarget target = new ScalableTarget();
target.setServiceNamespace(serviceNamespace);
target.setResourceId(resourceId);
target.setScalableDimension(scalableDimension);
target.setMinCapacity(minCapacity);
target.setMaxCapacity(maxCapacity);
target.setRoleArn(roleArn != null ? roleArn : serviceLinkedRoleArn(serviceNamespace));
target.setScalableTargetArn(buildScalableTargetArn(region));
target.setCreationTime(nowEpochSeconds());
target.setSuspendedState(suspendedState != null ? suspendedState : new SuspendedState());
if (tags != null) {
target.setTags(tags);
}
targets.putAllAtomically(Map.of(key, target));
LOG.infov("RegisterScalableTarget: {0} {1} {2} in {3}",
serviceNamespace, resourceId, scalableDimension, region);
return target;
}
ScalableTarget target = new ScalableTarget();
target.setServiceNamespace(serviceNamespace);
target.setResourceId(resourceId);
target.setScalableDimension(scalableDimension);
target.setMinCapacity(minCapacity);
target.setMaxCapacity(maxCapacity);
target.setRoleArn(roleArn != null ? roleArn : serviceLinkedRoleArn(serviceNamespace));
target.setScalableTargetArn(buildScalableTargetArn(region));
target.setCreationTime(nowEpochSeconds());
target.setSuspendedState(suspendedState != null ? suspendedState : new SuspendedState());
if (tags != null) {
target.setTags(tags);
if (suspendedState != null && suspendedState.isScheduledScalingSuspended()
!= existing.getSuspendedState().isScheduledScalingSuspended()) {
runTargetScheduledActions(serviceNamespace, resourceId, scalableDimension, region, Instant.now());
existing = new ScalableTarget(targets.get(key).orElseThrow());
}
targets.put(key, target);
LOG.infov("RegisterScalableTarget: {0} {1} {2} in {3}",
// Update semantics: only supplied parameters change.
if (minCapacity != null) {
existing.setMinCapacity(minCapacity);
}
if (maxCapacity != null) {
existing.setMaxCapacity(maxCapacity);
}
if (roleArn != null) {
existing.setRoleArn(roleArn);
}
if (suspendedState != null) {
existing.setSuspendedState(suspendedState);
}
if (tags != null && !tags.isEmpty()) {
existing.putTags(tags);
}
targets.putAllAtomically(Map.of(key, existing));
LOG.infov("RegisterScalableTarget (update): {0} {1} {2} in {3}",
serviceNamespace, resourceId, scalableDimension, region);
return target;
return existing;
}
// Update semantics: only supplied parameters change.
if (minCapacity != null) {
existing.setMinCapacity(minCapacity);
}
if (maxCapacity != null) {
existing.setMaxCapacity(maxCapacity);
}
if (roleArn != null) {
existing.setRoleArn(roleArn);
}
if (suspendedState != null) {
existing.setSuspendedState(suspendedState);
}
if (tags != null && !tags.isEmpty()) {
existing.putTags(tags);
}
targets.put(key, existing);
LOG.infov("RegisterScalableTarget (update): {0} {1} {2} in {3}",
serviceNamespace, resourceId, scalableDimension, region);
return existing;
}
public List<ScalableTarget> describeScalableTargets(String serviceNamespace, List<String> resourceIds,
@@ -212,21 +236,273 @@ public class ApplicationAutoScalingService implements StoredResourceArns {
*/
public void deregisterScalableTarget(String serviceNamespace, String resourceId,
String scalableDimension, String region) {
validateTriple(serviceNamespace, resourceId, scalableDimension);
String key = targetKey(region, serviceNamespace, resourceId, scalableDimension);
if (targets.get(key).isEmpty()) {
throw new AwsException("ObjectNotFoundException",
"No scalable target found for service namespace: " + serviceNamespace
+ ", resource ID: " + resourceId
+ ", scalable dimension: " + scalableDimension, 400);
synchronized (targetLock(region, serviceNamespace, resourceId, scalableDimension)) {
validateTriple(serviceNamespace, resourceId, scalableDimension);
String key = targetKey(region, serviceNamespace, resourceId, scalableDimension);
if (targets.get(key).isEmpty()) {
throw new AwsException("ObjectNotFoundException",
"No scalable target found for service namespace: " + serviceNamespace
+ ", resource ID: " + resourceId
+ ", scalable dimension: " + scalableDimension, 400);
}
for (ScalingPolicy policy : findPolicies(region, serviceNamespace, resourceId, scalableDimension)) {
deleteAlarms(policy, region);
policies.delete(policyKey(region, serviceNamespace, resourceId, scalableDimension, policy.getPolicyName()));
}
Set<String> actionKeys = scheduledActions.keys().stream()
.filter(actionKey -> actionKey.startsWith(key + "::")).collect(Collectors.toSet());
scheduledActions.deleteAllAtomically(actionKeys);
targets.deleteAllAtomically(Set.of(key));
LOG.infov("DeregisterScalableTarget: {0} {1} {2} in {3}",
serviceNamespace, resourceId, scalableDimension, region);
}
for (ScalingPolicy policy : findPolicies(region, serviceNamespace, resourceId, scalableDimension)) {
deleteAlarms(policy, region);
policies.delete(policyKey(region, serviceNamespace, resourceId, scalableDimension, policy.getPolicyName()));
}
public ScheduledAction putScheduledAction(String namespace, String resourceId, String dimension, String name,
String schedule, boolean actionSupplied, Integer min, Integer max,
String timezone, String region) {
return putScheduledAction(namespace, resourceId, dimension, name, schedule, actionSupplied, min, max,
timezone, region, Instant.now());
}
ScheduledAction putScheduledAction(String namespace, String resourceId, String dimension, String name,
String schedule, boolean actionSupplied, Integer min, Integer max,
String timezone, String region, Instant now) {
validateTriple(namespace, resourceId, dimension);
validateActionName(name);
if (!"ecs".equals(namespace) || !"ecs:service:DesiredCount".equals(dimension)) {
throw new AwsException("ValidationException", "Scheduled actions support ECS desired count only.", 400);
}
targets.delete(key);
LOG.infov("DeregisterScalableTarget: {0} {1} {2} in {3}",
serviceNamespace, resourceId, scalableDimension, region);
if (timezone != null && !"UTC".equals(timezone)) {
throw new AwsException("ValidationException", "Only UTC is supported for Timezone.", 400);
}
Instant deadline = schedule == null ? null : parseSchedule(schedule);
if (actionSupplied && (min == null && max == null || min != null && min < 0 || max != null && max < 0
|| min != null && max != null && min > max)) {
throw new AwsException("ValidationException", "Supply nonnegative capacity bounds with MinCapacity <= MaxCapacity.", 400);
}
synchronized (targetLock(region, namespace, resourceId, dimension)) {
requireTarget(region, namespace, resourceId, dimension);
String key = policyKey(region, namespace, resourceId, dimension, name);
ScheduledAction existing = scheduledActions.get(key).orElse(null);
if (existing == null && (schedule == null || !actionSupplied)) {
throw new AwsException("ValidationException", "Schedule and ScalableTargetAction are required.", 400);
}
ScheduledAction action = existing == null ? new ScheduledAction() : new ScheduledAction(existing);
if (existing == null) {
action.setServiceNamespace(namespace);
action.setResourceId(resourceId);
action.setScalableDimension(dimension);
action.setScheduledActionName(name);
action.setCreationTime(now.getEpochSecond() + now.getNano() / 1_000_000_000.0);
action.setScheduledActionArn(regionResolver.buildArn("autoscaling", region,
"scheduledAction:" + UUID.randomUUID() + ":resource/" + namespace + "/" + resourceId
+ ":scheduledActionName/" + name));
}
if (schedule != null) {
action.setSchedule(schedule);
action.setDeadline(deadline);
action.setState(deadline.isBefore(now.truncatedTo(ChronoUnit.SECONDS)) ? State.SKIPPED : State.PENDING);
}
if (timezone != null) {
action.setTimezone(timezone);
}
if (actionSupplied) {
action.setMinCapacity(min);
action.setMaxCapacity(max);
}
scheduledActions.putAllAtomically(Map.of(key, action));
return new ScheduledAction(action);
}
}
public void deleteScheduledAction(String namespace, String resourceId, String dimension, String name, String region) {
validateTriple(namespace, resourceId, dimension);
validateActionName(name);
synchronized (targetLock(region, namespace, resourceId, dimension)) {
String key = policyKey(region, namespace, resourceId, dimension, name);
if (scheduledActions.get(key).isEmpty()) {
throw new AwsException("ObjectNotFoundException", "Scheduled action not found: " + name, 400);
}
scheduledActions.deleteAllAtomically(Set.of(key));
}
}
PaginatedResult<ScheduledAction> describeScheduledActions(String namespace, String resourceId, String dimension,
List<String> names, Integer maxResults,
String nextToken, String region) {
requireNamespace(namespace);
if (dimension != null && (resourceId == null || resourceId.isBlank())) {
throw new AwsException("ValidationException", "A resource ID is required with ScalableDimension.", 400);
}
if (dimension != null) {
validateTriple(namespace, resourceId, dimension);
}
if (names != null && names.size() > 50) {
throw new AwsException("ValidationException", "At most 50 scheduled action names are allowed.", 400);
}
String prefix = region + "::" + namespace + "::";
List<ScheduledAction> matching = scheduledActions.scan(key -> key.startsWith(prefix)).stream()
.filter(a -> resourceId == null || resourceId.equals(a.getResourceId()))
.filter(a -> dimension == null || dimension.equals(a.getScalableDimension()))
.filter(a -> names == null || names.isEmpty() || names.contains(a.getScheduledActionName()))
.map(ScheduledAction::new).sorted(Comparator.comparing(ApplicationAutoScalingService::scheduledActionCursor))
.toList();
return signedPage(Pagination.paginate(matching, ApplicationAutoScalingService::scheduledActionCursor,
pageSize(maxResults, 50), decodeNextToken(nextToken, "DescribeScheduledActions"),
pageNamespace(names, "DescribeScheduledActions", regionResolver.getAccountId(), region, namespace,
resourceId, dimension), token -> invalidNextToken("DescribeScheduledActions")));
}
private static String scheduledActionCursor(ScheduledAction action) {
return action.getScheduledActionName() + "\u0000" + action.getResourceId() + "\u0000" + action.getScalableDimension();
}
private static void validateActionName(String name) {
if (name == null || name.isBlank() || name.length() > 256
|| name.chars().anyMatch(c -> c == ':' || c == '/' || c == '|' || Character.isISOControl(c))) {
throw new AwsException("ValidationException", "Invalid ScheduledActionName.", 400);
}
}
private static Instant parseSchedule(String schedule) {
if (!schedule.matches("at\\(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\)")) {
throw new AwsException("ValidationException", "Only UTC at(yyyy-MM-ddTHH:mm:ss) schedules are supported.", 400);
}
try {
return SchedulerExpressionParser.parseAt(schedule, "UTC");
} catch (DateTimeParseException e) {
throw new AwsException("ValidationException", "Invalid scheduled date.", 400);
}
}
private ScalableTarget requireTarget(String region, String namespace, String resourceId, String dimension) {
return targets.get(targetKey(region, namespace, resourceId, dimension))
.orElseThrow(() -> new AwsException("ObjectNotFoundException", "Scalable target not found.", 400));
}
Object targetLock(String region, String namespace, String resourceId, String dimension) {
int hash = (regionResolver.getAccountId() + "::" + targetKey(region, namespace, resourceId, dimension)).hashCode();
return targetLocks[Math.floorMod(hash, targetLocks.length)];
}
private List<AccountEntry<ScheduledAction>> allScheduledActions() {
if (scheduledActions instanceof AccountAwareStorageBackend<ScheduledAction> accountAware) {
return accountAware.scanAllAccountEntries(key -> true);
}
return scheduledActions.keys().stream().map(key -> new AccountEntry<>(regionResolver.getAccountId(), key,
scheduledActions.get(key).orElseThrow())).toList();
}
/** Restored overdue occurrences are skipped. Claimed occurrences are never replayed. */
void recoverScheduledActions(Instant now) {
for (AccountEntry<ScheduledAction> entry : allScheduledActions()) {
String region = entry.key().substring(0, entry.key().indexOf("::"));
RequestScopes.runAs(entry.accountId(), region, () -> {
ScheduledAction action = entry.value();
if (action.getState() == State.PENDING && action.getDeadline().isBefore(now)
|| action.getState() == State.CLAIMED) {
ScheduledAction recovered = new ScheduledAction(action);
recovered.setState(State.SKIPPED);
scheduledActions.putAllAtomically(Map.of(entry.key(), recovered));
}
});
}
}
public void runScheduledActions(Instant now) {
List<AccountEntry<ScheduledAction>> entries = allScheduledActions().stream()
.filter(e -> e.value().getState() == State.PENDING && !e.value().getDeadline().isAfter(now))
.sorted(Comparator.comparing((AccountEntry<ScheduledAction> e) -> e.value().getDeadline())
.thenComparing(e -> e.value().getScheduledActionName())).toList();
Set<String> processedTargets = new HashSet<>();
for (AccountEntry<ScheduledAction> entry : entries) {
String region = entry.key().substring(0, entry.key().indexOf("::"));
ScheduledAction candidate = entry.value();
String targetKey = targetKey(region, candidate.getServiceNamespace(), candidate.getResourceId(),
candidate.getScalableDimension());
if (!processedTargets.add(entry.accountId() + "::" + targetKey)) {
continue;
}
try {
RequestScopes.runAs(entry.accountId(), region, () -> {
ScheduledAction action = entry.value();
synchronized (targetLock(region, action.getServiceNamespace(), action.getResourceId(),
action.getScalableDimension())) {
runTargetScheduledActions(action.getServiceNamespace(), action.getResourceId(),
action.getScalableDimension(), region, now);
}
});
} catch (RuntimeException e) {
LOG.warnv(e, "Scheduled action {0} failed", entry.key());
}
}
}
private void runTargetScheduledActions(String namespace, String resourceId, String dimension,
String region, Instant now) {
String prefix = targetKey(region, namespace, resourceId, dimension) + "::";
List<ScheduledAction> due = scheduledActions.scan(key -> key.startsWith(prefix)).stream()
.filter(a -> a.getState() == State.PENDING && !a.getDeadline().isAfter(now))
.sorted(Comparator.comparing(ScheduledAction::getDeadline)
.thenComparing(ScheduledAction::getScheduledActionName)).toList();
for (ScheduledAction action : due) {
try {
executeScheduledAction(prefix + action.getScheduledActionName(), now, region);
} catch (RuntimeException e) {
LOG.warnv(e, "Scheduled action {0} failed", action.getScheduledActionName());
}
}
}
private void executeScheduledAction(String key, Instant now, String region) {
ScheduledAction stored = scheduledActions.get(key).orElse(null);
if (stored == null || stored.getState() != State.PENDING || stored.getDeadline().isAfter(now)) {
return;
}
ScheduledAction action = new ScheduledAction(stored);
ScalableTarget existing = targets.get(targetKey(region, action.getServiceNamespace(), action.getResourceId(),
action.getScalableDimension())).orElse(null);
if (existing == null || existing.getSuspendedState().isScheduledScalingSuspended()) {
action.setState(State.SKIPPED);
scheduledActions.putAllAtomically(Map.of(key, action));
return;
}
action.setState(State.CLAIMED);
scheduledActions.putAllAtomically(Map.of(key, new ScheduledAction(action)));
String description = "Applying scheduled action " + action.getScheduledActionName();
String failure = null;
try {
ScalableTarget target = new ScalableTarget(existing);
int min = action.getMinCapacity() == null ? target.getMinCapacity() : action.getMinCapacity();
int max = action.getMaxCapacity() == null ? target.getMaxCapacity() : action.getMaxCapacity();
if (min > max) {
throw new AwsException("ValidationException", "Scheduled bounds conflict with the target's current bounds.", 400);
}
target.setMinCapacity(min);
target.setMaxCapacity(max);
targets.putAllAtomically(Map.of(targetKey(region, target.getServiceNamespace(), target.getResourceId(),
target.getScalableDimension()), target));
int current = ecsCapacityAdjuster.getCurrentCapacity(target.getResourceId(), region);
int desired = Math.max(min, Math.min(max, current));
if (desired != current) {
ecsCapacityAdjuster.setCapacity(target.getResourceId(), desired, region);
}
description = "Setting capacity bounds to " + min + " and " + max;
action.setState(State.SUCCEEDED);
} catch (RuntimeException e) {
action.setState(State.FAILED);
failure = e.getMessage();
LOG.warnv(e, "Scheduled action {0} could not complete", action.getScheduledActionName());
}
try {
recordScalingActivity(action.getServiceNamespace(), action.getResourceId(), action.getScalableDimension(),
description, "scheduled action " + action.getScheduledActionName(), region,
action.getState() == State.SUCCEEDED ? "Successful" : "Failed", failure);
} catch (RuntimeException e) {
LOG.warnv(e, "Could not record activity for scheduled action {0}", action.getScheduledActionName());
}
scheduledActions.putAllAtomically(Map.of(key, action));
}
// ---------------------------------------------------------------- scaling policies
@@ -340,20 +616,26 @@ public class ApplicationAutoScalingService implements StoredResourceArns {
if (tags == null || tags.isEmpty()) {
throw new AwsException("ValidationException", "Tags are required.", 400);
}
ScalableTarget target = findTargetByArn(resourceArn, region);
target.putTags(tags);
targets.put(targetKey(region, target.getServiceNamespace(), target.getResourceId(),
target.getScalableDimension()), target);
ScalableTarget found = findTargetByArn(resourceArn, region);
synchronized (targetLock(region, found.getServiceNamespace(), found.getResourceId(), found.getScalableDimension())) {
ScalableTarget target = new ScalableTarget(findTargetByArn(resourceArn, region));
target.putTags(tags);
targets.putAllAtomically(Map.of(targetKey(region, target.getServiceNamespace(), target.getResourceId(),
target.getScalableDimension()), target));
}
}
public void untagResource(String resourceArn, List<String> tagKeys, String region) {
if (tagKeys == null || tagKeys.isEmpty()) {
throw new AwsException("ValidationException", "TagKeys are required.", 400);
}
ScalableTarget target = findTargetByArn(resourceArn, region);
target.removeTags(tagKeys);
targets.put(targetKey(region, target.getServiceNamespace(), target.getResourceId(),
target.getScalableDimension()), target);
ScalableTarget found = findTargetByArn(resourceArn, region);
synchronized (targetLock(region, found.getServiceNamespace(), found.getResourceId(), found.getScalableDimension())) {
ScalableTarget target = new ScalableTarget(findTargetByArn(resourceArn, region));
target.removeTags(tagKeys);
targets.putAllAtomically(Map.of(targetKey(region, target.getServiceNamespace(), target.getResourceId(),
target.getScalableDimension()), target));
}
}
// ---------------------------------------------------------------- internals
@@ -743,21 +1025,29 @@ public class ApplicationAutoScalingService implements StoredResourceArns {
/** Records that the control loop changed capacity, mirroring what AWS reports through
* DescribeScalingActivities. */
void recordScalingActivity(ScalingPolicy policy, String description, String cause, String region) {
recordScalingActivity(policy.getServiceNamespace(), policy.getResourceId(), policy.getScalableDimension(),
description, cause, region, "Successful", null);
}
private void recordScalingActivity(String serviceNamespace, String resourceId, String dimension,
String description, String cause, String region,
String status, String statusMessage) {
ScalingActivity activity = new ScalingActivity();
activity.setActivityId(UUID.randomUUID().toString());
activity.setServiceNamespace(policy.getServiceNamespace());
activity.setResourceId(policy.getResourceId());
activity.setScalableDimension(policy.getScalableDimension());
activity.setServiceNamespace(serviceNamespace);
activity.setResourceId(resourceId);
activity.setScalableDimension(dimension);
activity.setDescription(description);
activity.setCause(cause);
double now = nowEpochSeconds();
activity.setStartTime(now);
activity.setEndTime(now);
activity.setStatusCode("Successful");
String key = region + "::" + policy.getServiceNamespace() + "::" + policy.getScalableDimension()
+ "::" + policy.getResourceId() + "::" + activity.getActivityId();
activities.put(key, activity);
LOG.infov("Scaling activity for policy {0}: {1}", policy.getPolicyName(), description);
activity.setStatusCode(status);
activity.setStatusMessage(statusMessage);
String key = region + "::" + serviceNamespace + "::" + dimension
+ "::" + resourceId + "::" + activity.getActivityId();
activities.putAllAtomically(Map.of(key, activity));
LOG.infov("Scaling activity for {0}: {1}", resourceId, description);
}
public List<ScalingActivity> describeScalingActivities(String serviceNamespace, String resourceId,
@@ -86,6 +86,17 @@ public class ScalingPolicyAlarmActionHandler implements AlarmActionHandler {
LOG.debugv("No scaling policy found for alarm action {0}", actionArn);
return;
}
synchronized (service.targetLock(region, policy.getServiceNamespace(), policy.getResourceId(),
policy.getScalableDimension())) {
ScalingPolicy currentPolicy = service.findPolicyByArn(actionArn, region).orElse(null);
if (currentPolicy == null) {
return;
}
execute(currentPolicy, alarm, metricValue, region);
}
}
private void execute(ScalingPolicy policy, MetricAlarm alarm, double metricValue, String region) {
ScalableTarget target = service.findTarget(region, policy.getServiceNamespace(),
policy.getResourceId(), policy.getScalableDimension()).orElse(null);
if (target == null) {
@@ -31,6 +31,24 @@ public class ScalableTarget {
private SuspendedState suspendedState = new SuspendedState();
private Map<String, String> tags = new HashMap<>();
public ScalableTarget() {}
public ScalableTarget(ScalableTarget source) {
serviceNamespace = source.serviceNamespace;
resourceId = source.resourceId;
scalableDimension = source.scalableDimension;
minCapacity = source.minCapacity;
maxCapacity = source.maxCapacity;
roleArn = source.roleArn;
scalableTargetArn = source.scalableTargetArn;
creationTime = source.creationTime;
suspendedState = new SuspendedState();
suspendedState.setScheduledScalingSuspended(source.suspendedState.isScheduledScalingSuspended());
suspendedState.setDynamicScalingInSuspended(source.suspendedState.isDynamicScalingInSuspended());
suspendedState.setDynamicScalingOutSuspended(source.suspendedState.isDynamicScalingOutSuspended());
tags = new HashMap<>(source.tags);
}
public String getServiceNamespace() { return serviceNamespace; }
public void setServiceNamespace(String v) { this.serviceNamespace = v; }
@@ -0,0 +1,78 @@
package io.floci.aws.services.applicationautoscaling.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
/** A retained one-off scheduled action and its execution state. */
@RegisterForReflection
public class ScheduledAction {
@RegisterForReflection
public enum State { PENDING, CLAIMED, SUCCEEDED, FAILED, SKIPPED }
private String serviceNamespace;
private String resourceId;
private String scalableDimension;
private String scheduledActionName;
private String scheduledActionArn;
private String schedule;
private String timezone;
private Instant deadline;
private Integer minCapacity;
private Integer maxCapacity;
private double creationTime;
private State state;
public ScheduledAction() {}
public ScheduledAction(ScheduledAction source) {
this.serviceNamespace = source.serviceNamespace;
this.resourceId = source.resourceId;
this.scalableDimension = source.scalableDimension;
this.scheduledActionName = source.scheduledActionName;
this.scheduledActionArn = source.scheduledActionArn;
this.schedule = source.schedule;
this.timezone = source.timezone;
this.deadline = source.deadline;
this.minCapacity = source.minCapacity;
this.maxCapacity = source.maxCapacity;
this.creationTime = source.creationTime;
this.state = source.state;
}
public String getServiceNamespace() { return serviceNamespace; }
public void setServiceNamespace(String value) { this.serviceNamespace = value; }
public String getResourceId() { return resourceId; }
public void setResourceId(String value) { this.resourceId = value; }
public String getScalableDimension() { return scalableDimension; }
public void setScalableDimension(String value) { this.scalableDimension = value; }
public String getScheduledActionName() { return scheduledActionName; }
public void setScheduledActionName(String value) { this.scheduledActionName = value; }
public String getScheduledActionArn() { return scheduledActionArn; }
public void setScheduledActionArn(String value) { this.scheduledActionArn = value; }
public String getSchedule() { return schedule; }
public void setSchedule(String value) { this.schedule = value; }
public String getTimezone() { return timezone; }
public void setTimezone(String value) { this.timezone = value; }
public Instant getDeadline() { return deadline; }
public void setDeadline(Instant value) { this.deadline = value; }
public Integer getMinCapacity() { return minCapacity; }
public void setMinCapacity(Integer value) { this.minCapacity = value; }
public Integer getMaxCapacity() { return maxCapacity; }
public void setMaxCapacity(Integer value) { this.maxCapacity = value; }
public double getCreationTime() { return creationTime; }
public void setCreationTime(double value) { this.creationTime = value; }
public State getState() { return state; }
public void setState(State value) { this.state = value; }
}
+1
View File
@@ -927,6 +927,7 @@ floci:
enabled: true
applicationautoscaling:
enabled: true
scheduled-action-interval-seconds: ${FLOCI_SERVICES_APPLICATIONAUTOSCALING_SCHEDULED_ACTION_INTERVAL_SECONDS:1}
elasticbeanstalk:
enabled: true
backup:
@@ -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 + "\","
+1
View File
@@ -434,6 +434,7 @@ floci:
enabled: true
applicationautoscaling:
enabled: true
scheduled-action-interval-seconds: ${FLOCI_SERVICES_APPLICATIONAUTOSCALING_SCHEDULED_ACTION_INTERVAL_SECONDS:1}
elasticbeanstalk:
enabled: true
transfer: