mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -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
@@ -0,0 +1,114 @@
|
||||
package io.github.hectorvent.floci.services.rds;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Tag;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
|
||||
@QuarkusTest
|
||||
@Tag("docker")
|
||||
class RdsAwsIntegrationTest {
|
||||
|
||||
private static final String RDS_AUTH = "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/rds/aws4_request";
|
||||
|
||||
@Inject
|
||||
DockerClient dockerClient;
|
||||
|
||||
@BeforeEach
|
||||
void checkDocker() {
|
||||
try {
|
||||
dockerClient.pingCmd().exec();
|
||||
} catch (Exception e) {
|
||||
assumeTrue(false, "Docker is not available: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void createDescribeRestoreRoundTrip() throws Exception {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String dbId = "test-db-" + suffix;
|
||||
String snapshotId = "test-snap-" + suffix;
|
||||
String restoreId = "test-restore-" + suffix;
|
||||
|
||||
// 1. Create DB instance
|
||||
given()
|
||||
.header("Authorization", RDS_AUTH)
|
||||
.formParam("Action", "CreateDBInstance")
|
||||
.formParam("DBInstanceIdentifier", dbId)
|
||||
.formParam("Engine", "postgres")
|
||||
.formParam("MasterUsername", "admin")
|
||||
.formParam("MasterUserPassword", "secret123")
|
||||
.formParam("AllocatedStorage", "5")
|
||||
.formParam("DBInstanceClass", "db.t3.micro")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString(dbId));
|
||||
|
||||
// 2. Wait for it to be available
|
||||
waitForDb(dbId);
|
||||
|
||||
// 3. Create snapshot
|
||||
given()
|
||||
.header("Authorization", RDS_AUTH)
|
||||
.formParam("Action", "CreateDBSnapshot")
|
||||
.formParam("DBInstanceIdentifier", dbId)
|
||||
.formParam("DBSnapshotIdentifier", snapshotId)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString(snapshotId));
|
||||
|
||||
// 4. Restore DB instance
|
||||
given()
|
||||
.header("Authorization", RDS_AUTH)
|
||||
.formParam("Action", "RestoreDBInstanceFromDBSnapshot")
|
||||
.formParam("DBInstanceIdentifier", restoreId)
|
||||
.formParam("DBSnapshotIdentifier", snapshotId)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString(restoreId));
|
||||
|
||||
// 5. Wait for it to be available
|
||||
waitForDb(restoreId);
|
||||
|
||||
// 6. Describe restored DB instance to ensure it exists
|
||||
given()
|
||||
.header("Authorization", RDS_AUTH)
|
||||
.formParam("Action", "DescribeDBInstances")
|
||||
.formParam("DBInstanceIdentifier", restoreId)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString(restoreId));
|
||||
}
|
||||
|
||||
private void waitForDb(String dbId) throws Exception {
|
||||
for (int i = 0; i < 60; i++) {
|
||||
String status = given()
|
||||
.header("Authorization", RDS_AUTH)
|
||||
.formParam("Action", "DescribeDBInstances")
|
||||
.formParam("DBInstanceIdentifier", dbId)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.extract().xmlPath().getString("DescribeDBInstancesResponse.DescribeDBInstancesResult.DBInstances.DBInstance.DBInstanceStatus");
|
||||
|
||||
if ("available".equals(status) || status == null) {
|
||||
return; // mock mode might return available immediately or not have status depending on delay config
|
||||
}
|
||||
Thread.sleep(1000);
|
||||
}
|
||||
throw new RuntimeException("DB instance " + dbId + " did not become available.");
|
||||
}
|
||||
}
|
||||
@@ -1005,6 +1005,7 @@ class RdsQueryHandlerTest {
|
||||
|
||||
@Test
|
||||
void describeDbSnapshots_returnsEmptyListWith200() {
|
||||
when(service.describeDbSnapshots(null, null)).thenReturn(List.of());
|
||||
Response response = handler.handle("DescribeDBSnapshots", params());
|
||||
|
||||
String body = (String) response.getEntity();
|
||||
@@ -1014,6 +1015,26 @@ class RdsQueryHandlerTest {
|
||||
assertFalse(body.contains("<Marker>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeDbSnapshots_returnsSnapshotListWith200() {
|
||||
io.github.hectorvent.floci.services.rds.model.DbSnapshot snapshot = new io.github.hectorvent.floci.services.rds.model.DbSnapshot();
|
||||
snapshot.setDbSnapshotIdentifier("mysnap");
|
||||
snapshot.setDbInstanceIdentifier("mydb");
|
||||
snapshot.setEngine(io.github.hectorvent.floci.services.rds.model.DatabaseEngine.POSTGRES);
|
||||
when(service.describeDbSnapshots("mysnap", "mydb")).thenReturn(List.of(snapshot));
|
||||
|
||||
MultivaluedMap<String, String> p = params();
|
||||
p.add("DBSnapshotIdentifier", "mysnap");
|
||||
p.add("DBInstanceIdentifier", "mydb");
|
||||
Response response = handler.handle("DescribeDBSnapshots", p);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
String body = (String) response.getEntity();
|
||||
assertTrue(body.contains("<DescribeDBSnapshotsResult>"));
|
||||
assertTrue(body.contains("<DBSnapshotIdentifier>mysnap</DBSnapshotIdentifier>"));
|
||||
assertTrue(body.contains("<DBInstanceIdentifier>mydb</DBInstanceIdentifier>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeDbProxies_returnsEmptyListWith200() {
|
||||
Response response = handler.handle("DescribeDBProxies", params());
|
||||
@@ -1658,18 +1679,49 @@ class RdsQueryHandlerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeDbSubnetGroups_missingNameReturnsNotFoundFault() {
|
||||
when(service.listDbSubnetGroups("does-not-exist", null))
|
||||
.thenThrow(new AwsException("DBSubnetGroupNotFoundFault",
|
||||
"DB subnet group does-not-exist not found.", 404));
|
||||
void createDbSnapshot_success() {
|
||||
io.github.hectorvent.floci.services.rds.model.DbSnapshot snapshot = new io.github.hectorvent.floci.services.rds.model.DbSnapshot();
|
||||
snapshot.setDbSnapshotIdentifier("mysnap");
|
||||
snapshot.setDbInstanceIdentifier("mydb");
|
||||
snapshot.setEngine(io.github.hectorvent.floci.services.rds.model.DatabaseEngine.POSTGRES);
|
||||
when(service.createDbSnapshot("mysnap", "mydb")).thenReturn(snapshot);
|
||||
|
||||
MultivaluedMap<String, String> p = params();
|
||||
p.add("DBSubnetGroupName", "does-not-exist");
|
||||
p.add("DBSnapshotIdentifier", "mysnap");
|
||||
p.add("DBInstanceIdentifier", "mydb");
|
||||
Response response = handler.handle("CreateDBSnapshot", p);
|
||||
|
||||
Response response = handler.handle("DescribeDBSubnetGroups", p);
|
||||
assertEquals(200, response.getStatus());
|
||||
String body = (String) response.getEntity();
|
||||
assertTrue(body.contains("<CreateDBSnapshotResult>"));
|
||||
assertTrue(body.contains("<DBSnapshotIdentifier>mysnap</DBSnapshotIdentifier>"));
|
||||
assertTrue(body.contains("<DBInstanceIdentifier>mydb</DBInstanceIdentifier>"));
|
||||
assertTrue(body.contains("<Engine>postgres</Engine>"));
|
||||
}
|
||||
|
||||
assertEquals(404, response.getStatus());
|
||||
assertTrue(((String) response.getEntity()).contains("DBSubnetGroupNotFoundFault"));
|
||||
@Test
|
||||
void restoreDbInstanceFromDbSnapshot_success() {
|
||||
DbInstance instance = makeInstance("mydb");
|
||||
when(service.restoreDbInstanceFromDbSnapshot(eq("mydb"), eq("mysnap"), eq("db.t3.large"), eq("us-east-1a"), eq(true), eq("my-subnets"), eq(List.of("sg-123")), eq(Map.of("Env", "Prod"))))
|
||||
.thenReturn(instance);
|
||||
|
||||
MultivaluedMap<String, String> p = params();
|
||||
p.add("DBInstanceIdentifier", "mydb");
|
||||
p.add("DBSnapshotIdentifier", "mysnap");
|
||||
p.add("DBInstanceClass", "db.t3.large");
|
||||
p.add("AvailabilityZone", "us-east-1a");
|
||||
p.add("MultiAZ", "true");
|
||||
p.add("DBSubnetGroupName", "my-subnets");
|
||||
p.add("VpcSecurityGroupIds.VpcSecurityGroupId.1", "sg-123");
|
||||
p.add("Tags.Tag.1.Key", "Env");
|
||||
p.add("Tags.Tag.1.Value", "Prod");
|
||||
|
||||
Response response = handler.handle("RestoreDBInstanceFromDBSnapshot", p);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
String body = (String) response.getEntity();
|
||||
assertTrue(body.contains("<RestoreDBInstanceFromDBSnapshotResult>"));
|
||||
assertTrue(body.contains("<DBInstanceIdentifier>mydb</DBInstanceIdentifier>"));
|
||||
}
|
||||
|
||||
// ─────────────── NotFound faults for missing identifiers (AWS parity) ───────────────
|
||||
|
||||
@@ -2608,6 +2608,155 @@ class RdsServiceTest {
|
||||
eq("admin"), eq("secret"), eq("app"), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createDbInstanceAcceptsMasterUsernameWithUnderscores() {
|
||||
DbInstance instance = rdsService.createDbInstance("mydb", "postgres", "13",
|
||||
"my_master_user", "password", "dbname", "db.t3.micro",
|
||||
20, false, null, null, null, null, false);
|
||||
assertEquals("my_master_user", instance.getMasterUsername());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createDbInstanceRejectsInvalidMasterUsername() {
|
||||
AwsException ex1 = assertThrows(AwsException.class, () ->
|
||||
rdsService.createDbInstance("mydb1", "postgres", "13",
|
||||
"_admin", "password", "dbname", "db.t3.micro",
|
||||
20, false, null, null, null, null, false));
|
||||
assertEquals("InvalidParameterValue", ex1.getErrorCode());
|
||||
assertEquals("MasterUsername must begin with a letter and contain only alphanumeric characters or underscores.", ex1.getMessage());
|
||||
|
||||
AwsException ex2 = assertThrows(AwsException.class, () ->
|
||||
rdsService.createDbInstance("mydb2", "postgres", "13",
|
||||
"1admin", "password", "dbname", "db.t3.micro",
|
||||
20, false, null, null, null, null, false));
|
||||
assertEquals("InvalidParameterValue", ex2.getErrorCode());
|
||||
|
||||
AwsException ex3 = assertThrows(AwsException.class, () ->
|
||||
rdsService.createDbInstance("mydb3", "postgres", "13",
|
||||
"admin-user", "password", "dbname", "db.t3.micro",
|
||||
20, false, null, null, null, null, false));
|
||||
assertEquals("InvalidParameterValue", ex3.getErrorCode());
|
||||
|
||||
AwsException ex4 = assertThrows(AwsException.class, () ->
|
||||
rdsService.createDbInstance("mydb4", "postgres", "13",
|
||||
"a1234567890123456", "password", "dbname", "db.t3.micro",
|
||||
20, false, null, null, null, null, false));
|
||||
assertEquals("InvalidParameterValue", ex4.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createDbSnapshotThrowsForNonPostgres() {
|
||||
rdsService.createDbInstance("mydb", "mysql", "8.0",
|
||||
"admin", "password", "dbname", "db.t3.micro",
|
||||
20, false, null, null, null, null, false);
|
||||
|
||||
AwsException exception = assertThrows(AwsException.class, () ->
|
||||
rdsService.createDbSnapshot("mysnap", "mydb"));
|
||||
|
||||
assertEquals("InvalidDBInstanceState", exception.getErrorCode());
|
||||
assertTrue(exception.getMessage().contains("CreateDBSnapshot is not supported for engine MYSQL"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createDbSnapshotSucceedsForPostgres() {
|
||||
rdsService.createDbInstance("mydb", "postgres", "13",
|
||||
"admin", "password", "dbname", "db.t3.micro",
|
||||
20, false, null, null, null, null, false);
|
||||
when(containerManager.createPostgresSnapshot(any(), eq("admin"))).thenReturn("MOCK_DUMP_DATA");
|
||||
|
||||
io.github.hectorvent.floci.services.rds.model.DbSnapshot snapshot = rdsService.createDbSnapshot("mysnap", "mydb");
|
||||
|
||||
assertEquals("mysnap", snapshot.getDbSnapshotIdentifier());
|
||||
assertEquals("mydb", snapshot.getDbInstanceIdentifier());
|
||||
assertEquals(DatabaseEngine.POSTGRES, snapshot.getEngine());
|
||||
assertEquals("available", snapshot.getStatus());
|
||||
verify(containerManager).createPostgresSnapshot(any(), eq("admin"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createDbSnapshotThrowsOnDumpFailure() {
|
||||
rdsService.createDbInstance("mydb", "postgres", "13",
|
||||
"admin", "password", "dbname", "db.t3.micro",
|
||||
20, false, null, null, null, null, false);
|
||||
when(containerManager.createPostgresSnapshot(any(), eq("admin"))).thenThrow(new RuntimeException("dump failed"));
|
||||
|
||||
AwsException exception = assertThrows(AwsException.class, () ->
|
||||
rdsService.createDbSnapshot("mysnap", "mydb"));
|
||||
|
||||
assertEquals("InvalidDBInstanceState", exception.getErrorCode());
|
||||
assertTrue(exception.getMessage().contains("Failed to create snapshot: dump failed"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoreDbInstanceFromDbSnapshotRestoresData() {
|
||||
rdsService.createDbInstance("mydb", "postgres", "13",
|
||||
"admin", "password", "dbname", "db.t3.micro",
|
||||
20, false, null, null, null, null, false);
|
||||
when(containerManager.createPostgresSnapshot(any(), eq("admin"))).thenReturn("MOCK_DUMP_DATA");
|
||||
|
||||
rdsService.createDbSnapshot("mysnap", "mydb");
|
||||
|
||||
DbInstance restored = rdsService.restoreDbInstanceFromDbSnapshot("restored-db", "mysnap", "db.t3.large", "us-east-1a", false, null, null, Map.of());
|
||||
|
||||
assertEquals("restored-db", restored.getDbInstanceIdentifier());
|
||||
assertEquals("db.t3.large", restored.getDbInstanceClass());
|
||||
assertEquals(DatabaseEngine.POSTGRES, restored.getEngine());
|
||||
assertEquals("admin", restored.getMasterUsername());
|
||||
assertEquals("us-east-1a", restored.getAvailabilityZone());
|
||||
assertEquals("dbname", restored.getDbName());
|
||||
verify(containerManager).restorePostgresSnapshot(any(), eq("admin"), eq("MOCK_DUMP_DATA"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoreDbInstanceFromDbSnapshotThrowsOnRestoreFailure() {
|
||||
rdsService.createDbInstance("mydb", "postgres", "13",
|
||||
"admin", "password", "dbname", "db.t3.micro",
|
||||
20, false, null, null, null, null, false);
|
||||
when(containerManager.createPostgresSnapshot(any(), eq("admin"))).thenReturn("MOCK_DUMP_DATA");
|
||||
rdsService.createDbSnapshot("mysnap", "mydb");
|
||||
|
||||
org.mockito.Mockito.doThrow(new RuntimeException("failed restore"))
|
||||
.when(containerManager).restorePostgresSnapshot(any(), eq("admin"), eq("MOCK_DUMP_DATA"));
|
||||
|
||||
AwsException exception = assertThrows(AwsException.class, () ->
|
||||
rdsService.restoreDbInstanceFromDbSnapshot("restored-db", "mysnap", "db.t3.large", "us-east-1a", false, null, null, Map.of()));
|
||||
|
||||
assertEquals("InvalidDBSnapshotState", exception.getErrorCode());
|
||||
assertTrue(exception.getMessage().contains("Failed to restore snapshot: failed restore"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeDbSnapshotsFiltersCorrectly() {
|
||||
rdsService.createDbInstance("mydb1", "postgres", "13",
|
||||
"admin", "password", "dbname", "db.t3.micro",
|
||||
20, false, null, null, null, null, false);
|
||||
rdsService.createDbInstance("mydb2", "postgres", "13",
|
||||
"admin", "password", "dbname", "db.t3.micro",
|
||||
20, false, null, null, null, null, false);
|
||||
|
||||
when(containerManager.createPostgresSnapshot(any(), eq("admin"))).thenReturn("MOCK_DUMP_DATA");
|
||||
|
||||
rdsService.createDbSnapshot("snap1", "mydb1");
|
||||
rdsService.createDbSnapshot("snap2", "mydb2");
|
||||
|
||||
// 1. Describe all
|
||||
Collection<io.github.hectorvent.floci.services.rds.model.DbSnapshot> all = rdsService.describeDbSnapshots(null, null);
|
||||
assertEquals(2, all.size());
|
||||
|
||||
// 2. Describe by snapshot ID
|
||||
Collection<io.github.hectorvent.floci.services.rds.model.DbSnapshot> snap1Result = rdsService.describeDbSnapshots("snap1", null);
|
||||
assertEquals(1, snap1Result.size());
|
||||
assertEquals("snap1", snap1Result.iterator().next().getDbSnapshotIdentifier());
|
||||
|
||||
// 3. Describe by invalid snapshot ID throws
|
||||
assertThrows(AwsException.class, () -> rdsService.describeDbSnapshots("invalid-snap", null));
|
||||
|
||||
// 4. Describe by DB instance ID
|
||||
Collection<io.github.hectorvent.floci.services.rds.model.DbSnapshot> inst1Result = rdsService.describeDbSnapshots(null, "mydb1");
|
||||
assertEquals(1, inst1Result.size());
|
||||
assertEquals("snap1", inst1Result.iterator().next().getDbSnapshotIdentifier());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedInstanceRestoreClearsRuntimeStateAndReleasesItsEndpointPort() {
|
||||
InMemoryStorage<String, DbInstance> instances = new InMemoryStorage<>();
|
||||
|
||||
+298
@@ -0,0 +1,298 @@
|
||||
package io.github.hectorvent.floci.services.rds.container;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.CreateContainerResponse;
|
||||
import com.github.dockerjava.api.exception.DockerException;
|
||||
import com.github.dockerjava.api.model.ExposedPort;
|
||||
import com.github.dockerjava.api.model.HostConfig;
|
||||
import com.github.dockerjava.api.model.Ports;
|
||||
import com.github.dockerjava.core.DefaultDockerClientConfig;
|
||||
import com.github.dockerjava.core.DockerClientImpl;
|
||||
import com.github.dockerjava.httpclient5.ApacheDockerHttpClient;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Tag;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestInstance;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.Closeable;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import com.github.dockerjava.api.async.ResultCallback;
|
||||
import com.github.dockerjava.api.model.Frame;
|
||||
import com.github.dockerjava.api.model.StreamType;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Round-trip test for PostgreSQL snapshot dump and restore using real Docker containers.
|
||||
* Verifies that a dump taken from one container can be restored into a fresh container
|
||||
* with the same master user, which previously failed due to "current user cannot be dropped".
|
||||
*/
|
||||
@Tag("docker")
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
class RdsContainerManagerPostgresTest {
|
||||
|
||||
private static final String IMAGE = "postgres:16-alpine";
|
||||
private static final String MASTER_USER = "admin";
|
||||
private static final String MASTER_PASSWORD = "secret";
|
||||
private static final String DB_NAME = "appdb";
|
||||
private static final int PG_PORT = 5432;
|
||||
|
||||
private DockerClient dockerClient;
|
||||
private String sourceContainerId;
|
||||
private String targetContainerId;
|
||||
|
||||
@BeforeAll
|
||||
void setUp() {
|
||||
try {
|
||||
DefaultDockerClientConfig clientConfig = DefaultDockerClientConfig
|
||||
.createDefaultConfigBuilder()
|
||||
.build();
|
||||
ApacheDockerHttpClient httpClient = new ApacheDockerHttpClient.Builder()
|
||||
.dockerHost(clientConfig.getDockerHost())
|
||||
.maxConnections(10)
|
||||
.connectionTimeout(Duration.ofSeconds(10))
|
||||
.responseTimeout(Duration.ofMinutes(5))
|
||||
.build();
|
||||
dockerClient = DockerClientImpl.getInstance(clientConfig, httpClient);
|
||||
dockerClient.pingCmd().exec();
|
||||
} catch (Exception e) {
|
||||
assumeTrue(false, "Docker is not available: " + e.getMessage());
|
||||
}
|
||||
|
||||
try {
|
||||
dockerClient.pullImageCmd(IMAGE).start().awaitCompletion(120, TimeUnit.SECONDS);
|
||||
} catch (Exception e) {
|
||||
assumeTrue(false, "Could not pull " + IMAGE + ": " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
void tearDown() {
|
||||
removeContainer(sourceContainerId);
|
||||
removeContainer(targetContainerId);
|
||||
if (dockerClient != null) {
|
||||
try {
|
||||
dockerClient.close();
|
||||
} catch (IOException ignored) {
|
||||
// best effort
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void snapshotRoundTripPreservesDataWithNonDefaultUser() throws Exception {
|
||||
// 1. Start source container with non-default master user
|
||||
sourceContainerId = startPostgresContainer("floci-test-pg-source");
|
||||
waitForPostgresReady(sourceContainerId, MASTER_USER, DB_NAME, 60);
|
||||
|
||||
// 2. Create a probe table with data in the application database
|
||||
execPsql(sourceContainerId, MASTER_USER, DB_NAME,
|
||||
"CREATE TABLE probe (id serial PRIMARY KEY, value text);"
|
||||
+ "INSERT INTO probe (value) VALUES ('round-trip-test');");
|
||||
|
||||
// 3. Dump using the production code path
|
||||
RdsContainerManager manager = createManager();
|
||||
String dump = manager.createPostgresSnapshot(sourceContainerId, MASTER_USER);
|
||||
|
||||
assertTrue(dump.contains("CREATE ROLE " + MASTER_USER),
|
||||
"Dump should contain CREATE ROLE for the master user");
|
||||
assertTrue(dump.contains(DB_NAME),
|
||||
"Dump should reference the application database");
|
||||
|
||||
// 4. Start a fresh target container with the same master user
|
||||
targetContainerId = startPostgresContainer("floci-test-pg-target");
|
||||
waitForPostgresReady(targetContainerId, MASTER_USER, DB_NAME, 60);
|
||||
|
||||
// 5. Restore using the production code path
|
||||
manager.restorePostgresSnapshot(targetContainerId, MASTER_USER, dump);
|
||||
|
||||
// 6. Verify the probe row exists in the target
|
||||
String result = queryPsql(targetContainerId, MASTER_USER, DB_NAME,
|
||||
"SELECT value FROM probe WHERE id = 1");
|
||||
assertEquals("round-trip-test", result.trim(),
|
||||
"Restored database should contain the probe row");
|
||||
}
|
||||
|
||||
private String startPostgresContainer(String name) {
|
||||
removeContainerByName(name);
|
||||
|
||||
ExposedPort pgPort = ExposedPort.tcp(PG_PORT);
|
||||
CreateContainerResponse container = dockerClient.createContainerCmd(IMAGE)
|
||||
.withName(name)
|
||||
.withExposedPorts(pgPort)
|
||||
.withHostConfig(HostConfig.newHostConfig()
|
||||
.withPortBindings(new Ports(pgPort, Ports.Binding.empty())))
|
||||
.withEnv(
|
||||
"POSTGRES_USER=" + MASTER_USER,
|
||||
"POSTGRES_PASSWORD=" + MASTER_PASSWORD,
|
||||
"POSTGRES_DB=" + DB_NAME,
|
||||
"POSTGRES_HOST_AUTH_METHOD=md5"
|
||||
)
|
||||
.exec();
|
||||
|
||||
dockerClient.startContainerCmd(container.getId()).exec();
|
||||
return container.getId();
|
||||
}
|
||||
|
||||
private void waitForPostgresReady(String containerId, String user, String dbName, int maxSeconds) {
|
||||
String[] cmd = {"psql", "-U", user, "-d", dbName, "-c", "SELECT 1"};
|
||||
for (int i = 0; i < maxSeconds; i++) {
|
||||
try {
|
||||
ExecResult result = exec(containerId, cmd, 5);
|
||||
if (result.exitCode() == 0) {
|
||||
return;
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
// not ready yet
|
||||
}
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new RuntimeException("Interrupted waiting for PostgreSQL", e);
|
||||
}
|
||||
}
|
||||
throw new RuntimeException("PostgreSQL did not become ready within " + maxSeconds + "s");
|
||||
}
|
||||
|
||||
private void execPsql(String containerId, String user, String db, String sql) throws Exception {
|
||||
String[] cmd = {"psql", "-v", "ON_ERROR_STOP=1", "-U", user, "-d", db, "-c", sql};
|
||||
ExecResult result = exec(containerId, cmd, 30);
|
||||
if (result.exitCode() != 0) {
|
||||
throw new RuntimeException("psql exec failed (exit " + result.exitCode() + "): "
|
||||
+ result.stderr() + " | " + result.stdout());
|
||||
}
|
||||
}
|
||||
|
||||
private String queryPsql(String containerId, String user, String db, String sql) throws Exception {
|
||||
String[] cmd = {"psql", "-v", "ON_ERROR_STOP=1", "-U", user, "-d", db, "-tAc", sql};
|
||||
ExecResult result = exec(containerId, cmd, 30);
|
||||
if (result.exitCode() != 0) {
|
||||
throw new RuntimeException("psql query failed (exit " + result.exitCode() + "): "
|
||||
+ result.stderr() + " | " + result.stdout());
|
||||
}
|
||||
return result.stdout();
|
||||
}
|
||||
|
||||
private ExecResult exec(String containerId, String[] cmd, int timeoutSeconds) throws Exception {
|
||||
String execId = dockerClient.execCreateCmd(containerId)
|
||||
.withCmd(cmd)
|
||||
.withAttachStdout(true)
|
||||
.withAttachStderr(true)
|
||||
.exec()
|
||||
.getId();
|
||||
|
||||
CountDownLatch latch = new CountDownLatch(1);
|
||||
ByteArrayOutputStream stdout = new ByteArrayOutputStream();
|
||||
ByteArrayOutputStream stderr = new ByteArrayOutputStream();
|
||||
|
||||
Closeable callback = dockerClient.execStartCmd(execId)
|
||||
.exec(new ResultCallback.Adapter<Frame>() {
|
||||
@Override
|
||||
public void onNext(Frame frame) {
|
||||
if (frame.getPayload() != null) {
|
||||
try {
|
||||
if (frame.getStreamType() == StreamType.STDOUT) {
|
||||
stdout.write(frame.getPayload());
|
||||
} else if (frame.getStreamType() == StreamType.STDERR) {
|
||||
stderr.write(frame.getPayload());
|
||||
}
|
||||
} catch (IOException ignored) {
|
||||
// best effort
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onComplete() {
|
||||
latch.countDown();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(Throwable t) {
|
||||
latch.countDown();
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
boolean completed = latch.await(timeoutSeconds, TimeUnit.SECONDS);
|
||||
if (!completed) {
|
||||
return new ExecResult(-1, stdout.toString(StandardCharsets.UTF_8),
|
||||
"Timed out after " + timeoutSeconds + "s");
|
||||
}
|
||||
Long exitCode = dockerClient.inspectExecCmd(execId).exec().getExitCodeLong();
|
||||
return new ExecResult(
|
||||
exitCode != null ? exitCode : -1,
|
||||
stdout.toString(StandardCharsets.UTF_8),
|
||||
stderr.toString(StandardCharsets.UTF_8));
|
||||
} finally {
|
||||
callback.close();
|
||||
}
|
||||
}
|
||||
|
||||
private RdsContainerManager createManager() {
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
|
||||
|
||||
return new RdsContainerManager(
|
||||
mock(ContainerBuilder.class),
|
||||
lifecycleManager,
|
||||
mock(ContainerLogStreamer.class),
|
||||
mock(ContainerDetector.class),
|
||||
mock(EmulatorConfig.class),
|
||||
new RegionResolver("us-east-1", "000000000000"),
|
||||
mock(ServiceConfigAccess.class));
|
||||
}
|
||||
|
||||
private void removeContainer(String containerId) {
|
||||
if (containerId == null || dockerClient == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
dockerClient.stopContainerCmd(containerId).withTimeout(5).exec();
|
||||
} catch (DockerException ignored) {
|
||||
// already stopped or gone
|
||||
}
|
||||
try {
|
||||
dockerClient.removeContainerCmd(containerId).withForce(true).exec();
|
||||
} catch (DockerException ignored) {
|
||||
// already removed
|
||||
}
|
||||
}
|
||||
|
||||
private void removeContainerByName(String name) {
|
||||
try {
|
||||
List<com.github.dockerjava.api.model.Container> containers = dockerClient
|
||||
.listContainersCmd()
|
||||
.withShowAll(true)
|
||||
.withNameFilter(List.of(name))
|
||||
.exec();
|
||||
for (com.github.dockerjava.api.model.Container c : containers) {
|
||||
removeContainer(c.getId());
|
||||
}
|
||||
} catch (DockerException ignored) {
|
||||
// best effort
|
||||
}
|
||||
}
|
||||
|
||||
record ExecResult(long exitCode, String stdout, String stderr) {}
|
||||
}
|
||||
+31
@@ -1072,6 +1072,36 @@ class RdsContainerManagerTest {
|
||||
org.mockito.ArgumentMatchers.isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoreScriptConnectsToPostgresDatabase() {
|
||||
String script = RdsContainerManager.postgresRestoreScript();
|
||||
|
||||
assertTrue(script.contains("-d postgres"), "Script must connect to postgres, not template1");
|
||||
assertTrue(script.contains("-f /tmp/dump.sql"), "Script must replay the dump file");
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoreScriptDropsNonSystemDatabasesAndRoles() {
|
||||
String script = RdsContainerManager.postgresRestoreScript();
|
||||
|
||||
assertTrue(script.contains("datistemplate = false"),
|
||||
"Script must only drop non-template databases");
|
||||
assertTrue(script.contains("datname <> 'postgres'"),
|
||||
"Script must preserve the postgres database");
|
||||
assertTrue(script.contains("rolname <> current_user"),
|
||||
"Script must not drop the current user");
|
||||
assertTrue(script.contains("rolname NOT LIKE 'pg_%'"),
|
||||
"Script must not drop system roles");
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoreScriptInterpolatesUser() {
|
||||
String script = RdsContainerManager.postgresRestoreScript();
|
||||
|
||||
assertTrue(script.contains("USER=\"$1\""),
|
||||
"Script must assign the first argument to the USER variable");
|
||||
}
|
||||
|
||||
private static EmulatorConfig config(Path hostRoot) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
@@ -1088,6 +1118,7 @@ class RdsContainerManagerTest {
|
||||
when(docker.logMaxFile()).thenReturn("3");
|
||||
when(config.storage()).thenReturn(storage);
|
||||
when(storage.hostPersistentPath()).thenReturn(hostRoot.toString());
|
||||
when(storage.mode()).thenReturn("persistent");
|
||||
return config;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user