feat(rds): DB cluster snapshots (#4097)

* feat(rds): DB cluster snapshots

Add CreateDBClusterSnapshot, DeleteDBClusterSnapshot, CopyDBClusterSnapshot,
RestoreDBClusterFromSnapshot, DescribeDBClusterSnapshotAttributes and
ModifyDBClusterSnapshotAttribute, and make DescribeDBClusterSnapshots list
real snapshots with its three filters instead of an empty list.

A cluster snapshot records the cluster's description and a dump of its
database; a restore creates a new cluster from the snapshot's settings
and loads the dump into it. Copies carry the data, CopyTags and Tags and
record SourceDBClusterSnapshotArn; the restore attribute is shared the way
instance snapshots share it.

Closes #4042

* feat(rds): restore a cluster from a snapshot named by ARN, simplify the cluster snapshot handlers

RestoreDBClusterFromSnapshot resolves SnapshotIdentifier by name or ARN
through the helper CopyDBClusterSnapshot already uses, as the API
reference allows and aws_rds_cluster commonly sends. The six handlers
use the shared firstMissingParam helper and the central AwsException
handling; the new service lines import InMemoryStorage and Predicate
instead of qualifying them inline, and the tests import
DbClusterSnapshot.
This commit is contained in:
David authored and GitHub committed 2026-09-21 19:42:22 -04:00
1 parent 2af7ed71a7
commit ecdc9ccfdd
8 files changed
+1065 -11

No files matched your search

@@ -0,0 +1,207 @@
package io.github.hectorvent.floci.services.rds;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.StreamType;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import io.github.hectorvent.floci.services.rds.model.DbCluster;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static io.restassured.RestAssured.given;
import static io.restassured.http.ContentType.URLENC;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
/**
* The cluster snapshot lifecycle against real Postgres containers: a row written before the
* snapshot comes back from a cluster restored from a copy of that snapshot, the source snapshot
* can be deleted without touching the copy, and each refusal carries the AWS error.
*/
@QuarkusTest
@Tag("docker")
class RdsClusterSnapshotLifecycleIntegrationTest {
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260921/us-east-1/rds/aws4_request, "
+ "SignedHeaders=content-type;host, Signature=test";
@Inject
DockerClient dockerClient;
@Inject
RdsService rdsService;
@BeforeEach
void checkDocker() {
try {
dockerClient.pingCmd().exec();
} catch (Exception e) {
assumeTrue(false, "Docker is not available: " + e.getMessage());
}
}
private static RequestSpecification query(String action) {
return given().header("Authorization", AUTH)
.contentType(URLENC)
.formParam("Action", action)
.formParam("Version", "2014-10-31");
}
@Test
void clusterSnapshotRoundTripsTheClustersDataIntoARestoredCluster() throws Exception {
String suffix = Long.toString(System.nanoTime(), 36);
String cluster = "csnap-src-" + suffix;
String snapshot = "csnap-" + suffix;
String copy = "csnap-copy-" + suffix;
String restored = "csnap-restored-" + suffix;
query("CreateDBCluster")
.formParam("DBClusterIdentifier", cluster)
.formParam("Engine", "aurora-postgresql")
.formParam("EngineVersion", "16.3")
.formParam("MasterUsername", "admin")
.formParam("MasterUserPassword", "password123")
.formParam("DatabaseName", "appdb")
.when().post("/").then().statusCode(200);
waitForCluster(cluster);
DbCluster source = rdsService.getDbCluster(cluster);
psql(source.getContainerId(), "CREATE TABLE marker(v text); INSERT INTO marker VALUES ('cluster-row');");
query("CreateDBClusterSnapshot")
.formParam("DBClusterSnapshotIdentifier", snapshot)
.formParam("DBClusterIdentifier", cluster)
.formParam("Tags.Tag.1.Key", "owner")
.formParam("Tags.Tag.1.Value", "platform")
.when().post("/").then().statusCode(200)
.body(containsString("<CreateDBClusterSnapshotResult>"))
.body(containsString("<Engine>aurora-postgresql</Engine>"))
.body(containsString("<Status>available</Status>"))
.body(containsString("<SnapshotType>manual</SnapshotType>"))
.body(containsString("<PercentProgress>100</PercentProgress>"))
.body(containsString(":cluster-snapshot:" + snapshot + "</DBClusterSnapshotArn>"));
query("DescribeDBClusterSnapshots")
.formParam("DBClusterIdentifier", cluster)
.when().post("/").then().statusCode(200)
.body(containsString("<DBClusterSnapshotIdentifier>" + snapshot + "</DBClusterSnapshotIdentifier>"));
String sourceArn = "arn:aws:rds:us-east-1:000000000000:cluster-snapshot:" + snapshot;
query("CopyDBClusterSnapshot")
.formParam("SourceDBClusterSnapshotIdentifier", sourceArn)
.formParam("TargetDBClusterSnapshotIdentifier", copy)
.formParam("CopyTags", "true")
.when().post("/").then().statusCode(200)
.body(containsString("<SourceDBClusterSnapshotArn>" + sourceArn + "</SourceDBClusterSnapshotArn>"))
.body(containsString("<Value>platform</Value>"));
query("ModifyDBClusterSnapshotAttribute")
.formParam("DBClusterSnapshotIdentifier", copy)
.formParam("AttributeName", "restore")
.formParam("ValuesToAdd.member.1", "all")
.when().post("/").then().statusCode(200)
.body(containsString("<AttributeValue>all</AttributeValue>"));
query("DeleteDBClusterSnapshot")
.formParam("DBClusterSnapshotIdentifier", snapshot)
.when().post("/").then().statusCode(200)
.body(containsString("<Status>deleted</Status>"));
query("DescribeDBClusterSnapshots")
.formParam("DBClusterSnapshotIdentifier", snapshot)
.when().post("/").then().statusCode(404)
.body(containsString("<Code>DBClusterSnapshotNotFoundFault</Code>"));
// Restore by ARN, the form aws_rds_cluster's snapshot_identifier is commonly given.
query("RestoreDBClusterFromSnapshot")
.formParam("DBClusterIdentifier", restored)
.formParam("SnapshotIdentifier", "arn:aws:rds:us-east-1:000000000000:cluster-snapshot:" + copy)
.formParam("Engine", "aurora-postgresql")
.when().post("/").then().statusCode(200)
.body(containsString("<RestoreDBClusterFromSnapshotResult>"))
.body(containsString("<DBClusterIdentifier>" + restored + "</DBClusterIdentifier>"));
waitForCluster(restored);
DbCluster restoredCluster = rdsService.getDbCluster(restored);
assertTrue(psql(restoredCluster.getContainerId(), "SELECT v FROM marker;").contains("cluster-row"),
"the row written before the cluster snapshot must come back from the copy");
query("DeleteDBClusterSnapshot").formParam("DBClusterSnapshotIdentifier", copy)
.when().post("/").then().statusCode(200);
query("DeleteDBCluster").formParam("DBClusterIdentifier", restored).formParam("SkipFinalSnapshot", "true")
.when().post("/").then().statusCode(200);
query("DeleteDBCluster").formParam("DBClusterIdentifier", cluster).formParam("SkipFinalSnapshot", "true")
.when().post("/").then().statusCode(200);
}
private void waitForCluster(String clusterId) throws Exception {
for (int i = 0; i < 60; i++) {
String status = query("DescribeDBClusters")
.formParam("DBClusterIdentifier", clusterId)
.when().post("/").then()
.extract().xmlPath().getString(
"DescribeDBClustersResponse.DescribeDBClustersResult.DBClusters.DBCluster.Status");
if ("available".equals(status)) {
return;
}
Thread.sleep(1000);
}
throw new RuntimeException("DB cluster " + clusterId + " did not become available.");
}
private String psql(String containerId, String sql) throws Exception {
String[] command = {"psql", "-U", "admin", "-d", "appdb", "-tAc", sql};
String execId = dockerClient.execCreateCmd(containerId)
.withCmd(command)
.withAttachStdout(true)
.withAttachStderr(true)
.exec()
.getId();
ByteArrayOutputStream output = new ByteArrayOutputStream();
ByteArrayOutputStream errors = new ByteArrayOutputStream();
CountDownLatch latch = new CountDownLatch(1);
Closeable callback = dockerClient.execStartCmd(execId).exec(new ExecStartResultCallback() {
@Override
public void onNext(Frame frame) {
try {
if (frame.getStreamType() == StreamType.STDOUT) {
output.write(frame.getPayload());
} else if (frame.getStreamType() == StreamType.STDERR) {
errors.write(frame.getPayload());
}
} catch (IOException e) {
throw new IllegalStateException("Failed to capture psql output", e);
}
}
@Override
public void onComplete() {
latch.countDown();
}
@Override
public void onError(Throwable throwable) {
latch.countDown();
}
});
try {
assertTrue(latch.await(30, TimeUnit.SECONDS), "Timed out running psql");
long exitCode = dockerClient.inspectExecCmd(execId).exec().getExitCodeLong();
assertTrue(exitCode == 0, "psql failed with exit code " + exitCode + ": " + errors.toString(StandardCharsets.UTF_8));
return output.toString(StandardCharsets.UTF_8);
} finally {
callback.close();
}
}
}
@@ -4,6 +4,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.rds.model.DatabaseEngine;
import io.github.hectorvent.floci.services.rds.model.DbCluster;
import io.github.hectorvent.floci.services.rds.model.DbClusterSnapshot;
import io.github.hectorvent.floci.services.rds.model.DbClusterParameterGroup;
import io.github.hectorvent.floci.services.docdb.DocDbQueryHandler;
import io.github.hectorvent.floci.services.neptune.NeptuneQueryHandler;
@@ -1951,6 +1952,55 @@ class RdsQueryHandlerTest {
verify(service, never()).startDbCluster(any(), any());
}
@Test
void clusterSnapshotActions_dispatchAndRenderTheClusterSnapshot() {
DbClusterSnapshot snapshot = new DbClusterSnapshot();
snapshot.setDbClusterSnapshotIdentifier("csnap");
snapshot.setDbClusterIdentifier("aurora");
snapshot.setEngineIdentifier("aurora-postgresql");
snapshot.setStatus("available");
snapshot.setPercentProgress(100);
snapshot.setDbClusterSnapshotArn("arn:aws:rds:us-east-1:000000000000:cluster-snapshot:csnap");
snapshot.setAvailabilityZones(List.of("us-east-1a"));
snapshot.setRestoreAccountIds(List.of("all"));
when(service.createDbClusterSnapshot(eq("csnap"), eq("aurora"), eq(Map.of()), isNull())).thenReturn(snapshot);
MultivaluedMap<String, String> create = params();
create.add("DBClusterSnapshotIdentifier", "csnap");
create.add("DBClusterIdentifier", "aurora");
Response created = handler.handle("CreateDBClusterSnapshot", create);
assertEquals(200, created.getStatus());
String body = (String) created.getEntity();
assertTrue(body.contains("<CreateDBClusterSnapshotResult>"));
assertTrue(body.contains("<DBClusterSnapshot>"));
assertTrue(body.contains("<AvailabilityZone>us-east-1a</AvailabilityZone>"));
assertTrue(body.contains("<SnapshotType>manual</SnapshotType>"));
assertTrue(body.contains("<PercentProgress>100</PercentProgress>"));
assertTrue(body.contains("<DBClusterSnapshotArn>arn:aws:rds:us-east-1:000000000000:cluster-snapshot:csnap</DBClusterSnapshotArn>"));
when(service.describeDbClusterSnapshots(isNull(), eq("aurora"), isNull(), isNull())).thenReturn(List.of(snapshot));
MultivaluedMap<String, String> describe = params();
describe.add("DBClusterIdentifier", "aurora");
String listBody = (String) handler.handle("DescribeDBClusterSnapshots", describe).getEntity();
assertTrue(listBody.contains("<DBClusterSnapshots><DBClusterSnapshot>"));
when(service.describeDbClusterSnapshotAttributes(eq("csnap"), isNull())).thenReturn(snapshot);
MultivaluedMap<String, String> attrs = params();
attrs.add("DBClusterSnapshotIdentifier", "csnap");
String attrBody = (String) handler.handle("DescribeDBClusterSnapshotAttributes", attrs).getEntity();
assertTrue(attrBody.contains("<DBClusterSnapshotAttributesResult>"));
assertTrue(attrBody.contains("<AttributeName>restore</AttributeName>"));
assertTrue(attrBody.contains("<AttributeValue>all</AttributeValue>"));
assertEquals(400, handler.handle("CreateDBClusterSnapshot", params()).getStatus());
assertEquals(400, handler.handle("DeleteDBClusterSnapshot", params()).getStatus());
MultivaluedMap<String, String> restore = params();
restore.add("DBClusterIdentifier", "restored");
restore.add("SnapshotIdentifier", "csnap");
Response missingEngine = handler.handle("RestoreDBClusterFromSnapshot", restore);
assertEquals(400, missingEngine.getStatus());
assertTrue(((String) missingEngine.getEntity()).contains("Engine is required."));
}
@Test
void describeDbSnapshotAttributes_returnsRestoreAttribute() {
io.github.hectorvent.floci.services.rds.model.DbSnapshot snapshot = new io.github.hectorvent.floci.services.rds.model.DbSnapshot();
@@ -14,6 +14,7 @@ import io.github.hectorvent.floci.services.ec2.model.Vpc;
import io.github.hectorvent.floci.services.ec2.model.VpcIpv6CidrBlockAssociation;
import io.github.hectorvent.floci.services.rds.model.DatabaseEngine;
import io.github.hectorvent.floci.services.rds.model.DbCluster;
import io.github.hectorvent.floci.services.rds.model.DbClusterSnapshot;
import io.github.hectorvent.floci.services.rds.model.DbClusterParameterGroup;
import io.github.hectorvent.floci.services.rds.container.RdsContainerHandle;
import io.github.hectorvent.floci.services.rds.container.RdsContainerManager;
@@ -3096,6 +3097,102 @@ class RdsServiceTest {
rdsService.listTagsForResource(snapshot.getDbSnapshotArn()));
}
private DbClusterSnapshot clusterSnapshotOfNewCluster(String snapshotId) {
rdsService.createDbCluster("aurora-cluster", "aurora-postgresql", "16.3",
"admin", "password", "dbname", false, null);
when(containerManager.createPostgresSnapshot(any(), eq("admin"))).thenReturn("CLUSTER_DUMP");
return rdsService.createDbClusterSnapshot(snapshotId, "aurora-cluster", Map.of("owner", "platform"));
}
@Test
void createDbClusterSnapshotRecordsTheClusterAndItsData() {
DbClusterSnapshot snapshot = clusterSnapshotOfNewCluster("csnap");
assertEquals("csnap", snapshot.getDbClusterSnapshotIdentifier());
assertEquals("aurora-cluster", snapshot.getDbClusterIdentifier());
assertEquals("available", snapshot.getStatus());
assertEquals("manual", snapshot.getSnapshotType());
assertEquals(100, snapshot.getPercentProgress());
assertEquals("aurora-postgresql", snapshot.getEngineIdentifier());
assertEquals("16.3", snapshot.getEngineVersion());
assertEquals("admin", snapshot.getMasterUsername());
assertEquals("dbname", snapshot.getDatabaseName());
assertEquals("arn:aws:rds:us-east-1:123456789012:cluster-snapshot:csnap", snapshot.getDbClusterSnapshotArn());
assertEquals(Map.of("owner", "platform"), snapshot.getTags());
assertEquals(Map.of("owner", "platform"), rdsService.listTagsForResource(snapshot.getDbClusterSnapshotArn()));
verify(containerManager).createPostgresSnapshot(any(), eq("admin"));
assertEquals(1, rdsService.describeDbClusterSnapshots(null, null, null).size());
assertEquals(1, rdsService.describeDbClusterSnapshots(null, "aurora-cluster", "manual").size());
assertTrue(rdsService.describeDbClusterSnapshots(null, "other-cluster", null).isEmpty());
assertTrue(rdsService.describeDbClusterSnapshots(null, null, "automated").isEmpty());
assertEquals("DBClusterSnapshotAlreadyExistsFault", assertThrows(AwsException.class,
() -> rdsService.createDbClusterSnapshot("csnap", "aurora-cluster", null)).getErrorCode());
assertEquals("DBClusterNotFoundFault", assertThrows(AwsException.class,
() -> rdsService.createDbClusterSnapshot("other", "absent-cluster", null)).getErrorCode());
assertEquals("DBClusterSnapshotNotFoundFault", assertThrows(AwsException.class,
() -> rdsService.describeDbClusterSnapshots("absent", null, null)).getErrorCode());
}
@Test
void clusterSnapshotCanBeCopiedRestoredAndDeleted() {
DbClusterSnapshot source = clusterSnapshotOfNewCluster("csnap");
DbClusterSnapshot copy =
rdsService.copyDbClusterSnapshot(source.getDbClusterSnapshotArn(), "csnap-copy", true, Map.of("stage", "test"));
assertEquals("csnap-copy", copy.getDbClusterSnapshotIdentifier());
assertEquals(source.getDbClusterSnapshotArn(), copy.getSourceDbClusterSnapshotArn());
assertEquals(Map.of("owner", "platform", "stage", "test"), copy.getTags());
assertEquals("DBClusterSnapshotAlreadyExistsFault", assertThrows(AwsException.class,
() -> rdsService.copyDbClusterSnapshot("csnap", "csnap-copy", false, null)).getErrorCode());
// SnapshotIdentifier takes the ARN as well as the name, as aws_rds_cluster commonly passes it.
DbCluster restored = rdsService.restoreDbClusterFromSnapshot("restored-cluster", copy.getDbClusterSnapshotArn(),
"aurora-postgresql", null, null, null, null, null, null, null, null, Map.of("env", "restore"), "us-east-1");
assertEquals("restored-cluster", restored.getDbClusterIdentifier());
assertEquals("admin", restored.getMasterUsername());
assertEquals("dbname", restored.getDatabaseName());
assertEquals("16.3", restored.getEngineVersion());
assertEquals("restore", restored.getTags().get("env"));
verify(containerManager).restorePostgresSnapshot(any(), eq("admin"), eq("CLUSTER_DUMP"));
assertEquals("InvalidParameterValue", assertThrows(AwsException.class,
() -> rdsService.restoreDbClusterFromSnapshot("mysql-cluster", "csnap", "aurora-mysql",
null, null, null, null, null, null, null, null, null, "us-east-1")).getErrorCode());
assertEquals("DBClusterSnapshotNotFoundFault", assertThrows(AwsException.class,
() -> rdsService.restoreDbClusterFromSnapshot("other-cluster",
"arn:aws:rds:us-east-1:123456789012:cluster-snapshot:absent", "aurora-postgresql",
null, null, null, null, null, null, null, null, null, "us-east-1")).getErrorCode());
DbClusterSnapshot deleted = rdsService.deleteDbClusterSnapshot("csnap");
assertEquals("deleted", deleted.getStatus());
assertEquals("DBClusterSnapshotNotFoundFault", assertThrows(AwsException.class,
() -> rdsService.deleteDbClusterSnapshot("csnap")).getErrorCode());
assertEquals(1, rdsService.describeDbClusterSnapshots(null, null, null).size());
source.setStatus("creating");
copy.setStatus("copying");
assertEquals("InvalidDBClusterSnapshotStateFault", assertThrows(AwsException.class,
() -> rdsService.deleteDbClusterSnapshot("csnap-copy")).getErrorCode());
}
@Test
void clusterSnapshotRestoreAttributeIsSharedLikeAnInstanceSnapshots() {
clusterSnapshotOfNewCluster("csnap");
DbClusterSnapshot shared = rdsService.modifyDbClusterSnapshotAttribute(
"csnap", "restore", List.of("111122223333", "all"), null, "us-east-1");
assertEquals(List.of("111122223333", "all"), shared.getRestoreAccountIds());
DbClusterSnapshot narrowed = rdsService.modifyDbClusterSnapshotAttribute(
"csnap", "restore", null, List.of("all"), "us-east-1");
assertEquals(List.of("111122223333"), narrowed.getRestoreAccountIds());
assertEquals(List.of("111122223333"),
rdsService.describeDbClusterSnapshotAttributes("csnap", "us-east-1").getRestoreAccountIds());
assertEquals("InvalidParameterValue", assertThrows(AwsException.class,
() -> rdsService.modifyDbClusterSnapshotAttribute("csnap", "engine", List.of("x"), null, "us-east-1")).getErrorCode());
}
@Test
void dbSnapshotTagsRoundTripAndMutateByArn() {
rdsService.createDbInstance("mydb", "postgres", "13",