feat(redshift-serverless): expire snapshots after their retention period (#6966)

* feat(redshift-serverless): expire snapshots after their retention period

* fix(redshift-serverless): stop the snapshot expiration worker before storage closes

* fix(redshift-serverless): mark pending snapshot cleanup DELETED and test the sweep lock without timing

* refactor(redshift-serverless): run snapshot expiration on a shared sweep worker
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-29 23:29:50 -04:00
1 parent 9c00c8c70e
commit 80edd853de
14 files changed
+958 -3

No files matched your search

@@ -1909,6 +1909,12 @@ public interface EmulatorConfig {
@WithDefault("true")
boolean enabled();
@WithDefault("true")
boolean snapshotExpirationEnabled();
@WithDefault("60")
int snapshotExpirationSweepIntervalSeconds();
@WithDefault("true")
boolean scheduledActionsEnabled();
@@ -0,0 +1,109 @@
package io.github.hectorvent.floci.core.common;
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;
import java.util.function.Consumer;
/**
* Runs a periodic sweep on its own daemon thread, one sweep at a time. A service owns one worker and
* forwards its startup, shutdown and reset events to it; the worker has no CDI wiring of its own.
*/
public final class SweepWorker {
private static final Logger LOG = Logger.getLogger(SweepWorker.class);
private final String name;
private final Consumer<Instant> sweep;
private final long intervalSeconds;
private final boolean sweepAtStart;
private final ScheduledExecutorService executor;
private final ReentrantLock sweepLock = new ReentrantLock();
private volatile boolean paused;
/**
* @param name display name used in the thread name and log messages
* @param enabled whether a background thread exists; a disabled worker still runs {@link #tick}
* @param intervalSeconds delay between sweeps, at least one second
* @param sweepAtStart whether the first sweep runs at startup, not after one interval
* @param sweep the work, run under the sweep lock and skipped while paused
*/
public SweepWorker(String name, boolean enabled, long intervalSeconds, boolean sweepAtStart,
Consumer<Instant> sweep) {
this.name = name;
this.sweep = sweep;
this.intervalSeconds = Math.max(1, intervalSeconds);
this.sweepAtStart = sweepAtStart;
this.executor = enabled
? Executors.newSingleThreadScheduledExecutor(task -> {
Thread thread = new Thread(task, name);
thread.setDaemon(true);
return thread;
}) : null;
}
public void start() {
if (executor != null) {
executor.scheduleWithFixedDelay(this::tickSafely, sweepAtStart ? 0 : intervalSeconds, intervalSeconds, TimeUnit.SECONDS);
}
}
/** Interrupts a running sweep and waits briefly for it to end. */
public void stop() {
if (executor == null) {
return;
}
executor.shutdownNow();
try {
if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
LOG.warnv("The {0} worker is still finishing a sweep during shutdown", name);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
LOG.debugv(e, "Interrupted while stopping the {0} worker", name);
}
}
/** Whether a background thread exists, which the owner's configuration switches decide. */
public boolean active() {
return executor != null;
}
public void tick(Instant now) {
sweepLock.lock();
try {
if (!paused) {
sweep.accept(now);
}
} finally {
sweepLock.unlock();
}
}
/** Stops new sweeps and waits for a running one, so it cannot write into storage that reset is about to clear. */
public void pause() {
paused = true;
sweepLock.lock();
sweepLock.unlock();
}
public void resume() {
paused = false;
}
/** Threads waiting for the running sweep, which lets tests observe blocking without timing. */
public int queuedSweeps() {
return sweepLock.getQueueLength();
}
private void tickSafely() {
try {
tick(Instant.now());
} catch (RuntimeException e) {
LOG.warnv(e, "The {0} sweep failed", name);
}
}
}
@@ -17,6 +17,7 @@ import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
/**
* Resource policies for Redshift Serverless snapshots. A policy is stored and echoed, not
@@ -47,6 +48,9 @@ public class RedshiftServerlessResourcePolicyService implements Resettable {
requireJsonObject(policy);
RedshiftServerlessSnapshot snapshot = findSnapshot(resourceArn, region)
.orElseThrow(() -> ServerlessSupport.notFound("The resource " + resourceArn + " was not found."));
if (!"AVAILABLE".equals(snapshot.getStatus())) {
throw ServerlessSupport.conflict("The snapshot is not available.");
}
ResourcePolicy stored = new ResourcePolicy(resourceArn, policy);
stored.setSnapshotCreateTime(snapshot.getSnapshotCreateTime());
policies.put(storageKey(region, resourceArn), stored);
@@ -63,6 +67,17 @@ public class RedshiftServerlessResourcePolicyService implements Resettable {
policies.delete(storageKey(region, resourceArn));
}
synchronized void deleteExpiredSnapshotPolicy(
AccountAwareStorageBackend.AccountEntry<RedshiftServerlessSnapshot> entry) {
RedshiftServerlessSnapshot snapshot = entry.value();
String region = entry.key().substring(0, entry.key().indexOf("::"));
String key = storageKey(region, snapshot.getSnapshotArn());
policies.getForAccountMigratingLegacy(entry.accountId(), key,
legacy -> policies.getLegacyForAccount(entry.accountId(), key).isPresent())
.filter(policy -> Objects.equals(policy.getSnapshotCreateTime(), snapshot.getSnapshotCreateTime()))
.ifPresent(policy -> policies.deleteAllAtomicallyForAccounts(Map.of(entry.accountId(), Set.of(key))));
}
@Override
public void clear() {
policies.clear();
@@ -31,6 +31,7 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
@@ -564,9 +565,13 @@ public class RedshiftServerlessService implements Resettable {
/** Absolute, normalised {@code <persistentPath>/redshift-serverless-dumps/<accountId>/<region>} directory. */
private Path dumpDir(String region) {
return dumpDir(workgroups.accountId(), region);
}
private Path dumpDir(String accountId, String region) {
return Paths.get(config.storage().persistentPath())
.resolve("redshift-serverless-dumps")
.resolve(workgroups.accountId())
.resolve(accountId)
.resolve(region)
.toAbsolutePath()
.normalize();
@@ -649,6 +654,7 @@ public class RedshiftServerlessService implements Resettable {
public synchronized RedshiftServerlessSnapshot updateSnapshot(String snapshotName, Integer retentionPeriod,
String region) {
RedshiftServerlessSnapshot snapshot = new RedshiftServerlessSnapshot(getSnapshot(snapshotName, region));
requireAvailableSnapshot(snapshot);
if (retentionPeriod != null) {
snapshot.setRetentionPeriod(validateRetentionPeriod(retentionPeriod));
snapshots.put(storageKey(region, snapshotName), snapshot);
@@ -658,11 +664,70 @@ public class RedshiftServerlessService implements Resettable {
public synchronized RedshiftServerlessSnapshot deleteSnapshot(String snapshotName, String region) {
RedshiftServerlessSnapshot deleted = getSnapshot(snapshotName, region);
requireAvailableSnapshot(deleted);
snapshots.delete(storageKey(region, snapshotName));
trustedDump(deleted, region).ifPresent(RedshiftServerlessService::deleteDumpQuietly);
return deleted;
}
/** The monitor also protects restore, retention changes and snapshot creation from cleanup. */
synchronized void expireSnapshots(Instant now,
Consumer<AccountAwareStorageBackend.AccountEntry<RedshiftServerlessSnapshot>> deletePolicy) {
for (AccountAwareStorageBackend.AccountEntry<RedshiftServerlessSnapshot> entry
: snapshots.scanAllAccountEntries(key -> true)) {
try {
// The scan assigns unprefixed entries to the default account; never claim them for another account.
RedshiftServerlessSnapshot snapshot = snapshots.getForAccountMigratingLegacy(
entry.accountId(), entry.key(), legacy -> snapshots
.getLegacyForAccount(entry.accountId(), entry.key()).isPresent())
.orElse(null);
if (snapshot == null || !isExpired(snapshot, now)) {
continue;
}
RedshiftServerlessSnapshot deleting = new RedshiftServerlessSnapshot(snapshot);
deleting.setStatus("DELETED");
snapshots.putAllAtomicallyForAccount(entry.accountId(), Map.of(entry.key(), deleting));
deleteExpiredDump(deleting, entry.accountId(), regionOf(entry.key()));
deletePolicy.accept(new AccountAwareStorageBackend.AccountEntry<>(
entry.accountId(), entry.key(), deleting));
snapshots.deleteAllAtomicallyForAccounts(Map.of(entry.accountId(), Set.of(entry.key())));
} catch (IOException | RuntimeException e) {
LOG.warnv(e, "Could not expire Redshift Serverless snapshot {0} for account {1}; will retry",
entry.key(), entry.accountId());
}
}
}
private static boolean isExpired(RedshiftServerlessSnapshot snapshot, Instant now) {
if ("DELETED".equals(snapshot.getStatus())) {
return true;
}
Integer retention = snapshot.getRetentionPeriod();
return "AVAILABLE".equals(snapshot.getStatus()) && retention != null && retention > 0
&& snapshot.getSnapshotCreateTime() != null
&& !now.isBefore(snapshot.getSnapshotCreateTime().plus(retention, ChronoUnit.DAYS));
}
private void deleteExpiredDump(RedshiftServerlessSnapshot snapshot, String accountId, String region)
throws IOException {
String stored = snapshot.getSqlDump();
if (stored == null || stored.isBlank()) {
return;
}
Path dump = Paths.get(stored).toAbsolutePath().normalize();
Path directory = dumpDir(accountId, region);
if (!dump.startsWith(directory) || dump.equals(directory)) {
throw new IOException("Snapshot dump is outside its account and Region directory: " + dump);
}
Files.deleteIfExists(dump);
}
private static void requireAvailableSnapshot(RedshiftServerlessSnapshot snapshot) {
if (!"AVAILABLE".equals(snapshot.getStatus())) {
throw ServerlessSupport.conflict("The snapshot " + snapshot.getSnapshotName() + " is not available.");
}
}
/**
* Lists the Region's snapshots, narrowed by every filter that is supplied: the namespace by
* name or ARN, the owning account, and a creation-time window that includes both ends.
@@ -704,6 +769,7 @@ public class RedshiftServerlessService implements Resettable {
validateManagedPassword(manageAdminPassword, null, adminPasswordSecretKmsKeyId);
validateNamespaceName(namespaceName);
RedshiftServerlessSnapshot snapshot = getSnapshot(snapshotName, region);
requireAvailableSnapshot(snapshot);
if (ownerAccount != null && !ownerAccount.isBlank() && !ownerAccount.equals(snapshot.getOwnerAccount())) {
throw snapshotNotFound(snapshotName);
}
@@ -0,0 +1,64 @@
package io.github.hectorvent.floci.services.redshiftserverless;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.common.SweepWorker;
import io.quarkus.runtime.ShutdownEvent;
import io.quarkus.runtime.StartupEvent;
import jakarta.annotation.Priority;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import java.time.Instant;
/** Drives Serverless snapshot expirations outside AWS request threads, one sweep at a time. */
@ApplicationScoped
public class RedshiftServerlessSnapshotExpirationScheduler implements Resettable {
private final SweepWorker worker;
@Inject
public RedshiftServerlessSnapshotExpirationScheduler(RedshiftServerlessService service,
RedshiftServerlessResourcePolicyService policies,
EmulatorConfig config) {
EmulatorConfig.RedshiftServerlessServiceConfig serverless = config.services().redshiftServerless();
this.worker = new SweepWorker("redshift-serverless-snapshot-expiration",
serverless.enabled() && serverless.snapshotExpirationEnabled(),
serverless.snapshotExpirationSweepIntervalSeconds(), true,
now -> service.expireSnapshots(now, policies::deleteExpiredSnapshotPolicy));
}
void onStart(@Observes StartupEvent ignored) {
worker.start();
}
// Priority below APPLICATION (2000) so the worker drains before EmulatorLifecycle.onStop flushes storage.
void onStop(@Observes @Priority(1000) ShutdownEvent ignored) {
worker.stop();
}
/** Whether a background worker exists, which the two configuration switches decide. */
boolean active() {
return worker.active();
}
public void tick(Instant now) {
worker.tick(now);
}
/** Drains a running sweep so it cannot write a snapshot back into storage that reset is about to clear. */
@Override
public void beforeReset() {
worker.pause();
}
@Override
public void clear() {
// Snapshot state lives in RedshiftServerlessService storage, which reset wipes.
}
@Override
public void afterReset() {
worker.resume();
}
}