feat(redshift): support CopyClusterSnapshot API action (#7748) (#7750)

* feat(redshift): support CopyClusterSnapshot API action (#7748)

* fix(redshift): address review findings and sync docs for CopyClusterSnapshot (#7748)

* refactor(redshift): simplify CopyClusterSnapshot using existing helpers (#7748)

Drop Tags, KmsKeyId and the ARN branch, which CopyClusterSnapshotMessage does not carry.
Reuse validateManualRetention (InvalidRetentionPeriodFault), takenFrom and SnapshotDumpCopier.copy,
and share the automated-snapshot setup across the new tests.
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-08 17:56:25 -04:00
1 parent b4b80cf039
commit e0692092b5
7 files changed
+358 -1

No files matched your search

+1 -1
View File
@@ -80,7 +80,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [DocumentDB](docdb.md) | `POST /` with `Action=` param + MongoDB container | Query + MongoDB wire | 17 |
| [DMS](dms.md) | `POST /` + `X-Amz-Target: AmazonDMSv20160101.*` | JSON 1.1 | 20 |
| [QuickSight](quicksight.md) | `/accounts/{AwsAccountId}/...` | REST JSON, metadata only | 16 |
| [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire (+ CFN) | 55 |
| [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire (+ CFN) | 56 |
| [Redshift Data API](redshift-data.md) | `POST /` + `X-Amz-Target: RedshiftData.*` | JSON 1.1 | 12 |
| [Redshift Serverless](redshift-serverless.md) | `POST /` + `X-Amz-Target: RedshiftServerless.*` | JSON 1.1 | 55 |
| [EMR](emr.md) | `POST /` + `X-Amz-Target: ElasticMapReduce.*` | JSON 1.1 | 40 |
+1
View File
@@ -129,6 +129,7 @@ The attributes follow the [CloudFormation resource schema](https://docs.aws.amaz
| `CreateClusterSnapshot` | Back up a cluster to a SQL dump via `pg_dump` |
| `DescribeClusterSnapshots` | List snapshots, optionally filtered by snapshot or cluster identifier and SnapshotType (manual or automated) |
| `DeleteClusterSnapshot` | Remove a snapshot and its stored dump |
| `CopyClusterSnapshot` | Copy an automated cluster snapshot to a manual snapshot with a new identifier and retention period |
| `RestoreFromClusterSnapshot` | Create a new cluster and load a snapshot's dump into it via `psql`; accepts `SnapshotIdentifier` or a same-account, same-region `SnapshotArn` |
| `CreateClusterParameterGroup` | Register a parameter group (metadata only) |
| `DescribeClusterParameterGroups` | List parameter groups, optionally filtered by name |
@@ -241,6 +241,27 @@ public class RedshiftQueryHandler {
.build();
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
}
case "CopyClusterSnapshot" -> {
String sourceSnapshotId = requireParam(params, "SourceSnapshotIdentifier");
String targetSnapshotId = requireParam(params, "TargetSnapshotIdentifier");
String sourceClusterId = params.getFirst("SourceSnapshotClusterIdentifier");
Integer manualRetention = parseOptionalInteger(params, "ManualSnapshotRetentionPeriod");
Snapshot snapshot = service.copyClusterSnapshot(sourceSnapshotId, targetSnapshotId,
sourceClusterId, manualRetention);
String xml = new XmlBuilder()
.start("CopyClusterSnapshotResponse")
.start("CopyClusterSnapshotResult")
.raw(buildSnapshotXml(snapshot))
.end("CopyClusterSnapshotResult")
.start("ResponseMetadata")
.elem("RequestId", "test-req-id")
.end("ResponseMetadata")
.end("CopyClusterSnapshotResponse")
.build();
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
}
case "RestoreFromClusterSnapshot" -> {
String clusterIdentifier = params.getFirst("ClusterIdentifier");
String snapshotIdentifier = params.getFirst("SnapshotIdentifier");
@@ -2052,6 +2052,88 @@ public class RedshiftService implements ManagedSecretRotator {
|| clusterIdentifier.equals(snapshot.getClusterIdentifier());
}
public Snapshot copyClusterSnapshot(String sourceSnapshotIdentifier, String targetSnapshotIdentifier,
String sourceSnapshotClusterIdentifier, Integer manualRetention) {
validateSnapshotIdentifier(targetSnapshotIdentifier);
if (manualRetention != null) {
validateManualRetention(manualRetention);
}
String accountId = clusters.accountId();
String region = regionResolver.getRegion();
return withResourceLock("snapshot", targetSnapshotIdentifier, () -> {
boolean shadowedByCopy = snapshotCopies.get(copyKey(region, targetSnapshotIdentifier)).isPresent();
if (shadowedByCopy || snapshots.get(targetSnapshotIdentifier).isPresent()) {
throw new AwsException("ClusterSnapshotAlreadyExists",
"Snapshot " + targetSnapshotIdentifier + " already exists", 400);
}
Snapshot source = findSnapshot(sourceSnapshotIdentifier)
.filter(found -> takenFrom(found, sourceSnapshotClusterIdentifier))
.orElseThrow(() -> new AwsException("ClusterSnapshotNotFound",
"Snapshot " + sourceSnapshotIdentifier + " not found", 404));
if (!"available".equals(source.getStatus())) {
throw new AwsException("InvalidClusterSnapshotState",
"Snapshot " + sourceSnapshotIdentifier + " is not available", 400);
}
if (!"automated".equals(source.getSnapshotType())) {
throw new AwsException("InvalidClusterSnapshotState",
"Cannot copy a manual snapshot: " + sourceSnapshotIdentifier
+ ". Only automated snapshots can be copied.", 400);
}
Snapshot copy = new Snapshot(source);
copy.setSnapshotIdentifier(targetSnapshotIdentifier);
copy.setSnapshotType("manual");
copy.setSnapshotCreateTime(Instant.now());
copy.setManualSnapshotRetentionPeriod(
manualRetention != null ? manualRetention : RETAIN_MANUAL_SNAPSHOTS_INDEFINITELY);
copy.setAutomatedSnapshotRetentionPeriod(null);
copy.setScheduledTime(null);
copy.setSnapshotArn(snapshotArn(source.getClusterIdentifier(), targetSnapshotIdentifier));
copy.setCopiedToRegions(new LinkedHashSet<>());
copy.setSqlDump(null);
Path copiedDump = null;
if (source.getSqlDump() != null && !source.getSqlDump().isBlank()) {
Path dumpDir = accountDumpDir(accountId);
try {
copiedDump = SnapshotDumpCopier.copy(Paths.get(source.getSqlDump()), dumpDir, dumpDir);
} catch (IOException e) {
LOG.warnv(e, "Could not copy the dump of snapshot {0}", sourceSnapshotIdentifier);
throw new AwsException("InternalFailure", "Failed to copy snapshot dump", 500);
}
copy.setSqlDump(copiedDump.toString());
}
try {
snapshots.putAllAtomically(Map.of(targetSnapshotIdentifier, copy));
snapshots.flush();
} catch (RuntimeException e) {
deleteQuietly(copiedDump, e);
throw e;
}
emitSnapshotEvent(accountId, region, RedshiftEventCatalog.SNAPSHOT_STARTED,
targetSnapshotIdentifier, "A user snapshot '" + targetSnapshotIdentifier
+ "' for Amazon Redshift cluster '" + source.getClusterIdentifier()
+ "' was copied from snapshot '" + sourceSnapshotIdentifier + "'.");
return copy;
});
}
private static void deleteQuietly(Path file, Exception cause) {
if (file == null) {
return;
}
try {
Files.deleteIfExists(file);
} catch (IOException cleanupFailure) {
cause.addSuppressed(cleanupFailure);
}
}
public Snapshot deleteSnapshot(String snapshotIdentifier) {
return deleteSnapshot(snapshotIdentifier, null);
}
@@ -452,6 +452,64 @@ public class RedshiftOperationsTest {
.contentType("application/xml")
.body(containsString("<SnapshotIdentifier>snap-test-1</SnapshotIdentifier>"));
// 3b. CopyClusterSnapshot rejects manual snapshot
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "CopyClusterSnapshot")
.formParam("SourceSnapshotIdentifier", "snap-test-1")
.formParam("TargetSnapshotIdentifier", "snap-copy-1")
.when()
.post("/")
.then()
.statusCode(400)
.contentType("application/xml")
.body(containsString("<Code>InvalidClusterSnapshotState</Code>"));
// 3c. CopyClusterSnapshot succeeds when source is automated
service.getSnapshot("snap-test-1").ifPresent(s -> s.setSnapshotType("automated"));
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "CopyClusterSnapshot")
.formParam("SourceSnapshotIdentifier", "snap-test-1")
.formParam("TargetSnapshotIdentifier", "snap-copy-1")
.formParam("ManualSnapshotRetentionPeriod", "30")
.when()
.post("/")
.then()
.statusCode(200)
.contentType("application/xml")
.body(containsString("<CopyClusterSnapshotResponse>"))
.body(containsString("<SnapshotIdentifier>snap-copy-1</SnapshotIdentifier>"))
.body(containsString("<SnapshotType>manual</SnapshotType>"))
.body(containsString("<ClusterIdentifier>cluster-src</ClusterIdentifier>"));
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "DescribeClusterSnapshots")
.formParam("SnapshotIdentifier", "snap-copy-1")
.when()
.post("/")
.then()
.statusCode(200)
.contentType("application/xml")
.body(containsString("<SnapshotIdentifier>snap-copy-1</SnapshotIdentifier>"));
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "DeleteClusterSnapshot")
.formParam("SnapshotIdentifier", "snap-copy-1")
.when()
.post("/")
.then()
.statusCode(200);
// Restore snap-test-1 type to manual so later step 6 can delete it
service.getSnapshot("snap-test-1").ifPresent(s -> s.setSnapshotType("manual"));
// 4. DeleteCluster
given()
.contentType("application/x-www-form-urlencoded")
@@ -1477,4 +1477,53 @@ class RedshiftQueryHandlerTest {
String xml = (String) response.getEntity();
assertTrue(xml.contains("<DbUser>IAM:alice</DbUser>"));
}
// ── CopyClusterSnapshot ──────────────────────────────────────────────────
@Test
void copyClusterSnapshotRequiresSourceAndTargetIdentifiers() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
AwsException ex1 = assertThrows(AwsException.class, () -> handler.handle("CopyClusterSnapshot", params));
assertEquals("InvalidParameterValue", ex1.getErrorCode());
assertTrue(ex1.getMessage().contains("SourceSnapshotIdentifier is required"));
params.putSingle("SourceSnapshotIdentifier", "source-snap");
AwsException ex2 = assertThrows(AwsException.class, () -> handler.handle("CopyClusterSnapshot", params));
assertEquals("InvalidParameterValue", ex2.getErrorCode());
assertTrue(ex2.getMessage().contains("TargetSnapshotIdentifier is required"));
}
@Test
void copyClusterSnapshotDelegatesToServiceAndFormatsXml() {
Snapshot snapshot = new Snapshot();
snapshot.setSnapshotIdentifier("target-snap");
snapshot.setClusterIdentifier("my-cluster");
snapshot.setSnapshotType("manual");
snapshot.setStatus("available");
snapshot.setMasterUsername("admin");
snapshot.setPort(5439);
snapshot.setManualSnapshotRetentionPeriod(15);
snapshot.setSnapshotArn("arn:aws:redshift:us-east-1:111111111111:snapshot:my-cluster/target-snap");
when(service.copyClusterSnapshot("source-snap", "target-snap", "my-cluster", 15))
.thenReturn(snapshot);
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("SourceSnapshotIdentifier", "source-snap");
params.putSingle("TargetSnapshotIdentifier", "target-snap");
params.putSingle("SourceSnapshotClusterIdentifier", "my-cluster");
params.putSingle("ManualSnapshotRetentionPeriod", "15");
Response response = handler.handle("CopyClusterSnapshot", params);
assertEquals(200, response.getStatus());
String xml = (String) response.getEntity();
assertTrue(xml.contains("<CopyClusterSnapshotResponse>"));
assertTrue(xml.contains("<CopyClusterSnapshotResult>"));
assertTrue(xml.contains("<SnapshotIdentifier>target-snap</SnapshotIdentifier>"));
assertTrue(xml.contains("<ClusterIdentifier>my-cluster</ClusterIdentifier>"));
assertTrue(xml.contains("<SnapshotType>manual</SnapshotType>"));
assertTrue(xml.contains("<SnapshotArn>arn:aws:redshift:us-east-1:111111111111:snapshot:my-cluster/target-snap</SnapshotArn>"));
verify(service).copyClusterSnapshot("source-snap", "target-snap", "my-cluster", 15);
}
}
@@ -68,6 +68,8 @@ import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static io.floci.aws.testing.InlineMocks.inlineMock;
import static io.floci.aws.testing.ThreadStates.awaitBlockedOrDone;
@@ -2393,6 +2395,150 @@ class RedshiftServiceTest {
verify(snapshotBackend, never()).put(anyString(), any(Snapshot.class));
}
private Snapshot automatedSnapshot(String identifier) {
Snapshot snapshot = new Snapshot();
snapshot.setSnapshotIdentifier(identifier);
snapshot.setClusterIdentifier("my-cluster");
snapshot.setSnapshotType("automated");
snapshot.setStatus("available");
snapshot.setMasterUsername("admin");
snapshot.setMasterPassword("secret-pw");
snapshot.setPort(5439);
snapshot.setAutomatedSnapshotRetentionPeriod(7);
when(snapshotBackend.get(identifier)).thenReturn(Optional.of(snapshot));
return snapshot;
}
private void targetSnapshotIsFree(String identifier) {
when(snapshotBackend.get(identifier)).thenReturn(Optional.empty());
when(snapshotCopyBackend.get(anyString())).thenReturn(Optional.empty());
}
private void assertCopyFails(String errorCode, int status, String source, String target, String cluster,
Integer retention) {
AwsException ex = assertThrows(AwsException.class, () ->
service.copyClusterSnapshot(source, target, cluster, retention));
assertEquals(errorCode, ex.getErrorCode());
assertEquals(status, ex.getHttpStatus());
}
@Test
void copyClusterSnapshotSuccess() {
Snapshot source = automatedSnapshot("auto-snap-1");
source.setKmsKeyId("orig-key");
source.setTags(Map.of("Env", "Test"));
source.setCopiedToRegions(new HashSet<>(Set.of("us-west-2")));
targetSnapshotIsFree("manual-copy-1");
Snapshot copy = service.copyClusterSnapshot("auto-snap-1", "manual-copy-1", null, 30);
assertEquals("manual-copy-1", copy.getSnapshotIdentifier());
assertEquals("my-cluster", copy.getClusterIdentifier());
assertEquals("manual", copy.getSnapshotType());
assertEquals("available", copy.getStatus());
assertEquals(30, copy.getManualSnapshotRetentionPeriod());
assertNull(copy.getAutomatedSnapshotRetentionPeriod());
assertEquals("orig-key", copy.getKmsKeyId());
assertEquals(Map.of("Env", "Test"), copy.getTags());
assertTrue(copy.getCopiedToRegions().isEmpty());
verify(snapshotBackend).putAllAtomically(any());
verify(snapshotBackend).flush();
}
@Test
void copyClusterSnapshotDefaultsToIndefiniteRetention() {
automatedSnapshot("auto-snap-1");
targetSnapshotIsFree("manual-copy-1");
Snapshot copy = service.copyClusterSnapshot("auto-snap-1", "manual-copy-1", "my-cluster", null);
assertEquals(-1, copy.getManualSnapshotRetentionPeriod());
}
@Test
void copyClusterSnapshotSourceNotFound() {
targetSnapshotIsFree("missing-snap");
targetSnapshotIsFree("manual-copy-1");
assertCopyFails("ClusterSnapshotNotFound", 404, "missing-snap", "manual-copy-1", null, -1);
}
@Test
void copyClusterSnapshotClusterMismatch() {
automatedSnapshot("auto-snap-1");
targetSnapshotIsFree("manual-copy-1");
assertCopyFails("ClusterSnapshotNotFound", 404, "auto-snap-1", "manual-copy-1", "wrong-cluster", -1);
}
@Test
void copyClusterSnapshotManualSourceRejected() {
automatedSnapshot("manual-snap-1").setSnapshotType("manual");
targetSnapshotIsFree("manual-copy-1");
assertCopyFails("InvalidClusterSnapshotState", 400, "manual-snap-1", "manual-copy-1", null, -1);
}
@Test
void copyClusterSnapshotSourceNotAvailable() {
automatedSnapshot("auto-snap-1").setStatus("creating");
targetSnapshotIsFree("manual-copy-1");
assertCopyFails("InvalidClusterSnapshotState", 400, "auto-snap-1", "manual-copy-1", null, -1);
}
@Test
void copyClusterSnapshotTargetAlreadyExists() {
when(snapshotBackend.get("manual-copy-1")).thenReturn(Optional.of(new Snapshot()));
when(snapshotCopyBackend.get(anyString())).thenReturn(Optional.empty());
assertCopyFails("ClusterSnapshotAlreadyExists", 400, "auto-snap-1", "manual-copy-1", null, -1);
}
@Test
void copyClusterSnapshotInvalidRetentionPeriod() {
assertCopyFails("InvalidRetentionPeriodFault", 400, "auto-snap-1", "manual-copy-1", null, 0);
}
@Test
void copyClusterSnapshotInvalidTargetIdentifier() {
assertCopyFails("InvalidParameterValue", 400, "auto-snap-1", "bad--name", null, -1);
}
@Test
void copyClusterSnapshotCopiesDumpAndCleansUpOnPersistenceFailure() throws Exception {
Path dumpDir = Paths.get("target/test-data").resolve("redshift-dumps").resolve("111111111111")
.toAbsolutePath().normalize();
Files.createDirectories(dumpDir);
Path sourceDump = dumpDir.resolve("auto-snap-src.sql");
Files.writeString(sourceDump, "SELECT 1;");
automatedSnapshot("auto-snap-src").setSqlDump(sourceDump.toString());
targetSnapshotIsFree("manual-copy-dump");
targetSnapshotIsFree("manual-copy-fail");
Snapshot copy = service.copyClusterSnapshot("auto-snap-src", "manual-copy-dump", null, -1);
Path copiedDump = Paths.get(copy.getSqlDump());
assertNotEquals(sourceDump, copiedDump);
assertEquals(dumpDir, copiedDump.getParent());
assertEquals("SELECT 1;", Files.readString(copiedDump));
try (Stream<Path> before = Files.list(dumpDir)) {
Set<Path> existing = before.collect(Collectors.toSet());
doThrow(new RuntimeException("Simulated storage write error"))
.when(snapshotBackend).putAllAtomically(any());
assertThrows(RuntimeException.class, () ->
service.copyClusterSnapshot("auto-snap-src", "manual-copy-fail", null, -1));
try (Stream<Path> after = Files.list(dumpDir)) {
assertEquals(existing, after.collect(Collectors.toSet()));
}
} finally {
Files.deleteIfExists(sourceDump);
Files.deleteIfExists(copiedDump);
}
}
@Test
void modifyClusterUpdatesMetadataAndPassword() {
Cluster cluster = new Cluster();