feat(redshift): create final snapshots before deleting clusters (#6346)

* feat(redshift): create final snapshots before deleting clusters

* fix(redshift): clean failed dumps and scope snapshot locking

* fix(redshift): default manual snapshot retention and fix Spectrum cleanup
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-23 14:06:47 -04:00
1 parent 1f31f5bf48
commit 1b8548a0af
14 files changed
+923 -37

No files matched your search

@@ -139,7 +139,12 @@ public class RedshiftQueryHandler {
}
case "DeleteCluster" -> {
String identifier = params.getFirst("ClusterIdentifier");
Cluster cluster = service.deleteCluster(identifier);
String rawSkip = params.getFirst("SkipFinalClusterSnapshot");
if (rawSkip != null && !"true".equalsIgnoreCase(rawSkip) && !"false".equalsIgnoreCase(rawSkip)) {
throw new AwsException("InvalidParameterValue", "SkipFinalClusterSnapshot must be a boolean.", 400);
}
Cluster cluster = service.deleteCluster(identifier, rawSkip == null ? null : Boolean.valueOf(rawSkip),
params.getFirst("FinalClusterSnapshotIdentifier"), intParam(params, "FinalClusterSnapshotRetentionPeriod"));
String xml = new XmlBuilder()
.start("DeleteClusterResponse")
.start("DeleteClusterResult")
@@ -1058,6 +1063,7 @@ public class RedshiftQueryHandler {
.elem("ClusterIdentifier", snapshot.getClusterIdentifier())
.elem("SnapshotArn", snapshot.getSnapshotArn())
.elem("SnapshotCreateTime", createTime)
.elem("ManualSnapshotRetentionPeriod", snapshot.getManualSnapshotRetentionPeriod().toString())
.elem("Status", snapshot.getStatus())
.elem("Port", String.valueOf(snapshot.getPort()))
.elem("MasterUsername", snapshot.getMasterUsername());
@@ -52,7 +52,9 @@ import java.util.Optional;
import java.util.Set;
import java.util.UUID;
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;
@@ -91,6 +93,39 @@ public class RedshiftService {
private final DynamoDbStreamReader streamReader;
// Proxy ports currently handed out, so allocateProxyPort never double-assigns within this JVM.
private final Set<Integer> usedPorts = ConcurrentHashMap.newKeySet();
private final ConcurrentHashMap<ResourceKey, ResourceLock> resourceLocks = new ConcurrentHashMap<>();
private record ResourceKey(String accountId, String kind, String identifier) { }
private static final class ResourceLock {
private final ReentrantLock lock = new ReentrantLock();
private int users;
}
private <T> T withResourceLock(String kind, String identifier, Supplier<T> work) {
ResourceKey key = new ResourceKey(clusters.accountId(), kind, identifier);
ResourceLock scoped = resourceLocks.compute(key, (ignored, existing) -> {
ResourceLock selected = existing == null ? new ResourceLock() : existing;
selected.users++;
return selected;
});
scoped.lock.lock();
try {
return work.get();
} finally {
scoped.lock.unlock();
resourceLocks.compute(key, (ignored, existing) -> --scoped.users == 0 ? null : scoped);
}
}
// Acquire resource locks before the service monitor; snapshot I/O never takes the monitor.
private <T> T mutateCluster(String identifier, Supplier<T> mutation) {
return withResourceLock("cluster", identifier, () -> mutate(mutation));
}
private synchronized <T> T mutate(Supplier<T> mutation) {
return mutation.get();
}
@Inject
public RedshiftService(StorageFactory storageFactory, RedshiftContainerManager containerManager,
@@ -183,22 +218,28 @@ public class RedshiftService {
return createCluster(identifier, nodeType, username, password, null, List.of(), List.of());
}
// synchronized like modify/reboot: the container + proxy + port steps must not
// interleave with another admin call on the same cluster.
public synchronized Cluster createCluster(String identifier, String nodeType, String username, String password,
// Cluster lifecycle mutations take the scoped resource lock before the service monitor.
public Cluster createCluster(String identifier, String nodeType, String username, String password,
String clusterSubnetGroupName, List<String> vpcSecurityGroupIds) {
return createCluster(identifier, nodeType, username, password, clusterSubnetGroupName,
vpcSecurityGroupIds, List.of());
}
public synchronized Cluster createCluster(String identifier, String nodeType, String username, String password,
public Cluster createCluster(String identifier, String nodeType, String username, String password,
String clusterSubnetGroupName, List<String> vpcSecurityGroupIds,
List<String> iamRoleArns) {
return createCluster(identifier, nodeType, username, password, clusterSubnetGroupName,
vpcSecurityGroupIds, iamRoleArns, null);
}
public synchronized Cluster createCluster(String identifier, String nodeType, String username, String password,
public Cluster createCluster(String identifier, String nodeType, String username, String password,
String clusterSubnetGroupName, List<String> vpcSecurityGroupIds,
List<String> iamRoleArns, String defaultIamRoleArn) {
return mutateCluster(identifier, () -> createClusterLocked(identifier, nodeType, username, password,
clusterSubnetGroupName, vpcSecurityGroupIds, iamRoleArns, defaultIamRoleArn));
}
private Cluster createClusterLocked(String identifier, String nodeType, String username, String password,
String clusterSubnetGroupName, List<String> vpcSecurityGroupIds,
List<String> iamRoleArns, String defaultIamRoleArn) {
if (clusters.get(identifier).isPresent()) {
@@ -274,7 +315,7 @@ public class RedshiftService {
return cluster;
}
public synchronized Cluster createClusterWithManagedMasterPassword(
public Cluster createClusterWithManagedMasterPassword(
String identifier, String nodeType, String username, String clusterSubnetGroupName,
List<String> vpcSecurityGroupIds, List<String> iamRoleArns,
String kmsKeyId, String region) {
@@ -282,7 +323,15 @@ public class RedshiftService {
vpcSecurityGroupIds, iamRoleArns, kmsKeyId, region, null);
}
public synchronized Cluster createClusterWithManagedMasterPassword(
public Cluster createClusterWithManagedMasterPassword(
String identifier, String nodeType, String username, String clusterSubnetGroupName,
List<String> vpcSecurityGroupIds, List<String> iamRoleArns,
String kmsKeyId, String region, String defaultIamRoleArn) {
return mutateCluster(identifier, () -> createClusterWithManagedMasterPasswordLocked(identifier,
nodeType, username, clusterSubnetGroupName, vpcSecurityGroupIds, iamRoleArns, kmsKeyId, region, defaultIamRoleArn));
}
private Cluster createClusterWithManagedMasterPasswordLocked(
String identifier, String nodeType, String username, String clusterSubnetGroupName,
List<String> vpcSecurityGroupIds, List<String> iamRoleArns,
String kmsKeyId, String region, String defaultIamRoleArn) {
@@ -612,13 +661,54 @@ public class RedshiftService {
return clusters.scanForAccount(accountId, k -> true);
}
public synchronized Cluster deleteCluster(String identifier) {
/** Internal deletion used by provisioner cleanup, which explicitly skips the final snapshot. */
public Cluster deleteCluster(String identifier) {
return deleteCluster(identifier, true, null, null);
}
public Cluster deleteCluster(String identifier, Boolean skipFinalClusterSnapshot,
String finalSnapshotIdentifier, Integer finalSnapshotRetentionPeriod) {
return withResourceLock("cluster", identifier, () -> {
Supplier<Cluster> deletion = () -> deleteClusterWithFinalSnapshot(identifier, skipFinalClusterSnapshot,
finalSnapshotIdentifier, finalSnapshotRetentionPeriod);
return Boolean.TRUE.equals(skipFinalClusterSnapshot) ? deletion.get()
: withResourceLock("snapshot", finalSnapshotIdentifier, deletion);
});
}
private Cluster deleteClusterWithFinalSnapshot(String identifier, Boolean skipFinalClusterSnapshot,
String finalSnapshotIdentifier, Integer finalSnapshotRetentionPeriod) {
boolean skipSnapshot = Boolean.TRUE.equals(skipFinalClusterSnapshot);
if (skipSnapshot && finalSnapshotIdentifier != null) {
throw new AwsException("InvalidParameterCombination",
"FinalClusterSnapshotIdentifier cannot be supplied when SkipFinalClusterSnapshot is true", 400);
}
if (!skipSnapshot && (finalSnapshotIdentifier == null || finalSnapshotIdentifier.isBlank())) {
throw new AwsException("InvalidParameterCombination",
"FinalClusterSnapshotIdentifier is required unless SkipFinalClusterSnapshot is true", 400);
}
int retentionPeriod = finalSnapshotRetentionPeriod == null ? -1 : finalSnapshotRetentionPeriod;
if (retentionPeriod != -1 && (retentionPeriod < 1 || retentionPeriod > 3653)) {
throw new AwsException("InvalidRetentionPeriodFault",
"FinalClusterSnapshotRetentionPeriod must be -1 or between 1 and 3653", 400);
}
Optional<Cluster> clusterOpt = clusters.get(identifier);
if (clusterOpt.isEmpty()) {
throw new AwsException("ClusterNotFound", "Cluster " + identifier + " not found", 404);
}
Cluster cluster = clusterOpt.get();
if (!skipSnapshot) {
if (!"available".equals(cluster.getClusterStatus())) {
throw new AwsException("InvalidClusterState", "Cluster must be available to create a final snapshot", 400);
}
createSnapshot(finalSnapshotIdentifier, identifier, retentionPeriod);
}
return mutate(() -> removeCluster(identifier, cluster));
}
private Cluster removeCluster(String identifier, Cluster cluster) {
// Tear down the auth proxy and return its port before stopping the container.
// If it fails, abort deletion so the metadata remains and the user can retry.
if (!stopProxyAndReleasePortSafely(identifier, cluster.getProxyPort())) {
@@ -654,7 +744,14 @@ public class RedshiftService {
clusterParameterGroupName, vpcSecurityGroupIds, null);
}
public synchronized Cluster modifyCluster(String clusterIdentifier, String nodeType, Integer numberOfNodes,
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));
}
private Cluster modifyClusterLocked(String clusterIdentifier, String nodeType, Integer numberOfNodes,
String masterUserPassword, String clusterParameterGroupName,
List<String> vpcSecurityGroupIds, Boolean multiAZ) {
Cluster cluster = clusters.get(clusterIdentifier)
@@ -693,12 +790,18 @@ public class RedshiftService {
return cluster;
}
public synchronized Cluster modifyClusterIamRoles(String clusterIdentifier, List<String> addIamRoles,
public Cluster modifyClusterIamRoles(String clusterIdentifier, List<String> addIamRoles,
List<String> removeIamRoles) {
return modifyClusterIamRoles(clusterIdentifier, addIamRoles, removeIamRoles, null);
}
public synchronized Cluster modifyClusterIamRoles(String clusterIdentifier, List<String> addIamRoles,
public Cluster modifyClusterIamRoles(String clusterIdentifier, List<String> addIamRoles,
List<String> removeIamRoles, String defaultIamRoleArn) {
return mutateCluster(clusterIdentifier, () -> modifyClusterIamRolesLocked(clusterIdentifier,
addIamRoles, removeIamRoles, defaultIamRoleArn));
}
private Cluster modifyClusterIamRolesLocked(String clusterIdentifier, List<String> addIamRoles,
List<String> removeIamRoles, String defaultIamRoleArn) {
Cluster cluster = clusters.get(clusterIdentifier)
.orElseThrow(() -> new AwsException("ClusterNotFound", "Cluster " + clusterIdentifier + " not found", 404));
@@ -777,12 +880,19 @@ public class RedshiftService {
.orElseThrow(() -> new AwsException("ClusterNotFound", "Cluster " + clusterIdentifier + " not found", 404));
}
public synchronized Cluster enableLogging(String clusterIdentifier, String bucketName, String s3KeyPrefix,
public Cluster enableLogging(String clusterIdentifier, String bucketName, String s3KeyPrefix,
String logDestinationType, List<String> logExports) {
return enableLogging(clusterIdentifier, bucketName, s3KeyPrefix, logDestinationType, logExports, null, null);
}
public synchronized Cluster enableLogging(String clusterIdentifier, String bucketName, String s3KeyPrefix,
public Cluster enableLogging(String clusterIdentifier, String bucketName, String s3KeyPrefix,
String logDestinationType, List<String> logExports,
String s3TableKmsKeyId, String s3TableGranularity) {
return mutateCluster(clusterIdentifier, () -> enableLoggingLocked(clusterIdentifier, bucketName,
s3KeyPrefix, logDestinationType, logExports, s3TableKmsKeyId, s3TableGranularity));
}
private Cluster enableLoggingLocked(String clusterIdentifier, String bucketName, String s3KeyPrefix,
String logDestinationType, List<String> logExports,
String s3TableKmsKeyId, String s3TableGranularity) {
Cluster cluster = clusters.get(clusterIdentifier)
@@ -813,7 +923,11 @@ public class RedshiftService {
return cluster;
}
public synchronized Cluster disableLogging(String clusterIdentifier) {
public Cluster disableLogging(String clusterIdentifier) {
return mutateCluster(clusterIdentifier, () -> disableLoggingLocked(clusterIdentifier));
}
private Cluster disableLoggingLocked(String clusterIdentifier) {
Cluster cluster = clusters.get(clusterIdentifier)
.orElseThrow(() -> new AwsException("ClusterNotFound", "Cluster " + clusterIdentifier + " not found", 404));
cluster.setLoggingEnabled(false);
@@ -828,7 +942,11 @@ public class RedshiftService {
return cluster;
}
public synchronized Cluster rebootCluster(String clusterIdentifier) {
public Cluster rebootCluster(String clusterIdentifier) {
return mutateCluster(clusterIdentifier, () -> rebootClusterLocked(clusterIdentifier));
}
private Cluster rebootClusterLocked(String clusterIdentifier) {
Cluster cluster = clusters.get(clusterIdentifier)
.orElseThrow(() -> new AwsException("ClusterNotFound", "Cluster " + clusterIdentifier + " not found", 404));
@@ -958,6 +1076,11 @@ public class RedshiftService {
}
public Snapshot createSnapshot(String snapshotIdentifier, String clusterIdentifier) {
return withResourceLock("cluster", clusterIdentifier, () -> withResourceLock("snapshot", snapshotIdentifier,
() -> createSnapshot(snapshotIdentifier, clusterIdentifier, null)));
}
private Snapshot createSnapshot(String snapshotIdentifier, String clusterIdentifier, Integer retentionPeriod) {
validateSnapshotIdentifier(snapshotIdentifier);
Optional<Cluster> clusterOpt = clusters.get(clusterIdentifier);
if (clusterOpt.isEmpty()) {
@@ -976,6 +1099,7 @@ public class RedshiftService {
snapshot.setMasterPassword(cluster.getMasterPassword());
snapshot.setSnapshotArn(snapshotArn(clusterIdentifier, snapshotIdentifier));
snapshot.setSnapshotCreateTime(Instant.now());
snapshot.setManualSnapshotRetentionPeriod(retentionPeriod);
if (cluster.getEndpoint() != null) {
snapshot.setPort(cluster.getEndpoint().getPort());
} else {
@@ -989,18 +1113,31 @@ public class RedshiftService {
if (!dumpFile.startsWith(dumpDir)) {
throw new AwsException("InvalidParameterValue", "Invalid snapshot identifier", 400);
}
boolean committed = false;
try {
Files.createDirectories(dumpDir);
containerManager.takeSnapshot(clusters.accountId(), clusterIdentifier, cluster.getMasterUsername(), dumpFile);
snapshot.setSqlDump(dumpFile.toString());
} catch (AwsException e) {
throw e;
snapshots.putAllAtomically(Map.of(snapshotIdentifier, snapshot));
committed = true;
snapshots.flush();
} catch (Exception e) {
throw new AwsException("InternalFailure", "Failed to take snapshot for cluster " + clusterIdentifier + ": " + e.getMessage(), 500);
if (!committed) {
try {
Files.deleteIfExists(dumpFile);
} catch (IOException cleanupFailure) {
e.addSuppressed(cleanupFailure);
}
}
if (e instanceof AwsException awsFailure) {
throw awsFailure;
}
AwsException failure = new AwsException("InternalFailure",
"Failed to take snapshot for cluster " + clusterIdentifier + ": " + e.getMessage(), 500);
failure.initCause(e);
throw failure;
}
snapshots.put(snapshotIdentifier, snapshot);
snapshots.flush();
return snapshot;
}
@@ -1029,6 +1166,10 @@ public class RedshiftService {
}
public Snapshot deleteSnapshot(String snapshotIdentifier) {
return withResourceLock("snapshot", snapshotIdentifier, () -> mutate(() -> removeSnapshot(snapshotIdentifier)));
}
private Snapshot removeSnapshot(String snapshotIdentifier) {
Optional<Snapshot> snapshotOpt = snapshots.get(snapshotIdentifier);
if (snapshotOpt.isEmpty()) {
throw new AwsException("ClusterSnapshotNotFound", "Snapshot " + snapshotIdentifier + " not found", 404);
@@ -1051,7 +1192,12 @@ public class RedshiftService {
return restoreFromClusterSnapshot(clusterIdentifier, snapshotIdentifier, null);
}
public synchronized Cluster restoreFromClusterSnapshot(String clusterIdentifier, String snapshotIdentifier, String nodeType) {
public Cluster restoreFromClusterSnapshot(String clusterIdentifier, String snapshotIdentifier, String nodeType) {
return withResourceLock("cluster", clusterIdentifier, () -> withResourceLock("snapshot", snapshotIdentifier,
() -> mutate(() -> restoreSnapshot(clusterIdentifier, snapshotIdentifier, nodeType))));
}
private Cluster restoreSnapshot(String clusterIdentifier, String snapshotIdentifier, String nodeType) {
if (clusters.get(clusterIdentifier).isPresent()) {
throw new AwsException("ClusterAlreadyExists", "Cluster " + clusterIdentifier + " already exists", 400);
}
@@ -1480,7 +1626,14 @@ public class RedshiftService {
}
/** Copy is recorded on the cluster only; no snapshot is actually copied to another region. */
public synchronized Cluster enableSnapshotCopy(String clusterIdentifier, String destinationRegion,
public Cluster enableSnapshotCopy(String clusterIdentifier, String destinationRegion,
Integer retentionPeriod, Integer manualRetentionPeriod,
String snapshotCopyGrantName) {
return mutateCluster(clusterIdentifier, () -> enableSnapshotCopyLocked(clusterIdentifier,
destinationRegion, retentionPeriod, manualRetentionPeriod, snapshotCopyGrantName));
}
private Cluster enableSnapshotCopyLocked(String clusterIdentifier, String destinationRegion,
Integer retentionPeriod, Integer manualRetentionPeriod,
String snapshotCopyGrantName) {
Cluster cluster = requireCluster(clusterIdentifier);
@@ -1511,7 +1664,11 @@ public class RedshiftService {
return cluster;
}
public synchronized Cluster disableSnapshotCopy(String clusterIdentifier) {
public Cluster disableSnapshotCopy(String clusterIdentifier) {
return mutateCluster(clusterIdentifier, () -> disableSnapshotCopyLocked(clusterIdentifier));
}
private Cluster disableSnapshotCopyLocked(String clusterIdentifier) {
Cluster cluster = requireCluster(clusterIdentifier);
if (cluster.getSnapshotCopyDestinationRegion() == null) {
throw new AwsException("SnapshotCopyAlreadyDisabledFault",
@@ -1526,7 +1683,13 @@ public class RedshiftService {
return cluster;
}
public synchronized Cluster modifySnapshotCopyRetentionPeriod(String clusterIdentifier, int retentionPeriod,
public Cluster modifySnapshotCopyRetentionPeriod(String clusterIdentifier, int retentionPeriod,
boolean manual) {
return mutateCluster(clusterIdentifier,
() -> modifySnapshotCopyRetentionPeriodLocked(clusterIdentifier, retentionPeriod, manual));
}
private Cluster modifySnapshotCopyRetentionPeriodLocked(String clusterIdentifier, int retentionPeriod,
boolean manual) {
Cluster cluster = requireCluster(clusterIdentifier);
// SnapshotCopyDisabledFault, not ...AlreadyDisabledFault: the model lists only this one here.
@@ -1670,7 +1833,13 @@ public class RedshiftService {
snapshotSchedules.flush();
}
public synchronized Cluster modifyClusterSnapshotSchedule(String clusterIdentifier, String scheduleIdentifier,
public Cluster modifyClusterSnapshotSchedule(String clusterIdentifier, String scheduleIdentifier,
boolean disassociate) {
return mutateCluster(clusterIdentifier, () -> modifyClusterSnapshotScheduleLocked(clusterIdentifier,
scheduleIdentifier, disassociate));
}
private Cluster modifyClusterSnapshotScheduleLocked(String clusterIdentifier, String scheduleIdentifier,
boolean disassociate) {
Cluster cluster = requireCluster(clusterIdentifier);
if (disassociate) {
@@ -17,6 +17,7 @@ public class Snapshot {
private String sqlDump;
private String snapshotArn;
private Instant snapshotCreateTime;
private Integer manualSnapshotRetentionPeriod;
public Snapshot() {}
@@ -109,6 +110,14 @@ public class Snapshot {
this.snapshotCreateTime = snapshotCreateTime;
}
public Integer getManualSnapshotRetentionPeriod() {
return manualSnapshotRetentionPeriod == null ? -1 : manualSnapshotRetentionPeriod;
}
public void setManualSnapshotRetentionPeriod(Integer manualSnapshotRetentionPeriod) {
this.manualSnapshotRetentionPeriod = manualSnapshotRetentionPeriod;
}
private Map<String, String> tags = new LinkedHashMap<>();
public Map<String, String> getTags() { return tags; }