mirror of
https://github.com/floci-io/floci.git
synced 2026-11-26 23:29:28 -05:00
feat(docdb): support cluster snapshots and restores (#7585)
Adds CreateDBClusterSnapshot, DeleteDBClusterSnapshot, RestoreDBClusterFromSnapshot and RestoreDBClusterToPointInTime, and makes DescribeDBClusterSnapshots list stored snapshots. A snapshot is a mongodump archive of the cluster's MongoDB container; rds-signed requests naming a DocumentDB cluster or snapshot are routed to DocumentDB. fix(docdb): round out cluster snapshots and restores after review List DocumentDB snapshots in the RDS-family list form on either endpoint, accept snapshot ARNs, keep the source's encryption and key on restore, check restore and snapshot identifiers against RDS too, read a point-in-time restore's data as a snapshot does, refuse RestoreToTime, apply every describe filter, and remove a cluster whose restore failed even under deletion protection. Drop the unrelated endpoint host, container-name host and audit log group changes. Cover the archive reaching the restored cluster outside mock mode. Read a snapshot's record and archive together under the snapshot lock delete takes, and refuse a restore whose archive is missing or empty before any cluster exists; a snapshot taken in mock mode is marked metadata-only and restores only in mock mode. A KmsKeyId on RestoreDBClusterFromSnapshot now encrypts the restored cluster under that key even when the snapshot is unencrypted, as the restore guide allows; the point-in-time restore still refuses one for an unencrypted source. Share the docdb-scoped request in the integration test.
This commit is contained in:
1 parent
5fe30ee5eb
commit
46a8cbe51d
13 files changed
+1260
-19
No files matched your search
@@ -211,6 +211,11 @@ public class AwsQueryController {
|
||||
if ("docdb".equalsIgnoreCase(engine)
|
||||
|| docDbService.hasCluster(clusterId, region)
|
||||
|| docDbService.hasInstance(instanceId, region)
|
||||
|| docDbService.hasCluster(formParams.getFirst("SourceDBClusterIdentifier"), region)
|
||||
// A create names the snapshot it makes, not one that exists: it follows its cluster.
|
||||
|| (!"CreateDBClusterSnapshot".equals(action)
|
||||
&& docDbService.hasClusterSnapshot(formParams.getFirst("DBClusterSnapshotIdentifier"), region))
|
||||
|| docDbService.hasClusterSnapshot(formParams.getFirst("SnapshotIdentifier"), region)
|
||||
|| namesDocDbResource(formParams.getFirst("ResourceName"), region)) {
|
||||
yield docDbQueryHandler.handle(action, formParams);
|
||||
}
|
||||
@@ -300,7 +305,9 @@ public class AwsQueryController {
|
||||
* check has to run on every route that reaches DocumentDB, not only the {@code rds} scope.
|
||||
*
|
||||
* <p>Only the identifier being created is checked: {@code CreateDBInstance} names its parent
|
||||
* cluster too, and that cluster existing in RDS is the normal case rather than a clash.
|
||||
* cluster too, and that cluster existing in RDS is the normal case rather than a clash. The
|
||||
* restores create a cluster and {@code CreateDBClusterSnapshot} a snapshot, so those identifiers
|
||||
* are checked against both stores, which share one cluster and cluster-snapshot ARN space.
|
||||
*/
|
||||
private Response rdsAlreadyHoldsIdentifier(String action,
|
||||
MultivaluedMap<String, String> formParams,
|
||||
@@ -313,6 +320,19 @@ public class AwsQueryController {
|
||||
null, formParams.getFirst("DBInstanceIdentifier"), region)) {
|
||||
return xmlErrorResponse("DBInstanceAlreadyExists", "DB Instance already exists", 400);
|
||||
}
|
||||
if ("RestoreDBClusterFromSnapshot".equals(action) || "RestoreDBClusterToPointInTime".equals(action)) {
|
||||
String clusterId = formParams.getFirst("DBClusterIdentifier");
|
||||
if (rdsService.hasClusterOrInstance(clusterId, null, region) || docDbService.hasCluster(clusterId, region)) {
|
||||
return xmlErrorResponse("DBClusterAlreadyExistsFault", "DB Cluster already exists", 400);
|
||||
}
|
||||
}
|
||||
if ("CreateDBClusterSnapshot".equals(action)) {
|
||||
String snapshotId = formParams.getFirst("DBClusterSnapshotIdentifier");
|
||||
if (rdsService.hasClusterSnapshot(snapshotId, region) || docDbService.hasClusterSnapshot(snapshotId, region)) {
|
||||
return xmlErrorResponse("DBClusterSnapshotAlreadyExistsFault",
|
||||
"DB cluster snapshot " + snapshotId + " already exists.", 400);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -336,6 +356,8 @@ public class AwsQueryController {
|
||||
return switch (action) {
|
||||
case "DescribeDBClusters" -> isBlank(formParams.getFirst("DBClusterIdentifier"));
|
||||
case "DescribeDBInstances" -> isBlank(formParams.getFirst("DBInstanceIdentifier"));
|
||||
case "DescribeDBClusterSnapshots" -> isBlank(formParams.getFirst("DBClusterSnapshotIdentifier"))
|
||||
&& isBlank(formParams.getFirst("DBClusterIdentifier"));
|
||||
default -> false;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import io.floci.aws.core.common.RdsFamilyQuerySupport;
|
||||
import io.floci.aws.core.common.XmlBuilder;
|
||||
import io.floci.aws.services.docdb.model.DocDbCluster;
|
||||
import io.floci.aws.services.docdb.model.DocDbClusterSettings;
|
||||
import io.floci.aws.services.docdb.model.DocDbClusterSnapshot;
|
||||
import io.floci.aws.services.docdb.model.DocDbInstance;
|
||||
import io.floci.aws.services.docdb.model.DocDbInstanceSettings;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
@@ -44,6 +45,10 @@ public class DocDbQueryHandler {
|
||||
case "CreateDBCluster" -> handleCreateDbCluster(params);
|
||||
case "DescribeDBClusters" -> handleDescribeDbClusters(params);
|
||||
case "DescribeDBClusterSnapshots" -> handleDescribeDbClusterSnapshots(params);
|
||||
case "CreateDBClusterSnapshot" -> handleCreateDbClusterSnapshot(params);
|
||||
case "DeleteDBClusterSnapshot" -> handleDeleteDbClusterSnapshot(params);
|
||||
case "RestoreDBClusterFromSnapshot" -> handleRestoreDbClusterFromSnapshot(params);
|
||||
case "RestoreDBClusterToPointInTime" -> handleRestoreDbClusterToPointInTime(params);
|
||||
case "DescribeGlobalClusters" -> handleDescribeGlobalClusters(params);
|
||||
case "DeleteDBCluster" -> handleDeleteDbCluster(params);
|
||||
case "ModifyDBCluster" -> handleModifyDbCluster(params);
|
||||
@@ -120,6 +125,16 @@ public class DocDbQueryHandler {
|
||||
return service.listDbClusters(filterId).stream().map(this::clusterInnerXml).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* The rows the list form of DescribeDBClusterSnapshots would return, for the RDS-family listing
|
||||
* {@code RdsQueryHandler} assembles: a live account lists DocumentDB cluster snapshots from the
|
||||
* RDS endpoint too.
|
||||
*/
|
||||
public List<String> clusterSnapshotRowsXml(String clusterId, String snapshotType) {
|
||||
return service.describeDbClusterSnapshots(null, clusterId, snapshotType).stream()
|
||||
.map(this::snapshotInnerXml).toList();
|
||||
}
|
||||
|
||||
public List<String> instanceRowsXml(String filterId) {
|
||||
return service.listDbInstances(filterId).stream().map(this::instanceInnerXml).toList();
|
||||
}
|
||||
@@ -129,13 +144,104 @@ public class DocDbQueryHandler {
|
||||
}
|
||||
|
||||
private Response handleDescribeDbClusterSnapshots(MultivaluedMap<String, String> params) {
|
||||
// Snapshots are not modeled by the emulator; return the wire-accurate empty result
|
||||
// the DocDB/RDS Query API uses (empty <DBClusterSnapshots/>, no <Marker>) so SDK
|
||||
// clients complete the read instead of failing on an unsupported action.
|
||||
XmlBuilder xml = new XmlBuilder().start("DBClusterSnapshots").end("DBClusterSnapshots");
|
||||
String clusterId = params.getFirst("DBClusterIdentifier");
|
||||
if (clusterId == null || clusterId.isBlank()) {
|
||||
clusterId = extractFilterValue(params, "db-cluster-id");
|
||||
}
|
||||
List<DocDbClusterSnapshot> found = service.describeDbClusterSnapshots(
|
||||
params.getFirst("DBClusterSnapshotIdentifier"), clusterId, params.getFirst("SnapshotType"));
|
||||
XmlBuilder xml = new XmlBuilder().start("DBClusterSnapshots");
|
||||
for (DocDbClusterSnapshot snapshot : found) {
|
||||
xml.start("DBClusterSnapshot").raw(snapshotInnerXml(snapshot)).end("DBClusterSnapshot");
|
||||
}
|
||||
xml.end("DBClusterSnapshots");
|
||||
return Response.ok(AwsQueryResponse.envelope("DescribeDBClusterSnapshots", AwsNamespaces.RDS, xml.build())).build();
|
||||
}
|
||||
|
||||
private Response handleCreateDbClusterSnapshot(MultivaluedMap<String, String> params) {
|
||||
DocDbClusterSnapshot snapshot = service.createDbClusterSnapshot(
|
||||
params.getFirst("DBClusterSnapshotIdentifier"), params.getFirst("DBClusterIdentifier"),
|
||||
parseTags(params));
|
||||
return Response.ok(AwsQueryResponse.envelope("CreateDBClusterSnapshot", AwsNamespaces.RDS,
|
||||
snapshotXml(snapshot))).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteDbClusterSnapshot(MultivaluedMap<String, String> params) {
|
||||
DocDbClusterSnapshot snapshot = service.deleteDbClusterSnapshot(params.getFirst("DBClusterSnapshotIdentifier"));
|
||||
return Response.ok(AwsQueryResponse.envelope("DeleteDBClusterSnapshot", AwsNamespaces.RDS,
|
||||
snapshotXml(snapshot))).build();
|
||||
}
|
||||
|
||||
private Response handleRestoreDbClusterFromSnapshot(MultivaluedMap<String, String> params) {
|
||||
String id = params.getFirst("DBClusterIdentifier");
|
||||
String snapshotId = params.getFirst("SnapshotIdentifier");
|
||||
if (id == null || id.isBlank() || snapshotId == null || snapshotId.isBlank()) {
|
||||
return AwsQueryResponse.error("InvalidParameterValue",
|
||||
"DBClusterIdentifier and SnapshotIdentifier are required.", AwsNamespaces.RDS, 400);
|
||||
}
|
||||
DocDbCluster cluster = service.restoreDbClusterFromSnapshot(id, snapshotId,
|
||||
params.getFirst("EngineVersion"), clusterSettings(params, true), parseTags(params));
|
||||
return Response.ok(AwsQueryResponse.envelope("RestoreDBClusterFromSnapshot", AwsNamespaces.RDS,
|
||||
clusterXml(cluster))).build();
|
||||
}
|
||||
|
||||
private Response handleRestoreDbClusterToPointInTime(MultivaluedMap<String, String> params) {
|
||||
String id = params.getFirst("DBClusterIdentifier");
|
||||
String sourceId = params.getFirst("SourceDBClusterIdentifier");
|
||||
if (id == null || id.isBlank() || sourceId == null || sourceId.isBlank()) {
|
||||
return AwsQueryResponse.error("InvalidParameterValue",
|
||||
"DBClusterIdentifier and SourceDBClusterIdentifier are required.", AwsNamespaces.RDS, 400);
|
||||
}
|
||||
// The same checks as RDS's restore; only the latest restorable time is modeled, so a
|
||||
// requested time is refused rather than silently answered with the source's current data.
|
||||
boolean restoreTimeGiven = params.getFirst("RestoreToTime") != null && !params.getFirst("RestoreToTime").isBlank();
|
||||
boolean latestRequested = Boolean.TRUE.equals(optionalBoolean(params.getFirst("UseLatestRestorableTime")));
|
||||
if (restoreTimeGiven && latestRequested) {
|
||||
return AwsQueryResponse.error("InvalidParameterCombination",
|
||||
"RestoreToTime cannot be specified when UseLatestRestorableTime is true.", AwsNamespaces.RDS, 400);
|
||||
}
|
||||
if (!restoreTimeGiven && !latestRequested) {
|
||||
return AwsQueryResponse.error("InvalidParameterCombination",
|
||||
"Specify either RestoreToTime or UseLatestRestorableTime.", AwsNamespaces.RDS, 400);
|
||||
}
|
||||
if (restoreTimeGiven) {
|
||||
return AwsQueryResponse.error("InvalidParameterValue",
|
||||
"Floci restores DocumentDB clusters to the latest restorable time only; use UseLatestRestorableTime.",
|
||||
AwsNamespaces.RDS, 400);
|
||||
}
|
||||
DocDbCluster cluster = service.restoreDbClusterToPointInTime(id, sourceId,
|
||||
clusterSettings(params, true), parseTags(params));
|
||||
return Response.ok(AwsQueryResponse.envelope("RestoreDBClusterToPointInTime", AwsNamespaces.RDS,
|
||||
clusterXml(cluster))).build();
|
||||
}
|
||||
|
||||
private String snapshotXml(DocDbClusterSnapshot snapshot) {
|
||||
return new XmlBuilder().start("DBClusterSnapshot").raw(snapshotInnerXml(snapshot))
|
||||
.end("DBClusterSnapshot").build();
|
||||
}
|
||||
|
||||
private String snapshotInnerXml(DocDbClusterSnapshot s) {
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.elem("DBClusterSnapshotIdentifier", s.getDbClusterSnapshotIdentifier())
|
||||
.elem("DBClusterIdentifier", s.getDbClusterIdentifier())
|
||||
.elem("SnapshotCreateTime", s.getSnapshotCreateTime() != null ? s.getSnapshotCreateTime().toString() : "")
|
||||
.elem("Engine", "docdb")
|
||||
.elem("Status", s.getStatus())
|
||||
.elem("Port", s.getPort())
|
||||
.elem("ClusterCreateTime", s.getClusterCreateTime() != null ? s.getClusterCreateTime().toString() : "")
|
||||
.elem("MasterUsername", s.getMasterUsername())
|
||||
.elem("EngineVersion", s.getEngineVersion())
|
||||
.elem("SnapshotType", s.getSnapshotType())
|
||||
.elem("PercentProgress", 100)
|
||||
.elem("StorageEncrypted", s.isStorageEncrypted())
|
||||
.elem("DBClusterSnapshotArn", s.getDbClusterSnapshotArn());
|
||||
if (s.getKmsKeyId() != null && !s.getKmsKeyId().isBlank()) {
|
||||
xml.elem("KmsKeyId", s.getKmsKeyId());
|
||||
}
|
||||
return xml.start("AvailabilityZones").elem("AvailabilityZone", config.defaultAvailabilityZone())
|
||||
.end("AvailabilityZones").build();
|
||||
}
|
||||
|
||||
private Response handleDeleteDbCluster(MultivaluedMap<String, String> params) {
|
||||
String id = params.getFirst("DBClusterIdentifier");
|
||||
if (id == null || id.isBlank()) {
|
||||
|
||||
@@ -12,6 +12,7 @@ import io.floci.aws.services.docdb.container.DocDbContainerHandle;
|
||||
import io.floci.aws.services.docdb.container.DocDbContainerManager;
|
||||
import io.floci.aws.services.docdb.model.DocDbCluster;
|
||||
import io.floci.aws.services.docdb.model.DocDbClusterSettings;
|
||||
import io.floci.aws.services.docdb.model.DocDbClusterSnapshot;
|
||||
import io.floci.aws.services.docdb.model.DocDbInstance;
|
||||
import io.floci.aws.services.docdb.model.DocDbInstanceSettings;
|
||||
import io.floci.aws.services.ec2.Ec2Service;
|
||||
@@ -54,6 +55,9 @@ public class DocDbService {
|
||||
|
||||
private final StorageBackend<String, DocDbCluster> clusters;
|
||||
private final StorageBackend<String, DocDbInstance> instances;
|
||||
private final StorageBackend<String, DocDbClusterSnapshot> snapshots;
|
||||
/** Snapshot archives, keyed like the snapshot records they belong to. */
|
||||
private final StorageBackend<String, String> snapshotData;
|
||||
private final EmulatorConfig config;
|
||||
private final RegionResolver regionResolver;
|
||||
private final DocDbContainerManager containerManager;
|
||||
@@ -188,6 +192,10 @@ public class DocDbService {
|
||||
new TypeReference<Map<String, DocDbCluster>>() {});
|
||||
this.instances = storageFactory.create("docdb", "docdb-instances.json",
|
||||
new TypeReference<Map<String, DocDbInstance>>() {});
|
||||
this.snapshots = storageFactory.create("docdb", "docdb-cluster-snapshots.json",
|
||||
new TypeReference<Map<String, DocDbClusterSnapshot>>() {});
|
||||
this.snapshotData = storageFactory.create("docdb", "docdb-cluster-snapshot-data.json",
|
||||
new TypeReference<Map<String, String>>() {});
|
||||
}
|
||||
|
||||
// ── Clusters ──────────────────────────────────────────────────────────────
|
||||
@@ -640,18 +648,282 @@ public class DocDbService {
|
||||
"Cannot delete DocDB cluster " + id + " — it still has DB instances.", 400);
|
||||
}
|
||||
|
||||
cluster.setStatus("deleting");
|
||||
clusters.put(key(region, id), cluster);
|
||||
removeCluster(region, cluster);
|
||||
}
|
||||
}
|
||||
|
||||
if (cluster.getContainerId() != null) {
|
||||
containerManager.stop(new DocDbContainerHandle(
|
||||
cluster.getContainerId(), id,
|
||||
cluster.getContainerHost(), cluster.getContainerPort()));
|
||||
/** Stops a cluster's container and removes its record; the caller holds the cluster's lock. */
|
||||
private void removeCluster(String region, DocDbCluster cluster) {
|
||||
String id = cluster.getDbClusterIdentifier();
|
||||
cluster.setStatus("deleting");
|
||||
clusters.put(key(region, id), cluster);
|
||||
|
||||
if (cluster.getContainerId() != null) {
|
||||
containerManager.stop(new DocDbContainerHandle(
|
||||
cluster.getContainerId(), id,
|
||||
cluster.getContainerHost(), cluster.getContainerPort()));
|
||||
}
|
||||
|
||||
clusters.delete(key(region, id));
|
||||
writeLocks.remove("cluster:" + key(region, id));
|
||||
LOG.infov("DocDB cluster {0} deleted", id);
|
||||
}
|
||||
|
||||
// ── Cluster snapshots ─────────────────────────────────────────────────────
|
||||
|
||||
/** What a snapshot or a point-in-time restore takes from a cluster: its data and master password. */
|
||||
private record ClusterArchive(String data, String masterPassword) {}
|
||||
|
||||
/**
|
||||
* Takes a manual snapshot: a {@code mongodump} archive of the cluster's MongoDB container,
|
||||
* complete when this returns, so the snapshot is {@code available} straight away.
|
||||
*/
|
||||
public DocDbClusterSnapshot createDbClusterSnapshot(String snapshotId, String clusterId,
|
||||
Map<String, String> tags) {
|
||||
String region = regionResolver.getRegion();
|
||||
requireIdentifier(snapshotId, "DBClusterSnapshotIdentifier");
|
||||
DocDbCluster cluster = getDbCluster(clusterId, region);
|
||||
synchronized (lockFor("snapshot:" + key(region, snapshotId))) {
|
||||
if (snapshots.get(key(region, snapshotId)).isPresent()) {
|
||||
throw new AwsException("DBClusterSnapshotAlreadyExistsFault",
|
||||
"Cannot create the cluster snapshot because one with the identifier "
|
||||
+ snapshotId + " already exists.", 400);
|
||||
}
|
||||
ClusterArchive archive = archiveOf(cluster);
|
||||
DocDbClusterSnapshot snapshot = new DocDbClusterSnapshot();
|
||||
snapshot.setDbClusterSnapshotIdentifier(snapshotId);
|
||||
snapshot.setDbClusterIdentifier(clusterId);
|
||||
snapshot.setDbClusterSnapshotArn(regionResolver.buildArn("rds", region, "cluster-snapshot:" + snapshotId));
|
||||
snapshot.setStatus("available");
|
||||
snapshot.setSnapshotType("manual");
|
||||
snapshot.setEngineVersion(cluster.getEngineVersion());
|
||||
snapshot.setMasterUsername(cluster.getMasterUsername());
|
||||
snapshot.setMasterPassword(archive.masterPassword());
|
||||
snapshot.setPort(cluster.getPort());
|
||||
snapshot.setStorageEncrypted(cluster.isStorageEncrypted());
|
||||
snapshot.setKmsKeyId(cluster.getKmsKeyId());
|
||||
snapshot.setSnapshotCreateTime(Instant.now());
|
||||
snapshot.setClusterCreateTime(cluster.getCreatedAt());
|
||||
snapshot.setSizeBytes(archive.data().length() * 3L / 4L);
|
||||
snapshot.setMetadataOnly(config.services().docdb().mock());
|
||||
if (tags != null && !tags.isEmpty()) {
|
||||
snapshot.setTags(new LinkedHashMap<>(tags));
|
||||
}
|
||||
snapshotData.put(key(region, snapshotId), archive.data());
|
||||
snapshots.put(key(region, snapshotId), snapshot);
|
||||
LOG.infov("DocDB cluster snapshot {0} of {1} created ({2} bytes)",
|
||||
snapshotId, clusterId, String.valueOf(snapshot.getSizeBytes()));
|
||||
return snapshot;
|
||||
}
|
||||
}
|
||||
|
||||
clusters.delete(key(region, id));
|
||||
writeLocks.remove("cluster:" + key(region, id));
|
||||
LOG.infov("DocDB cluster {0} deleted", id);
|
||||
/**
|
||||
* The cluster's data and master password, read from its MongoDB container. A snapshot and a
|
||||
* point-in-time restore both take them this way, with the same checks: the cluster has to be
|
||||
* available and, outside mock mode, running a backend whose data can be read.
|
||||
*/
|
||||
private ClusterArchive archiveOf(DocDbCluster cluster) {
|
||||
String clusterId = cluster.getDbClusterIdentifier();
|
||||
if (!"available".equals(cluster.getStatus())) {
|
||||
throw new AwsException("InvalidDBClusterStateFault",
|
||||
"DB cluster " + clusterId + " is not available.", 400);
|
||||
}
|
||||
if (config.services().docdb().mock()) {
|
||||
return new ClusterArchive("", null);
|
||||
}
|
||||
if (cluster.getContainerId() == null) {
|
||||
throw new AwsException("InvalidDBClusterStateFault",
|
||||
"DB cluster " + clusterId + " has no running MongoDB backend to read.", 400);
|
||||
}
|
||||
try {
|
||||
return new ClusterArchive(containerManager.dumpCluster(cluster.getContainerId()),
|
||||
containerManager.masterPassword(cluster.getContainerId()));
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Failed to read the data of DocDB cluster {0}", clusterId);
|
||||
throw new AwsException("InvalidDBClusterStateFault",
|
||||
"Failed to read the data of DB cluster " + clusterId + ": " + e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a request's snapshot parameter, an identifier or an ARN, names a DocumentDB snapshot
|
||||
* in this region. An ARN matches only the record stored under that exact ARN.
|
||||
*/
|
||||
public boolean hasClusterSnapshot(String snapshotIdOrArn, String region) {
|
||||
if (snapshotIdOrArn == null || snapshotIdOrArn.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
if (!AwsArnUtils.isArn(snapshotIdOrArn)) {
|
||||
return snapshots.get(key(region, snapshotIdOrArn)).isPresent();
|
||||
}
|
||||
String id = snapshotIdInArn(snapshotIdOrArn);
|
||||
return id != null && snapshots.get(key(region, id))
|
||||
.map(snapshot -> snapshotIdOrArn.equals(snapshot.getDbClusterSnapshotArn()))
|
||||
.orElse(false);
|
||||
}
|
||||
|
||||
/** The snapshot identifier an RDS cluster-snapshot ARN names, or null when it names none. */
|
||||
private static String snapshotIdInArn(String arn) {
|
||||
try {
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
String prefix = "cluster-snapshot:";
|
||||
return "rds".equals(parsed.service()) && parsed.resource().startsWith(prefix)
|
||||
? parsed.resource().substring(prefix.length()) : null;
|
||||
} catch (IllegalArgumentException malformed) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The snapshot a request names, by identifier or by ARN, in the caller's region. */
|
||||
public DocDbClusterSnapshot getDbClusterSnapshot(String snapshotIdOrArn) {
|
||||
String region = regionResolver.getRegion();
|
||||
String id = snapshotIdOrArn;
|
||||
if (AwsArnUtils.isArn(snapshotIdOrArn)) {
|
||||
id = snapshotIdInArn(snapshotIdOrArn);
|
||||
if (id == null) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"Invalid DB cluster snapshot identifier: " + snapshotIdOrArn, 400);
|
||||
}
|
||||
}
|
||||
String name = id;
|
||||
DocDbClusterSnapshot snapshot = snapshots.get(key(region, id)).orElseThrow(() ->
|
||||
new AwsException("DBClusterSnapshotNotFoundFault",
|
||||
"DBClusterSnapshot " + name + " not found.", 404));
|
||||
// Storage is keyed by identifier alone, so an ARN of another region or account would
|
||||
// otherwise resolve this caller's snapshot.
|
||||
if (AwsArnUtils.isArn(snapshotIdOrArn) && !snapshotIdOrArn.equals(snapshot.getDbClusterSnapshotArn())) {
|
||||
throw new AwsException("DBClusterSnapshotNotFoundFault",
|
||||
"DBClusterSnapshot " + snapshotIdOrArn + " not found.", 404);
|
||||
}
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
/** Snapshots in this region matching every one of the request's identifier, cluster and type. */
|
||||
public List<DocDbClusterSnapshot> describeDbClusterSnapshots(String snapshotIdOrArn, String clusterId,
|
||||
String snapshotType) {
|
||||
List<DocDbClusterSnapshot> candidates = snapshotIdOrArn != null && !snapshotIdOrArn.isBlank()
|
||||
? List.of(getDbClusterSnapshot(snapshotIdOrArn))
|
||||
: inRegion(snapshots, regionResolver.getRegion(), DocDbClusterSnapshot::getDbClusterSnapshotIdentifier);
|
||||
return candidates.stream()
|
||||
.filter(sn -> clusterId == null || clusterId.isBlank() || clusterId.equals(sn.getDbClusterIdentifier()))
|
||||
.filter(sn -> snapshotType == null || snapshotType.isBlank() || snapshotType.equals(sn.getSnapshotType()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
public DocDbClusterSnapshot deleteDbClusterSnapshot(String snapshotIdOrArn) {
|
||||
String region = regionResolver.getRegion();
|
||||
String snapshotId = getDbClusterSnapshot(snapshotIdOrArn).getDbClusterSnapshotIdentifier();
|
||||
synchronized (lockFor("snapshot:" + key(region, snapshotId))) {
|
||||
DocDbClusterSnapshot snapshot = getDbClusterSnapshot(snapshotIdOrArn);
|
||||
snapshots.delete(key(region, snapshotId));
|
||||
snapshotData.delete(key(region, snapshotId));
|
||||
writeLocks.remove("snapshot:" + key(region, snapshotId));
|
||||
snapshot.setStatus("deleted");
|
||||
return snapshot;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A new cluster holding the snapshot's data. It has no instances, as on AWS: the caller adds
|
||||
* them with CreateDBInstance. The snapshot's master user comes back with the data.
|
||||
*/
|
||||
public DocDbCluster restoreDbClusterFromSnapshot(String clusterId, String snapshotIdOrArn, String engineVersion,
|
||||
DocDbClusterSettings settings, Map<String, String> tags) {
|
||||
String region = regionResolver.getRegion();
|
||||
String snapshotId = getDbClusterSnapshot(snapshotIdOrArn).getDbClusterSnapshotIdentifier();
|
||||
DocDbClusterSnapshot snapshot;
|
||||
String data;
|
||||
// The record and its archive are read together under the lock delete takes, so a restore
|
||||
// sees both or neither, and a snapshot whose archive is gone is refused before any cluster
|
||||
// exists rather than restored as an empty one.
|
||||
synchronized (lockFor("snapshot:" + key(region, snapshotId))) {
|
||||
snapshot = getDbClusterSnapshot(snapshotIdOrArn);
|
||||
data = snapshotData.get(key(region, snapshotId)).orElse(null);
|
||||
boolean restorable = snapshot.isMetadataOnly()
|
||||
? config.services().docdb().mock()
|
||||
: data != null && !data.isEmpty();
|
||||
if (!restorable) {
|
||||
throw new AwsException("InvalidDBClusterSnapshotStateFault",
|
||||
"DB cluster snapshot " + snapshotId + " has no data to restore.", 400);
|
||||
}
|
||||
}
|
||||
String password = snapshot.getMasterPassword() != null ? snapshot.getMasterPassword()
|
||||
: UUID.randomUUID().toString();
|
||||
String version = engineVersion != null && !engineVersion.isBlank()
|
||||
? engineVersion : snapshot.getEngineVersion();
|
||||
DocDbCluster cluster = createDbCluster(clusterId, version, snapshot.getMasterUsername(), password, false,
|
||||
restoredFrom(settings, snapshot.isStorageEncrypted(), snapshot.getKmsKeyId(), true), tags);
|
||||
loadInto(cluster, snapshot.isMetadataOnly() ? "" : data);
|
||||
return cluster;
|
||||
}
|
||||
|
||||
/**
|
||||
* A new cluster holding the source's data as it is now, the latest restorable time. The data is
|
||||
* read as a snapshot reads it, with the same checks and faults.
|
||||
*/
|
||||
public DocDbCluster restoreDbClusterToPointInTime(String clusterId, String sourceClusterId,
|
||||
DocDbClusterSettings settings, Map<String, String> tags) {
|
||||
DocDbCluster source = getDbCluster(sourceClusterId);
|
||||
ClusterArchive archive = archiveOf(source);
|
||||
String password = archive.masterPassword() != null ? archive.masterPassword()
|
||||
: UUID.randomUUID().toString();
|
||||
DocDbCluster cluster = createDbCluster(clusterId, source.getEngineVersion(), source.getMasterUsername(),
|
||||
password, false, restoredFrom(settings, source.isStorageEncrypted(), source.getKmsKeyId(), false), tags);
|
||||
loadInto(cluster, archive.data());
|
||||
return cluster;
|
||||
}
|
||||
|
||||
/**
|
||||
* The settings a restore creates its cluster with. A restore request carries no
|
||||
* {@code StorageEncrypted} of its own: the cluster takes its source's encryption and key unless
|
||||
* the request names a key. A snapshot restore may encrypt an unencrypted snapshot that way, as
|
||||
* the restore guide allows; a point-in-time restore may not, and a key named for an unencrypted
|
||||
* source is refused by {@code validate}, as its reference has it.
|
||||
*/
|
||||
private static DocDbClusterSettings restoredFrom(DocDbClusterSettings requested, boolean sourceEncrypted,
|
||||
String sourceKmsKeyId, boolean keyMayEncrypt) {
|
||||
boolean keyNamed = requested.kmsKeyId() != null && !requested.kmsKeyId().isBlank();
|
||||
String kmsKeyId = keyNamed ? requested.kmsKeyId() : (sourceEncrypted ? sourceKmsKeyId : null);
|
||||
boolean encrypted = sourceEncrypted || (keyNamed && keyMayEncrypt);
|
||||
return new DocDbClusterSettings(requested.dbSubnetGroupName(), requested.dbClusterParameterGroupName(),
|
||||
requested.vpcSecurityGroupIds(), encrypted, kmsKeyId, requested.backupRetentionPeriod(),
|
||||
requested.preferredBackupWindow(), requested.preferredMaintenanceWindow(),
|
||||
requested.deletionProtection());
|
||||
}
|
||||
|
||||
private void loadInto(DocDbCluster cluster, String data) {
|
||||
if (config.services().docdb().mock() || data.isEmpty() || cluster.getContainerId() == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
containerManager.restoreCluster(cluster.getContainerId(), data);
|
||||
} catch (RuntimeException e) {
|
||||
try {
|
||||
discardRestoredCluster(cluster.getDbClusterIdentifier());
|
||||
} catch (RuntimeException cleanup) {
|
||||
LOG.warnv(cleanup, "Could not remove DocDB cluster {0} after its failed restore",
|
||||
cluster.getDbClusterIdentifier());
|
||||
e.addSuppressed(cleanup);
|
||||
}
|
||||
throw new AwsException("InvalidRestoreFault",
|
||||
"Failed to restore cluster " + cluster.getDbClusterIdentifier() + ": " + e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a cluster this restore just created and could not load. It bypasses deletion
|
||||
* protection, which the request may have asked for: the caller never received the cluster.
|
||||
*/
|
||||
private void discardRestoredCluster(String id) {
|
||||
String region = regionResolver.getRegion();
|
||||
synchronized (lockFor("cluster:" + key(region, id))) {
|
||||
findCluster(region, id).ifPresent(cluster -> removeCluster(region, cluster));
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireIdentifier(String value, String name) {
|
||||
if (value == null || value.isBlank()) {
|
||||
throw new AwsException("InvalidParameterValue", name + " is required.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,12 +5,14 @@ import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.docker.ContainerBuilder;
|
||||
import io.floci.aws.core.common.docker.ContainerDetector;
|
||||
import io.floci.aws.core.common.docker.ContainerExec;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager.ContainerInfo;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager.EndpointInfo;
|
||||
import io.floci.aws.core.common.docker.ContainerLogStreamer;
|
||||
import io.floci.aws.core.common.docker.ContainerSpec;
|
||||
import io.floci.aws.core.common.docker.ContainerStorageHelper;
|
||||
import io.floci.aws.core.common.docker.RetryingTarCopier;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
@@ -20,6 +22,7 @@ import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Socket;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
@@ -171,6 +174,79 @@ public class DocDbContainerManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The master password the container was started with. A restore replays the source's users,
|
||||
* so the restored cluster's container must start with the same password for later dumps of
|
||||
* it to authenticate.
|
||||
*/
|
||||
public String masterPassword(String containerId) {
|
||||
String[] env = lifecycleManager.getDockerClient().inspectContainerCmd(containerId).exec().getConfig().getEnv();
|
||||
if (env != null) {
|
||||
for (String entry : env) {
|
||||
if (entry.startsWith("MONGO_INITDB_ROOT_PASSWORD=")) {
|
||||
return entry.substring("MONGO_INITDB_ROOT_PASSWORD=".length());
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A snapshot of the cluster's data: a gzipped {@code mongodump} archive of every database,
|
||||
* users and roles included, base64 encoded so it travels through the exec's text output.
|
||||
* The container's own MONGO_INITDB credentials authenticate the dump.
|
||||
*/
|
||||
public String dumpCluster(String containerId) {
|
||||
String[] cmd = {"bash", "-o", "pipefail", "-c",
|
||||
"mongodump --quiet --host 127.0.0.1 --port " + MONGO_PORT
|
||||
+ " \"--username=$MONGO_INITDB_ROOT_USERNAME\" \"--password=$MONGO_INITDB_ROOT_PASSWORD\""
|
||||
+ " --authenticationDatabase admin --archive --gzip | base64 -w0"};
|
||||
ContainerExec.Result result = ContainerExec.run(lifecycleManager.getDockerClient(), containerId, cmd, 600);
|
||||
if (result.exitCode() != 0) {
|
||||
throw new RuntimeException("mongodump failed with exit code " + result.exitCode() + ": " + result.stderr());
|
||||
}
|
||||
return result.stdout().trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a {@link #dumpCluster} archive into a cluster's container, replacing what it holds. The
|
||||
* archive carries the source's users, so the restored cluster keeps the snapshot's master
|
||||
* credentials, as a restore does on AWS. Waits for the server to accept writes first: a new
|
||||
* container may still be initializing or electing its replica-set primary.
|
||||
*/
|
||||
public void restoreCluster(String containerId, String archiveBase64) {
|
||||
byte[] archive = Base64.getDecoder().decode(archiveBase64);
|
||||
RetryingTarCopier.copyBytes(lifecycleManager.getDockerClient(), containerId, "/tmp",
|
||||
"floci-docdb-restore.archive.gz", archive, 0644, RetryingTarCopier.DEFAULT_MAX_ATTEMPTS, 500);
|
||||
String auth = " \"--username=$MONGO_INITDB_ROOT_USERNAME\" \"--password=$MONGO_INITDB_ROOT_PASSWORD\" --authenticationDatabase admin";
|
||||
String[] ready = {"bash", "-c", "mongosh --quiet --host 127.0.0.1 --port " + MONGO_PORT + auth
|
||||
+ " --eval 'quit(db.hello().isWritablePrimary ? 0 : 3)'"};
|
||||
ContainerExec.Result probe = null;
|
||||
for (int i = 0; i < 120; i++) {
|
||||
probe = ContainerExec.run(lifecycleManager.getDockerClient(), containerId, ready, 30);
|
||||
if (probe.exitCode() == 0) {
|
||||
break;
|
||||
}
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException ie) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new RuntimeException("Interrupted waiting for MongoDB to accept writes", ie);
|
||||
}
|
||||
}
|
||||
if (probe == null || probe.exitCode() != 0) {
|
||||
throw new RuntimeException("MongoDB did not accept writes before the restore: "
|
||||
+ (probe != null ? probe.stderr() : ""));
|
||||
}
|
||||
String[] cmd = {"bash", "-c", "mongorestore --quiet --host 127.0.0.1 --port " + MONGO_PORT + auth
|
||||
+ " --drop --nsExclude='config.*' --archive=/tmp/floci-docdb-restore.archive.gz --gzip"
|
||||
+ " && rm -f /tmp/floci-docdb-restore.archive.gz"};
|
||||
ContainerExec.Result result = ContainerExec.run(lifecycleManager.getDockerClient(), containerId, cmd, 600);
|
||||
if (result.exitCode() != 0) {
|
||||
throw new RuntimeException("mongorestore failed with exit code " + result.exitCode() + ": " + result.stderr());
|
||||
}
|
||||
}
|
||||
|
||||
private static void waitForBackendReady(String clusterId, String host, int port) {
|
||||
long deadline = System.currentTimeMillis() + BACKEND_READY_DEADLINE_MS;
|
||||
int attempt = 0;
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
package io.floci.aws.services.docdb.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* A DocumentDB cluster snapshot. The data itself, a {@code mongodump} archive of the cluster's
|
||||
* MongoDB container, is kept beside the record under the same key rather than on it, so listing
|
||||
* snapshots never reads every archive.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
public class DocDbClusterSnapshot {
|
||||
|
||||
private String dbClusterSnapshotIdentifier;
|
||||
private String dbClusterIdentifier;
|
||||
private String dbClusterSnapshotArn;
|
||||
private String status;
|
||||
private String snapshotType;
|
||||
private String engineVersion;
|
||||
private String masterUsername;
|
||||
/** Kept so a restore starts its container with the credentials the data carries; never returned by the API. */
|
||||
private String masterPassword;
|
||||
private int port;
|
||||
private String vpcId;
|
||||
private boolean storageEncrypted;
|
||||
private String kmsKeyId;
|
||||
private Instant snapshotCreateTime;
|
||||
private Instant clusterCreateTime;
|
||||
private long sizeBytes;
|
||||
/** Taken in mock mode, with no backend to read: the record alone, with no archive to restore. */
|
||||
private boolean metadataOnly;
|
||||
private Map<String, String> tags = new LinkedHashMap<>();
|
||||
|
||||
public String getDbClusterSnapshotIdentifier() { return dbClusterSnapshotIdentifier; }
|
||||
public void setDbClusterSnapshotIdentifier(String v) { this.dbClusterSnapshotIdentifier = v; }
|
||||
|
||||
public String getDbClusterIdentifier() { return dbClusterIdentifier; }
|
||||
public void setDbClusterIdentifier(String v) { this.dbClusterIdentifier = v; }
|
||||
|
||||
public String getDbClusterSnapshotArn() { return dbClusterSnapshotArn; }
|
||||
public void setDbClusterSnapshotArn(String v) { this.dbClusterSnapshotArn = v; }
|
||||
|
||||
public String getStatus() { return status; }
|
||||
public void setStatus(String v) { this.status = v; }
|
||||
|
||||
public String getSnapshotType() { return snapshotType; }
|
||||
public void setSnapshotType(String v) { this.snapshotType = v; }
|
||||
|
||||
public String getEngineVersion() { return engineVersion; }
|
||||
public void setEngineVersion(String v) { this.engineVersion = 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 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 boolean isMetadataOnly() { return metadataOnly; }
|
||||
public void setMetadataOnly(boolean v) { this.metadataOnly = 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 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 long getSizeBytes() { return sizeBytes; }
|
||||
public void setSizeBytes(long v) { this.sizeBytes = v; }
|
||||
|
||||
public Map<String, String> getTags() { return tags; }
|
||||
public void setTags(Map<String, String> v) { this.tags = v != null ? v : new LinkedHashMap<>(); }
|
||||
}
|
||||
@@ -2822,12 +2822,25 @@ public class RdsQueryHandler {
|
||||
}
|
||||
|
||||
private Response handleDescribeDbClusterSnapshots(MultivaluedMap<String, String> params, String region) {
|
||||
String snapshotId = params.getFirst("DBClusterSnapshotIdentifier");
|
||||
XmlBuilder xml = new XmlBuilder().start("DBClusterSnapshots");
|
||||
for (DbClusterSnapshot s : service.describeDbClusterSnapshots(
|
||||
params.getFirst("DBClusterSnapshotIdentifier"), params.getFirst("DBClusterIdentifier"),
|
||||
snapshotId, params.getFirst("DBClusterIdentifier"),
|
||||
params.getFirst("SnapshotType"), region)) {
|
||||
xml.raw(dbClusterSnapshotXml(s));
|
||||
}
|
||||
// The list form covers the whole RDS family, as DescribeDBClusters does: a live account
|
||||
// lists DocumentDB cluster snapshots here too. The identifier form is routed to the store
|
||||
// that owns the identifier.
|
||||
if (snapshotId == null || snapshotId.isBlank()) {
|
||||
String clusterId = params.getFirst("DBClusterIdentifier");
|
||||
if (clusterId == null || clusterId.isBlank()) {
|
||||
clusterId = extractRdsFilterValue(params, "db-cluster-id");
|
||||
}
|
||||
for (String row : docDbQueryHandler.clusterSnapshotRowsXml(clusterId, params.getFirst("SnapshotType"))) {
|
||||
xml.start("DBClusterSnapshot").raw(row).end("DBClusterSnapshot");
|
||||
}
|
||||
}
|
||||
xml.end("DBClusterSnapshots");
|
||||
return Response.ok(AwsQueryResponse.envelope("DescribeDBClusterSnapshots", AwsNamespaces.RDS, xml.build())).build();
|
||||
}
|
||||
|
||||
@@ -5730,6 +5730,12 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
return cluster || instance;
|
||||
}
|
||||
|
||||
/** Whether RDS holds a cluster snapshot of this identifier in the request's region. */
|
||||
public boolean hasClusterSnapshot(String snapshotId, String region) {
|
||||
return snapshotId != null && !snapshotId.isBlank()
|
||||
&& findClusterSnapshotForScope(currentAccountId(), effectiveRegion(region), snapshotId) != null;
|
||||
}
|
||||
|
||||
public DbCluster getDbCluster(String id) {
|
||||
return getDbCluster(id, regionResolver.getDefaultRegion());
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user