From d08c241d98696fb6c715530a8993dcca003c0a2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C5=A9=20Th=E1=BA=BF=20Huy?= <31652864+vuthehuyht@users.noreply.github.com> Date: Sun, 15 Nov 2026 00:28:06 +0700 Subject: [PATCH] feat(redshift): scheduled actions that pause and resume provisioned clusters (#8260) --- .../java/com/floci/test/TestFixtures.java | 8 + .../test/RedshiftScheduledActionTest.java | 124 ++++++ docs/services/index.md | 2 +- docs/services/redshift.md | 10 + .../io/floci/aws/config/EmulatorConfig.java | 10 + .../aws/core/common/AwsCronSchedule.java | 92 +++++ .../redshift/RedshiftQueryHandler.java | 148 ++++++- .../RedshiftScheduledActionAuthorizer.java | 56 +++ .../RedshiftScheduledActionSchedule.java | 112 +++++ .../RedshiftScheduledActionScheduler.java | 23 ++ .../RedshiftScheduledActionService.java | 382 ++++++++++++++++++ .../services/redshift/RedshiftService.java | 36 ++ .../redshift/RedshiftSnapshotSchedule.java | 15 +- .../redshift/model/ScheduledAction.java | 93 +++++ .../RedshiftServerlessSchedule.java | 60 +-- src/main/resources/application.yml | 2 + .../aws/core/common/AwsCronScheduleTest.java | 62 +++ ...RedshiftScheduledActionAuthorizerTest.java | 69 ++++ .../RedshiftScheduledActionQueryTest.java | 175 ++++++++ .../RedshiftScheduledActionScheduleTest.java | 73 ++++ .../RedshiftScheduledActionServiceTest.java | 303 ++++++++++++++ src/test/resources/application.yml | 2 + 22 files changed, 1791 insertions(+), 66 deletions(-) create mode 100644 compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftScheduledActionTest.java create mode 100644 src/main/java/io/floci/aws/core/common/AwsCronSchedule.java create mode 100644 src/main/java/io/floci/aws/services/redshift/RedshiftScheduledActionAuthorizer.java create mode 100644 src/main/java/io/floci/aws/services/redshift/RedshiftScheduledActionSchedule.java create mode 100644 src/main/java/io/floci/aws/services/redshift/RedshiftScheduledActionScheduler.java create mode 100644 src/main/java/io/floci/aws/services/redshift/RedshiftScheduledActionService.java create mode 100644 src/main/java/io/floci/aws/services/redshift/model/ScheduledAction.java create mode 100644 src/test/java/io/floci/aws/core/common/AwsCronScheduleTest.java create mode 100644 src/test/java/io/floci/aws/services/redshift/RedshiftScheduledActionAuthorizerTest.java create mode 100644 src/test/java/io/floci/aws/services/redshift/RedshiftScheduledActionQueryTest.java create mode 100644 src/test/java/io/floci/aws/services/redshift/RedshiftScheduledActionScheduleTest.java create mode 100644 src/test/java/io/floci/aws/services/redshift/RedshiftScheduledActionServiceTest.java diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java index c08e8785e5..14bd417d93 100644 --- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java +++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java @@ -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) diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftScheduledActionTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftScheduledActionTest.java new file mode 100644 index 0000000000..1125091059 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftScheduledActionTest.java @@ -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 disabled = owner.describeScheduledActions(r -> r.active(false) + .filters(f -> f.name("cluster-identifier").values(CLUSTER))).scheduledActions(); + assertThat(disabled).extracting(ScheduledAction::scheduledActionName).containsExactly(RESUME); + List 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")); + } +} diff --git a/docs/services/index.md b/docs/services/index.md index ad2be9b111..f4b718b5d8 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -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 | diff --git a/docs/services/redshift.md b/docs/services/redshift.md index 774d8b4474..7ad5e5b770 100644 --- a/docs/services/redshift.md +++ b/docs/services/redshift.md @@ -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 | diff --git a/src/main/java/io/floci/aws/config/EmulatorConfig.java b/src/main/java/io/floci/aws/config/EmulatorConfig.java index 114ff0dc07..a5f6c4034a 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -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") diff --git a/src/main/java/io/floci/aws/core/common/AwsCronSchedule.java b/src/main/java/io/floci/aws/core/common/AwsCronSchedule.java new file mode 100644 index 0000000000..73d1af7d3b --- /dev/null +++ b/src/main/java/io/floci/aws/core/common/AwsCronSchedule.java @@ -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 ExecutionTime parse(String[] fields, Function 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 void requireHourlySpacing(ExecutionTime cron, + Function invalid) { + Optional 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 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 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 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)); + } +} diff --git a/src/main/java/io/floci/aws/services/redshift/RedshiftQueryHandler.java b/src/main/java/io/floci/aws/services/redshift/RedshiftQueryHandler.java index 2688336b51..ae989f8811 100644 --- a/src/main/java/io/floci/aws/services/redshift/RedshiftQueryHandler.java +++ b/src/main/java/io/floci/aws/services/redshift/RedshiftQueryHandler.java @@ -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 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 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 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 params) { + List clusterIdentifiers = new ArrayList<>(); + List iamRoles = new ArrayList<>(); + for (AwsQueryLists.IndexedMember filter : AwsQueryLists.members(params, "Filters", "ScheduledActionFilter")) { + String name = params.getFirst(filter.prefix() + ".Name"); + List 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 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") diff --git a/src/main/java/io/floci/aws/services/redshift/RedshiftScheduledActionAuthorizer.java b/src/main/java/io/floci/aws/services/redshift/RedshiftScheduledActionAuthorizer.java new file mode 100644 index 0000000000..1cb48b86d7 --- /dev/null +++ b/src/main/java/io/floci/aws/services/redshift/RedshiftScheduledActionAuthorizer.java @@ -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 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 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); + } +} diff --git a/src/main/java/io/floci/aws/services/redshift/RedshiftScheduledActionSchedule.java b/src/main/java/io/floci/aws/services/redshift/RedshiftScheduledActionSchedule.java new file mode 100644 index 0000000000..16e2d0d0f7 --- /dev/null +++ b/src/main/java/io/floci/aws/services/redshift/RedshiftScheduledActionSchedule.java @@ -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 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 upcoming(ScheduledAction action, Instant after, int count) { + List invocations = new ArrayList<>(); + Instant cursor = after; + while (invocations.size() < count) { + Optional 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 latestDue(ScheduledAction action, Instant anchor, Instant now) { + if (!action.isEnabled()) { + return Optional.empty(); + } + Instant upper = AwsCronSchedule.searchUpTo(now, action.getEndTime()); + Optional 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); + } +} diff --git a/src/main/java/io/floci/aws/services/redshift/RedshiftScheduledActionScheduler.java b/src/main/java/io/floci/aws/services/redshift/RedshiftScheduledActionScheduler.java new file mode 100644 index 0000000000..92de3c083c --- /dev/null +++ b/src/main/java/io/floci/aws/services/redshift/RedshiftScheduledActionScheduler.java @@ -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); + } +} diff --git a/src/main/java/io/floci/aws/services/redshift/RedshiftScheduledActionService.java b/src/main/java/io/floci/aws/services/redshift/RedshiftScheduledActionService.java new file mode 100644 index 0000000000..8a796bd719 --- /dev/null +++ b/src/main/java/io/floci/aws/services/redshift/RedshiftScheduledActionService.java @@ -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. + * + *

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. + * + *

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. + * + *

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 actions; + private final RedshiftService redshift; + private final RedshiftScheduledActionAuthorizer authorizer; + private final RegionResolver regionResolver; + private final Clock clock; + private final ConcurrentHashMap 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>() {}); + 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 describeScheduledActions( + String name, String targetActionType, Instant startTime, Instant endTime, Boolean active, + List clusterIdentifiers, List 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 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 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 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 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 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 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 mutate(String name, Supplier 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 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()); + } +} diff --git a/src/main/java/io/floci/aws/services/redshift/RedshiftService.java b/src/main/java/io/floci/aws/services/redshift/RedshiftService.java index 74f2963366..2273978049 100644 --- a/src/main/java/io/floci/aws/services/redshift/RedshiftService.java +++ b/src/main/java/io/floci/aws/services/redshift/RedshiftService.java @@ -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 usedPorts = ConcurrentHashMap.newKeySet(); private final ConcurrentHashMap resourceLocks = new ConcurrentHashMap<>(); private final ConcurrentHashMap managedRotationReservations = new ConcurrentHashMap<>(); + private final List> 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 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 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 listener : clusterRemovalListeners) { + try { + listener.accept(clusters.accountId(), identifier); + } catch (RuntimeException e) { + LOG.warnv(e, "Cluster removal listener failed for cluster {0}", identifier); + } + } + } + public List describeClusters(String identifier) { if (identifier != null) { Optional 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); diff --git a/src/main/java/io/floci/aws/services/redshift/RedshiftSnapshotSchedule.java b/src/main/java/io/floci/aws/services/redshift/RedshiftSnapshotSchedule.java index 468070c7ee..debcc68ef4 100644 --- a/src/main/java/io/floci/aws/services/redshift/RedshiftSnapshotSchedule.java +++ b/src/main/java/io/floci/aws/services/redshift/RedshiftSnapshotSchedule.java @@ -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 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); } } } diff --git a/src/main/java/io/floci/aws/services/redshift/model/ScheduledAction.java b/src/main/java/io/floci/aws/services/redshift/model/ScheduledAction.java new file mode 100644 index 0000000000..a5ca8e6cc8 --- /dev/null +++ b/src/main/java/io/floci/aws/services/redshift/model/ScheduledAction.java @@ -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; } +} diff --git a/src/main/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessSchedule.java b/src/main/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessSchedule.java index e6880922cf..f44408366a 100644 --- a/src/main/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessSchedule.java +++ b/src/main/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessSchedule.java @@ -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 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 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 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 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); } } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index daeabd0422..7b8b9dd4c6 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -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 diff --git a/src/test/java/io/floci/aws/core/common/AwsCronScheduleTest.java b/src/test/java/io/floci/aws/core/common/AwsCronScheduleTest.java new file mode 100644 index 0000000000..2de69ab6f5 --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/AwsCronScheduleTest.java @@ -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)); + } +} diff --git a/src/test/java/io/floci/aws/services/redshift/RedshiftScheduledActionAuthorizerTest.java b/src/test/java/io/floci/aws/services/redshift/RedshiftScheduledActionAuthorizerTest.java new file mode 100644 index 0000000000..38fe06d349 --- /dev/null +++ b/src/test/java/io/floci/aws/services/redshift/RedshiftScheduledActionAuthorizerTest.java @@ -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 refusal = authorizer.refusal(ROLE, "123456789012", "eu-west-1", "PauseCluster", "analytics"); + + assertEquals(Optional.of("denied"), refusal); + ArgumentCaptor> 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> 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 refusal = authorizer.refusal(ROLE, "123456789012", "eu-west-1", "NoSuchOperation", "analytics"); + + assertTrue(refusal.isPresent()); + } +} diff --git a/src/test/java/io/floci/aws/services/redshift/RedshiftScheduledActionQueryTest.java b/src/test/java/io/floci/aws/services/redshift/RedshiftScheduledActionQueryTest.java new file mode 100644 index 0000000000..78ee13f284 --- /dev/null +++ b/src/test/java/io/floci/aws/services/redshift/RedshiftScheduledActionQueryTest.java @@ -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 store = + new AccountAwareStorageBackend<>(new InMemoryStorage(), 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 createParams(String name) { + MultivaluedMap 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("nightly"), xml); + assertTrue(xml.contains("analytics" + + ""), xml); + assertTrue(xml.contains("ACTIVE"), xml); + assertTrue(xml.contains("2026-11-20T22:00:00Z"), xml); + assertTrue(xml.contains("pause at night"), xml); + } + + @Test + void describeListsTheActionsFilteredByClusterAndModifyDisablesOne() { + handler.handle("CreateScheduledAction", createParams("nightly")); + MultivaluedMap modify = new MultivaluedHashMap<>(); + modify.add("ScheduledActionName", "nightly"); + modify.add("Enable", "false"); + + assertTrue(body(handler.handle("ModifyScheduledAction", modify)).contains("DISABLED")); + + MultivaluedMap 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("nightly"), xml); + + describe.putSingle("Filters.ScheduledActionFilter.1.Values.item.1", "other"); + assertTrue(body(handler.handle("DescribeScheduledActions", describe)) + .contains("")); + } + + @Test + void activeFlagKeepsEnabledOrDisabledActionsAndAbsentMeansAll() { + handler.handle("CreateScheduledAction", createParams("on")); + handler.handle("CreateScheduledAction", createParams("off")); + MultivaluedMap disable = new MultivaluedHashMap<>(); + disable.add("ScheduledActionName", "off"); + disable.add("Enable", "false"); + handler.handle("ModifyScheduledAction", disable); + + MultivaluedMap describe = new MultivaluedHashMap<>(); + String all = body(handler.handle("DescribeScheduledActions", describe)); + assertTrue(all.contains("on<") && all.contains("off<"), all); + + describe.putSingle("Active", "false"); + String disabled = body(handler.handle("DescribeScheduledActions", describe)); + assertTrue(disabled.contains("off<") && !disabled.contains("on<"), + disabled); + + describe.putSingle("Active", "true"); + String enabled = body(handler.handle("DescribeScheduledActions", describe)); + assertTrue(enabled.contains("on<") && !enabled.contains("off<"), + enabled); + } + + @Test + void aNonBooleanEnableOrActiveIsRefusedAndNeverChangesState() { + MultivaluedMap create = createParams("typo"); + create.add("Enable", "maybe"); + assertEquals("InvalidParameterValue", assertThrows(AwsException.class, + () -> handler.handle("CreateScheduledAction", create)).getErrorCode()); + + handler.handle("CreateScheduledAction", createParams("nightly")); + MultivaluedMap modify = new MultivaluedHashMap<>(); + modify.add("ScheduledActionName", "nightly"); + modify.add("Enable", "maybe"); + assertEquals("InvalidParameterValue", assertThrows(AwsException.class, + () -> handler.handle("ModifyScheduledAction", modify)).getErrorCode()); + + MultivaluedMap 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("ACTIVE")); + } + + @Test + void deleteRemovesTheActionAndAMissingOneIsNotFound() { + handler.handle("CreateScheduledAction", createParams("nightly")); + MultivaluedMap 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 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 both = createParams("both"); + both.add("TargetAction.ResumeCluster.ClusterIdentifier", "analytics"); + assertEquals("InvalidScheduledAction", assertThrows(AwsException.class, + () -> handler.handle("CreateScheduledAction", both)).getErrorCode()); + } +} diff --git a/src/test/java/io/floci/aws/services/redshift/RedshiftScheduledActionScheduleTest.java b/src/test/java/io/floci/aws/services/redshift/RedshiftScheduledActionScheduleTest.java new file mode 100644 index 0000000000..d5610e42bd --- /dev/null +++ b/src/test/java/io/floci/aws/services/redshift/RedshiftScheduledActionScheduleTest.java @@ -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); + } + } +} diff --git a/src/test/java/io/floci/aws/services/redshift/RedshiftScheduledActionServiceTest.java b/src/test/java/io/floci/aws/services/redshift/RedshiftScheduledActionServiceTest.java new file mode 100644 index 0000000000..8ff7281b90 --- /dev/null +++ b/src/test/java/io/floci/aws/services/redshift/RedshiftScheduledActionServiceTest.java @@ -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 store; + private RedshiftService redshift; + private RedshiftScheduledActionAuthorizer authorizer; + private RedshiftScheduledActionService service; + + @BeforeEach + @SuppressWarnings({"unchecked", "rawtypes"}) + void setUp() { + store = spy(new AccountAwareStorageBackend<>(new InMemoryStorage(), 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 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 pauses = service.describeScheduledActions( + null, ScheduledAction.PAUSE_CLUSTER, null, null, null, List.of(), List.of(), null, null); + assertEquals(1, pauses.items().size()); + + PaginatedResult 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 first = service.describeScheduledActions( + null, null, null, null, null, List.of(), List.of(), 20, null); + assertEquals(20, first.items().size()); + assertNotNull(first.nextToken()); + PaginatedResult 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> 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()); + } +} diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index 468b4c0924..db6b11eabd 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -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