feat(redshift): support pausing and resuming provisioned clusters (#6911)

* feat(redshift): support pausing and resuming provisioned clusters

* docs(redshift): sync supported operation count

* fix(redshift): harden pause and resume failure recovery

* fix(redshift): skip unchanged idle integration writes

* fix: consolidate Redshift pause and resume state persistence
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-29 12:55:50 -04:00
1 parent 85813108c1
commit 1a871392b7
12 files changed
+842 -17

No files matched your search

@@ -134,6 +134,9 @@ public class RedshiftDynamoDbZeroEtlConsumer implements Resettable {
}
private void poll(Integration integration) {
if (targetPaused(integration)) {
return;
}
writer.createLandingTable(integration.getAccountId(), integration.getTargetClusterIdentifier(),
integration.getLandingTableName());
if (!integration.isBackfillCompleted()) {
@@ -145,8 +148,28 @@ public class RedshiftDynamoDbZeroEtlConsumer implements Resettable {
ignored -> ConcurrentHashMap.newKeySet());
// ponytail: a shard whose read or write throws ends the tick for the shards after it; the next
// tick starts over from committed progress, so it only delays them.
boolean checkpointPersisted = false;
for (DynamoDbStreamReader.Shard shard : DynamoDbStreamReader.readable(streamReader.shards(stream), finished)) {
pollShard(integration, stream, shard.shardId(), finished);
if (pollShard(integration, stream, shard.shardId(), finished)) {
checkpointPersisted = true;
}
}
if (!checkpointPersisted) {
redshiftService.recoverIntegrationRuntime(integration.getAccountId(), integration.getIntegrationArn());
}
}
private boolean targetPaused(Integration integration) {
try {
return redshiftService.describeClustersForAccount(integration.getAccountId(),
integration.getTargetClusterIdentifier()).stream()
.anyMatch(cluster -> "paused".equals(cluster.getClusterStatus()));
} catch (AwsException expected) {
if (!"ClusterNotFound".equals(expected.getErrorCode())) {
throw expected;
}
// A missing target is a polling failure, not an intentional pause; let the writer report it.
return false;
}
}
@@ -154,7 +177,7 @@ public class RedshiftDynamoDbZeroEtlConsumer implements Resettable {
* Writes one batch after the shard's committed sequence and commits it only once written, so a
* failed write is read and written again next poll.
*/
private void pollShard(Integration integration, DynamoDbStreamReader.Stream stream, String shardId,
private boolean pollShard(Integration integration, DynamoDbStreamReader.Stream stream, String shardId,
Set<String> finished) {
Map<String, String> committed = integration.getShardSequenceNumbers();
DynamoDbStreamReader.RecordsPage page;
@@ -171,7 +194,7 @@ public class RedshiftDynamoDbZeroEtlConsumer implements Resettable {
if (page.closed()) {
finished.add(shardId);
}
return;
return false;
}
writer.writeBatch(integration.getAccountId(), integration.getTargetClusterIdentifier(),
integration.getLandingTableName(),
@@ -179,6 +202,7 @@ public class RedshiftDynamoDbZeroEtlConsumer implements Resettable {
committed.put(shardId, records.get(records.size() - 1).sequenceNumber());
redshiftService.updateIntegrationRuntime(integration.getAccountId(), integration.getIntegrationArn(),
committed, true, null);
return true;
}
private void pollBackfillPage(Integration integration) {
@@ -351,10 +375,14 @@ public class RedshiftDynamoDbZeroEtlConsumer implements Resettable {
try {
unlessQuiesced(submittedAt, () -> poll(integration));
} catch (Exception e) {
LOG.warnv(e, "Zero-ETL polling failed for integration {0}", integration.getIntegrationArn());
try {
unlessQuiesced(submittedAt, () -> redshiftService.updateIntegrationRuntime(integration.getAccountId(),
integration.getIntegrationArn(), integration.getShardSequenceNumbers(), false, e.getMessage()));
unlessQuiesced(submittedAt, () -> {
if (!targetPaused(integration)) {
LOG.warnv(e, "Zero-ETL polling failed for integration {0}", integration.getIntegrationArn());
redshiftService.updateIntegrationRuntime(integration.getAccountId(), integration.getIntegrationArn(),
integration.getShardSequenceNumbers(), false, e.getMessage());
}
});
} catch (Exception updateError) {
LOG.warnv(updateError, "Could not persist zero-ETL failure for integration {0}",
integration.getIntegrationArn());
@@ -924,6 +924,22 @@ public class RedshiftQueryHandler {
String clusterIdentifier = requireParam(params, "ClusterIdentifier");
return loggingStatusResponse(action, service.disableLogging(clusterIdentifier));
}
case "PauseCluster", "ResumeCluster" -> {
String clusterIdentifier = requireParam(params, "ClusterIdentifier");
Cluster cluster = "PauseCluster".equals(action)
? service.pauseCluster(clusterIdentifier) : service.resumeCluster(clusterIdentifier);
String xml = new XmlBuilder()
.start(action + "Response", AwsNamespaces.REDSHIFT)
.start(action + "Result")
.raw(buildClusterXml(cluster))
.end(action + "Result")
.start("ResponseMetadata")
.elem("RequestId", "test-req-id")
.end("ResponseMetadata")
.end(action + "Response")
.build();
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
}
case "RebootCluster" -> {
String clusterIdentifier = params.getFirst("ClusterIdentifier");
if (clusterIdentifier == null || clusterIdentifier.isBlank()) {
@@ -249,8 +249,15 @@ public class RedshiftService implements ManagedSecretRotator {
// Recreate Docker containers for persisted clusters on app restart (across every account, not just default)
void onStart(@Observes StartupEvent event) {
List<AccountAwareStorageBackend.AccountEntry<Cluster>> persistedClusters =
clusters.scanAllAccountEntries(k -> true);
for (AccountAwareStorageBackend.AccountEntry<Cluster> entry : persistedClusters) {
if (entry.value().getProxyPort() > 0) {
usedPorts.add(entry.value().getProxyPort());
}
}
List<AccountAwareStorageBackend.AccountEntry<Cluster>> availableClusters =
clusters.scanAllAccountEntries(k -> true).stream()
persistedClusters.stream()
.filter(entry -> "available".equals(entry.value().getClusterStatus()))
.toList();
for (AccountAwareStorageBackend.AccountEntry<Cluster> entry : availableClusters) {
@@ -697,22 +704,39 @@ public class RedshiftService implements ManagedSecretRotator {
public void updateIntegrationRuntime(String accountId, String integrationArn,
Map<String, String> shardSequenceNumbers,
boolean successful, String error) {
updateIntegrationRuntimeLocked(accountId, integrationArn, shardSequenceNumbers, successful, error);
updateIntegrationRuntimeLocked(accountId, integrationArn, shardSequenceNumbers, successful, error, false);
publishIntegrationEvents();
}
/** Recovers idle polling health without replacing checkpoints or persisting unchanged state. */
public void recoverIntegrationRuntime(String accountId, String integrationArn) {
updateIntegrationRuntimeLocked(accountId, integrationArn, null, true, null, true);
publishIntegrationEvents();
}
private synchronized void updateIntegrationRuntimeLocked(String accountId, String integrationArn,
Map<String, String> shardSequenceNumbers,
boolean successful, String error) {
boolean successful, String error, boolean recoveryOnly) {
for (String key : integrations.keysForAccount(accountId)) {
Optional<Integration> stored = integrations.getForAccount(accountId, key);
if (stored.isEmpty() || !integrationArn.equals(stored.get().getIntegrationArn())) {
continue;
}
Integration integration = stored.get();
String targetIdentifier = integration.getTargetClusterIdentifier();
if (!successful && targetIdentifier != null && clusters.getForAccount(accountId, targetIdentifier)
.filter(cluster -> "paused".equals(cluster.getClusterStatus())).isPresent()) {
return;
}
String previousStatus = integration.getStatus();
if (recoveryOnly && "active".equals(previousStatus)
&& integration.getRetryCount() == 0 && integration.getLastError() == null) {
return;
}
if (successful) {
integration.setShardSequenceNumbers(shardSequenceNumbers);
if (!recoveryOnly) {
integration.setShardSequenceNumbers(shardSequenceNumbers);
}
integration.setRetryCount(0);
integration.setLastError(null);
integration.setStatus("active");
@@ -1004,6 +1028,7 @@ public class RedshiftService implements ManagedSecretRotator {
Integer automatedRetention) {
Cluster cluster = clusters.get(clusterIdentifier)
.orElseThrow(() -> new AwsException("ClusterNotFound", "Cluster " + clusterIdentifier + " not found", 404));
rejectPausedCluster(cluster);
validateAutomatedRetention(nodeType == null ? cluster.getNodeType() : nodeType,
automatedRetention == null ? cluster.getAutomatedSnapshotRetentionPeriod() : automatedRetention);
@@ -1314,6 +1339,126 @@ public class RedshiftService implements ManagedSecretRotator {
return cluster;
}
public Cluster pauseCluster(String clusterIdentifier) {
return mutateCluster(clusterIdentifier, () -> {
Cluster cluster = clusterInState(clusterIdentifier, "available");
if (cluster.getAutomatedSnapshotRetentionPeriod() == 0) {
throw new AwsException("InvalidClusterState",
"Clusters with automated snapshots disabled cannot be paused", 400);
}
String accountId = clusters.accountId();
try {
proxyManager.stopProxy(relayKey(accountId, clusterIdentifier));
} catch (RuntimeException failure) {
LOG.warnv(failure, "Failed to stop auth proxy while pausing cluster {0}", clusterIdentifier);
persistClusterWithoutBackend(cluster, "unavailable");
throw new AwsException("InternalFailure", "Failed to stop auth proxy for cluster "
+ clusterIdentifier, 500);
}
try {
containerManager.pause(accountId, clusterIdentifier);
persistClusterWithoutBackend(cluster, "paused");
return cluster;
} catch (RuntimeException failure) {
boolean restored = false;
try {
RedshiftContainerHandle handle = containerManager.resume(accountId, clusterIdentifier,
cluster.getMasterUsername(), CLUSTER_DB_NAME);
startResumedProxy(accountId, cluster, handle);
cluster.setClusterStatus("available");
restored = true;
} catch (RuntimeException rollbackFailure) {
LOG.warnv(rollbackFailure, "Failed to restore cluster {0} after unsuccessful pause", clusterIdentifier);
}
if (restored) {
clusters.put(clusterIdentifier, cluster);
clusters.flush();
} else {
persistClusterWithoutBackend(cluster, "unavailable");
}
LOG.warnv(failure, "Failed to pause Redshift cluster {0}", clusterIdentifier);
throw new AwsException("InternalFailure", "Failed to pause cluster " + clusterIdentifier, 500);
}
});
}
public Cluster resumeCluster(String clusterIdentifier) {
return mutateCluster(clusterIdentifier, () -> {
Cluster cluster = clusterInState(clusterIdentifier, "paused");
String accountId = clusters.accountId();
try {
RedshiftContainerHandle handle = containerManager.resume(accountId, clusterIdentifier,
cluster.getMasterUsername(), CLUSTER_DB_NAME);
startResumedProxy(accountId, cluster, handle);
cluster.setClusterStatus("available");
clusters.put(clusterIdentifier, cluster);
clusters.flush();
registerAuditLogging(accountId, cluster);
return cluster;
} catch (RuntimeException failure) {
cluster.setClusterStatus("paused");
try {
proxyManager.stopProxy(relayKey(accountId, clusterIdentifier));
} catch (RuntimeException rollbackFailure) {
LOG.warnv(rollbackFailure, "Failed to stop proxy during resume rollback for cluster {0}", clusterIdentifier);
cluster.setClusterStatus("unavailable");
}
try {
containerManager.pause(accountId, clusterIdentifier);
} catch (RuntimeException rollbackFailure) {
LOG.warnv(rollbackFailure, "Failed to return cluster {0} to paused state", clusterIdentifier);
cluster.setClusterStatus("unavailable");
}
persistClusterWithoutBackend(cluster, cluster.getClusterStatus());
if (failure instanceof AwsException awsFailure) {
throw awsFailure;
}
LOG.warnv(failure, "Failed to resume Redshift cluster {0}", clusterIdentifier);
throw new AwsException("InternalFailure", "Failed to resume cluster " + clusterIdentifier, 500);
}
});
}
private void persistClusterWithoutBackend(Cluster cluster, String status) {
cluster.setClusterStatus(status);
cluster.setContainerHost(null);
cluster.setContainerPort(0);
clusters.put(cluster.getClusterIdentifier(), cluster);
clusters.flush();
}
private Cluster clusterInState(String identifier, String requiredState) {
Cluster cluster = clusters.get(identifier).orElseThrow(() ->
new AwsException("ClusterNotFound", "Cluster " + identifier + " not found", 404));
if (!requiredState.equals(cluster.getClusterStatus())) {
throw new AwsException("InvalidClusterState", "Cluster " + identifier
+ " must be " + requiredState + " for this operation", 400);
}
return cluster;
}
private static void rejectPausedCluster(Cluster cluster) {
if ("paused".equals(cluster.getClusterStatus())) {
throw new AwsException("InvalidClusterState", "Cluster " + cluster.getClusterIdentifier()
+ " must be resumed before this operation", 400);
}
}
private void startResumedProxy(String accountId, Cluster cluster, RedshiftContainerHandle handle) {
int port = cluster.getProxyPort() > 0 ? cluster.getProxyPort() : allocateProxyPort();
usedPorts.add(port);
cluster.setProxyPort(port);
Endpoint endpoint = cluster.getEndpoint() != null ? cluster.getEndpoint() : proxyEndpoint(port);
String password = cluster.getMasterPassword() != null ? cluster.getMasterPassword() : "admin";
proxyManager.startProxy(relayKey(accountId, cluster.getClusterIdentifier()), port,
handle.getHost(), handle.getPort(), endpoint.getAddress(), cluster.getMasterUsername(), password,
CLUSTER_DB_NAME, passwordValidatorFor(accountId, cluster.getClusterIdentifier()),
cluster.getIamRoleArns(), cluster.getDefaultIamRoleArn());
cluster.setContainerHost(handle.getHost());
cluster.setContainerPort(handle.getPort());
cluster.setEndpoint(endpoint);
}
public Cluster rebootCluster(String clusterIdentifier) {
return mutateCluster(clusterIdentifier, () -> rebootClusterLocked(clusterIdentifier));
}
@@ -1321,6 +1466,7 @@ public class RedshiftService implements ManagedSecretRotator {
private Cluster rebootClusterLocked(String clusterIdentifier) {
Cluster cluster = clusters.get(clusterIdentifier)
.orElseThrow(() -> new AwsException("ClusterNotFound", "Cluster " + clusterIdentifier + " not found", 404));
rejectPausedCluster(cluster);
// Replacement containers do not reattach the old anonymous volume, so a plain stop+recreate
// would silently drop the cluster's data. Dump before stopping and
@@ -1473,6 +1619,7 @@ public class RedshiftService implements ManagedSecretRotator {
private Snapshot createSnapshot(String accountId, String snapshotIdentifier, Cluster cluster,
Integer retentionPeriod, Instant now, Instant scheduledTime) {
rejectPausedCluster(cluster);
validateSnapshotIdentifier(snapshotIdentifier);
String clusterIdentifier = cluster.getClusterIdentifier();
if ((scheduledTime == null ? snapshots.get(snapshotIdentifier)
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.redshift.container;
import com.github.dockerjava.api.exception.NotModifiedException;
import com.github.dockerjava.api.model.Container;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
@@ -112,7 +113,7 @@ public class RedshiftContainerManager {
ContainerSpec spec = specBuilder.build();
ContainerInfo info = lifecycleManager.createAndStartEphemeral(spec);
return initializeAndRegisterHandle(info, accountId, clusterIdentifier, masterUsername, containerName, enginePort,
effectiveDb);
effectiveDb, true);
}
/**
@@ -145,15 +146,48 @@ public class RedshiftContainerManager {
return start(accountId, clusterIdentifier, masterUsername, masterPassword, databaseName, nodeType);
}
return adoptExisting(accountId, clusterIdentifier, masterUsername, databaseName, existing.get(), true);
}
/** Stops PostgreSQL without removing its container or data volume. Docker failures propagate. */
public void pause(String accountId, String clusterIdentifier) {
String key = containerKey(accountId, clusterIdentifier);
RedshiftContainerHandle handle = containers.get(key);
String id = handle == null ? containerName(accountId, clusterIdentifier) : handle.getContainerId();
try {
lifecycleManager.getDockerClient().stopContainerCmd(id).withTimeout(30).exec();
} catch (NotModifiedException alreadyStopped) {
LOG.debugv("Redshift container {0} was already stopped", id);
}
if (handle != null && handle.getLogStream() != null) {
lifecycleManager.closeLogStreamAfterContainerStop(handle.getLogStream());
handle.setLogStream(null);
}
containers.remove(key);
}
/** Resumes only the existing data-bearing container; never creates an empty replacement. */
public RedshiftContainerHandle resume(String accountId, String clusterIdentifier,
String masterUsername, String databaseName) {
Container existing = lifecycleManager.findByName(containerName(accountId, clusterIdentifier))
.orElseThrow(() -> new AwsException("InvalidClusterState",
"The paused container for cluster " + clusterIdentifier + " no longer exists", 400));
return adoptExisting(accountId, clusterIdentifier, masterUsername, databaseName, existing, false);
}
private RedshiftContainerHandle adoptExisting(String accountId, String clusterIdentifier,
String masterUsername, String databaseName, Container existing,
boolean bootstrap) {
String containerName = containerName(accountId, clusterIdentifier);
String effectiveDb = (databaseName != null && !databaseName.isBlank()) ? databaseName : DEFAULT_DATABASE;
adoptedContainers.put(containerKey(accountId, clusterIdentifier), existing.get().getId());
adoptedContainers.put(containerKey(accountId, clusterIdentifier), existing.getId());
LOG.infov("Adopting existing container {0} for cluster {1} to avoid discarding its data",
containerName, clusterIdentifier);
int enginePort = 5432;
ContainerInfo info = lifecycleManager.adopt(existing.get().getId(), List.of(enginePort),
ContainerInfo info = lifecycleManager.adopt(existing.getId(), List.of(enginePort),
containerBuilder.resolveDockerNetwork(config.services().redshift().dockerNetwork()));
return initializeAndRegisterHandle(info, accountId, clusterIdentifier, masterUsername, containerName, enginePort,
effectiveDb);
effectiveDb, bootstrap);
}
static int maxConnections(String clusterIdentifier, String nodeType) {
@@ -180,7 +214,7 @@ public class RedshiftContainerManager {
String masterUsername,
String containerName,
int enginePort,
String databaseName) {
String databaseName, boolean bootstrap) {
EndpointInfo endpoint = info.getEndpoint(enginePort);
RedshiftContainerHandle handle = new RedshiftContainerHandle(
info.containerId(), clusterIdentifier, endpoint.host(), endpoint.port());
@@ -199,7 +233,9 @@ public class RedshiftContainerManager {
try {
waitForReady(containerName, info.containerId(), masterUsername, databaseName);
bootstrapCatalog(info.containerId(), masterUsername, databaseName);
if (bootstrap) {
bootstrapCatalog(info.containerId(), masterUsername, databaseName);
}
} catch (RuntimeException e) {
containers.put(containerKey(accountId, clusterIdentifier), handle);
throw e;