feat(redshift): execute automated snapshot schedules (#6536)

* feat(redshift): execute automated snapshot schedules

* fix(redshift): address automated snapshot review findings

Flush snapshot metadata before deleting an expired dump, pause the
snapshot scheduler across emulator reset, run retention even when the
next dump fails, and remove checkpoints of deleted clusters.

* fix(redshift): retake an automated snapshot whose metadata was lost

The checkpoint is a separate store, so it can persist while the snapshot
metadata never reached disk. Skip a completed occurrence only when its
snapshot still exists.

* test(redshift): restore the automated snapshot on the shared interceptor cluster

Run the Docker restore scenario in RedshiftInterceptorIntegrationTest
against the cluster it already starts, so only the restore pays for a
container, and drop the hand-rolled Docker probe.
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-26 11:42:07 -04:00
1 parent 986117a45c
commit f184cce726
18 files changed
+1305 -62

No files matched your search

@@ -1723,6 +1723,10 @@ public interface EmulatorConfig {
}
interface RedshiftServiceConfig {
@WithDefault("true")
boolean automatedSnapshotsEnabled();
@WithDefault("60")
long snapshotSweepIntervalSeconds();
@WithDefault("true")
boolean enabled();
@WithDefault("5439")
@@ -92,12 +92,23 @@ public class RedshiftQueryHandler {
String region = regionResolver.resolveRegionFromAuth(authorizationHeader);
String defaultIamRoleArn = params.getFirst("DefaultIamRoleArn");
Cluster cluster = manageMasterPassword
? service.createClusterWithManagedMasterPassword(identifier, nodeType, masterUsername,
clusterSubnetGroupName, vpcSecurityGroupIds, iamRoleArns,
params.getFirst("MasterPasswordSecretKmsKeyId"), region, defaultIamRoleArn)
: service.createCluster(identifier, nodeType, masterUsername, masterUserPassword,
clusterSubnetGroupName, vpcSecurityGroupIds, iamRoleArns, defaultIamRoleArn);
Integer automatedRetention = parseOptionalInteger(params, "AutomatedSnapshotRetentionPeriod");
Cluster cluster;
if (manageMasterPassword) {
cluster = automatedRetention == null
? service.createClusterWithManagedMasterPassword(identifier, nodeType, masterUsername,
clusterSubnetGroupName, vpcSecurityGroupIds, iamRoleArns,
params.getFirst("MasterPasswordSecretKmsKeyId"), region, defaultIamRoleArn)
: service.createClusterWithManagedMasterPassword(identifier, nodeType, masterUsername,
clusterSubnetGroupName, vpcSecurityGroupIds, iamRoleArns,
params.getFirst("MasterPasswordSecretKmsKeyId"), region, defaultIamRoleArn, automatedRetention);
} else {
cluster = automatedRetention == null
? service.createCluster(identifier, nodeType, masterUsername, masterUserPassword,
clusterSubnetGroupName, vpcSecurityGroupIds, iamRoleArns, defaultIamRoleArn)
: service.createCluster(identifier, nodeType, masterUsername, masterUserPassword,
clusterSubnetGroupName, vpcSecurityGroupIds, iamRoleArns, defaultIamRoleArn, automatedRetention);
}
String parameterGroupName = params.getFirst("ClusterParameterGroupName");
String multiAz = params.getFirst("MultiAZ");
boolean hasParameterGroup = parameterGroupName != null && !parameterGroupName.isBlank();
@@ -177,6 +188,13 @@ public class RedshiftQueryHandler {
String snapshotIdentifier = params.getFirst("SnapshotIdentifier");
String clusterIdentifier = params.getFirst("ClusterIdentifier");
List<Snapshot> snapshots = service.describeSnapshots(snapshotIdentifier, clusterIdentifier);
String snapshotType = params.getFirst("SnapshotType");
if (snapshotType != null) {
if (!List.of("manual", "automated").contains(snapshotType)) {
throw new AwsException("InvalidParameterValue", "SnapshotType must be manual or automated", 400);
}
snapshots = snapshots.stream().filter(snapshot -> snapshotType.equals(snapshot.getSnapshotType())).toList();
}
XmlBuilder xmlBuilder = new XmlBuilder()
.start("DescribeClusterSnapshotsResponse")
.start("DescribeClusterSnapshotsResult")
@@ -680,9 +698,14 @@ public class RedshiftQueryHandler {
String clusterParameterGroupName = params.getFirst("ClusterParameterGroupName");
List<String> vpcSecurityGroupIds = memberList(params, "VpcSecurityGroupIds");
String multiAz = params.getFirst("MultiAZ");
Cluster cluster = service.modifyCluster(clusterIdentifier, nodeType, numberOfNodes,
masterUserPassword, clusterParameterGroupName, vpcSecurityGroupIds,
multiAz == null ? null : Boolean.parseBoolean(multiAz));
Integer automatedRetention = parseOptionalInteger(params, "AutomatedSnapshotRetentionPeriod");
Cluster cluster = automatedRetention == null
? service.modifyCluster(clusterIdentifier, nodeType, numberOfNodes,
masterUserPassword, clusterParameterGroupName, vpcSecurityGroupIds,
multiAz == null ? null : Boolean.parseBoolean(multiAz))
: service.modifyCluster(clusterIdentifier, nodeType, numberOfNodes,
masterUserPassword, clusterParameterGroupName, vpcSecurityGroupIds,
multiAz == null ? null : Boolean.parseBoolean(multiAz), automatedRetention);
String xml = new XmlBuilder()
.start("ModifyClusterResponse")
.start("ModifyClusterResult")
@@ -926,6 +949,7 @@ public class RedshiftQueryHandler {
.elem("NodeType", cluster.getNodeType())
.elem("MasterUsername", cluster.getMasterUsername())
.elem("ClusterStatus", cluster.getClusterStatus())
.elem("AutomatedSnapshotRetentionPeriod", String.valueOf(cluster.getAutomatedSnapshotRetentionPeriod()))
.elem("ClusterAvailabilityStatus", availabilityStatus(cluster.getClusterStatus()))
.elem("AvailabilityZoneRelocationStatus", "disabled")
// AWS always returns "enabled" or "disabled" here, never blank.
@@ -1063,6 +1087,7 @@ public class RedshiftQueryHandler {
.elem("ClusterIdentifier", snapshot.getClusterIdentifier())
.elem("SnapshotArn", snapshot.getSnapshotArn())
.elem("SnapshotCreateTime", createTime)
.elem("SnapshotType", snapshot.getSnapshotType())
.elem("ManualSnapshotRetentionPeriod", snapshot.getManualSnapshotRetentionPeriod().toString())
.elem("Status", snapshot.getStatus())
.elem("Port", String.valueOf(snapshot.getPort()))
@@ -16,6 +16,7 @@ import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReader
import io.github.hectorvent.floci.services.rds.proxy.PasswordValidator;
import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerHandle;
import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerManager;
import io.github.hectorvent.floci.services.redshift.model.AutomatedSnapshotState;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.services.redshift.model.ClusterParameterGroup;
import io.github.hectorvent.floci.services.redshift.model.ClusterSubnetGroup;
@@ -37,9 +38,11 @@ import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
@@ -49,6 +52,7 @@ import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
@@ -56,7 +60,6 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ApplicationScoped
@@ -83,6 +86,7 @@ public class RedshiftService implements ManagedSecretRotator {
private final AccountAwareStorageBackend<Integration> integrations;
private final AccountAwareStorageBackend<SnapshotCopyGrant> snapshotCopyGrants;
private final AccountAwareStorageBackend<SnapshotSchedule> snapshotSchedules;
private final AccountAwareStorageBackend<AutomatedSnapshotState> automatedSnapshotStates;
private final RedshiftContainerManager containerManager;
private final EmulatorConfig config;
private final RegionResolver regionResolver;
@@ -159,6 +163,8 @@ public class RedshiftService implements ManagedSecretRotator {
this.integrations = storageFactory.create("redshift", "redshift-integrations.json", new TypeReference<Map<String, Integration>>() {});
this.snapshotCopyGrants = storageFactory.create("redshift", "redshift-snapshot-copy-grants.json", new TypeReference<Map<String, SnapshotCopyGrant>>() {});
this.snapshotSchedules = storageFactory.create("redshift", "redshift-snapshot-schedules.json", new TypeReference<Map<String, SnapshotSchedule>>() {});
this.automatedSnapshotStates = storageFactory.create("redshift", "redshift-automated-snapshot-state.json",
new TypeReference<Map<String, AutomatedSnapshotState>>() {});
this.containerManager = containerManager;
this.config = config;
this.regionResolver = regionResolver;
@@ -265,13 +271,22 @@ public class RedshiftService implements ManagedSecretRotator {
public Cluster createCluster(String identifier, String nodeType, String username, String password,
String clusterSubnetGroupName, List<String> vpcSecurityGroupIds,
List<String> iamRoleArns, String defaultIamRoleArn) {
return createCluster(identifier, nodeType, username, password, clusterSubnetGroupName,
vpcSecurityGroupIds, iamRoleArns, defaultIamRoleArn, null);
}
public Cluster createCluster(String identifier, String nodeType, String username, String password,
String clusterSubnetGroupName, List<String> vpcSecurityGroupIds,
List<String> iamRoleArns, String defaultIamRoleArn, Integer automatedRetention) {
validateAutomatedRetention(nodeType, automatedRetention == null ? 1 : automatedRetention);
return mutateCluster(identifier, () -> createClusterLocked(identifier, nodeType, username, password,
clusterSubnetGroupName, vpcSecurityGroupIds, iamRoleArns, defaultIamRoleArn));
clusterSubnetGroupName, vpcSecurityGroupIds, iamRoleArns, defaultIamRoleArn, automatedRetention));
}
private Cluster createClusterLocked(String identifier, String nodeType, String username, String password,
String clusterSubnetGroupName, List<String> vpcSecurityGroupIds,
List<String> iamRoleArns, String defaultIamRoleArn) {
List<String> iamRoleArns, String defaultIamRoleArn,
Integer automatedRetention) {
if (clusters.get(identifier).isPresent()) {
throw new AwsException("ClusterAlreadyExists", "Cluster " + identifier + " already exists", 400);
}
@@ -284,6 +299,10 @@ public class RedshiftService implements ManagedSecretRotator {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier(identifier);
cluster.setNodeType(nodeType);
cluster.setAutomatedSnapshotRetentionPeriod(automatedRetention);
cluster.setAutomatedSnapshotAnchor(Instant.now());
cluster.setSnapshotGeneration(UUID.randomUUID().toString());
cluster.setSnapshotRegion(regionResolver.getRegion());
cluster.setMasterUsername(username);
cluster.setMasterPassword(password);
cluster.setClusterSubnetGroupName(clusterSubnetGroupName);
@@ -359,18 +378,31 @@ public class RedshiftService implements ManagedSecretRotator {
String identifier, String nodeType, String username, String clusterSubnetGroupName,
List<String> vpcSecurityGroupIds, List<String> iamRoleArns,
String kmsKeyId, String region, String defaultIamRoleArn) {
return createClusterWithManagedMasterPassword(identifier, nodeType, username, clusterSubnetGroupName,
vpcSecurityGroupIds, iamRoleArns, kmsKeyId, region, defaultIamRoleArn, null);
}
public Cluster createClusterWithManagedMasterPassword(
String identifier, String nodeType, String username, String clusterSubnetGroupName,
List<String> vpcSecurityGroupIds, List<String> iamRoleArns,
String kmsKeyId, String region, String defaultIamRoleArn, Integer automatedRetention) {
validateAutomatedRetention(nodeType, automatedRetention == null ? 1 : automatedRetention);
return mutateCluster(identifier, () -> createClusterWithManagedMasterPasswordLocked(identifier,
nodeType, username, clusterSubnetGroupName, vpcSecurityGroupIds, iamRoleArns, kmsKeyId, region, defaultIamRoleArn));
nodeType, username, clusterSubnetGroupName, vpcSecurityGroupIds, iamRoleArns, kmsKeyId, region,
defaultIamRoleArn, automatedRetention));
}
private Cluster createClusterWithManagedMasterPasswordLocked(
String identifier, String nodeType, String username, String clusterSubnetGroupName,
List<String> vpcSecurityGroupIds, List<String> iamRoleArns,
String kmsKeyId, String region, String defaultIamRoleArn) {
String kmsKeyId, String region, String defaultIamRoleArn, Integer automatedRetention) {
requireSecretsManager();
String password = RandomPasswordGenerator.generate(objectMapper.createObjectNode());
Cluster cluster = createCluster(identifier, nodeType, username, password,
clusterSubnetGroupName, vpcSecurityGroupIds, iamRoleArns, defaultIamRoleArn);
clusterSubnetGroupName, vpcSecurityGroupIds, iamRoleArns, defaultIamRoleArn, automatedRetention);
if (region != null) {
cluster.setSnapshotRegion(region);
}
try {
return createManagedMasterSecret(cluster, kmsKeyId, region);
} catch (RuntimeException e) {
@@ -798,16 +830,32 @@ public class RedshiftService implements ManagedSecretRotator {
public Cluster modifyCluster(String clusterIdentifier, String nodeType, Integer numberOfNodes,
String masterUserPassword, String clusterParameterGroupName,
List<String> vpcSecurityGroupIds, Boolean multiAZ) {
return mutateCluster(clusterIdentifier, () -> modifyClusterLocked(clusterIdentifier, nodeType,
numberOfNodes, masterUserPassword, clusterParameterGroupName, vpcSecurityGroupIds, multiAZ));
return modifyCluster(clusterIdentifier, nodeType, numberOfNodes, masterUserPassword, clusterParameterGroupName,
vpcSecurityGroupIds, multiAZ, null);
}
public Cluster modifyCluster(String clusterIdentifier, String nodeType, Integer numberOfNodes,
String masterUserPassword, String clusterParameterGroupName,
List<String> vpcSecurityGroupIds, Boolean multiAZ, Integer automatedRetention) {
return withResourceLock("cluster", clusterIdentifier, () -> {
Cluster cluster = mutate(() -> modifyClusterLocked(clusterIdentifier, nodeType,
numberOfNodes, masterUserPassword, clusterParameterGroupName, vpcSecurityGroupIds, multiAZ,
automatedRetention));
if (automatedRetention != null) {
expireAutomatedSnapshots(clusters.accountId(), clusterIdentifier, cluster, Instant.now());
}
return cluster;
});
}
private Cluster modifyClusterLocked(String clusterIdentifier, String nodeType, Integer numberOfNodes,
String masterUserPassword, String clusterParameterGroupName,
List<String> vpcSecurityGroupIds, Boolean multiAZ) {
List<String> vpcSecurityGroupIds, Boolean multiAZ,
Integer automatedRetention) {
Cluster cluster = clusters.get(clusterIdentifier)
.orElseThrow(() -> new AwsException("ClusterNotFound", "Cluster " + clusterIdentifier + " not found", 404));
validateAutomatedRetention(nodeType == null ? cluster.getNodeType() : nodeType,
automatedRetention == null ? cluster.getAutomatedSnapshotRetentionPeriod() : automatedRetention);
// alterUserPassword runs before any mutation of the cluster object (a live reference
// from HybridStorage, not a copy); if it throws, no metadata has been changed yet.
if (masterUserPassword != null && !masterUserPassword.isBlank()) {
@@ -836,6 +884,12 @@ public class RedshiftService implements ManagedSecretRotator {
if (multiAZ != null) {
cluster.setMultiAZ(multiAZ);
}
if (automatedRetention != null) {
if (cluster.getAutomatedSnapshotRetentionPeriod() == 0 && automatedRetention > 0) {
cluster.setAutomatedSnapshotAnchor(Instant.now());
}
cluster.setAutomatedSnapshotRetentionPeriod(automatedRetention);
}
clusters.put(clusterIdentifier, cluster);
clusters.flush();
@@ -1208,9 +1262,13 @@ public class RedshiftService implements ManagedSecretRotator {
/** Absolute, normalised {@code <persistentPath>/redshift-dumps/<accountId>} for this request's account. */
private Path accountDumpDir() {
return accountDumpDir(clusters.accountId());
}
private Path accountDumpDir(String accountId) {
return Paths.get(config.storage().persistentPath())
.resolve("redshift-dumps")
.resolve(clusters.accountId())
.resolve(accountId)
.toAbsolutePath()
.normalize();
}
@@ -1239,27 +1297,43 @@ public class RedshiftService implements ManagedSecretRotator {
if (clusterOpt.isEmpty()) {
throw new AwsException("ClusterNotFound", "Cluster " + clusterIdentifier + " not found", 404);
}
if (snapshots.get(snapshotIdentifier).isPresent()) {
return createSnapshot(clusters.accountId(), snapshotIdentifier, clusterOpt.get(), retentionPeriod,
Instant.now(), null);
}
private Snapshot createSnapshot(String accountId, String snapshotIdentifier, Cluster cluster,
Integer retentionPeriod, Instant now, Instant scheduledTime) {
validateSnapshotIdentifier(snapshotIdentifier);
String clusterIdentifier = cluster.getClusterIdentifier();
if ((scheduledTime == null ? snapshots.get(snapshotIdentifier)
: snapshots.getForAccount(accountId, snapshotIdentifier)).isPresent()) {
throw new AwsException("ClusterSnapshotAlreadyExists", "Snapshot " + snapshotIdentifier + " already exists", 400);
}
Cluster cluster = clusterOpt.get();
Snapshot snapshot = new Snapshot();
snapshot.setSnapshotIdentifier(snapshotIdentifier);
snapshot.setClusterIdentifier(clusterIdentifier);
snapshot.setStatus("available");
snapshot.setMasterUsername(cluster.getMasterUsername());
snapshot.setMasterPassword(cluster.getMasterPassword());
snapshot.setSnapshotArn(snapshotArn(clusterIdentifier, snapshotIdentifier));
snapshot.setSnapshotCreateTime(Instant.now());
snapshot.setSnapshotArn(scheduledTime == null ? snapshotArn(clusterIdentifier, snapshotIdentifier)
: AwsArnUtils.Arn.of("redshift", snapshotRegion(cluster), accountId,
"snapshot:" + clusterIdentifier + "/" + snapshotIdentifier).toString());
snapshot.setSnapshotCreateTime(now);
snapshot.setManualSnapshotRetentionPeriod(retentionPeriod);
snapshot.setSnapshotType(scheduledTime == null ? "manual" : "automated");
snapshot.setScheduledTime(scheduledTime);
snapshot.setClusterGeneration(cluster.getSnapshotGeneration());
if (scheduledTime != null) {
snapshot.setAutomatedSnapshotRetentionPeriod(cluster.getAutomatedSnapshotRetentionPeriod());
}
if (cluster.getEndpoint() != null) {
snapshot.setPort(cluster.getEndpoint().getPort());
} else {
snapshot.setPort(5439);
}
Path dumpDir = accountDumpDir();
Path dumpDir = accountDumpDir(accountId);
// Defence in depth: validateSnapshotIdentifier already rejects path separators,
// but keep the containment check so the dump can never land outside the account dir.
Path dumpFile = dumpDir.resolve(snapshotIdentifier + ".sql").normalize();
@@ -1269,9 +1343,13 @@ public class RedshiftService implements ManagedSecretRotator {
boolean committed = false;
try {
Files.createDirectories(dumpDir);
containerManager.takeSnapshot(clusters.accountId(), clusterIdentifier, cluster.getMasterUsername(), dumpFile);
containerManager.takeSnapshot(accountId, clusterIdentifier, cluster.getMasterUsername(), dumpFile);
snapshot.setSqlDump(dumpFile.toString());
snapshots.putAllAtomically(Map.of(snapshotIdentifier, snapshot));
if (scheduledTime == null) {
snapshots.putAllAtomically(Map.of(snapshotIdentifier, snapshot));
} else {
snapshots.putAllAtomicallyForAccount(accountId, Map.of(snapshotIdentifier, snapshot));
}
committed = true;
snapshots.flush();
} catch (Exception e) {
@@ -1328,6 +1406,9 @@ public class RedshiftService implements ManagedSecretRotator {
throw new AwsException("ClusterSnapshotNotFound", "Snapshot " + snapshotIdentifier + " not found", 404);
}
Snapshot snapshot = snapshotOpt.get();
if ("automated".equals(snapshot.getSnapshotType())) {
throw new AwsException("InvalidClusterSnapshotState", "Automated snapshots cannot be deleted manually", 400);
}
snapshots.delete(snapshotIdentifier);
snapshots.flush();
if (isTrustedDumpPath(snapshot.getSqlDump())) {
@@ -1439,6 +1520,9 @@ public class RedshiftService implements ManagedSecretRotator {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier(clusterIdentifier);
cluster.setNodeType(effectiveNodeType);
cluster.setAutomatedSnapshotAnchor(Instant.now());
cluster.setSnapshotGeneration(UUID.randomUUID().toString());
cluster.setSnapshotRegion(regionResolver.getRegion());
cluster.setMasterUsername(username);
cluster.setMasterPassword(password);
cluster.setClusterParameterGroupName(DEFAULT_PARAMETER_GROUP_NAME);
@@ -1941,39 +2025,180 @@ public class RedshiftService implements ManagedSecretRotator {
private static final int SNAPSHOT_SCHEDULE_PAGE_MAX = 100;
private static final Pattern RATE_DEFINITION =
Pattern.compile("rate\\(\\s*(\\d+)\\s+(hours?|days?)\\s*\\)");
private static final Pattern CRON_DEFINITION =
Pattern.compile("cron\\(\\s*([A-Za-z0-9,\\-*/?#]+(?:\\s+[A-Za-z0-9,\\-*/?#]+){2,5})\\s*\\)");
private static void validateAutomatedRetention(String nodeType, int retention) {
boolean required = nodeType != null && (nodeType.startsWith("ra3.") || nodeType.startsWith("rg."));
if (retention < 0 || retention > 35 || required && retention == 0) {
throw new AwsException("InvalidParameterValue", "AutomatedSnapshotRetentionPeriod must be "
+ (required ? "1" : "0") + " to 35 days", 400);
}
}
/** A deterministic sweep; the lifecycle scheduler supplies now, tests supply a fixed instant. */
void runSnapshotSchedules(Instant now) {
for (AccountAwareStorageBackend.AccountEntry<Cluster> entry : clusters.scanAllAccountEntries(key -> true)) {
if (Thread.currentThread().isInterrupted()) {
return;
}
try {
withResourceLock(entry.accountId(), "cluster", entry.key(), () -> {
Cluster cluster = clusters.getForAccount(entry.accountId(), entry.key()).orElse(null);
if (cluster != null) {
try {
runSnapshotSchedule(entry.accountId(), cluster, now);
} finally {
// Retention must not depend on the next dump succeeding.
expireAutomatedSnapshots(entry.accountId(), cluster.getClusterIdentifier(), cluster, now);
}
}
return null;
});
} catch (RuntimeException e) {
LOG.warnv(e, "Could not process automated snapshots for account {0}, cluster {1}",
entry.accountId(), entry.key());
}
}
for (AccountAwareStorageBackend.AccountEntry<Snapshot> entry : snapshots.scanAllAccountEntries(key -> true)) {
if (!"automated".equals(entry.value().getSnapshotType())) {
continue;
}
String clusterId = entry.value().getClusterIdentifier();
try {
withResourceLock(entry.accountId(), "cluster", clusterId, () -> {
if (clusters.getForAccount(entry.accountId(), clusterId).isEmpty()) {
removeAutomatedSnapshot(entry.accountId(), entry.key());
}
return null;
});
} catch (RuntimeException e) {
LOG.warnv(e, "Could not clean up automated snapshot {0} in account {1}", entry.key(), entry.accountId());
}
}
for (AccountAwareStorageBackend.AccountEntry<AutomatedSnapshotState> entry
: automatedSnapshotStates.scanAllAccountEntries(key -> true)) {
try {
withResourceLock(entry.accountId(), "cluster", entry.key(), () -> {
if (clusters.getForAccount(entry.accountId(), entry.key()).isEmpty()) {
automatedSnapshotStates.deleteForAccount(entry.accountId(), entry.key());
}
return null;
});
} catch (RuntimeException e) {
LOG.warnv(e, "Could not remove the automated snapshot checkpoint of cluster {0} in account {1}",
entry.key(), entry.accountId());
}
}
}
private void runSnapshotSchedule(String accountId, Cluster cluster, Instant now) {
if (!"available".equals(cluster.getClusterStatus()) || cluster.getAutomatedSnapshotRetentionPeriod() == 0) {
return;
}
SnapshotSchedule schedule = cluster.getSnapshotScheduleIdentifier() == null ? null
: snapshotSchedules.getForAccount(accountId, cluster.getSnapshotScheduleIdentifier()).orElseThrow(
() -> new AwsException("SnapshotScheduleNotFound", "The cluster's snapshot schedule is missing", 400));
List<String> definitions = schedule == null ? List.of("rate(8 hours)")
: List.copyOf(schedule.getScheduleDefinitions());
Instant activation = cluster.getAutomatedSnapshotAnchor();
if (schedule != null && schedule.getUpdatedAt() != null
&& (activation == null || schedule.getUpdatedAt().isAfter(activation))) {
activation = schedule.getUpdatedAt();
}
String scheduleKey = cluster.getSnapshotGeneration() + "|" + cluster.getSnapshotScheduleIdentifier()
+ "|" + definitions + "|" + activation;
String clusterId = cluster.getClusterIdentifier();
AutomatedSnapshotState state = automatedSnapshotStates.getForAccount(accountId, clusterId).orElse(null);
if (state == null || !scheduleKey.equals(state.scheduleKey())) {
state = new AutomatedSnapshotState(scheduleKey, activation == null ? now : activation, null);
automatedSnapshotStates.putAllAtomicallyForAccount(accountId, Map.of(clusterId, state));
}
Optional<Instant> due = RedshiftSnapshotSchedule.latestDue(definitions, state.anchor(), now);
if (due.isEmpty()) {
return;
}
Instant scheduled = due.get();
String identity = clusterId + "|" + state.anchor() + "|" + scheduled;
String snapshotId = "rs-auto-" + UUID.nameUUIDFromBytes(identity.getBytes(StandardCharsets.UTF_8));
Instant last = state.lastScheduledTime();
// The checkpoint lives in a separate store, so it can outlive a snapshot whose metadata never reached disk.
if (last != null && (scheduled.isBefore(last)
|| scheduled.equals(last) && snapshots.getForAccount(accountId, snapshotId).isPresent())) {
return;
}
boolean tooSoon = snapshots.scanForAccount(accountId, key -> true).stream()
.filter(snapshot -> "automated".equals(snapshot.getSnapshotType()))
.filter(snapshot -> clusterId.equals(snapshot.getClusterIdentifier()))
.map(Snapshot::getSnapshotCreateTime).filter(time -> time != null)
.anyMatch(time -> time.plus(Duration.ofHours(1)).isAfter(now));
boolean completed = withResourceLock(accountId, "snapshot", snapshotId, () -> {
Snapshot existing = snapshots.getForAccount(accountId, snapshotId).orElse(null);
if (existing == null) {
if (tooSoon) {
return false;
}
createSnapshot(accountId, snapshotId, cluster, null, now, scheduled);
} else if (!"automated".equals(existing.getSnapshotType())
|| !clusterId.equals(existing.getClusterIdentifier()) || !scheduled.equals(existing.getScheduledTime())) {
throw new AwsException("ClusterSnapshotAlreadyExists", "Snapshot identifier is already in use", 400);
}
return true;
});
if (!completed) {
return;
}
automatedSnapshotStates.putAllAtomicallyForAccount(accountId, Map.of(clusterId,
new AutomatedSnapshotState(scheduleKey, state.anchor(), scheduled)));
}
private String snapshotRegion(Cluster cluster) {
return cluster.getSnapshotRegion() == null ? regionResolver.getDefaultRegion() : cluster.getSnapshotRegion();
}
private void expireAutomatedSnapshots(String accountId, String clusterId, Cluster cluster, Instant now) {
List<Snapshot> automated = snapshots.scanForAccount(accountId, key -> true).stream()
.filter(snapshot -> "automated".equals(snapshot.getSnapshotType()))
.filter(snapshot -> clusterId.equals(snapshot.getClusterIdentifier()))
.filter(snapshot -> snapshot.getSnapshotCreateTime() != null).toList();
Snapshot latest = automated.stream().max(Comparator.comparing(Snapshot::getSnapshotCreateTime)
.thenComparing(Snapshot::getSnapshotIdentifier)).orElse(null);
for (Snapshot snapshot : automated) {
boolean replacedCluster = cluster.getSnapshotGeneration() != null
&& !Objects.equals(cluster.getSnapshotGeneration(), snapshot.getClusterGeneration());
if (replacedCluster || cluster.getAutomatedSnapshotRetentionPeriod() == 0 || snapshot != latest
&& !snapshot.getSnapshotCreateTime().plus(Duration.ofDays(cluster.getAutomatedSnapshotRetentionPeriod()))
.isAfter(now)) {
removeAutomatedSnapshot(accountId, snapshot.getSnapshotIdentifier());
}
}
}
private void removeAutomatedSnapshot(String accountId, String snapshotId) {
withResourceLock(accountId, "snapshot", snapshotId, () -> mutate(() -> {
Snapshot current = snapshots.getForAccount(accountId, snapshotId).orElse(null);
if (current == null || !"automated".equals(current.getSnapshotType())) {
return null;
}
snapshots.deleteAllAtomicallyForAccounts(Map.of(accountId, Set.of(snapshotId)));
// Hybrid storage flushes lazily; a crash after the dump is gone would resurrect a dump-less snapshot.
snapshots.flush();
if (current.getSqlDump() != null) {
Path file = Paths.get(current.getSqlDump()).toAbsolutePath().normalize();
if (file.startsWith(accountDumpDir(accountId))) {
try {
Files.deleteIfExists(file);
} catch (IOException e) {
LOG.warnv(e, "Could not delete the dump of automated snapshot {0}", snapshotId);
}
}
}
return null;
}));
}
// The API reference allows only alphanumerics; the management guide's own example uses a hyphen.
private static final Pattern SCHEDULE_IDENTIFIER = Pattern.compile("[A-Za-z0-9-]+");
/**
* Shape check against the Redshift snapshot-schedule documentation: {@code rate(<n> hours|days)}
* with a frequency between once an hour and once a day, or {@code cron(...)} with three to six
* whitespace-separated fields drawn from the documented cron alphabet. Per-field value ranges
* are not checked.
*/
private static boolean isValidScheduleDefinition(String definition) {
if (definition == null) {
return false;
}
Matcher rate = RATE_DEFINITION.matcher(definition);
if (rate.matches()) {
long n = Long.parseLong(rate.group(1).length() > 9 ? "0" : rate.group(1));
return rate.group(2).startsWith("hour") ? n >= 1 && n <= 24 : n == 1;
}
return CRON_DEFINITION.matcher(definition).matches();
}
private static void validateScheduleDefinitions(List<String> definitions) {
if (definitions == null || definitions.isEmpty()) {
throw new AwsException("InvalidSchedule", "ScheduleDefinitions must contain at least one definition.", 400);
}
for (String definition : definitions) {
if (!isValidScheduleDefinition(definition)) {
throw new AwsException("InvalidSchedule", "Invalid schedule definition: " + definition, 400);
}
}
RedshiftSnapshotSchedule.validate(definitions);
}
private SnapshotSchedule requireSnapshotSchedule(String scheduleIdentifier) {
@@ -1996,6 +2221,7 @@ public class RedshiftService implements ManagedSecretRotator {
}
validateScheduleDefinitions(definitions);
SnapshotSchedule schedule = new SnapshotSchedule(id, description, definitions);
schedule.setUpdatedAt(Instant.now());
if (tags != null && !tags.isEmpty()) {
schedule.setTags(new LinkedHashMap<>(tags));
}
@@ -2043,9 +2269,11 @@ public class RedshiftService implements ManagedSecretRotator {
}
public synchronized SnapshotSchedule modifySnapshotSchedule(String scheduleIdentifier, List<String> definitions) {
SnapshotSchedule schedule = requireSnapshotSchedule(scheduleIdentifier);
SnapshotSchedule current = requireSnapshotSchedule(scheduleIdentifier);
validateScheduleDefinitions(definitions);
schedule.setScheduleDefinitions(new ArrayList<>(definitions));
SnapshotSchedule schedule = new SnapshotSchedule(scheduleIdentifier, current.getScheduleDescription(), definitions);
schedule.setTags(new LinkedHashMap<>(current.getTags()));
schedule.setUpdatedAt(Instant.now());
snapshotSchedules.put(scheduleIdentifier, schedule);
snapshotSchedules.flush();
return schedule;
@@ -2080,6 +2308,7 @@ public class RedshiftService implements ManagedSecretRotator {
requireSnapshotSchedule(scheduleIdentifier);
cluster.setSnapshotScheduleIdentifier(scheduleIdentifier);
}
cluster.setAutomatedSnapshotAnchor(Instant.now());
clusters.put(clusterIdentifier, cluster);
clusters.flush();
return cluster;
@@ -0,0 +1,116 @@
package io.github.hectorvent.floci.services.redshift;
import com.cronutils.model.Cron;
import com.cronutils.model.time.ExecutionTime;
import io.github.hectorvent.floci.core.common.AwsCronDefinitions;
import io.github.hectorvent.floci.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;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** Redshift's UTC snapshot rules, including its minute/hour/day-of-week shorthand. */
final class RedshiftSnapshotSchedule {
private static final Pattern RATE = Pattern.compile("rate\\(\\s*(\\d+)\\s+(hours?|days?)\\s*\\)");
private static final Duration MINIMUM_INTERVAL = Duration.ofHours(1);
private RedshiftSnapshotSchedule() { }
static void validate(List<String> definitions) {
try {
if (definitions == null || definitions.isEmpty()) {
throw new IllegalArgumentException("ScheduleDefinitions must contain at least one definition");
}
Instant anchor = Instant.now().truncatedTo(ChronoUnit.DAYS);
List<Rule> rules = definitions.stream().map(RedshiftSnapshotSchedule::parse).toList();
List<Instant> next = new ArrayList<>();
for (Rule rule : rules) {
next.add(rule.next(anchor, anchor).orElse(null));
}
Instant previous = null;
Instant limit = null;
while (true) {
Instant earliest = next.stream().filter(value -> value != null).min(Instant::compareTo).orElse(null);
if (earliest == null || limit != null && earliest.isAfter(limit)) {
break;
}
if (previous != null && Duration.between(previous, earliest).compareTo(MINIMUM_INTERVAL) < 0) {
throw new IllegalArgumentException("Snapshot schedules must be at least one hour apart");
}
if (limit == null) {
limit = earliest.plus(Duration.ofDays(400));
}
previous = earliest;
for (int i = 0; i < rules.size(); i++) {
if (earliest.equals(next.get(i))) {
next.set(i, rules.get(i).next(anchor, earliest).orElse(null));
}
}
}
} catch (IllegalArgumentException e) {
throw new AwsException("InvalidSchedule", "Invalid snapshot schedule: " + e.getMessage(), 400);
}
}
static Optional<Instant> latestDue(List<String> definitions, Instant anchor, Instant now) {
return definitions.stream().map(RedshiftSnapshotSchedule::parse)
.map(rule -> rule.latest(anchor, now)).flatMap(Optional::stream)
.filter(time -> time.isAfter(anchor) && !time.isAfter(now)).max(Instant::compareTo);
}
private static Rule parse(String definition) {
if (definition == null) {
throw new IllegalArgumentException("A schedule definition cannot be null");
}
Matcher rate = RATE.matcher(definition);
if (rate.matches()) {
long value = Long.parseLong(rate.group(1));
boolean days = rate.group(2).startsWith("day");
if (value < 1 || days && value != 1 || !days && value > 24) {
throw new IllegalArgumentException("Snapshot rates must be between one hour and one day");
}
long hours = days ? 24 : value;
return new Rule(Duration.ofHours(hours), null);
}
if (!definition.startsWith("cron(") || !definition.endsWith(")")) {
throw new IllegalArgumentException("Expected rate(...) or cron(...)");
}
String[] fields = definition.substring(5, definition.length() - 1).trim().split("\\s+");
String normalized = switch (fields.length) {
case 3 -> fields[0] + " " + fields[1] + " ? * " + fields[2] + " *";
case 6 -> String.join(" ", fields);
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));
}
private record Rule(Duration rate, ExecutionTime cron) {
Optional<Instant> latest(Instant anchor, Instant now) {
if (rate != null) {
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());
}
Optional<Instant> next(Instant anchor, Instant after) {
if (rate != null) {
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());
}
}
}
@@ -0,0 +1,96 @@
package io.github.hectorvent.floci.services.redshift;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.Resettable;
import io.quarkus.runtime.ShutdownEvent;
import io.quarkus.runtime.StartupEvent;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Instant;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
/** Drives automated snapshots outside AWS request threads. */
@ApplicationScoped
public class RedshiftSnapshotScheduler implements Resettable {
private static final Logger LOG = Logger.getLogger(RedshiftSnapshotScheduler.class);
private final RedshiftService service;
private final ScheduledExecutorService executor;
private final long intervalSeconds;
private final ReentrantLock sweepLock = new ReentrantLock();
private volatile boolean paused;
@Inject
public RedshiftSnapshotScheduler(RedshiftService service, EmulatorConfig config) {
this.service = service;
this.intervalSeconds = Math.max(1, config.services().redshift().snapshotSweepIntervalSeconds());
this.executor = config.services().redshift().enabled() && config.services().redshift().automatedSnapshotsEnabled()
? Executors.newSingleThreadScheduledExecutor(task -> {
Thread thread = new Thread(task, "redshift-snapshot-scheduler");
thread.setDaemon(true);
return thread;
}) : null;
}
void onStart(@Observes StartupEvent ignored) {
if (executor != null) {
executor.scheduleWithFixedDelay(this::tickSafely, intervalSeconds, intervalSeconds, TimeUnit.SECONDS);
}
}
void onStop(@Observes ShutdownEvent ignored) {
if (executor != null) {
executor.shutdownNow();
try {
if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
LOG.warn("Redshift snapshot scheduler is still finishing a dump during shutdown");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
LOG.debugv(e, "Interrupted while stopping the Redshift snapshot scheduler");
}
}
}
public void tick(Instant now) {
sweepLock.lock();
try {
if (!paused) {
service.runSnapshotSchedules(now);
}
} finally {
sweepLock.unlock();
}
}
/** Drains a running sweep so it cannot write old snapshots back into storage that reset is about to clear. */
@Override
public void beforeReset() {
paused = true;
sweepLock.lock();
sweepLock.unlock();
}
@Override
public void clear() {
// Snapshot state lives in RedshiftService storage, which reset wipes.
}
@Override
public void afterReset() {
paused = false;
}
private void tickSafely() {
try {
tick(Instant.now());
} catch (RuntimeException e) {
LOG.warnv(e, "Redshift automated snapshot sweep failed");
}
}
}
@@ -0,0 +1,9 @@
package io.github.hectorvent.floci.services.redshift.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
/** Restart checkpoint for a cluster's currently effective snapshot rules. */
@RegisterForReflection
public record AutomatedSnapshotState(String scheduleKey, Instant anchor, Instant lastScheduledTime) { }
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.redshift.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
@@ -90,6 +91,22 @@ public class Cluster {
private Integer snapshotCopyManualRetentionPeriod;
private String snapshotCopyGrantName;
private String snapshotScheduleIdentifier;
private Instant automatedSnapshotAnchor;
private String snapshotRegion;
private Integer automatedSnapshotRetentionPeriod;
private String snapshotGeneration;
public String getSnapshotGeneration() { return snapshotGeneration; }
public void setSnapshotGeneration(String value) { snapshotGeneration = value; }
public Instant getAutomatedSnapshotAnchor() { return automatedSnapshotAnchor; }
public void setAutomatedSnapshotAnchor(Instant value) { automatedSnapshotAnchor = value; }
public String getSnapshotRegion() { return snapshotRegion; }
public void setSnapshotRegion(String value) { snapshotRegion = value; }
public int getAutomatedSnapshotRetentionPeriod() {
return automatedSnapshotRetentionPeriod == null ? 1 : automatedSnapshotRetentionPeriod;
}
public void setAutomatedSnapshotRetentionPeriod(Integer value) { automatedSnapshotRetentionPeriod = value; }
public String getSnapshotCopyDestinationRegion() { return snapshotCopyDestinationRegion; }
public void setSnapshotCopyDestinationRegion(String snapshotCopyDestinationRegion) { this.snapshotCopyDestinationRegion = snapshotCopyDestinationRegion; }
@@ -18,6 +18,20 @@ public class Snapshot {
private String snapshotArn;
private Instant snapshotCreateTime;
private Integer manualSnapshotRetentionPeriod;
private String snapshotType;
private Integer automatedSnapshotRetentionPeriod;
private Instant scheduledTime;
private String clusterGeneration;
public String getClusterGeneration() { return clusterGeneration; }
public void setClusterGeneration(String value) { clusterGeneration = value; }
public String getSnapshotType() { return snapshotType == null ? "manual" : snapshotType; }
public void setSnapshotType(String value) { snapshotType = value; }
public Integer getAutomatedSnapshotRetentionPeriod() { return automatedSnapshotRetentionPeriod; }
public void setAutomatedSnapshotRetentionPeriod(Integer value) { automatedSnapshotRetentionPeriod = value; }
public Instant getScheduledTime() { return scheduledTime; }
public void setScheduledTime(Instant value) { scheduledTime = value; }
public Snapshot() {}
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.redshift.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
@@ -17,6 +18,10 @@ public class SnapshotSchedule {
private String scheduleDescription;
private List<String> scheduleDefinitions = new ArrayList<>();
private Map<String, String> tags = new LinkedHashMap<>();
private Instant updatedAt;
public Instant getUpdatedAt() { return updatedAt; }
public void setUpdatedAt(Instant value) { updatedAt = value; }
public SnapshotSchedule() {}