mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(rds): accept MySQL and MariaDB sources in CreateDBInstanceReadReplica (#7857)
CreateDBInstanceReadReplica now accepts MySQL and MariaDB sources and initialises the replica from a mysqldump or mariadb-dump copy of the source, the same copy CreateDBSnapshot uses. One engine set gates both the replica check and the SupportsReadReplica flag DescribeDBEngineVersions reports. The copy passes MYSQL_PWD in the exec's environment rather than its command, uploads the dump readable by root only and removes it after the restore, keeps a name containing a newline whole, and replays each SHOW GRANTS row as one statement, so MariaDB's SET DEFAULT ROLE and MySQL's partial revokes restore. Other engines are still refused with InvalidDBInstanceState.
This commit is contained in:
1 parent
f3116c8b8d
commit
39f2426ba2
10 files changed
+371
-67
No files matched your search
@@ -61,7 +61,7 @@ RDS endpoints return the us-east-1 hosted zone ID `Z2R2ITUGPM61AM` in all region
|
||||
| `StopDBCluster` | Stop a cluster and its member instances |
|
||||
| `StartDBCluster` | Start a stopped cluster and its members |
|
||||
| `RebootDBCluster` | Restart a cluster's database and its members' proxies |
|
||||
| `CreateDBInstanceReadReplica` | Create a read replica of a PostgreSQL instance, initialised from a copy of the source; see [Read replicas](#read-replicas) |
|
||||
| `CreateDBInstanceReadReplica` | Create a read replica of a PostgreSQL, MySQL or MariaDB instance, initialised from a copy of the source; see [Read replicas](#read-replicas) |
|
||||
| `PromoteReadReplica` | Detach a read replica into a standalone instance and turn automated backups on |
|
||||
| `SwitchoverReadReplica` | Refused with `InvalidDBInstanceState`: AWS supports switchover only for Oracle and SQL Server replicas, neither of which is emulated |
|
||||
| `PromoteReadReplicaDBCluster` | Refused with `InvalidDBClusterStateFault`: no cluster is created as a replica of an instance |
|
||||
@@ -724,11 +724,11 @@ and a `StatusInfos` entry of type `read replication`, the source lists it under
|
||||
it is the ARN. A `DBSubnetGroupName` with a source given by plain identifier is refused with
|
||||
`DBSubnetGroupNotAllowedFault`, as on AWS.
|
||||
|
||||
The replica's database is initialised from a `pg_dumpall` of the source taken when the replica is
|
||||
created, the same mechanism `RestoreDBInstanceFromDBSnapshot` uses, so it holds the source's data
|
||||
as of that moment. Writes made to the source afterwards are not streamed to the replica. Because
|
||||
the copy is dump based, only PostgreSQL sources are accepted; MySQL and MariaDB sources are refused
|
||||
with `InvalidDBInstanceState`, although `CreateDBSnapshot` accepts them. A source with automated backups
|
||||
The replica's database is initialised from a dump of the source taken when the replica is
|
||||
created, the same mechanism `CreateDBSnapshot` and `RestoreDBInstanceFromDBSnapshot` use, so it
|
||||
holds the source's data as of that moment. Writes made to the source afterwards are not streamed to
|
||||
the replica. PostgreSQL, MySQL and MariaDB sources are accepted; other engines are refused with
|
||||
`InvalidDBInstanceState`. A source with automated backups
|
||||
off (`BackupRetentionPeriod` 0) is refused with the same error AWS uses.
|
||||
|
||||
`PromoteReadReplica` clears the link on both ends, sets the requested `BackupRetentionPeriod`
|
||||
|
||||
@@ -54,9 +54,15 @@ public final class ContainerExec {
|
||||
|
||||
/** Runs {@code cmd}, keeping its stdout and stderr apart. */
|
||||
public static Result run(DockerClient dockerClient, String containerId, String[] cmd, int timeoutSeconds) {
|
||||
return run(dockerClient, containerId, cmd, List.of(), timeoutSeconds);
|
||||
}
|
||||
|
||||
/** As {@link #run(DockerClient, String, String[], int)}, with {@code env} for this command alone. */
|
||||
public static Result run(DockerClient dockerClient, String containerId, String[] cmd, List<String> env,
|
||||
int timeoutSeconds) {
|
||||
ByteArrayOutputStream stdout = new ByteArrayOutputStream();
|
||||
ByteArrayOutputStream stderr = new ByteArrayOutputStream();
|
||||
Result result = run(dockerClient, containerId, cmd, timeoutSeconds, stdout, stderr);
|
||||
Result result = run(dockerClient, containerId, cmd, env, timeoutSeconds, stdout, stderr);
|
||||
return new Result(result.exitCode(), stdout.toString(StandardCharsets.UTF_8),
|
||||
joinLines(stderr.toString(StandardCharsets.UTF_8), result.stderr()), result.timedOut());
|
||||
}
|
||||
|
||||
@@ -115,9 +115,9 @@ final class RdsEngineCatalog {
|
||||
return FEATURE_NAMES.getOrDefault(catalogued, List.of());
|
||||
}
|
||||
|
||||
/** Floci creates read replicas of PostgreSQL instances only. */
|
||||
/** Floci creates read replicas of PostgreSQL, MySQL and MariaDB instances. */
|
||||
static boolean supportsReadReplica(EngineVersion version) {
|
||||
return version.engine().equals("postgres");
|
||||
return RdsService.READ_REPLICA_ENGINES.contains(version.engine());
|
||||
}
|
||||
|
||||
static boolean supportsGlobalDatabases(EngineVersion version) {
|
||||
|
||||
@@ -2199,8 +2199,11 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
+ "automated backups, use ModifyDBInstance to set the backup retention period "
|
||||
+ "to a non-zero value.", 400);
|
||||
}
|
||||
if (source.getEngine() != DatabaseEngine.POSTGRES) {
|
||||
// CreateDBSnapshot draws the same line: the point-in-time copy is pg_dumpall based.
|
||||
boolean mysqlFamily = source.getEngine() == DatabaseEngine.MYSQL
|
||||
|| source.getEngine() == DatabaseEngine.MARIADB;
|
||||
if (!READ_REPLICA_ENGINES.contains(source.getEngine().name().toLowerCase(Locale.ROOT))) {
|
||||
// The copy is dump based: pg_dumpall for PostgreSQL, mysqldump or mariadb-dump for
|
||||
// MySQL and MariaDB. No dump path exists for the other engines.
|
||||
throw new AwsException("InvalidDBInstanceState",
|
||||
"Operation CreateDBInstanceReadReplica is not supported for engine "
|
||||
+ source.getEngine() + ".", 400);
|
||||
@@ -2255,10 +2258,18 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
if (!config.services().rds().mock()
|
||||
&& source.getContainerId() != null && replica.getContainerId() != null) {
|
||||
try {
|
||||
String sqlDump = containerManager.createPostgresSnapshot(
|
||||
source.getContainerId(), source.getMasterUsername());
|
||||
containerManager.restorePostgresSnapshot(
|
||||
replica.getContainerId(), replica.getMasterUsername(), sqlDump);
|
||||
if (mysqlFamily) {
|
||||
String sqlDump = containerManager.createMysqlSnapshot(source.getEngine(),
|
||||
source.getContainerId(), source.getMasterUsername(), source.getMasterPassword());
|
||||
containerManager.restoreMysqlSnapshot(replica.getEngine(),
|
||||
replica.getContainerId(), replica.getMasterUsername(),
|
||||
replica.getMasterPassword(), sqlDump);
|
||||
} else {
|
||||
String sqlDump = containerManager.createPostgresSnapshot(
|
||||
source.getContainerId(), source.getMasterUsername());
|
||||
containerManager.restorePostgresSnapshot(
|
||||
replica.getContainerId(), replica.getMasterUsername(), sqlDump);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
deleteDbInstance(id, effectiveRegion);
|
||||
@@ -6480,6 +6491,9 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
|
||||
// ── Global clusters (Aurora global databases) ─────────────────────────────
|
||||
|
||||
/** Engines CreateDBInstanceReadReplica copies; DescribeDBEngineVersions reports the same set. */
|
||||
static final Set<String> READ_REPLICA_ENGINES = Set.of("postgres", "mysql", "mariadb");
|
||||
|
||||
static final Set<String> GLOBAL_CLUSTER_ENGINES = Set.of("aurora-mysql", "aurora-postgresql");
|
||||
|
||||
/**
|
||||
|
||||
@@ -1278,7 +1278,7 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
|
||||
files.put("dump.sql", sqlDump);
|
||||
files.put("restore.sh", postgresRestoreScript());
|
||||
runSnapshotScript(containerId, "postgres-restore", files,
|
||||
new String[]{"sh", "/tmp/restore.sh", effectiveUser}, 60, 120, "psql restore");
|
||||
new String[]{"sh", "/tmp/restore.sh", effectiveUser}, List.of(), 60, 120, "psql restore");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1290,7 +1290,8 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
|
||||
* tries, throws with {@code operation} and the command's error output.
|
||||
*/
|
||||
private String runSnapshotScript(String containerId, String uploadName, Map<String, String> files,
|
||||
String[] cmd, int attempts, int timeoutSeconds, String operation) {
|
||||
String[] cmd, List<String> env, int attempts, int timeoutSeconds,
|
||||
String operation) {
|
||||
try (Lease _ = holdContainer(containerId)) {
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
try (TarArchiveOutputStream tar = new TarArchiveOutputStream(bos)) {
|
||||
@@ -1304,26 +1305,36 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
|
||||
"/tmp", uploadName, out -> out.write(archive),
|
||||
RetryingTarCopier.DEFAULT_MAX_ATTEMPTS, uploadBackoffMillis);
|
||||
|
||||
ContainerExec.Result result = null;
|
||||
for (int i = 0; i < attempts; i++) {
|
||||
result = execInContainer(containerId, cmd, timeoutSeconds);
|
||||
if (result.exitCode() != 2) {
|
||||
break;
|
||||
boolean succeeded = false;
|
||||
try {
|
||||
ContainerExec.Result result = null;
|
||||
for (int i = 0; i < attempts; i++) {
|
||||
result = ContainerExec.run(lifecycleManager.getDockerClient(), containerId, cmd, env,
|
||||
timeoutSeconds);
|
||||
if (result.exitCode() != 2) {
|
||||
break;
|
||||
}
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException ie) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new RuntimeException("Interrupted while waiting to run " + operation, ie);
|
||||
}
|
||||
}
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException ie) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new RuntimeException("Interrupted while waiting to run " + operation, ie);
|
||||
}
|
||||
}
|
||||
|
||||
if (result == null || result.exitCode() != 0) {
|
||||
String errMsg = result != null ? (result.stderr().isEmpty() ? result.stdout() : result.stderr()) : "";
|
||||
throw new RuntimeException(operation + " failed with exit code "
|
||||
+ (result != null ? result.exitCode() : -1) + ": " + errMsg);
|
||||
if (result == null || result.exitCode() != 0) {
|
||||
String errMsg = result != null ? (result.stderr().isEmpty() ? result.stdout() : result.stderr()) : "";
|
||||
throw new RuntimeException(operation + " failed with exit code "
|
||||
+ (result != null ? result.exitCode() : -1) + ": " + errMsg);
|
||||
}
|
||||
succeeded = true;
|
||||
return result.stdout();
|
||||
} finally {
|
||||
// On success the script's own EXIT trap has removed it.
|
||||
if (!succeeded && files.containsKey("dump.sql")) {
|
||||
removeDump(containerId);
|
||||
}
|
||||
}
|
||||
return result.stdout();
|
||||
} catch (RuntimeException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
@@ -1331,6 +1342,19 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the uploaded dump when the script could not: it gave up on a server that never answered,
|
||||
* or its exec timed out or was killed. Best effort, since the container may be gone.
|
||||
*/
|
||||
private void removeDump(String containerId) {
|
||||
try {
|
||||
ContainerExec.run(lifecycleManager.getDockerClient(), containerId,
|
||||
new String[]{"rm", "-f", "/tmp/dump.sql"}, 30);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.debugv("Could not remove /tmp/dump.sql from {0}: {1}", containerId, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A logical copy of a MySQL or MariaDB server, the counterpart of {@link #createPostgresSnapshot}:
|
||||
* every user schema (with its routines, triggers and events), then every role and every account
|
||||
@@ -1343,11 +1367,10 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
|
||||
public String createMysqlSnapshot(DatabaseEngine engine, String containerId,
|
||||
String masterUsername, String masterPassword) {
|
||||
MysqlTools tools = MysqlTools.of(engine);
|
||||
String[] cmd = {"env", "MYSQL_PWD=" + (masterPassword == null ? "" : masterPassword),
|
||||
"sh", "/tmp/floci-mysql-dump.sh", tools.client(), tools.dump(), mysqlUser(masterUsername),
|
||||
String[] cmd = {"sh", "/tmp/floci-mysql-dump.sh", tools.client(), tools.dump(), mysqlUser(masterUsername),
|
||||
tools.dumpFlags(), tools.accountClause(), tools.roleFilter()};
|
||||
return runSnapshotScript(containerId, "mysql-dump", Map.of("floci-mysql-dump.sh", mysqlDumpScript()),
|
||||
cmd, 120, 300, tools.dump());
|
||||
cmd, mysqlPasswordEnv(masterPassword), 120, 300, tools.dump());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1361,9 +1384,9 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
|
||||
Map<String, String> files = new LinkedHashMap<>();
|
||||
files.put("dump.sql", sqlDump);
|
||||
files.put("restore.sh", mysqlRestoreScript());
|
||||
String[] cmd = {"env", "MYSQL_PWD=" + (masterPassword == null ? "" : masterPassword),
|
||||
"sh", "/tmp/restore.sh", tools.client(), mysqlUser(masterUsername)};
|
||||
runSnapshotScript(containerId, "mysql-restore", files, cmd, 120, 300, tools.client() + " restore");
|
||||
String[] cmd = {"sh", "/tmp/restore.sh", tools.client(), mysqlUser(masterUsername)};
|
||||
runSnapshotScript(containerId, "mysql-restore", files, cmd, mysqlPasswordEnv(masterPassword), 120, 300,
|
||||
tools.client() + " restore");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1385,6 +1408,11 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
|
||||
}
|
||||
}
|
||||
|
||||
/** The password goes in the exec's own environment, so it is not part of the command Docker records. */
|
||||
private static List<String> mysqlPasswordEnv(String masterPassword) {
|
||||
return List.of("MYSQL_PWD=" + (masterPassword == null ? "" : masterPassword));
|
||||
}
|
||||
|
||||
private static String mysqlUser(String masterUsername) {
|
||||
return masterUsername != null && !masterUsername.isBlank() ? masterUsername : "root";
|
||||
}
|
||||
@@ -1393,20 +1421,23 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
|
||||
return """
|
||||
#!/bin/sh
|
||||
# usage: floci-mysql-dump.sh <client> <dump> <user> <dump flags> <account clause> <role filter>
|
||||
# The password arrives in MYSQL_PWD. Names are read one per line, so a schema or
|
||||
# account name with spaces stays one argument.
|
||||
# The password arrives in MYSQL_PWD. Names are read one per line, so the client
|
||||
# escapes a newline in one as \\n (batch mode without -r) and unesc restores it.
|
||||
set -ef
|
||||
C="$1"; D="$2"; U="$3"; FLAGS="$4"; ACCOUNT_CLAUSE="$5"; ROLE_FILTER="$6"
|
||||
SQL() { "$C" -h127.0.0.1 --protocol=TCP -u"$U" -N -B -r -e "$1"; }
|
||||
NAMES() { "$C" -h127.0.0.1 --protocol=TCP -u"$U" -N -B -e "$1"; }
|
||||
# Sets R to the name in $1 with its escapes undone; the dot keeps a trailing newline.
|
||||
unesc() { R=$(printf '%b.' "$1"); R=${R%.}; }
|
||||
# Exit 2: the server does not accept the master user over TCP yet. Past this point a
|
||||
# failure exits 1, even mysqldump's own exit 2, so it is not retried as one.
|
||||
SQL "SELECT 1" >/dev/null 2>&1 || exit 2
|
||||
trap 'rc=$?; if [ "$rc" = 2 ]; then exit 1; fi' EXIT
|
||||
DBS=$(SQL "SELECT schema_name FROM information_schema.schemata WHERE schema_name NOT IN \\
|
||||
DBS=$(NAMES "SELECT schema_name FROM information_schema.schemata WHERE schema_name NOT IN \\
|
||||
('mysql','sys','performance_schema','information_schema')")
|
||||
set --
|
||||
while IFS= read -r db; do
|
||||
if [ -n "$db" ]; then set -- "$@" "$db"; fi
|
||||
if [ -n "$db" ]; then unesc "$db"; set -- "$@" "$R"; fi
|
||||
done <<EOF
|
||||
$DBS
|
||||
EOF
|
||||
@@ -1415,17 +1446,18 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
|
||||
"$D" -h127.0.0.1 --protocol=TCP -u"$U" --routines --events --triggers \\
|
||||
--single-transaction --hex-blob --no-tablespaces $FLAGS --databases "$@"
|
||||
fi
|
||||
ROLES=$(SQL "SELECT QUOTE(user) FROM mysql.user WHERE $ROLE_FILTER")
|
||||
ACCOUNTS=$(SQL "SELECT CONCAT(QUOTE(user),'@',QUOTE(host)) FROM mysql.user WHERE user NOT IN \\
|
||||
ROLES=$(NAMES "SELECT QUOTE(user) FROM mysql.user WHERE $ROLE_FILTER")
|
||||
ACCOUNTS=$(NAMES "SELECT CONCAT(QUOTE(user),'@',QUOTE(host)) FROM mysql.user WHERE user NOT IN \\
|
||||
('','root','mysql.sys','mysql.session','mysql.infoschema','mariadb.sys','healthcheck','PUBLIC') $ACCOUNT_CLAUSE")
|
||||
# Every role and account is created before any grant, which can name a role.
|
||||
while IFS= read -r role; do
|
||||
if [ -n "$role" ]; then echo "CREATE ROLE IF NOT EXISTS $role;"; fi
|
||||
if [ -n "$role" ]; then unesc "$role"; echo "CREATE ROLE IF NOT EXISTS $R;"; fi
|
||||
done <<EOF
|
||||
$ROLES
|
||||
EOF
|
||||
while IFS= read -r acct; do
|
||||
if [ -n "$acct" ]; then
|
||||
unesc "$acct"; acct=$R
|
||||
# MySQL prints a binary password hash as hex only when asked; MariaDB has no such setting.
|
||||
stmt=$(SQL "SET SESSION print_identified_with_as_hex = ON; SHOW CREATE USER $acct" 2>/dev/null \\
|
||||
|| SQL "SHOW CREATE USER $acct")
|
||||
@@ -1435,7 +1467,9 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
|
||||
$ACCOUNTS
|
||||
EOF
|
||||
while IFS= read -r grantee; do
|
||||
if [ -n "$grantee" ]; then SQL "SHOW GRANTS FOR $grantee" | sed 's/$/;/'; fi
|
||||
# Batch mode without -r prints each statement on one line (a newline in a name is \\n), so one row is
|
||||
# one statement whatever a name contains; %b undoes the escapes.
|
||||
if [ -n "$grantee" ]; then unesc "$grantee"; NAMES "SHOW GRANTS FOR $R" | while IFS= read -r g; do printf '%b;\\n' "$g"; done; fi
|
||||
done <<EOF
|
||||
$ROLES
|
||||
$ACCOUNTS
|
||||
@@ -1449,6 +1483,9 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
|
||||
#!/bin/sh
|
||||
# usage: restore.sh <client> <user>; the password arrives in MYSQL_PWD.
|
||||
C="$1"; U="$2"
|
||||
# The dump holds every schema and account; leave none behind for FILE-privileged readers.
|
||||
# Exit 2 means the server is not up: the caller retries, and needs the dump.
|
||||
trap 'rc=$?; [ "$rc" = 2 ] || rm -f /tmp/dump.sql' EXIT
|
||||
"$C" -h127.0.0.1 --protocol=TCP -u"$U" -e "SELECT 1" >/dev/null 2>&1 || exit 2
|
||||
"$C" -h127.0.0.1 --protocol=TCP -u"$U" < /tmp/dump.sql || exit 1
|
||||
""";
|
||||
@@ -1487,6 +1524,9 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
|
||||
#!/bin/sh
|
||||
set -e
|
||||
USER="$1"
|
||||
# The dump holds every database; leave none behind. Exit 2 means the server is not up:
|
||||
# the caller retries, and needs it.
|
||||
trap 'rc=$?; [ "$rc" = 2 ] || rm -f /tmp/dump.sql /tmp/dump_filtered.sql' EXIT
|
||||
|
||||
# Drop every database but postgres, template0 and template1, including template
|
||||
# databases an image creates at startup (PostGIS's template_postgis), which the dump
|
||||
@@ -1502,6 +1542,7 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
|
||||
# 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
|
||||
chmod 600 /tmp/dump.sql
|
||||
|
||||
# Drop all non-current-user, non-system roles
|
||||
psql -v ON_ERROR_STOP=1 -U "$USER" -d postgres -tAc \\
|
||||
@@ -1523,7 +1564,8 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
|
||||
TarArchiveEntry entry =
|
||||
new TarArchiveEntry(name);
|
||||
entry.setSize(bytes.length);
|
||||
entry.setMode(0755);
|
||||
// The dump holds every schema; only root, who restores it, may read it.
|
||||
entry.setMode(name.endsWith(".sql") ? 0600 : 0755);
|
||||
tar.putArchiveEntry(entry);
|
||||
tar.write(bytes);
|
||||
tar.closeArchiveEntry();
|
||||
|
||||
@@ -16,6 +16,7 @@ import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.Mockito.RETURNS_SELF;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -41,6 +42,13 @@ public final class ContainerExecStubs {
|
||||
*/
|
||||
public static List<List<String>> completeEveryExec(DockerClient dockerClient, String containerId,
|
||||
List<Long> exitCodes, String stdout, String stderr) {
|
||||
return completeEveryExec(dockerClient, containerId, exitCodes, stdout, stderr, new ArrayList<>());
|
||||
}
|
||||
|
||||
/** As above, adding to {@code envs} the environment each exec was created with, in order. */
|
||||
public static List<List<String>> completeEveryExec(DockerClient dockerClient, String containerId,
|
||||
List<Long> exitCodes, String stdout, String stderr,
|
||||
List<List<String>> envs) {
|
||||
String execId = "exec-" + containerId;
|
||||
List<List<String>> commands = new ArrayList<>();
|
||||
|
||||
@@ -53,6 +61,10 @@ public final class ContainerExecStubs {
|
||||
commands.add(List.of(cmd));
|
||||
return createCmd;
|
||||
});
|
||||
when(createCmd.withEnv(anyList())).thenAnswer(invocation -> {
|
||||
envs.add(invocation.getArgument(0));
|
||||
return createCmd;
|
||||
});
|
||||
ExecCreateCmdResponse createResponse = mock(ExecCreateCmdResponse.class);
|
||||
when(createResponse.getId()).thenReturn(execId);
|
||||
when(createCmd.exec()).thenReturn(createResponse);
|
||||
|
||||
@@ -102,6 +102,16 @@ class RdsCatalogueReadIntegrationTest {
|
||||
.body(VERSIONS + ".SupportsReadReplica", equalTo("false"))
|
||||
.body(containsString("<SupportedFeatureNames></SupportedFeatureNames>"))
|
||||
.body(VERSIONS + ".SupportsGlobalDatabases", equalTo("true"));
|
||||
for (String engine : new String[]{"mysql", "mariadb"}) {
|
||||
query("DescribeDBEngineVersions").formParam("Engine", engine).formParam("DefaultOnly", "true")
|
||||
.when().post("/").then()
|
||||
.statusCode(200)
|
||||
.body(VERSIONS + ".SupportsReadReplica", equalTo("true"));
|
||||
}
|
||||
query("DescribeDBEngineVersions").formParam("Engine", "sqlserver-se").formParam("DefaultOnly", "true")
|
||||
.when().post("/").then()
|
||||
.statusCode(200)
|
||||
.body(VERSIONS + ".SupportsReadReplica", equalTo("false"));
|
||||
query("DescribeDBEngineVersions").formParam("Engine", "aurora-postgresql").formParam("DefaultOnly", "true")
|
||||
.when().post("/").then()
|
||||
.statusCode(200)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package io.floci.aws.services.rds;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
@@ -36,19 +37,26 @@ class RdsReadReplicaIntegrationTest {
|
||||
.formParam("Version", "2014-10-31");
|
||||
}
|
||||
|
||||
/** DBName is left off SQL Server, which refuses it. */
|
||||
private static ValidatableResponse createInstance(String id, String engine, String version, String password) {
|
||||
RequestSpecification request = query("CreateDBInstance")
|
||||
.formParam("DBInstanceIdentifier", id)
|
||||
.formParam("Engine", engine)
|
||||
.formParam("EngineVersion", version)
|
||||
.formParam("MasterUsername", "admin")
|
||||
.formParam("MasterUserPassword", password)
|
||||
.formParam("DBInstanceClass", "db.t3.medium")
|
||||
.formParam("AllocatedStorage", "40");
|
||||
if (!engine.startsWith("sqlserver")) {
|
||||
request.formParam("DBName", "appdb");
|
||||
}
|
||||
return request.when().post("/").then();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void createReadReplicaLinksBothEndsInDescribeDbInstances() {
|
||||
query("CreateDBInstance")
|
||||
.formParam("DBInstanceIdentifier", SOURCE)
|
||||
.formParam("Engine", "postgres")
|
||||
.formParam("EngineVersion", "16.3")
|
||||
.formParam("MasterUsername", "admin")
|
||||
.formParam("MasterUserPassword", "password123")
|
||||
.formParam("DBName", "appdb")
|
||||
.formParam("DBInstanceClass", "db.t3.medium")
|
||||
.formParam("AllocatedStorage", "40")
|
||||
.when().post("/").then().statusCode(200)
|
||||
createInstance(SOURCE, "postgres", "16.3", "password123").statusCode(200)
|
||||
.body(containsString("<ReadReplicaDBInstanceIdentifiers></ReadReplicaDBInstanceIdentifiers>"))
|
||||
.body(not(containsString("<StatusInfos>")));
|
||||
|
||||
@@ -169,6 +177,40 @@ class RdsReadReplicaIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Order(6)
|
||||
void createReadReplicaAcceptsAMysqlSourceAndRefusesSqlServer() {
|
||||
createInstance("replica-test-mysql", "mysql", "8.0.36", "password123").statusCode(200);
|
||||
|
||||
query("CreateDBInstanceReadReplica")
|
||||
.formParam("DBInstanceIdentifier", "replica-test-mysql-reader")
|
||||
.formParam("SourceDBInstanceIdentifier", "replica-test-mysql")
|
||||
.when().post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<Engine>mysql</Engine>"))
|
||||
.body(containsString("<ReadReplicaSourceDBInstanceIdentifier>replica-test-mysql"
|
||||
+ "</ReadReplicaSourceDBInstanceIdentifier>"));
|
||||
|
||||
createInstance("replica-test-sqlserver", "sqlserver-se", "15.00", "Password123!").statusCode(200);
|
||||
|
||||
query("CreateDBInstanceReadReplica")
|
||||
.formParam("DBInstanceIdentifier", "replica-test-sqlserver-reader")
|
||||
.formParam("SourceDBInstanceIdentifier", "replica-test-sqlserver")
|
||||
.when().post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body(containsString("<Code>InvalidDBInstanceState</Code>"))
|
||||
.body(containsString("not supported for engine SQLSERVER"));
|
||||
|
||||
for (String id : new String[]{"replica-test-mysql-reader", "replica-test-mysql",
|
||||
"replica-test-sqlserver"}) {
|
||||
query("DeleteDBInstance").formParam("DBInstanceIdentifier", id)
|
||||
.formParam("SkipFinalSnapshot", "true")
|
||||
.when().post("/").then().statusCode(200);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(7)
|
||||
void cleanUp() {
|
||||
query("DeleteDBInstance").formParam("DBInstanceIdentifier", REPLICA)
|
||||
.when().post("/").then().statusCode(200);
|
||||
|
||||
@@ -12066,7 +12066,7 @@ class RdsServiceTest {
|
||||
"db.t3.micro", 20, false, null, null, null, null, false, false, null,
|
||||
Map.of(), List.of(), null, null, true,
|
||||
new DbInstanceSettings(null, null, 0, null, null, null));
|
||||
rdsService.createDbInstance("maria", "mariadb", "11.2", "admin", "password", "appdb",
|
||||
rdsService.createDbInstance("mssql", "sqlserver-se", "15.00", "admin", "Password123!", null,
|
||||
"db.t3.micro", 20, false, null, null, null, null, false);
|
||||
|
||||
AwsException noSource = assertThrows(AwsException.class, () ->
|
||||
@@ -12083,8 +12083,9 @@ class RdsServiceTest {
|
||||
assertTrue(backupsOff.getMessage().contains("Automated backups are not enabled"));
|
||||
|
||||
AwsException otherEngine = assertThrows(AwsException.class, () ->
|
||||
rdsService.createDbInstanceReadReplica(replicaRequest("r", "maria"), null));
|
||||
rdsService.createDbInstanceReadReplica(replicaRequest("r", "mssql"), null));
|
||||
assertEquals("InvalidDBInstanceState", otherEngine.getErrorCode());
|
||||
assertTrue(otherEngine.getMessage().contains("not supported for engine SQLSERVER"));
|
||||
|
||||
AwsException replicaMode = assertThrows(AwsException.class, () ->
|
||||
rdsService.createDbInstanceReadReplica(new ReadReplicaRequest("r", "primary",
|
||||
@@ -12112,6 +12113,35 @@ class RdsServiceTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void createReadReplicaCopiesMysqlAndMariadbSourcesWithTheirOwnDumpTools() {
|
||||
when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()))
|
||||
.thenAnswer(invocation -> new RdsContainerHandle(
|
||||
"cont-" + invocation.getArgument(1), invocation.getArgument(1), "localhost", 3306));
|
||||
rdsService.createDbInstance("my", "mysql", "8.0.36", "admin", "secret", "appdb",
|
||||
"db.t3.micro", 20, false, null, null, null, null, false);
|
||||
rdsService.createDbInstance("maria", "mariadb", "11.2", "admin", "secret", "appdb",
|
||||
"db.t3.micro", 20, false, null, null, null, null, false);
|
||||
when(containerManager.createMysqlSnapshot(DatabaseEngine.MYSQL, "cont-my", "admin", "secret"))
|
||||
.thenReturn("MYDUMP");
|
||||
when(containerManager.createMysqlSnapshot(DatabaseEngine.MARIADB, "cont-maria", "admin", "secret"))
|
||||
.thenReturn("MARIADUMP");
|
||||
|
||||
DbInstance my = rdsService.createDbInstanceReadReplica(replicaRequest("my-replica", "my"), null);
|
||||
DbInstance maria = rdsService.createDbInstanceReadReplica(replicaRequest("maria-replica", "maria"), null);
|
||||
|
||||
assertEquals(DatabaseEngine.MYSQL, my.getEngine());
|
||||
assertEquals(DbInstanceStatus.AVAILABLE, my.getStatus());
|
||||
assertEquals("my", rdsService.getDbInstance("my-replica").getReadReplicaSourceDbInstanceIdentifier());
|
||||
assertEquals(List.of("my-replica"), rdsService.getDbInstance("my").getReadReplicaDbInstanceIdentifiers());
|
||||
assertEquals(DatabaseEngine.MARIADB, maria.getEngine());
|
||||
verify(containerManager).restoreMysqlSnapshot(
|
||||
DatabaseEngine.MYSQL, "cont-my-replica", "admin", "secret", "MYDUMP");
|
||||
verify(containerManager).restoreMysqlSnapshot(
|
||||
DatabaseEngine.MARIADB, "cont-maria-replica", "admin", "secret", "MARIADUMP");
|
||||
verify(containerManager, never()).createPostgresSnapshot(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createReadReplicaRollsBackWhenTheCopyFails() {
|
||||
createPostgresSource("primary");
|
||||
|
||||
@@ -29,10 +29,14 @@ import org.mockito.InOrder;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.PosixFilePermission;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
@@ -189,7 +193,7 @@ class RdsArchiveRetryTest {
|
||||
|
||||
assertTrue(failure.getMessage().contains("psql restore failed with exit code 1: invalid dump"));
|
||||
assertEquals(1, uploads.commands.size());
|
||||
assertEquals(List.of(List.of("sh", "/tmp/restore.sh", "admin")), commands);
|
||||
assertEquals(List.of(List.of("sh", "/tmp/restore.sh", "admin"), List.of("rm", "-f", "/tmp/dump.sql")), commands);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -204,22 +208,166 @@ class RdsArchiveRetryTest {
|
||||
|
||||
assertSame(transportFailure, failure);
|
||||
assertEquals(1, uploads.commands.size());
|
||||
assertEquals(List.of(List.of("sh", "/tmp/restore.sh", "admin")), commands);
|
||||
assertEquals(List.of(List.of("sh", "/tmp/restore.sh", "admin"), List.of("rm", "-f", "/tmp/dump.sql")), commands);
|
||||
}
|
||||
|
||||
@Test
|
||||
void mysqlDumpWaitsForTheServerToAcceptTheMasterUser() {
|
||||
DockerArchiveUploadFixture uploads = failingUploads(0, 0);
|
||||
List<List<String>> envs = new ArrayList<>();
|
||||
List<List<String>> commands = ContainerExecStubs.completeEveryExec(docker, CONTAINER,
|
||||
List.of(2L, 2L, 0L), "-- dump", "");
|
||||
List.of(2L, 2L, 0L), "-- dump", "", envs);
|
||||
|
||||
String dump = manager.createMysqlSnapshot(DatabaseEngine.MYSQL, CONTAINER, "admin", "secret");
|
||||
|
||||
assertEquals("-- dump", dump);
|
||||
assertEquals(1, uploads.commands.size());
|
||||
assertEquals(3, commands.size());
|
||||
assertEquals(List.of("env", "MYSQL_PWD=secret", "sh", "/tmp/floci-mysql-dump.sh", "mysql", "mysqldump",
|
||||
"admin"), commands.getFirst().subList(0, 7));
|
||||
assertEquals(List.of("sh", "/tmp/floci-mysql-dump.sh", "mysql", "mysqldump", "admin"),
|
||||
commands.getFirst().subList(0, 5));
|
||||
// The password reaches the exec as environment, never as a word of the command Docker records.
|
||||
assertEquals(List.of(List.of("MYSQL_PWD=secret"), List.of("MYSQL_PWD=secret"), List.of("MYSQL_PWD=secret")),
|
||||
envs);
|
||||
assertTrue(commands.stream().flatMap(List::stream).noneMatch(word -> word.contains("secret")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mysqlRestorePassesThePasswordAsEnvironmentAndUploadsTheDumpUnreadableByTheServer() throws IOException {
|
||||
DockerArchiveUploadFixture uploads = failingUploads(0, 0);
|
||||
List<List<String>> envs = new ArrayList<>();
|
||||
List<List<String>> commands = ContainerExecStubs.completeEveryExec(docker, CONTAINER, List.of(0L), "", "",
|
||||
envs);
|
||||
|
||||
manager.restoreMysqlSnapshot(DatabaseEngine.MARIADB, CONTAINER, "admin", "secret", "-- dump");
|
||||
|
||||
assertEquals(List.of(List.of("sh", "/tmp/restore.sh", "mariadb", "admin")), commands);
|
||||
assertEquals(List.of(List.of("MYSQL_PWD=secret")), envs);
|
||||
try (TarArchiveInputStream tar = new TarArchiveInputStream(
|
||||
new ByteArrayInputStream(uploads.completed.getFirst()))) {
|
||||
TarArchiveEntry dump = tar.getNextEntry();
|
||||
assertEquals("dump.sql", dump.getName());
|
||||
// mysqld runs as an unprivileged user and must not be able to LOAD_FILE the dump.
|
||||
assertEquals(0600, dump.getMode());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void mysqlDumpScriptKeepsASchemaNameWithANewlineAsOneArgument(@TempDir Path dir) throws Exception {
|
||||
// Stand-ins for the client and the dump tool. The client answers the schema query the way
|
||||
// mysql -B does without -r: a newline in a name arrives as the two characters \n.
|
||||
Path client = dir.resolve("client");
|
||||
Files.writeString(client, """
|
||||
#!/bin/sh
|
||||
for last; do :; done
|
||||
case "$last" in
|
||||
*information_schema.schemata*) printf 'a\\\\nb\\nplain\\n' ;;
|
||||
*CONCAT*QUOTE*) printf '\\047u\\\\nser\\047@\\047%%\\047\\n' ;;
|
||||
*QUOTE*) printf '\\047r\\\\nGRANT ole\\047\\n' ;;
|
||||
*SHOW*GRANTS*) n=$(printf '%s\\n' "${last#SHOW GRANTS FOR }" | awk 'NR>1{printf "\\\\n"} {printf "%s", $0}')
|
||||
printf 'GRANT USAGE ON *.* TO %s\\nREVOKE SELECT ON mysql.* FROM %s\\nSET DEFAULT ROLE r FOR %s\\n' "$n" "$n" "$n" ;;
|
||||
*SHOW*) printf '%s\\n' "$last" ;;
|
||||
esac
|
||||
""");
|
||||
Path dump = dir.resolve("dump");
|
||||
Files.writeString(dump, "#!/bin/sh\nfor a; do case \"$a\" in -*) ;; *) printf '<%s>' \"$a\" ;; esac; done\n");
|
||||
Path script = dir.resolve("dump.sh");
|
||||
Files.writeString(script, RdsContainerManager.mysqlDumpScript());
|
||||
for (Path p : List.of(client, dump)) {
|
||||
assertTrue(p.toFile().setExecutable(true));
|
||||
}
|
||||
|
||||
Process process = new ProcessBuilder("sh", script.toString(), client.toString(), dump.toString(), "admin",
|
||||
"", "", "FALSE").redirectErrorStream(true).start();
|
||||
String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
|
||||
|
||||
assertEquals(0, process.waitFor(), output);
|
||||
assertTrue(output.startsWith("<a\nb><plain>"), output);
|
||||
// Roles, accounts and grantees are decoded too: each statement carries the real newline.
|
||||
assertTrue(output.contains("CREATE ROLE IF NOT EXISTS 'r\nGRANT ole';"), output);
|
||||
assertTrue(output.contains("SHOW CREATE USER 'u\nser'@'%'"), output);
|
||||
// Each GRANT ends with one ';' after the whole name, even when a continuation line starts with a keyword.
|
||||
assertTrue(output.contains("GRANT USAGE ON *.* TO 'r\nGRANT ole';\n"), output);
|
||||
assertTrue(output.contains("GRANT USAGE ON *.* TO 'u\nser'@'%';\n"), output);
|
||||
// MariaDB's SET DEFAULT ROLE and MySQL's partial REVOKE are statements of their own, not GRANT tails.
|
||||
assertTrue(output.contains("GRANT USAGE ON *.* TO 'u\nser'@'%';\nREVOKE SELECT ON mysql.* FROM 'u\nser'@'%';\n"
|
||||
+ "SET DEFAULT ROLE r FOR 'u\nser'@'%';\n"), output);
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoreRemovesTheDumpEvenWhenItsExecDiesBeforeTheScriptCanClean() {
|
||||
failingUploads(0, 0);
|
||||
List<List<String>> commands = ContainerExecStubs.completeEveryExec(docker, CONTAINER, 0, "", "");
|
||||
RuntimeException killed = new RuntimeException(new IOException("exec killed"));
|
||||
when(docker.execStartCmd(anyString())).thenThrow(killed);
|
||||
|
||||
RuntimeException failure = assertThrows(RuntimeException.class,
|
||||
() -> manager.restoreMysqlSnapshot(DatabaseEngine.MYSQL, CONTAINER, "admin", "secret", "-- dump"));
|
||||
|
||||
assertSame(killed, failure);
|
||||
assertEquals(List.of("rm", "-f", "/tmp/dump.sql"), commands.getLast());
|
||||
}
|
||||
|
||||
/** Runs a restore script on a stub client or psql; returns the exit code, and whether the dump is left. */
|
||||
private record Restore(int exit, boolean dumpLeft, String mode) {
|
||||
}
|
||||
|
||||
private Restore runRestoreScript(Path dir, String script, String mode, boolean takesClient) throws Exception {
|
||||
Path dump = dir.resolve("dump.sql");
|
||||
Files.writeString(dump, "SELECT 1;");
|
||||
Path stub = dir.resolve("stub");
|
||||
// down: the server does not answer; fail: it answers but the replay fails; up: all well.
|
||||
Files.writeString(stub, """
|
||||
#!/bin/sh
|
||||
case "$*" in
|
||||
*-f*) [ "$MODE" = down ] && exit 2; [ "$MODE" = fail ] && exit 1; exit 0 ;;
|
||||
*-e*) [ "$MODE" = down ] && exit 1; exit 0 ;;
|
||||
esac
|
||||
[ "$MODE" = down ] && exit 2
|
||||
[ "$MODE" = fail ] && exit 1
|
||||
exit 0
|
||||
""");
|
||||
Path psql = dir.resolve("psql");
|
||||
Files.copy(stub, psql);
|
||||
for (Path p : List.of(stub, psql)) {
|
||||
assertTrue(p.toFile().setExecutable(true));
|
||||
}
|
||||
Path file = dir.resolve("restore.sh");
|
||||
Files.writeString(file, script.replace("/tmp/dump", dir + "/dump"));
|
||||
List<String> command = new ArrayList<>(List.of("sh", file.toString()));
|
||||
if (takesClient) {
|
||||
command.add(stub.toString());
|
||||
}
|
||||
command.add("admin");
|
||||
ProcessBuilder pb = new ProcessBuilder(command).redirectErrorStream(true);
|
||||
pb.environment().put("MODE", mode);
|
||||
pb.environment().put("PATH", dir + ":" + System.getenv("PATH"));
|
||||
Process process = pb.start();
|
||||
process.getInputStream().readAllBytes();
|
||||
return new Restore(process.waitFor(), Files.exists(dump), mode);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"up,0,false", "fail,1,false", "down,2,true"})
|
||||
void mysqlRestoreScriptRemovesTheDumpUnlessTheServerIsStillDown(String mode, int exit, boolean left,
|
||||
@TempDir Path dir) throws Exception {
|
||||
Restore result = runRestoreScript(dir, RdsContainerManager.mysqlRestoreScript(), mode, true);
|
||||
|
||||
assertEquals(exit, result.exit());
|
||||
assertEquals(left, result.dumpLeft());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"up,0,false", "fail,1,false", "down,2,true"})
|
||||
void postgresRestoreScriptRemovesTheDumpUnlessTheServerIsStillDownAndKeepsItPrivate(String mode, int exit,
|
||||
boolean left, @TempDir Path dir) throws Exception {
|
||||
Restore result = runRestoreScript(dir, RdsContainerManager.postgresRestoreScript(), mode, false);
|
||||
|
||||
assertEquals(exit, result.exit());
|
||||
assertEquals(left, result.dumpLeft());
|
||||
if (left) {
|
||||
assertEquals(Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE),
|
||||
Files.getPosixFilePermissions(dir.resolve("dump.sql")));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -238,7 +386,7 @@ class RdsArchiveRetryTest {
|
||||
private static void assertTarEntry(TarArchiveInputStream tar, String name, String content) throws IOException {
|
||||
TarArchiveEntry entry = tar.getNextEntry();
|
||||
assertEquals(name, entry.getName());
|
||||
assertEquals(0755, entry.getMode());
|
||||
assertEquals(name.endsWith(".sql") ? 0600 : 0755, entry.getMode());
|
||||
assertArrayEquals(content.getBytes(StandardCharsets.UTF_8), tar.readAllBytes());
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user