feat(redshift): scheduled actions that pause and resume provisioned clusters (#8260)

This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-14 13:28:06 -04:00
1 parent 0b19c15e71
commit d08c241d98
22 files changed
+1791 -66

No files matched your search

@@ -1898,6 +1898,14 @@ public final class TestFixtures {
.build();
}
public static RedshiftClient redshiftClient(String accountId) {
return RedshiftClient.builder()
.endpointOverride(ENDPOINT)
.region(REGION)
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(accountId, "test")))
.build();
}
public static RedshiftDataClient redshiftDataClient() {
return RedshiftDataClient.builder()
.endpointOverride(ENDPOINT)
@@ -0,0 +1,124 @@
package com.floci.test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.redshift.RedshiftClient;
import software.amazon.awssdk.services.redshift.model.CreateScheduledActionResponse;
import software.amazon.awssdk.services.redshift.model.RedshiftException;
import software.amazon.awssdk.services.redshift.model.ScheduledAction;
import software.amazon.awssdk.services.redshift.model.ScheduledActionAlreadyExistsException;
import software.amazon.awssdk.services.redshift.model.ScheduledActionNotFoundException;
import software.amazon.awssdk.services.redshift.model.ScheduledActionState;
import java.util.List;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** Scheduled actions that pause and resume a provisioned Redshift cluster, through the AWS SDK for Java v2. */
@DisplayName("Redshift scheduled actions")
class RedshiftScheduledActionTest {
private static final String OWNER = "111111111111";
private static final String OTHER = "222222222222";
private static final String ROLE = "arn:aws:iam::" + OWNER + ":role/redshift-scheduler";
private static final String SUFFIX = UUID.randomUUID().toString().substring(0, 8);
private static final String CLUSTER = "sched-c-" + SUFFIX;
private static final String PAUSE = "sched-pause-" + SUFFIX;
private static final String RESUME = "sched-resume-" + SUFFIX;
private static RedshiftClient owner;
private static RedshiftClient other;
@BeforeAll
static void setUp() {
owner = TestFixtures.redshiftClient(OWNER);
other = TestFixtures.redshiftClient(OTHER);
owner.createCluster(r -> r.clusterIdentifier(CLUSTER).nodeType("dc2.large")
.masterUsername("admin").masterUserPassword("Secret123"));
}
@AfterAll
static void cleanup() {
for (Runnable step : new Runnable[] {
() -> owner.deleteScheduledAction(r -> r.scheduledActionName(PAUSE)),
() -> owner.deleteScheduledAction(r -> r.scheduledActionName(RESUME)),
() -> owner.deleteCluster(r -> r.clusterIdentifier(CLUSTER).skipFinalClusterSnapshot(true))}) {
try {
step.run();
} catch (Exception ignored) {
// Best effort: the test may have failed before creating the resource.
}
}
owner.close();
other.close();
}
@Test
@DisplayName("create, describe, modify and delete a pause and a resume action")
void lifecycle() {
CreateScheduledActionResponse created = owner.createScheduledAction(r -> r.scheduledActionName(PAUSE)
.iamRole(ROLE).schedule("cron(0 22 * * ? *)").scheduledActionDescription("pause at night")
.targetAction(t -> t.pauseCluster(p -> p.clusterIdentifier(CLUSTER))));
assertThat(created.state()).isEqualTo(ScheduledActionState.ACTIVE);
assertThat(created.targetAction().pauseCluster().clusterIdentifier()).isEqualTo(CLUSTER);
assertThat(created.nextInvocations()).isNotEmpty();
owner.createScheduledAction(r -> r.scheduledActionName(RESUME).iamRole(ROLE)
.schedule("cron(0 6 * * ? *)")
.targetAction(t -> t.resumeCluster(p -> p.clusterIdentifier(CLUSTER))));
assertThatThrownBy(() -> owner.createScheduledAction(r -> r.scheduledActionName(PAUSE).iamRole(ROLE)
.schedule("cron(0 22 * * ? *)")
.targetAction(t -> t.pauseCluster(p -> p.clusterIdentifier(CLUSTER)))))
.isInstanceOf(ScheduledActionAlreadyExistsException.class);
owner.modifyScheduledAction(r -> r.scheduledActionName(RESUME).enable(false));
List<ScheduledAction> disabled = owner.describeScheduledActions(r -> r.active(false)
.filters(f -> f.name("cluster-identifier").values(CLUSTER))).scheduledActions();
assertThat(disabled).extracting(ScheduledAction::scheduledActionName).containsExactly(RESUME);
List<ScheduledAction> enabled = owner.describeScheduledActions(r -> r.active(true)
.filters(f -> f.name("cluster-identifier").values(CLUSTER))).scheduledActions();
assertThat(enabled).extracting(ScheduledAction::scheduledActionName).containsExactly(PAUSE);
owner.deleteScheduledAction(r -> r.scheduledActionName(PAUSE));
owner.deleteScheduledAction(r -> r.scheduledActionName(RESUME));
assertThatThrownBy(() -> owner.deleteScheduledAction(r -> r.scheduledActionName(PAUSE)))
.isInstanceOf(ScheduledActionNotFoundException.class);
}
@Test
@DisplayName("another account does not see or delete the action")
void actionsAreAccountScoped() {
String name = "sched-iso-" + SUFFIX;
owner.createScheduledAction(r -> r.scheduledActionName(name).iamRole(ROLE)
.schedule("at(2099-01-01T00:00:00)")
.targetAction(t -> t.pauseCluster(p -> p.clusterIdentifier(CLUSTER))));
try {
assertThat(other.describeScheduledActions(r -> r.scheduledActionName(name)).scheduledActions()).isEmpty();
assertThatThrownBy(() -> other.deleteScheduledAction(r -> r.scheduledActionName(name)))
.isInstanceOf(ScheduledActionNotFoundException.class);
} finally {
owner.deleteScheduledAction(r -> r.scheduledActionName(name));
}
}
@Test
@DisplayName("a resize target and a malformed schedule are refused")
void unsupportedTargetAndInvalidSchedule() {
assertThatThrownBy(() -> owner.createScheduledAction(r -> r.scheduledActionName("sched-resize-" + SUFFIX)
.iamRole(ROLE).schedule("cron(0 22 * * ? *)")
.targetAction(t -> t.resizeCluster(c -> c.clusterIdentifier(CLUSTER).numberOfNodes(2)))))
.isInstanceOf(RedshiftException.class)
.hasMessageContaining("ResizeCluster");
assertThatThrownBy(() -> owner.createScheduledAction(r -> r.scheduledActionName("sched-bad-" + SUFFIX)
.iamRole(ROLE).schedule("rate(1 hour)")
.targetAction(t -> t.pauseCluster(p -> p.clusterIdentifier(CLUSTER)))))
.isInstanceOf(RedshiftException.class)
.satisfies(e -> assertThat(((RedshiftException) e).awsErrorDetails().errorCode())
.isEqualTo("InvalidSchedule"));
}
}
+1 -1
View File
@@ -81,7 +81,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [DocumentDB](docdb.md) | `POST /` with `Action=` param + MongoDB container | Query + MongoDB wire | 17 |
| [DMS](dms.md) | `POST /` + `X-Amz-Target: AmazonDMSv20160101.*` | JSON 1.1 | 20 |
| [QuickSight](quicksight.md) | `/accounts/{AwsAccountId}/...` | REST JSON, metadata only | 16 |
| [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire (+ CFN) | 59 |
| [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire (+ CFN) | 63 |
| [Redshift Data API](redshift-data.md) | `POST /` + `X-Amz-Target: RedshiftData.*` | JSON 1.1 | 12 |
| [Redshift Serverless](redshift-serverless.md) | `POST /` + `X-Amz-Target: RedshiftServerless.*` | JSON 1.1 | 55 |
| [EMR](emr.md) | `POST /` + `X-Amz-Target: ElasticMapReduce.*` | JSON 1.1 | 40 |
+10
View File
@@ -165,6 +165,10 @@ The attributes follow the [CloudFormation resource schema](https://docs.aws.amaz
| `EnableSnapshotCopy` | Record cross-region snapshot copy on a cluster (`RetentionPeriod` defaults to 7, `ManualSnapshotRetentionPeriod` to -1); `DescribeClusters` then reports `ClusterSnapshotCopyStatus`. A `DestinationRegion` that is not an AWS region is refused with `UnknownSnapshotCopyRegionFault`. A background sweep then copies the cluster's snapshots to that Region, see [Cross-region snapshot copy](#cross-region-snapshot-copy) |
| `DisableSnapshotCopy` | Clear a cluster's snapshot copy configuration |
| `ModifySnapshotCopyRetentionPeriod` | Change the automated (or, with `Manual`, the manual) snapshot copy retention period |
| `CreateScheduledAction` | Create a scheduled action that runs `PauseCluster` or `ResumeCluster` on a cluster at an `at(...)` time or on a six-field `cron(...)` schedule, in UTC, with an optional `StartTime`/`EndTime` window, `Enable` and description. A `ResizeCluster` target is refused with `ScheduledActionTypeUnsupported` |
| `ModifyScheduledAction` | Change the role, schedule, target, window, description or `Enable` of an action; a new schedule, or enabling a disabled action, restarts the count from now |
| `DeleteScheduledAction` | Remove an action |
| `DescribeScheduledActions` | List actions filtered by `ScheduledActionName`, `TargetActionType`, `Active`, `StartTime`, `EndTime` and the `cluster-identifier` and `iam-role` filters, paged with `MaxRecords` (20 to 100) and `Marker`, with `State` and `NextInvocations` |
| `CreateSnapshotSchedule` | Create a UTC rate or cron schedule that takes automated snapshots on associated clusters, with optional tags |
| `ModifySnapshotSchedule` | Replace a schedule's definitions |
| `DescribeSnapshotSchedules` | List schedules filtered by `ScheduleIdentifier`, `ClusterIdentifier`, `TagKeys` and `TagValues`, paged with `MaxRecords` and `Marker`, with their associated clusters |
@@ -381,6 +385,10 @@ See AWS's [COPY JOB](https://docs.aws.amazon.com/redshift/latest/dg/r_COPY-JOB.h
- **Retention.** Copied automated snapshots follow the cluster's current `RetentionPeriod`, so `ModifySnapshotCopyRetentionPeriod` changes existing ones. Copied manual snapshots keep the `ManualSnapshotRetentionPeriod` they were copied with; `-1` keeps them until deleted. Retention counts from the source snapshot's creation time.
- **The cluster store has no Region.** A cluster restored from a copy is created in the same store as every other cluster, as before.
## Scheduled actions
A scheduled action pauses or resumes a provisioned cluster on a schedule. A background sweep runs the latest invocation that came due since it last looked, once, so a long downtime does not replay missed invocations and nothing before an action was created, rescheduled or enabled again runs. With IAM enforcement on, the action's role has to trust `scheduler.redshift.amazonaws.com` and allow `redshift:PauseCluster` or `redshift:ResumeCluster` on the cluster. A failing invocation, such as pausing a cluster that is already paused, is logged and the sweep goes on. Actions are removed with their cluster. Only `PauseCluster` and `ResumeCluster` targets are supported. A cron schedule whose invocations are less than one hour apart is refused with `InvalidSchedule`, as in AWS. Memory storage forgets actions on restart.
## Automated snapshots
Clusters take automated SQL-dump snapshots using their associated snapshot schedule. Use
@@ -687,6 +695,8 @@ For `AWS::Redshift::ClusterParameterGroup`, `Parameters` is applied via `ModifyC
| `FLOCI_SERVICES_REDSHIFT_SNAPSHOT_SWEEP_INTERVAL_SECONDS` | `60` | Delay between background snapshot sweeps |
| `FLOCI_SERVICES_REDSHIFT_SNAPSHOT_COPY_ENABLED` | `true` | Run the background sweep that copies snapshots of copy-enabled clusters to their destination Region |
| `FLOCI_SERVICES_REDSHIFT_SNAPSHOT_COPY_SWEEP_INTERVAL_SECONDS` | `60` | Delay between snapshot copy sweeps |
| `FLOCI_SERVICES_REDSHIFT_SCHEDULED_ACTIONS_ENABLED` | `true` | Run the background sweep that pauses and resumes clusters through scheduled actions |
| `FLOCI_SERVICES_REDSHIFT_SCHEDULED_ACTION_SWEEP_INTERVAL_SECONDS` | `60` | Delay between scheduled action sweeps |
| `FLOCI_SERVICES_REDSHIFT_IMAGE_VERSION` | `postgres:15-alpine` | PostgreSQL Docker image backing each cluster |
| `FLOCI_SERVICES_REDSHIFT_DEFAULT_PORT` | `5439` | Reported Redshift port hint (the real host port is dynamic and comes from `DescribeClusters`) |
| `FLOCI_SERVICES_REDSHIFT_PROXY_BASE_PORT` | `7100` | Lowest host port the per-cluster auth proxies bind |
@@ -1833,6 +1833,16 @@ public interface EmulatorConfig {
@WithDefault("60")
long snapshotCopySweepIntervalSeconds();
/**
* Run the scheduled actions of provisioned clusters, which pause or resume a cluster on a schedule.
* Env: FLOCI_SERVICES_REDSHIFT_SCHEDULED_ACTIONS_ENABLED
*/
@WithDefault("true")
boolean scheduledActionsEnabled();
@WithDefault("60")
long scheduledActionSweepIntervalSeconds();
@WithDefault("true")
boolean enabled();
@WithDefault("5439")
@@ -0,0 +1,92 @@
package io.floci.aws.core.common;
import com.cronutils.model.Cron;
import com.cronutils.model.time.ExecutionTime;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.Optional;
import java.util.function.Function;
/**
* The UTC rules the scheduled actions and snapshot schedules of Redshift and Redshift Serverless share for a
* six-field AWS {@code cron}: how the fields are read, that two invocations are at least an hour apart, which
* invocation comes next or is the latest due, and how an active window narrows them. The error each service
* raises for a bad expression differs, so the callers pass the exception to throw.
*/
public final class AwsCronSchedule {
private static final Duration MINIMUM_INTERVAL = Duration.ofHours(1);
private static final Duration SPACING_HORIZON = Duration.ofDays(400);
private static final int MAX_SPACING_CHECKS = 1000;
private AwsCronSchedule() {
}
/** Reads the six fields of an AWS cron, which put {@code ?} in exactly one of day-of-month and day-of-week. */
public static <E extends RuntimeException> ExecutionTime parse(String[] fields, Function<String, E> invalid) {
if (fields.length != 6) {
throw invalid.apply("The cron schedule needs six fields.");
}
if ("?".equals(fields[2]) == "?".equals(fields[4])) {
throw invalid.apply("Use ? in exactly one of day-of-month and day-of-week.");
}
try {
Cron cron = AwsCronDefinitions.newParser().parse("0 " + String.join(" ", fields));
cron.validate();
return ExecutionTime.forCron(cron);
} catch (IllegalArgumentException e) {
throw invalid.apply("The cron schedule is invalid: " + e.getMessage());
}
}
/** AWS requires the invocations of a cron schedule to be at least one hour apart. */
public static <E extends RuntimeException> void requireHourlySpacing(ExecutionTime cron,
Function<String, E> invalid) {
Optional<Instant> first = next(cron, Instant.EPOCH);
if (first.isEmpty()) {
return;
}
Instant cursor = first.get().minusSeconds(1);
Instant limit = cursor.plus(SPACING_HORIZON);
Instant previous = null;
for (int i = 0; i < MAX_SPACING_CHECKS; i++) {
Optional<Instant> next = next(cron, cursor);
if (next.isEmpty() || next.get().isAfter(limit)) {
return;
}
if (previous != null && Duration.between(previous, next.get()).compareTo(MINIMUM_INTERVAL) < 0) {
throw invalid.apply("The cron schedule must be at least one hour apart.");
}
previous = next.get();
cursor = next.get();
}
}
/** The first invocation strictly after {@code after}. */
public static Optional<Instant> next(ExecutionTime cron, Instant after) {
return cron.nextExecution(after.atZone(ZoneOffset.UTC)).map(value -> value.toInstant());
}
/** The latest invocation at or before {@code upper}. */
public static Optional<Instant> latest(ExecutionTime cron, Instant upper) {
return cron.lastExecution(upper.atZone(ZoneOffset.UTC).plusNanos(1)).map(value -> value.toInstant());
}
/** Where to look for the next invocation after {@code after}, which a window that has not opened moves up. */
public static Instant searchFrom(Instant after, Instant windowStart) {
return windowStart != null && windowStart.isAfter(after) ? windowStart.minusNanos(1) : after;
}
/** The last moment worth looking at up to {@code now}, which a window that has closed moves back. */
public static Instant searchUpTo(Instant now, Instant windowEnd) {
return windowEnd != null && windowEnd.isBefore(now) ? windowEnd : now;
}
/** Whether {@code time} is inside the window, whose ends are inclusive and either of which may be open. */
public static boolean inWindow(Instant time, Instant windowStart, Instant windowEnd) {
return (windowStart == null || !time.isBefore(windowStart))
&& (windowEnd == null || !time.isAfter(windowEnd));
}
}
@@ -17,6 +17,7 @@ import io.floci.aws.services.redshift.model.EventSubscription;
import io.floci.aws.services.redshift.model.Integration;
import io.floci.aws.services.redshift.model.Parameter;
import io.floci.aws.services.redshift.model.RedshiftEvent;
import io.floci.aws.services.redshift.model.ScheduledAction;
import io.floci.aws.services.redshift.model.Snapshot;
import io.floci.aws.services.redshift.model.SnapshotCopyGrant;
import io.floci.aws.services.redshift.model.SnapshotSchedule;
@@ -64,6 +65,7 @@ public class RedshiftQueryHandler {
private final RedshiftDynamoDbZeroEtlConsumer zeroEtlConsumer;
private final IamEnforcementFilter iamEnforcementFilter;
private final RedshiftResourcePolicies resourcePolicies;
private final RedshiftScheduledActionService scheduledActions;
@Inject
public RedshiftQueryHandler(RedshiftService service, RedshiftCredentialBroker credentialBroker,
@@ -71,7 +73,8 @@ public class RedshiftQueryHandler {
RegionResolver regionResolver,
RedshiftDynamoDbZeroEtlConsumer zeroEtlConsumer,
IamEnforcementFilter iamEnforcementFilter,
RedshiftResourcePolicies resourcePolicies) {
RedshiftResourcePolicies resourcePolicies,
RedshiftScheduledActionService scheduledActions) {
this.service = service;
this.credentialBroker = credentialBroker;
this.config = config;
@@ -80,12 +83,13 @@ public class RedshiftQueryHandler {
this.zeroEtlConsumer = zeroEtlConsumer;
this.iamEnforcementFilter = iamEnforcementFilter;
this.resourcePolicies = resourcePolicies;
this.scheduledActions = scheduledActions;
}
RedshiftQueryHandler(RedshiftService service, RedshiftCredentialBroker credentialBroker,
EmulatorConfig config, RedshiftIamDbUserResolver iamDbUserResolver,
RegionResolver regionResolver) {
this(service, credentialBroker, config, iamDbUserResolver, regionResolver, null, null, null);
this(service, credentialBroker, config, iamDbUserResolver, regionResolver, null, null, null, null);
}
public Response handle(String action, MultivaluedMap<String, String> params) {
@@ -854,6 +858,22 @@ public class RedshiftQueryHandler {
intParam(params, "RetentionPeriod"), Boolean.parseBoolean(params.getFirst("Manual")));
return clusterResponse(action, cluster);
}
case "CreateScheduledAction" -> {
ScheduledAction request = scheduledActionRequest(params);
return scheduledActionResponse(action, scheduledActions.createScheduledAction(request));
}
case "ModifyScheduledAction" -> {
ScheduledAction changes = scheduledActionRequest(params);
Boolean enable = booleanParam(params, "Enable");
return scheduledActionResponse(action, scheduledActions.modifyScheduledAction(changes, enable));
}
case "DeleteScheduledAction" -> {
scheduledActions.deleteScheduledAction(requireParam(params, "ScheduledActionName"));
return emptyResponse(action);
}
case "DescribeScheduledActions" -> {
return describeScheduledActionsResponse(params);
}
case "CreateSnapshotSchedule" -> {
SnapshotSchedule schedule = service.createSnapshotSchedule(params.getFirst("ScheduleIdentifier"),
params.getFirst("ScheduleDescription"), memberList(params, "ScheduleDefinitions"),
@@ -1404,6 +1424,130 @@ public class RedshiftQueryHandler {
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
}
/**
* The members a Create or ModifyScheduledAction request carries; a member left out stays null.
* TargetAction is a union of which exactly one member may be set.
*/
private static ScheduledAction scheduledActionRequest(MultivaluedMap<String, String> params) {
ScheduledAction request = new ScheduledAction();
request.setScheduledActionName(requireParam(params, "ScheduledActionName"));
request.setIamRole(params.getFirst("IamRole"));
request.setSchedule(params.getFirst("Schedule"));
request.setDescription(params.getFirst("ScheduledActionDescription"));
request.setStartTime(timestampParam(params, "StartTime"));
request.setEndTime(timestampParam(params, "EndTime"));
Boolean enable = booleanParam(params, "Enable");
if (enable != null) {
request.setEnabled(enable);
}
List<String> targets = params.keySet().stream()
.filter(key -> key.startsWith("TargetAction."))
.map(key -> key.substring("TargetAction.".length()).split("\\.")[0])
.distinct()
.toList();
if (targets.size() > 1) {
throw new AwsException("InvalidScheduledAction", "TargetAction must set exactly one member.", 400);
}
if (!targets.isEmpty()) {
String type = targets.get(0);
if ("ResizeCluster".equals(type)) {
throw new AwsException("ScheduledActionTypeUnsupported",
"Scheduled ResizeCluster actions are not supported.", 400);
}
if (!ScheduledAction.PAUSE_CLUSTER.equals(type) && !ScheduledAction.RESUME_CLUSTER.equals(type)) {
throw new AwsException("InvalidScheduledAction", "Unknown TargetAction member " + type + ".", 400);
}
request.setTargetActionType(type);
request.setClusterIdentifier(requireParam(params, "TargetAction." + type + ".ClusterIdentifier"));
}
return request;
}
private Response describeScheduledActionsResponse(MultivaluedMap<String, String> params) {
List<String> clusterIdentifiers = new ArrayList<>();
List<String> iamRoles = new ArrayList<>();
for (AwsQueryLists.IndexedMember filter : AwsQueryLists.members(params, "Filters", "ScheduledActionFilter")) {
String name = params.getFirst(filter.prefix() + ".Name");
List<String> values = AwsQueryLists.values(params, filter.prefix() + ".Values", "item");
if ("cluster-identifier".equals(name)) {
clusterIdentifiers.addAll(values);
} else if ("iam-role".equals(name)) {
iamRoles.addAll(values);
} else {
throw new AwsException("InvalidParameterValue",
"Filter name must be cluster-identifier or iam-role.", 400);
}
}
PaginatedResult<ScheduledAction> page = scheduledActions.describeScheduledActions(
params.getFirst("ScheduledActionName"), params.getFirst("TargetActionType"),
timestampParam(params, "StartTime"), timestampParam(params, "EndTime"),
booleanParam(params, "Active"),
clusterIdentifiers, iamRoles,
intParam(params, "MaxRecords"), params.getFirst("Marker"));
XmlBuilder xml = new XmlBuilder()
.start("DescribeScheduledActionsResponse")
.start("DescribeScheduledActionsResult")
.start("ScheduledActions");
for (ScheduledAction scheduledAction : page.items()) {
xml.start("ScheduledAction").raw(buildScheduledActionFields(scheduledAction)).end("ScheduledAction");
}
xml.end("ScheduledActions");
if (page.nextToken() != null) {
xml.elem("Marker", page.nextToken());
}
String body = xml
.end("DescribeScheduledActionsResult")
.start("ResponseMetadata")
.elem("RequestId", "test-req-id")
.end("ResponseMetadata")
.end("DescribeScheduledActionsResponse")
.build();
return Response.ok(body).type(MediaType.APPLICATION_XML).build();
}
// Create/ModifyScheduledAction return the ScheduledAction members directly inside the Result.
private Response scheduledActionResponse(String operation, ScheduledAction scheduledAction) {
String xml = new XmlBuilder()
.start(operation + "Response")
.start(operation + "Result")
.raw(buildScheduledActionFields(scheduledAction))
.end(operation + "Result")
.start("ResponseMetadata")
.elem("RequestId", "test-req-id")
.end("ResponseMetadata")
.end(operation + "Response")
.build();
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
}
private String buildScheduledActionFields(ScheduledAction scheduledAction) {
XmlBuilder xml = new XmlBuilder()
.elem("ScheduledActionName", scheduledAction.getScheduledActionName())
.start("TargetAction")
.start(scheduledAction.getTargetActionType())
.elem("ClusterIdentifier", scheduledAction.getClusterIdentifier())
.end(scheduledAction.getTargetActionType())
.end("TargetAction")
.elem("Schedule", scheduledAction.getSchedule())
.elem("IamRole", scheduledAction.getIamRole());
if (scheduledAction.getDescription() != null) {
xml.elem("ScheduledActionDescription", scheduledAction.getDescription());
}
xml.elem("State", scheduledAction.isEnabled() ? "ACTIVE" : "DISABLED");
xml.start("NextInvocations");
for (Instant invocation : scheduledActions.upcomingInvocations(scheduledAction, 5)) {
xml.elem("ScheduledActionTime", DateTimeFormatter.ISO_INSTANT.format(invocation));
}
xml.end("NextInvocations");
if (scheduledAction.getStartTime() != null) {
xml.elem("StartTime", DateTimeFormatter.ISO_INSTANT.format(scheduledAction.getStartTime()));
}
if (scheduledAction.getEndTime() != null) {
xml.elem("EndTime", DateTimeFormatter.ISO_INSTANT.format(scheduledAction.getEndTime()));
}
return xml.build();
}
private static Response emptyResponse(String operation) {
String xml = new XmlBuilder()
.start(operation + "Response")
@@ -0,0 +1,56 @@
package io.floci.aws.services.redshift;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestResources;
import io.floci.aws.core.common.ServicePrincipals;
import io.floci.aws.services.iam.IamAuthorizedActions;
import io.floci.aws.services.iam.ServiceRoleAuthorizer;
import io.floci.aws.services.iam.ServiceRoleAuthorizer.Permission;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.List;
import java.util.Optional;
/**
* Decides whether the IAM role of a scheduled action may pause or resume its cluster. The role has to
* trust the Redshift scheduler principal, and its identity policies, boundary and SCPs have to allow
* {@code redshift:PauseCluster} or {@code redshift:ResumeCluster} on the cluster. Only active with IAM
* enforcement on, as for every other API call. The action and the cluster resource come from the same
* generated tables a direct request to the operation is checked with.
*/
@ApplicationScoped
public class RedshiftScheduledActionAuthorizer {
private static final String SCHEDULER_PRINCIPAL = ServicePrincipals.of("scheduler.redshift");
private final ServiceRoleAuthorizer authorizer;
private final RegionResolver regionResolver;
@Inject
public RedshiftScheduledActionAuthorizer(ServiceRoleAuthorizer authorizer, RegionResolver regionResolver) {
this.authorizer = authorizer;
this.regionResolver = regionResolver;
}
/**
* Returns why {@code roleArn} may not run {@code operation}, {@code PauseCluster} or {@code ResumeCluster},
* on the cluster {@code clusterIdentifier} of {@code region}, or nothing when it may.
*/
public Optional<String> refusal(String roleArn, String accountId, String region, String operation,
String clusterIdentifier) {
String namedAs = "redshift:" + operation;
String action = IamAuthorizedActions.actionFor("redshift", operation);
ObjectNode request = JsonNodeFactory.instance.objectNode().put("ClusterIdentifier", clusterIdentifier);
List<Permission> permissions = RequestResources.ofBody(namedAs, request,
regionResolver.partitionForRegion(region), region, accountId, null).stream()
.map(resource -> new Permission(action, resource))
.toList();
if (permissions.isEmpty()) {
return Optional.of("The scheduled action's target names no cluster to run " + action + " on.");
}
return authorizer.refusal(roleArn, accountId, SCHEDULER_PRINCIPAL, null, permissions);
}
}
@@ -0,0 +1,112 @@
package io.floci.aws.services.redshift;
import com.cronutils.model.time.ExecutionTime;
import io.floci.aws.core.common.AwsCronSchedule;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.redshift.model.ScheduledAction;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/** UTC schedule rules of a provisioned scheduled action: one-off {@code at(...)} or six-field AWS {@code cron(...)}. */
final class RedshiftScheduledActionSchedule {
private RedshiftScheduledActionSchedule() { }
/** Rejects an expression that is neither a well-formed {@code at} nor a well-formed {@code cron}. */
static void validate(String schedule) {
if (schedule == null || schedule.isBlank()) {
throw invalid("Schedule is required.");
}
String body = schedule.trim();
if (body.startsWith("at(")) {
parseAt(body);
} else if (body.startsWith("cron(")) {
AwsCronSchedule.requireHourlySpacing(parseCron(body), RedshiftScheduledActionSchedule::invalid);
} else {
throw invalid("The schedule must be an at(...) or a cron(...) expression.");
}
}
/** The first invocation strictly after {@code after} that is enabled and inside the active window. */
static Optional<Instant> next(ScheduledAction action, Instant after) {
if (!action.isEnabled()) {
return Optional.empty();
}
Instant candidate;
String schedule = action.getSchedule().trim();
if (schedule.startsWith("at(")) {
Instant at = parseAt(schedule);
candidate = at.isAfter(after) ? at : null;
} else {
candidate = AwsCronSchedule.next(parseCron(schedule),
AwsCronSchedule.searchFrom(after, action.getStartTime())).orElse(null);
}
return Optional.ofNullable(candidate).filter(time -> inWindow(action, time));
}
/** The next {@code count} invocations after {@code after}. */
static List<Instant> upcoming(ScheduledAction action, Instant after, int count) {
List<Instant> invocations = new ArrayList<>();
Instant cursor = after;
while (invocations.size() < count) {
Optional<Instant> next = next(action, cursor);
if (next.isEmpty()) {
break;
}
invocations.add(next.get());
cursor = next.get();
}
return invocations;
}
/** The latest invocation in {@code (anchor, now]} that is inside the window; older ones are coalesced away. */
static Optional<Instant> latestDue(ScheduledAction action, Instant anchor, Instant now) {
if (!action.isEnabled()) {
return Optional.empty();
}
Instant upper = AwsCronSchedule.searchUpTo(now, action.getEndTime());
Optional<Instant> latest;
String schedule = action.getSchedule().trim();
if (schedule.startsWith("at(")) {
latest = Optional.of(parseAt(schedule)).filter(time -> !time.isAfter(upper));
} else {
latest = AwsCronSchedule.latest(parseCron(schedule), upper);
}
return latest.filter(time -> time.isAfter(anchor) && inWindow(action, time));
}
private static boolean inWindow(ScheduledAction action, Instant time) {
return AwsCronSchedule.inWindow(time, action.getStartTime(), action.getEndTime());
}
private static Instant parseAt(String expression) {
if (!expression.endsWith(")")) {
throw invalid("The at(...) schedule is not closed.");
}
String timestamp = expression.substring("at(".length(), expression.length() - 1).trim();
try {
return LocalDateTime.parse(timestamp).toInstant(ZoneOffset.UTC);
} catch (DateTimeParseException e) {
throw invalid("The at(...) schedule needs a UTC timestamp such as at(2026-11-20T10:00:00).");
}
}
private static ExecutionTime parseCron(String expression) {
if (!expression.endsWith(")")) {
throw invalid("The cron(...) schedule is not closed.");
}
String body = expression.substring("cron(".length(), expression.length() - 1).trim();
String[] fields = body.split("\\s+");
return AwsCronSchedule.parse(fields, RedshiftScheduledActionSchedule::invalid);
}
private static AwsException invalid(String message) {
return new AwsException("InvalidSchedule", message, 400);
}
}
@@ -0,0 +1,23 @@
package io.floci.aws.services.redshift;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.SweepScheduler;
import io.floci.aws.core.common.SweepWorker;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
/** Drives provisioned scheduled actions outside AWS request threads, one sweep at a time. */
@ApplicationScoped
public class RedshiftScheduledActionScheduler extends SweepScheduler {
@Inject
public RedshiftScheduledActionScheduler(RedshiftScheduledActionService service, EmulatorConfig config) {
super(worker(service, config.services().redshift()));
}
private static SweepWorker worker(RedshiftScheduledActionService service,
EmulatorConfig.RedshiftServiceConfig redshift) {
return new SweepWorker("redshift-scheduled-actions",
redshift.enabled() && redshift.scheduledActionsEnabled(),
redshift.scheduledActionSweepIntervalSeconds(), false, service::runScheduledActions);
}
}
@@ -0,0 +1,382 @@
package io.floci.aws.services.redshift;
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.Pagination;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.core.common.Resettable;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.AccountAwareStorageBackend.AccountEntry;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.redshift.model.ScheduledAction;
import io.quarkus.runtime.StartupEvent;
import jakarta.annotation.PostConstruct;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Clock;
import java.time.Instant;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Supplier;
/**
* Redshift scheduled actions of provisioned clusters, which pause or resume a cluster on an {@code at}
* or {@code cron} schedule. A sweep ({@link #runScheduledActions}) runs the latest invocation of every
* action whose schedule came due since it last looked. Resizing on a schedule is not supported.
*
* <p>An action belongs to a cluster but lives in its own store. Deleting the cluster removes its
* actions through a removal listener, and every read drops an action whose cluster is gone, so a
* cluster recreated under the same identifier never inherits its predecessor's actions.
*
* <p>The sweep records its checkpoint after attempting the invocation, so a crash in between can retry
* that time once. After downtime only the latest due time runs, and nothing before an action was
* created, rescheduled or enabled again is replayed. A failing invocation, such as pausing a cluster
* that is already paused, is logged and kept as the action's last failure, and never stops the others.
*
* <p>Lock order: the action's lock, then this service's monitor. The removal listener takes neither,
* because it runs under the cluster's lock, which a sweep takes while holding the action's lock.
*/
@ApplicationScoped
public class RedshiftScheduledActionService implements Resettable {
private static final Logger LOG = Logger.getLogger(RedshiftScheduledActionService.class);
private static final int MIN_MAX_RECORDS = 20;
private static final int MAX_MAX_RECORDS = 100;
private final AccountAwareStorageBackend<ScheduledAction> actions;
private final RedshiftService redshift;
private final RedshiftScheduledActionAuthorizer authorizer;
private final RegionResolver regionResolver;
private final Clock clock;
private final ConcurrentHashMap<String, ReentrantLock> actionLocks = new ConcurrentHashMap<>();
@Inject
public RedshiftScheduledActionService(StorageFactory storageFactory, RedshiftService redshift,
RedshiftScheduledActionAuthorizer authorizer,
RegionResolver regionResolver, Clock clock) {
this.actions = storageFactory.create("redshift", "redshift-scheduled-actions.json",
new TypeReference<Map<String, ScheduledAction>>() {});
this.redshift = redshift;
this.authorizer = authorizer;
this.regionResolver = regionResolver;
this.clock = clock;
}
RedshiftScheduledActionService(StorageFactory storageFactory, RedshiftService redshift,
RedshiftScheduledActionAuthorizer authorizer, RegionResolver regionResolver) {
this(storageFactory, redshift, authorizer, regionResolver, Clock.systemUTC());
}
@PostConstruct
void registerClusterRemoval() {
redshift.onClusterRemoved(this::removeActionsOfCluster);
}
// Observing startup builds this lazy bean at boot, so its removal listener is registered before any
// cluster can be deleted, also when the sweep is disabled or has not ticked yet.
void onStart(@Observes StartupEvent ignored) {
LOG.debug("Redshift scheduled actions registered for cluster removal");
}
/** Creates {@code request}. The target cluster must exist and the name must be unused. */
public ScheduledAction createScheduledAction(ScheduledAction request) {
return mutate(request.getScheduledActionName(), () -> {
validate(request);
if (liveActions().stream().anyMatch(existing ->
existing.getScheduledActionName().equals(request.getScheduledActionName()))) {
throw new AwsException("ScheduledActionAlreadyExists",
"The scheduled action " + request.getScheduledActionName() + " already exists.", 400);
}
ScheduledAction action = new ScheduledAction(request);
action.setActivatedAt(clock.instant());
actions.put(request.getScheduledActionName(), action);
// The cluster can be deleted between the check in validate and the write; its removal
// listener has already run by then, so the action would be left behind.
if (!clusterExists(action)) {
actions.delete(request.getScheduledActionName());
throw new AwsException("ClusterNotFound",
"Cluster " + request.getClusterIdentifier() + " not found", 404);
}
return new ScheduledAction(action);
});
}
/**
* Lists the account's actions filtered by the given members, which are all optional. {@code active}
* keeps only the enabled actions when true and only the disabled ones when false. The time
* filters keep the enabled actions with an invocation at or after {@code startTime}, or at or
* before {@code endTime}.
*/
public synchronized PaginatedResult<ScheduledAction> describeScheduledActions(
String name, String targetActionType, Instant startTime, Instant endTime, Boolean active,
List<String> clusterIdentifiers, List<String> iamRoles, Integer maxRecords, String marker) {
int limit = maxRecords == null ? MAX_MAX_RECORDS : maxRecords;
if (limit < MIN_MAX_RECORDS || limit > MAX_MAX_RECORDS) {
throw new AwsException("InvalidParameterValue",
"MaxRecords must be between " + MIN_MAX_RECORDS + " and " + MAX_MAX_RECORDS + ".", 400);
}
Instant now = clock.instant();
List<ScheduledAction> matching = liveActions().stream()
.filter(action -> name == null || name.equals(action.getScheduledActionName()))
.filter(action -> targetActionType == null || targetActionType.equals(action.getTargetActionType()))
.filter(action -> active == null || action.isEnabled() == active)
.filter(action -> clusterIdentifiers.isEmpty()
|| clusterIdentifiers.contains(action.getClusterIdentifier()))
.filter(action -> iamRoles.isEmpty() || iamRoles.contains(action.getIamRole()))
.filter(action -> startTime == null
|| RedshiftScheduledActionSchedule.next(action, startTime.minusNanos(1)).isPresent())
.filter(action -> endTime == null || RedshiftScheduledActionSchedule.next(action, now)
.filter(next -> !next.isAfter(endTime)).isPresent())
.sorted(Comparator.comparing(ScheduledAction::getScheduledActionName))
.map(ScheduledAction::new)
.toList();
return Pagination.paginate(matching, ScheduledAction::getScheduledActionName, limit, marker,
"redshift-scheduled-action",
token -> new AwsException("InvalidParameterValue", "Invalid Marker.", 400));
}
/**
* Applies the members {@code changes} carries; a null member is left as it was. A new schedule, or
* enabling a disabled action, restarts the count from now so nothing earlier is replayed.
*/
public ScheduledAction modifyScheduledAction(ScheduledAction changes, Boolean enable) {
return mutate(changes.getScheduledActionName(), () -> {
ScheduledAction current = require(changes.getScheduledActionName());
ScheduledAction updated = new ScheduledAction(current);
if (changes.getIamRole() != null) {
updated.setIamRole(changes.getIamRole());
}
if (changes.getDescription() != null) {
updated.setDescription(changes.getDescription());
}
if (changes.getSchedule() != null) {
RedshiftScheduledActionSchedule.validate(changes.getSchedule());
updated.setSchedule(changes.getSchedule());
updated.setActivatedAt(clock.instant());
updated.setLastClaimedInvocation(null);
}
if (changes.getTargetActionType() != null) {
updated.setTargetActionType(changes.getTargetActionType());
updated.setClusterIdentifier(changes.getClusterIdentifier());
}
if (changes.getStartTime() != null) {
updated.setStartTime(changes.getStartTime());
}
if (changes.getEndTime() != null) {
updated.setEndTime(changes.getEndTime());
}
if (enable != null) {
if (enable && !current.isEnabled()) {
updated.setActivatedAt(clock.instant());
}
updated.setEnabled(enable);
}
validate(updated);
actions.put(updated.getScheduledActionName(), updated);
// Same race as in createScheduledAction: a deletion between validate and put leaves an orphan.
if (!clusterExists(updated)) {
actions.delete(updated.getScheduledActionName());
throw new AwsException("ClusterNotFound",
"Cluster " + updated.getClusterIdentifier() + " not found", 404);
}
return new ScheduledAction(updated);
});
}
public void deleteScheduledAction(String name) {
mutate(name, () -> {
require(name);
actions.delete(name);
return null;
});
}
/** The next {@code count} invocations of {@code action} from now. */
public List<Instant> upcomingInvocations(ScheduledAction action, int count) {
return RedshiftScheduledActionSchedule.upcoming(action, clock.instant(), count);
}
/**
* Runs the latest due invocation of every action whose time falls in {@code (checkpoint, now]}. A
* deterministic entry point: the lifecycle scheduler supplies the clock and tests a fixed instant.
*/
public void runScheduledActions(Instant now) {
for (AccountEntry<ScheduledAction> entry : actions.scanAllAccountEntries(key -> true)) {
if (Thread.currentThread().isInterrupted()) {
return;
}
ReentrantLock lock = lockOf(entry.accountId(), entry.key());
lock.lock();
try {
RequestScopes.runAs(entry.accountId(), regionOf(entry.accountId(), entry.value()),
() -> runScheduledAction(entry.accountId(), entry.key(), now));
} catch (RuntimeException e) {
LOG.warnv(e, "Scheduled action {0} in account {1} could not be processed",
entry.key(), entry.accountId());
} finally {
lock.unlock();
}
}
}
/** Runs under the action's lock, with the action's account as the request scope. */
private void runScheduledAction(String accountId, String key, Instant now) {
ScheduledAction action = actions.getForAccount(accountId, key).orElse(null);
if (action == null) {
return;
}
if (!redshift.clusterExists(accountId, action.getClusterIdentifier())) {
actions.deleteForAccount(accountId, key);
return;
}
if (action.getActivatedAt() == null) {
ScheduledAction activated = new ScheduledAction(action);
activated.setActivatedAt(now);
actions.putAllAtomicallyForAccount(accountId, Map.of(key, activated));
return;
}
Instant checkpoint = action.getLastClaimedInvocation() != null
&& action.getLastClaimedInvocation().isAfter(action.getActivatedAt())
? action.getLastClaimedInvocation() : action.getActivatedAt();
Optional<Instant> due = RedshiftScheduledActionSchedule.latestDue(action, checkpoint, now);
if (due.isEmpty()) {
return;
}
Instant scheduled = due.get();
ScheduledAction outcome = new ScheduledAction(action);
outcome.setLastClaimedInvocation(scheduled);
outcome.setLastFailure(null);
try {
invoke(action, accountId);
outcome.setLastCompletedInvocation(scheduled);
} catch (RuntimeException e) {
LOG.warnv(e, "Scheduled action {0} in account {1} failed at {2}",
action.getScheduledActionName(), accountId, scheduled);
outcome.setLastFailure(String.valueOf(e.getMessage()));
}
recordOutcome(accountId, key, outcome);
}
private void invoke(ScheduledAction action, String accountId) {
Optional<String> refusal = authorizer.refusal(action.getIamRole(), accountId, regionOf(accountId, action),
action.getTargetActionType(), action.getClusterIdentifier());
if (refusal.isPresent()) {
throw new AwsException("UnauthorizedOperation", refusal.get(), 400);
}
if (ScheduledAction.PAUSE_CLUSTER.equals(action.getTargetActionType())) {
redshift.pauseCluster(action.getClusterIdentifier());
} else {
redshift.resumeCluster(action.getClusterIdentifier());
}
}
/** Stores the checkpoint and outcome only when the action is still the one that was run. */
private void recordOutcome(String accountId, String key, ScheduledAction outcome) {
// A failed write propagates to runScheduledActions, which logs it; swallowing it here would leave the
// checkpoint behind and re-run the same invocation on every sweep.
ScheduledAction current = actions.getForAccount(accountId, key).orElse(null);
if (current != null && Objects.equals(current.getActivatedAt(), outcome.getActivatedAt())) {
ScheduledAction recorded = new ScheduledAction(current);
recorded.setLastClaimedInvocation(outcome.getLastClaimedInvocation());
recorded.setLastCompletedInvocation(outcome.getLastCompletedInvocation());
recorded.setLastFailure(outcome.getLastFailure());
actions.putAllAtomicallyForAccount(accountId, Map.of(key, recorded));
}
}
/** The region of the target cluster, which its ARN and the role check are scoped to. */
private String regionOf(String accountId, ScheduledAction action) {
return redshift.clusterRegion(accountId, action.getClusterIdentifier())
.orElseGet(regionResolver::getDefaultRegion);
}
private void removeActionsOfCluster(String accountId, String clusterIdentifier) {
for (AccountEntry<ScheduledAction> entry : actions.scanAllAccountEntries(key -> true)) {
if (entry.accountId().equals(accountId)
&& clusterIdentifier.equals(entry.value().getClusterIdentifier())) {
actions.deleteForAccount(accountId, entry.key());
}
}
}
@Override
public void clear() {
actions.clear();
actionLocks.clear();
}
private <T> T mutate(String name, Supplier<T> body) {
ReentrantLock lock = lockOf(regionResolver.getAccountId(), name);
lock.lock();
try {
synchronized (this) {
return body.get();
}
} finally {
lock.unlock();
}
}
private ReentrantLock lockOf(String accountId, String key) {
return actionLocks.computeIfAbsent(accountId + "|" + key, ignored -> new ReentrantLock());
}
private ScheduledAction require(String name) {
ScheduledAction action = actions.get(name).orElse(null);
if (action != null && !clusterExists(action)) {
actions.delete(name);
action = null;
}
if (action == null) {
throw new AwsException("ScheduledActionNotFound", "The scheduled action " + name + " was not found.", 400);
}
return action;
}
/** The account's actions whose cluster is still there; any other is deleted as it is found. */
private List<ScheduledAction> liveActions() {
return actions.scan(key -> true).stream()
.filter(action -> {
if (clusterExists(action)) {
return true;
}
actions.delete(action.getScheduledActionName());
return false;
})
.toList();
}
private boolean clusterExists(ScheduledAction action) {
return redshift.clusterExists(regionResolver.getAccountId(), action.getClusterIdentifier());
}
private void validate(ScheduledAction action) {
if (action.getScheduledActionName() == null || action.getScheduledActionName().isBlank()) {
throw new AwsException("InvalidParameterValue", "ScheduledActionName is required.", 400);
}
if (action.getIamRole() == null || action.getIamRole().isBlank()) {
throw new AwsException("InvalidParameterValue", "IamRole is required.", 400);
}
RedshiftScheduledActionSchedule.validate(action.getSchedule());
if (action.getStartTime() != null && action.getEndTime() != null
&& !action.getEndTime().isAfter(action.getStartTime())) {
throw new AwsException("InvalidSchedule", "EndTime must be after StartTime.", 400);
}
if (!ScheduledAction.PAUSE_CLUSTER.equals(action.getTargetActionType())
&& !ScheduledAction.RESUME_CLUSTER.equals(action.getTargetActionType())) {
throw new AwsException("InvalidScheduledAction", "TargetAction must be PauseCluster or ResumeCluster.", 400);
}
// Throws ClusterNotFound for a cluster the account does not have.
redshift.describeClusters(action.getClusterIdentifier());
}
}
@@ -71,7 +71,9 @@ import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.BiConsumer;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Predicate;
@@ -128,6 +130,7 @@ public class RedshiftService implements ManagedSecretRotator {
private final Set<Integer> usedPorts = ConcurrentHashMap.newKeySet();
private final ConcurrentHashMap<ResourceKey, ResourceLock> resourceLocks = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, ResourceKey> managedRotationReservations = new ConcurrentHashMap<>();
private final List<BiConsumer<String, String>> clusterRemovalListeners = new CopyOnWriteArrayList<>();
private record ResourceKey(String accountId, String kind, String identifier) { }
@@ -507,6 +510,7 @@ public class RedshiftService implements ManagedSecretRotator {
if (proxyStopped) {
clusters.delete(identifier);
credentialBroker.revokeCluster(clusters.accountId(), identifier);
notifyClusterRemoved(identifier);
} else {
cluster.setClusterStatus("failed");
clusters.put(identifier, cluster);
@@ -519,6 +523,7 @@ public class RedshiftService implements ManagedSecretRotator {
if (proxyStopped) {
clusters.delete(identifier);
credentialBroker.revokeCluster(clusters.accountId(), identifier);
notifyClusterRemoved(identifier);
} else {
cluster.setClusterStatus("failed");
clusters.put(identifier, cluster);
@@ -619,6 +624,7 @@ public class RedshiftService implements ManagedSecretRotator {
if (proxyStopped) {
clusters.delete(cluster.getClusterIdentifier());
credentialBroker.revokeCluster(clusters.accountId(), cluster.getClusterIdentifier());
notifyClusterRemoved(cluster.getClusterIdentifier());
} else {
cluster.setClusterStatus("failed");
clusters.put(cluster.getClusterIdentifier(), cluster);
@@ -1127,6 +1133,34 @@ public class RedshiftService implements ManagedSecretRotator {
}
}
/**
* Registers a callback run with the account id and identifier of every cluster that is deleted. It runs
* while the cluster's resource lock is held, so it must not wait for locks of its own.
*/
public void onClusterRemoved(BiConsumer<String, String> listener) {
clusterRemovalListeners.add(listener);
}
public boolean clusterExists(String accountId, String identifier) {
return clusters.getForAccount(accountId, identifier).isPresent();
}
/** The region the cluster was created in, or empty when the account has no such cluster. */
public Optional<String> clusterRegion(String accountId, String identifier) {
return clusters.getForAccount(accountId, identifier).map(this::snapshotRegion);
}
/** A failing listener must not abort the removal: the cluster is already gone by now. */
private void notifyClusterRemoved(String identifier) {
for (BiConsumer<String, String> listener : clusterRemovalListeners) {
try {
listener.accept(clusters.accountId(), identifier);
} catch (RuntimeException e) {
LOG.warnv(e, "Cluster removal listener failed for cluster {0}", identifier);
}
}
}
public List<Cluster> describeClusters(String identifier) {
if (identifier != null) {
Optional<Cluster> cluster = clusters.get(identifier);
@@ -1274,6 +1308,7 @@ public class RedshiftService implements ManagedSecretRotator {
// Invalidate any GetClusterCredentials passwords so a cluster later recreated with this
// identifier does not accept them as master-equivalent.
credentialBroker.revokeCluster(clusters.accountId(), identifier);
notifyClusterRemoved(identifier);
if (cluster.getMasterPasswordSecretArn() != null && secretsManagerService != null) {
try {
@@ -2535,6 +2570,7 @@ public class RedshiftService implements ManagedSecretRotator {
mutate(() -> {
if (proxyStopped) {
clusters.delete(identifier);
notifyClusterRemoved(identifier);
} else {
cluster.setClusterStatus("failed");
clusters.put(identifier, cluster);
@@ -1,13 +1,11 @@
package io.floci.aws.services.redshift;
import com.cronutils.model.Cron;
import com.cronutils.model.time.ExecutionTime;
import io.floci.aws.core.common.AwsCronDefinitions;
import io.floci.aws.core.common.AwsCronSchedule;
import io.floci.aws.core.common.AwsException;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
@@ -88,12 +86,7 @@ final class RedshiftSnapshotSchedule {
default -> throw new IllegalArgumentException("Redshift cron needs three or six fields");
};
String[] full = normalized.split(" ");
if ("?".equals(full[2]) == "?".equals(full[4])) {
throw new IllegalArgumentException("Use ? in exactly one of day-of-month and day-of-week");
}
Cron cron = AwsCronDefinitions.newParser().parse("0 " + normalized);
cron.validate();
return new Rule(null, ExecutionTime.forCron(cron));
return new Rule(null, AwsCronSchedule.parse(full, IllegalArgumentException::new));
}
private record Rule(Duration rate, ExecutionTime cron) {
@@ -102,7 +95,7 @@ final class RedshiftSnapshotSchedule {
long count = Duration.between(anchor, now).getSeconds() / rate.getSeconds();
return count < 1 ? Optional.empty() : Optional.of(anchor.plus(rate.multipliedBy(count)));
}
return cron.lastExecution(now.atZone(ZoneOffset.UTC).plusNanos(1)).map(value -> value.toInstant());
return AwsCronSchedule.latest(cron, now);
}
Optional<Instant> next(Instant anchor, Instant after) {
@@ -110,7 +103,7 @@ final class RedshiftSnapshotSchedule {
long count = Math.max(0, Duration.between(anchor, after).getSeconds() / rate.getSeconds()) + 1;
return Optional.of(anchor.plus(rate.multipliedBy(count)));
}
return cron.nextExecution(after.atZone(ZoneOffset.UTC)).map(value -> value.toInstant());
return AwsCronSchedule.next(cron, after);
}
}
}
@@ -0,0 +1,93 @@
package io.floci.aws.services.redshift.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
/**
* A scheduled action of a provisioned cluster. The activation and invocation members are internal
* bookkeeping of the sweep: no AWS response shows them.
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class ScheduledAction {
public static final String PAUSE_CLUSTER = "PauseCluster";
public static final String RESUME_CLUSTER = "ResumeCluster";
private String scheduledActionName;
private String iamRole;
private String schedule;
private String description;
private String targetActionType;
private String clusterIdentifier;
private boolean enabled = true;
private Instant startTime;
private Instant endTime;
private Instant activatedAt;
private Instant lastClaimedInvocation;
private Instant lastCompletedInvocation;
private String lastFailure;
public ScheduledAction() {
}
public ScheduledAction(ScheduledAction other) {
this.scheduledActionName = other.scheduledActionName;
this.iamRole = other.iamRole;
this.schedule = other.schedule;
this.description = other.description;
this.targetActionType = other.targetActionType;
this.clusterIdentifier = other.clusterIdentifier;
this.enabled = other.enabled;
this.startTime = other.startTime;
this.endTime = other.endTime;
this.activatedAt = other.activatedAt;
this.lastClaimedInvocation = other.lastClaimedInvocation;
this.lastCompletedInvocation = other.lastCompletedInvocation;
this.lastFailure = other.lastFailure;
}
public String getScheduledActionName() { return scheduledActionName; }
public void setScheduledActionName(String value) { scheduledActionName = value; }
public String getIamRole() { return iamRole; }
public void setIamRole(String value) { iamRole = value; }
public String getSchedule() { return schedule; }
public void setSchedule(String value) { schedule = value; }
public String getDescription() { return description; }
public void setDescription(String value) { description = value; }
/** {@link #PAUSE_CLUSTER} or {@link #RESUME_CLUSTER}. */
public String getTargetActionType() { return targetActionType; }
public void setTargetActionType(String value) { targetActionType = value; }
public String getClusterIdentifier() { return clusterIdentifier; }
public void setClusterIdentifier(String value) { clusterIdentifier = value; }
public boolean isEnabled() { return enabled; }
public void setEnabled(boolean value) { enabled = value; }
public Instant getStartTime() { return startTime; }
public void setStartTime(Instant value) { startTime = value; }
public Instant getEndTime() { return endTime; }
public void setEndTime(Instant value) { endTime = value; }
/** When the current schedule began counting, so no invocation before it is replayed. */
public Instant getActivatedAt() { return activatedAt; }
public void setActivatedAt(Instant value) { activatedAt = value; }
/** The latest scheduled time that was attempted; it is never attempted twice. */
public Instant getLastClaimedInvocation() { return lastClaimedInvocation; }
public void setLastClaimedInvocation(Instant value) { lastClaimedInvocation = value; }
public Instant getLastCompletedInvocation() { return lastCompletedInvocation; }
public void setLastCompletedInvocation(Instant value) { lastCompletedInvocation = value; }
public String getLastFailure() { return lastFailure; }
public void setLastFailure(String value) { lastFailure = value; }
}
@@ -1,21 +1,14 @@
package io.floci.aws.services.redshiftserverless;
import com.cronutils.model.Cron;
import com.cronutils.model.time.ExecutionTime;
import io.floci.aws.core.common.AwsCronDefinitions;
import io.floci.aws.core.common.AwsCronSchedule;
import io.floci.aws.services.redshiftserverless.model.ScheduledAction;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.Optional;
/** UTC schedule rules of a Serverless scheduled action: one-off {@code at} or six-field AWS {@code cron}. */
final class RedshiftServerlessSchedule {
private static final Duration MINIMUM_INTERVAL = Duration.ofHours(1);
private static final Duration SPACING_HORIZON = Duration.ofDays(400);
private static final int MAX_SPACING_CHECKS = 1000;
private RedshiftServerlessSchedule() { }
/** Rejects a cron that does not parse or fires more often than hourly; an {@code at} schedule always passes. */
@@ -23,25 +16,7 @@ final class RedshiftServerlessSchedule {
if (action.getScheduleCron() == null || action.getScheduleCron().isBlank()) {
return;
}
ExecutionTime cron = parse(action.getScheduleCron());
Optional<Instant> first = nextCron(cron, Instant.EPOCH);
if (first.isEmpty()) {
return;
}
Instant cursor = first.get().minusSeconds(1);
Instant limit = cursor.plus(SPACING_HORIZON);
Instant previous = null;
for (int i = 0; i < MAX_SPACING_CHECKS; i++) {
Optional<Instant> next = nextCron(cron, cursor);
if (next.isEmpty() || next.get().isAfter(limit)) {
return;
}
if (previous != null && Duration.between(previous, next.get()).compareTo(MINIMUM_INTERVAL) < 0) {
throw ServerlessSupport.validation("The cron schedule must be at least one hour apart.");
}
previous = next.get();
cursor = next.get();
}
AwsCronSchedule.requireHourlySpacing(parse(action.getScheduleCron()), ServerlessSupport::validation);
}
/** The first invocation strictly after {@code after} that is enabled and inside the active window. */
@@ -53,9 +28,8 @@ final class RedshiftServerlessSchedule {
if (action.getScheduleAt() != null) {
candidate = action.getScheduleAt().isAfter(after) ? action.getScheduleAt() : null;
} else {
Instant from = action.getStartTime() != null && action.getStartTime().isAfter(after)
? action.getStartTime().minusNanos(1) : after;
candidate = nextCron(parse(action.getScheduleCron()), from).orElse(null);
candidate = AwsCronSchedule.next(parse(action.getScheduleCron()),
AwsCronSchedule.searchFrom(after, action.getStartTime())).orElse(null);
}
return Optional.ofNullable(candidate).filter(time -> inWindow(action, time));
}
@@ -65,24 +39,18 @@ final class RedshiftServerlessSchedule {
if (Boolean.FALSE.equals(action.getEnabled())) {
return Optional.empty();
}
Instant upper = action.getEndTime() != null && action.getEndTime().isBefore(now) ? action.getEndTime() : now;
Instant upper = AwsCronSchedule.searchUpTo(now, action.getEndTime());
Optional<Instant> latest;
if (action.getScheduleAt() != null) {
latest = Optional.of(action.getScheduleAt()).filter(time -> !time.isAfter(upper));
} else {
latest = parse(action.getScheduleCron()).lastExecution(upper.atZone(ZoneOffset.UTC).plusNanos(1))
.map(value -> value.toInstant());
latest = AwsCronSchedule.latest(parse(action.getScheduleCron()), upper);
}
return latest.filter(time -> time.isAfter(anchor) && inWindow(action, time));
}
private static boolean inWindow(ScheduledAction action, Instant time) {
return (action.getStartTime() == null || !time.isBefore(action.getStartTime()))
&& (action.getEndTime() == null || !time.isAfter(action.getEndTime()));
}
private static Optional<Instant> nextCron(ExecutionTime cron, Instant after) {
return cron.nextExecution(after.atZone(ZoneOffset.UTC)).map(value -> value.toInstant());
return AwsCronSchedule.inWindow(time, action.getStartTime(), action.getEndTime());
}
private static ExecutionTime parse(String expression) {
@@ -94,18 +62,6 @@ final class RedshiftServerlessSchedule {
body = body.substring(1, body.length() - 1).trim();
}
String[] fields = body.split("\\s+");
if (fields.length != 6) {
throw ServerlessSupport.validation("The cron schedule needs six fields.");
}
if ("?".equals(fields[2]) == "?".equals(fields[4])) {
throw ServerlessSupport.validation("Use ? in exactly one of day-of-month and day-of-week.");
}
try {
Cron cron = AwsCronDefinitions.newParser().parse("0 " + String.join(" ", fields));
cron.validate();
return ExecutionTime.forCron(cron);
} catch (IllegalArgumentException e) {
throw ServerlessSupport.validation("The cron schedule is invalid: " + e.getMessage());
}
return AwsCronSchedule.parse(fields, ServerlessSupport::validation);
}
}
+2
View File
@@ -558,6 +558,8 @@ floci:
snapshot-sweep-interval-seconds: 60
snapshot-copy-enabled: true
snapshot-copy-sweep-interval-seconds: 60
scheduled-actions-enabled: true
scheduled-action-sweep-interval-seconds: 60
default-port: 5439
image-version: postgres:15-alpine
poll-interval-ms: 1000
@@ -0,0 +1,62 @@
package io.floci.aws.core.common;
import com.cronutils.model.time.ExecutionTime;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class AwsCronScheduleTest {
private static final Instant NOON = Instant.parse("2026-11-20T12:00:00Z");
private static ExecutionTime parse(String fields) {
return AwsCronSchedule.parse(fields.split("\s+"), IllegalArgumentException::new);
}
@Test
void nextAndLatestAreStrictlyAfterAndAtOrBefore() {
ExecutionTime hourly = parse("0 * * * ? *");
assertEquals(Optional.of(Instant.parse("2026-11-20T13:00:00Z")), AwsCronSchedule.next(hourly, NOON));
assertEquals(Optional.of(NOON), AwsCronSchedule.latest(hourly, NOON));
assertEquals(Optional.of(NOON), AwsCronSchedule.latest(hourly, NOON.plusSeconds(1800)));
}
@Test
void aBadExpressionRaisesTheCallersException() {
assertEquals("The cron schedule needs six fields.",
assertThrows(IllegalStateException.class,
() -> AwsCronSchedule.parse(new String[] {"0", "*"}, IllegalStateException::new)).getMessage());
assertThrows(IllegalArgumentException.class, () -> parse("0 * * * * *"));
assertThrows(IllegalArgumentException.class, () -> parse("0 * ? * ? *"));
assertThrows(IllegalArgumentException.class, () -> parse("99 * * * ? *"));
}
@Test
void spacingUnderAnHourIsRefusedAndAnHourIsAccepted() {
AwsCronSchedule.requireHourlySpacing(parse("0 * * * ? *"), IllegalArgumentException::new);
assertThrows(IllegalArgumentException.class,
() -> AwsCronSchedule.requireHourlySpacing(parse("0/30 * * * ? *"), IllegalArgumentException::new));
}
@Test
void aWindowMovesTheSearchAndKeepsItsEndsInclusive() {
Instant start = NOON.plusSeconds(3600);
Instant end = NOON.plusSeconds(7200);
assertEquals(start.minusNanos(1), AwsCronSchedule.searchFrom(NOON, start));
assertEquals(NOON, AwsCronSchedule.searchFrom(NOON, null));
assertEquals(end, AwsCronSchedule.searchUpTo(NOON.plusSeconds(9000), end));
assertEquals(NOON, AwsCronSchedule.searchUpTo(NOON, end));
assertTrue(AwsCronSchedule.inWindow(start, start, end));
assertTrue(AwsCronSchedule.inWindow(end, start, end));
assertFalse(AwsCronSchedule.inWindow(end.plusSeconds(1), start, end));
assertTrue(AwsCronSchedule.inWindow(NOON, null, null));
}
}
@@ -0,0 +1,69 @@
package io.floci.aws.services.redshift;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.ServicePrincipals;
import io.floci.aws.services.iam.ServiceRoleAuthorizer;
import io.floci.aws.services.iam.ServiceRoleAuthorizer.Permission;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class RedshiftScheduledActionAuthorizerTest {
private static final String ROLE = "arn:aws:iam::123456789012:role/scheduler";
private ServiceRoleAuthorizer roles;
private RedshiftScheduledActionAuthorizer authorizer;
@BeforeEach
void setUp() {
roles = mock(ServiceRoleAuthorizer.class);
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.partitionForRegion("eu-west-1")).thenReturn("aws");
authorizer = new RedshiftScheduledActionAuthorizer(roles, regionResolver);
}
@Test
void theRoleIsCheckedForTheActionOfTheOperationOnTheClusterOfItsRegion() {
when(roles.refusal(any(), any(), any(), any(), anyList())).thenReturn(Optional.of("denied"));
Optional<String> refusal = authorizer.refusal(ROLE, "123456789012", "eu-west-1", "PauseCluster", "analytics");
assertEquals(Optional.of("denied"), refusal);
ArgumentCaptor<List<Permission>> permissions = ArgumentCaptor.forClass(List.class);
verify(roles).refusal(eq(ROLE), eq("123456789012"), eq(ServicePrincipals.of("scheduler.redshift")), isNull(),
permissions.capture());
assertEquals(1, permissions.getValue().size());
assertEquals("redshift:PauseCluster", permissions.getValue().get(0).action());
assertEquals("arn:aws:redshift:eu-west-1:123456789012:cluster:analytics",
permissions.getValue().get(0).resourceArn());
}
@Test
void resumeIsCheckedAsItsOwnAction() {
authorizer.refusal(ROLE, "123456789012", "eu-west-1", "ResumeCluster", "analytics");
ArgumentCaptor<List<Permission>> permissions = ArgumentCaptor.forClass(List.class);
verify(roles).refusal(any(), any(), any(), any(), permissions.capture());
assertEquals("redshift:ResumeCluster", permissions.getValue().get(0).action());
}
@Test
void anOperationTheTablesDoNotKnowIsRefusedInsteadOfCheckedOnNothing() {
Optional<String> refusal = authorizer.refusal(ROLE, "123456789012", "eu-west-1", "NoSuchOperation", "analytics");
assertTrue(refusal.isPresent());
}
}
@@ -0,0 +1,175 @@
package io.floci.aws.services.redshift;
import com.fasterxml.jackson.core.type.TypeReference;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.redshift.model.ScheduledAction;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
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.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class RedshiftScheduledActionQueryTest {
private static final String ACCOUNT_ID = "123456789012";
private static final String ROLE_ARN = "arn:aws:iam::" + ACCOUNT_ID + ":role/scheduler";
private RedshiftQueryHandler handler;
@BeforeEach
@SuppressWarnings({"unchecked", "rawtypes"})
void setUp() {
AccountAwareStorageBackend<ScheduledAction> store =
new AccountAwareStorageBackend<>(new InMemoryStorage<String, ScheduledAction>(), null, ACCOUNT_ID);
StorageFactory storageFactory = mock(StorageFactory.class);
when(storageFactory.create(eq("redshift"), eq("redshift-scheduled-actions.json"),
any(TypeReference.class))).thenReturn((AccountAwareStorageBackend) store);
RedshiftService redshift = mock(RedshiftService.class);
when(redshift.clusterExists(anyString(), anyString())).thenReturn(true);
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn(ACCOUNT_ID);
RedshiftScheduledActionService scheduledActions = new RedshiftScheduledActionService(
storageFactory, redshift, mock(RedshiftScheduledActionAuthorizer.class), regionResolver,
Clock.fixed(Instant.parse("2026-11-20T12:15:00Z"), ZoneOffset.UTC));
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
handler = new RedshiftQueryHandler(redshift, new RedshiftCredentialBroker(), config,
mock(RedshiftIamDbUserResolver.class), regionResolver, null, null, null, scheduledActions);
}
private static MultivaluedMap<String, String> createParams(String name) {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.add("ScheduledActionName", name);
params.add("IamRole", ROLE_ARN);
params.add("Schedule", "cron(0 22 * * ? *)");
params.add("TargetAction.PauseCluster.ClusterIdentifier", "analytics");
params.add("ScheduledActionDescription", "pause at night");
return params;
}
private static String body(Response response) {
return String.valueOf(response.getEntity());
}
@Test
void createReturnsTheActionWithItsStateAndNextInvocations() {
String xml = body(handler.handle("CreateScheduledAction", createParams("nightly")));
assertTrue(xml.contains("<ScheduledActionName>nightly</ScheduledActionName>"), xml);
assertTrue(xml.contains("<TargetAction><PauseCluster><ClusterIdentifier>analytics</ClusterIdentifier>"
+ "</PauseCluster></TargetAction>"), xml);
assertTrue(xml.contains("<State>ACTIVE</State>"), xml);
assertTrue(xml.contains("<ScheduledActionTime>2026-11-20T22:00:00Z</ScheduledActionTime>"), xml);
assertTrue(xml.contains("<ScheduledActionDescription>pause at night</ScheduledActionDescription>"), xml);
}
@Test
void describeListsTheActionsFilteredByClusterAndModifyDisablesOne() {
handler.handle("CreateScheduledAction", createParams("nightly"));
MultivaluedMap<String, String> modify = new MultivaluedHashMap<>();
modify.add("ScheduledActionName", "nightly");
modify.add("Enable", "false");
assertTrue(body(handler.handle("ModifyScheduledAction", modify)).contains("<State>DISABLED</State>"));
MultivaluedMap<String, String> describe = new MultivaluedHashMap<>();
describe.add("Filters.ScheduledActionFilter.1.Name", "cluster-identifier");
describe.add("Filters.ScheduledActionFilter.1.Values.item.1", "analytics");
String xml = body(handler.handle("DescribeScheduledActions", describe));
assertTrue(xml.contains("<ScheduledActions><ScheduledAction><ScheduledActionName>nightly"), xml);
describe.putSingle("Filters.ScheduledActionFilter.1.Values.item.1", "other");
assertTrue(body(handler.handle("DescribeScheduledActions", describe))
.contains("<ScheduledActions></ScheduledActions>"));
}
@Test
void activeFlagKeepsEnabledOrDisabledActionsAndAbsentMeansAll() {
handler.handle("CreateScheduledAction", createParams("on"));
handler.handle("CreateScheduledAction", createParams("off"));
MultivaluedMap<String, String> disable = new MultivaluedHashMap<>();
disable.add("ScheduledActionName", "off");
disable.add("Enable", "false");
handler.handle("ModifyScheduledAction", disable);
MultivaluedMap<String, String> describe = new MultivaluedHashMap<>();
String all = body(handler.handle("DescribeScheduledActions", describe));
assertTrue(all.contains("<ScheduledActionName>on<") && all.contains("<ScheduledActionName>off<"), all);
describe.putSingle("Active", "false");
String disabled = body(handler.handle("DescribeScheduledActions", describe));
assertTrue(disabled.contains("<ScheduledActionName>off<") && !disabled.contains("<ScheduledActionName>on<"),
disabled);
describe.putSingle("Active", "true");
String enabled = body(handler.handle("DescribeScheduledActions", describe));
assertTrue(enabled.contains("<ScheduledActionName>on<") && !enabled.contains("<ScheduledActionName>off<"),
enabled);
}
@Test
void aNonBooleanEnableOrActiveIsRefusedAndNeverChangesState() {
MultivaluedMap<String, String> create = createParams("typo");
create.add("Enable", "maybe");
assertEquals("InvalidParameterValue", assertThrows(AwsException.class,
() -> handler.handle("CreateScheduledAction", create)).getErrorCode());
handler.handle("CreateScheduledAction", createParams("nightly"));
MultivaluedMap<String, String> modify = new MultivaluedHashMap<>();
modify.add("ScheduledActionName", "nightly");
modify.add("Enable", "maybe");
assertEquals("InvalidParameterValue", assertThrows(AwsException.class,
() -> handler.handle("ModifyScheduledAction", modify)).getErrorCode());
MultivaluedMap<String, String> describe = new MultivaluedHashMap<>();
describe.add("Active", "maybe");
assertEquals("InvalidParameterValue", assertThrows(AwsException.class,
() -> handler.handle("DescribeScheduledActions", describe)).getErrorCode());
describe.remove("Active");
assertTrue(body(handler.handle("DescribeScheduledActions", describe)).contains("<State>ACTIVE</State>"));
}
@Test
void deleteRemovesTheActionAndAMissingOneIsNotFound() {
handler.handle("CreateScheduledAction", createParams("nightly"));
MultivaluedMap<String, String> delete = new MultivaluedHashMap<>();
delete.add("ScheduledActionName", "nightly");
assertEquals(200, handler.handle("DeleteScheduledAction", delete).getStatus());
AwsException failure = assertThrows(AwsException.class,
() -> handler.handle("DeleteScheduledAction", delete));
assertEquals("ScheduledActionNotFound", failure.getErrorCode());
}
@Test
void resizeAndAmbiguousTargetsAreRefused() {
MultivaluedMap<String, String> resize = createParams("resize");
resize.remove("TargetAction.PauseCluster.ClusterIdentifier");
resize.add("TargetAction.ResizeCluster.ClusterIdentifier", "analytics");
assertEquals("ScheduledActionTypeUnsupported", assertThrows(AwsException.class,
() -> handler.handle("CreateScheduledAction", resize)).getErrorCode());
MultivaluedMap<String, String> both = createParams("both");
both.add("TargetAction.ResumeCluster.ClusterIdentifier", "analytics");
assertEquals("InvalidScheduledAction", assertThrows(AwsException.class,
() -> handler.handle("CreateScheduledAction", both)).getErrorCode());
}
}
@@ -0,0 +1,73 @@
package io.floci.aws.services.redshift;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.redshift.model.ScheduledAction;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class RedshiftScheduledActionScheduleTest {
private static ScheduledAction action(String schedule) {
ScheduledAction action = new ScheduledAction();
action.setSchedule(schedule);
return action;
}
@Test
void atScheduleFiresOnceAtItsUtcTimestamp() {
ScheduledAction action = action("at(2026-11-20T10:00:00)");
assertEquals(Optional.of(Instant.parse("2026-11-20T10:00:00Z")),
RedshiftScheduledActionSchedule.next(action, Instant.parse("2026-11-19T00:00:00Z")));
assertTrue(RedshiftScheduledActionSchedule.next(action, Instant.parse("2026-11-20T10:00:00Z")).isEmpty());
}
@Test
void cronScheduleListsTheNextInvocationsInUtc() {
ScheduledAction action = action("cron(0 18 * * ? *)");
assertEquals(List.of(Instant.parse("2026-11-20T18:00:00Z"), Instant.parse("2026-11-21T18:00:00Z")),
RedshiftScheduledActionSchedule.upcoming(action, Instant.parse("2026-11-20T09:00:00Z"), 2));
}
@Test
void windowAndDisabledStateLimitInvocations() {
ScheduledAction action = action("cron(0 18 * * ? *)");
action.setStartTime(Instant.parse("2026-11-22T00:00:00Z"));
action.setEndTime(Instant.parse("2026-11-23T20:00:00Z"));
assertEquals(List.of(Instant.parse("2026-11-22T18:00:00Z"), Instant.parse("2026-11-23T18:00:00Z")),
RedshiftScheduledActionSchedule.upcoming(action, Instant.parse("2026-11-20T09:00:00Z"), 5));
action.setEnabled(false);
assertTrue(RedshiftScheduledActionSchedule.upcoming(action, Instant.parse("2026-11-20T09:00:00Z"), 5).isEmpty());
}
@Test
void latestDueCoalescesMissedInvocations() {
ScheduledAction action = action("cron(0 18 * * ? *)");
assertEquals(Optional.of(Instant.parse("2026-11-22T18:00:00Z")),
RedshiftScheduledActionSchedule.latestDue(action,
Instant.parse("2026-11-20T00:00:00Z"), Instant.parse("2026-11-22T19:00:00Z")));
assertTrue(RedshiftScheduledActionSchedule.latestDue(action,
Instant.parse("2026-11-22T18:00:00Z"), Instant.parse("2026-11-22T19:00:00Z")).isEmpty());
}
@Test
void malformedSchedulesAreRejectedAsInvalidSchedule() {
for (String schedule : List.of("rate(1 hour)", "at(tomorrow)", "cron(0 18 * * *)",
"cron(0 18 * * * *)", "cron(0/30 * * * ? *)", "at(2026-11-20T10:00:00", "")) {
AwsException failure = assertThrows(AwsException.class,
() -> RedshiftScheduledActionSchedule.validate(schedule), schedule);
assertEquals("InvalidSchedule", failure.getErrorCode(), schedule);
}
}
}
@@ -0,0 +1,303 @@
package io.floci.aws.services.redshift;
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.AccountAwareStorageBackend;
import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.redshift.model.ScheduledAction;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.List;
import java.util.Optional;
import java.util.function.BiConsumer;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class RedshiftScheduledActionServiceTest {
private static final String ACCOUNT_ID = "123456789012";
private static final String REGION = "us-east-1";
private static final String ROLE_ARN = "arn:aws:iam::" + ACCOUNT_ID + ":role/scheduler";
private static final Instant BASE_TIME = Instant.parse("2026-11-20T12:15:00Z");
private AccountAwareStorageBackend<ScheduledAction> store;
private RedshiftService redshift;
private RedshiftScheduledActionAuthorizer authorizer;
private RedshiftScheduledActionService service;
@BeforeEach
@SuppressWarnings({"unchecked", "rawtypes"})
void setUp() {
store = spy(new AccountAwareStorageBackend<>(new InMemoryStorage<String, ScheduledAction>(), null, ACCOUNT_ID));
StorageFactory storageFactory = mock(StorageFactory.class);
when(storageFactory.create(eq("redshift"), eq("redshift-scheduled-actions.json"),
any(TypeReference.class))).thenReturn((AccountAwareStorageBackend) store);
redshift = mock(RedshiftService.class);
when(redshift.clusterExists(anyString(), anyString())).thenReturn(true);
authorizer = mock(RedshiftScheduledActionAuthorizer.class);
when(authorizer.refusal(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(Optional.empty());
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn(ACCOUNT_ID);
when(regionResolver.getDefaultRegion()).thenReturn(REGION);
when(regionResolver.getRegion()).thenReturn(REGION);
when(regionResolver.buildArn(eq("redshift"), anyString(), anyString(), anyString()))
.thenAnswer(call -> "arn:aws:redshift:" + call.getArgument(1) + ":" + call.getArgument(2)
+ ":" + call.getArgument(3));
service = new RedshiftScheduledActionService(storageFactory, redshift, authorizer, regionResolver,
Clock.fixed(BASE_TIME, ZoneOffset.UTC));
}
private static ScheduledAction request(String name, String type, String schedule) {
ScheduledAction request = new ScheduledAction();
request.setScheduledActionName(name);
request.setIamRole(ROLE_ARN);
request.setSchedule(schedule);
request.setTargetActionType(type);
request.setClusterIdentifier("analytics");
return request;
}
@Test
void createStoresTheActionEnabledAndRejectsADuplicateName() {
ScheduledAction created = service.createScheduledAction(
request("nightly-pause", ScheduledAction.PAUSE_CLUSTER, "cron(0 22 * * ? *)"));
assertTrue(created.isEnabled());
assertEquals(BASE_TIME, created.getActivatedAt());
AwsException duplicate = assertThrows(AwsException.class, () -> service.createScheduledAction(
request("nightly-pause", ScheduledAction.PAUSE_CLUSTER, "cron(0 22 * * ? *)")));
assertEquals("ScheduledActionAlreadyExists", duplicate.getErrorCode());
}
@Test
void createRefusesAnUnknownClusterAnUnsupportedTargetAndAnInvertedWindow() {
doThrow(new AwsException("ClusterNotFound", "Cluster analytics not found", 404))
.when(redshift).describeClusters("analytics");
assertEquals("ClusterNotFound", assertThrows(AwsException.class, () -> service.createScheduledAction(
request("a", ScheduledAction.PAUSE_CLUSTER, "cron(0 22 * * ? *)"))).getErrorCode());
assertEquals("InvalidScheduledAction", assertThrows(AwsException.class, () -> service.createScheduledAction(
request("b", "ResizeCluster", "cron(0 22 * * ? *)"))).getErrorCode());
ScheduledAction inverted = request("c", ScheduledAction.PAUSE_CLUSTER, "cron(0 22 * * ? *)");
inverted.setStartTime(Instant.parse("2026-12-01T00:00:00Z"));
inverted.setEndTime(Instant.parse("2026-11-01T00:00:00Z"));
assertEquals("InvalidSchedule",
assertThrows(AwsException.class, () -> service.createScheduledAction(inverted)).getErrorCode());
}
@Test
void describeFiltersAndPagesByName() {
service.createScheduledAction(request("b-resume", ScheduledAction.RESUME_CLUSTER, "cron(0 6 * * ? *)"));
service.createScheduledAction(request("a-pause", ScheduledAction.PAUSE_CLUSTER, "cron(0 22 * * ? *)"));
PaginatedResult<ScheduledAction> all = service.describeScheduledActions(
null, null, null, null, null, List.of(), List.of(), null, null);
assertEquals(List.of("a-pause", "b-resume"),
all.items().stream().map(ScheduledAction::getScheduledActionName).toList());
PaginatedResult<ScheduledAction> pauses = service.describeScheduledActions(
null, ScheduledAction.PAUSE_CLUSTER, null, null, null, List.of(), List.of(), null, null);
assertEquals(1, pauses.items().size());
PaginatedResult<ScheduledAction> otherCluster = service.describeScheduledActions(
null, null, null, null, false, List.of("other"), List.of(), null, null);
assertTrue(otherCluster.items().isEmpty());
ScheduledAction disable = new ScheduledAction();
disable.setScheduledActionName("b-resume");
service.modifyScheduledAction(disable, false);
assertEquals(List.of("b-resume"), service.describeScheduledActions(
null, null, null, null, false, List.of(), List.of(), null, null).items().stream()
.map(ScheduledAction::getScheduledActionName).toList());
assertEquals(List.of("a-pause"), service.describeScheduledActions(
null, null, null, null, true, List.of(), List.of(), null, null).items().stream()
.map(ScheduledAction::getScheduledActionName).toList());
assertEquals("InvalidParameterValue", assertThrows(AwsException.class, () -> service.describeScheduledActions(
null, null, null, null, null, List.of(), List.of(), 5, null)).getErrorCode());
}
@Test
void modifyReplacesOnlyTheGivenMembersAndRestartsTheCountOnANewSchedule() {
service.createScheduledAction(request("pause", ScheduledAction.PAUSE_CLUSTER, "cron(0 22 * * ? *)"));
ScheduledAction changes = new ScheduledAction();
changes.setScheduledActionName("pause");
changes.setSchedule("cron(0 23 * * ? *)");
ScheduledAction modified = service.modifyScheduledAction(changes, false);
assertEquals("cron(0 23 * * ? *)", modified.getSchedule());
assertEquals(ROLE_ARN, modified.getIamRole());
assertEquals(ScheduledAction.PAUSE_CLUSTER, modified.getTargetActionType());
assertTrue(!modified.isEnabled());
assertEquals(BASE_TIME, modified.getActivatedAt());
}
@Test
void deletingAMissingActionIsNotFound() {
assertEquals("ScheduledActionNotFound", assertThrows(AwsException.class,
() -> service.deleteScheduledAction("missing")).getErrorCode());
}
@Test
void describePagesWithMarkerAndFiltersByInvocationWindow() {
for (int i = 0; i < 21; i++) {
service.createScheduledAction(request(String.format("a%02d", i), ScheduledAction.PAUSE_CLUSTER,
"cron(0 22 * * ? *)"));
}
PaginatedResult<ScheduledAction> first = service.describeScheduledActions(
null, null, null, null, null, List.of(), List.of(), 20, null);
assertEquals(20, first.items().size());
assertNotNull(first.nextToken());
PaginatedResult<ScheduledAction> second = service.describeScheduledActions(
null, null, null, null, null, List.of(), List.of(), 20, first.nextToken());
assertEquals(List.of("a20"), second.items().stream().map(ScheduledAction::getScheduledActionName).toList());
Instant farFuture = Instant.parse("2027-01-01T00:00:00Z");
assertEquals(21, service.describeScheduledActions(
null, null, farFuture, null, null, List.of(), List.of(), 100, null).items().size());
assertTrue(service.describeScheduledActions(
null, null, null, BASE_TIME.plusSeconds(60), null, List.of(), List.of(), 100, null).items().isEmpty());
}
@Test
void sweepRunsOnlyTheLatestDueInvocationOnceAndRecordsIt() {
service.createScheduledAction(request("pause", ScheduledAction.PAUSE_CLUSTER, "cron(0 * * * ? *)"));
Instant tick = BASE_TIME.plusSeconds(3 * 3600);
service.runScheduledActions(tick);
service.runScheduledActions(tick.plusSeconds(60));
verify(redshift, times(1)).pauseCluster("analytics");
ScheduledAction stored = store.get("pause").orElseThrow();
assertEquals(Instant.parse("2026-11-20T15:00:00Z"), stored.getLastCompletedInvocation());
assertNull(stored.getLastFailure());
}
@Test
void sweepResumesAtAOneOffTimeAndNeverRepeatsIt() {
service.createScheduledAction(request("resume", ScheduledAction.RESUME_CLUSTER, "at(2026-11-20T13:00:00)"));
service.runScheduledActions(Instant.parse("2026-11-20T12:30:00Z"));
verify(redshift, never()).resumeCluster(anyString());
service.runScheduledActions(Instant.parse("2026-11-20T13:05:00Z"));
service.runScheduledActions(Instant.parse("2026-11-20T14:05:00Z"));
verify(redshift, times(1)).resumeCluster("analytics");
}
@Test
void disabledActionAndRefusedRoleDoNotRunAndAFailureIsRecorded() {
service.createScheduledAction(request("pause", ScheduledAction.PAUSE_CLUSTER, "cron(0 * * * ? *)"));
ScheduledAction changes = new ScheduledAction();
changes.setScheduledActionName("pause");
service.modifyScheduledAction(changes, false);
service.runScheduledActions(BASE_TIME.plusSeconds(7200));
verify(redshift, never()).pauseCluster(anyString());
service.modifyScheduledAction(changes, true);
when(authorizer.refusal(eq(ROLE_ARN), eq(ACCOUNT_ID), anyString(), eq("PauseCluster"), anyString()))
.thenReturn(Optional.of("the role does not trust the scheduler"));
service.runScheduledActions(BASE_TIME.plusSeconds(4 * 3600));
verify(redshift, never()).pauseCluster(anyString());
ScheduledAction stored = store.get("pause").orElseThrow();
assertNotNull(stored.getLastFailure());
assertNull(stored.getLastCompletedInvocation());
}
@Test
void failedInvocationIsRecordedAndNotRetriedAndReEnablingDoesNotReplay() {
service.createScheduledAction(request("pause", ScheduledAction.PAUSE_CLUSTER, "cron(0 * * * ? *)"));
doThrow(new AwsException("InvalidClusterState", "not available", 400)).when(redshift).pauseCluster("analytics");
Instant tick = BASE_TIME.plusSeconds(3 * 3600);
service.runScheduledActions(tick);
service.runScheduledActions(tick.plusSeconds(60));
verify(redshift, times(1)).pauseCluster("analytics");
assertEquals("not available", store.get("pause").orElseThrow().getLastFailure());
ScheduledAction changes = new ScheduledAction();
changes.setScheduledActionName("pause");
service.modifyScheduledAction(changes, false);
service.modifyScheduledAction(changes, true);
service.runScheduledActions(tick.plusSeconds(120));
verify(redshift, times(1)).pauseCluster("analytics");
}
@Test
void sweepAuthorizesAgainstTheArnOfTheRegionTheClusterLivesIn() {
when(redshift.clusterRegion(ACCOUNT_ID, "analytics")).thenReturn(Optional.of("eu-west-1"));
service.createScheduledAction(request("pause", ScheduledAction.PAUSE_CLUSTER, "cron(0 * * * ? *)"));
service.runScheduledActions(BASE_TIME.plusSeconds(3 * 3600));
verify(authorizer).refusal(ROLE_ARN, ACCOUNT_ID, "eu-west-1", ScheduledAction.PAUSE_CLUSTER, "analytics");
verify(redshift).pauseCluster("analytics");
}
@Test
void aFailedOutcomeWriteIsNotSwallowedAndDoesNotAdvanceTheCheckpoint() {
service.createScheduledAction(request("pause", ScheduledAction.PAUSE_CLUSTER, "cron(0 * * * ? *)"));
doThrow(new IllegalStateException("disk full")).when(store).putAllAtomicallyForAccount(anyString(), any());
Instant tick = BASE_TIME.plusSeconds(3 * 3600);
service.runScheduledActions(tick);
assertNull(store.get("pause").orElseThrow().getLastClaimedInvocation());
}
@Test
void modifyDropsTheActionWhenTheClusterIsDeletedBetweenValidationAndWrite() {
service.createScheduledAction(request("pause", ScheduledAction.PAUSE_CLUSTER, "cron(0 * * * ? *)"));
when(redshift.clusterExists(ACCOUNT_ID, "analytics")).thenReturn(true, false);
ScheduledAction changes = new ScheduledAction();
changes.setScheduledActionName("pause");
changes.setDescription("changed");
AwsException failure = assertThrows(AwsException.class, () -> service.modifyScheduledAction(changes, null));
assertEquals("ClusterNotFound", failure.getErrorCode());
assertTrue(store.get("pause").isEmpty());
}
@Test
void removingTheClusterDeletesItsActionsAndASweepDropsAnOrphan() {
service.registerClusterRemoval();
ArgumentCaptor<BiConsumer<String, String>> listener = ArgumentCaptor.forClass(BiConsumer.class);
verify(redshift).onClusterRemoved(listener.capture());
service.createScheduledAction(request("pause", ScheduledAction.PAUSE_CLUSTER, "cron(0 * * * ? *)"));
listener.getValue().accept(ACCOUNT_ID, "analytics");
assertTrue(store.get("pause").isEmpty());
service.createScheduledAction(request("again", ScheduledAction.PAUSE_CLUSTER, "cron(0 * * * ? *)"));
when(redshift.clusterExists(ACCOUNT_ID, "analytics")).thenReturn(false);
service.runScheduledActions(BASE_TIME.plusSeconds(7200));
assertTrue(store.get("again").isEmpty());
verify(redshift, never()).pauseCluster(anyString());
}
}
+2
View File
@@ -218,6 +218,8 @@ floci:
snapshot-sweep-interval-seconds: 60
snapshot-copy-enabled: false
snapshot-copy-sweep-interval-seconds: 60
scheduled-actions-enabled: false
scheduled-action-sweep-interval-seconds: 60
default-port: 5439
image-version: postgres:15-alpine
poll-interval-ms: 1000