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

@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.core.common.AwsQueryResponse;
import io.github.hectorvent.floci.core.common.XmlBuilder;
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.model.DbEndpoint;
import io.github.hectorvent.floci.services.docdb.DocDbQueryHandler;
@@ -132,7 +133,13 @@ public class RdsQueryHandler {
case "DescribeDBProxyTargetGroups" -> handleDescribeDbProxyTargetGroups(params, region);
case "ModifyDBProxyTargetGroup" -> handleModifyDbProxyTargetGroup(params, region);
case "DescribeDBProxyTargets" -> handleDescribeDbProxyTargets(params, region);
case "DescribeDBClusterSnapshots" -> handleDescribeDbClusterSnapshots(params);
case "DescribeDBClusterSnapshots" -> handleDescribeDbClusterSnapshots(params, region);
case "CreateDBClusterSnapshot" -> handleCreateDbClusterSnapshot(params, region);
case "DeleteDBClusterSnapshot" -> handleDeleteDbClusterSnapshot(params, region);
case "CopyDBClusterSnapshot" -> handleCopyDbClusterSnapshot(params, region);
case "RestoreDBClusterFromSnapshot" -> handleRestoreDbClusterFromSnapshot(params, region);
case "DescribeDBClusterSnapshotAttributes" -> handleDescribeDbClusterSnapshotAttributes(params, region);
case "ModifyDBClusterSnapshotAttribute" -> handleModifyDbClusterSnapshotAttribute(params, region);
case "DescribeGlobalClusters" -> handleDescribeGlobalClusters(params);
case "CreateGlobalCluster" -> handleCreateGlobalCluster(params, region);
case "ModifyGlobalCluster" -> handleModifyGlobalCluster(params);
@@ -2000,12 +2007,92 @@ public class RdsQueryHandler {
return xml.end(elementName).build();
}
private Response handleDescribeDbClusterSnapshots(MultivaluedMap<String, String> params) {
// DB cluster snapshots are not modeled; return the RDS Query API's wire-accurate
// empty result (empty <DBClusterSnapshots> wrapper, no <Marker>) so SDK clients
// complete the read instead of failing with UnsupportedOperation.
String result = new XmlBuilder().start("DBClusterSnapshots").end("DBClusterSnapshots").build();
return Response.ok(AwsQueryResponse.envelope("DescribeDBClusterSnapshots", AwsNamespaces.RDS, result)).build();
private Response handleDescribeDbClusterSnapshots(MultivaluedMap<String, String> params, String region) {
XmlBuilder xml = new XmlBuilder().start("DBClusterSnapshots");
for (DbClusterSnapshot s : service.describeDbClusterSnapshots(
params.getFirst("DBClusterSnapshotIdentifier"), params.getFirst("DBClusterIdentifier"),
params.getFirst("SnapshotType"), region)) {
xml.raw(dbClusterSnapshotXml(s));
}
xml.end("DBClusterSnapshots");
return Response.ok(AwsQueryResponse.envelope("DescribeDBClusterSnapshots", AwsNamespaces.RDS, xml.build())).build();
}
private Response handleCreateDbClusterSnapshot(MultivaluedMap<String, String> params, String region) {
String snapshotId = params.getFirst("DBClusterSnapshotIdentifier");
String clusterId = params.getFirst("DBClusterIdentifier");
Response missing = firstMissingParam(
"DBClusterSnapshotIdentifier", snapshotId,
"DBClusterIdentifier", clusterId);
if (missing != null) {
return missing;
}
DbClusterSnapshot snapshot = service.createDbClusterSnapshot(snapshotId, clusterId, parseTags(params), region);
return Response.ok(AwsQueryResponse.envelope("CreateDBClusterSnapshot", AwsNamespaces.RDS,
dbClusterSnapshotXml(snapshot))).build();
}
private Response handleDeleteDbClusterSnapshot(MultivaluedMap<String, String> params, String region) {
String snapshotId = params.getFirst("DBClusterSnapshotIdentifier");
Response missing = firstMissingParam("DBClusterSnapshotIdentifier", snapshotId);
if (missing != null) {
return missing;
}
DbClusterSnapshot snapshot = service.deleteDbClusterSnapshot(snapshotId, region);
return Response.ok(AwsQueryResponse.envelope("DeleteDBClusterSnapshot", AwsNamespaces.RDS,
dbClusterSnapshotXml(snapshot))).build();
}
private Response handleCopyDbClusterSnapshot(MultivaluedMap<String, String> params, String region) {
String sourceId = params.getFirst("SourceDBClusterSnapshotIdentifier");
String targetId = params.getFirst("TargetDBClusterSnapshotIdentifier");
Response missing = firstMissingParam(
"SourceDBClusterSnapshotIdentifier", sourceId,
"TargetDBClusterSnapshotIdentifier", targetId);
if (missing != null) {
return missing;
}
boolean copyTags = "true".equalsIgnoreCase(params.getFirst("CopyTags"));
DbClusterSnapshot copy = service.copyDbClusterSnapshot(sourceId, targetId, copyTags, parseTags(params), region);
return Response.ok(AwsQueryResponse.envelope("CopyDBClusterSnapshot", AwsNamespaces.RDS,
dbClusterSnapshotXml(copy))).build();
}
private Response handleRestoreDbClusterFromSnapshot(MultivaluedMap<String, String> params, String region) {
String clusterId = params.getFirst("DBClusterIdentifier");
String snapshotId = params.getFirst("SnapshotIdentifier");
String engine = params.getFirst("Engine");
Response missing = firstMissingParam(
"DBClusterIdentifier", clusterId,
"SnapshotIdentifier", snapshotId,
"Engine", engine);
if (missing != null) {
return missing;
}
DbCluster cluster = service.restoreDbClusterFromSnapshot(clusterId, snapshotId, engine,
params.getFirst("EngineVersion"), optionalInt(params.getFirst("Port")),
params.getFirst("DatabaseName"), params.getFirst("DBSubnetGroupName"),
params.getFirst("DBClusterParameterGroupName"),
params.getFirst("AvailabilityZones.member.1"),
optionalBoolean(params.getFirst("EnableIAMDatabaseAuthentication")),
params.getFirst("EngineMode"), parseTags(params), region);
return Response.ok(AwsQueryResponse.envelope("RestoreDBClusterFromSnapshot", AwsNamespaces.RDS,
dbClusterXml(cluster))).build();
}
private Response handleDescribeDbClusterSnapshotAttributes(MultivaluedMap<String, String> params, String region) {
DbClusterSnapshot snapshot = service.describeDbClusterSnapshotAttributes(
params.getFirst("DBClusterSnapshotIdentifier"), region);
return Response.ok(AwsQueryResponse.envelope("DescribeDBClusterSnapshotAttributes", AwsNamespaces.RDS,
dbClusterSnapshotAttributesResultXml(snapshot))).build();
}
private Response handleModifyDbClusterSnapshotAttribute(MultivaluedMap<String, String> params, String region) {
DbClusterSnapshot snapshot = service.modifyDbClusterSnapshotAttribute(
params.getFirst("DBClusterSnapshotIdentifier"), params.getFirst("AttributeName"),
memberList(params, "ValuesToAdd"), memberList(params, "ValuesToRemove"), region);
return Response.ok(AwsQueryResponse.envelope("ModifyDBClusterSnapshotAttribute", AwsNamespaces.RDS,
dbClusterSnapshotAttributesResultXml(snapshot))).build();
}
// ── XML builders ──────────────────────────────────────────────────────────
@@ -2050,6 +2137,52 @@ public class RdsQueryHandler {
return xml.end("DBSnapshot").build();
}
private String dbClusterSnapshotXml(DbClusterSnapshot s) {
XmlBuilder xml = new XmlBuilder().start("DBClusterSnapshot");
xml.start("AvailabilityZones");
for (String zone : s.getAvailabilityZones()) {
xml.elem("AvailabilityZone", zone);
}
xml.end("AvailabilityZones");
xml.elem("DBClusterSnapshotIdentifier", s.getDbClusterSnapshotIdentifier())
.elem("DBClusterIdentifier", s.getDbClusterIdentifier())
.elem("SnapshotCreateTime", s.getSnapshotCreateTime() != null ? s.getSnapshotCreateTime().toString() : "")
.elem("Engine", s.getEngineIdentifier() != null ? s.getEngineIdentifier() : "")
.elem("EngineMode", s.getEngineMode() != null ? s.getEngineMode() : "provisioned")
.elem("AllocatedStorage", s.getAllocatedStorage())
.elem("Status", s.getStatus())
.elem("Port", s.getPort());
if (s.getVpcId() != null) xml.elem("VpcId", s.getVpcId());
xml.elem("ClusterCreateTime", s.getClusterCreateTime() != null ? s.getClusterCreateTime().toString() : "")
.elem("MasterUsername", s.getMasterUsername())
.elem("EngineVersion", s.getEngineVersion());
if (s.getLicenseModel() != null) xml.elem("LicenseModel", s.getLicenseModel());
xml.elem("SnapshotType", s.getSnapshotType())
.elem("PercentProgress", s.getPercentProgress())
.elem("StorageEncrypted", s.isStorageEncrypted());
if (s.getKmsKeyId() != null) xml.elem("KmsKeyId", s.getKmsKeyId());
xml.elem("DBClusterSnapshotArn", s.getDbClusterSnapshotArn());
if (s.getSourceDbClusterSnapshotArn() != null) xml.elem("SourceDBClusterSnapshotArn", s.getSourceDbClusterSnapshotArn());
xml.elem("IAMDatabaseAuthenticationEnabled", s.isIamDatabaseAuthenticationEnabled());
if (s.getDbClusterResourceId() != null) xml.elem("DbClusterResourceId", s.getDbClusterResourceId());
xml.start("TagList");
writeTags(xml, s.getTags());
xml.end("TagList");
return xml.end("DBClusterSnapshot").build();
}
private String dbClusterSnapshotAttributesResultXml(DbClusterSnapshot s) {
XmlBuilder xml = new XmlBuilder().start("DBClusterSnapshotAttributesResult")
.elem("DBClusterSnapshotIdentifier", s.getDbClusterSnapshotIdentifier());
xml.start("DBClusterSnapshotAttributes").start("DBClusterSnapshotAttribute")
.elem("AttributeName", "restore");
xml.start("AttributeValues");
s.getRestoreAccountIds().forEach(id -> xml.elem("AttributeValue", id));
xml.end("AttributeValues");
xml.end("DBClusterSnapshotAttribute").end("DBClusterSnapshotAttributes");
return xml.end("DBClusterSnapshotAttributesResult").build();
}
private String dbSnapshotAttributesResultXml(io.github.hectorvent.floci.services.rds.model.DbSnapshot s) {
XmlBuilder xml = new XmlBuilder().start("DBSnapshotAttributesResult")
.elem("DBSnapshotIdentifier", s.getDbSnapshotIdentifier());
@@ -28,6 +28,7 @@ import io.github.hectorvent.floci.services.rds.container.RdsContainerManager;
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.DbClusterParameterGroup;
import io.github.hectorvent.floci.services.rds.model.DbClusterSnapshot;
import io.github.hectorvent.floci.services.rds.model.DbEndpoint;
import io.github.hectorvent.floci.services.rds.model.DbInstance;
import io.github.hectorvent.floci.services.kms.KmsService;
@@ -70,6 +71,7 @@ import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -155,6 +157,7 @@ public class RdsService implements Resettable, ResourceProvider {
private final StorageBackend<String, DbProxy> proxies;
private final StorageBackend<String, DbProxyTargetGroup> proxyTargetGroups;
private final StorageBackend<String, DbSnapshot> snapshots;
private final StorageBackend<String, DbClusterSnapshot> clusterSnapshots;
private final StorageBackend<String, GlobalCluster> globalClusters;
private final StorageBackend<String, String> snapshotData;
private StorageBackend<String, RdsEvent> events = new InMemoryStorage<>();
@@ -239,6 +242,8 @@ public class RdsService implements Resettable, ResourceProvider {
new TypeReference<Map<String, GlobalCluster>>() {});
this.snapshots = storageFactory.create("rds", "rds-snapshots.json",
new TypeReference<Map<String, DbSnapshot>>() {});
this.clusterSnapshots = storageFactory.create("rds", "rds-cluster-snapshots.json",
new TypeReference<Map<String, DbClusterSnapshot>>() {});
this.snapshotData = storageFactory.create("rds", "rds-snapshot-data.json",
new TypeReference<Map<String, String>>() {});
this.events = storageFactory.create("rds", "rds-events.json",
@@ -376,6 +381,7 @@ public class RdsService implements Resettable, ResourceProvider {
this.taggingService = taggingService;
this.globalClusters = new io.github.hectorvent.floci.core.storage.InMemoryStorage<>();
this.snapshots = new io.github.hectorvent.floci.core.storage.InMemoryStorage<>();
this.clusterSnapshots = new InMemoryStorage<>();
this.snapshotData = new io.github.hectorvent.floci.core.storage.InMemoryStorage<>();
}
@@ -1470,6 +1476,350 @@ public class RdsService implements Resettable, ResourceProvider {
return snapshot;
}
// ── DB cluster snapshots ───────────────────────────────────────────────────
/**
* Takes a manual snapshot of an available cluster: its description plus a dump of its
* database, so RestoreDBClusterFromSnapshot can bring the data back into a new cluster.
*/
public DbClusterSnapshot createDbClusterSnapshot(String snapshotId, String clusterId, Map<String, String> tags) {
return createDbClusterSnapshot(snapshotId, clusterId, tags, regionResolver.getDefaultRegion());
}
public synchronized DbClusterSnapshot createDbClusterSnapshot(String snapshotId, String clusterId,
Map<String, String> tags, String region) {
String effectiveRegion = effectiveRegion(region);
String accountId = currentAccountId();
if (snapshotId == null || snapshotId.isBlank()) {
throw new AwsException("InvalidParameterValue", "DBClusterSnapshotIdentifier is required.", 400);
}
if (findClusterSnapshotForScope(accountId, effectiveRegion, snapshotId) != null) {
throw new AwsException("DBClusterSnapshotAlreadyExistsFault",
"DB cluster snapshot " + snapshotId + " already exists.", 400);
}
DbCluster cluster = getDbCluster(clusterId, effectiveRegion);
if (cluster.getStatus() != null && cluster.getStatus() != DbInstanceStatus.AVAILABLE) {
throw new AwsException("InvalidDBClusterStateFault",
"DB cluster " + clusterId + " is not available.", 400);
}
if (cluster.getEngine() != DatabaseEngine.POSTGRES) {
throw new AwsException("InvalidDBClusterStateFault",
"Operation CreateDBClusterSnapshot is not supported for engine " + cluster.getEngine() + ".", 400);
}
DbClusterSnapshot snapshot = clusterSnapshotOf(cluster, snapshotId, effectiveRegion);
snapshot.setTags(tags != null ? new LinkedHashMap<>(tags) : new LinkedHashMap<>());
String sqlDump = "";
if (!config.services().rds().mock()) {
try {
sqlDump = containerManager.createPostgresSnapshot(cluster.getContainerId(), cluster.getMasterUsername());
} catch (Exception e) {
LOG.warnv(e, "Failed to create snapshot {0} of DB cluster {1}", snapshotId, clusterId);
throw new AwsException("InvalidDBClusterStateFault", "Failed to create snapshot: " + e.getMessage(), 400);
}
}
snapshotData.put(clusterSnapshotDataKey(effectiveRegion, snapshotId), sqlDump);
putClusterSnapshotForScope(accountId, effectiveRegion, snapshotId, snapshot);
LOG.infov("Created DB cluster snapshot {0} of cluster {1}", snapshotId, clusterId);
return snapshot;
}
public Collection<DbClusterSnapshot> describeDbClusterSnapshots(String snapshotId, String clusterId, String snapshotType) {
return describeDbClusterSnapshots(snapshotId, clusterId, snapshotType, regionResolver.getDefaultRegion());
}
public Collection<DbClusterSnapshot> describeDbClusterSnapshots(String snapshotId, String clusterId,
String snapshotType, String region) {
String effectiveRegion = effectiveRegion(region);
String accountId = currentAccountId();
List<DbClusterSnapshot> matching;
if (snapshotId != null && !snapshotId.isBlank()) {
matching = List.of(requireClusterSnapshot(accountId, effectiveRegion, snapshotId));
} else {
matching = clusterSnapshots.scan(k -> true).stream()
.filter(s -> hasRdsResourceIdentity(s.getDbClusterSnapshotArn(), accountId, effectiveRegion,
"cluster-snapshot", s.getDbClusterSnapshotIdentifier()))
.toList();
}
return matching.stream()
.filter(s -> clusterId == null || clusterId.isBlank() || clusterId.equals(s.getDbClusterIdentifier()))
.filter(s -> snapshotType == null || snapshotType.isBlank() || snapshotType.equals(s.getSnapshotType()))
.toList();
}
/** Deletes an available cluster snapshot and its data, answering with the snapshot at status "deleted". */
public DbClusterSnapshot deleteDbClusterSnapshot(String snapshotId) {
return deleteDbClusterSnapshot(snapshotId, regionResolver.getDefaultRegion());
}
public synchronized DbClusterSnapshot deleteDbClusterSnapshot(String snapshotId, String region) {
String effectiveRegion = effectiveRegion(region);
String accountId = currentAccountId();
DbClusterSnapshot snapshot = requireClusterSnapshot(accountId, effectiveRegion, snapshotId);
requireClusterSnapshotAvailable(snapshot, "delete");
snapshotData.delete(clusterSnapshotDataKey(effectiveRegion, snapshotId));
deleteClusterSnapshotForScope(accountId, effectiveRegion, snapshotId);
snapshot.setStatus("deleted");
LOG.infov("Deleted DB cluster snapshot {0}", snapshotId);
return snapshot;
}
/** Copies an available cluster snapshot to a new manual one, recording the source ARN. */
public DbClusterSnapshot copyDbClusterSnapshot(String sourceSnapshotId, String targetSnapshotId,
boolean copyTags, Map<String, String> tags) {
return copyDbClusterSnapshot(sourceSnapshotId, targetSnapshotId, copyTags, tags, regionResolver.getDefaultRegion());
}
public synchronized DbClusterSnapshot copyDbClusterSnapshot(String sourceSnapshotId, String targetSnapshotId,
boolean copyTags, Map<String, String> tags, String region) {
String effectiveRegion = effectiveRegion(region);
String accountId = currentAccountId();
String sourceId = clusterSnapshotIdentifierFromArnOrName(sourceSnapshotId, effectiveRegion);
DbClusterSnapshot source = requireClusterSnapshot(accountId, effectiveRegion, sourceId);
requireClusterSnapshotAvailable(source, "copy");
if (targetSnapshotId == null || targetSnapshotId.isBlank()) {
throw new AwsException("InvalidParameterValue", "TargetDBClusterSnapshotIdentifier is required.", 400);
}
if (findClusterSnapshotForScope(accountId, effectiveRegion, targetSnapshotId) != null) {
throw new AwsException("DBClusterSnapshotAlreadyExistsFault",
"DB cluster snapshot " + targetSnapshotId + " already exists.", 400);
}
DbClusterSnapshot copy = copyOfClusterSnapshot(source, targetSnapshotId, effectiveRegion);
copy.setSourceDbClusterSnapshotArn(source.getDbClusterSnapshotArn());
Map<String, String> copiedTags = new LinkedHashMap<>();
if (copyTags) {
copiedTags.putAll(source.getTags());
}
if (tags != null) {
copiedTags.putAll(tags);
}
copy.setTags(copiedTags);
String sqlDump = snapshotData.get(clusterSnapshotDataKey(effectiveRegion, sourceId)).orElse("");
snapshotData.put(clusterSnapshotDataKey(effectiveRegion, targetSnapshotId), sqlDump);
putClusterSnapshotForScope(accountId, effectiveRegion, targetSnapshotId, copy);
LOG.infov("Copied DB cluster snapshot {0} to {1}", sourceId, targetSnapshotId);
return copy;
}
public DbClusterSnapshot describeDbClusterSnapshotAttributes(String snapshotId, String region) {
return requireClusterSnapshot(currentAccountId(), effectiveRegion(region), snapshotId);
}
/** The "restore" attribute, as ModifyDBSnapshotAttribute keeps it for instance snapshots. */
public synchronized DbClusterSnapshot modifyDbClusterSnapshotAttribute(String snapshotId, String attributeName,
List<String> valuesToAdd,
List<String> valuesToRemove, String region) {
String effectiveRegion = effectiveRegion(region);
String accountId = currentAccountId();
DbClusterSnapshot snapshot = requireClusterSnapshot(accountId, effectiveRegion, snapshotId);
if (!"restore".equals(attributeName)) {
throw new AwsException("InvalidParameterValue", "AttributeName must be restore.", 400);
}
requireClusterSnapshotAvailable(snapshot, "share");
List<String> updated = new ArrayList<>(snapshot.getRestoreAccountIds());
if (valuesToAdd != null) {
valuesToAdd.stream().filter(v -> !updated.contains(v)).forEach(updated::add);
}
if (valuesToRemove != null) {
updated.removeAll(valuesToRemove);
}
snapshot.setRestoreAccountIds(updated);
putClusterSnapshotForScope(accountId, effectiveRegion, snapshotId, snapshot);
return snapshot;
}
/**
* Creates a new cluster from a cluster snapshot: the snapshot's engine, credentials and
* database, the request's overrides where AWS allows them, and then the snapshot's data
* restored into the new cluster's database.
*/
public DbCluster restoreDbClusterFromSnapshot(String clusterId, String snapshotId, String engine,
String engineVersion, Integer port, String databaseName,
String dbSubnetGroupName, String parameterGroupName,
String availabilityZone, Boolean iamEnabled, String engineMode,
Map<String, String> tags, String region) {
String effectiveRegion = effectiveRegion(region);
String accountId = currentAccountId();
// SnapshotIdentifier takes the snapshot's name or its ARN (API reference).
String resolvedSnapshotId = clusterSnapshotIdentifierFromArnOrName(snapshotId, effectiveRegion);
DbClusterSnapshot snapshot = requireClusterSnapshot(accountId, effectiveRegion, resolvedSnapshotId);
requireClusterSnapshotAvailable(snapshot, "restore from");
if (engine == null || engine.isBlank()) {
throw new AwsException("InvalidParameterValue", "Engine is required.", 400);
}
if (resolveEngine(engine) != snapshot.getEngine()) {
throw new AwsException("InvalidParameterValue",
"The snapshot's engine is " + snapshot.getEngineIdentifier() + "; cannot restore it as " + engine + ".", 400);
}
String sqlDump = snapshotData.get(clusterSnapshotDataKey(effectiveRegion, resolvedSnapshotId))
.orElseThrow(() -> new AwsException("DBClusterSnapshotNotFoundFault",
"DB cluster snapshot data for " + resolvedSnapshotId + " not found.", 404));
DbCluster cluster = createDbCluster(clusterId, engine,
engineVersion != null && !engineVersion.isBlank() ? engineVersion : snapshot.getEngineVersion(),
snapshot.getMasterUsername(), snapshot.getMasterPassword(),
databaseName != null && !databaseName.isBlank() ? databaseName : snapshot.getDatabaseName(),
iamEnabled != null ? iamEnabled : snapshot.isIamDatabaseAuthenticationEnabled(),
parameterGroupName, dbSubnetGroupName, availabilityZone, false, effectiveRegion,
null, null, null, false, null,
engineMode != null && !engineMode.isBlank() ? engineMode : snapshot.getEngineMode(),
snapshot.isStorageEncrypted());
if (tags != null && !tags.isEmpty()) {
cluster.getTags().putAll(tags);
putClusterForScope(accountId, effectiveRegion, clusterId, cluster);
}
if (!config.services().rds().mock()) {
try {
containerManager.restorePostgresSnapshot(cluster.getContainerId(), cluster.getMasterUsername(), sqlDump);
} catch (Exception e) {
try {
deleteDbCluster(clusterId, effectiveRegion);
} catch (Exception cleanupError) {
e.addSuppressed(cleanupError);
}
AwsException awsEx = new AwsException("InvalidDBClusterSnapshotStateFault",
"Failed to restore snapshot: " + e.getMessage(), 400);
awsEx.initCause(e);
throw awsEx;
}
}
return cluster;
}
private DbClusterSnapshot clusterSnapshotOf(DbCluster cluster, String snapshotId, String region) {
DbClusterSnapshot snapshot = new DbClusterSnapshot();
snapshot.setDbClusterSnapshotIdentifier(snapshotId);
snapshot.setDbClusterSnapshotArn(regionResolver.buildArn("rds", region, "cluster-snapshot:" + snapshotId));
snapshot.setDbClusterIdentifier(cluster.getDbClusterIdentifier());
snapshot.setSnapshotCreateTime(Instant.now());
snapshot.setClusterCreateTime(cluster.getCreatedAt());
snapshot.setEngine(cluster.getEngine());
snapshot.setEngineIdentifier(cluster.getEngineIdentifier() != null
? cluster.getEngineIdentifier() : cluster.getEngine().name().toLowerCase(Locale.ROOT));
snapshot.setEngineVersion(cluster.getEngineVersion());
snapshot.setEngineMode(cluster.getEngineMode());
// Aurora reports 1 GiB for a cluster snapshot: storage is not provisioned per cluster.
snapshot.setAllocatedStorage(1);
snapshot.setStatus("available");
snapshot.setPercentProgress(100);
snapshot.setPort(cluster.getEndpoint() != null ? cluster.getEndpoint().port() : cluster.getProxyPort());
snapshot.setVpcId(cluster.getVpcId());
if (cluster.getAvailabilityZone() != null) {
snapshot.setAvailabilityZones(new ArrayList<>(List.of(cluster.getAvailabilityZone())));
}
snapshot.setMasterUsername(cluster.getMasterUsername());
snapshot.setMasterPassword(cluster.getMasterPassword());
snapshot.setDatabaseName(cluster.getDatabaseName());
snapshot.setLicenseModel("postgresql-license");
snapshot.setStorageEncrypted(cluster.isStorageEncrypted());
snapshot.setIamDatabaseAuthenticationEnabled(cluster.isIamDatabaseAuthenticationEnabled());
snapshot.setDbClusterResourceId(cluster.getDbClusterResourceId());
return snapshot;
}
private DbClusterSnapshot copyOfClusterSnapshot(DbClusterSnapshot source, String targetId, String region) {
DbClusterSnapshot copy = new DbClusterSnapshot();
copy.setDbClusterSnapshotIdentifier(targetId);
copy.setDbClusterSnapshotArn(regionResolver.buildArn("rds", region, "cluster-snapshot:" + targetId));
copy.setDbClusterIdentifier(source.getDbClusterIdentifier());
copy.setSnapshotCreateTime(Instant.now());
copy.setClusterCreateTime(source.getClusterCreateTime());
copy.setEngine(source.getEngine());
copy.setEngineIdentifier(source.getEngineIdentifier());
copy.setEngineVersion(source.getEngineVersion());
copy.setEngineMode(source.getEngineMode());
copy.setAllocatedStorage(source.getAllocatedStorage());
copy.setStatus("available");
copy.setPercentProgress(100);
copy.setPort(source.getPort());
copy.setVpcId(source.getVpcId());
copy.setAvailabilityZones(new ArrayList<>(source.getAvailabilityZones()));
copy.setMasterUsername(source.getMasterUsername());
copy.setMasterPassword(source.getMasterPassword());
copy.setDatabaseName(source.getDatabaseName());
copy.setLicenseModel(source.getLicenseModel());
copy.setStorageEncrypted(source.isStorageEncrypted());
copy.setKmsKeyId(source.getKmsKeyId());
copy.setIamDatabaseAuthenticationEnabled(source.isIamDatabaseAuthenticationEnabled());
copy.setDbClusterResourceId(source.getDbClusterResourceId());
return copy;
}
private DbClusterSnapshot requireClusterSnapshot(String accountId, String region, String snapshotId) {
if (snapshotId == null || snapshotId.isBlank()) {
throw new AwsException("InvalidParameterValue", "DBClusterSnapshotIdentifier is required.", 400);
}
return Optional.ofNullable(findClusterSnapshotForScope(accountId, region, snapshotId))
.orElseThrow(() -> new AwsException("DBClusterSnapshotNotFoundFault",
"DBClusterSnapshot " + snapshotId + " not found.", 404));
}
private static void requireClusterSnapshotAvailable(DbClusterSnapshot snapshot, String operation) {
if (!"available".equals(snapshot.getStatus())) {
throw new AwsException("InvalidDBClusterSnapshotStateFault",
"Cannot " + operation + " DB cluster snapshot " + snapshot.getDbClusterSnapshotIdentifier()
+ " while its status is " + snapshot.getStatus() + ".", 400);
}
}
private String clusterSnapshotIdentifierFromArnOrName(String source, String region) {
if (source == null || source.isBlank()) {
throw new AwsException("InvalidParameterValue", "A DB cluster snapshot identifier is required.", 400);
}
if (!source.startsWith("arn:")) {
return source;
}
AwsArnUtils.Arn arn;
try {
arn = AwsArnUtils.parse(source);
} catch (IllegalArgumentException malformed) {
throw new AwsException("InvalidParameterValue", "Invalid snapshot identifier: " + source, 400);
}
String resource = arn.resource();
if (!"rds".equals(arn.service()) || !resource.startsWith("cluster-snapshot:")) {
throw new AwsException("InvalidParameterValue", "Invalid snapshot identifier: " + source, 400);
}
if (!region.equals(arn.region())) {
throw new AwsException("InvalidParameterValue",
"Cross-region snapshot copy is not supported: " + source, 400);
}
return resource.substring("cluster-snapshot:".length());
}
/** Cluster snapshot dumps share the snapshot data store with instance snapshots under their own prefix. */
private String clusterSnapshotDataKey(String region, String snapshotId) {
return dbResourceKey(region, "cluster-snapshot:" + snapshotId);
}
private synchronized DbClusterSnapshot findClusterSnapshotForScope(String accountId, String region, String snapshotId) {
String key = dbResourceKey(region, snapshotId);
Predicate<DbClusterSnapshot> owner = snapshot -> hasRdsResourceIdentity(
snapshot.getDbClusterSnapshotArn(), accountId, region, "cluster-snapshot", snapshotId);
if (clusterSnapshots instanceof AccountAwareStorageBackend<DbClusterSnapshot> aware) {
return aware.getForAccount(accountId, key).filter(owner).orElse(null);
}
return clusterSnapshots.get(key).filter(owner).orElse(null);
}
private void putClusterSnapshotForScope(String accountId, String region, String snapshotId, DbClusterSnapshot snapshot) {
String key = dbResourceKey(region, snapshotId);
if (clusterSnapshots instanceof AccountAwareStorageBackend<DbClusterSnapshot> aware) {
aware.putForAccount(accountId, key, snapshot);
} else {
clusterSnapshots.put(key, snapshot);
}
}
private void deleteClusterSnapshotForScope(String accountId, String region, String snapshotId) {
String key = dbResourceKey(region, snapshotId);
if (clusterSnapshots instanceof AccountAwareStorageBackend<DbClusterSnapshot> aware) {
aware.deleteForAccount(accountId, key);
} else {
clusterSnapshots.delete(key);
}
}
public Map<String, String> listTagsForResource(String resourceName) {
return listTagsForResource(resourceName, resourceRegionOrDefault(resourceName));
}
@@ -1575,6 +1925,13 @@ public class RdsService implements Resettable, ResourceProvider {
currentAccountId(), effectiveRegion, resourceId, group);
});
}
case "cluster-snapshot" -> {
DbClusterSnapshot snapshot = requireClusterSnapshot(currentAccountId(), effectiveRegion, resourceId);
yield new TagHandle(snapshot.getTags(), updated -> {
snapshot.setTags(updated);
putClusterSnapshotForScope(currentAccountId(), effectiveRegion, resourceId, snapshot);
});
}
case "snapshot" -> {
DbSnapshot snapshot = Optional.ofNullable(
findSnapshotForScope(currentAccountId(), effectiveRegion, resourceId))
@@ -0,0 +1,125 @@
package io.github.hectorvent.floci.services.rds.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* A manual DB cluster snapshot, the {@code DBClusterSnapshot} structure of the RDS API. The
* cluster's data is kept beside it in the snapshot data store, keyed by the snapshot id.
*/
@RegisterForReflection
public class DbClusterSnapshot {
private String dbClusterSnapshotIdentifier;
private String dbClusterSnapshotArn;
private String dbClusterIdentifier;
private Instant snapshotCreateTime;
private Instant clusterCreateTime;
private DatabaseEngine engine;
private String engineIdentifier;
private String engineVersion;
private String engineMode;
private int allocatedStorage;
private String status;
private int port;
private String vpcId;
private List<String> availabilityZones = new ArrayList<>();
private String masterUsername;
private String masterPassword;
private String databaseName;
private String licenseModel;
private String snapshotType = "manual";
private int percentProgress;
private boolean storageEncrypted;
private String kmsKeyId;
private String sourceDbClusterSnapshotArn;
private boolean iamDatabaseAuthenticationEnabled;
private String dbClusterResourceId;
private Map<String, String> tags = new LinkedHashMap<>();
private List<String> restoreAccountIds = new ArrayList<>();
public String getDbClusterSnapshotIdentifier() { return dbClusterSnapshotIdentifier; }
public void setDbClusterSnapshotIdentifier(String v) { this.dbClusterSnapshotIdentifier = v; }
public String getDbClusterSnapshotArn() { return dbClusterSnapshotArn; }
public void setDbClusterSnapshotArn(String v) { this.dbClusterSnapshotArn = v; }
public String getDbClusterIdentifier() { return dbClusterIdentifier; }
public void setDbClusterIdentifier(String v) { this.dbClusterIdentifier = v; }
public Instant getSnapshotCreateTime() { return snapshotCreateTime; }
public void setSnapshotCreateTime(Instant v) { this.snapshotCreateTime = v; }
public Instant getClusterCreateTime() { return clusterCreateTime; }
public void setClusterCreateTime(Instant v) { this.clusterCreateTime = v; }
public DatabaseEngine getEngine() { return engine; }
public void setEngine(DatabaseEngine v) { this.engine = v; }
public String getEngineIdentifier() { return engineIdentifier; }
public void setEngineIdentifier(String v) { this.engineIdentifier = v; }
public String getEngineVersion() { return engineVersion; }
public void setEngineVersion(String v) { this.engineVersion = v; }
public String getEngineMode() { return engineMode; }
public void setEngineMode(String v) { this.engineMode = v; }
public int getAllocatedStorage() { return allocatedStorage; }
public void setAllocatedStorage(int v) { this.allocatedStorage = v; }
public String getStatus() { return status; }
public void setStatus(String v) { this.status = v; }
public int getPort() { return port; }
public void setPort(int v) { this.port = v; }
public String getVpcId() { return vpcId; }
public void setVpcId(String v) { this.vpcId = v; }
public List<String> getAvailabilityZones() { return availabilityZones; }
public void setAvailabilityZones(List<String> v) { this.availabilityZones = v; }
public String getMasterUsername() { return masterUsername; }
public void setMasterUsername(String v) { this.masterUsername = v; }
public String getMasterPassword() { return masterPassword; }
public void setMasterPassword(String v) { this.masterPassword = v; }
public String getDatabaseName() { return databaseName; }
public void setDatabaseName(String v) { this.databaseName = v; }
public String getLicenseModel() { return licenseModel; }
public void setLicenseModel(String v) { this.licenseModel = v; }
public String getSnapshotType() { return snapshotType; }
public void setSnapshotType(String v) { this.snapshotType = v; }
public int getPercentProgress() { return percentProgress; }
public void setPercentProgress(int v) { this.percentProgress = v; }
public boolean isStorageEncrypted() { return storageEncrypted; }
public void setStorageEncrypted(boolean v) { this.storageEncrypted = v; }
public String getKmsKeyId() { return kmsKeyId; }
public void setKmsKeyId(String v) { this.kmsKeyId = v; }
public String getSourceDbClusterSnapshotArn() { return sourceDbClusterSnapshotArn; }
public void setSourceDbClusterSnapshotArn(String v) { this.sourceDbClusterSnapshotArn = v; }
public boolean isIamDatabaseAuthenticationEnabled() { return iamDatabaseAuthenticationEnabled; }
public void setIamDatabaseAuthenticationEnabled(boolean v) { this.iamDatabaseAuthenticationEnabled = v; }
public String getDbClusterResourceId() { return dbClusterResourceId; }
public void setDbClusterResourceId(String v) { this.dbClusterResourceId = v; }
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> v) { this.tags = v; }
public List<String> getRestoreAccountIds() { return restoreAccountIds; }
public void setRestoreAccountIds(List<String> v) { this.restoreAccountIds = v; }
}