feat(rds): export DB snapshots to S3 as Parquet (#7289)

This commit is contained in:
Simon Claessens authored and GitHub committed 2026-11-02 08:34:19 -04:00
1 parent b92340b243
commit b65755da3a
14 files changed
+1615 -64

No files matched your search

@@ -1820,6 +1820,13 @@ public interface EmulatorConfig {
/** Empty when Floci should adapt its built-in image to the requested engine version. */
Optional<String> 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<String> defaultMysqlImage();
@@ -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<String, String> 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<String, String> 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<String> 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";
@@ -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 <a href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_ExportSnapshot.data-types.html">
* Data conversion when exporting to an Amazon S3 bucket</a>
*/
record ExportColumn(String name, String pgType, boolean builtIn) {
ExportColumn(String name, String pgType) {
this(name, pgType, true);
}
private static final Map<String, String> NATIVE_DUCK_TYPES = Map.of(
"int2", "SMALLINT",
"int4", "INTEGER",
"int8", "BIGINT",
"float4", "FLOAT",
"float8", "DOUBLE",
"bool", "BOOLEAN");
private static final Map<String, String> 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 <a href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_ExportSnapshot.html#USER_ExportSnapshot.Limits">
* Limitations</a>
*/
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("\"", "\"\"") + "\"";
}
}
@@ -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 <S3Prefix>/<task>/<database>/<schema>.<table>/<batch>/}, named
* {@code part-<partition>-<uuid>.gz.parquet}, and the task's own description sits at
* {@code <S3Prefix>/<task>/}. Floci reads each table in one batch and one partition.
*
* @see <a href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_ExportSnapshot.FileNames.html">
* File naming conventions for exports to Amazon S3</a>
*/
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);
}
}
@@ -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.
*
* <p>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<ExportColumn> 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<String> warnings = new ArrayList<>();
List<Table> 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<Table> tables(String containerId, SnapshotExportSource source, String database) {
Map<String, Table> 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<String> 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<String> extract = new ArrayList<>();
List<String> write = new ArrayList<>();
List<String> 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<String> 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<String> 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<String> 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<String> jsonLines(String output) {
List<String> 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("'", "''");
}
}
@@ -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<Map<String, ExportTask>>() {}),
@@ -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);
}
}