feat(redshift): restore a single table from a snapshot (#8290)

Add RestoreTableFromClusterSnapshot and DescribeTableRestoreStatus for
provisioned clusters, and RestoreTableFromSnapshot, GetTableRestoreStatus
and ListTableRestoreStatus for Redshift Serverless. The table's CREATE TABLE
statement and rows are lifted out of the snapshot dump, renamed, and
replayed in one transaction. The restore runs inside the request, so a
described request is already SUCCEEDED or FAILED.

The name checks, script, pending copy, replay and status of a table restore
live once in RedshiftTableRestorer, and both services keep only their
lookups and storage. ListTableRestoreStatus answers a bad nextToken with
InvalidPaginationException. A Docker backed integration test writes rows,
snapshots, restores under a new name and reads them back, connecting through
RedshiftConnections, and the Redshift compatibility tests share one
TestFixtures.awaitRedshiftConnection.

Closes #7806
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-14 20:43:18 -04:00
1 parent d65e76b7ea
commit 2d85e4ea3b
28 files changed
+1909 -61

No files matched your search

@@ -21,6 +21,7 @@ import io.floci.aws.services.redshift.model.ScheduledAction;
import io.floci.aws.services.redshift.model.Snapshot;
import io.floci.aws.services.redshift.model.SnapshotCopyGrant;
import io.floci.aws.services.redshift.model.SnapshotSchedule;
import io.floci.aws.services.redshift.model.TableRestoreStatus;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.MediaType;
@@ -66,6 +67,7 @@ public class RedshiftQueryHandler {
private final IamEnforcementFilter iamEnforcementFilter;
private final RedshiftResourcePolicies resourcePolicies;
private final RedshiftScheduledActionService scheduledActions;
private final RedshiftTableRestoreService tableRestores;
@Inject
public RedshiftQueryHandler(RedshiftService service, RedshiftCredentialBroker credentialBroker,
@@ -74,7 +76,8 @@ public class RedshiftQueryHandler {
RedshiftDynamoDbZeroEtlConsumer zeroEtlConsumer,
IamEnforcementFilter iamEnforcementFilter,
RedshiftResourcePolicies resourcePolicies,
RedshiftScheduledActionService scheduledActions) {
RedshiftScheduledActionService scheduledActions,
RedshiftTableRestoreService tableRestores) {
this.service = service;
this.credentialBroker = credentialBroker;
this.config = config;
@@ -84,12 +87,13 @@ public class RedshiftQueryHandler {
this.iamEnforcementFilter = iamEnforcementFilter;
this.resourcePolicies = resourcePolicies;
this.scheduledActions = scheduledActions;
this.tableRestores = tableRestores;
}
RedshiftQueryHandler(RedshiftService service, RedshiftCredentialBroker credentialBroker,
EmulatorConfig config, RedshiftIamDbUserResolver iamDbUserResolver,
RegionResolver regionResolver) {
this(service, credentialBroker, config, iamDbUserResolver, regionResolver, null, null, null, null);
this(service, credentialBroker, config, iamDbUserResolver, regionResolver, null, null, null, null, null);
}
public Response handle(String action, MultivaluedMap<String, String> params) {
@@ -335,6 +339,49 @@ public class RedshiftQueryHandler {
.build();
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
}
case "RestoreTableFromClusterSnapshot" -> {
TableRestoreStatus status = tableRestores.restoreTable(new RedshiftTableRestoreService.Request(
requireParam(params, "ClusterIdentifier"), requireParam(params, "SnapshotIdentifier"),
requireParam(params, "SourceDatabaseName"), params.getFirst("SourceSchemaName"),
requireParam(params, "SourceTableName"), params.getFirst("TargetDatabaseName"),
params.getFirst("TargetSchemaName"), requireParam(params, "NewTableName"),
Boolean.TRUE.equals(booleanParam(params, "EnableCaseSensitiveIdentifier"))));
String xml = new XmlBuilder()
.start("RestoreTableFromClusterSnapshotResponse")
.start("RestoreTableFromClusterSnapshotResult")
.raw(tableRestoreStatusXml(status))
.end("RestoreTableFromClusterSnapshotResult")
.start("ResponseMetadata")
.elem("RequestId", "test-req-id")
.end("ResponseMetadata")
.end("RestoreTableFromClusterSnapshotResponse")
.build();
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
}
case "DescribeTableRestoreStatus" -> {
PaginatedResult<TableRestoreStatus> page = tableRestores.describeTableRestoreStatus(
params.getFirst("ClusterIdentifier"), params.getFirst("TableRestoreRequestId"),
intParam(params, "MaxRecords"), params.getFirst("Marker"));
XmlBuilder xml = new XmlBuilder()
.start("DescribeTableRestoreStatusResponse")
.start("DescribeTableRestoreStatusResult")
.start("TableRestoreStatusDetails");
for (TableRestoreStatus status : page.items()) {
xml.raw(tableRestoreStatusXml(status));
}
xml.end("TableRestoreStatusDetails");
if (page.nextToken() != null) {
xml.elem("Marker", page.nextToken());
}
String body = xml
.end("DescribeTableRestoreStatusResult")
.start("ResponseMetadata")
.elem("RequestId", "test-req-id")
.end("ResponseMetadata")
.end("DescribeTableRestoreStatusResponse")
.build();
return Response.ok(body).type(MediaType.APPLICATION_XML).build();
}
case "CreateClusterParameterGroup" -> {
String parameterGroupName = params.getFirst("ParameterGroupName");
String parameterGroupFamily = params.getFirst("ParameterGroupFamily");
@@ -1722,6 +1769,30 @@ public class RedshiftQueryHandler {
.end("Event").build();
}
private static String tableRestoreStatusXml(TableRestoreStatus status) {
XmlBuilder xml = new XmlBuilder().start("TableRestoreStatus")
.elem("TableRestoreRequestId", status.getTableRestoreRequestId())
.elem("Status", status.getStatus())
.elem("Message", status.getMessage())
.elem("RequestTime", status.getRequestTime() == null ? null
: DateTimeFormatter.ISO_INSTANT.format(status.getRequestTime()))
.elem("ClusterIdentifier", status.getClusterIdentifier())
.elem("SnapshotIdentifier", status.getSnapshotIdentifier())
.elem("SourceDatabaseName", status.getSourceDatabaseName())
.elem("SourceSchemaName", status.getSourceSchemaName())
.elem("SourceTableName", status.getSourceTableName())
.elem("TargetDatabaseName", status.getTargetDatabaseName())
.elem("TargetSchemaName", status.getTargetSchemaName())
.elem("NewTableName", status.getNewTableName());
if (status.getProgressInMegaBytes() != null) {
xml.elem("ProgressInMegaBytes", status.getProgressInMegaBytes());
}
if (status.getTotalDataInMegaBytes() != null) {
xml.elem("TotalDataInMegaBytes", status.getTotalDataInMegaBytes());
}
return xml.end("TableRestoreStatus").build();
}
private static Boolean booleanParam(MultivaluedMap<String, String> params, String name) {
String raw = params.getFirst(name);
if (raw == null || raw.isBlank()) {
@@ -2493,6 +2493,40 @@ public class RedshiftService implements ManagedSecretRotator {
return snapshot;
}
/** Whether the caller's account has a cluster named {@code identifier}. */
public boolean hasCluster(String identifier) {
return clusters.get(identifier).isPresent();
}
/** What a table restore reads from and writes into: the cluster, the snapshot dump and the database it covers. */
public record TableRestoreSource(Cluster cluster, Path dump, String database) {
}
/**
* Resolves the cluster and the snapshot of it a table is restored from. Like AWS, the snapshot must have been
* taken from the cluster, and both must be available.
*/
public TableRestoreSource tableRestoreSource(String clusterIdentifier, String snapshotIdentifier) {
Cluster cluster = clusters.get(clusterIdentifier).orElseThrow(
() -> new AwsException("ClusterNotFound", "Cluster " + clusterIdentifier + " not found", 404));
Snapshot snapshot = findSnapshot(snapshotIdentifier)
.filter(found -> clusterIdentifier.equals(found.getClusterIdentifier()))
.filter(this::isInRequestRegion)
.orElseThrow(() -> new AwsException("ClusterSnapshotNotFound",
"Snapshot " + snapshotIdentifier + " not found", 404));
if (!"available".equals(cluster.getClusterStatus())) {
throw new AwsException("InvalidClusterState",
"Cluster " + clusterIdentifier + " is not in the available state.", 400);
}
String sqlDump = snapshot.getSqlDump();
if (!"available".equals(snapshot.getStatus()) || !isTrustedDumpPath(sqlDump)
|| !Files.exists(Paths.get(sqlDump))) {
throw new AwsException("InvalidClusterSnapshotState",
"Snapshot " + snapshotIdentifier + " is not in the available state.", 400);
}
return new TableRestoreSource(cluster, Paths.get(sqlDump), CLUSTER_DB_NAME);
}
public Cluster restoreFromClusterSnapshot(String clusterIdentifier, String snapshotIdentifier) {
return restoreFromClusterSnapshot(clusterIdentifier, snapshotIdentifier, null);
}
@@ -0,0 +1,165 @@
package io.floci.aws.services.redshift;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* Builds the SQL that restores one table of a snapshot into a live database under another name. A
* snapshot is a plain {@code pg_dump} script, so the table's {@code CREATE TABLE} statement and its
* {@code COPY} data block are lifted out of it and renamed. Only the table's definition and rows are
* restored: constraints, defaults that reference a sequence and ownership are not carried over.
*/
public final class RedshiftSnapshotTableExtractor {
private static final List<String> CREATE_TABLE_PREFIXES = List.of("CREATE TABLE ", "CREATE UNLOGGED TABLE ");
private static final String PARTITIONED = "PARTITION BY ";
private static final String COPY = "COPY ";
private static final String COPY_END = "\\.";
private RedshiftSnapshotTableExtractor() {
}
/** The table is of a kind a restore cannot carry over whole, such as a partitioned one whose rows live elsewhere. */
public static final class UnsupportedTableException extends RuntimeException {
public UnsupportedTableException(String message) {
super(message);
}
}
/**
* The script that creates {@code targetSchema.targetTable} from {@code sourceSchema.sourceTable} of the
* dump, or empty when the dump has no such table. Names match ignoring case unless {@code caseSensitive}.
*/
public static Optional<String> restoreScript(Path dump, String sourceSchema, String sourceTable,
String targetSchema, String targetTable,
boolean caseSensitive) throws IOException {
List<String> create = new ArrayList<>();
List<String> data = new ArrayList<>();
boolean inCreate = false;
boolean inCopy = false;
boolean copyMatches = false;
try (BufferedReader reader = Files.newBufferedReader(dump, StandardCharsets.UTF_8)) {
String line;
while ((line = reader.readLine()) != null) {
if (inCopy) {
if (copyMatches) {
data.add(line);
}
if (line.equals(COPY_END)) {
inCopy = false;
copyMatches = false;
}
continue;
}
if (inCreate) {
create.add(line);
if (line.endsWith(";")) {
inCreate = false;
}
continue;
}
String createPrefix = create.isEmpty() ? createPrefix(line) : null;
if (createPrefix != null) {
QualifiedName name = QualifiedName.parse(line, createPrefix.length());
if (name != null && name.matches(sourceSchema, sourceTable, caseSensitive)) {
create.add(createPrefix + quote(targetSchema) + "." + quote(targetTable)
+ line.substring(name.end()));
inCreate = !line.endsWith(";");
}
} else if (line.startsWith(COPY) && line.endsWith(" FROM stdin;")) {
inCopy = true;
QualifiedName name = QualifiedName.parse(line, COPY.length());
if (name != null && name.matches(sourceSchema, sourceTable, caseSensitive) && data.isEmpty()) {
copyMatches = true;
data.add(COPY + quote(targetSchema) + "." + quote(targetTable) + line.substring(name.end()));
}
}
}
}
if (create.isEmpty()) {
return Optional.empty();
}
if (create.stream().anyMatch(statement -> statement.stripLeading().startsWith(PARTITIONED)
|| statement.contains(") " + PARTITIONED))) {
throw new UnsupportedTableException("The table " + sourceSchema + "." + sourceTable
+ " is partitioned, and its rows are stored in its partitions, which cannot be restored with it.");
}
StringBuilder script = new StringBuilder("BEGIN;\n");
create.forEach(statement -> script.append(statement).append('\n'));
data.forEach(row -> script.append(row).append('\n'));
return Optional.of(script.append("COMMIT;\n").toString());
}
private static String createPrefix(String line) {
for (String prefix : CREATE_TABLE_PREFIXES) {
if (line.startsWith(prefix)) {
return prefix;
}
}
return null;
}
/** The identifier as a quoted one, so a name with spaces, quotes or capitals reaches Postgres unchanged. */
static String quote(String identifier) {
return '"' + identifier.replace("\"", "\"\"") + '"';
}
/** A {@code schema.table} name as pg_dump writes it, quoted when it needs to be, and where it ends. */
private record QualifiedName(String schema, String table, int end) {
static QualifiedName parse(String line, int from) {
Part schema = part(line, from);
if (schema == null || schema.end() >= line.length() || line.charAt(schema.end()) != '.') {
return null;
}
Part table = part(line, schema.end() + 1);
return table == null ? null : new QualifiedName(schema.value(), table.value(), table.end());
}
boolean matches(String sourceSchema, String sourceTable, boolean caseSensitive) {
return caseSensitive
? schema.equals(sourceSchema) && table.equals(sourceTable)
: schema.equalsIgnoreCase(sourceSchema) && table.equalsIgnoreCase(sourceTable);
}
private record Part(String value, int end) {
}
private static Part part(String line, int from) {
if (from >= line.length()) {
return null;
}
StringBuilder value = new StringBuilder();
int index = from;
if (line.charAt(index) == '"') {
index++;
while (index < line.length()) {
char c = line.charAt(index);
if (c == '"') {
if (index + 1 < line.length() && line.charAt(index + 1) == '"') {
value.append('"');
index += 2;
continue;
}
return new Part(value.toString(), index + 1);
}
value.append(c);
index++;
}
return null;
}
while (index < line.length() && (Character.isLetterOrDigit(line.charAt(index))
|| line.charAt(index) == '_' || line.charAt(index) == '$')) {
value.append(line.charAt(index));
index++;
}
return value.isEmpty() ? null : new Part(value.toString(), index);
}
}
}
@@ -0,0 +1,127 @@
package io.floci.aws.services.redshift;
import com.fasterxml.jackson.core.type.TypeReference;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.Pagination;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.Resettable;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.redshift.RedshiftService.TableRestoreSource;
import io.floci.aws.services.redshift.RedshiftTableRestorer.TableNames;
import io.floci.aws.services.redshift.model.TableRestoreStatus;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.time.Clock;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
/**
* Restores one table of a provisioned cluster's snapshot into the cluster under a new name, and keeps the
* status of each request. The restore runs inside the request, so a request that was accepted has already
* ended in {@code SUCCEEDED} or {@code FAILED} when it is next described; the response to the request itself
* shows it as {@code PENDING}, as AWS does.
*/
@ApplicationScoped
public class RedshiftTableRestoreService implements Resettable {
private static final int MIN_MAX_RECORDS = 20;
private static final int MAX_MAX_RECORDS = 100;
private final AccountAwareStorageBackend<TableRestoreStatus> restores;
private final RedshiftService redshift;
private final RedshiftTableRestorer restorer;
private final RegionResolver regionResolver;
private final Clock clock;
@Inject
public RedshiftTableRestoreService(StorageFactory storageFactory, RedshiftService redshift,
RedshiftTableRestorer restorer, RegionResolver regionResolver, Clock clock) {
this.restores = storageFactory.create("redshift", "redshift-table-restores.json",
new TypeReference<Map<String, TableRestoreStatus>>() {});
this.redshift = redshift;
this.restorer = restorer;
this.regionResolver = regionResolver;
this.clock = clock;
}
/** The members a {@code RestoreTableFromClusterSnapshot} request carries. */
public record Request(String clusterIdentifier, String snapshotIdentifier, String sourceDatabaseName,
String sourceSchemaName, String sourceTableName, String targetDatabaseName,
String targetSchemaName, String newTableName, boolean caseSensitive) {
}
public TableRestoreStatus restoreTable(Request request) {
return redshift.withResourceLock(regionResolver.getAccountId(), "cluster", request.clusterIdentifier(),
() -> restore(request));
}
private TableRestoreStatus restore(Request request) {
TableRestoreSource source = redshift.tableRestoreSource(request.clusterIdentifier(),
request.snapshotIdentifier());
TableNames names = new TableNames(request.sourceDatabaseName(), request.sourceSchemaName(),
request.sourceTableName(), request.targetDatabaseName(), request.targetSchemaName(),
request.newTableName(), request.caseSensitive());
return restorer.restore(names, source.dump(), new RedshiftTableRestorer.Backend(regionResolver.getAccountId(),
request.clusterIdentifier(), source.cluster().getMasterUsername(), source.database()),
clock.instant(), RedshiftTableRestoreService::invalidArgument, status -> {
status.setClusterIdentifier(request.clusterIdentifier());
status.setSnapshotIdentifier(request.snapshotIdentifier());
}, status -> restores.put(status.getTableRestoreRequestId(), status));
}
/**
* The status of the cluster's restore requests in the order they were made, or of the one request given.
* Without a cluster every cluster of the account is listed.
*/
public PaginatedResult<TableRestoreStatus> describeTableRestoreStatus(
String clusterIdentifier, String tableRestoreRequestId, Integer maxRecords, String marker) {
int limit = maxRecords == null ? MAX_MAX_RECORDS : maxRecords;
if (limit < MIN_MAX_RECORDS || limit > MAX_MAX_RECORDS) {
throw new AwsException("InvalidParameterValue",
"MaxRecords must be between " + MIN_MAX_RECORDS + " and " + MAX_MAX_RECORDS + ".", 400);
}
if (clusterIdentifier != null) {
redshift.describeClusters(clusterIdentifier);
}
List<TableRestoreStatus> matching = liveRestores().stream()
.filter(restore -> clusterIdentifier == null || clusterIdentifier.equals(restore.getClusterIdentifier()))
.filter(restore -> tableRestoreRequestId == null
|| tableRestoreRequestId.equals(restore.getTableRestoreRequestId()))
.sorted(Comparator.comparing(TableRestoreStatus::getRequestTime)
.thenComparing(TableRestoreStatus::getTableRestoreRequestId))
.map(TableRestoreStatus::new)
.toList();
if (tableRestoreRequestId != null && matching.isEmpty()) {
throw new AwsException("TableRestoreNotFoundFault",
"The table restore request " + tableRestoreRequestId + " was not found.", 400);
}
return Pagination.paginate(matching, TableRestoreStatus::getTableRestoreRequestId, limit, marker,
"redshift-table-restore", token -> new AwsException("InvalidParameterValue", "Invalid Marker.", 400));
}
/** The account's restore requests whose cluster is still there; those of a deleted one are dropped as found. */
private List<TableRestoreStatus> liveRestores() {
return restores.scan(key -> true).stream()
.filter(restore -> {
if (redshift.hasCluster(restore.getClusterIdentifier())) {
return true;
}
restores.delete(restore.getTableRestoreRequestId());
return false;
})
.toList();
}
@Override
public void clear() {
restores.clear();
}
private static AwsException invalidArgument(String message) {
return new AwsException("InvalidTableRestoreArgument", message, 400);
}
}
@@ -0,0 +1,217 @@
package io.floci.aws.services.redshift;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.redshift.container.RedshiftContainerManager;
import io.floci.aws.services.redshift.model.TableRestoreStatus;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.Locale;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* Restores one table of a snapshot dump into a running backend, for Redshift and Redshift Serverless alike.
* The caller decides what an unknown source table means, since the two APIs report it differently.
*/
@ApplicationScoped
public class RedshiftTableRestorer {
private static final Logger LOG = Logger.getLogger(RedshiftTableRestorer.class);
private final RedshiftContainerManager containerManager;
@Inject
public RedshiftTableRestorer(RedshiftContainerManager containerManager) {
this.containerManager = containerManager;
}
private static final long MEGABYTE = 1024L * 1024L;
/**
* The names of one table restore request. They are case insensitive unless the request says otherwise, which
* Postgres folds to lower case; {@code applyTo} reports them as the request gave them.
*/
public record TableNames(String sourceDatabaseName, String sourceSchemaName, String sourceTableName,
String targetDatabaseName, String targetSchemaName, String newTableName,
boolean caseSensitive) {
public String sourceDatabase() {
return fold(sourceDatabaseName);
}
public String sourceSchema() {
return fold(orDefault(sourceSchemaName, "public"));
}
public String sourceTable() {
return fold(sourceTableName);
}
public String targetDatabase() {
return fold(orDefault(targetDatabaseName, sourceDatabaseName));
}
public String targetSchema() {
return fold(orDefault(targetSchemaName, sourceSchema()));
}
public String newTable() {
return fold(newTableName);
}
/** Whether {@code actual}, the one database of the backend, is the source database the request names. */
public boolean sourceDatabaseIs(String actual) {
return sourceDatabase().equals(fold(actual));
}
/** Whether {@code actual}, the one database of the backend, is the target database the request names. */
public boolean targetDatabaseIs(String actual) {
return targetDatabase().equals(fold(actual));
}
public void applyTo(TableRestoreStatus status) {
status.setSourceDatabaseName(sourceDatabaseName);
status.setSourceSchemaName(orDefault(sourceSchemaName, "public"));
status.setSourceTableName(sourceTableName);
status.setTargetDatabaseName(orDefault(targetDatabaseName, sourceDatabaseName));
status.setTargetSchemaName(orDefault(targetSchemaName, status.getSourceSchemaName()));
status.setNewTableName(newTableName);
}
private String fold(String name) {
return caseSensitive ? name : name.toLowerCase(Locale.ROOT);
}
private static String orDefault(String value, String fallback) {
return value == null || value.isBlank() ? fallback : value;
}
}
/** The size of {@code script} in whole megabytes, which a status reports as the data to restore. */
public static long megabytes(String script) {
return script.length() / MEGABYTE;
}
/** The script that restores the table under its new name, or empty when the dump has no such table. */
public Optional<String> script(Path dump, String sourceSchema, String sourceTable, String targetSchema,
String newTableName, boolean caseSensitive) {
try {
return RedshiftSnapshotTableExtractor.restoreScript(dump, sourceSchema, sourceTable, targetSchema,
newTableName, caseSensitive);
} catch (IOException e) {
LOG.warnv(e, "Could not read the snapshot dump {0}", dump);
throw new AwsException("InternalFailure", "The data of the snapshot could not be read: " + e.getMessage(),
500);
}
}
/** The backend a restore runs in: whose it is, how to reach it, and its one database. */
public record Backend(String accountId, String backendId, String masterUsername, String database) {
}
/**
* Restores the table the request names, which both services do the same way after their own lookups: the
* names are checked against the one database of the backend and the dump, the request is stored as in
* progress, the script is replayed, and the outcome is stored. The restore runs inside the call, so the
* request is reported as {@code PENDING} while the stored status already holds its outcome. A request the
* dump cannot serve is refused with the exception {@code invalid} makes.
*
* @param identify sets what names the resource of the request on its status: its cluster or its workgroup
* @param store persists the status as it stands
*/
public <E extends RuntimeException> TableRestoreStatus restore(
TableNames names, Path dump, Backend backend, Instant requestTime, Function<String, E> invalid,
Consumer<TableRestoreStatus> identify, Consumer<TableRestoreStatus> store) {
if (!names.sourceDatabaseIs(backend.database())) {
throw invalid.apply("The database " + names.sourceDatabaseName() + " does not exist in the snapshot.");
}
// A backend holds one database; psql would also read an odd name as a connection string.
if (!names.targetDatabaseIs(backend.database())) {
throw invalid.apply("The database " + names.targetDatabaseName() + " does not exist.");
}
String script;
try {
script = script(dump, names.sourceSchema(), names.sourceTable(), names.targetSchema(), names.newTable(),
names.caseSensitive()).orElseThrow(() -> invalid.apply("The table " + names.sourceSchema() + "."
+ names.sourceTable() + " does not exist in the database " + names.sourceDatabase()
+ " of the snapshot."));
} catch (RedshiftSnapshotTableExtractor.UnsupportedTableException e) {
throw invalid.apply(e.getMessage());
}
TableRestoreStatus status = new TableRestoreStatus();
status.setTableRestoreRequestId(UUID.randomUUID().toString());
status.setRequestTime(requestTime);
identify.accept(status);
names.applyTo(status);
status.setTotalDataInMegaBytes(megabytes(script));
status.setProgressInMegaBytes(0L);
TableRestoreStatus accepted = new TableRestoreStatus(status);
accepted.setStatus(TableRestoreStatus.PENDING);
status.setStatus(TableRestoreStatus.IN_PROGRESS);
store.accept(status);
try {
run(backend.accountId(), backend.backendId(), backend.masterUsername(), names.targetDatabase(), script);
status.setStatus(TableRestoreStatus.SUCCEEDED);
status.setProgressInMegaBytes(status.getTotalDataInMegaBytes());
} catch (AwsException e) {
LOG.warnv(e, "Table restore {0} in {1} failed", status.getTableRestoreRequestId(), backend.backendId());
status.setStatus(TableRestoreStatus.FAILED);
status.setMessage(e.getMessage());
}
store.accept(status);
return accepted;
}
/** The psql error line alone: its CONTEXT lines carry the rows that failed. */
private static String reason(String message) {
if (message != null) {
for (String line : message.split("\\R")) {
int at = line.indexOf("ERROR:");
if (at >= 0) {
String reason = line.substring(at + "ERROR:".length()).strip();
return reason.length() > 300 ? reason.substring(0, 300) : reason;
}
}
}
return "the script failed.";
}
/**
* Runs {@code script} in {@code database} of the backend. It is one transaction, so a failing statement leaves
* nothing behind.
*/
public void run(String accountId, String backendId, String masterUsername, String database, String script) {
Path file;
try {
file = Files.createTempFile("redshift-table-restore-", ".sql");
Files.writeString(file, script, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new AwsException("InternalFailure", "The table restore could not be prepared: " + e.getMessage(),
500);
}
try {
try {
containerManager.runTableRestoreScript(accountId, backendId, masterUsername, database, file);
} catch (AwsException e) {
throw new AwsException("InternalFailure", "The table could not be restored: " + reason(e.getMessage()), 500);
}
} finally {
try {
Files.deleteIfExists(file);
} catch (IOException e) {
LOG.warnv(e, "Could not delete the table restore script {0}", file);
}
}
}
}
@@ -464,6 +464,44 @@ public class RedshiftContainerManager {
}
}
/** How long a table restore script may run before psql is killed; the exec timeout leaves it room to finish. */
static final int TABLE_RESTORE_PSQL_SECONDS = 600;
private static final int TABLE_RESTORE_EXEC_SECONDS = TABLE_RESTORE_PSQL_SECONDS + 30;
/**
* Replays a table restore script in one psql run and removes the copy of it from the container once psql
* has ended, whichever way it ended. psql is killed by {@code timeout} on its own deadline, so a script that
* is too slow ends before it commits instead of running on after the caller has reported a failure.
*/
public void runTableRestoreScript(String accountId, String clusterIdentifier, String username, String dbname,
Path script) {
RedshiftContainerHandle handle = requireHandle(accountId, clusterIdentifier);
String fileName = script.getFileName().toString();
try {
RetryingTarCopier.copyHostResource(lifecycleManager.getDockerClient(), handle.getContainerId(),
"/tmp", script.toString(), RetryingTarCopier.DEFAULT_MAX_ATTEMPTS, retryBackoffMillis);
String[] cmd = {"sh", "-c", "timeout -s KILL " + TABLE_RESTORE_PSQL_SECONDS
+ " psql -U \"$1\" -d \"$2\" -v ON_ERROR_STOP=1 -f \"$3\"; status=$?; rm -f \"$3\"; exit $status",
"sh", userOrDefault(username), databaseOrDefault(dbname), "/tmp/" + fileName};
ContainerExec.Result result = execInContainer(handle.getContainerId(), cmd, TABLE_RESTORE_EXEC_SECONDS);
if (result.timedOut() || result.exitCode() == 137) {
throw new AwsException("InternalFailure", "ERROR: the restore ran longer than "
+ TABLE_RESTORE_PSQL_SECONDS + " seconds and was stopped", 500);
}
if (result.exitCode() != 0) {
LOG.warnv("Table restore failed in cluster {0} (exit {1}): {2}", clusterIdentifier,
result.exitCode(), result.stderr());
throw new AwsException("InternalFailure", result.stderr(), 500);
}
} catch (AwsException e) {
throw e;
} catch (Exception e) {
LOG.errorv(e, "Error restoring a table in cluster {0}", clusterIdentifier);
throw new AwsException("InternalFailure", "Failed to restore a table in cluster " + clusterIdentifier + ": "
+ e.getMessage(), 500);
}
}
private static final String DROP_USER_SCHEMAS_SQL = "DO $$ DECLARE s text; BEGIN "
+ "PERFORM lo_unlink(oid) FROM pg_largeobject_metadata; "
+ "FOR s IN SELECT nspname FROM pg_namespace WHERE nspname NOT IN ('pg_catalog', 'information_schema') "
@@ -0,0 +1,108 @@
package io.floci.aws.services.redshift.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
/**
* A request to restore one table from a snapshot, and how it went. Shared by Redshift, which reports the
* cluster, and Redshift Serverless, which reports the namespace and workgroup.
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class TableRestoreStatus {
public static final String PENDING = "PENDING";
public static final String IN_PROGRESS = "IN_PROGRESS";
public static final String SUCCEEDED = "SUCCEEDED";
public static final String FAILED = "FAILED";
private String tableRestoreRequestId;
private String status;
private String message;
private Instant requestTime;
private String clusterIdentifier;
private String namespaceName;
private String workgroupName;
private String snapshotIdentifier;
private String sourceDatabaseName;
private String sourceSchemaName;
private String sourceTableName;
private String targetDatabaseName;
private String targetSchemaName;
private String newTableName;
private Long progressInMegaBytes;
private Long totalDataInMegaBytes;
public TableRestoreStatus() {
}
public TableRestoreStatus(TableRestoreStatus other) {
this.tableRestoreRequestId = other.tableRestoreRequestId;
this.status = other.status;
this.message = other.message;
this.requestTime = other.requestTime;
this.clusterIdentifier = other.clusterIdentifier;
this.namespaceName = other.namespaceName;
this.workgroupName = other.workgroupName;
this.snapshotIdentifier = other.snapshotIdentifier;
this.sourceDatabaseName = other.sourceDatabaseName;
this.sourceSchemaName = other.sourceSchemaName;
this.sourceTableName = other.sourceTableName;
this.targetDatabaseName = other.targetDatabaseName;
this.targetSchemaName = other.targetSchemaName;
this.newTableName = other.newTableName;
this.progressInMegaBytes = other.progressInMegaBytes;
this.totalDataInMegaBytes = other.totalDataInMegaBytes;
}
public String getTableRestoreRequestId() { return tableRestoreRequestId; }
public void setTableRestoreRequestId(String value) { tableRestoreRequestId = value; }
/** One of {@link #PENDING}, {@link #IN_PROGRESS}, {@link #SUCCEEDED} or {@link #FAILED}. */
public String getStatus() { return status; }
public void setStatus(String value) { status = value; }
public String getMessage() { return message; }
public void setMessage(String value) { message = value; }
public Instant getRequestTime() { return requestTime; }
public void setRequestTime(Instant value) { requestTime = value; }
public String getClusterIdentifier() { return clusterIdentifier; }
public void setClusterIdentifier(String value) { clusterIdentifier = value; }
public String getNamespaceName() { return namespaceName; }
public void setNamespaceName(String value) { namespaceName = value; }
public String getWorkgroupName() { return workgroupName; }
public void setWorkgroupName(String value) { workgroupName = value; }
public String getSnapshotIdentifier() { return snapshotIdentifier; }
public void setSnapshotIdentifier(String value) { snapshotIdentifier = value; }
public String getSourceDatabaseName() { return sourceDatabaseName; }
public void setSourceDatabaseName(String value) { sourceDatabaseName = value; }
public String getSourceSchemaName() { return sourceSchemaName; }
public void setSourceSchemaName(String value) { sourceSchemaName = value; }
public String getSourceTableName() { return sourceTableName; }
public void setSourceTableName(String value) { sourceTableName = value; }
public String getTargetDatabaseName() { return targetDatabaseName; }
public void setTargetDatabaseName(String value) { targetDatabaseName = value; }
public String getTargetSchemaName() { return targetSchemaName; }
public void setTargetSchemaName(String value) { targetSchemaName = value; }
public String getNewTableName() { return newTableName; }
public void setNewTableName(String value) { newTableName = value; }
public Long getProgressInMegaBytes() { return progressInMegaBytes; }
public void setProgressInMegaBytes(Long value) { progressInMegaBytes = value; }
public Long getTotalDataInMegaBytes() { return totalDataInMegaBytes; }
public void setTotalDataInMegaBytes(Long value) { totalDataInMegaBytes = value; }
}
@@ -11,6 +11,7 @@ import io.floci.aws.core.common.JsonErrorResponseUtils;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.services.redshift.RedshiftIamDbUserResolver;
import io.floci.aws.services.redshift.TempCredential;
import io.floci.aws.services.redshift.model.TableRestoreStatus;
import io.floci.aws.services.redshiftserverless.model.ConfigParameter;
import io.floci.aws.services.redshiftserverless.model.CustomDomainAssociation;
import io.floci.aws.services.redshiftserverless.model.Namespace;
@@ -48,6 +49,7 @@ public class RedshiftServerlessJsonHandler {
private final RedshiftServerlessAdminJsonHandler admin;
private final RedshiftServerlessCustomDomainService customDomains;
private final RedshiftServerlessSharedSnapshots sharedSnapshots;
private final RedshiftServerlessTableRestoreService tableRestores;
@Inject
public RedshiftServerlessJsonHandler(RedshiftServerlessService service, ObjectMapper objectMapper,
@@ -55,7 +57,8 @@ public class RedshiftServerlessJsonHandler {
RedshiftServerlessUsageLimitService usageLimits,
RedshiftServerlessAdminJsonHandler admin,
RedshiftServerlessCustomDomainService customDomains,
RedshiftServerlessSharedSnapshots sharedSnapshots) {
RedshiftServerlessSharedSnapshots sharedSnapshots,
RedshiftServerlessTableRestoreService tableRestores) {
this.service = service;
this.objectMapper = objectMapper;
this.iamDbUserResolver = iamDbUserResolver;
@@ -63,6 +66,7 @@ public class RedshiftServerlessJsonHandler {
this.admin = admin;
this.customDomains = customDomains;
this.sharedSnapshots = sharedSnapshots;
this.tableRestores = tableRestores;
}
public Response handle(String action, JsonNode request, String region) {
@@ -89,6 +93,9 @@ public class RedshiftServerlessJsonHandler {
case "UpdateSnapshot" -> () -> handleUpdateSnapshot(request, region);
case "DeleteSnapshot" -> () -> handleDeleteSnapshot(request, region);
case "RestoreFromSnapshot" -> () -> handleRestoreFromSnapshot(request, region);
case "RestoreTableFromSnapshot" -> () -> handleRestoreTableFromSnapshot(request, region);
case "GetTableRestoreStatus" -> () -> handleGetTableRestoreStatus(request, region);
case "ListTableRestoreStatus" -> () -> handleListTableRestoreStatus(request, region);
case "CreateUsageLimit" -> () -> handleCreateUsageLimit(request, region);
case "GetUsageLimit" -> () -> handleGetUsageLimit(request, region);
case "ListUsageLimits" -> () -> handleListUsageLimits(request, region);
@@ -294,6 +301,72 @@ public class RedshiftServerlessJsonHandler {
ServerlessSupport.text(request, "snapshotName"), ServerlessSupport.integer(request, "retentionPeriod"), region));
}
private Response handleRestoreTableFromSnapshot(JsonNode request, String region) {
TableRestoreStatus status = tableRestores.restoreTable(new RedshiftServerlessTableRestoreService.Request(
ServerlessSupport.text(request, "namespaceName"), ServerlessSupport.text(request, "workgroupName"),
ServerlessSupport.text(request, "snapshotName"), ServerlessSupport.text(request, "sourceDatabaseName"),
ServerlessSupport.text(request, "sourceSchemaName"), ServerlessSupport.text(request, "sourceTableName"),
ServerlessSupport.text(request, "targetDatabaseName"),
ServerlessSupport.text(request, "targetSchemaName"), ServerlessSupport.text(request, "newTableName"),
Boolean.TRUE.equals(ServerlessSupport.bool(request, "activateCaseSensitiveIdentifier"))), region);
ObjectNode response = objectMapper.createObjectNode();
response.set("tableRestoreStatus", tableRestoreStatusNode(status));
return Response.ok(response).build();
}
private Response handleGetTableRestoreStatus(JsonNode request, String region) {
ObjectNode response = objectMapper.createObjectNode();
response.set("tableRestoreStatus", tableRestoreStatusNode(tableRestores.getTableRestoreStatus(
ServerlessSupport.text(request, "tableRestoreRequestId"), region)));
return Response.ok(response).build();
}
private Response handleListTableRestoreStatus(JsonNode request, String region) {
PaginatedResult<TableRestoreStatus> page = tableRestores.listTableRestoreStatus(
ServerlessSupport.text(request, "namespaceName"), ServerlessSupport.text(request, "workgroupName"),
ServerlessSupport.maxResults(request), ServerlessSupport.text(request, "nextToken"), region);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode items = response.putArray("tableRestoreStatuses");
page.items().forEach(status -> items.add(tableRestoreStatusNode(status)));
if (page.nextToken() != null) {
response.put("nextToken", page.nextToken());
}
return Response.ok(response).build();
}
/** {@code requestTime} has no timestamp format trait in the model, so it is epoch seconds as a JSON number. */
private ObjectNode tableRestoreStatusNode(TableRestoreStatus status) {
ObjectNode node = objectMapper.createObjectNode();
putIfPresent(node, "message", status.getMessage());
putIfPresent(node, "namespaceName", status.getNamespaceName());
putIfPresent(node, "newTableName", status.getNewTableName());
if (status.getProgressInMegaBytes() != null) {
node.put("progressInMegaBytes", status.getProgressInMegaBytes());
}
if (status.getRequestTime() != null) {
node.put("requestTime", status.getRequestTime().toEpochMilli() / 1000.0);
}
putIfPresent(node, "snapshotName", status.getSnapshotIdentifier());
putIfPresent(node, "sourceDatabaseName", status.getSourceDatabaseName());
putIfPresent(node, "sourceSchemaName", status.getSourceSchemaName());
putIfPresent(node, "sourceTableName", status.getSourceTableName());
putIfPresent(node, "status", status.getStatus());
putIfPresent(node, "tableRestoreRequestId", status.getTableRestoreRequestId());
putIfPresent(node, "targetDatabaseName", status.getTargetDatabaseName());
putIfPresent(node, "targetSchemaName", status.getTargetSchemaName());
if (status.getTotalDataInMegaBytes() != null) {
node.put("totalDataInMegaBytes", status.getTotalDataInMegaBytes());
}
putIfPresent(node, "workgroupName", status.getWorkgroupName());
return node;
}
private static void putIfPresent(ObjectNode node, String field, String value) {
if (value != null) {
node.put(field, value);
}
}
private Response handleDeleteSnapshot(JsonNode request, String region) {
return snapshotResponse(service.deleteSnapshot(ServerlessSupport.text(request, "snapshotName"), region));
}
@@ -1072,6 +1072,34 @@ public class RedshiftServerlessService implements Resettable, StoredResourceArns
public record RestoreResult(Namespace namespace, RedshiftServerlessSnapshot snapshot) {}
/** What a table restore reads from and writes into: the workgroup's backend, the snapshot's database and dump. */
public record TableRestoreSource(Workgroup workgroup, Namespace namespace, Path dump) {}
/**
* Resolves what restoring one table of {@code snapshotName} into {@code workgroupName} needs. The snapshot must be
* available and of {@code namespaceName}, the workgroup must be running, and the snapshot must hold data.
*/
public synchronized TableRestoreSource tableRestoreSource(String namespaceName, String workgroupName,
String snapshotName, String region) {
RedshiftServerlessSnapshot snapshot = getSnapshot(snapshotName, region);
requireAvailableSnapshot(snapshot);
if (!namespaceName.equals(snapshot.getNamespaceName())) {
throw snapshotNotFound(snapshotName);
}
Namespace namespace = getNamespace(namespaceName, region);
Workgroup workgroup = getWorkgroup(workgroupName, region);
if (!namespaceName.equals(workgroup.getNamespaceName())) {
throw ServerlessSupport.validation("The workgroup " + workgroupName + " does not belong to the namespace "
+ namespaceName + ".");
}
if (!hasLiveRuntime(workgroup)) {
throw ServerlessSupport.conflict("The workgroup " + workgroupName + " is not available.");
}
Path dump = trustedDump(snapshot, region).filter(Files::exists).orElseThrow(() -> ServerlessSupport.validation(
"The snapshot " + snapshotName + " holds no table data to restore."));
return new TableRestoreSource(workgroup, namespace, dump);
}
public Map<String, String> listTagsForResource(String resourceArn, String region) {
requireResourceArn(resourceArn);
Optional<Namespace> namespace = namespaceByArn(resourceArn, region);
@@ -0,0 +1,116 @@
package io.floci.aws.services.redshiftserverless;
import com.fasterxml.jackson.core.type.TypeReference;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.Pagination;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.Resettable;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.redshift.RedshiftTableRestorer;
import io.floci.aws.services.redshift.RedshiftTableRestorer.TableNames;
import io.floci.aws.services.redshift.model.TableRestoreStatus;
import io.floci.aws.services.redshiftserverless.RedshiftServerlessService.TableRestoreSource;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.time.Clock;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
/**
* Restores one table of a Redshift Serverless snapshot into a workgroup under a new name, and keeps the status of
* each request. The restore runs inside the request, so a request that was accepted has already ended in
* {@code SUCCEEDED} or {@code FAILED} when it is next read; the response to the request itself shows it as
* {@code PENDING}, as AWS does.
*/
@ApplicationScoped
public class RedshiftServerlessTableRestoreService implements Resettable {
private final AccountAwareStorageBackend<TableRestoreStatus> restores;
private final RedshiftServerlessService serverless;
private final RedshiftTableRestorer restorer;
private final RegionResolver regionResolver;
private final Clock clock;
@Inject
public RedshiftServerlessTableRestoreService(StorageFactory storageFactory, RedshiftServerlessService serverless,
RedshiftTableRestorer restorer, RegionResolver regionResolver,
Clock clock) {
this.restores = storageFactory.create("redshiftserverless", "redshiftserverless-table-restores.json",
new TypeReference<Map<String, TableRestoreStatus>>() {});
this.serverless = serverless;
this.restorer = restorer;
this.regionResolver = regionResolver;
this.clock = clock;
}
/** The members a {@code RestoreTableFromSnapshot} request carries. */
public record Request(String namespaceName, String workgroupName, String snapshotName, String sourceDatabaseName,
String sourceSchemaName, String sourceTableName, String targetDatabaseName,
String targetSchemaName, String newTableName, boolean caseSensitive) {
}
public TableRestoreStatus restoreTable(Request request, String region) {
ServerlessSupport.requireText(request.namespaceName(), "namespaceName");
ServerlessSupport.requireText(request.workgroupName(), "workgroupName");
ServerlessSupport.requireText(request.snapshotName(), "snapshotName");
ServerlessSupport.requireText(request.sourceDatabaseName(), "sourceDatabaseName");
ServerlessSupport.requireText(request.sourceTableName(), "sourceTableName");
ServerlessSupport.requireText(request.newTableName(), "newTableName");
TableRestoreSource source = serverless.tableRestoreSource(request.namespaceName(), request.workgroupName(),
request.snapshotName(), region);
TableNames names = new TableNames(request.sourceDatabaseName(), request.sourceSchemaName(),
request.sourceTableName(), request.targetDatabaseName(), request.targetSchemaName(),
request.newTableName(), request.caseSensitive());
return restorer.restore(names, source.dump(), new RedshiftTableRestorer.Backend(regionResolver.getAccountId(),
RedshiftServerlessRuntime.backendId(region, request.workgroupName()),
source.workgroup().getMasterUsername(), source.namespace().getDbName()), clock.instant(),
ServerlessSupport::validation, status -> {
status.setNamespaceName(request.namespaceName());
status.setWorkgroupName(request.workgroupName());
status.setSnapshotIdentifier(request.snapshotName());
}, status -> restores.put(storageKey(region, status.getTableRestoreRequestId()), status));
}
public TableRestoreStatus getTableRestoreStatus(String tableRestoreRequestId, String region) {
ServerlessSupport.requireText(tableRestoreRequestId, "tableRestoreRequestId");
return restores.get(storageKey(region, tableRestoreRequestId))
.filter(restore -> hasWorkgroup(restore, region))
.map(TableRestoreStatus::new)
.orElseThrow(() -> ServerlessSupport.notFound(
"The table restore request " + tableRestoreRequestId + " was not found."));
}
/** The Region's restore requests in the order they were made, narrowed by namespace and workgroup. */
public PaginatedResult<TableRestoreStatus> listTableRestoreStatus(
String namespaceName, String workgroupName, Integer maxResults, String nextToken, String region) {
int limit = ServerlessSupport.pageSize(maxResults);
List<TableRestoreStatus> matching = ServerlessSupport.live(restores, region, restore -> hasWorkgroup(restore, region),
restore -> storageKey(region, restore.getTableRestoreRequestId())).stream()
.filter(restore -> namespaceName == null || namespaceName.equals(restore.getNamespaceName()))
.filter(restore -> workgroupName == null || workgroupName.equals(restore.getWorkgroupName()))
.sorted(Comparator.comparing(TableRestoreStatus::getRequestTime)
.thenComparing(TableRestoreStatus::getTableRestoreRequestId))
.map(TableRestoreStatus::new)
.toList();
return Pagination.paginate(matching, TableRestoreStatus::getTableRestoreRequestId, limit, nextToken,
"redshift-serverless-table-restore",
token -> ServerlessSupport.invalidPagination("Invalid nextToken."));
}
@Override
public void clear() {
restores.clear();
}
private boolean hasWorkgroup(TableRestoreStatus restore, String region) {
return serverless.findWorkgroup(restore.getWorkgroupName(), region).isPresent();
}
private static String storageKey(String region, String requestId) {
return region + "::" + requestId;
}
}