mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(rds): implement CreateDBSnapshot and RestoreDBInstanceFromDBSnap… (#1894)
* feat(rds): implement CreateDBSnapshot and RestoreDBInstanceFromDBSnapshot for postgres (#1817) * feat(rds): implement CreateDBSnapshot and RestoreDBInstanceFromDBSnapshot for postgres (#1817) * feat(rds): generated docs * fix(rds): preserve master password across DbSnapshot restore * fix(rds): preserve thread interrupt flag in restorePostgresSnapshot * fix(rds): handle duplicate RDS snapshots and mock mode operations * fix(rds): separate stdout and stderr in container exec to prevent snapshot corruption * fix(rds): add missing stderr argument to ContainerExecResult on timeout * fix(rds): cleanup RDS instance on snapshot restore failure * fix(rds): return structured AWS error when RDS snapshot restore fails * fix(rds): address PR #1894 snapshot and restore review comments - Wire handleDescribeDbSnapshots to use the new snapshots storage backend - Change engine validation error from UnsupportedOperation to InvalidDBInstanceState - Change restore failure error from InvalidDBSnapshotStateFault to InvalidDBSnapshotState - Add corresponding unit and query handler tests * fix(rds): address PR #1894 review feedback and restore process issues - Wire DescribeDBSnapshots to the snapshots storage backend with filtering support - Align CreateDBSnapshot engine error code to InvalidDBInstanceState - Align restore snapshot failure error code to InvalidDBSnapshotState - Carry over dbName from DbSnapshot to the restored DBInstance - Connect to template1 during psql restore to prevent active postgres connection drop failures - Remove unused AwsNamespaces import in RdsService - Add corresponding unit and query handler tests * fix(rds): address PR #1894 review feedback and snapshot error handling * fix(rds): add --if-exists to pg_dumpall snapshot command - Appends the --if-exists flag to pg_dumpall commands during database snapshot creation. This ensures DROP DATABASE statements are emitted conditionally, preventing restore failures on fresh container instances where user databases do not yet exist. * fix(rds): added real docker test * docs(rds): add descriptions for snapshot actions Added concise, handwritten descriptions for the `CreateDBSnapshot` and `RestoreDBInstanceFromDBSnapshot` actions in the RDS documentation action table to comply with the contributing guidelines. * feat(rds): improve RDS snapshot restore reliability and API coverage - Update `postgresRestoreScript` to explicitly filter out the master user `CREATE ROLE` statement, preventing restore failures when `ON_ERROR_STOP=1` is enabled. - Add strict validation for `masterUsername` in `CreateDBInstance` to adhere to AWS requirements (only alphanumeric chars starting with a letter, max 16 chars). - Ensure `dbInstanceClass` is accurately preserved in the `DbSnapshot` model so it can be restored to the same hardware class automatically. - Fix missing Windows absolute path detection in `ContainerStorageHelper`, resolving test-environment `NoSuchElement` errors on Windows. - Make `RdsAwsIntegrationTest` gracefully skip on agents without a Docker daemon, matching test suite expectations. - Update `rds.md` to include concise handwritten descriptions for all remaining placeholder actions. - Improve exception logging inside container execution wrappers.
This commit is contained in:
1 parent
1de6b80035
commit
2869502e7c
11 files changed
+1088
-26
No files matched your search
+5
-1
@@ -168,7 +168,11 @@ public final class ContainerStorageHelper {
|
||||
* they are treated as named-volume mode.
|
||||
*/
|
||||
public static boolean isNamedVolumeMode(EmulatorConfig config) {
|
||||
return !config.storage().hostPersistentPath().startsWith("/");
|
||||
String path = config.storage().hostPersistentPath();
|
||||
if (path == null || path.isBlank()) {
|
||||
return true;
|
||||
}
|
||||
return !java.nio.file.Paths.get(path).isAbsolute() && !path.startsWith("/");
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -92,6 +92,8 @@ public class RdsQueryHandler {
|
||||
case "DescribeOptionGroups" -> handleDescribeOptionGroups(params, region);
|
||||
case "ModifyOptionGroup" -> handleModifyOptionGroup(params, region);
|
||||
case "DeleteOptionGroup" -> handleDeleteOptionGroup(params, region);
|
||||
case "CreateDBSnapshot" -> handleCreateDbSnapshot(params);
|
||||
case "RestoreDBInstanceFromDBSnapshot" -> handleRestoreDbInstanceFromDbSnapshot(params);
|
||||
case "DescribeDBSnapshots" -> handleDescribeDbSnapshots(params);
|
||||
case "DescribeDBProxies" -> handleDescribeDbProxies(params, region);
|
||||
case "CreateDBProxy" -> handleCreateDbProxy(params, region);
|
||||
@@ -937,12 +939,71 @@ public class RdsQueryHandler {
|
||||
|
||||
// ── Snapshots & Proxies (not modeled — empty lists) ───────────────────────
|
||||
|
||||
private Response handleCreateDbSnapshot(MultivaluedMap<String, String> params) {
|
||||
String snapshotId = params.getFirst("DBSnapshotIdentifier");
|
||||
String instanceId = params.getFirst("DBInstanceIdentifier");
|
||||
if (snapshotId == null || snapshotId.isBlank()) {
|
||||
return AwsQueryResponse.error("InvalidParameterValue", "DBSnapshotIdentifier is required.", AwsNamespaces.RDS, 400);
|
||||
}
|
||||
if (instanceId == null || instanceId.isBlank()) {
|
||||
return AwsQueryResponse.error("InvalidParameterValue", "DBInstanceIdentifier is required.", AwsNamespaces.RDS, 400);
|
||||
}
|
||||
try {
|
||||
io.github.hectorvent.floci.services.rds.model.DbSnapshot snapshot = service.createDbSnapshot(snapshotId, instanceId);
|
||||
String result = dbSnapshotXml(snapshot);
|
||||
return Response.ok(AwsQueryResponse.envelope("CreateDBSnapshot", AwsNamespaces.RDS, result)).build();
|
||||
} catch (AwsException e) {
|
||||
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.RDS, e.getHttpStatus());
|
||||
}
|
||||
}
|
||||
|
||||
private Response handleRestoreDbInstanceFromDbSnapshot(MultivaluedMap<String, String> params) {
|
||||
String instanceId = params.getFirst("DBInstanceIdentifier");
|
||||
String snapshotId = params.getFirst("DBSnapshotIdentifier");
|
||||
if (instanceId == null || instanceId.isBlank()) {
|
||||
return AwsQueryResponse.error("InvalidParameterValue", "DBInstanceIdentifier is required.", AwsNamespaces.RDS, 400);
|
||||
}
|
||||
if (snapshotId == null || snapshotId.isBlank()) {
|
||||
return AwsQueryResponse.error("InvalidParameterValue", "DBSnapshotIdentifier is required.", AwsNamespaces.RDS, 400);
|
||||
}
|
||||
String dbInstanceClass = params.getFirst("DBInstanceClass");
|
||||
String availabilityZone = params.getFirst("AvailabilityZone");
|
||||
String multiAzStr = params.getFirst("MultiAZ");
|
||||
boolean multiAz = multiAzStr != null && Boolean.parseBoolean(multiAzStr);
|
||||
String dbSubnetGroupName = params.getFirst("DBSubnetGroupName");
|
||||
|
||||
java.util.List<String> vpcSecurityGroupIds = new java.util.ArrayList<>();
|
||||
for (int i = 1; ; i++) {
|
||||
String sg = params.getFirst("VpcSecurityGroupIds.VpcSecurityGroupId." + i);
|
||||
if (sg == null) break;
|
||||
vpcSecurityGroupIds.add(sg);
|
||||
}
|
||||
|
||||
java.util.Map<String, String> tags = parseTags(params);
|
||||
|
||||
try {
|
||||
DbInstance instance = service.restoreDbInstanceFromDbSnapshot(instanceId, snapshotId, dbInstanceClass, availabilityZone, multiAz, dbSubnetGroupName, vpcSecurityGroupIds, tags);
|
||||
String result = dbInstanceXml(instance);
|
||||
return Response.ok(AwsQueryResponse.envelope("RestoreDBInstanceFromDBSnapshot", AwsNamespaces.RDS, result)).build();
|
||||
} catch (AwsException e) {
|
||||
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.RDS, e.getHttpStatus());
|
||||
}
|
||||
}
|
||||
|
||||
private Response handleDescribeDbSnapshots(MultivaluedMap<String, String> params) {
|
||||
// DB snapshots are not modeled; return the RDS Query API's wire-accurate empty
|
||||
// result (empty <DBSnapshots> wrapper, no <Marker>) so SDK clients complete the
|
||||
// read instead of failing with UnsupportedOperation.
|
||||
String result = new XmlBuilder().start("DBSnapshots").end("DBSnapshots").build();
|
||||
return Response.ok(AwsQueryResponse.envelope("DescribeDBSnapshots", AwsNamespaces.RDS, result)).build();
|
||||
String snapshotId = params.getFirst("DBSnapshotIdentifier");
|
||||
String instanceId = params.getFirst("DBInstanceIdentifier");
|
||||
try {
|
||||
Collection<io.github.hectorvent.floci.services.rds.model.DbSnapshot> result = service.describeDbSnapshots(snapshotId, instanceId);
|
||||
XmlBuilder xml = new XmlBuilder().start("DBSnapshots");
|
||||
for (io.github.hectorvent.floci.services.rds.model.DbSnapshot s : result) {
|
||||
xml.raw(dbSnapshotXml(s));
|
||||
}
|
||||
xml.end("DBSnapshots");
|
||||
return Response.ok(AwsQueryResponse.envelope("DescribeDBSnapshots", AwsNamespaces.RDS, xml.build())).build();
|
||||
} catch (AwsException e) {
|
||||
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.RDS, e.getHttpStatus());
|
||||
}
|
||||
}
|
||||
|
||||
private Response handleDescribeDbProxies(MultivaluedMap<String, String> params, String region) {
|
||||
@@ -1282,6 +1343,26 @@ public class RdsQueryHandler {
|
||||
return new XmlBuilder().start("DBInstance").raw(dbInstanceInnerXml(i)).end("DBInstance").build();
|
||||
}
|
||||
|
||||
private String dbSnapshotXml(io.github.hectorvent.floci.services.rds.model.DbSnapshot s) {
|
||||
String engineStr = s.getEngine() != null ? s.getEngine().name().toLowerCase() : "";
|
||||
XmlBuilder xml = new XmlBuilder().start("DBSnapshot")
|
||||
.elem("DBSnapshotIdentifier", s.getDbSnapshotIdentifier())
|
||||
.elem("DBInstanceIdentifier", s.getDbInstanceIdentifier())
|
||||
.elem("SnapshotCreateTime", s.getSnapshotCreateTime() != null ? s.getSnapshotCreateTime().toString() : "")
|
||||
.elem("Engine", engineStr)
|
||||
.elem("EngineVersion", s.getEngineVersion())
|
||||
.elem("AllocatedStorage", s.getAllocatedStorage())
|
||||
.elem("Status", s.getStatus())
|
||||
.elem("MasterUsername", s.getMasterUsername());
|
||||
if (s.getAvailabilityZone() != null) xml.elem("AvailabilityZone", s.getAvailabilityZone());
|
||||
if (s.getVpcId() != null) xml.elem("VpcId", s.getVpcId());
|
||||
xml.elem("InstanceCreateTime", s.getInstanceCreateTime() != null ? s.getInstanceCreateTime().toString() : "")
|
||||
.elem("Port", s.getPort())
|
||||
.elem("IAMDatabaseAuthenticationEnabled", s.isIamDatabaseAuthenticationEnabled());
|
||||
if (s.getDbiResourceId() != null) xml.elem("DbiResourceId", s.getDbiResourceId());
|
||||
return xml.end("DBSnapshot").build();
|
||||
}
|
||||
|
||||
private String dbInstanceInnerXml(DbInstance i) {
|
||||
DbEndpoint ep = i.getEndpoint();
|
||||
String engineStr = instanceEngine(i);
|
||||
|
||||
@@ -35,6 +35,7 @@ import io.github.hectorvent.floci.services.rds.model.DbProxy;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbProxyAuth;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbProxyTarget;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbProxyTargetGroup;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbSnapshot;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbSubnetGroup;
|
||||
import io.github.hectorvent.floci.services.rds.model.OptionGroup;
|
||||
import io.github.hectorvent.floci.services.rds.model.OptionGroupOption;
|
||||
@@ -137,6 +138,8 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
private final StorageBackend<String, DbSubnetGroup> subnetGroups;
|
||||
private final StorageBackend<String, DbProxy> proxies;
|
||||
private final StorageBackend<String, DbProxyTargetGroup> proxyTargetGroups;
|
||||
private final StorageBackend<String, DbSnapshot> snapshots;
|
||||
private final StorageBackend<String, String> snapshotData;
|
||||
private final RdsContainerManager containerManager;
|
||||
private final RdsProxyManager proxyManager;
|
||||
// CreateDBCluster/CreateDBInstance register the new resource only after the
|
||||
@@ -214,6 +217,10 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
new TypeReference<Map<String, DbProxy>>() {});
|
||||
this.proxyTargetGroups = storageFactory.create("rds", "rds-proxy-target-groups.json",
|
||||
new TypeReference<Map<String, DbProxyTargetGroup>>() {});
|
||||
this.snapshots = storageFactory.create("rds", "rds-snapshots.json",
|
||||
new TypeReference<Map<String, DbSnapshot>>() {});
|
||||
this.snapshotData = storageFactory.create("rds", "rds-snapshot-data.json",
|
||||
new TypeReference<Map<String, String>>() {});
|
||||
}
|
||||
|
||||
RdsService(RdsContainerManager containerManager,
|
||||
@@ -345,6 +352,8 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
this.proxies = proxies;
|
||||
this.proxyTargetGroups = proxyTargetGroups;
|
||||
this.taggingService = taggingService;
|
||||
this.snapshots = new io.github.hectorvent.floci.core.storage.InMemoryStorage<>();
|
||||
this.snapshotData = new io.github.hectorvent.floci.core.storage.InMemoryStorage<>();
|
||||
}
|
||||
|
||||
public void restorePersistedRuntime() {
|
||||
@@ -572,6 +581,9 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
int proxyPort = allocateProxyPort();
|
||||
if (masterUsername == null || masterUsername.isBlank()) {
|
||||
masterUsername = "root";
|
||||
} else if (masterUsername.length() > 16 || !masterUsername.matches("^[a-zA-Z][a-zA-Z0-9_]*$")) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"MasterUsername must begin with a letter and contain only alphanumeric characters or underscores.", 400);
|
||||
}
|
||||
if (manageMasterUserPassword && (masterPassword == null || masterPassword.isBlank())) {
|
||||
masterPassword = generatedMasterPassword();
|
||||
@@ -699,6 +711,96 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
return instance;
|
||||
}
|
||||
|
||||
public DbSnapshot createDbSnapshot(String snapshotId, String instanceId) {
|
||||
if (snapshots.get(snapshotId).isPresent()) {
|
||||
throw new AwsException("DBSnapshotAlreadyExists", "DBSnapshot " + snapshotId + " already exists.", 400);
|
||||
}
|
||||
|
||||
DbInstance instance = getDbInstance(instanceId);
|
||||
|
||||
if (instance.getEngine() != DatabaseEngine.POSTGRES) {
|
||||
throw new AwsException("InvalidDBInstanceState", "Operation CreateDBSnapshot is not supported for engine " + instance.getEngine() + ".", 400);
|
||||
}
|
||||
|
||||
DbSnapshot snapshot = new DbSnapshot(snapshotId, instanceId, Instant.now(), instance.getEngine(),
|
||||
instance.getEngineVersion(), instance.getAllocatedStorage(), "available",
|
||||
instance.getMasterUsername(), instance.getMasterPassword(), instance.getAvailabilityZone(), instance.getVpcId(),
|
||||
instance.getCreatedAt(), instance.getEndpoint() != null ? instance.getEndpoint().port() : instance.getProxyPort(),
|
||||
instance.isIamDatabaseAuthenticationEnabled(), instance.getDbiResourceId(), instance.getDbInstanceClass());
|
||||
snapshot.setDbName(instance.getDbName());
|
||||
|
||||
String sqlDump = "";
|
||||
if (!config.services().rds().mock()) {
|
||||
try {
|
||||
sqlDump = containerManager.createPostgresSnapshot(instance.getContainerId(), instance.getMasterUsername());
|
||||
} catch (Exception e) {
|
||||
throw new AwsException("InvalidDBInstanceState", "Failed to create snapshot: " + e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
snapshotData.put(snapshotId, sqlDump);
|
||||
snapshots.put(snapshotId, snapshot);
|
||||
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
public DbInstance restoreDbInstanceFromDbSnapshot(String instanceId, String snapshotId, String dbInstanceClass, String availabilityZone, boolean multiAz, String dbSubnetGroupName, java.util.List<String> vpcSecurityGroupIds, java.util.Map<String, String> tags) {
|
||||
DbSnapshot snapshot = snapshots.get(snapshotId)
|
||||
.orElseThrow(() -> new AwsException("DBSnapshotNotFound", "DBSnapshot " + snapshotId + " not found.", 404));
|
||||
|
||||
String sqlDump = snapshotData.get(snapshotId)
|
||||
.orElseThrow(() -> new AwsException("DBSnapshotNotFound", "DBSnapshot data for " + snapshotId + " not found.", 404));
|
||||
|
||||
String targetClass = (dbInstanceClass != null && !dbInstanceClass.isBlank()) ? dbInstanceClass : snapshot.getDbInstanceClass();
|
||||
if (targetClass == null || targetClass.isBlank()) {
|
||||
targetClass = "db.t3.micro";
|
||||
}
|
||||
// Use the parameters from the snapshot
|
||||
DbInstance instance = createDbInstance(instanceId, snapshot.getEngine().name().toLowerCase(), snapshot.getEngineVersion(),
|
||||
snapshot.getMasterUsername(), snapshot.getMasterPassword(),
|
||||
snapshot.getDbName(), targetClass, snapshot.getAllocatedStorage(), snapshot.isIamDatabaseAuthenticationEnabled(),
|
||||
null, dbSubnetGroupName, null, availabilityZone, multiAz, false, null, tags, vpcSecurityGroupIds);
|
||||
|
||||
if (!config.services().rds().mock()) {
|
||||
try {
|
||||
containerManager.restorePostgresSnapshot(instance.getContainerId(), instance.getMasterUsername(), sqlDump);
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
deleteDbInstance(instanceId);
|
||||
} catch (Exception cleanupError) {
|
||||
e.addSuppressed(cleanupError);
|
||||
}
|
||||
AwsException awsEx = new AwsException("InvalidDBSnapshotState", "Failed to restore snapshot: " + e.getMessage(), 400);
|
||||
awsEx.initCause(e);
|
||||
throw awsEx;
|
||||
}
|
||||
}
|
||||
|
||||
return instance;
|
||||
}
|
||||
|
||||
public Collection<DbSnapshot> describeDbSnapshots(String snapshotId, String instanceId) {
|
||||
if (snapshotId != null && !snapshotId.isBlank()) {
|
||||
DbSnapshot snapshot = snapshots.get(snapshotId)
|
||||
.orElseThrow(() -> new AwsException("DBSnapshotNotFound", "DBSnapshot " + snapshotId + " not found.", 404));
|
||||
if (instanceId != null && !instanceId.isBlank()) {
|
||||
if (instanceId.equals(snapshot.getDbInstanceIdentifier())) {
|
||||
return List.of(snapshot);
|
||||
} else {
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
return List.of(snapshot);
|
||||
}
|
||||
|
||||
List<DbSnapshot> allSnapshots = snapshots.scan(k -> true);
|
||||
if (instanceId != null && !instanceId.isBlank()) {
|
||||
return allSnapshots.stream()
|
||||
.filter(s -> instanceId.equals(s.getDbInstanceIdentifier()))
|
||||
.toList();
|
||||
}
|
||||
return allSnapshots;
|
||||
}
|
||||
|
||||
public Map<String, String> listTagsForResource(String resourceName) {
|
||||
return listTagsForResource(resourceName, resourceRegionOrDefault(resourceName));
|
||||
}
|
||||
|
||||
+127
-6
@@ -592,7 +592,7 @@ public class RdsContainerManager {
|
||||
for (int attempt = 1; attempt <= 60; attempt++) {
|
||||
try {
|
||||
ContainerExecResult result = execInContainer(containerId, cmd, 5);
|
||||
lastOutput = result.output();
|
||||
lastOutput = result.output() + (result.stderr().isEmpty() ? "" : "\n" + result.stderr());
|
||||
if (result.exitCode() == 0) {
|
||||
LOG.infov("Initialized {0} in RDS container {1}", description, containerName);
|
||||
return;
|
||||
@@ -610,6 +610,120 @@ public class RdsContainerManager {
|
||||
throw new IllegalStateException("Timed out initializing " + description + " in " + containerName + ": " + lastOutput);
|
||||
}
|
||||
|
||||
public String createPostgresSnapshot(String containerId, String masterUsername) {
|
||||
String effectiveUser = (masterUsername != null && !masterUsername.isBlank()) ? masterUsername : "postgres";
|
||||
String[] cmd = {
|
||||
"pg_dumpall",
|
||||
"-U", effectiveUser
|
||||
};
|
||||
try {
|
||||
ContainerExecResult result = execInContainer(containerId, cmd, 120);
|
||||
if (result.exitCode() != 0) {
|
||||
throw new RuntimeException("pg_dumpall failed with exit code " + result.exitCode() + ": " + result.stderr());
|
||||
}
|
||||
return result.output();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to create postgres snapshot", e);
|
||||
}
|
||||
}
|
||||
|
||||
public void restorePostgresSnapshot(String containerId, String masterUsername, String sqlDump) {
|
||||
String effectiveUser = (masterUsername != null && !masterUsername.isBlank()) ? masterUsername : "postgres";
|
||||
|
||||
try {
|
||||
String restoreScript = postgresRestoreScript();
|
||||
|
||||
java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
|
||||
try (org.apache.commons.compress.archivers.tar.TarArchiveOutputStream tar =
|
||||
new org.apache.commons.compress.archivers.tar.TarArchiveOutputStream(bos)) {
|
||||
tar.setLongFileMode(org.apache.commons.compress.archivers.tar.TarArchiveOutputStream.LONGFILE_GNU);
|
||||
|
||||
addTarEntry(tar, "dump.sql", sqlDump);
|
||||
addTarEntry(tar, "restore.sh", restoreScript);
|
||||
}
|
||||
|
||||
try (java.io.InputStream tarStream = new java.io.ByteArrayInputStream(bos.toByteArray())) {
|
||||
lifecycleManager.getDockerClient().copyArchiveToContainerCmd(containerId)
|
||||
.withRemotePath("/tmp")
|
||||
.withTarInputStream(tarStream)
|
||||
.exec();
|
||||
}
|
||||
|
||||
String[] cmd = { "sh", "/tmp/restore.sh", effectiveUser };
|
||||
|
||||
ContainerExecResult result = null;
|
||||
for (int i = 0; i < 60; i++) {
|
||||
result = execInContainer(containerId, cmd, 120);
|
||||
if (result.exitCode() == 0) {
|
||||
break;
|
||||
}
|
||||
if (result.exitCode() != 2) {
|
||||
break;
|
||||
}
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException ie) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new RuntimeException("Interrupted while restoring postgres snapshot", ie);
|
||||
}
|
||||
}
|
||||
|
||||
if (result == null || result.exitCode() != 0) {
|
||||
String errMsg = result != null ? (result.stderr().isEmpty() ? result.output() : result.stderr()) : "";
|
||||
throw new RuntimeException("psql restore failed with exit code "
|
||||
+ (result != null ? result.exitCode() : -1) + ": " + errMsg);
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to restore postgres snapshot", e);
|
||||
}
|
||||
}
|
||||
|
||||
static String postgresRestoreScript() {
|
||||
return """
|
||||
#!/bin/sh
|
||||
set -e
|
||||
USER="$1"
|
||||
|
||||
# Drop all non-template, non-postgres databases
|
||||
psql -v ON_ERROR_STOP=1 -U "$USER" -d postgres -tAc \\
|
||||
"SELECT datname FROM pg_database WHERE datistemplate = false AND datname <> 'postgres'" \\
|
||||
| while read -r db; do
|
||||
[ -z "$db" ] && continue
|
||||
psql -v ON_ERROR_STOP=1 -U "$USER" -d postgres -c "DROP DATABASE IF EXISTS \\"$db\\""
|
||||
done
|
||||
|
||||
# Exclude the master user CREATE ROLE statement to avoid conflicts during restore
|
||||
sed -e "s/^CREATE ROLE \\\"\\?$USER\\\"\\?.*;/-- &/" /tmp/dump.sql > /tmp/dump_filtered.sql
|
||||
mv /tmp/dump_filtered.sql /tmp/dump.sql
|
||||
|
||||
# Drop all non-current-user, non-system roles
|
||||
psql -v ON_ERROR_STOP=1 -U "$USER" -d postgres -tAc \\
|
||||
"SELECT rolname FROM pg_roles WHERE rolname <> current_user AND rolname NOT LIKE 'pg_%'" \\
|
||||
| while read -r role; do
|
||||
[ -z "$role" ] && continue
|
||||
psql -v ON_ERROR_STOP=1 -U "$USER" -d postgres -c "DROP ROLE IF EXISTS \\"$role\\""
|
||||
done
|
||||
|
||||
# Replay the dump connected to postgres
|
||||
psql -v ON_ERROR_STOP=1 -U "$USER" -d postgres -f /tmp/dump.sql
|
||||
""";
|
||||
}
|
||||
|
||||
private static void addTarEntry(
|
||||
org.apache.commons.compress.archivers.tar.TarArchiveOutputStream tar,
|
||||
String name, String content) throws java.io.IOException {
|
||||
byte[] bytes = content.getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||
org.apache.commons.compress.archivers.tar.TarArchiveEntry entry =
|
||||
new org.apache.commons.compress.archivers.tar.TarArchiveEntry(name);
|
||||
entry.setSize(bytes.length);
|
||||
entry.setMode(0755);
|
||||
tar.putArchiveEntry(entry);
|
||||
tar.write(bytes);
|
||||
tar.closeArchiveEntry();
|
||||
}
|
||||
|
||||
private ContainerExecResult execInContainer(String containerId, String[] cmd, int timeoutSeconds) throws Exception {
|
||||
String execId = lifecycleManager.getDockerClient().execCreateCmd(containerId)
|
||||
.withCmd(cmd)
|
||||
@@ -620,13 +734,19 @@ public class RdsContainerManager {
|
||||
|
||||
CountDownLatch latch = new CountDownLatch(1);
|
||||
ByteArrayOutputStream output = new ByteArrayOutputStream();
|
||||
ByteArrayOutputStream stderr = new ByteArrayOutputStream();
|
||||
Closeable callback = lifecycleManager.getDockerClient().execStartCmd(execId).exec(new ResultCallback.Adapter<Frame>() {
|
||||
@Override
|
||||
public void onNext(Frame frame) {
|
||||
if (frame.getPayload() != null) {
|
||||
try {
|
||||
output.write(frame.getPayload());
|
||||
} catch (IOException ignored) {
|
||||
if (frame.getStreamType() == com.github.dockerjava.api.model.StreamType.STDOUT) {
|
||||
output.write(frame.getPayload());
|
||||
} else if (frame.getStreamType() == com.github.dockerjava.api.model.StreamType.STDERR) {
|
||||
stderr.write(frame.getPayload());
|
||||
}
|
||||
} catch (IOException e) {
|
||||
LOG.warnv(e, "Failed to read output stream for container exec {0}", execId);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -645,18 +765,19 @@ public class RdsContainerManager {
|
||||
try {
|
||||
boolean completed = latch.await(timeoutSeconds, TimeUnit.SECONDS);
|
||||
if (!completed) {
|
||||
return new ContainerExecResult(-1, "Timed out after " + timeoutSeconds + "s");
|
||||
return new ContainerExecResult(-1, "Timed out after " + timeoutSeconds + "s", "");
|
||||
}
|
||||
Long exitCode = lifecycleManager.getDockerClient().inspectExecCmd(execId).exec().getExitCodeLong();
|
||||
return new ContainerExecResult(
|
||||
exitCode != null ? exitCode : -1,
|
||||
output.toString(StandardCharsets.UTF_8));
|
||||
output.toString(StandardCharsets.UTF_8),
|
||||
stderr.toString(StandardCharsets.UTF_8));
|
||||
} finally {
|
||||
callback.close();
|
||||
}
|
||||
}
|
||||
|
||||
record ContainerExecResult(long exitCode, String output) {}
|
||||
record ContainerExecResult(long exitCode, String output, String stderr) {}
|
||||
|
||||
public void removeVolume(String instanceId, String volumeId) {
|
||||
removeVolume(instanceId, instanceId,
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
package io.github.hectorvent.floci.services.rds.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
public class DbSnapshot {
|
||||
|
||||
private String dbSnapshotIdentifier;
|
||||
private String dbInstanceIdentifier;
|
||||
private Instant snapshotCreateTime;
|
||||
private DatabaseEngine engine;
|
||||
private String engineVersion;
|
||||
private int allocatedStorage;
|
||||
private String status;
|
||||
private String masterUsername;
|
||||
private String masterPassword;
|
||||
private String availabilityZone;
|
||||
private String vpcId;
|
||||
private Instant instanceCreateTime;
|
||||
private int port;
|
||||
private boolean iamDatabaseAuthenticationEnabled;
|
||||
private String dbiResourceId;
|
||||
private String dbName;
|
||||
private String dbInstanceClass;
|
||||
private Map<String, String> tags = new LinkedHashMap<>();
|
||||
|
||||
public DbSnapshot() {}
|
||||
|
||||
public DbSnapshot(String dbSnapshotIdentifier, String dbInstanceIdentifier, Instant snapshotCreateTime,
|
||||
DatabaseEngine engine, String engineVersion, int allocatedStorage, String status,
|
||||
String masterUsername, String masterPassword, String availabilityZone, String vpcId, Instant instanceCreateTime,
|
||||
int port, boolean iamDatabaseAuthenticationEnabled, String dbiResourceId, String dbInstanceClass) {
|
||||
this.dbSnapshotIdentifier = dbSnapshotIdentifier;
|
||||
this.dbInstanceIdentifier = dbInstanceIdentifier;
|
||||
this.snapshotCreateTime = snapshotCreateTime;
|
||||
this.engine = engine;
|
||||
this.engineVersion = engineVersion;
|
||||
this.allocatedStorage = allocatedStorage;
|
||||
this.status = status;
|
||||
this.masterUsername = masterUsername;
|
||||
this.masterPassword = masterPassword;
|
||||
this.availabilityZone = availabilityZone;
|
||||
this.vpcId = vpcId;
|
||||
this.instanceCreateTime = instanceCreateTime;
|
||||
this.port = port;
|
||||
this.iamDatabaseAuthenticationEnabled = iamDatabaseAuthenticationEnabled;
|
||||
this.dbiResourceId = dbiResourceId;
|
||||
this.dbInstanceClass = dbInstanceClass;
|
||||
}
|
||||
|
||||
public String getDbSnapshotIdentifier() { return dbSnapshotIdentifier; }
|
||||
public void setDbSnapshotIdentifier(String dbSnapshotIdentifier) { this.dbSnapshotIdentifier = dbSnapshotIdentifier; }
|
||||
|
||||
public String getDbInstanceIdentifier() { return dbInstanceIdentifier; }
|
||||
public void setDbInstanceIdentifier(String dbInstanceIdentifier) { this.dbInstanceIdentifier = dbInstanceIdentifier; }
|
||||
|
||||
public Instant getSnapshotCreateTime() { return snapshotCreateTime; }
|
||||
public void setSnapshotCreateTime(Instant snapshotCreateTime) { this.snapshotCreateTime = snapshotCreateTime; }
|
||||
|
||||
public DatabaseEngine getEngine() { return engine; }
|
||||
public void setEngine(DatabaseEngine engine) { this.engine = engine; }
|
||||
|
||||
public String getEngineVersion() { return engineVersion; }
|
||||
public void setEngineVersion(String engineVersion) { this.engineVersion = engineVersion; }
|
||||
|
||||
public int getAllocatedStorage() { return allocatedStorage; }
|
||||
public void setAllocatedStorage(int allocatedStorage) { this.allocatedStorage = allocatedStorage; }
|
||||
|
||||
public String getStatus() { return status; }
|
||||
public void setStatus(String status) { this.status = status; }
|
||||
|
||||
public String getMasterUsername() { return masterUsername; }
|
||||
public void setMasterUsername(String masterUsername) { this.masterUsername = masterUsername; }
|
||||
|
||||
public String getMasterPassword() { return masterPassword; }
|
||||
public void setMasterPassword(String masterPassword) { this.masterPassword = masterPassword; }
|
||||
|
||||
public String getAvailabilityZone() { return availabilityZone; }
|
||||
public void setAvailabilityZone(String availabilityZone) { this.availabilityZone = availabilityZone; }
|
||||
|
||||
public String getVpcId() { return vpcId; }
|
||||
public void setVpcId(String vpcId) { this.vpcId = vpcId; }
|
||||
|
||||
public Instant getInstanceCreateTime() { return instanceCreateTime; }
|
||||
public void setInstanceCreateTime(Instant instanceCreateTime) { this.instanceCreateTime = instanceCreateTime; }
|
||||
|
||||
public int getPort() { return port; }
|
||||
public void setPort(int port) { this.port = port; }
|
||||
|
||||
public boolean isIamDatabaseAuthenticationEnabled() { return iamDatabaseAuthenticationEnabled; }
|
||||
public void setIamDatabaseAuthenticationEnabled(boolean iamDatabaseAuthenticationEnabled) { this.iamDatabaseAuthenticationEnabled = iamDatabaseAuthenticationEnabled; }
|
||||
|
||||
public String getDbiResourceId() { return dbiResourceId; }
|
||||
public void setDbiResourceId(String dbiResourceId) { this.dbiResourceId = dbiResourceId; }
|
||||
|
||||
public Map<String, String> getTags() { return tags; }
|
||||
public void setTags(Map<String, String> tags) { this.tags = tags; }
|
||||
|
||||
public String getDbName() { return dbName; }
|
||||
public void setDbName(String dbName) { this.dbName = dbName; }
|
||||
|
||||
public String getDbInstanceClass() { return dbInstanceClass; }
|
||||
public void setDbInstanceClass(String dbInstanceClass) { this.dbInstanceClass = dbInstanceClass; }
|
||||
}
|
||||
Reference in new issue
Block a user