mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(redshift): scheduled actions that pause and resume provisioned clusters (#8260)
This commit is contained in:
1 parent
0b19c15e71
commit
d08c241d98
22 files changed
+1791
-66
No files matched your search
@@ -1833,6 +1833,16 @@ public interface EmulatorConfig {
|
||||
|
||||
@WithDefault("60")
|
||||
long snapshotCopySweepIntervalSeconds();
|
||||
|
||||
/**
|
||||
* Run the scheduled actions of provisioned clusters, which pause or resume a cluster on a schedule.
|
||||
* Env: FLOCI_SERVICES_REDSHIFT_SCHEDULED_ACTIONS_ENABLED
|
||||
*/
|
||||
@WithDefault("true")
|
||||
boolean scheduledActionsEnabled();
|
||||
|
||||
@WithDefault("60")
|
||||
long scheduledActionSweepIntervalSeconds();
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
@WithDefault("5439")
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
package io.floci.aws.core.common;
|
||||
|
||||
import com.cronutils.model.Cron;
|
||||
import com.cronutils.model.time.ExecutionTime;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* The UTC rules the scheduled actions and snapshot schedules of Redshift and Redshift Serverless share for a
|
||||
* six-field AWS {@code cron}: how the fields are read, that two invocations are at least an hour apart, which
|
||||
* invocation comes next or is the latest due, and how an active window narrows them. The error each service
|
||||
* raises for a bad expression differs, so the callers pass the exception to throw.
|
||||
*/
|
||||
public final class AwsCronSchedule {
|
||||
|
||||
private static final Duration MINIMUM_INTERVAL = Duration.ofHours(1);
|
||||
private static final Duration SPACING_HORIZON = Duration.ofDays(400);
|
||||
private static final int MAX_SPACING_CHECKS = 1000;
|
||||
|
||||
private AwsCronSchedule() {
|
||||
}
|
||||
|
||||
/** Reads the six fields of an AWS cron, which put {@code ?} in exactly one of day-of-month and day-of-week. */
|
||||
public static <E extends RuntimeException> ExecutionTime parse(String[] fields, Function<String, E> invalid) {
|
||||
if (fields.length != 6) {
|
||||
throw invalid.apply("The cron schedule needs six fields.");
|
||||
}
|
||||
if ("?".equals(fields[2]) == "?".equals(fields[4])) {
|
||||
throw invalid.apply("Use ? in exactly one of day-of-month and day-of-week.");
|
||||
}
|
||||
try {
|
||||
Cron cron = AwsCronDefinitions.newParser().parse("0 " + String.join(" ", fields));
|
||||
cron.validate();
|
||||
return ExecutionTime.forCron(cron);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw invalid.apply("The cron schedule is invalid: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/** AWS requires the invocations of a cron schedule to be at least one hour apart. */
|
||||
public static <E extends RuntimeException> void requireHourlySpacing(ExecutionTime cron,
|
||||
Function<String, E> invalid) {
|
||||
Optional<Instant> first = next(cron, Instant.EPOCH);
|
||||
if (first.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Instant cursor = first.get().minusSeconds(1);
|
||||
Instant limit = cursor.plus(SPACING_HORIZON);
|
||||
Instant previous = null;
|
||||
for (int i = 0; i < MAX_SPACING_CHECKS; i++) {
|
||||
Optional<Instant> next = next(cron, cursor);
|
||||
if (next.isEmpty() || next.get().isAfter(limit)) {
|
||||
return;
|
||||
}
|
||||
if (previous != null && Duration.between(previous, next.get()).compareTo(MINIMUM_INTERVAL) < 0) {
|
||||
throw invalid.apply("The cron schedule must be at least one hour apart.");
|
||||
}
|
||||
previous = next.get();
|
||||
cursor = next.get();
|
||||
}
|
||||
}
|
||||
|
||||
/** The first invocation strictly after {@code after}. */
|
||||
public static Optional<Instant> next(ExecutionTime cron, Instant after) {
|
||||
return cron.nextExecution(after.atZone(ZoneOffset.UTC)).map(value -> value.toInstant());
|
||||
}
|
||||
|
||||
/** The latest invocation at or before {@code upper}. */
|
||||
public static Optional<Instant> latest(ExecutionTime cron, Instant upper) {
|
||||
return cron.lastExecution(upper.atZone(ZoneOffset.UTC).plusNanos(1)).map(value -> value.toInstant());
|
||||
}
|
||||
|
||||
/** Where to look for the next invocation after {@code after}, which a window that has not opened moves up. */
|
||||
public static Instant searchFrom(Instant after, Instant windowStart) {
|
||||
return windowStart != null && windowStart.isAfter(after) ? windowStart.minusNanos(1) : after;
|
||||
}
|
||||
|
||||
/** The last moment worth looking at up to {@code now}, which a window that has closed moves back. */
|
||||
public static Instant searchUpTo(Instant now, Instant windowEnd) {
|
||||
return windowEnd != null && windowEnd.isBefore(now) ? windowEnd : now;
|
||||
}
|
||||
|
||||
/** Whether {@code time} is inside the window, whose ends are inclusive and either of which may be open. */
|
||||
public static boolean inWindow(Instant time, Instant windowStart, Instant windowEnd) {
|
||||
return (windowStart == null || !time.isBefore(windowStart))
|
||||
&& (windowEnd == null || !time.isAfter(windowEnd));
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import io.floci.aws.services.redshift.model.EventSubscription;
|
||||
import io.floci.aws.services.redshift.model.Integration;
|
||||
import io.floci.aws.services.redshift.model.Parameter;
|
||||
import io.floci.aws.services.redshift.model.RedshiftEvent;
|
||||
import io.floci.aws.services.redshift.model.ScheduledAction;
|
||||
import io.floci.aws.services.redshift.model.Snapshot;
|
||||
import io.floci.aws.services.redshift.model.SnapshotCopyGrant;
|
||||
import io.floci.aws.services.redshift.model.SnapshotSchedule;
|
||||
@@ -64,6 +65,7 @@ public class RedshiftQueryHandler {
|
||||
private final RedshiftDynamoDbZeroEtlConsumer zeroEtlConsumer;
|
||||
private final IamEnforcementFilter iamEnforcementFilter;
|
||||
private final RedshiftResourcePolicies resourcePolicies;
|
||||
private final RedshiftScheduledActionService scheduledActions;
|
||||
|
||||
@Inject
|
||||
public RedshiftQueryHandler(RedshiftService service, RedshiftCredentialBroker credentialBroker,
|
||||
@@ -71,7 +73,8 @@ public class RedshiftQueryHandler {
|
||||
RegionResolver regionResolver,
|
||||
RedshiftDynamoDbZeroEtlConsumer zeroEtlConsumer,
|
||||
IamEnforcementFilter iamEnforcementFilter,
|
||||
RedshiftResourcePolicies resourcePolicies) {
|
||||
RedshiftResourcePolicies resourcePolicies,
|
||||
RedshiftScheduledActionService scheduledActions) {
|
||||
this.service = service;
|
||||
this.credentialBroker = credentialBroker;
|
||||
this.config = config;
|
||||
@@ -80,12 +83,13 @@ public class RedshiftQueryHandler {
|
||||
this.zeroEtlConsumer = zeroEtlConsumer;
|
||||
this.iamEnforcementFilter = iamEnforcementFilter;
|
||||
this.resourcePolicies = resourcePolicies;
|
||||
this.scheduledActions = scheduledActions;
|
||||
}
|
||||
|
||||
RedshiftQueryHandler(RedshiftService service, RedshiftCredentialBroker credentialBroker,
|
||||
EmulatorConfig config, RedshiftIamDbUserResolver iamDbUserResolver,
|
||||
RegionResolver regionResolver) {
|
||||
this(service, credentialBroker, config, iamDbUserResolver, regionResolver, null, null, null);
|
||||
this(service, credentialBroker, config, iamDbUserResolver, regionResolver, null, null, null, null);
|
||||
}
|
||||
|
||||
public Response handle(String action, MultivaluedMap<String, String> params) {
|
||||
@@ -854,6 +858,22 @@ public class RedshiftQueryHandler {
|
||||
intParam(params, "RetentionPeriod"), Boolean.parseBoolean(params.getFirst("Manual")));
|
||||
return clusterResponse(action, cluster);
|
||||
}
|
||||
case "CreateScheduledAction" -> {
|
||||
ScheduledAction request = scheduledActionRequest(params);
|
||||
return scheduledActionResponse(action, scheduledActions.createScheduledAction(request));
|
||||
}
|
||||
case "ModifyScheduledAction" -> {
|
||||
ScheduledAction changes = scheduledActionRequest(params);
|
||||
Boolean enable = booleanParam(params, "Enable");
|
||||
return scheduledActionResponse(action, scheduledActions.modifyScheduledAction(changes, enable));
|
||||
}
|
||||
case "DeleteScheduledAction" -> {
|
||||
scheduledActions.deleteScheduledAction(requireParam(params, "ScheduledActionName"));
|
||||
return emptyResponse(action);
|
||||
}
|
||||
case "DescribeScheduledActions" -> {
|
||||
return describeScheduledActionsResponse(params);
|
||||
}
|
||||
case "CreateSnapshotSchedule" -> {
|
||||
SnapshotSchedule schedule = service.createSnapshotSchedule(params.getFirst("ScheduleIdentifier"),
|
||||
params.getFirst("ScheduleDescription"), memberList(params, "ScheduleDefinitions"),
|
||||
@@ -1404,6 +1424,130 @@ public class RedshiftQueryHandler {
|
||||
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* The members a Create or ModifyScheduledAction request carries; a member left out stays null.
|
||||
* TargetAction is a union of which exactly one member may be set.
|
||||
*/
|
||||
private static ScheduledAction scheduledActionRequest(MultivaluedMap<String, String> params) {
|
||||
ScheduledAction request = new ScheduledAction();
|
||||
request.setScheduledActionName(requireParam(params, "ScheduledActionName"));
|
||||
request.setIamRole(params.getFirst("IamRole"));
|
||||
request.setSchedule(params.getFirst("Schedule"));
|
||||
request.setDescription(params.getFirst("ScheduledActionDescription"));
|
||||
request.setStartTime(timestampParam(params, "StartTime"));
|
||||
request.setEndTime(timestampParam(params, "EndTime"));
|
||||
Boolean enable = booleanParam(params, "Enable");
|
||||
if (enable != null) {
|
||||
request.setEnabled(enable);
|
||||
}
|
||||
List<String> targets = params.keySet().stream()
|
||||
.filter(key -> key.startsWith("TargetAction."))
|
||||
.map(key -> key.substring("TargetAction.".length()).split("\\.")[0])
|
||||
.distinct()
|
||||
.toList();
|
||||
if (targets.size() > 1) {
|
||||
throw new AwsException("InvalidScheduledAction", "TargetAction must set exactly one member.", 400);
|
||||
}
|
||||
if (!targets.isEmpty()) {
|
||||
String type = targets.get(0);
|
||||
if ("ResizeCluster".equals(type)) {
|
||||
throw new AwsException("ScheduledActionTypeUnsupported",
|
||||
"Scheduled ResizeCluster actions are not supported.", 400);
|
||||
}
|
||||
if (!ScheduledAction.PAUSE_CLUSTER.equals(type) && !ScheduledAction.RESUME_CLUSTER.equals(type)) {
|
||||
throw new AwsException("InvalidScheduledAction", "Unknown TargetAction member " + type + ".", 400);
|
||||
}
|
||||
request.setTargetActionType(type);
|
||||
request.setClusterIdentifier(requireParam(params, "TargetAction." + type + ".ClusterIdentifier"));
|
||||
}
|
||||
return request;
|
||||
}
|
||||
|
||||
private Response describeScheduledActionsResponse(MultivaluedMap<String, String> params) {
|
||||
List<String> clusterIdentifiers = new ArrayList<>();
|
||||
List<String> iamRoles = new ArrayList<>();
|
||||
for (AwsQueryLists.IndexedMember filter : AwsQueryLists.members(params, "Filters", "ScheduledActionFilter")) {
|
||||
String name = params.getFirst(filter.prefix() + ".Name");
|
||||
List<String> values = AwsQueryLists.values(params, filter.prefix() + ".Values", "item");
|
||||
if ("cluster-identifier".equals(name)) {
|
||||
clusterIdentifiers.addAll(values);
|
||||
} else if ("iam-role".equals(name)) {
|
||||
iamRoles.addAll(values);
|
||||
} else {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"Filter name must be cluster-identifier or iam-role.", 400);
|
||||
}
|
||||
}
|
||||
PaginatedResult<ScheduledAction> page = scheduledActions.describeScheduledActions(
|
||||
params.getFirst("ScheduledActionName"), params.getFirst("TargetActionType"),
|
||||
timestampParam(params, "StartTime"), timestampParam(params, "EndTime"),
|
||||
booleanParam(params, "Active"),
|
||||
clusterIdentifiers, iamRoles,
|
||||
intParam(params, "MaxRecords"), params.getFirst("Marker"));
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("DescribeScheduledActionsResponse")
|
||||
.start("DescribeScheduledActionsResult")
|
||||
.start("ScheduledActions");
|
||||
for (ScheduledAction scheduledAction : page.items()) {
|
||||
xml.start("ScheduledAction").raw(buildScheduledActionFields(scheduledAction)).end("ScheduledAction");
|
||||
}
|
||||
xml.end("ScheduledActions");
|
||||
if (page.nextToken() != null) {
|
||||
xml.elem("Marker", page.nextToken());
|
||||
}
|
||||
String body = xml
|
||||
.end("DescribeScheduledActionsResult")
|
||||
.start("ResponseMetadata")
|
||||
.elem("RequestId", "test-req-id")
|
||||
.end("ResponseMetadata")
|
||||
.end("DescribeScheduledActionsResponse")
|
||||
.build();
|
||||
return Response.ok(body).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
|
||||
// Create/ModifyScheduledAction return the ScheduledAction members directly inside the Result.
|
||||
private Response scheduledActionResponse(String operation, ScheduledAction scheduledAction) {
|
||||
String xml = new XmlBuilder()
|
||||
.start(operation + "Response")
|
||||
.start(operation + "Result")
|
||||
.raw(buildScheduledActionFields(scheduledAction))
|
||||
.end(operation + "Result")
|
||||
.start("ResponseMetadata")
|
||||
.elem("RequestId", "test-req-id")
|
||||
.end("ResponseMetadata")
|
||||
.end(operation + "Response")
|
||||
.build();
|
||||
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
|
||||
private String buildScheduledActionFields(ScheduledAction scheduledAction) {
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.elem("ScheduledActionName", scheduledAction.getScheduledActionName())
|
||||
.start("TargetAction")
|
||||
.start(scheduledAction.getTargetActionType())
|
||||
.elem("ClusterIdentifier", scheduledAction.getClusterIdentifier())
|
||||
.end(scheduledAction.getTargetActionType())
|
||||
.end("TargetAction")
|
||||
.elem("Schedule", scheduledAction.getSchedule())
|
||||
.elem("IamRole", scheduledAction.getIamRole());
|
||||
if (scheduledAction.getDescription() != null) {
|
||||
xml.elem("ScheduledActionDescription", scheduledAction.getDescription());
|
||||
}
|
||||
xml.elem("State", scheduledAction.isEnabled() ? "ACTIVE" : "DISABLED");
|
||||
xml.start("NextInvocations");
|
||||
for (Instant invocation : scheduledActions.upcomingInvocations(scheduledAction, 5)) {
|
||||
xml.elem("ScheduledActionTime", DateTimeFormatter.ISO_INSTANT.format(invocation));
|
||||
}
|
||||
xml.end("NextInvocations");
|
||||
if (scheduledAction.getStartTime() != null) {
|
||||
xml.elem("StartTime", DateTimeFormatter.ISO_INSTANT.format(scheduledAction.getStartTime()));
|
||||
}
|
||||
if (scheduledAction.getEndTime() != null) {
|
||||
xml.elem("EndTime", DateTimeFormatter.ISO_INSTANT.format(scheduledAction.getEndTime()));
|
||||
}
|
||||
return xml.build();
|
||||
}
|
||||
|
||||
private static Response emptyResponse(String operation) {
|
||||
String xml = new XmlBuilder()
|
||||
.start(operation + "Response")
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package io.floci.aws.services.redshift;
|
||||
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.RequestResources;
|
||||
import io.floci.aws.core.common.ServicePrincipals;
|
||||
import io.floci.aws.services.iam.IamAuthorizedActions;
|
||||
import io.floci.aws.services.iam.ServiceRoleAuthorizer;
|
||||
import io.floci.aws.services.iam.ServiceRoleAuthorizer.Permission;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Decides whether the IAM role of a scheduled action may pause or resume its cluster. The role has to
|
||||
* trust the Redshift scheduler principal, and its identity policies, boundary and SCPs have to allow
|
||||
* {@code redshift:PauseCluster} or {@code redshift:ResumeCluster} on the cluster. Only active with IAM
|
||||
* enforcement on, as for every other API call. The action and the cluster resource come from the same
|
||||
* generated tables a direct request to the operation is checked with.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class RedshiftScheduledActionAuthorizer {
|
||||
|
||||
private static final String SCHEDULER_PRINCIPAL = ServicePrincipals.of("scheduler.redshift");
|
||||
|
||||
private final ServiceRoleAuthorizer authorizer;
|
||||
private final RegionResolver regionResolver;
|
||||
|
||||
@Inject
|
||||
public RedshiftScheduledActionAuthorizer(ServiceRoleAuthorizer authorizer, RegionResolver regionResolver) {
|
||||
this.authorizer = authorizer;
|
||||
this.regionResolver = regionResolver;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns why {@code roleArn} may not run {@code operation}, {@code PauseCluster} or {@code ResumeCluster},
|
||||
* on the cluster {@code clusterIdentifier} of {@code region}, or nothing when it may.
|
||||
*/
|
||||
public Optional<String> refusal(String roleArn, String accountId, String region, String operation,
|
||||
String clusterIdentifier) {
|
||||
String namedAs = "redshift:" + operation;
|
||||
String action = IamAuthorizedActions.actionFor("redshift", operation);
|
||||
ObjectNode request = JsonNodeFactory.instance.objectNode().put("ClusterIdentifier", clusterIdentifier);
|
||||
List<Permission> permissions = RequestResources.ofBody(namedAs, request,
|
||||
regionResolver.partitionForRegion(region), region, accountId, null).stream()
|
||||
.map(resource -> new Permission(action, resource))
|
||||
.toList();
|
||||
if (permissions.isEmpty()) {
|
||||
return Optional.of("The scheduled action's target names no cluster to run " + action + " on.");
|
||||
}
|
||||
return authorizer.refusal(roleArn, accountId, SCHEDULER_PRINCIPAL, null, permissions);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package io.floci.aws.services.redshift;
|
||||
|
||||
import com.cronutils.model.time.ExecutionTime;
|
||||
import io.floci.aws.core.common.AwsCronSchedule;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.services.redshift.model.ScheduledAction;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/** UTC schedule rules of a provisioned scheduled action: one-off {@code at(...)} or six-field AWS {@code cron(...)}. */
|
||||
final class RedshiftScheduledActionSchedule {
|
||||
|
||||
private RedshiftScheduledActionSchedule() { }
|
||||
|
||||
/** Rejects an expression that is neither a well-formed {@code at} nor a well-formed {@code cron}. */
|
||||
static void validate(String schedule) {
|
||||
if (schedule == null || schedule.isBlank()) {
|
||||
throw invalid("Schedule is required.");
|
||||
}
|
||||
String body = schedule.trim();
|
||||
if (body.startsWith("at(")) {
|
||||
parseAt(body);
|
||||
} else if (body.startsWith("cron(")) {
|
||||
AwsCronSchedule.requireHourlySpacing(parseCron(body), RedshiftScheduledActionSchedule::invalid);
|
||||
} else {
|
||||
throw invalid("The schedule must be an at(...) or a cron(...) expression.");
|
||||
}
|
||||
}
|
||||
|
||||
/** The first invocation strictly after {@code after} that is enabled and inside the active window. */
|
||||
static Optional<Instant> next(ScheduledAction action, Instant after) {
|
||||
if (!action.isEnabled()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Instant candidate;
|
||||
String schedule = action.getSchedule().trim();
|
||||
if (schedule.startsWith("at(")) {
|
||||
Instant at = parseAt(schedule);
|
||||
candidate = at.isAfter(after) ? at : null;
|
||||
} else {
|
||||
candidate = AwsCronSchedule.next(parseCron(schedule),
|
||||
AwsCronSchedule.searchFrom(after, action.getStartTime())).orElse(null);
|
||||
}
|
||||
return Optional.ofNullable(candidate).filter(time -> inWindow(action, time));
|
||||
}
|
||||
|
||||
/** The next {@code count} invocations after {@code after}. */
|
||||
static List<Instant> upcoming(ScheduledAction action, Instant after, int count) {
|
||||
List<Instant> invocations = new ArrayList<>();
|
||||
Instant cursor = after;
|
||||
while (invocations.size() < count) {
|
||||
Optional<Instant> next = next(action, cursor);
|
||||
if (next.isEmpty()) {
|
||||
break;
|
||||
}
|
||||
invocations.add(next.get());
|
||||
cursor = next.get();
|
||||
}
|
||||
return invocations;
|
||||
}
|
||||
|
||||
/** The latest invocation in {@code (anchor, now]} that is inside the window; older ones are coalesced away. */
|
||||
static Optional<Instant> latestDue(ScheduledAction action, Instant anchor, Instant now) {
|
||||
if (!action.isEnabled()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Instant upper = AwsCronSchedule.searchUpTo(now, action.getEndTime());
|
||||
Optional<Instant> latest;
|
||||
String schedule = action.getSchedule().trim();
|
||||
if (schedule.startsWith("at(")) {
|
||||
latest = Optional.of(parseAt(schedule)).filter(time -> !time.isAfter(upper));
|
||||
} else {
|
||||
latest = AwsCronSchedule.latest(parseCron(schedule), upper);
|
||||
}
|
||||
return latest.filter(time -> time.isAfter(anchor) && inWindow(action, time));
|
||||
}
|
||||
|
||||
private static boolean inWindow(ScheduledAction action, Instant time) {
|
||||
return AwsCronSchedule.inWindow(time, action.getStartTime(), action.getEndTime());
|
||||
}
|
||||
|
||||
private static Instant parseAt(String expression) {
|
||||
if (!expression.endsWith(")")) {
|
||||
throw invalid("The at(...) schedule is not closed.");
|
||||
}
|
||||
String timestamp = expression.substring("at(".length(), expression.length() - 1).trim();
|
||||
try {
|
||||
return LocalDateTime.parse(timestamp).toInstant(ZoneOffset.UTC);
|
||||
} catch (DateTimeParseException e) {
|
||||
throw invalid("The at(...) schedule needs a UTC timestamp such as at(2026-11-20T10:00:00).");
|
||||
}
|
||||
}
|
||||
|
||||
private static ExecutionTime parseCron(String expression) {
|
||||
if (!expression.endsWith(")")) {
|
||||
throw invalid("The cron(...) schedule is not closed.");
|
||||
}
|
||||
String body = expression.substring("cron(".length(), expression.length() - 1).trim();
|
||||
String[] fields = body.split("\\s+");
|
||||
return AwsCronSchedule.parse(fields, RedshiftScheduledActionSchedule::invalid);
|
||||
}
|
||||
|
||||
private static AwsException invalid(String message) {
|
||||
return new AwsException("InvalidSchedule", message, 400);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package io.floci.aws.services.redshift;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.SweepScheduler;
|
||||
import io.floci.aws.core.common.SweepWorker;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
/** Drives provisioned scheduled actions outside AWS request threads, one sweep at a time. */
|
||||
@ApplicationScoped
|
||||
public class RedshiftScheduledActionScheduler extends SweepScheduler {
|
||||
@Inject
|
||||
public RedshiftScheduledActionScheduler(RedshiftScheduledActionService service, EmulatorConfig config) {
|
||||
super(worker(service, config.services().redshift()));
|
||||
}
|
||||
|
||||
private static SweepWorker worker(RedshiftScheduledActionService service,
|
||||
EmulatorConfig.RedshiftServiceConfig redshift) {
|
||||
return new SweepWorker("redshift-scheduled-actions",
|
||||
redshift.enabled() && redshift.scheduledActionsEnabled(),
|
||||
redshift.scheduledActionSweepIntervalSeconds(), false, service::runScheduledActions);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,382 @@
|
||||
package io.floci.aws.services.redshift;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.PaginatedResult;
|
||||
import io.floci.aws.core.common.Pagination;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.core.common.Resettable;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend.AccountEntry;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.redshift.model.ScheduledAction;
|
||||
import io.quarkus.runtime.StartupEvent;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.event.Observes;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* Redshift scheduled actions of provisioned clusters, which pause or resume a cluster on an {@code at}
|
||||
* or {@code cron} schedule. A sweep ({@link #runScheduledActions}) runs the latest invocation of every
|
||||
* action whose schedule came due since it last looked. Resizing on a schedule is not supported.
|
||||
*
|
||||
* <p>An action belongs to a cluster but lives in its own store. Deleting the cluster removes its
|
||||
* actions through a removal listener, and every read drops an action whose cluster is gone, so a
|
||||
* cluster recreated under the same identifier never inherits its predecessor's actions.
|
||||
*
|
||||
* <p>The sweep records its checkpoint after attempting the invocation, so a crash in between can retry
|
||||
* that time once. After downtime only the latest due time runs, and nothing before an action was
|
||||
* created, rescheduled or enabled again is replayed. A failing invocation, such as pausing a cluster
|
||||
* that is already paused, is logged and kept as the action's last failure, and never stops the others.
|
||||
*
|
||||
* <p>Lock order: the action's lock, then this service's monitor. The removal listener takes neither,
|
||||
* because it runs under the cluster's lock, which a sweep takes while holding the action's lock.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class RedshiftScheduledActionService implements Resettable {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(RedshiftScheduledActionService.class);
|
||||
private static final int MIN_MAX_RECORDS = 20;
|
||||
private static final int MAX_MAX_RECORDS = 100;
|
||||
|
||||
private final AccountAwareStorageBackend<ScheduledAction> actions;
|
||||
private final RedshiftService redshift;
|
||||
private final RedshiftScheduledActionAuthorizer authorizer;
|
||||
private final RegionResolver regionResolver;
|
||||
private final Clock clock;
|
||||
private final ConcurrentHashMap<String, ReentrantLock> actionLocks = new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
public RedshiftScheduledActionService(StorageFactory storageFactory, RedshiftService redshift,
|
||||
RedshiftScheduledActionAuthorizer authorizer,
|
||||
RegionResolver regionResolver, Clock clock) {
|
||||
this.actions = storageFactory.create("redshift", "redshift-scheduled-actions.json",
|
||||
new TypeReference<Map<String, ScheduledAction>>() {});
|
||||
this.redshift = redshift;
|
||||
this.authorizer = authorizer;
|
||||
this.regionResolver = regionResolver;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
RedshiftScheduledActionService(StorageFactory storageFactory, RedshiftService redshift,
|
||||
RedshiftScheduledActionAuthorizer authorizer, RegionResolver regionResolver) {
|
||||
this(storageFactory, redshift, authorizer, regionResolver, Clock.systemUTC());
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
void registerClusterRemoval() {
|
||||
redshift.onClusterRemoved(this::removeActionsOfCluster);
|
||||
}
|
||||
|
||||
// Observing startup builds this lazy bean at boot, so its removal listener is registered before any
|
||||
// cluster can be deleted, also when the sweep is disabled or has not ticked yet.
|
||||
void onStart(@Observes StartupEvent ignored) {
|
||||
LOG.debug("Redshift scheduled actions registered for cluster removal");
|
||||
}
|
||||
|
||||
/** Creates {@code request}. The target cluster must exist and the name must be unused. */
|
||||
public ScheduledAction createScheduledAction(ScheduledAction request) {
|
||||
return mutate(request.getScheduledActionName(), () -> {
|
||||
validate(request);
|
||||
if (liveActions().stream().anyMatch(existing ->
|
||||
existing.getScheduledActionName().equals(request.getScheduledActionName()))) {
|
||||
throw new AwsException("ScheduledActionAlreadyExists",
|
||||
"The scheduled action " + request.getScheduledActionName() + " already exists.", 400);
|
||||
}
|
||||
ScheduledAction action = new ScheduledAction(request);
|
||||
action.setActivatedAt(clock.instant());
|
||||
actions.put(request.getScheduledActionName(), action);
|
||||
// The cluster can be deleted between the check in validate and the write; its removal
|
||||
// listener has already run by then, so the action would be left behind.
|
||||
if (!clusterExists(action)) {
|
||||
actions.delete(request.getScheduledActionName());
|
||||
throw new AwsException("ClusterNotFound",
|
||||
"Cluster " + request.getClusterIdentifier() + " not found", 404);
|
||||
}
|
||||
return new ScheduledAction(action);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists the account's actions filtered by the given members, which are all optional. {@code active}
|
||||
* keeps only the enabled actions when true and only the disabled ones when false. The time
|
||||
* filters keep the enabled actions with an invocation at or after {@code startTime}, or at or
|
||||
* before {@code endTime}.
|
||||
*/
|
||||
public synchronized PaginatedResult<ScheduledAction> describeScheduledActions(
|
||||
String name, String targetActionType, Instant startTime, Instant endTime, Boolean active,
|
||||
List<String> clusterIdentifiers, List<String> iamRoles, Integer maxRecords, String marker) {
|
||||
int limit = maxRecords == null ? MAX_MAX_RECORDS : maxRecords;
|
||||
if (limit < MIN_MAX_RECORDS || limit > MAX_MAX_RECORDS) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"MaxRecords must be between " + MIN_MAX_RECORDS + " and " + MAX_MAX_RECORDS + ".", 400);
|
||||
}
|
||||
Instant now = clock.instant();
|
||||
List<ScheduledAction> matching = liveActions().stream()
|
||||
.filter(action -> name == null || name.equals(action.getScheduledActionName()))
|
||||
.filter(action -> targetActionType == null || targetActionType.equals(action.getTargetActionType()))
|
||||
.filter(action -> active == null || action.isEnabled() == active)
|
||||
.filter(action -> clusterIdentifiers.isEmpty()
|
||||
|| clusterIdentifiers.contains(action.getClusterIdentifier()))
|
||||
.filter(action -> iamRoles.isEmpty() || iamRoles.contains(action.getIamRole()))
|
||||
.filter(action -> startTime == null
|
||||
|| RedshiftScheduledActionSchedule.next(action, startTime.minusNanos(1)).isPresent())
|
||||
.filter(action -> endTime == null || RedshiftScheduledActionSchedule.next(action, now)
|
||||
.filter(next -> !next.isAfter(endTime)).isPresent())
|
||||
.sorted(Comparator.comparing(ScheduledAction::getScheduledActionName))
|
||||
.map(ScheduledAction::new)
|
||||
.toList();
|
||||
return Pagination.paginate(matching, ScheduledAction::getScheduledActionName, limit, marker,
|
||||
"redshift-scheduled-action",
|
||||
token -> new AwsException("InvalidParameterValue", "Invalid Marker.", 400));
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the members {@code changes} carries; a null member is left as it was. A new schedule, or
|
||||
* enabling a disabled action, restarts the count from now so nothing earlier is replayed.
|
||||
*/
|
||||
public ScheduledAction modifyScheduledAction(ScheduledAction changes, Boolean enable) {
|
||||
return mutate(changes.getScheduledActionName(), () -> {
|
||||
ScheduledAction current = require(changes.getScheduledActionName());
|
||||
ScheduledAction updated = new ScheduledAction(current);
|
||||
if (changes.getIamRole() != null) {
|
||||
updated.setIamRole(changes.getIamRole());
|
||||
}
|
||||
if (changes.getDescription() != null) {
|
||||
updated.setDescription(changes.getDescription());
|
||||
}
|
||||
if (changes.getSchedule() != null) {
|
||||
RedshiftScheduledActionSchedule.validate(changes.getSchedule());
|
||||
updated.setSchedule(changes.getSchedule());
|
||||
updated.setActivatedAt(clock.instant());
|
||||
updated.setLastClaimedInvocation(null);
|
||||
}
|
||||
if (changes.getTargetActionType() != null) {
|
||||
updated.setTargetActionType(changes.getTargetActionType());
|
||||
updated.setClusterIdentifier(changes.getClusterIdentifier());
|
||||
}
|
||||
if (changes.getStartTime() != null) {
|
||||
updated.setStartTime(changes.getStartTime());
|
||||
}
|
||||
if (changes.getEndTime() != null) {
|
||||
updated.setEndTime(changes.getEndTime());
|
||||
}
|
||||
if (enable != null) {
|
||||
if (enable && !current.isEnabled()) {
|
||||
updated.setActivatedAt(clock.instant());
|
||||
}
|
||||
updated.setEnabled(enable);
|
||||
}
|
||||
validate(updated);
|
||||
actions.put(updated.getScheduledActionName(), updated);
|
||||
// Same race as in createScheduledAction: a deletion between validate and put leaves an orphan.
|
||||
if (!clusterExists(updated)) {
|
||||
actions.delete(updated.getScheduledActionName());
|
||||
throw new AwsException("ClusterNotFound",
|
||||
"Cluster " + updated.getClusterIdentifier() + " not found", 404);
|
||||
}
|
||||
return new ScheduledAction(updated);
|
||||
});
|
||||
}
|
||||
|
||||
public void deleteScheduledAction(String name) {
|
||||
mutate(name, () -> {
|
||||
require(name);
|
||||
actions.delete(name);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
/** The next {@code count} invocations of {@code action} from now. */
|
||||
public List<Instant> upcomingInvocations(ScheduledAction action, int count) {
|
||||
return RedshiftScheduledActionSchedule.upcoming(action, clock.instant(), count);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the latest due invocation of every action whose time falls in {@code (checkpoint, now]}. A
|
||||
* deterministic entry point: the lifecycle scheduler supplies the clock and tests a fixed instant.
|
||||
*/
|
||||
public void runScheduledActions(Instant now) {
|
||||
for (AccountEntry<ScheduledAction> entry : actions.scanAllAccountEntries(key -> true)) {
|
||||
if (Thread.currentThread().isInterrupted()) {
|
||||
return;
|
||||
}
|
||||
ReentrantLock lock = lockOf(entry.accountId(), entry.key());
|
||||
lock.lock();
|
||||
try {
|
||||
RequestScopes.runAs(entry.accountId(), regionOf(entry.accountId(), entry.value()),
|
||||
() -> runScheduledAction(entry.accountId(), entry.key(), now));
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Scheduled action {0} in account {1} could not be processed",
|
||||
entry.key(), entry.accountId());
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs under the action's lock, with the action's account as the request scope. */
|
||||
private void runScheduledAction(String accountId, String key, Instant now) {
|
||||
ScheduledAction action = actions.getForAccount(accountId, key).orElse(null);
|
||||
if (action == null) {
|
||||
return;
|
||||
}
|
||||
if (!redshift.clusterExists(accountId, action.getClusterIdentifier())) {
|
||||
actions.deleteForAccount(accountId, key);
|
||||
return;
|
||||
}
|
||||
if (action.getActivatedAt() == null) {
|
||||
ScheduledAction activated = new ScheduledAction(action);
|
||||
activated.setActivatedAt(now);
|
||||
actions.putAllAtomicallyForAccount(accountId, Map.of(key, activated));
|
||||
return;
|
||||
}
|
||||
Instant checkpoint = action.getLastClaimedInvocation() != null
|
||||
&& action.getLastClaimedInvocation().isAfter(action.getActivatedAt())
|
||||
? action.getLastClaimedInvocation() : action.getActivatedAt();
|
||||
Optional<Instant> due = RedshiftScheduledActionSchedule.latestDue(action, checkpoint, now);
|
||||
if (due.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Instant scheduled = due.get();
|
||||
ScheduledAction outcome = new ScheduledAction(action);
|
||||
outcome.setLastClaimedInvocation(scheduled);
|
||||
outcome.setLastFailure(null);
|
||||
try {
|
||||
invoke(action, accountId);
|
||||
outcome.setLastCompletedInvocation(scheduled);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Scheduled action {0} in account {1} failed at {2}",
|
||||
action.getScheduledActionName(), accountId, scheduled);
|
||||
outcome.setLastFailure(String.valueOf(e.getMessage()));
|
||||
}
|
||||
recordOutcome(accountId, key, outcome);
|
||||
}
|
||||
|
||||
private void invoke(ScheduledAction action, String accountId) {
|
||||
Optional<String> refusal = authorizer.refusal(action.getIamRole(), accountId, regionOf(accountId, action),
|
||||
action.getTargetActionType(), action.getClusterIdentifier());
|
||||
if (refusal.isPresent()) {
|
||||
throw new AwsException("UnauthorizedOperation", refusal.get(), 400);
|
||||
}
|
||||
if (ScheduledAction.PAUSE_CLUSTER.equals(action.getTargetActionType())) {
|
||||
redshift.pauseCluster(action.getClusterIdentifier());
|
||||
} else {
|
||||
redshift.resumeCluster(action.getClusterIdentifier());
|
||||
}
|
||||
}
|
||||
|
||||
/** Stores the checkpoint and outcome only when the action is still the one that was run. */
|
||||
private void recordOutcome(String accountId, String key, ScheduledAction outcome) {
|
||||
// A failed write propagates to runScheduledActions, which logs it; swallowing it here would leave the
|
||||
// checkpoint behind and re-run the same invocation on every sweep.
|
||||
ScheduledAction current = actions.getForAccount(accountId, key).orElse(null);
|
||||
if (current != null && Objects.equals(current.getActivatedAt(), outcome.getActivatedAt())) {
|
||||
ScheduledAction recorded = new ScheduledAction(current);
|
||||
recorded.setLastClaimedInvocation(outcome.getLastClaimedInvocation());
|
||||
recorded.setLastCompletedInvocation(outcome.getLastCompletedInvocation());
|
||||
recorded.setLastFailure(outcome.getLastFailure());
|
||||
actions.putAllAtomicallyForAccount(accountId, Map.of(key, recorded));
|
||||
}
|
||||
}
|
||||
|
||||
/** The region of the target cluster, which its ARN and the role check are scoped to. */
|
||||
private String regionOf(String accountId, ScheduledAction action) {
|
||||
return redshift.clusterRegion(accountId, action.getClusterIdentifier())
|
||||
.orElseGet(regionResolver::getDefaultRegion);
|
||||
}
|
||||
|
||||
private void removeActionsOfCluster(String accountId, String clusterIdentifier) {
|
||||
for (AccountEntry<ScheduledAction> entry : actions.scanAllAccountEntries(key -> true)) {
|
||||
if (entry.accountId().equals(accountId)
|
||||
&& clusterIdentifier.equals(entry.value().getClusterIdentifier())) {
|
||||
actions.deleteForAccount(accountId, entry.key());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
actions.clear();
|
||||
actionLocks.clear();
|
||||
}
|
||||
|
||||
private <T> T mutate(String name, Supplier<T> body) {
|
||||
ReentrantLock lock = lockOf(regionResolver.getAccountId(), name);
|
||||
lock.lock();
|
||||
try {
|
||||
synchronized (this) {
|
||||
return body.get();
|
||||
}
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
private ReentrantLock lockOf(String accountId, String key) {
|
||||
return actionLocks.computeIfAbsent(accountId + "|" + key, ignored -> new ReentrantLock());
|
||||
}
|
||||
|
||||
private ScheduledAction require(String name) {
|
||||
ScheduledAction action = actions.get(name).orElse(null);
|
||||
if (action != null && !clusterExists(action)) {
|
||||
actions.delete(name);
|
||||
action = null;
|
||||
}
|
||||
if (action == null) {
|
||||
throw new AwsException("ScheduledActionNotFound", "The scheduled action " + name + " was not found.", 400);
|
||||
}
|
||||
return action;
|
||||
}
|
||||
|
||||
/** The account's actions whose cluster is still there; any other is deleted as it is found. */
|
||||
private List<ScheduledAction> liveActions() {
|
||||
return actions.scan(key -> true).stream()
|
||||
.filter(action -> {
|
||||
if (clusterExists(action)) {
|
||||
return true;
|
||||
}
|
||||
actions.delete(action.getScheduledActionName());
|
||||
return false;
|
||||
})
|
||||
.toList();
|
||||
}
|
||||
|
||||
private boolean clusterExists(ScheduledAction action) {
|
||||
return redshift.clusterExists(regionResolver.getAccountId(), action.getClusterIdentifier());
|
||||
}
|
||||
|
||||
private void validate(ScheduledAction action) {
|
||||
if (action.getScheduledActionName() == null || action.getScheduledActionName().isBlank()) {
|
||||
throw new AwsException("InvalidParameterValue", "ScheduledActionName is required.", 400);
|
||||
}
|
||||
if (action.getIamRole() == null || action.getIamRole().isBlank()) {
|
||||
throw new AwsException("InvalidParameterValue", "IamRole is required.", 400);
|
||||
}
|
||||
RedshiftScheduledActionSchedule.validate(action.getSchedule());
|
||||
if (action.getStartTime() != null && action.getEndTime() != null
|
||||
&& !action.getEndTime().isAfter(action.getStartTime())) {
|
||||
throw new AwsException("InvalidSchedule", "EndTime must be after StartTime.", 400);
|
||||
}
|
||||
if (!ScheduledAction.PAUSE_CLUSTER.equals(action.getTargetActionType())
|
||||
&& !ScheduledAction.RESUME_CLUSTER.equals(action.getTargetActionType())) {
|
||||
throw new AwsException("InvalidScheduledAction", "TargetAction must be PauseCluster or ResumeCluster.", 400);
|
||||
}
|
||||
// Throws ClusterNotFound for a cluster the account does not have.
|
||||
redshift.describeClusters(action.getClusterIdentifier());
|
||||
}
|
||||
}
|
||||
@@ -71,7 +71,9 @@ import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.BiPredicate;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Predicate;
|
||||
@@ -128,6 +130,7 @@ public class RedshiftService implements ManagedSecretRotator {
|
||||
private final Set<Integer> usedPorts = ConcurrentHashMap.newKeySet();
|
||||
private final ConcurrentHashMap<ResourceKey, ResourceLock> resourceLocks = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, ResourceKey> managedRotationReservations = new ConcurrentHashMap<>();
|
||||
private final List<BiConsumer<String, String>> clusterRemovalListeners = new CopyOnWriteArrayList<>();
|
||||
|
||||
private record ResourceKey(String accountId, String kind, String identifier) { }
|
||||
|
||||
@@ -507,6 +510,7 @@ public class RedshiftService implements ManagedSecretRotator {
|
||||
if (proxyStopped) {
|
||||
clusters.delete(identifier);
|
||||
credentialBroker.revokeCluster(clusters.accountId(), identifier);
|
||||
notifyClusterRemoved(identifier);
|
||||
} else {
|
||||
cluster.setClusterStatus("failed");
|
||||
clusters.put(identifier, cluster);
|
||||
@@ -519,6 +523,7 @@ public class RedshiftService implements ManagedSecretRotator {
|
||||
if (proxyStopped) {
|
||||
clusters.delete(identifier);
|
||||
credentialBroker.revokeCluster(clusters.accountId(), identifier);
|
||||
notifyClusterRemoved(identifier);
|
||||
} else {
|
||||
cluster.setClusterStatus("failed");
|
||||
clusters.put(identifier, cluster);
|
||||
@@ -619,6 +624,7 @@ public class RedshiftService implements ManagedSecretRotator {
|
||||
if (proxyStopped) {
|
||||
clusters.delete(cluster.getClusterIdentifier());
|
||||
credentialBroker.revokeCluster(clusters.accountId(), cluster.getClusterIdentifier());
|
||||
notifyClusterRemoved(cluster.getClusterIdentifier());
|
||||
} else {
|
||||
cluster.setClusterStatus("failed");
|
||||
clusters.put(cluster.getClusterIdentifier(), cluster);
|
||||
@@ -1127,6 +1133,34 @@ public class RedshiftService implements ManagedSecretRotator {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a callback run with the account id and identifier of every cluster that is deleted. It runs
|
||||
* while the cluster's resource lock is held, so it must not wait for locks of its own.
|
||||
*/
|
||||
public void onClusterRemoved(BiConsumer<String, String> listener) {
|
||||
clusterRemovalListeners.add(listener);
|
||||
}
|
||||
|
||||
public boolean clusterExists(String accountId, String identifier) {
|
||||
return clusters.getForAccount(accountId, identifier).isPresent();
|
||||
}
|
||||
|
||||
/** The region the cluster was created in, or empty when the account has no such cluster. */
|
||||
public Optional<String> clusterRegion(String accountId, String identifier) {
|
||||
return clusters.getForAccount(accountId, identifier).map(this::snapshotRegion);
|
||||
}
|
||||
|
||||
/** A failing listener must not abort the removal: the cluster is already gone by now. */
|
||||
private void notifyClusterRemoved(String identifier) {
|
||||
for (BiConsumer<String, String> listener : clusterRemovalListeners) {
|
||||
try {
|
||||
listener.accept(clusters.accountId(), identifier);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Cluster removal listener failed for cluster {0}", identifier);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public List<Cluster> describeClusters(String identifier) {
|
||||
if (identifier != null) {
|
||||
Optional<Cluster> cluster = clusters.get(identifier);
|
||||
@@ -1274,6 +1308,7 @@ public class RedshiftService implements ManagedSecretRotator {
|
||||
// Invalidate any GetClusterCredentials passwords so a cluster later recreated with this
|
||||
// identifier does not accept them as master-equivalent.
|
||||
credentialBroker.revokeCluster(clusters.accountId(), identifier);
|
||||
notifyClusterRemoved(identifier);
|
||||
|
||||
if (cluster.getMasterPasswordSecretArn() != null && secretsManagerService != null) {
|
||||
try {
|
||||
@@ -2535,6 +2570,7 @@ public class RedshiftService implements ManagedSecretRotator {
|
||||
mutate(() -> {
|
||||
if (proxyStopped) {
|
||||
clusters.delete(identifier);
|
||||
notifyClusterRemoved(identifier);
|
||||
} else {
|
||||
cluster.setClusterStatus("failed");
|
||||
clusters.put(identifier, cluster);
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
package io.floci.aws.services.redshift;
|
||||
|
||||
import com.cronutils.model.Cron;
|
||||
import com.cronutils.model.time.ExecutionTime;
|
||||
import io.floci.aws.core.common.AwsCronDefinitions;
|
||||
import io.floci.aws.core.common.AwsCronSchedule;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@@ -88,12 +86,7 @@ final class RedshiftSnapshotSchedule {
|
||||
default -> throw new IllegalArgumentException("Redshift cron needs three or six fields");
|
||||
};
|
||||
String[] full = normalized.split(" ");
|
||||
if ("?".equals(full[2]) == "?".equals(full[4])) {
|
||||
throw new IllegalArgumentException("Use ? in exactly one of day-of-month and day-of-week");
|
||||
}
|
||||
Cron cron = AwsCronDefinitions.newParser().parse("0 " + normalized);
|
||||
cron.validate();
|
||||
return new Rule(null, ExecutionTime.forCron(cron));
|
||||
return new Rule(null, AwsCronSchedule.parse(full, IllegalArgumentException::new));
|
||||
}
|
||||
|
||||
private record Rule(Duration rate, ExecutionTime cron) {
|
||||
@@ -102,7 +95,7 @@ final class RedshiftSnapshotSchedule {
|
||||
long count = Duration.between(anchor, now).getSeconds() / rate.getSeconds();
|
||||
return count < 1 ? Optional.empty() : Optional.of(anchor.plus(rate.multipliedBy(count)));
|
||||
}
|
||||
return cron.lastExecution(now.atZone(ZoneOffset.UTC).plusNanos(1)).map(value -> value.toInstant());
|
||||
return AwsCronSchedule.latest(cron, now);
|
||||
}
|
||||
|
||||
Optional<Instant> next(Instant anchor, Instant after) {
|
||||
@@ -110,7 +103,7 @@ final class RedshiftSnapshotSchedule {
|
||||
long count = Math.max(0, Duration.between(anchor, after).getSeconds() / rate.getSeconds()) + 1;
|
||||
return Optional.of(anchor.plus(rate.multipliedBy(count)));
|
||||
}
|
||||
return cron.nextExecution(after.atZone(ZoneOffset.UTC)).map(value -> value.toInstant());
|
||||
return AwsCronSchedule.next(cron, after);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package io.floci.aws.services.redshift.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/**
|
||||
* A scheduled action of a provisioned cluster. The activation and invocation members are internal
|
||||
* bookkeeping of the sweep: no AWS response shows them.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class ScheduledAction {
|
||||
|
||||
public static final String PAUSE_CLUSTER = "PauseCluster";
|
||||
public static final String RESUME_CLUSTER = "ResumeCluster";
|
||||
|
||||
private String scheduledActionName;
|
||||
private String iamRole;
|
||||
private String schedule;
|
||||
private String description;
|
||||
private String targetActionType;
|
||||
private String clusterIdentifier;
|
||||
private boolean enabled = true;
|
||||
private Instant startTime;
|
||||
private Instant endTime;
|
||||
private Instant activatedAt;
|
||||
private Instant lastClaimedInvocation;
|
||||
private Instant lastCompletedInvocation;
|
||||
private String lastFailure;
|
||||
|
||||
public ScheduledAction() {
|
||||
}
|
||||
|
||||
public ScheduledAction(ScheduledAction other) {
|
||||
this.scheduledActionName = other.scheduledActionName;
|
||||
this.iamRole = other.iamRole;
|
||||
this.schedule = other.schedule;
|
||||
this.description = other.description;
|
||||
this.targetActionType = other.targetActionType;
|
||||
this.clusterIdentifier = other.clusterIdentifier;
|
||||
this.enabled = other.enabled;
|
||||
this.startTime = other.startTime;
|
||||
this.endTime = other.endTime;
|
||||
this.activatedAt = other.activatedAt;
|
||||
this.lastClaimedInvocation = other.lastClaimedInvocation;
|
||||
this.lastCompletedInvocation = other.lastCompletedInvocation;
|
||||
this.lastFailure = other.lastFailure;
|
||||
}
|
||||
|
||||
public String getScheduledActionName() { return scheduledActionName; }
|
||||
public void setScheduledActionName(String value) { scheduledActionName = value; }
|
||||
|
||||
public String getIamRole() { return iamRole; }
|
||||
public void setIamRole(String value) { iamRole = value; }
|
||||
|
||||
public String getSchedule() { return schedule; }
|
||||
public void setSchedule(String value) { schedule = value; }
|
||||
|
||||
public String getDescription() { return description; }
|
||||
public void setDescription(String value) { description = value; }
|
||||
|
||||
/** {@link #PAUSE_CLUSTER} or {@link #RESUME_CLUSTER}. */
|
||||
public String getTargetActionType() { return targetActionType; }
|
||||
public void setTargetActionType(String value) { targetActionType = value; }
|
||||
|
||||
public String getClusterIdentifier() { return clusterIdentifier; }
|
||||
public void setClusterIdentifier(String value) { clusterIdentifier = value; }
|
||||
|
||||
public boolean isEnabled() { return enabled; }
|
||||
public void setEnabled(boolean value) { enabled = value; }
|
||||
|
||||
public Instant getStartTime() { return startTime; }
|
||||
public void setStartTime(Instant value) { startTime = value; }
|
||||
|
||||
public Instant getEndTime() { return endTime; }
|
||||
public void setEndTime(Instant value) { endTime = value; }
|
||||
|
||||
/** When the current schedule began counting, so no invocation before it is replayed. */
|
||||
public Instant getActivatedAt() { return activatedAt; }
|
||||
public void setActivatedAt(Instant value) { activatedAt = value; }
|
||||
|
||||
/** The latest scheduled time that was attempted; it is never attempted twice. */
|
||||
public Instant getLastClaimedInvocation() { return lastClaimedInvocation; }
|
||||
public void setLastClaimedInvocation(Instant value) { lastClaimedInvocation = value; }
|
||||
|
||||
public Instant getLastCompletedInvocation() { return lastCompletedInvocation; }
|
||||
public void setLastCompletedInvocation(Instant value) { lastCompletedInvocation = value; }
|
||||
|
||||
public String getLastFailure() { return lastFailure; }
|
||||
public void setLastFailure(String value) { lastFailure = value; }
|
||||
}
|
||||
+8
-52
@@ -1,21 +1,14 @@
|
||||
package io.floci.aws.services.redshiftserverless;
|
||||
|
||||
import com.cronutils.model.Cron;
|
||||
import com.cronutils.model.time.ExecutionTime;
|
||||
import io.floci.aws.core.common.AwsCronDefinitions;
|
||||
import io.floci.aws.core.common.AwsCronSchedule;
|
||||
import io.floci.aws.services.redshiftserverless.model.ScheduledAction;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.Optional;
|
||||
|
||||
/** UTC schedule rules of a Serverless scheduled action: one-off {@code at} or six-field AWS {@code cron}. */
|
||||
final class RedshiftServerlessSchedule {
|
||||
private static final Duration MINIMUM_INTERVAL = Duration.ofHours(1);
|
||||
private static final Duration SPACING_HORIZON = Duration.ofDays(400);
|
||||
private static final int MAX_SPACING_CHECKS = 1000;
|
||||
|
||||
private RedshiftServerlessSchedule() { }
|
||||
|
||||
/** Rejects a cron that does not parse or fires more often than hourly; an {@code at} schedule always passes. */
|
||||
@@ -23,25 +16,7 @@ final class RedshiftServerlessSchedule {
|
||||
if (action.getScheduleCron() == null || action.getScheduleCron().isBlank()) {
|
||||
return;
|
||||
}
|
||||
ExecutionTime cron = parse(action.getScheduleCron());
|
||||
Optional<Instant> first = nextCron(cron, Instant.EPOCH);
|
||||
if (first.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Instant cursor = first.get().minusSeconds(1);
|
||||
Instant limit = cursor.plus(SPACING_HORIZON);
|
||||
Instant previous = null;
|
||||
for (int i = 0; i < MAX_SPACING_CHECKS; i++) {
|
||||
Optional<Instant> next = nextCron(cron, cursor);
|
||||
if (next.isEmpty() || next.get().isAfter(limit)) {
|
||||
return;
|
||||
}
|
||||
if (previous != null && Duration.between(previous, next.get()).compareTo(MINIMUM_INTERVAL) < 0) {
|
||||
throw ServerlessSupport.validation("The cron schedule must be at least one hour apart.");
|
||||
}
|
||||
previous = next.get();
|
||||
cursor = next.get();
|
||||
}
|
||||
AwsCronSchedule.requireHourlySpacing(parse(action.getScheduleCron()), ServerlessSupport::validation);
|
||||
}
|
||||
|
||||
/** The first invocation strictly after {@code after} that is enabled and inside the active window. */
|
||||
@@ -53,9 +28,8 @@ final class RedshiftServerlessSchedule {
|
||||
if (action.getScheduleAt() != null) {
|
||||
candidate = action.getScheduleAt().isAfter(after) ? action.getScheduleAt() : null;
|
||||
} else {
|
||||
Instant from = action.getStartTime() != null && action.getStartTime().isAfter(after)
|
||||
? action.getStartTime().minusNanos(1) : after;
|
||||
candidate = nextCron(parse(action.getScheduleCron()), from).orElse(null);
|
||||
candidate = AwsCronSchedule.next(parse(action.getScheduleCron()),
|
||||
AwsCronSchedule.searchFrom(after, action.getStartTime())).orElse(null);
|
||||
}
|
||||
return Optional.ofNullable(candidate).filter(time -> inWindow(action, time));
|
||||
}
|
||||
@@ -65,24 +39,18 @@ final class RedshiftServerlessSchedule {
|
||||
if (Boolean.FALSE.equals(action.getEnabled())) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Instant upper = action.getEndTime() != null && action.getEndTime().isBefore(now) ? action.getEndTime() : now;
|
||||
Instant upper = AwsCronSchedule.searchUpTo(now, action.getEndTime());
|
||||
Optional<Instant> latest;
|
||||
if (action.getScheduleAt() != null) {
|
||||
latest = Optional.of(action.getScheduleAt()).filter(time -> !time.isAfter(upper));
|
||||
} else {
|
||||
latest = parse(action.getScheduleCron()).lastExecution(upper.atZone(ZoneOffset.UTC).plusNanos(1))
|
||||
.map(value -> value.toInstant());
|
||||
latest = AwsCronSchedule.latest(parse(action.getScheduleCron()), upper);
|
||||
}
|
||||
return latest.filter(time -> time.isAfter(anchor) && inWindow(action, time));
|
||||
}
|
||||
|
||||
private static boolean inWindow(ScheduledAction action, Instant time) {
|
||||
return (action.getStartTime() == null || !time.isBefore(action.getStartTime()))
|
||||
&& (action.getEndTime() == null || !time.isAfter(action.getEndTime()));
|
||||
}
|
||||
|
||||
private static Optional<Instant> nextCron(ExecutionTime cron, Instant after) {
|
||||
return cron.nextExecution(after.atZone(ZoneOffset.UTC)).map(value -> value.toInstant());
|
||||
return AwsCronSchedule.inWindow(time, action.getStartTime(), action.getEndTime());
|
||||
}
|
||||
|
||||
private static ExecutionTime parse(String expression) {
|
||||
@@ -94,18 +62,6 @@ final class RedshiftServerlessSchedule {
|
||||
body = body.substring(1, body.length() - 1).trim();
|
||||
}
|
||||
String[] fields = body.split("\\s+");
|
||||
if (fields.length != 6) {
|
||||
throw ServerlessSupport.validation("The cron schedule needs six fields.");
|
||||
}
|
||||
if ("?".equals(fields[2]) == "?".equals(fields[4])) {
|
||||
throw ServerlessSupport.validation("Use ? in exactly one of day-of-month and day-of-week.");
|
||||
}
|
||||
try {
|
||||
Cron cron = AwsCronDefinitions.newParser().parse("0 " + String.join(" ", fields));
|
||||
cron.validate();
|
||||
return ExecutionTime.forCron(cron);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw ServerlessSupport.validation("The cron schedule is invalid: " + e.getMessage());
|
||||
}
|
||||
return AwsCronSchedule.parse(fields, ServerlessSupport::validation);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user