mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(rds): CreateDBSnapshot and RestoreDBInstanceFromDBSnapshot for MySQL and MariaDB (#7747)
* feat(rds): CreateDBSnapshot and RestoreDBInstanceFromDBSnapshot for MySQL and MariaDB A snapshot of a MySQL or MariaDB instance is a mysqldump (mariadb-dump) of every user schema, with routines, triggers and events, taken as the master user, followed by every non-system account recreated from SHOW CREATE USER and SHOW GRANTS. Restoring replays it into the new instance once its server accepts the master user over TCP, so the copy is never loaded into the image's initializing server. SQL Server is still refused. * fix(rds): copy roles and names with spaces in MySQL and MariaDB snapshots Roles are now part of a MySQL or MariaDB snapshot: MariaDB roles are recreated with CREATE ROLE, and MySQL accounts used as roles are created first, since SHOW CREATE USER names an account's default roles. Every role and account exists before any grant is replayed, so a user granted a role restores. Schema and account names are read one per line, so names with spaces stay one argument. The integration test retries through one Awaitility helper and covers a role and a schema name with a space. * fix(rds): wait for the server before a MySQL dump, and share the snapshot script runner CreateDBSnapshot straight after CreateDBInstance failed: Floci reports the instance available while the image still initializes it on a server that does not listen on TCP. The dump script now exits 2 until the master user can log in over TCP and is run again, as the restore is; past that probe any failure, mysqldump's own exit 2 included, exits 1 so it is not retried. The PostgreSQL restore, the MySQL dump and the MySQL restore now share one runner for the upload, the exit-2 retry and the error handling.
This commit is contained in:
1 parent
6be18ea1ee
commit
46f0d91716
6 files changed
+439
-29
No files matched your search
+20
-5
@@ -36,7 +36,7 @@ mark those members `failed` until a successful retry.
|
||||
|
||||
Floci manages real PostgreSQL, MySQL, MariaDB, and SQL Server Docker containers and proxies TCP connections to them, including IAM authentication support where the protocol supports it. SQL Server uses a transparent TCP relay for its native TDS protocol.
|
||||
|
||||
MySQL and MariaDB master-grant script uploads, and PostgreSQL snapshot restore archive uploads,
|
||||
MySQL and MariaDB master-grant script uploads, and snapshot dump script and restore archive uploads,
|
||||
retry transient Docker connection failures up to six attempts with exponential backoff starting
|
||||
at 500 ms. Every attempt sends a fresh archive. Containers start, or snapshot restore commands
|
||||
run, only after the upload succeeds. A permanent Docker error or exhausted retries follows the
|
||||
@@ -212,6 +212,20 @@ checked against the instance's other window. Modifications apply immediately —
|
||||
`arn:aws:rds:<region>:<account>:cluster-snapshot:<name>`. RDS reserved instances aren't
|
||||
modeled (there's no reserved-instance API), so tagging doesn't apply to them.
|
||||
|
||||
!!! note "DB snapshot engines"
|
||||
|
||||
`CreateDBSnapshot` takes a logical copy of a PostgreSQL, MySQL or MariaDB instance, and
|
||||
`RestoreDBInstanceFromDBSnapshot` loads it into the new instance. PostgreSQL uses `pg_dumpall`.
|
||||
MySQL and MariaDB use `mysqldump` (`mariadb-dump`) of every user schema, with routines,
|
||||
triggers and events, run as the master user, followed by every account other than `root` and
|
||||
the image's system accounts, recreated from `SHOW CREATE USER` and `SHOW GRANTS` so they keep
|
||||
their passwords. Roles are copied too, and created before any grant names them. The `mysql`
|
||||
system schema itself is not copied. The restore waits until the new server accepts the master
|
||||
user over TCP before loading the copy. SQL Server instances are refused with
|
||||
`InvalidDBInstanceState`. The dump runs in one transaction, so InnoDB tables are copied as of
|
||||
one moment; as with `mysqldump --single-transaction` elsewhere, a MyISAM or other
|
||||
non-transactional table written to during the snapshot may not be.
|
||||
|
||||
## Cluster parameter groups
|
||||
|
||||
`DescribeDBClusterParameterGroups` includes `DBClusterParameterGroupArn` for managed `default.*`
|
||||
@@ -656,7 +670,7 @@ The replica's database is initialised from a `pg_dumpall` of the source taken wh
|
||||
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`, as `CreateDBSnapshot` refuses them. A source with automated backups
|
||||
with `InvalidDBInstanceState`, although `CreateDBSnapshot` accepts them. 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`
|
||||
@@ -851,8 +865,8 @@ they are added with `CreateDBInstance`, as on AWS.
|
||||
Floci keeps no transaction log, so it cannot rebuild a database as it was at an earlier time. The
|
||||
target is seeded from a `pg_dumpall` of the source taken when the request arrives, the mechanism read
|
||||
replicas use, so the restored data is the source's latest state whatever time in the window is
|
||||
asked for; this is also why `LatestRestorableTime` is always the current time. As with
|
||||
`CreateDBSnapshot`, only PostgreSQL sources are accepted.
|
||||
asked for; this is also why `LatestRestorableTime` is always the current time. Only PostgreSQL
|
||||
sources are accepted.
|
||||
|
||||
## Automated backups
|
||||
|
||||
@@ -941,7 +955,8 @@ What differs from RDS:
|
||||
- The IAM role is not assumed and the KMS key encrypts nothing: both are recorded and reported back
|
||||
as given. The bucket must exist, or the request fails with `InvalidS3BucketFault`. A bucket in
|
||||
another region than the snapshot's is accepted and the task then ends `FAILED`, as on RDS.
|
||||
- Only PostgreSQL snapshots can be exported, since Floci's snapshots hold PostgreSQL data only.
|
||||
- Only PostgreSQL snapshots can be exported: the export reads a `pg_dumpall`, and a MySQL or
|
||||
MariaDB snapshot holds a `mysqldump` instead.
|
||||
Any other source is refused with `InvalidExportSourceState`, and so is a snapshot that is not
|
||||
`available`.
|
||||
- `SourceArn` must name a snapshot: exporting a live DB cluster (`SourceType` `CLUSTER`) is not
|
||||
|
||||
@@ -1190,7 +1190,7 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
|
||||
DbInstance instance = getDbInstance(instanceId, effectiveRegion);
|
||||
|
||||
if (instance.getEngine() != DatabaseEngine.POSTGRES) {
|
||||
if (instance.getEngine() == DatabaseEngine.SQLSERVER) {
|
||||
throw new AwsException("InvalidDBInstanceState", "Operation CreateDBSnapshot is not supported for engine " + instance.getEngine() + ".", 400);
|
||||
}
|
||||
|
||||
@@ -1211,7 +1211,10 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
String sqlDump = "";
|
||||
if (!config.services().rds().mock()) {
|
||||
try {
|
||||
sqlDump = containerManager.createPostgresSnapshot(instance.getContainerId(), instance.getMasterUsername());
|
||||
sqlDump = instance.getEngine() == DatabaseEngine.POSTGRES
|
||||
? containerManager.createPostgresSnapshot(instance.getContainerId(), instance.getMasterUsername())
|
||||
: containerManager.createMysqlSnapshot(instance.getEngine(), instance.getContainerId(),
|
||||
instance.getMasterUsername(), instance.getMasterPassword());
|
||||
} catch (Exception e) {
|
||||
LOG.warnv(e, "Failed to create snapshot {0} of DB instance {1}", snapshotId, instanceId);
|
||||
throw new AwsException("InvalidDBInstanceState", "Failed to create snapshot: " + e.getMessage(), 400);
|
||||
@@ -1504,7 +1507,12 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
|
||||
if (!config.services().rds().mock()) {
|
||||
try {
|
||||
containerManager.restorePostgresSnapshot(instance.getContainerId(), instance.getMasterUsername(), sqlDump);
|
||||
if (instance.getEngine() == DatabaseEngine.POSTGRES) {
|
||||
containerManager.restorePostgresSnapshot(instance.getContainerId(), instance.getMasterUsername(), sqlDump);
|
||||
} else {
|
||||
containerManager.restoreMysqlSnapshot(instance.getEngine(), instance.getContainerId(),
|
||||
instance.getMasterUsername(), instance.getMasterPassword(), sqlDump);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
deleteDbInstance(instanceId, effectiveRegion);
|
||||
|
||||
@@ -37,6 +37,7 @@ import java.nio.file.Path;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
@@ -1211,31 +1212,39 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
|
||||
|
||||
public void restorePostgresSnapshot(String containerId, String masterUsername, String sqlDump) {
|
||||
String effectiveUser = (masterUsername != null && !masterUsername.isBlank()) ? masterUsername : "postgres";
|
||||
Map<String, String> files = new LinkedHashMap<>();
|
||||
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");
|
||||
}
|
||||
|
||||
/**
|
||||
* Uploads {@code files} into the container's {@code /tmp} and runs {@code cmd}, again every second
|
||||
* while it exits 2, which the snapshot scripts answer while the server does not accept connections
|
||||
* yet: a just-created MySQL or MariaDB container is still initializing its data directory on a
|
||||
* server that does not listen on TCP, and psql exits 2 when it cannot connect. Returns the
|
||||
* command's output; any other failure, or a server still not answering after {@code attempts}
|
||||
* 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) {
|
||||
try (Lease _ = holdContainer(containerId)) {
|
||||
String restoreScript = postgresRestoreScript();
|
||||
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
try (TarArchiveOutputStream tar = new TarArchiveOutputStream(bos)) {
|
||||
tar.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
|
||||
|
||||
addTarEntry(tar, "dump.sql", sqlDump);
|
||||
addTarEntry(tar, "restore.sh", restoreScript);
|
||||
for (Map.Entry<String, String> file : files.entrySet()) {
|
||||
addTarEntry(tar, file.getKey(), file.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
byte[] archive = bos.toByteArray();
|
||||
RetryingTarCopier.copyStreamed(lifecycleManager.getDockerClient(), containerId,
|
||||
"/tmp", "postgres-restore", out -> out.write(archive),
|
||||
"/tmp", uploadName, out -> out.write(archive),
|
||||
RetryingTarCopier.DEFAULT_MAX_ATTEMPTS, uploadBackoffMillis);
|
||||
|
||||
String[] cmd = { "sh", "/tmp/restore.sh", effectiveUser };
|
||||
|
||||
ContainerExec.Result result = null;
|
||||
for (int i = 0; i < 60; i++) {
|
||||
result = execInContainer(containerId, cmd, 120);
|
||||
if (result.exitCode() == 0) {
|
||||
break;
|
||||
}
|
||||
for (int i = 0; i < attempts; i++) {
|
||||
result = execInContainer(containerId, cmd, timeoutSeconds);
|
||||
if (result.exitCode() != 2) {
|
||||
break;
|
||||
}
|
||||
@@ -1243,22 +1252,146 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException ie) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new RuntimeException("Interrupted while restoring postgres snapshot", ie);
|
||||
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("psql restore failed with exit code "
|
||||
throw new RuntimeException(operation + " failed with exit code "
|
||||
+ (result != null ? result.exitCode() : -1) + ": " + errMsg);
|
||||
}
|
||||
return result.stdout();
|
||||
} catch (RuntimeException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to restore postgres snapshot", e);
|
||||
throw new RuntimeException("Failed to run " + operation, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* but root and the image's own system accounts, recreated from {@code SHOW CREATE USER} and
|
||||
* {@code SHOW GRANTS}. The {@code mysql} system schema itself is not copied, since MySQL 8 cannot
|
||||
* load one into a fresh server. It runs as the master user, whom the instance's init script
|
||||
* granted ALL on *.*, once the server accepts that user over TCP: Floci reports an instance
|
||||
* {@code available} while the image is still initializing it.
|
||||
*/
|
||||
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),
|
||||
tools.dumpFlags(), tools.accountClause(), tools.roleFilter()};
|
||||
return runSnapshotScript(containerId, "mysql-dump", Map.of("floci-mysql-dump.sh", mysqlDumpScript()),
|
||||
cmd, 120, 300, tools.dump());
|
||||
}
|
||||
|
||||
/**
|
||||
* Replays a {@link #createMysqlSnapshot} copy into a just-created MySQL or MariaDB instance, once
|
||||
* its server accepts the master user over TCP rather than into the initializing server the
|
||||
* image is about to stop.
|
||||
*/
|
||||
public void restoreMysqlSnapshot(DatabaseEngine engine, String containerId,
|
||||
String masterUsername, String masterPassword, String sqlDump) {
|
||||
MysqlTools tools = MysqlTools.of(engine);
|
||||
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");
|
||||
}
|
||||
|
||||
/**
|
||||
* The client binaries and dump flags of an engine, and the end of its account query. MariaDB
|
||||
* images ship only the {@code mariadb-*} names, and list roles in {@code mysql.user} next to
|
||||
* accounts, which {@code SHOW CREATE USER} refuses, so they are recreated with {@code CREATE ROLE}.
|
||||
* A MySQL role is an account, and {@code SHOW CREATE USER} names an account's default roles, so
|
||||
* the accounts used as roles are created first. MySQL's dump leaves out the GTID state, which a
|
||||
* fresh server would refuse to load.
|
||||
*/
|
||||
record MysqlTools(String client, String dump, String dumpFlags, String accountClause, String roleFilter) {
|
||||
static MysqlTools of(DatabaseEngine engine) {
|
||||
return engine == DatabaseEngine.MARIADB
|
||||
? new MysqlTools("mariadb", "mariadb-dump", "", "AND is_role = 'N'", "is_role = 'Y'")
|
||||
: new MysqlTools("mysql", "mysqldump", "--set-gtid-purged=OFF",
|
||||
"ORDER BY (user, host) IN (SELECT FROM_USER, FROM_HOST FROM mysql.role_edges"
|
||||
+ " UNION SELECT DEFAULT_ROLE_USER, DEFAULT_ROLE_HOST FROM mysql.default_roles) DESC",
|
||||
"FALSE");
|
||||
}
|
||||
}
|
||||
|
||||
private static String mysqlUser(String masterUsername) {
|
||||
return masterUsername != null && !masterUsername.isBlank() ? masterUsername : "root";
|
||||
}
|
||||
|
||||
static String mysqlDumpScript() {
|
||||
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.
|
||||
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"; }
|
||||
# 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 \\
|
||||
('mysql','sys','performance_schema','information_schema')")
|
||||
set --
|
||||
while IFS= read -r db; do
|
||||
if [ -n "$db" ]; then set -- "$@" "$db"; fi
|
||||
done <<EOF
|
||||
$DBS
|
||||
EOF
|
||||
if [ $# -gt 0 ]; then
|
||||
# shellcheck disable=SC2086
|
||||
"$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 \\
|
||||
('','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
|
||||
done <<EOF
|
||||
$ROLES
|
||||
EOF
|
||||
while IFS= read -r acct; do
|
||||
if [ -n "$acct" ]; then
|
||||
# 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")
|
||||
echo "$stmt;" | sed 's/^CREATE USER /CREATE USER IF NOT EXISTS /'
|
||||
fi
|
||||
done <<EOF
|
||||
$ACCOUNTS
|
||||
EOF
|
||||
while IFS= read -r grantee; do
|
||||
if [ -n "$grantee" ]; then SQL "SHOW GRANTS FOR $grantee" | sed 's/$/;/'; fi
|
||||
done <<EOF
|
||||
$ROLES
|
||||
$ACCOUNTS
|
||||
EOF
|
||||
echo "FLUSH PRIVILEGES;"
|
||||
""";
|
||||
}
|
||||
|
||||
static String mysqlRestoreScript() {
|
||||
return """
|
||||
#!/bin/sh
|
||||
# usage: restore.sh <client> <user>; the password arrives in MYSQL_PWD.
|
||||
C="$1"; U="$2"
|
||||
"$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
|
||||
""";
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives a restored database the name a point in time restore asked for. {@code from} is the
|
||||
* database the source's dump brought over: its DBName, or the master user's name when it had
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
package io.floci.aws.services.rds;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Tag;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.time.Duration;
|
||||
import java.util.Properties;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static io.floci.aws.testing.RdsRequests.assumeDocker;
|
||||
import static io.floci.aws.testing.RdsRequests.deleteInstance;
|
||||
import static io.floci.aws.testing.RdsRequests.rds;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* A MySQL or MariaDB instance's snapshot carries its schemas, its roles and its accounts: an
|
||||
* instance restored from it holds the same rows, including a schema whose name has a space, and an
|
||||
* account created on the source logs in to the restored instance with its own password and reads
|
||||
* through the role it was granted. A snapshot requested straight after CreateDBInstance waits for
|
||||
* the image to finish initializing the instance. Skipped without Docker.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@Tag("docker")
|
||||
class RdsMysqlSnapshotDockerIntegrationTest {
|
||||
|
||||
private static final String MASTER_USER = "admin";
|
||||
private static final String MASTER_PASSWORD = "Passw0rd12345";
|
||||
|
||||
@BeforeEach
|
||||
void checkDocker() throws InterruptedException {
|
||||
assumeDocker();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource(delimiter = '|', quoteCharacter = '"', value = {
|
||||
"mysql | 8.0 | SET DEFAULT ROLE 'readers' TO 'reader'@'%'",
|
||||
"mariadb | 10.11 | SET DEFAULT ROLE 'readers' FOR 'reader'@'%'"})
|
||||
void restoredInstanceHoldsTheSourcesRowsRolesAndAccounts(String engine, String version, String defaultRole) {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String sourceId = engine + "-snap-src-" + suffix;
|
||||
String restoredId = engine + "-snap-dst-" + suffix;
|
||||
String snapshotId = engine + "-snap-" + suffix;
|
||||
String earlySnapshotId = engine + "-snap-early-" + suffix;
|
||||
try {
|
||||
int sourcePort = createInstance(sourceId, engine, version);
|
||||
rds("CreateDBSnapshot")
|
||||
.formParam("DBInstanceIdentifier", sourceId)
|
||||
.formParam("DBSnapshotIdentifier", earlySnapshotId)
|
||||
.when().post("/").then().statusCode(200);
|
||||
execute(sourcePort, MASTER_USER, MASTER_PASSWORD,
|
||||
"CREATE TABLE appdb.notes (id INT PRIMARY KEY, body VARCHAR(32))",
|
||||
"INSERT INTO appdb.notes VALUES (1, 'kept')",
|
||||
"CREATE DATABASE `sales data`",
|
||||
"CREATE TABLE `sales data`.totals (amount INT)",
|
||||
"INSERT INTO `sales data`.totals VALUES (7)",
|
||||
"CREATE ROLE 'readers'",
|
||||
"GRANT SELECT ON appdb.* TO 'readers'",
|
||||
"CREATE USER 'reader'@'%' IDENTIFIED BY 'R3aderPass'",
|
||||
"GRANT 'readers' TO 'reader'@'%'",
|
||||
defaultRole);
|
||||
|
||||
rds("CreateDBSnapshot")
|
||||
.formParam("DBInstanceIdentifier", sourceId)
|
||||
.formParam("DBSnapshotIdentifier", snapshotId)
|
||||
.when().post("/").then().statusCode(200);
|
||||
int restoredPort = rds("RestoreDBInstanceFromDBSnapshot")
|
||||
.formParam("DBInstanceIdentifier", restoredId)
|
||||
.formParam("DBSnapshotIdentifier", snapshotId)
|
||||
.when().post("/").then().statusCode(200).extract().xmlPath()
|
||||
.getInt("RestoreDBInstanceFromDBSnapshotResponse.RestoreDBInstanceFromDBSnapshotResult"
|
||||
+ ".DBInstance.Endpoint.Port");
|
||||
|
||||
assertEquals("kept", query(restoredPort, MASTER_USER, MASTER_PASSWORD,
|
||||
"SELECT body FROM appdb.notes WHERE id = 1"));
|
||||
assertEquals("7", query(restoredPort, MASTER_USER, MASTER_PASSWORD,
|
||||
"SELECT amount FROM `sales data`.totals"));
|
||||
assertEquals("1", query(restoredPort, "reader", "R3aderPass", "SELECT COUNT(*) FROM appdb.notes"));
|
||||
} finally {
|
||||
deleteInstance(restoredId);
|
||||
deleteInstance(sourceId);
|
||||
for (String id : new String[] {snapshotId, earlySnapshotId}) {
|
||||
rds("DeleteDBSnapshot")
|
||||
.formParam("DBSnapshotIdentifier", id)
|
||||
.when().post("/");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static int createInstance(String instanceId, String engine, String version) {
|
||||
return rds("CreateDBInstance")
|
||||
.formParam("DBInstanceIdentifier", instanceId)
|
||||
.formParam("Engine", engine)
|
||||
.formParam("EngineVersion", version)
|
||||
.formParam("DBInstanceClass", "db.t3.micro")
|
||||
.formParam("AllocatedStorage", "20")
|
||||
.formParam("MasterUsername", MASTER_USER)
|
||||
.formParam("MasterUserPassword", MASTER_PASSWORD)
|
||||
.formParam("DBName", "appdb")
|
||||
.when().post("/").then().statusCode(200).extract().xmlPath()
|
||||
.getInt("CreateDBInstanceResponse.CreateDBInstanceResult.DBInstance.Endpoint.Port");
|
||||
}
|
||||
|
||||
/** Runs the statements in one connection, once the server accepts it (see {@link #whenConnected}). */
|
||||
private static void execute(int port, String user, String password, String... statements) {
|
||||
whenConnected(port, user, password, connection -> {
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
for (String sql : statements) {
|
||||
statement.execute(sql);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
/** The first column of a query's first row, once the server accepts the connection. */
|
||||
private static String query(int port, String user, String password, String sql) {
|
||||
return whenConnected(port, user, password, connection -> {
|
||||
try (Statement statement = connection.createStatement();
|
||||
ResultSet rows = statement.executeQuery(sql)) {
|
||||
rows.next();
|
||||
return rows.getString(1);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private interface SqlWork<T> {
|
||||
T run(Connection connection) throws SQLException;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs {@code work} in a new connection. Floci reports an instance before its image has
|
||||
* initialized the data directory, on a server that does not listen on TCP, so a refused
|
||||
* connection is tried again until the server it then starts answers.
|
||||
*/
|
||||
private static <T> T whenConnected(int port, String user, String password, SqlWork<T> work) {
|
||||
AtomicReference<T> result = new AtomicReference<>();
|
||||
await().atMost(Duration.ofSeconds(90)).pollInterval(Duration.ofSeconds(1))
|
||||
.ignoreExceptionsInstanceOf(SQLException.class)
|
||||
.until(() -> {
|
||||
try (Connection connection = connect(port, user, password)) {
|
||||
result.set(work.run(connection));
|
||||
return true;
|
||||
}
|
||||
});
|
||||
return result.get();
|
||||
}
|
||||
|
||||
private static Connection connect(int port, String user, String password) throws SQLException {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty("user", user);
|
||||
properties.setProperty("password", password);
|
||||
properties.setProperty("useSSL", "false");
|
||||
properties.setProperty("allowPublicKeyRetrieval", "true");
|
||||
properties.setProperty("connectTimeout", "10000");
|
||||
properties.setProperty("socketTimeout", "10000");
|
||||
return DriverManager.getConnection("jdbc:mysql://127.0.0.1:" + port + "/", properties);
|
||||
}
|
||||
}
|
||||
@@ -6639,16 +6639,75 @@ class RdsServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void createDbSnapshotThrowsForNonPostgres() {
|
||||
rdsService.createDbInstance("mydb", "mysql", "8.0",
|
||||
"admin", "password", "dbname", "db.t3.micro",
|
||||
void createDbSnapshotThrowsForSqlServer() {
|
||||
rdsService.createDbInstance("mydb", "sqlserver-se", "15.00",
|
||||
"sa", "Password123!", null, "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"));
|
||||
assertTrue(exception.getMessage().contains("CreateDBSnapshot is not supported for engine SQLSERVER"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"mysql, 8.0, MYSQL", "mariadb, 10.11, MARIADB"})
|
||||
void mysqlFamilySnapshotIsTheMasterUsersDumpAndSeedsTheRestoredInstance(String engine, String version,
|
||||
DatabaseEngine expected) {
|
||||
rdsService.createDbInstance("mydb", engine, version,
|
||||
"admin", "password", "dbname", "db.t3.micro",
|
||||
20, false, null, null, null, null, false);
|
||||
when(containerManager.createMysqlSnapshot(eq(expected), any(), eq("admin"), eq("password")))
|
||||
.thenReturn("MYSQL_DUMP");
|
||||
|
||||
DbSnapshot snapshot = rdsService.createDbSnapshot("mysnap", "mydb");
|
||||
DbInstance restored = rdsService.restoreDbInstanceFromDbSnapshot("restored", "mysnap",
|
||||
null, null, false, null, List.of(), Map.of(), "us-east-1");
|
||||
|
||||
assertEquals(expected, snapshot.getEngine());
|
||||
assertEquals("available", snapshot.getStatus());
|
||||
assertEquals(expected, restored.getEngine());
|
||||
verify(containerManager).restoreMysqlSnapshot(eq(expected), any(), eq("admin"), eq("password"),
|
||||
eq("MYSQL_DUMP"));
|
||||
verify(containerManager, never()).createPostgresSnapshot(any(), any());
|
||||
verify(containerManager, never()).restorePostgresSnapshot(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void mysqlSnapshotThatCannotBeReadIsNotRecorded() {
|
||||
rdsService.createDbInstance("mydb", "mysql", "8.0",
|
||||
"admin", "password", "dbname", "db.t3.micro",
|
||||
20, false, null, null, null, null, false);
|
||||
when(containerManager.createMysqlSnapshot(any(), any(), any(), any()))
|
||||
.thenThrow(new RuntimeException("mysqldump failed with exit code 2"));
|
||||
|
||||
AwsException exception = assertThrows(AwsException.class, () ->
|
||||
rdsService.createDbSnapshot("mysnap", "mydb"));
|
||||
|
||||
assertEquals("InvalidDBInstanceState", exception.getErrorCode());
|
||||
assertEquals("DBSnapshotNotFound", assertThrows(AwsException.class, () ->
|
||||
rdsService.restoreDbInstanceFromDbSnapshot("restored", "mysnap",
|
||||
null, null, false, null, List.of(), Map.of(), "us-east-1")).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void mysqlInstanceTheSnapshotCannotBeLoadedIntoIsRemoved() {
|
||||
rdsService.createDbInstance("mydb", "mysql", "8.0",
|
||||
"admin", "password", "dbname", "db.t3.micro",
|
||||
20, false, null, null, null, null, false);
|
||||
when(containerManager.createMysqlSnapshot(any(), any(), any(), any())).thenReturn("MYSQL_DUMP");
|
||||
rdsService.createDbSnapshot("mysnap", "mydb");
|
||||
doThrow(new RuntimeException("mysql restore failed with exit code 1"))
|
||||
.when(containerManager).restoreMysqlSnapshot(any(), any(), any(), any(), any());
|
||||
|
||||
AwsException exception = assertThrows(AwsException.class, () ->
|
||||
rdsService.restoreDbInstanceFromDbSnapshot("restored", "mysnap",
|
||||
null, null, false, null, List.of(), Map.of(), "us-east-1"));
|
||||
|
||||
assertEquals("InvalidDBSnapshotState", exception.getErrorCode());
|
||||
assertEquals("DBInstanceNotFound", assertThrows(AwsException.class, () ->
|
||||
rdsService.getDbInstance("restored")).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -207,6 +207,34 @@ class RdsArchiveRetryTest {
|
||||
assertEquals(List.of(List.of("sh", "/tmp/restore.sh", "admin")), commands);
|
||||
}
|
||||
|
||||
@Test
|
||||
void mysqlDumpWaitsForTheServerToAcceptTheMasterUser() {
|
||||
DockerArchiveUploadFixture uploads = failingUploads(0, 0);
|
||||
List<List<String>> commands = ContainerExecStubs.completeEveryExec(docker, CONTAINER,
|
||||
List.of(2L, 2L, 0L), "-- dump", "");
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mysqlDumpFailureIsNotRetried() {
|
||||
failingUploads(0, 0);
|
||||
List<List<String>> commands = ContainerExecStubs.completeEveryExec(docker, CONTAINER, 1, "",
|
||||
"Access denied");
|
||||
|
||||
RuntimeException failure = assertThrows(RuntimeException.class,
|
||||
() -> manager.createMysqlSnapshot(DatabaseEngine.MARIADB, CONTAINER, "admin", "secret"));
|
||||
|
||||
assertTrue(failure.getMessage().contains("mariadb-dump failed with exit code 1: Access denied"));
|
||||
assertEquals(1, commands.size());
|
||||
}
|
||||
|
||||
private static void assertTarEntry(TarArchiveInputStream tar, String name, String content) throws IOException {
|
||||
TarArchiveEntry entry = tar.getNextEntry();
|
||||
assertEquals(name, entry.getName());
|
||||
|
||||
Reference in new issue
Block a user