From b65755da3a26b61d2a7c7c04073586bc3d9270ed Mon Sep 17 00:00:00 2001 From: Simon Claessens Date: Mon, 2 Nov 2026 13:34:19 +0100 Subject: [PATCH] feat(rds): export DB snapshots to S3 as Parquet (#7289) --- docs/configuration/environment-variables.md | 1 + docs/services/rds.md | 67 ++- .../floci/config/EmulatorConfig.java | 7 + .../rds/container/RdsContainerManager.java | 114 ++++- .../services/rds/export/ExportColumn.java | 108 +++++ .../services/rds/export/ExportLayout.java | 58 +++ .../rds/export/PostgresSnapshotExporter.java | 441 ++++++++++++++++++ .../rds/export/RdsExportTaskService.java | 2 +- .../export/UnsupportedSnapshotExporter.java | 16 - src/main/resources/application.yml | 1 + .../services/rds/export/ExportPlanTest.java | 97 +++- .../export/PostgresSnapshotExporterTest.java | 428 +++++++++++++++++ .../rds/export/RdsExportTaskServiceTest.java | 13 - .../RdsSnapshotExportIntegrationTest.java | 326 +++++++++++++ 14 files changed, 1615 insertions(+), 64 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/rds/export/ExportColumn.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/rds/export/ExportLayout.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/rds/export/PostgresSnapshotExporter.java delete mode 100644 src/main/java/io/github/hectorvent/floci/services/rds/export/UnsupportedSnapshotExporter.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/rds/export/PostgresSnapshotExporterTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/rds/export/RdsSnapshotExportIntegrationTest.java diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md index 1be70d97ba..3d7a5d7fcb 100644 --- a/docs/configuration/environment-variables.md +++ b/docs/configuration/environment-variables.md @@ -442,6 +442,7 @@ These services spawn Docker containers. They require access to the Docker socket | `FLOCI_SERVICES_RDS_ENDPOINT_HOST` | _(auto-detected)_ | Hostname advertised in RDS endpoints; when set in Docker, Floci advertises each proxy's published host port | | `FLOCI_SERVICES_RDS_IAM_TOKEN_ENDPOINT_BINDING` | `true` | Refuse a PostgreSQL IAM auth token generated for another hostname, port or region than the endpoint publishes, as RDS does; set `false` to accept such tokens. MySQL and MariaDB always refuse them | | `FLOCI_SERVICES_RDS_DEFAULT_POSTGRES_IMAGE` | `postgres:16-alpine` | Default PostgreSQL Docker image | +| `FLOCI_SERVICES_RDS_EXPORT_STAGING_BUCKET` | `floci-rds-export-staging` | S3 bucket used to stage table rows and Parquet before a snapshot export writes the Parquet to its bucket | | `FLOCI_SERVICES_RDS_DEFAULT_MYSQL_IMAGE` | `mysql:8.0` | Default MySQL Docker image | | `FLOCI_SERVICES_RDS_DEFAULT_MARIADB_IMAGE` | `mariadb:11` | Default MariaDB Docker image | | `FLOCI_SERVICES_RDS_DEFAULT_SQL_SERVER_IMAGE` | `mcr.microsoft.com/mssql/server:2022-latest` | Default SQL Server Docker image | diff --git a/docs/services/rds.md b/docs/services/rds.md index af743248ce..97f3213729 100644 --- a/docs/services/rds.md +++ b/docs/services/rds.md @@ -154,7 +154,7 @@ RDS endpoints return the us-east-1 hosted zone ID `Z2R2ITUGPM61AM` in all region | `DeleteDBClusterAutomatedBackup` | Delete a retained cluster automated backup by `DbClusterResourceId` | | `DescribeDBClusterSnapshotAttributes` | Return the `restore` attribute of a cluster snapshot | | `ModifyDBClusterSnapshotAttribute` | Add or remove `restore` values (account ids or `all`) on a cluster snapshot | -| `StartExportTask` | Start an export task for a DB snapshot or DB cluster snapshot; see [Exporting snapshots to Amazon S3](#exporting-snapshots-to-amazon-s3) | +| `StartExportTask` | Export a DB snapshot or DB cluster snapshot to S3 as Parquet; see [Exporting snapshots to Amazon S3](#exporting-snapshots-to-amazon-s3) | | `DescribeExportTasks` | List export tasks, by `ExportTaskIdentifier`, `SourceArn`, `SourceType` and the `export-task-identifier`, `s3-bucket`, `source-arn` and `status` filters | | `CancelExportTask` | Cancel a running export task; what it already wrote stays in the bucket | | `DescribeGlobalClusters` | List the account's global clusters with their primary and secondary members; see [Global clusters](#global-clusters) | @@ -264,6 +264,7 @@ they belong to, as the model requires. An omitted `Enabled` activates the subscr | `FLOCI_SERVICES_RDS_ENDPOINT_HOST` | _(auto-detected)_ | Hostname advertised in RDS endpoints; when set in Docker, Floci advertises each proxy's published host port | | `FLOCI_SERVICES_RDS_IAM_TOKEN_ENDPOINT_BINDING` | `true` | Refuse a PostgreSQL IAM auth token generated for another hostname, port or region than the endpoint publishes, as RDS does; set `false` to accept such tokens. MySQL and MariaDB always refuse them | | `FLOCI_SERVICES_RDS_DEFAULT_POSTGRES_IMAGE` | `postgres:16-alpine` | Docker image for PostgreSQL instances | +| `FLOCI_SERVICES_RDS_EXPORT_STAGING_BUCKET` | `floci-rds-export-staging` | S3 bucket where snapshot exports stage rows and Parquet; see [Exporting snapshots to Amazon S3](#exporting-snapshots-to-amazon-s3) | | `FLOCI_SERVICES_RDS_DEFAULT_MYSQL_IMAGE` | `mysql:8.0` | Docker image for MySQL instances | | `FLOCI_SERVICES_RDS_DEFAULT_MARIADB_IMAGE` | `mariadb:11` | Docker image for MariaDB instances | | `FLOCI_SERVICES_RDS_DEFAULT_SQL_SERVER_IMAGE` | `mcr.microsoft.com/mssql/server:2022-latest` | Docker image for SQL Server instances | @@ -882,26 +883,58 @@ source, keeps the replica as `retained`; a stop with nothing replicating to the ## Exporting snapshots to Amazon S3 -`StartExportTask`, `DescribeExportTasks` and `CancelExportTask` manage RDS snapshot export tasks. -`ExportTaskIdentifier`, `SourceArn`, `S3BucketName`, `IamRoleArn` and `KmsKeyId` are required, -`S3Prefix` and `ExportOnly` are optional. +`StartExportTask` exports a DB snapshot or a DB cluster snapshot to an S3 bucket in Floci as Apache +Parquet, laid out as RDS lays it out, so a reader written against RDS exports (OpenSearch Data +Prepper's `rds` source, Athena, Glue) reads Floci's. `ExportTaskIdentifier`, `SourceArn`, +`S3BucketName`, `IamRoleArn` and `KmsKeyId` are required, `S3Prefix` and `ExportOnly` are optional. -A task reports `STARTING`, then `IN_PROGRESS` with a `PercentProgress` while its tables are written, -then `COMPLETE` or `FAILED` with a `FailureCause`. `CancelExportTask` moves a running task to -`CANCELING`; it stops before its next table and becomes `CANCELED`, and the data it already wrote -stays in the bucket, as on RDS. A table the export skips is named in `WarningMessage`. A task still -running when Floci stops is `FAILED` as soon as Floci starts again, or `CANCELED` if it was being -canceled. A `StartExportTask` that arrives while Floci is resetting waits for the reset to finish, -and is refused with `Throttling` if it lasts more than 30 seconds. +A task reports `STARTING` while the snapshot is restored, `IN_PROGRESS` with a `PercentProgress` +while its tables are written, then `COMPLETE` or `FAILED` with a `FailureCause`. `CancelExportTask` +moves a running task to `CANCELING`; it stops before its next table and becomes `CANCELED`, and the +data it already wrote stays in the bucket, as on RDS. A table the export skips is named in +`WarningMessage`. A task still running when Floci stops is `FAILED` as soon as Floci starts again, +or `CANCELED` if it was being canceled, and the container and volume it was using are removed then. A `StartExportTask` that arrives while +Floci is resetting waits for the reset to finish, and is refused with `Throttling` if it lasts more +than 30 seconds. -Floci does not write snapshot data to S3 yet. In [mock mode](#mock-mode-ci-tests) a task completes -without writing anything, unless its bucket is in another region (see below). Outside mock mode a task is accepted and then ends `FAILED` with the -`FailureCause` `Floci does not write snapshot data to S3 yet: export tasks complete only in mock -mode (FLOCI_SERVICES_RDS_MOCK=true)`. +The snapshot is restored into a PostgreSQL container started from the snapshot's image, with a +Docker volume of its own in every storage mode, and both are removed once the export ends, whether it +completed, failed or was canceled. Each table's rows are streamed out of the restored database +(for up to an hour per table) and staged, with the Parquet written from them, in the bucket named by +`FLOCI_SERVICES_RDS_EXPORT_STAGING_BUCKET` (`floci-rds-export-staging`, created on first use); only +the finished Parquet object is written to the export's bucket, so a failed table leaves nothing +there. The Parquet is written by the floci-duck sidecar, the one Athena uses, so an export needs +Docker for both. In [mock mode](#mock-mode-ci-tests) a task completes without writing anything, +unless its bucket is in another region (see below). + +Each table goes under `///./1/` as +`part-00000-.gz.parquet`, compressed with GZIP. Floci reads a table in one batch and one +partition, so each table has one file; an empty table has none. The task's own description is +written next to the databases as `export_info_.json`, with a +`export_tables_info__from_1_to_.json` that lists each table it wrote with the +type every column was exported as. A backslash, backquote, double quote or space in an object path +becomes an underscore. + +Column types follow the +[RDS PostgreSQL mapping](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_ExportSnapshot.data-types.html#USER_ExportSnapshot.data-types.PostgreSQL): +`smallint` is `INT32` annotated `INT(16)`, `integer` `INT32`, `bigint` `INT64`, `real` `FLOAT`, +`double precision` `DOUBLE`, `boolean` `BOOLEAN` and `bytea` binary. Every other type is a UTF-8 +string holding PostgreSQL's text output for the value: `numeric`, `money`, dates, times and +intervals, `json` and `jsonb`, `uuid`, arrays, ranges, enums, domains and extension types such as +pgvector's `vector`. Dates and times are written in ISO format, a `timestamptz` in UTC. `ExportOnly` takes `database`, `database.schema` or `database.schema.table` entries made of letters, digits, `$` and `_`, and refuses anything else with `InvalidExportOnly`, since RDS supports -a partial export only for such names. +a partial export only for such names. Every database that accepts connections is exported when it +is absent. As on RDS, temporary and unlogged tables, views and materialized views are not exported, +a partitioned table is exported once through its parent, and a table with a `/` in its name, or a +column name holding a space or one of `, ; { } ( ) = \n \t`, is skipped. Floci also skips a table +whose database or schema name has a `/`, which would split its path in the bucket, and a table +with two column names that differ only in case, such as `"Foo"` and `"foo"`, which its Parquet +writer, DuckDB, cannot keep apart; both are named in `WarningMessage`. A column of a type or domain +of the user's own is exported as a string, whatever its name. A table that +others inherit from (`INHERITS`) is exported with its own rows only, since each child is exported as +a table of its own. What differs from RDS: @@ -913,6 +946,8 @@ What differs from RDS: `available`. - `SourceArn` must name a snapshot: exporting a live DB cluster (`SourceType` `CLUSTER`) is not supported. +- `TotalExtractedDataInGB` is the size of the rows Floci read, in whole gigabytes, and is 0 for + most local data sets. ## Global clusters diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index e772b87eeb..56d5570995 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -1820,6 +1820,13 @@ public interface EmulatorConfig { /** Empty when Floci should adapt its built-in image to the requested engine version. */ Optional defaultPostgresImage(); + /** + * S3 bucket a snapshot export stages each table's rows and Parquet in, before the finished + * Parquet is written to the export's own bucket. Created on first use if it doesn't exist. + */ + @WithDefault("floci-rds-export-staging") + String exportStagingBucket(); + /** Empty when Floci should adapt its built-in image to the requested engine version. */ Optional defaultMysqlImage(); diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManager.java index 3999fb1e20..6333f401aa 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManager.java @@ -31,6 +31,7 @@ import org.jboss.logging.Logger; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; +import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.time.Clock; @@ -272,7 +273,7 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe String dockerVolumeName, DatabaseEngine engine, String image, String masterUsername, String masterPassword, String dbName) { return start(runtimeId, instanceId, containerStorageResourceId, dockerVolumeName, - engine, image, masterUsername, masterPassword, dbName, Map.of()); + engine, image, masterUsername, masterPassword, dbName, Map.of(), false); } public RdsContainerHandle start( @@ -280,6 +281,42 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe String dockerVolumeName, DatabaseEngine engine, String image, String masterUsername, String masterPassword, String dbName, Map engineParameters) { + return start(runtimeId, instanceId, containerStorageResourceId, dockerVolumeName, + engine, image, masterUsername, masterPassword, dbName, engineParameters, false); + } + + /** + * Starts the PostgreSQL container a snapshot export restores into. {@code runtimeArn} gives it + * the task's account and region, and {@code volumeId}, unique to the task, names the container + * and its volume. It backs no DB instance, so its log goes to no instance's log group, it never + * pauses, and its data lives in a Docker volume of its own in every storage mode, which + * {@link #discardExport} removes once the export ends. + */ + public RdsContainerHandle startForExport(String runtimeArn, String exportTaskIdentifier, String volumeId, + String image, String masterUsername, String masterPassword) { + return start(runtimeArn, exportTaskIdentifier, volumeId, exportVolumeName(volumeId), + DatabaseEngine.POSTGRES, image, masterUsername, masterPassword, null, Map.of(), true); + } + + /** + * Removes an export's container, if it is still there, and its volume, which no storage mode + * keeps. Also clears what an export left behind when Floci stopped while it ran. + */ + public void discardExport(String volumeId) { + String volumeName = exportVolumeName(volumeId); + lifecycleManager.removeIfExistsStrict(ContainerStorageHelper.dockerName(config, volumeName)); + lifecycleManager.removeVolumeStrict(volumeName); + } + + private String exportVolumeName(String volumeId) { + return ContainerStorageHelper.resourceName(config, "rds", volumeId, volumeId); + } + + private RdsContainerHandle start( + String runtimeId, String instanceId, String containerStorageResourceId, + String dockerVolumeName, DatabaseEngine engine, String image, + String masterUsername, String masterPassword, String dbName, + Map engineParameters, boolean ephemeral) { LOG.infov("Starting RDS backend container for instance: {0} engine={1}", instanceId, engine); String effectiveRuntimeId = runtimeId == null || runtimeId.isBlank() @@ -349,8 +386,13 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe } // Handle persistence mounting - addPersistenceMounts( - specBuilder, storageResourceId, exactVolumeName, engine, image); + if (ephemeral) { + ContainerStorageHelper.applyNamedVolume(specBuilder, lifecycleManager, exactVolumeName, + engineDefaultDataPath(engine, image)); + } else { + addPersistenceMounts( + specBuilder, storageResourceId, exactVolumeName, engine, image); + } // Add engine-specific command List cmd = buildContainerCmd(engine, image, engineParameters); @@ -383,23 +425,27 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe endpoint.host(), endpoint.port(), storageKey, containerKey); // Attach log streaming - String shortId = info.containerId().length() >= 8 - ? info.containerId().substring(0, 8) - : info.containerId(); - String logGroup = "/aws/rds/instance/" + instanceId + "/error"; - String logStream = logStreamer.generateLogStreamName(shortId); + if (!ephemeral) { + String shortId = info.containerId().length() >= 8 + ? info.containerId().substring(0, 8) + : info.containerId(); + String logGroup = "/aws/rds/instance/" + instanceId + "/error"; + String logStream = logStreamer.generateLogStreamName(shortId); - Closeable logHandle = runtimeIdentity.arnAccountId() != null - ? logStreamer.attachForAccount( - runtimeIdentity.arnAccountId(), info.containerId(), logGroup, - logStream, runtimeIdentity.region(), "rds:" + effectiveRuntimeId) - : logStreamer.attach( - info.containerId(), logGroup, logStream, runtimeIdentity.region(), - "rds:" + effectiveRuntimeId); - handle.setLogStream(logHandle); + Closeable logHandle = runtimeIdentity.arnAccountId() != null + ? logStreamer.attachForAccount( + runtimeIdentity.arnAccountId(), info.containerId(), logGroup, + logStream, runtimeIdentity.region(), "rds:" + effectiveRuntimeId) + : logStreamer.attach( + info.containerId(), logGroup, logStream, runtimeIdentity.region(), + "rds:" + effectiveRuntimeId); + handle.setLogStream(logHandle); + } // Before the handle is returned, so that the connections of every proxy started on it // are counted from the first one. - registerAutoPause(effectiveRuntimeId, handle); + if (!ephemeral) { + registerAutoPause(effectiveRuntimeId, handle); + } activeContainers.put(effectiveRuntimeId, handle); return handle; @@ -1084,6 +1130,40 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe } } + /** + * Runs one query as the master user and returns its rows, one per line, unaligned and without + * headers. The session uses ISO dates in UTC, so a value's text output does not depend on the + * image's defaults. + */ + public String queryPostgres(String containerId, String masterUsername, String database, String sql) { + ByteArrayOutputStream rows = new ByteArrayOutputStream(); + queryPostgres(containerId, masterUsername, database, sql, rows, 600); + return rows.toString(StandardCharsets.UTF_8); + } + + /** + * {@link #queryPostgres(String, String, String, String)} writing the rows to {@code rows} as + * psql prints them, so a large result never has to be held in memory. + */ + public void queryPostgres(String containerId, String masterUsername, String database, String sql, + OutputStream rows, int timeoutSeconds) { + String effectiveUser = (masterUsername != null && !masterUsername.isBlank()) ? masterUsername : "postgres"; + String[] cmd = { + "env", "PGOPTIONS=-c DateStyle=ISO -c TimeZone=UTC -c IntervalStyle=postgres", + "psql", "-X", "-q", "-A", "-t", "-v", "ON_ERROR_STOP=1", + "-U", effectiveUser, "-d", database, "-c", sql + }; + ByteArrayOutputStream errors = new ByteArrayOutputStream(); + try (Lease _ = holdContainer(containerId)) { + ContainerExec.Result result = ContainerExec.run(lifecycleManager.getDockerClient(), containerId, cmd, + timeoutSeconds, rows, errors).throwIfTimedOut(containerId); + if (result.exitCode() != 0) { + throw new IllegalStateException("psql failed with exit code " + result.exitCode() + ": " + + errors.toString(StandardCharsets.UTF_8).trim()); + } + } + } + public void restorePostgresSnapshot(String containerId, String masterUsername, String sqlDump) { String effectiveUser = (masterUsername != null && !masterUsername.isBlank()) ? masterUsername : "postgres"; diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/export/ExportColumn.java b/src/main/java/io/github/hectorvent/floci/services/rds/export/ExportColumn.java new file mode 100644 index 0000000000..c371276fb6 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/rds/export/ExportColumn.java @@ -0,0 +1,108 @@ +package io.github.hectorvent.floci.services.rds.export; + +import java.util.Map; + +/** + * One column of an exported PostgreSQL table, named by its {@code pg_type.typname}, with + * {@code builtIn} telling whether that type is one of {@code pg_catalog}'s. The Parquet type follows + * the RDS export mapping: built-in integers, floating point and boolean keep a Parquet type of their + * own, built-in {@code bytea} is binary, and every other type, arrays, {@code json}, + * {@code numeric}, dates and times, {@code uuid}, extension types such as {@code vector} and any + * type or domain of the user's own, whatever its name, included, is a UTF-8 string holding + * PostgreSQL's text output for the value. + * + * @see + * Data conversion when exporting to an Amazon S3 bucket + */ +record ExportColumn(String name, String pgType, boolean builtIn) { + + ExportColumn(String name, String pgType) { + this(name, pgType, true); + } + + private static final Map NATIVE_DUCK_TYPES = Map.of( + "int2", "SMALLINT", + "int4", "INTEGER", + "int8", "BIGINT", + "float4", "FLOAT", + "float8", "DOUBLE", + "bool", "BOOLEAN"); + + private static final Map PARQUET_TYPE_NAMES = Map.of( + "SMALLINT", "INT32", + "INTEGER", "INT32", + "BIGINT", "INT64", + "FLOAT", "FLOAT", + "DOUBLE", "DOUBLE", + "BOOLEAN", "BOOLEAN", + "BLOB", "BINARY"); + + private static final String BYTEA = "bytea"; + + /** The Parquet type, as the DuckDB type the column is written with. */ + String parquetType() { + if (isBytea()) { + return "BLOB"; + } + String nativeType = nativeDuckType(); + return nativeType == null ? "VARCHAR" : nativeType; + } + + /** The Parquet primitive type the column is written as, or STRING for a UTF-8 string. */ + String parquetTypeName() { + return PARQUET_TYPE_NAMES.getOrDefault(parquetType(), "STRING"); + } + + /** The type DuckDB reads the staged JSON value as, before it is written. */ + String stagedType() { + return isBytea() ? "VARCHAR" : parquetType(); + } + + /** The PostgreSQL expression that stages the value: native, hex for bytea, text otherwise. */ + String extractExpression() { + String column = quoteIdentifier(name); + if (isBytea()) { + return "encode(" + column + ", 'hex')"; + } + if (nativeDuckType() != null) { + return column; + } + return column + "::text"; + } + + /** The DuckDB expression that writes the staged value. */ + String writeExpression() { + String column = quoteIdentifier(name); + if (isBytea()) { + return "unhex(" + column + ") AS " + column; + } + return column; + } + + private boolean isBytea() { + return builtIn && BYTEA.equals(pgType); + } + + private String nativeDuckType() { + return builtIn ? NATIVE_DUCK_TYPES.get(pgType) : null; + } + + /** + * RDS skips a table with any of these characters in a column name. + * + * @see + * Limitations + */ + boolean hasExportableName() { + for (char c : name.toCharArray()) { + if (",;{}()\n\t= ".indexOf(c) >= 0) { + return false; + } + } + return true; + } + + static String quoteIdentifier(String identifier) { + return "\"" + identifier.replace("\"", "\"\"") + "\""; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/export/ExportLayout.java b/src/main/java/io/github/hectorvent/floci/services/rds/export/ExportLayout.java new file mode 100644 index 0000000000..42482f201d --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/rds/export/ExportLayout.java @@ -0,0 +1,58 @@ +package io.github.hectorvent.floci.services.rds.export; + +import java.util.UUID; + +/** + * Where an export task writes in its bucket. Each table's data goes under + * {@code ///.
//}, named + * {@code part--.gz.parquet}, and the task's own description sits at + * {@code //}. Floci reads each table in one batch and one partition. + * + * @see + * File naming conventions for exports to Amazon S3 + */ +final class ExportLayout { + + private final String taskRoot; + private final String taskId; + + ExportLayout(String s3Prefix, String taskId) { + String prefix = s3Prefix == null ? "" : stripSlashes(s3Prefix); + this.taskId = taskId; + this.taskRoot = (prefix.isEmpty() ? "" : prefix + "/") + pathComponent(taskId) + "/"; + } + + String taskRoot() { + return taskRoot; + } + + String dataFileKey(String database, String schema, String table) { + return taskRoot + pathComponent(database) + "/" + pathComponent(schema) + "." + pathComponent(table) + + "/1/part-00000-" + UUID.randomUUID() + ".gz.parquet"; + } + + String exportInfoKey() { + return taskRoot + "export_info_" + taskId + ".json"; + } + + String tablesInfoKey(int tableCount) { + return taskRoot + "export_tables_info_" + taskId + "_from_1_to_" + tableCount + ".json"; + } + + /** RDS writes a backslash, backquote, double quote or space in an object path as an underscore. */ + static String pathComponent(String name) { + return name.replaceAll("[\\\\`\" ]", "_"); + } + + private static String stripSlashes(String prefix) { + int start = 0; + int end = prefix.length(); + while (start < end && prefix.charAt(start) == '/') { + start++; + } + while (end > start && prefix.charAt(end - 1) == '/') { + end--; + } + return prefix.substring(start, end); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/export/PostgresSnapshotExporter.java b/src/main/java/io/github/hectorvent/floci/services/rds/export/PostgresSnapshotExporter.java new file mode 100644 index 0000000000..76f79c0dac --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/rds/export/PostgresSnapshotExporter.java @@ -0,0 +1,441 @@ +package io.github.hectorvent.floci.services.rds.export; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.floci.duck.FlociDuckClient; +import io.github.hectorvent.floci.services.rds.container.RdsContainerHandle; +import io.github.hectorvent.floci.services.rds.container.RdsContainerManager; +import io.github.hectorvent.floci.services.rds.model.ExportTask; +import io.github.hectorvent.floci.services.s3.S3Service; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Instant; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +/** + * Exports a PostgreSQL snapshot the way RDS does: the snapshot is restored into a database of its + * own, here a container started from the snapshot's image and removed afterwards, and each table + * is then read out and written as Parquet by the floci-duck sidecar. PostgreSQL renders every value + * the export stores as a string, so the strings are PostgreSQL's own text output. + * + *

As in {@code FirehoseParquetConverter}, a table's rows and its Parquet are staged in a bucket + * of Floci's own, and only a finished Parquet object is written to the export's bucket, so nothing + * partial or temporary ever appears there. A table's rows are streamed from psql to a temporary + * file and staged in bounded chunks, so its size never has to fit in memory. + */ +@ApplicationScoped +public class PostgresSnapshotExporter implements SnapshotExporter { + + private static final Logger LOG = Logger.getLogger(PostgresSnapshotExporter.class); + + private static final String DATABASES_SQL = "SELECT to_json(datname) FROM pg_database " + + "WHERE datallowconn AND NOT datistemplate ORDER BY datname"; + + // Ordinary and partitioned tables, but not a partition on its own, since reading the parent + // reads its partitions. Temporary and unlogged tables are skipped, as RDS skips them. + private static final String COLUMNS_SQL = "SELECT json_build_object('schema', n.nspname, " + + "'table', c.relname, 'kind', c.relkind, 'column', a.attname, 'type', t.typname, " + + "'builtin', t.typnamespace = 'pg_catalog'::regnamespace) " + + "FROM pg_class c " + + "JOIN pg_namespace n ON n.oid = c.relnamespace " + + "JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped " + + "JOIN pg_type t ON t.oid = a.atttypid " + + "WHERE c.relkind IN ('r', 'p') AND NOT c.relispartition AND c.relpersistence = 'p' " + + "AND n.nspname <> 'information_schema' AND n.nspname NOT LIKE 'pg\\_%' " + + "ORDER BY n.nspname, c.relname, a.attnum"; + + private static final String NDJSON = "application/x-ndjson"; + private static final String JSON = "application/json"; + private static final String PARQUET = "application/octet-stream"; + + // How long one table may take to read out of the restored database. + static final int TABLE_READ_TIMEOUT_SECONDS = 3600; + static final int STAGING_CHUNK_BYTES = 32 * 1024 * 1024; + static final int DUCKDB_DEFAULT_MAXIMUM_OBJECT_SIZE = 16 * 1024 * 1024; + + private final RdsContainerManager containerManager; + private final FlociDuckClient duckClient; + private final S3Service s3Service; + private final ObjectMapper mapper; + private final Clock clock; + private final String stagingBucket; + + @Inject + public PostgresSnapshotExporter(RdsContainerManager containerManager, FlociDuckClient duckClient, + S3Service s3Service, ObjectMapper mapper, Clock clock, + EmulatorConfig config) { + this.containerManager = containerManager; + this.duckClient = duckClient; + this.s3Service = s3Service; + this.mapper = mapper; + this.clock = clock; + this.stagingBucket = config.services().rds().exportStagingBucket(); + } + + record Table(String database, String schema, String name, boolean partitioned, List columns) { + + String target() { + return database + "." + schema + "." + name; + } + } + + @Override + public Outcome export(ExportTask task, SnapshotExportSource source, Progress progress) { + RdsContainerHandle handle = null; + try { + handle = containerManager.startForExport(task.getRuntimeArn(), task.getExportTaskIdentifier(), + task.getRuntimeVolumeId(), source.image(), source.masterUsername(), source.masterPassword()); + containerManager.restorePostgresSnapshot(handle.getContainerId(), source.masterUsername(), + source.sqlDump()); + progress.extracting(0); + return exportTables(task, source, handle.getContainerId(), progress); + } finally { + removeContainer(handle, task); + } + } + + private Outcome exportTables(ExportTask task, SnapshotExportSource source, String containerId, + Progress progress) { + ExportOnlySelection selection = ExportOnlySelection.of(task.getExportOnly()); + ExportLayout layout = new ExportLayout(task.getS3Prefix(), task.getExportTaskIdentifier()); + List warnings = new ArrayList<>(); + List

tables = new ArrayList<>(); + for (String database : jsonLines(query(containerId, source, "postgres", DATABASES_SQL))) { + if (!selection.includesDatabase(database)) { + continue; + } + for (Table table : tables(containerId, source, database)) { + if (!selection.includes(database, table.schema(), table.name())) { + continue; + } + if (table.target().contains("/") + || !table.columns().stream().allMatch(ExportColumn::hasExportableName)) { + warnings.add("The table " + table.target() + " was skipped because its database, schema or" + + " table name, or a column name, has characters RDS cannot export."); + continue; + } + if (hasColumnsDifferingOnlyInCase(table)) { + warnings.add("The table " + table.target() + " was skipped because two of its column names" + + " differ only in case, which the Parquet writer cannot keep apart."); + continue; + } + tables.add(table); + } + } + + if (!tables.isEmpty()) { + ensureStagingBucket(task.getRegion()); + } + long bytes = 0; + ArrayNode perTableStatus = mapper.createArrayNode(); + for (int i = 0; i < tables.size(); i++) { + if (progress.canceled()) { + break; + } + Table table = tables.get(i); + long written = exportTable(task, source, containerId, layout, table, i + 1, progress); + bytes += written; + perTableStatus.add(tableStatus(table, written)); + progress.extracting((i + 1) * 100 / tables.size()); + } + Instant finishedAt = Instant.now(clock); + if (!progress.canceled()) { + writeInfo(task, layout, perTableStatus, tables.size(), bytes, finishedAt); + } + return new Outcome(bytes, warnings, finishedAt); + } + + private List
tables(String containerId, SnapshotExportSource source, String database) { + Map tables = new LinkedHashMap<>(); + for (String line : query(containerId, source, database, COLUMNS_SQL).split("\n")) { + if (line.isBlank()) { + continue; + } + JsonNode row = readTree(line); + String schema = row.get("schema").asText(); + String name = row.get("table").asText(); + boolean partitioned = "p".equals(row.path("kind").asText()); + tables.computeIfAbsent(schema + "\u0000" + name, + key -> new Table(database, schema, name, partitioned, new ArrayList<>())) + .columns() + .add(new ExportColumn(row.get("column").asText(), row.get("type").asText(), + row.path("builtin").asBoolean(true))); + } + return List.copyOf(tables.values()); + } + + private static boolean hasColumnsDifferingOnlyInCase(Table table) { + Set names = new HashSet<>(); + for (ExportColumn column : table.columns()) { + if (!names.add(column.name().toLowerCase(Locale.ROOT))) { + return true; + } + } + return false; + } + + /** + * Writes one table and returns the size of its rows. A table with no rows writes no file, as + * RDS writes none for an empty partition. + */ + private long exportTable(ExportTask task, SnapshotExportSource source, String containerId, + ExportLayout layout, Table table, int tableNumber, Progress progress) { + List extract = new ArrayList<>(); + List write = new ArrayList<>(); + List types = new ArrayList<>(); + for (ExportColumn column : table.columns()) { + extract.add(column.extractExpression() + " AS " + ExportColumn.quoteIdentifier(column.name())); + write.add(column.writeExpression()); + types.add("'" + escapeLiteral(column.name()) + "': '" + column.stagedType() + "'"); + } + String select = "SELECT row_to_json(r) FROM (SELECT " + String.join(", ", extract) + + (table.partitioned() ? " FROM " : " FROM ONLY ") + ExportColumn.quoteIdentifier(table.schema()) + + "." + ExportColumn.quoteIdentifier(table.name()) + ") r"; + + Path rows = null; + List staged = new ArrayList<>(); + try { + rows = Files.createTempFile("floci-rds-export-", ".ndjson"); + try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(rows))) { + containerManager.queryPostgres(containerId, source.masterUsername(), table.database(), select, + out, TABLE_READ_TIMEOUT_SECONDS); + } + long size = Files.size(rows); + if (size == 0) { + return 0; + } + String stagingRoot = "rds-export/" + task.getRuntimeVolumeId() + "/" + tableNumber + "/"; + int longestRow = stageChunksReturningTheLongestRow(rows, stagingRoot, staged); + String stagedParquet = stagingRoot + "data.gz.parquet"; + staged.add(stagedParquet); + // floci-duck's /execute wraps its sql field in a CSV export, so the Parquet COPY goes + // in setup_sql and no output path is given, as FirehoseParquetConverter does. + String copy = "COPY (SELECT " + String.join(", ", write) + " FROM read_json('" + + escapeLiteral("s3://" + stagingBucket + "/" + stagingRoot + "part-*.ndjson") + + "', format='newline_delimited', maximum_object_size=" + + Math.max(DUCKDB_DEFAULT_MAXIMUM_OBJECT_SIZE, longestRow) + + ", columns={" + String.join(", ", types) + "})) TO '" + + escapeLiteral("s3://" + stagingBucket + "/" + stagedParquet) + + "' (FORMAT PARQUET, COMPRESSION GZIP)"; + duckClient.execute("SELECT 1 AS ok", copy, null, task.getAccountId()); + if (progress.abandonedByReset()) { + return size; + } + try (InputStream parquet = s3Service.openObjectStream(stagingBucket, stagedParquet, null)) { + s3Service.putObjectFromStream(task.getS3Bucket(), + layout.dataFileKey(table.database(), table.schema(), table.name()), parquet, PARQUET, Map.of()); + } + return size; + } catch (IOException e) { + throw new UncheckedIOException(e); + } finally { + for (String key : staged) { + deleteQuietly(stagingBucket, key); + } + deleteQuietly(rows); + } + } + + /** Stages the rows as NDJSON objects of about {@link #STAGING_CHUNK_BYTES}, split between rows. */ + private int stageChunksReturningTheLongestRow(Path rows, String stagingRoot, List keys) + throws IOException { + ByteArrayOutputStream chunk = new ByteArrayOutputStream(); + int longestRow = 0; + try (BufferedReader reader = Files.newBufferedReader(rows, StandardCharsets.UTF_8)) { + String line; + while ((line = reader.readLine()) != null) { + if (line.isBlank()) { + continue; + } + byte[] row = line.getBytes(StandardCharsets.UTF_8); + longestRow = Math.max(longestRow, row.length + 1); + chunk.write(row); + chunk.write('\n'); + if (chunk.size() >= STAGING_CHUNK_BYTES) { + putChunk(stagingRoot, keys, chunk); + } + } + } + if (chunk.size() > 0) { + putChunk(stagingRoot, keys, chunk); + } + return longestRow; + } + + private void putChunk(String stagingRoot, List keys, ByteArrayOutputStream chunk) { + String key = stagingRoot + "part-" + keys.size() + ".ndjson"; + keys.add(key); + s3Service.putObject(stagingBucket, key, chunk.toByteArray(), NDJSON, Map.of()); + chunk.reset(); + } + + /** + * Two workers can reach an empty region together, and outside us-east-1 the second + * {@code createBucket} answers {@code BucketAlreadyOwnedByYou}. + */ + private void ensureStagingBucket(String region) { + if (s3Service.bucketExists(stagingBucket)) { + return; + } + try { + s3Service.createBucket(stagingBucket, region); + } catch (AwsException e) { + if (!"BucketAlreadyOwnedByYou".equals(e.getErrorCode()) + && !"BucketAlreadyExists".equals(e.getErrorCode())) { + throw e; + } + } + } + + private ObjectNode tableStatus(Table table, long bytes) { + ObjectNode status = mapper.createObjectNode(); + status.put("target", table.target()); + status.put("status", ExportTask.STATUS_COMPLETE); + status.put("sizeGB", (double) bytes / RdsExportTaskService.GIB); + ArrayNode mappings = status.putObject("schemaMetadata").putArray("originalTypeMappings"); + for (ExportColumn column : table.columns()) { + mappings.addObject() + .put("columnName", column.name()) + .put("originalType", column.pgType()) + .put("expectedExportedType", column.parquetTypeName()); + } + return status; + } + + /** + * The task's own record next to its data: its description, and the status of every table it + * wrote. Readers that follow the RDS advice to read everything under a table's prefix never + * see these, as they sit above the tables. + */ + private void writeInfo(ExportTask task, ExportLayout layout, ArrayNode perTableStatus, int tableCount, + long bytes, Instant finishedAt) { + ObjectNode info = mapper.createObjectNode(); + info.put("exportTaskIdentifier", task.getExportTaskIdentifier()); + info.put("sourceArn", task.getSourceArn()); + info.set("exportOnly", mapper.valueToTree(task.getExportOnly())); + info.put("snapshotTime", String.valueOf(task.getSnapshotTime())); + info.put("taskStartTime", String.valueOf(task.getTaskStartTime())); + info.put("taskEndTime", finishedAt.toString()); + info.put("s3Bucket", task.getS3Bucket()); + info.put("s3Prefix", task.getS3Prefix() == null ? "" : task.getS3Prefix()); + info.put("exportedFilesPath", layout.taskRoot()); + info.put("iamRoleArn", task.getIamRoleArn()); + info.put("kmsKeyId", task.getKmsKeyId()); + info.put("status", ExportTask.STATUS_COMPLETE); + info.put("percentProgress", 100); + info.put("totalExportedDataInGB", (double) bytes / RdsExportTaskService.GIB); + + ObjectNode tablesInfo = mapper.createObjectNode(); + tablesInfo.set("perTableStatus", perTableStatus); + putJson(task.getS3Bucket(), layout.tablesInfoKey(Math.max(tableCount, 1)), tablesInfo); + putJson(task.getS3Bucket(), layout.exportInfoKey(), info); + } + + private void putJson(String bucket, String key, JsonNode body) { + try { + s3Service.putObject(bucket, key, mapper.writeValueAsBytes(body), JSON, Map.of()); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + private String query(String containerId, SnapshotExportSource source, String database, String sql) { + return containerManager.queryPostgres(containerId, source.masterUsername(), database, sql); + } + + private List jsonLines(String output) { + List values = new ArrayList<>(); + for (String line : output.split("\n")) { + if (!line.isBlank()) { + values.add(readTree(line).asText()); + } + } + return values; + } + + private JsonNode readTree(String json) { + try { + return mapper.readTree(json); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + @Override + public void discard(ExportTask task) { + if (task.getRuntimeVolumeId() != null) { + containerManager.discardExport(task.getRuntimeVolumeId()); + } + } + + /** + * Stops the container, then removes it and its volume whether or not the stop succeeded: a + * volume left behind holds a whole copy of the database. + */ + private void removeContainer(RdsContainerHandle handle, ExportTask task) { + String volumeId = task.getRuntimeVolumeId(); + if (handle != null) { + try { + containerManager.stop(handle); + } catch (RuntimeException e) { + LOG.warnv(e, "Could not stop the export container {0}", volumeId); + } + } + try { + containerManager.discardExport(volumeId); + } catch (RuntimeException e) { + LOG.warnv(e, "Could not remove the export container and volume {0}", volumeId); + } + try { + containerManager.stopByRuntimeId(task.getRuntimeArn()); + } catch (RuntimeException e) { + LOG.warnv(e, "Could not release the export runtime {0}", task.getRuntimeArn()); + } + } + + private void deleteQuietly(String bucket, String key) { + try { + s3Service.deleteObject(bucket, key); + } catch (RuntimeException e) { + LOG.warnv(e, "Could not remove the staged export object s3://{0}/{1}", bucket, key); + } + } + + private static void deleteQuietly(Path file) { + if (file == null) { + return; + } + try { + Files.deleteIfExists(file); + } catch (IOException e) { + LOG.warnv(e, "Could not remove the temporary export file {0}", file); + } + } + + private static String escapeLiteral(String raw) { + return raw.replace("'", "''"); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/export/RdsExportTaskService.java b/src/main/java/io/github/hectorvent/floci/services/rds/export/RdsExportTaskService.java index 0ea3bd7e2d..661b2dfaa4 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/export/RdsExportTaskService.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/export/RdsExportTaskService.java @@ -79,7 +79,7 @@ public class RdsExportTaskService implements Resettable { @Inject public RdsExportTaskService(StorageFactory storageFactory, RdsService rdsService, S3Service s3Service, - UnsupportedSnapshotExporter exporter, RegionResolver regionResolver, + PostgresSnapshotExporter exporter, RegionResolver regionResolver, EmulatorConfig config, Clock clock) { this(storageFactory.create("rds", "rds-export-tasks.json", new TypeReference>() {}), diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/export/UnsupportedSnapshotExporter.java b/src/main/java/io/github/hectorvent/floci/services/rds/export/UnsupportedSnapshotExporter.java deleted file mode 100644 index 7fbb0004b5..0000000000 --- a/src/main/java/io/github/hectorvent/floci/services/rds/export/UnsupportedSnapshotExporter.java +++ /dev/null @@ -1,16 +0,0 @@ -package io.github.hectorvent.floci.services.rds.export; - -import io.github.hectorvent.floci.services.rds.model.ExportTask; -import jakarta.enterprise.context.ApplicationScoped; - -@ApplicationScoped -public class UnsupportedSnapshotExporter implements SnapshotExporter { - - static final String FAILURE_CAUSE = "Floci does not write snapshot data to S3 yet: " - + "export tasks complete only in mock mode (FLOCI_SERVICES_RDS_MOCK=true)"; - - @Override - public Outcome export(ExportTask task, SnapshotExportSource source, Progress progress) { - throw new UnsupportedOperationException(FAILURE_CAUSE); - } -} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 3169cfeb6e..e1ac9667dc 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -571,6 +571,7 @@ floci: # default-postgres-image: "registry.example.com/postgres:16-alpine" # default-mysql-image: "registry.example.com/mysql:8.0" # default-mariadb-image: "registry.example.com/mariadb:11" + export-staging-bucket: floci-rds-export-staging # Where snapshot exports stage rows and Parquet before writing to the export bucket default-sql-server-image: "mcr.microsoft.com/mssql/server:2022-latest" proxy-handshake-timeout-millis: 10000 # Max time a client has to complete the startup/auth handshake proxy-backend-connect-timeout-millis: 5000 # Max time to wait for the backend TCP connect diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/export/ExportPlanTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/export/ExportPlanTest.java index a6e03e09f2..b9ef507c63 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/export/ExportPlanTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/export/ExportPlanTest.java @@ -3,17 +3,23 @@ package io.github.hectorvent.floci.services.rds.export; import io.github.hectorvent.floci.core.common.AwsException; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.matchesPattern; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -/** Which tables an export's {@code ExportOnly} selects, and the entries it refuses. */ +/** + * The pure pieces of an export: which tables {@code ExportOnly} selects, the Parquet type each + * PostgreSQL type is written as, and the object keys a task writes, which Data Prepper's + * {@code ExportObjectKey} parses from the last five path segments. + */ class ExportPlanTest { @Test @@ -43,4 +49,93 @@ class ExportPlanTest { assertThat(error.getErrorCode(), equalTo("InvalidExportOnly")); } + + @ParameterizedTest + @CsvSource({ + "int2, SMALLINT, \"c\"", + "int4, INTEGER, \"c\"", + "int8, BIGINT, \"c\"", + "float4, FLOAT, \"c\"", + "float8, DOUBLE, \"c\"", + "bool, BOOLEAN, \"c\"", + "numeric, VARCHAR, \"c\"::text", + "timestamptz, VARCHAR, \"c\"::text", + "jsonb, VARCHAR, \"c\"::text", + "_uuid, VARCHAR, \"c\"::text", + "_int4, VARCHAR, \"c\"::text", + "vector, VARCHAR, \"c\"::text", + "bytea, BLOB, 'encode(\"c\", ''hex'')'" + }) + void columnsFollowTheRdsParquetMapping(String pgType, String parquetType, String extract) { + ExportColumn column = new ExportColumn("c", pgType); + + assertThat(column.parquetType(), equalTo(parquetType)); + assertThat(column.extractExpression(), equalTo(extract)); + } + + @ParameterizedTest + @CsvSource({"int2, INT32", "int4, INT32", "int8, INT64", "float4, FLOAT", "float8, DOUBLE", + "bool, BOOLEAN", "bytea, BINARY", "numeric, STRING", "vector, STRING"}) + void exportedTypesAreNamedAsParquetTypes(String pgType, String parquetTypeName) { + assertThat(new ExportColumn("c", pgType).parquetTypeName(), equalTo(parquetTypeName)); + } + + @Test + void byteaIsStagedAsHexAndWrittenAsBinary() { + ExportColumn column = new ExportColumn("payload", "bytea"); + + assertThat(column.stagedType(), equalTo("VARCHAR")); + assertThat(column.writeExpression(), equalTo("unhex(\"payload\") AS \"payload\"")); + } + + @ParameterizedTest + @ValueSource(strings = {"int4", "int8", "bool", "bytea"}) + void aTypeOfTheUsersOwnIsAStringWhateverItsName(String pgType) { + ExportColumn column = new ExportColumn("c", pgType, false); + + assertThat(column.parquetType(), equalTo("VARCHAR")); + assertThat(column.stagedType(), equalTo("VARCHAR")); + assertThat(column.parquetTypeName(), equalTo("STRING")); + assertThat(column.extractExpression(), equalTo("\"c\"::text")); + assertThat(column.writeExpression(), equalTo("\"c\"")); + } + + @ParameterizedTest + @ValueSource(strings = {"has space", "a,b", "a;b", "a=b", "a(b)", "a{b}", "a\tb"}) + void columnNamesRdsSkipsAreFlagged(String name) { + assertFalse(new ExportColumn(name, "text").hasExportableName()); + } + + @Test + void identifiersAreQuotedWithEmbeddedQuotesDoubled() { + assertThat(ExportColumn.quoteIdentifier("we\"ird"), equalTo("\"we\"\"ird\"")); + } + + @Test + void dataFileKeysFollowTheRdsLayoutDataPrepperParses() { + ExportLayout layout = new ExportLayout("items/rds", "fx-dp-snapshot-1a2b3c4d-export-5e6f7a8b"); + + String key = layout.dataFileKey("appdb", "public", "items"); + + assertThat(key, matchesPattern("items/rds/fx-dp-snapshot-1a2b3c4d-export-5e6f7a8b/appdb/public\\.items/1/" + + "part-00000-[0-9a-f-]{36}\\.gz\\.parquet")); + String[] parts = key.split("/"); + assertThat(parts[parts.length - 5], equalTo("fx-dp-snapshot-1a2b3c4d-export-5e6f7a8b")); + assertThat(parts[parts.length - 4], equalTo("appdb")); + assertThat(parts[parts.length - 3], equalTo("public.items")); + } + + @Test + void taskRootTrimsSlashesAndWorksWithoutAPrefix() { + assertThat(new ExportLayout("/exports/", "task-1").taskRoot(), equalTo("exports/task-1/")); + assertThat(new ExportLayout(null, "task-1").taskRoot(), equalTo("task-1/")); + assertThat(new ExportLayout("", "task-1").exportInfoKey(), equalTo("task-1/export_info_task-1.json")); + assertThat(new ExportLayout("", "task-1").tablesInfoKey(3), + equalTo("task-1/export_tables_info_task-1_from_1_to_3.json")); + } + + @Test + void pathCharactersRdsReplacesBecomeUnderscores() { + assertThat(ExportLayout.pathComponent("my table`\"\\x"), equalTo("my_table___x")); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/export/PostgresSnapshotExporterTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/export/PostgresSnapshotExporterTest.java new file mode 100644 index 0000000000..93d67b4afe --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/rds/export/PostgresSnapshotExporterTest.java @@ -0,0 +1,428 @@ +package io.github.hectorvent.floci.services.rds.export; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.services.floci.duck.FlociDuckClient; +import io.github.hectorvent.floci.services.rds.container.RdsContainerHandle; +import io.github.hectorvent.floci.services.rds.container.RdsContainerManager; +import io.github.hectorvent.floci.services.rds.model.ExportTask; +import io.github.hectorvent.floci.services.s3.S3Service; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; + +import java.io.ByteArrayInputStream; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.concurrent.atomic.AtomicBoolean; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.everyItem; +import static org.hamcrest.Matchers.matchesPattern; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.startsWith; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * The export of one snapshot with Docker, DuckDB and S3 replaced: where rows and Parquet are staged, + * what reaches the export's bucket, and that the restore container and its volume are removed + * however the export ends. + */ +class PostgresSnapshotExporterTest { + + private static final String STAGING = "floci-rds-export-staging"; + private static final Instant FINISHED = Instant.parse("2026-10-13T09:05:00Z"); + + private RdsContainerManager containerManager; + private FlociDuckClient duckClient; + private S3Service s3Service; + private PostgresSnapshotExporter exporter; + private final SnapshotExportSource source = new SnapshotExportSource( + "arn:aws:rds:us-east-1:000000000000:snapshot:snap", "postgres:16-alpine", "master", "secret", + Instant.parse("2026-10-13T08:00:00Z"), "-- dump"); + private final SnapshotExporter.Progress progress = new SnapshotExporter.Progress() { + @Override + public void extracting(int percent) { + } + + @Override + public boolean canceled() { + return false; + } + + @Override + public boolean abandonedByReset() { + return false; + } + }; + + @BeforeEach + void setUp() { + containerManager = mock(RdsContainerManager.class); + duckClient = mock(FlociDuckClient.class); + s3Service = mock(S3Service.class); + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.services().rds().exportStagingBucket()).thenReturn(STAGING); + exporter = new PostgresSnapshotExporter(containerManager, duckClient, s3Service, new ObjectMapper(), + Clock.fixed(FINISHED, ZoneOffset.UTC), config); + + when(containerManager.startForExport(any(), any(), any(), any(), any(), any())) + .thenReturn(new RdsContainerHandle("restore-container", "appdb-export", "localhost", 5432)); + when(containerManager.queryPostgres(eq("restore-container"), eq("master"), eq("postgres"), anyString())) + .thenReturn("\"appdb\"\n"); + when(containerManager.queryPostgres(eq("restore-container"), eq("master"), eq("appdb"), + argThat(sql -> sql.contains("pg_attribute")))) + .thenReturn("{\"schema\":\"public\",\"table\":\"items\",\"column\":\"id\",\"type\":\"int4\"}\n"); + when(s3Service.bucketExists(STAGING)).thenReturn(true); + when(s3Service.openObjectStream(eq(STAGING), anyString(), isNull())) + .thenAnswer(invocation -> new ByteArrayInputStream(new byte[]{'P', 'A', 'R', '1'})); + } + + private ExportTask task() { + ExportTask task = new ExportTask(); + task.setExportTaskIdentifier("appdb-export"); + task.setRuntimeArn("arn:aws:rds:us-east-1:000000000000:export-task:appdb-export"); + task.setRuntimeVolumeId("export-0123456789abcdef"); + task.setS3Bucket("exports"); + task.setS3Prefix("search/rds"); + task.setRegion("us-east-1"); + task.setAccountId("000000000000"); + return task; + } + + private void tableRows(String rows) { + doAnswer(invocation -> { + OutputStream out = invocation.getArgument(4); + out.write(rows.getBytes(StandardCharsets.UTF_8)); + return null; + }).when(containerManager).queryPostgres(eq("restore-container"), eq("master"), eq("appdb"), + argThat(sql -> sql.startsWith("SELECT row_to_json")), any(OutputStream.class), + eq(PostgresSnapshotExporter.TABLE_READ_TIMEOUT_SECONDS)); + } + + @Test + void rowsAndParquetAreStagedOutsideTheExportBucket() { + tableRows("{\"id\":1}\n{\"id\":2}\n"); + + SnapshotExporter.Outcome outcome = exporter.export(task(), source, progress); + + ArgumentCaptor setupSql = ArgumentCaptor.forClass(String.class); + verify(duckClient).execute(eq("SELECT 1 AS ok"), setupSql.capture(), isNull(), eq("000000000000")); + assertThat(setupSql.getValue(), containsString( + "read_json('s3://" + STAGING + "/rds-export/export-0123456789abcdef/1/part-*.ndjson'")); + assertThat(setupSql.getValue(), containsString( + "TO 's3://" + STAGING + "/rds-export/export-0123456789abcdef/1/data.gz.parquet'")); + verify(s3Service).putObject(eq(STAGING), eq("rds-export/export-0123456789abcdef/1/part-0.ndjson"), + argThat(bytes -> new String(bytes, StandardCharsets.UTF_8).equals("{\"id\":1}\n{\"id\":2}\n")), + anyString(), any()); + + ArgumentCaptor exportKeys = ArgumentCaptor.forClass(String.class); + verify(s3Service, atLeastOnce()).putObject(eq("exports"), exportKeys.capture(), any(), anyString(), any()); + assertThat(exportKeys.getAllValues(), everyItem(startsWith("search/rds/appdb-export/"))); + assertThat(exportKeys.getAllValues(), everyItem(not(containsString("ndjson")))); + ArgumentCaptor parquetKey = ArgumentCaptor.forClass(String.class); + verify(s3Service).putObjectFromStream(eq("exports"), parquetKey.capture(), any(), anyString(), any()); + assertThat(parquetKey.getValue(), + matchesPattern("search/rds/appdb-export/appdb/public\\.items/1/part-00000-[0-9a-f-]{36}\\.gz\\.parquet")); + verify(s3Service).deleteObject(STAGING, "rds-export/export-0123456789abcdef/1/part-0.ndjson"); + verify(s3Service).deleteObject(STAGING, "rds-export/export-0123456789abcdef/1/data.gz.parquet"); + assertThat(outcome.finishedAt(), equalTo(FINISHED)); + assertThat(outcome.bytesExtracted(), equalTo(18L)); + } + + @Test + void exportInfoRecordsTheClocksEndTime() throws Exception { + tableRows("{\"id\":1}\n"); + + exporter.export(task(), source, progress); + + ArgumentCaptor body = ArgumentCaptor.forClass(byte[].class); + verify(s3Service).putObject(eq("exports"), eq("search/rds/appdb-export/export_info_appdb-export.json"), + body.capture(), anyString(), any()); + JsonNode info = new ObjectMapper().readTree(body.getValue()); + assertThat(info.get("taskEndTime").asText(), equalTo("2026-10-13T09:05:00Z")); + } + + @Test + void aFailedConversionLeavesNothingInTheExportBucket() { + tableRows("{\"id\":1}\n"); + doThrow(new RuntimeException("floci-duck execute returned HTTP 500")).when(duckClient) + .execute(anyString(), anyString(), isNull(), anyString()); + + assertThrows(RuntimeException.class, () -> exporter.export(task(), source, progress)); + + verify(s3Service, never()).putObject(eq("exports"), anyString(), any(), anyString(), any()); + verify(s3Service, never()).putObjectFromStream(eq("exports"), anyString(), any(), anyString(), any()); + verify(s3Service).deleteObject(STAGING, "rds-export/export-0123456789abcdef/1/part-0.ndjson"); + verify(s3Service).deleteObject(STAGING, "rds-export/export-0123456789abcdef/1/data.gz.parquet"); + verify(containerManager).discardExport("export-0123456789abcdef"); + } + + @Test + void aTableFinishedAfterAResetIsNotWrittenToTheExportBucket() { + tableRows("{\"id\":1}\n"); + AtomicBoolean reset = new AtomicBoolean(); + doAnswer(invocation -> { + reset.set(true); + return null; + }).when(duckClient).execute(anyString(), anyString(), isNull(), anyString()); + SnapshotExporter.Progress resetMidTable = new SnapshotExporter.Progress() { + @Override + public void extracting(int percent) { + } + + @Override + public boolean canceled() { + return reset.get(); + } + + @Override + public boolean abandonedByReset() { + return reset.get(); + } + }; + + exporter.export(task(), source, resetMidTable); + + verify(s3Service, never()).putObject(eq("exports"), anyString(), any(), anyString(), any()); + verify(s3Service, never()).putObjectFromStream(eq("exports"), anyString(), any(), anyString(), any()); + verify(s3Service).deleteObject(STAGING, "rds-export/export-0123456789abcdef/1/data.gz.parquet"); + } + + @Test + void aChunkWhoseUploadFailsIsStillRemovedFromStaging() { + tableRows("{\"id\":1}\n"); + doThrow(new IllegalStateException("staging bucket unavailable")).when(s3Service) + .putObject(eq(STAGING), eq("rds-export/export-0123456789abcdef/1/part-0.ndjson"), any(), anyString(), + any()); + + assertThrows(IllegalStateException.class, () -> exporter.export(task(), source, progress)); + + verify(s3Service).deleteObject(STAGING, "rds-export/export-0123456789abcdef/1/part-0.ndjson"); + } + + @Test + void theSuccessRecordIsWrittenAfterTheTablesRecord() { + tableRows("{\"id\":1}\n"); + + exporter.export(task(), source, progress); + + InOrder order = inOrder(s3Service); + order.verify(s3Service).putObject(eq("exports"), + eq("search/rds/appdb-export/export_tables_info_appdb-export_from_1_to_1.json"), any(), anyString(), any()); + order.verify(s3Service).putObject(eq("exports"), eq("search/rds/appdb-export/export_info_appdb-export.json"), + any(), anyString(), any()); + } + + @Test + void duckDbReadsARowLargerThanItsDefaultObjectSize() { + String largeRow = "{\"id\":\"" + + "x".repeat(PostgresSnapshotExporter.DUCKDB_DEFAULT_MAXIMUM_OBJECT_SIZE) + "\"}"; + tableRows("{\"id\":\"1\"}\n" + largeRow + "\n"); + + exporter.export(task(), source, progress); + + ArgumentCaptor setupSql = ArgumentCaptor.forClass(String.class); + verify(duckClient).execute(eq("SELECT 1 AS ok"), setupSql.capture(), isNull(), eq("000000000000")); + assertThat(setupSql.getValue(), containsString("maximum_object_size=" + (largeRow.length() + 1) + ",")); + } + + @Test + void duckDbKeepsItsDefaultObjectSizeForSmallRows() { + tableRows("{\"id\":1}\n"); + + exporter.export(task(), source, progress); + + ArgumentCaptor setupSql = ArgumentCaptor.forClass(String.class); + verify(duckClient).execute(eq("SELECT 1 AS ok"), setupSql.capture(), isNull(), eq("000000000000")); + assertThat(setupSql.getValue(), containsString( + "maximum_object_size=" + PostgresSnapshotExporter.DUCKDB_DEFAULT_MAXIMUM_OBJECT_SIZE + ",")); + } + + @Test + void anEmptyTableWritesNoFile() { + tableRows(""); + + exporter.export(task(), source, progress); + + verify(duckClient, never()).execute(anyString(), anyString(), any(), anyString()); + verify(s3Service, never()).putObjectFromStream(eq("exports"), anyString(), any(), anyString(), any()); + } + + @Test + void aTableInASchemaWithASlashIsSkippedWithAWarning() { + when(containerManager.queryPostgres(eq("restore-container"), eq("master"), eq("appdb"), + argThat(sql -> sql.contains("pg_attribute")))) + .thenReturn("{\"schema\":\"sales/eu\",\"table\":\"items\",\"column\":\"id\",\"type\":\"int4\"}\n"); + + SnapshotExporter.Outcome outcome = exporter.export(task(), source, progress); + + assertThat(outcome.warnings(), contains(containsString("appdb.sales/eu.items was skipped"))); + verify(s3Service, never()).putObjectFromStream(eq("exports"), anyString(), any(), anyString(), any()); + } + + @Test + void aTableWithColumnNamesDifferingOnlyInCaseIsSkippedWithAWarning() { + when(containerManager.queryPostgres(eq("restore-container"), eq("master"), eq("appdb"), + argThat(sql -> sql.contains("pg_attribute")))) + .thenReturn("{\"schema\":\"public\",\"table\":\"items\",\"column\":\"Foo\",\"type\":\"int4\"}\n" + + "{\"schema\":\"public\",\"table\":\"items\",\"column\":\"foo\",\"type\":\"text\"}\n"); + + SnapshotExporter.Outcome outcome = exporter.export(task(), source, progress); + + assertThat(outcome.warnings(), contains(containsString("appdb.public.items was skipped because two of its" + + " column names differ only in case"))); + verify(s3Service, never()).putObjectFromStream(eq("exports"), anyString(), any(), anyString(), any()); + } + + @Test + void aColumnOfATypeOfTheUsersOwnIsReadAsText() { + when(containerManager.queryPostgres(eq("restore-container"), eq("master"), eq("appdb"), + argThat(sql -> sql.contains("pg_attribute")))) + .thenReturn("{\"schema\":\"public\",\"table\":\"items\",\"column\":\"label\",\"type\":\"int4\"," + + "\"builtin\":false}\n"); + + exporter.export(task(), source, progress); + + verify(containerManager).queryPostgres(eq("restore-container"), eq("master"), eq("appdb"), + argThat(sql -> sql.startsWith("SELECT row_to_json(r) FROM (SELECT \"label\"::text AS \"label\" ")), + any(OutputStream.class), eq(PostgresSnapshotExporter.TABLE_READ_TIMEOUT_SECONDS)); + } + + @Test + void aTableInADatabaseWithASlashIsSkippedWithAWarning() { + when(containerManager.queryPostgres(eq("restore-container"), eq("master"), eq("postgres"), anyString())) + .thenReturn("\"app/db\"\n"); + when(containerManager.queryPostgres(eq("restore-container"), eq("master"), eq("app/db"), + argThat(sql -> sql.contains("pg_attribute")))) + .thenReturn("{\"schema\":\"public\",\"table\":\"items\",\"column\":\"id\",\"type\":\"int4\"}\n"); + + SnapshotExporter.Outcome outcome = exporter.export(task(), source, progress); + + assertThat(outcome.warnings(), contains(containsString("app/db.public.items was skipped"))); + verify(s3Service, never()).putObjectFromStream(eq("exports"), anyString(), any(), anyString(), any()); + } + + @Test + void anOrdinaryTableIsReadWithoutTheRowsOfTablesInheritingFromIt() { + tableRows("{\"id\":1}\n"); + + exporter.export(task(), source, progress); + + verify(containerManager).queryPostgres(eq("restore-container"), eq("master"), eq("appdb"), + argThat(sql -> sql.startsWith("SELECT row_to_json") && sql.contains(" FROM ONLY \"public\".\"items\")")), + any(OutputStream.class), eq(PostgresSnapshotExporter.TABLE_READ_TIMEOUT_SECONDS)); + } + + @Test + void aPartitionedTableIsReadThroughItsPartitions() { + when(containerManager.queryPostgres(eq("restore-container"), eq("master"), eq("appdb"), + argThat(sql -> sql.contains("pg_attribute")))) + .thenReturn("{\"schema\":\"public\",\"table\":\"items\",\"kind\":\"p\",\"column\":\"id\"," + + "\"type\":\"int4\"}\n"); + tableRows("{\"id\":1}\n"); + + exporter.export(task(), source, progress); + + verify(containerManager).queryPostgres(eq("restore-container"), eq("master"), eq("appdb"), + argThat(sql -> sql.startsWith("SELECT row_to_json") && sql.contains(" FROM \"public\".\"items\")")), + any(OutputStream.class), eq(PostgresSnapshotExporter.TABLE_READ_TIMEOUT_SECONDS)); + } + + @Test + void theVolumeIsRemovedAndTheRuntimeReleasedWhenStoppingTheContainerFails() { + tableRows("{\"id\":1}\n"); + doThrow(new IllegalStateException("Docker refused to stop the container")) + .when(containerManager).stop(any()); + + exporter.export(task(), source, progress); + + InOrder order = inOrder(containerManager); + order.verify(containerManager).discardExport("export-0123456789abcdef"); + order.verify(containerManager).stopByRuntimeId("arn:aws:rds:us-east-1:000000000000:export-task:appdb-export"); + } + + @Test + void theRuntimeIsStillReleasedWhenRemovingTheVolumeFailsAfterAFailedStop() { + tableRows("{\"id\":1}\n"); + doThrow(new IllegalStateException("Docker refused to stop the container")) + .when(containerManager).stop(any()); + doThrow(new IllegalStateException("Docker refused to remove the volume")) + .when(containerManager).discardExport(any()); + + exporter.export(task(), source, progress); + + verify(containerManager).stopByRuntimeId("arn:aws:rds:us-east-1:000000000000:export-task:appdb-export"); + } + + @Test + void theVolumeIsRemovedAndTheRuntimeReleasedWhenTheContainerNeverStarted() { + when(containerManager.startForExport(any(), any(), any(), any(), any(), any())) + .thenThrow(new IllegalStateException("image not found")); + + assertThrows(IllegalStateException.class, () -> exporter.export(task(), source, progress)); + + verify(containerManager, never()).stop(any()); + InOrder order = inOrder(containerManager); + order.verify(containerManager).discardExport("export-0123456789abcdef"); + order.verify(containerManager).stopByRuntimeId("arn:aws:rds:us-east-1:000000000000:export-task:appdb-export"); + } + + @Test + void theRestoreContainerTakesTheTasksRuntimeArnAndVolume() { + tableRows(""); + + exporter.export(task(), source, progress); + + verify(containerManager).startForExport("arn:aws:rds:us-east-1:000000000000:export-task:appdb-export", + "appdb-export", "export-0123456789abcdef", "postgres:16-alpine", "master", "secret"); + } + + @Test + void discardRemovesWhatARestartLeftBehind() { + exporter.discard(task()); + + verify(containerManager).discardExport("export-0123456789abcdef"); + } + + @Test + void aStagingBucketIsCreatedWhenMissing() { + when(s3Service.bucketExists(STAGING)).thenReturn(false); + tableRows("{\"id\":1}\n"); + + exporter.export(task(), source, progress); + + verify(s3Service).createBucket(STAGING, "us-east-1"); + } + + @Test + void theDumpIsRestoredBeforeAnythingIsRead() { + tableRows(""); + + exporter.export(task(), source, progress); + + verify(containerManager).restorePostgresSnapshot("restore-container", "master", "-- dump"); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/export/RdsExportTaskServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/export/RdsExportTaskServiceTest.java index b89d998c10..7291211dfe 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/export/RdsExportTaskServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/export/RdsExportTaskServiceTest.java @@ -142,19 +142,6 @@ class RdsExportTaskServiceTest { assertThat(failed.getTaskEndTime(), notNullValue()); } - @Test - void outsideMockModeATaskFailsUntilSnapshotDataCanBeWritten() { - RdsExportTaskService service = service(new UnsupportedSnapshotExporter()); - start(service, "appdb-export", List.of()); - - runWorkers(); - - ExportTask failed = describe(service, "appdb-export"); - assertThat(failed.getStatus(), equalTo("FAILED")); - assertThat(failed.getFailureCause(), equalTo(UnsupportedSnapshotExporter.FAILURE_CAUSE)); - assertThat(failed.getTaskEndTime(), equalTo(CLOCK.instant())); - } - @Test void aFailureWithoutAMessageStillReportsACause() { RdsExportTaskService service = service((task, source, progress) -> { diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/export/RdsSnapshotExportIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/export/RdsSnapshotExportIntegrationTest.java new file mode 100644 index 0000000000..12b4206fa5 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/rds/export/RdsSnapshotExportIntegrationTest.java @@ -0,0 +1,326 @@ +package io.github.hectorvent.floci.services.rds.export; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.InspectVolumeResponse; +import io.github.hectorvent.floci.services.floci.duck.FlociDuckClient; +import io.github.hectorvent.floci.services.s3.S3Service; +import io.github.hectorvent.floci.services.s3.model.S3Object; +import io.github.hectorvent.floci.testing.SidecarContainersProfile; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.RestAssured; +import jakarta.inject.Inject; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; +import org.postgresql.Driver; +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.rds.RdsClient; +import software.amazon.awssdk.services.rds.model.DBInstance; +import software.amazon.awssdk.services.rds.model.ExportTask; +import software.amazon.awssdk.services.rds.model.StartExportTaskResponse; + +import java.net.URI; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.UUID; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.matchesPattern; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +/** + * A PostgreSQL snapshot exported through the SDK, read back from Floci's S3 with DuckDB: the + * statuses the task reports, the object layout, and the Parquet type and value of each column + * against the RDS export mapping. + * + *

Needs Docker for the database and the floci-duck sidecar, and a sidecar that can reach + * Floci's S3 from its container, which is why it is opted into like {@code ParquetEmitterIntegrationTest}. + */ +@QuarkusTest +@TestProfile(SidecarContainersProfile.class) +@Tag("docker") +@EnabledIfEnvironmentVariable(named = "FLOCI_DUCK_CROSS_CONTAINER_TEST", matches = "1|true|yes") +class RdsSnapshotExportIntegrationTest { + + private static final String MASTER_USER = "master"; + private static final String MASTER_PASSWORD = "Master123!"; + + @Inject + DockerClient dockerClient; + + @Inject + S3Service s3Service; + + @Inject + FlociDuckClient duckClient; + + @BeforeEach + void checkDocker() { + try { + dockerClient.pingCmd().exec(); + } catch (Exception e) { + assumeTrue(false, "Docker is not available: " + e.getMessage()); + } + } + + @Test + void snapshotTablesAreExportedAsParquetInTheRdsLayout() throws Exception { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String dbId = "export-src-" + suffix; + String bucket = "rds-export-" + suffix; + String taskId = "export-" + suffix; + s3Service.createBucket(bucket, "us-east-1"); + try (RdsClient rds = rdsClient()) { + DBInstance instance = rds.createDBInstance(request -> request + .dbInstanceIdentifier(dbId) + .engine("postgres") + .masterUsername(MASTER_USER) + .masterUserPassword(MASTER_PASSWORD) + .dbName("appdb") + .allocatedStorage(20) + .dbInstanceClass("db.t3.micro")).dbInstance(); + try { + asMaster(instance.endpoint().port(), + "CREATE TABLE items (id int PRIMARY KEY, small int2, big int8, ratio float8, flag bool, " + + "name text, price numeric(10,2), created_at timestamptz, attrs jsonb, " + + "tags uuid[], payload bytea)", + "INSERT INTO items VALUES (1, 7, 9000000000, 0.5, true, 'first', 12.30, " + + "'2026-10-13 10:00:00+02', '{\"color\": \"red\"}', " + + "'{6f1c2d34-1a2b-4c3d-8e9f-0a1b2c3d4e5f}', '\\xdeadbeef')", + "INSERT INTO items (id, name) VALUES (2, 'second')", + "CREATE TABLE empty_items (id int PRIMARY KEY)", + "CREATE TABLE left_out (id int PRIMARY KEY)", + "INSERT INTO left_out VALUES (1)"); + + String snapshotArn = rds.createDBSnapshot(request -> request + .dbInstanceIdentifier(dbId) + .dbSnapshotIdentifier(dbId + "-snap")).dbSnapshot().dbSnapshotArn(); + asMaster(instance.endpoint().port(), "INSERT INTO items (id, name) VALUES (3, 'after the snapshot')"); + + StartExportTaskResponse started = rds.startExportTask(request -> request + .exportTaskIdentifier(taskId) + .sourceArn(snapshotArn) + .s3BucketName(bucket) + .s3Prefix("exports/rds") + .iamRoleArn("arn:aws:iam::000000000000:role/export") + .kmsKeyId("alias/export") + .exportOnly("appdb.public.items", "appdb.public.empty_items")); + assertThat(started.status(), equalTo("STARTING")); + assertThat(started.exportOnly(), containsInAnyOrder("appdb.public.items", "appdb.public.empty_items")); + + ExportTask finished = awaitTerminal(rds, taskId); + assertThat(finished.failureCause(), finished.status(), equalTo("COMPLETE")); + assertThat(finished.percentProgress(), equalTo(100)); + assertThat(finished.sourceArn(), equalTo(snapshotArn)); + assertThat(finished.sourceTypeAsString(), equalTo("SNAPSHOT")); + assertThat("the container the snapshot was restored into is removed", + dockerClient.listContainersCmd().withShowAll(true) + .withLabelFilter(Map.of("io.floci.resource-id", taskId)).exec(), empty()); + assertThat("its volume is removed", dockerClient.listVolumesCmd().exec().getVolumes().stream() + .map(InspectVolumeResponse::getName) + .filter(name -> name.contains("rds-export-")).toList(), empty()); + assertThat("nothing is left in the staging bucket", + s3Service.listObjects("floci-rds-export-staging", "rds-export/", null, 1000), empty()); + + List keys = s3Service.listObjects(bucket, "exports/rds/" + taskId + "/", null, 1000) + .stream().map(S3Object::getKey).toList(); + assertThat(keys, hasSize(3)); + assertThat(keys, hasItem("exports/rds/" + taskId + "/export_info_" + taskId + ".json")); + assertThat(keys, hasItem("exports/rds/" + taskId + "/export_tables_info_" + taskId + + "_from_1_to_2.json")); + String dataKey = keys.stream().filter(key -> key.endsWith(".parquet")).findFirst().orElseThrow(); + assertThat(dataKey, matchesPattern("exports/rds/" + taskId + + "/appdb/public\\.items/1/part-00000-[0-9a-f-]{36}\\.gz\\.parquet")); + + String parquet = "read_parquet('s3://" + bucket + "/" + dataKey + "')"; + Map types = Map.of( + "id", "INTEGER", "small", "SMALLINT", "big", "BIGINT", "ratio", "DOUBLE", + "flag", "BOOLEAN", "name", "VARCHAR", "price", "VARCHAR", "created_at", "VARCHAR", + "attrs", "VARCHAR", "tags", "VARCHAR"); + for (Map column : duckClient.query("DESCRIBE SELECT * FROM " + parquet, null)) { + String name = (String) column.get("column_name"); + String expected = "payload".equals(name) ? "BLOB" : types.get(name); + assertThat(name, column.get("column_type"), equalTo(expected)); + } + + List> rows = duckClient.query("SELECT id, small, big, ratio, flag, name, " + + "price, created_at, attrs, tags, hex(payload) AS payload FROM " + parquet + " ORDER BY id", + null); + assertThat(rows, hasSize(2)); + Map first = rows.get(0); + assertEquals(1, ((Number) first.get("id")).intValue()); + assertEquals(7, ((Number) first.get("small")).intValue()); + assertEquals(9_000_000_000L, ((Number) first.get("big")).longValue()); + assertEquals(0.5, ((Number) first.get("ratio")).doubleValue()); + assertEquals(true, first.get("flag")); + assertEquals("first", first.get("name")); + assertEquals("12.30", first.get("price")); + assertEquals("2026-10-13 08:00:00+00", first.get("created_at")); + assertEquals("{\"color\": \"red\"}", first.get("attrs")); + assertEquals("{6f1c2d34-1a2b-4c3d-8e9f-0a1b2c3d4e5f}", first.get("tags")); + assertEquals("DEADBEEF", first.get("payload")); + assertEquals("second", rows.get(1).get("name")); + } finally { + rds.deleteDBInstance(request -> request.dbInstanceIdentifier(dbId).skipFinalSnapshot(true)); + } + } + } + + @Test + void anInheritanceParentAndItsChildEachExportOnlyTheirOwnRows() throws Exception { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String dbId = "export-inh-" + suffix; + String bucket = "rds-export-" + suffix; + String taskId = "export-" + suffix; + s3Service.createBucket(bucket, "us-east-1"); + try (RdsClient rds = rdsClient()) { + DBInstance instance = rds.createDBInstance(request -> request + .dbInstanceIdentifier(dbId) + .engine("postgres") + .masterUsername(MASTER_USER) + .masterUserPassword(MASTER_PASSWORD) + .dbName("appdb") + .allocatedStorage(20) + .dbInstanceClass("db.t3.micro")).dbInstance(); + try { + asMaster(instance.endpoint().port(), + "CREATE TABLE events (id int)", + "CREATE TABLE late_events () INHERITS (events)", + "INSERT INTO events VALUES (1)", + "INSERT INTO late_events VALUES (2)"); + String snapshotArn = rds.createDBSnapshot(request -> request + .dbInstanceIdentifier(dbId) + .dbSnapshotIdentifier(dbId + "-snap")).dbSnapshot().dbSnapshotArn(); + + rds.startExportTask(request -> request + .exportTaskIdentifier(taskId) + .sourceArn(snapshotArn) + .s3BucketName(bucket) + .iamRoleArn("arn:aws:iam::000000000000:role/export") + .kmsKeyId("alias/export") + .exportOnly("appdb.public.events", "appdb.public.late_events")); + ExportTask finished = awaitTerminal(rds, taskId); + assertThat(finished.failureCause(), finished.status(), equalTo("COMPLETE")); + + for (Map.Entry table : Map.of("events", 1, "late_events", 2).entrySet()) { + String dataKey = s3Service.listObjects(bucket, taskId + "/appdb/public." + table.getKey() + "/", + null, 1000).stream().map(S3Object::getKey).findFirst().orElseThrow(); + List> rows = duckClient.query( + "SELECT id FROM read_parquet('s3://" + bucket + "/" + dataKey + "')", null); + assertThat(table.getKey(), rows, hasSize(1)); + assertEquals(table.getValue(), ((Number) rows.getFirst().get("id")).intValue()); + } + } finally { + rds.deleteDBInstance(request -> request.dbInstanceIdentifier(dbId).skipFinalSnapshot(true)); + } + } + } + + @Test + void aTypeOfTheUsersOwnIsExportedAsTextAndCaseCollidingColumnsSkipTheirTable() throws Exception { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String dbId = "export-case-" + suffix; + String bucket = "rds-export-" + suffix; + String taskId = "export-" + suffix; + s3Service.createBucket(bucket, "us-east-1"); + try (RdsClient rds = rdsClient()) { + DBInstance instance = rds.createDBInstance(request -> request + .dbInstanceIdentifier(dbId) + .engine("postgres") + .masterUsername(MASTER_USER) + .masterUserPassword(MASTER_PASSWORD) + .dbName("appdb") + .allocatedStorage(20) + .dbInstanceClass("db.t3.micro")).dbInstance(); + try { + asMaster(instance.endpoint().port(), + "CREATE DOMAIN public.int4 AS text", + "CREATE TABLE labelled (id int, label public.int4)", + "INSERT INTO labelled VALUES (7, 'not a number')", + "CREATE TABLE mixed (\"Foo\" int, \"foo\" text)", + "INSERT INTO mixed VALUES (7, 'seven')"); + String snapshotArn = rds.createDBSnapshot(request -> request + .dbInstanceIdentifier(dbId) + .dbSnapshotIdentifier(dbId + "-snap")).dbSnapshot().dbSnapshotArn(); + + rds.startExportTask(request -> request + .exportTaskIdentifier(taskId) + .sourceArn(snapshotArn) + .s3BucketName(bucket) + .iamRoleArn("arn:aws:iam::000000000000:role/export") + .kmsKeyId("alias/export") + .exportOnly("appdb.public.labelled", "appdb.public.mixed")); + ExportTask finished = awaitTerminal(rds, taskId); + assertThat(finished.failureCause(), finished.status(), equalTo("COMPLETE")); + assertThat(finished.warningMessage(), containsString("appdb.public.mixed was skipped")); + assertThat(s3Service.listObjects(bucket, taskId + "/appdb/public.mixed/", null, 1000), hasSize(0)); + + String dataKey = s3Service.listObjects(bucket, taskId + "/appdb/public.labelled/", null, 1000) + .stream().map(S3Object::getKey).findFirst().orElseThrow(); + List> rows = duckClient.query( + "SELECT typeof(id) AS id_type, typeof(label) AS label_type, label FROM read_parquet('s3://" + + bucket + "/" + dataKey + "')", null); + assertThat(rows, hasSize(1)); + assertEquals("INTEGER", rows.getFirst().get("id_type")); + assertEquals("VARCHAR", rows.getFirst().get("label_type")); + assertEquals("not a number", rows.getFirst().get("label")); + } finally { + rds.deleteDBInstance(request -> request.dbInstanceIdentifier(dbId).skipFinalSnapshot(true)); + } + } + } + + private static ExportTask awaitTerminal(RdsClient rds, String taskId) throws InterruptedException { + Instant deadline = Instant.now().plus(Duration.ofMinutes(3)); + while (true) { + ExportTask task = rds.describeExportTasks(request -> request.exportTaskIdentifier(taskId)) + .exportTasks().getFirst(); + if (List.of("COMPLETE", "FAILED", "CANCELED").contains(task.status()) || Instant.now().isAfter(deadline)) { + return task; + } + Thread.sleep(1_000); + } + } + + private static RdsClient rdsClient() { + return RdsClient.builder() + .endpointOverride(URI.create("http://localhost:" + RestAssured.port)) + .httpClientBuilder(UrlConnectionHttpClient.builder()) + .region(Region.US_EAST_1) + .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test"))) + .build(); + } + + private static void asMaster(int port, String... statements) throws SQLException { + Properties master = new Properties(); + master.setProperty("user", MASTER_USER); + master.setProperty("password", MASTER_PASSWORD); + master.setProperty("sslmode", "disable"); + // The driver itself rather than DriverManager, which does not see it from a test profile's + // class loader once another profile has run. + try (Connection connection = new Driver().connect("jdbc:postgresql://127.0.0.1:" + port + "/appdb", master); + Statement statement = connection.createStatement()) { + for (String sql : statements) { + statement.execute(sql); + } + } + } +}