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

@@ -201,6 +201,7 @@ import java.sql.Connection;
import java.sql.DriverManager; import java.sql.DriverManager;
import java.sql.SQLException; import java.sql.SQLException;
import java.time.Duration; import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -1906,6 +1907,29 @@ public final class TestFixtures {
.build(); .build();
} }
/** Connects to the PostgreSQL database {@code dev} behind a Redshift cluster, retrying for up to a minute while it starts. */
public static Connection awaitRedshiftConnection(String host, int port, String username, String password)
throws Exception {
Instant deadline = Instant.now().plus(Duration.ofSeconds(60));
SQLException lastFailure = null;
while (Instant.now().isBefore(deadline)) {
try {
Properties properties = new Properties();
properties.setProperty("user", username);
properties.setProperty("password", password);
properties.setProperty("sslmode", "disable");
properties.setProperty("connectTimeout", "5");
return DriverManager.getConnection("jdbc:postgresql://" + host + ":" + port + "/dev", properties);
} catch (SQLException e) {
lastFailure = e;
Thread.sleep(1000);
}
}
throw lastFailure != null
? lastFailure
: new SQLException("Timed out waiting for Redshift connection at " + host + ":" + port);
}
public static RedshiftDataClient redshiftDataClient() { public static RedshiftDataClient redshiftDataClient() {
return RedshiftDataClient.builder() return RedshiftDataClient.builder()
.endpointOverride(ENDPOINT) .endpointOverride(ENDPOINT)
@@ -15,12 +15,9 @@ import software.amazon.awssdk.services.cloudformation.model.Output;
import software.amazon.awssdk.services.cloudformation.model.Stack; import software.amazon.awssdk.services.cloudformation.model.Stack;
import java.sql.Connection; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import java.time.Duration; import java.time.Duration;
import java.time.Instant;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Properties; import java.util.Properties;
@@ -117,7 +114,7 @@ class CloudFormationRedshiftClusterTest {
? TestFixtures.proxyHost() ? TestFixtures.proxyHost()
: addr; : addr;
try (Connection conn = awaitPostgresConnection(connectHost, port, "admin", "Secret12345"); try (Connection conn = TestFixtures.awaitRedshiftConnection(connectHost, port, "admin", "Secret12345");
Statement stmt = conn.createStatement(); Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT 1")) { ResultSet rs = stmt.executeQuery("SELECT 1")) {
assertThat(rs.next()).isTrue(); assertThat(rs.next()).isTrue();
@@ -125,29 +122,6 @@ class CloudFormationRedshiftClusterTest {
} }
} }
private static Connection awaitPostgresConnection(String host, int port, String username, String password) throws Exception {
Instant deadline = Instant.now().plus(Duration.ofSeconds(60));
SQLException lastFailure = null;
while (Instant.now().isBefore(deadline)) {
try {
Properties properties = new Properties();
properties.setProperty("user", username);
properties.setProperty("password", password);
properties.setProperty("sslmode", "disable");
properties.setProperty("connectTimeout", "5");
return DriverManager.getConnection(
"jdbc:postgresql://" + host + ":" + port + "/dev",
properties);
} catch (SQLException e) {
lastFailure = e;
Thread.sleep(1000);
}
}
throw lastFailure != null
? lastFailure
: new SQLException("Timed out waiting for Redshift connection at " + host + ":" + port);
}
private static void waitForDeleted(String name, int maxSeconds) throws InterruptedException { private static void waitForDeleted(String name, int maxSeconds) throws InterruptedException {
long deadline = System.currentTimeMillis() + maxSeconds * 1000L; long deadline = System.currentTimeMillis() + maxSeconds * 1000L;
while (System.currentTimeMillis() < deadline) { while (System.currentTimeMillis() < deadline) {
@@ -60,15 +60,10 @@ import software.amazon.awssdk.services.redshift.model.SnapshotCopyGrantNotFoundE
import software.amazon.awssdk.services.redshift.model.Tag; import software.amazon.awssdk.services.redshift.model.Tag;
import java.sql.Connection; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Properties;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
@@ -184,7 +179,7 @@ class RedshiftOperationsTest {
int sourcePort = sourceCluster.endpoint().port(); int sourcePort = sourceCluster.endpoint().port();
// 2. Use JDBC to create a table and insert a row // 2. Use JDBC to create a table and insert a row
try (Connection conn = awaitPostgresConnection(sourceHost, sourcePort, USERNAME, PASSWORD); try (Connection conn = TestFixtures.awaitRedshiftConnection(sourceHost, sourcePort, USERNAME, PASSWORD);
Statement stmt = conn.createStatement()) { Statement stmt = conn.createStatement()) {
stmt.execute("CREATE TABLE test_data (id INT PRIMARY KEY, name VARCHAR(100));"); stmt.execute("CREATE TABLE test_data (id INT PRIMARY KEY, name VARCHAR(100));");
stmt.execute("INSERT INTO test_data (id, name) VALUES (1, 'floci-redshift-snapshot-val');"); stmt.execute("INSERT INTO test_data (id, name) VALUES (1, 'floci-redshift-snapshot-val');");
@@ -237,7 +232,7 @@ class RedshiftOperationsTest {
int restoredPort = restoredCluster.endpoint().port(); int restoredPort = restoredCluster.endpoint().port();
// 6. Use JDBC to query restored cluster and verify row exists // 6. Use JDBC to query restored cluster and verify row exists
try (Connection conn = awaitPostgresConnection(restoredHost, restoredPort, USERNAME, PASSWORD); try (Connection conn = TestFixtures.awaitRedshiftConnection(restoredHost, restoredPort, USERNAME, PASSWORD);
Statement stmt = conn.createStatement(); Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT name FROM test_data WHERE id = 1;")) { ResultSet rs = stmt.executeQuery("SELECT name FROM test_data WHERE id = 1;")) {
assertThat(rs.next()).isTrue(); assertThat(rs.next()).isTrue();
@@ -512,23 +507,4 @@ class RedshiftOperationsTest {
assertThat(paged).doesNotHaveDuplicates(); assertThat(paged).doesNotHaveDuplicates();
assertThat(paged).isSorted(); assertThat(paged).isSorted();
} }
private static Connection awaitPostgresConnection(String host, int port, String username, String password) throws Exception {
Instant deadline = Instant.now().plus(Duration.ofSeconds(60));
SQLException last = null;
while (Instant.now().isBefore(deadline)) {
try {
Properties properties = new Properties();
properties.setProperty("user", username);
properties.setProperty("password", password);
properties.setProperty("sslmode", "disable");
properties.setProperty("connectTimeout", "5");
return DriverManager.getConnection("jdbc:postgresql://" + host + ":" + port + "/" + DATABASE, properties);
} catch (SQLException e) {
last = e;
Thread.sleep(1000);
}
}
throw last != null ? last : new SQLException("Timed out waiting for PostgreSQL connection at " + host + ":" + port);
}
} }
@@ -0,0 +1,144 @@
package com.floci.test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.redshift.RedshiftClient;
import software.amazon.awssdk.services.redshift.model.CreateClusterRequest;
import software.amazon.awssdk.services.redshift.model.CreateClusterSnapshotRequest;
import software.amazon.awssdk.services.redshift.model.DeleteClusterRequest;
import software.amazon.awssdk.services.redshift.model.DeleteClusterSnapshotRequest;
import software.amazon.awssdk.services.redshift.model.DescribeClustersRequest;
import software.amazon.awssdk.services.redshift.model.DescribeTableRestoreStatusRequest;
import software.amazon.awssdk.services.redshift.model.Endpoint;
import software.amazon.awssdk.services.redshift.model.RedshiftException;
import software.amazon.awssdk.services.redshift.model.RestoreTableFromClusterSnapshotRequest;
import software.amazon.awssdk.services.redshift.model.TableRestoreStatus;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.time.Duration;
import java.time.Instant;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@DisplayName("Redshift Table Restore")
class RedshiftTableRestoreTest {
private static final String USERNAME = "admin";
private static final String PASSWORD = "password123";
private static final String DATABASE = "dev";
private static RedshiftClient client;
private static String clusterId;
private static String snapshotId;
@BeforeAll
static void setup() {
client = TestFixtures.redshiftClient();
}
@AfterAll
static void cleanup() {
if (client == null) {
return;
}
try {
if (snapshotId != null) {
client.deleteClusterSnapshot(
DeleteClusterSnapshotRequest.builder().snapshotIdentifier(snapshotId).build());
}
if (clusterId != null) {
client.deleteCluster(DeleteClusterRequest.builder()
.clusterIdentifier(clusterId).skipFinalClusterSnapshot(true).build());
}
} finally {
client.close();
}
}
@Test
@DisplayName("Restore one table of a snapshot under a new name, and refuse what the snapshot does not hold")
void restoreTableFromClusterSnapshot() throws Exception {
clusterId = TestFixtures.uniqueName("rs-table");
snapshotId = TestFixtures.uniqueName("rs-table-snap");
client.createCluster(CreateClusterRequest.builder()
.clusterIdentifier(clusterId)
.nodeType("dc2.large")
.masterUsername(USERNAME)
.masterUserPassword(PASSWORD)
.build());
Endpoint endpoint = client.describeClusters(
DescribeClustersRequest.builder().clusterIdentifier(clusterId).build()).clusters().get(0).endpoint();
try (Connection connection = TestFixtures.awaitRedshiftConnection(endpoint.address(), endpoint.port(), USERNAME, PASSWORD);
Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE orders (id INT, note VARCHAR(40))");
statement.execute("INSERT INTO orders VALUES (1, 'first'), (2, 'second')");
client.createClusterSnapshot(CreateClusterSnapshotRequest.builder()
.snapshotIdentifier(snapshotId).clusterIdentifier(clusterId).build());
statement.execute("INSERT INTO orders VALUES (3, 'after the snapshot')");
TableRestoreStatus accepted = client.restoreTableFromClusterSnapshot(
RestoreTableFromClusterSnapshotRequest.builder()
.clusterIdentifier(clusterId)
.snapshotIdentifier(snapshotId)
.sourceDatabaseName(DATABASE)
.sourceTableName("orders")
.newTableName("orders_restored")
.build()).tableRestoreStatus();
assertThat(accepted.tableRestoreRequestId()).isNotBlank();
assertThat(accepted.sourceSchemaName()).isEqualTo("public");
assertThat(accepted.newTableName()).isEqualTo("orders_restored");
TableRestoreStatus described = awaitFinished(accepted.tableRestoreRequestId());
assertThat(described.statusAsString()).isEqualTo("SUCCEEDED");
try (ResultSet rows = statement.executeQuery("SELECT count(*) FROM orders_restored")) {
assertThat(rows.next()).isTrue();
assertThat(rows.getInt(1)).isEqualTo(2);
}
TableRestoreStatus duplicate = awaitFinished(client.restoreTableFromClusterSnapshot(
RestoreTableFromClusterSnapshotRequest.builder()
.clusterIdentifier(clusterId)
.snapshotIdentifier(snapshotId)
.sourceDatabaseName(DATABASE)
.sourceTableName("orders")
.newTableName("orders_restored")
.build()).tableRestoreStatus().tableRestoreRequestId());
assertThat(duplicate.statusAsString()).isEqualTo("FAILED");
assertThat(duplicate.message()).isNotBlank();
}
assertThat(client.describeTableRestoreStatus(DescribeTableRestoreStatusRequest.builder()
.clusterIdentifier(clusterId).build()).tableRestoreStatusDetails()).hasSize(2);
assertThatThrownBy(() -> client.restoreTableFromClusterSnapshot(
RestoreTableFromClusterSnapshotRequest.builder()
.clusterIdentifier(clusterId)
.snapshotIdentifier(snapshotId)
.sourceDatabaseName(DATABASE)
.sourceTableName("missing")
.newTableName("copy")
.build()))
.isInstanceOf(RedshiftException.class)
.hasMessageContaining("does not exist");
}
private static TableRestoreStatus awaitFinished(String requestId) throws InterruptedException {
Instant deadline = Instant.now().plus(Duration.ofSeconds(60));
TableRestoreStatus status;
do {
status = client.describeTableRestoreStatus(DescribeTableRestoreStatusRequest.builder()
.clusterIdentifier(clusterId).tableRestoreRequestId(requestId).build())
.tableRestoreStatusDetails().get(0);
if (!"PENDING".equals(status.statusAsString()) && !"IN_PROGRESS".equals(status.statusAsString())) {
return status;
}
Thread.sleep(500);
} while (Instant.now().isBefore(deadline));
return status;
}
}
+2 -2
View File
@@ -81,9 +81,9 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [DocumentDB](docdb.md) | `POST /` with `Action=` param + MongoDB container | Query + MongoDB wire | 17 | | [DocumentDB](docdb.md) | `POST /` with `Action=` param + MongoDB container | Query + MongoDB wire | 17 |
| [DMS](dms.md) | `POST /` + `X-Amz-Target: AmazonDMSv20160101.*` | JSON 1.1 | 20 | | [DMS](dms.md) | `POST /` + `X-Amz-Target: AmazonDMSv20160101.*` | JSON 1.1 | 20 |
| [QuickSight](quicksight.md) | `/accounts/{AwsAccountId}/...` | REST JSON, metadata only | 16 | | [QuickSight](quicksight.md) | `/accounts/{AwsAccountId}/...` | REST JSON, metadata only | 16 |
| [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire (+ CFN) | 63 | | [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire (+ CFN) | 65 |
| [Redshift Data API](redshift-data.md) | `POST /` + `X-Amz-Target: RedshiftData.*` | JSON 1.1 | 12 | | [Redshift Data API](redshift-data.md) | `POST /` + `X-Amz-Target: RedshiftData.*` | JSON 1.1 | 12 |
| [Redshift Serverless](redshift-serverless.md) | `POST /` + `X-Amz-Target: RedshiftServerless.*` | JSON 1.1 | 55 | | [Redshift Serverless](redshift-serverless.md) | `POST /` + `X-Amz-Target: RedshiftServerless.*` | JSON 1.1 | 58 |
| [EMR](emr.md) | `POST /` + `X-Amz-Target: ElasticMapReduce.*` | JSON 1.1 | 40 | | [EMR](emr.md) | `POST /` + `X-Amz-Target: ElasticMapReduce.*` | JSON 1.1 | 40 |
| [EMR Serverless](emr-serverless.md) | `/applications/*`, `/tags/*` | REST JSON | 15 | | [EMR Serverless](emr-serverless.md) | `/applications/*`, `/tags/*` | REST JSON | 15 |
| [Data Firehose](firehose.md) | `POST /` + `X-Amz-Target: Firehose_20150804.*` | JSON 1.1 | 12 | | [Data Firehose](firehose.md) | `POST /` + `X-Amz-Target: Firehose_20150804.*` | JSON 1.1 | 12 |
+4
View File
@@ -28,6 +28,9 @@ For the upstream API shape, see the [Amazon Redshift Serverless API Reference](h
| `UpdateSnapshot` | Change a snapshot's `retentionPeriod` (-1 for indefinite); an omitted period leaves it unchanged | | `UpdateSnapshot` | Change a snapshot's `retentionPeriod` (-1 for indefinite); an omitted period leaves it unchanged |
| `DeleteSnapshot` | Remove a snapshot and return it | | `DeleteSnapshot` | Remove a snapshot and return it |
| `RestoreFromSnapshot` | Restore into an existing namespace and workgroup, replaying the snapshot's dump into the workgroup's database; neither is created. With `ownerAccount` set to another account, the snapshot is restored from that account. With IAM enforcement on, the snapshot's resource policy must allow the caller `redshift-serverless:RestoreFromSnapshot` and the caller's own policies must too, or the call is refused with `AccessDeniedException` | | `RestoreFromSnapshot` | Restore into an existing namespace and workgroup, replaying the snapshot's dump into the workgroup's database; neither is created. With `ownerAccount` set to another account, the snapshot is restored from that account. With IAM enforcement on, the snapshot's resource policy must allow the caller `redshift-serverless:RestoreFromSnapshot` and the caller's own policies must too, or the call is refused with `AccessDeniedException` |
| `RestoreTableFromSnapshot` | Create one table of a snapshot in a running workgroup, under `newTableName` and in `targetSchemaName` (default: the source schema, which defaults to `public`). See Table restore below |
| `GetTableRestoreStatus` | Return a table restore request by `tableRestoreRequestId` |
| `ListTableRestoreStatus` | List the table restore requests in the order they were made, narrowed by `namespaceName` and `workgroupName` |
| `CreateUsageLimit` | Set a usage limit on a workgroup, defaulting `period` to `monthly` and `breachAction` to `log` | | `CreateUsageLimit` | Set a usage limit on a workgroup, defaulting `period` to `monthly` and `breachAction` to `log` |
| `GetUsageLimit` | Return a usage limit by `usageLimitId` | | `GetUsageLimit` | Return a usage limit by `usageLimitId` |
| `ListUsageLimits` | Page through the usage limits in the Region, filtered by `resourceArn` and `usageType` | | `ListUsageLimits` | Page through the usage limits in the Region, filtered by `resourceArn` and `usageType` |
@@ -141,6 +144,7 @@ aws redshift-serverless update-workgroup --workgroup-name analytics-wg --base-ca
aws redshift-serverless delete-workgroup --workgroup-name analytics-wg aws redshift-serverless delete-workgroup --workgroup-name analytics-wg
aws redshift-serverless delete-namespace --namespace-name analytics aws redshift-serverless delete-namespace --namespace-name analytics
``` ```
- **Table restore runs inside the request.** `RestoreTableFromSnapshot` lifts the table's `CREATE TABLE` statement and its rows out of the snapshot's dump and replays them, renamed, in one transaction. The response shows `PENDING`, and `GetTableRestoreStatus` already reports `SUCCEEDED` or `FAILED`, with the reason in `message`. The snapshot must be available and of `namespaceName`, the workgroup must be running, and a `sourceDatabaseName` or table the snapshot does not hold is a `ValidationException`. A target table that already exists, or a target schema that does not, ends the request in `FAILED` and leaves nothing behind. Only the definition and the rows are restored, not constraints, sequence defaults or ownership. A partitioned table is a `ValidationException`, because its rows live in its partitions. The workgroup must belong to `namespaceName`. Names are matched ignoring case unless `activateCaseSensitiveIdentifier` is `true`. Restoring from a recovery point is not supported.
- **Snapshots dump the database.** While the namespace's workgroup is running, `CreateSnapshot` runs `pg_dump` on its container and stores the dump under `<persistent-path>/redshift-serverless-dumps/<account>/<region>/`. `RestoreFromSnapshot` drops every user schema (the catalog bootstrap schema excepted) and replays the dump with `psql`, stopping at the first failing statement, so rows written after the snapshot are gone. The current contents are dumped first and put back if replay or credential changes fail, and a restore whose recorded dump file has gone missing fails instead of reporting success. A snapshot taken with no running workgroup is metadata only, and restoring it leaves the database untouched. `DeleteSnapshot` removes the dump. Snapshot ARNs use the snapshot name as their id, snapshot names are 3-255 lowercase letters, digits and hyphens, and `retentionPeriod` is `-1` (indefinite, the default) or 1 to 3653 days. Snapshots are taggable by ARN. `snapshotName` and `snapshotArn` cannot be sent together. Floci's own `floci_internal` bootstrap schema, which feeds the `svv_external_*` views from the Glue catalog, is left out of both the dump and the reset, matching AWS where the Glue catalog is outside a namespace snapshot, so a client schema with that exact name is not captured. Snapshots with finite retention expire at their creation time plus the retention period. A dedicated background worker removes expired metadata, dumps and resource policies across all accounts and Regions. It runs every `FLOCI_SERVICES_REDSHIFT_SERVERLESS_SNAPSHOT_EXPIRATION_SWEEP_INTERVAL_SECONDS` (60 by default) and can be disabled with `FLOCI_SERVICES_REDSHIFT_SERVERLESS_SNAPSHOT_EXPIRATION_ENABLED=false`. Indefinite snapshots are preserved. Cleanup serializes with restore and retention updates. A failed cleanup remains `DELETED`, rejects restore and retention updates, and is retried on later sweeps, including after restart. Persistent and WAL storage commit the deletion marker synchronously; hybrid storage retains its periodic-flush durability. Missing dump files are treated as already removed; untrusted paths are preserved and logged. Cross-Region copies are described under snapshot copy configurations below, and an expired copy is removed like any other snapshot. - **Snapshots dump the database.** While the namespace's workgroup is running, `CreateSnapshot` runs `pg_dump` on its container and stores the dump under `<persistent-path>/redshift-serverless-dumps/<account>/<region>/`. `RestoreFromSnapshot` drops every user schema (the catalog bootstrap schema excepted) and replays the dump with `psql`, stopping at the first failing statement, so rows written after the snapshot are gone. The current contents are dumped first and put back if replay or credential changes fail, and a restore whose recorded dump file has gone missing fails instead of reporting success. A snapshot taken with no running workgroup is metadata only, and restoring it leaves the database untouched. `DeleteSnapshot` removes the dump. Snapshot ARNs use the snapshot name as their id, snapshot names are 3-255 lowercase letters, digits and hyphens, and `retentionPeriod` is `-1` (indefinite, the default) or 1 to 3653 days. Snapshots are taggable by ARN. `snapshotName` and `snapshotArn` cannot be sent together. Floci's own `floci_internal` bootstrap schema, which feeds the `svv_external_*` views from the Glue catalog, is left out of both the dump and the reset, matching AWS where the Glue catalog is outside a namespace snapshot, so a client schema with that exact name is not captured. Snapshots with finite retention expire at their creation time plus the retention period. A dedicated background worker removes expired metadata, dumps and resource policies across all accounts and Regions. It runs every `FLOCI_SERVICES_REDSHIFT_SERVERLESS_SNAPSHOT_EXPIRATION_SWEEP_INTERVAL_SECONDS` (60 by default) and can be disabled with `FLOCI_SERVICES_REDSHIFT_SERVERLESS_SNAPSHOT_EXPIRATION_ENABLED=false`. Indefinite snapshots are preserved. Cleanup serializes with restore and retention updates. A failed cleanup remains `DELETED`, rejects restore and retention updates, and is retried on later sweeps, including after restart. Persistent and WAL storage commit the deletion marker synchronously; hybrid storage retains its periodic-flush durability. Missing dump files are treated as already removed; untrusted paths are preserved and logged. Cross-Region copies are described under snapshot copy configurations below, and an expired copy is removed like any other snapshot.
- **`UpdateSnapshot` changes only `retentionPeriod`.** It is validated like `CreateSnapshot` (`-1` or 1 to 3653 days), `-1` makes the snapshot indefinite, and an omitted period leaves the snapshot unchanged. `snapshotRemainingDays` keeps counting from the creation time, because Floci stores no separate retention start. - **`UpdateSnapshot` changes only `retentionPeriod`.** It is validated like `CreateSnapshot` (`-1` or 1 to 3653 days), `-1` makes the snapshot indefinite, and an omitted period leaves the snapshot unchanged. `snapshotRemainingDays` keeps counting from the creation time, because Floci stores no separate retention start.
- **Resource policies grant cross-account restore only.** A policy is stored per account and Region, echoed in the shape of the API model, and dropped on read once the snapshot it belongs to is gone. A snapshot recreated under the same name is a different snapshot: the record keeps the snapshot's creation time, so the policy is not inherited. `PutResourcePolicy` accepts a JSON object for a snapshot ARN of this account and Region. Under IAM enforcement the policy is read like the resource policy of an SQS queue: a request naming a snapshot of another account (`snapshotName` with `ownerAccount`, or `snapshotArn`) is checked on that account's snapshot ARN, so the policy must allow the caller (or the caller's account) `redshift-serverless:RestoreFromSnapshot`, an explicit `Deny` wins, a snapshot with no policy is not shared, and the caller's own identity policies must allow the call as well. A statement with no `Resource`, as in AWS's own `PutResourcePolicy` example, applies to the snapshot the policy is on. A snapshot whose `kmsKeyId` names a customer managed key also needs `kms:Decrypt` on that key, as AWS requires the key to be shared with the account performing the restore: the key policy in the owner's account must allow the caller or the caller's account, and the caller's own policies must allow it too. The owner restoring its own encrypted snapshot needs `kms:Decrypt` in its own policies. The check carries `kms:ViaService` as `redshift-serverless.<region>.amazonaws.com` and `aws:ViaAWSService` as `true`. A snapshot under `AWS_OWNED_KMS_KEY` needs nothing from KMS. With enforcement off nothing evaluates the policy. The dump is read from the owner's directory and the workgroup and namespace restored into are the caller's. `GetSnapshot` and `ListSnapshots` with another `ownerAccount` read that account's snapshots. `GetSnapshot` is checked by IAM enforcement like the restore, against `redshift-serverless:GetSnapshot`. `ListSnapshots` names no single snapshot, so it lists only the snapshots whose policy allows the caller `redshift-serverless:GetSnapshot` and leaves the others out, with enforcement on or off. A snapshot is never shared across partitions. A foreign or non-snapshot ARN is a `ValidationException`. - **Resource policies grant cross-account restore only.** A policy is stored per account and Region, echoed in the shape of the API model, and dropped on read once the snapshot it belongs to is gone. A snapshot recreated under the same name is a different snapshot: the record keeps the snapshot's creation time, so the policy is not inherited. `PutResourcePolicy` accepts a JSON object for a snapshot ARN of this account and Region. Under IAM enforcement the policy is read like the resource policy of an SQS queue: a request naming a snapshot of another account (`snapshotName` with `ownerAccount`, or `snapshotArn`) is checked on that account's snapshot ARN, so the policy must allow the caller (or the caller's account) `redshift-serverless:RestoreFromSnapshot`, an explicit `Deny` wins, a snapshot with no policy is not shared, and the caller's own identity policies must allow the call as well. A statement with no `Resource`, as in AWS's own `PutResourcePolicy` example, applies to the snapshot the policy is on. A snapshot whose `kmsKeyId` names a customer managed key also needs `kms:Decrypt` on that key, as AWS requires the key to be shared with the account performing the restore: the key policy in the owner's account must allow the caller or the caller's account, and the caller's own policies must allow it too. The owner restoring its own encrypted snapshot needs `kms:Decrypt` in its own policies. The check carries `kms:ViaService` as `redshift-serverless.<region>.amazonaws.com` and `aws:ViaAWSService` as `true`. A snapshot under `AWS_OWNED_KMS_KEY` needs nothing from KMS. With enforcement off nothing evaluates the policy. The dump is read from the owner's directory and the workgroup and namespace restored into are the caller's. `GetSnapshot` and `ListSnapshots` with another `ownerAccount` read that account's snapshots. `GetSnapshot` is checked by IAM enforcement like the restore, against `redshift-serverless:GetSnapshot`. `ListSnapshots` names no single snapshot, so it lists only the snapshots whose policy allows the caller `redshift-serverless:GetSnapshot` and leaves the others out, with enforcement on or off. A snapshot is never shared across partitions. A foreign or non-snapshot ARN is a `ValidationException`.
+12
View File
@@ -134,6 +134,8 @@ The attributes follow the [CloudFormation resource schema](https://docs.aws.amaz
| `ModifyClusterSnapshot` | Update the retention period of a manual cluster snapshot | | `ModifyClusterSnapshot` | Update the retention period of a manual cluster snapshot |
| `CopyClusterSnapshot` | Copy an automated cluster snapshot to a manual snapshot with a new identifier and retention period | | `CopyClusterSnapshot` | Copy an automated cluster snapshot to a manual snapshot with a new identifier and retention period |
| `RestoreFromClusterSnapshot` | Create a new cluster and load a snapshot's dump into it via `psql`; accepts `SnapshotIdentifier` or a same-region `SnapshotArn`. `OwnerAccount`, or a `SnapshotArn` of another account, restores a snapshot that account has authorized the caller to restore, and is refused with `AccessToSnapshotDenied` otherwise; the dump is read from the owner's directory and the cluster is created in the caller's account | | `RestoreFromClusterSnapshot` | Create a new cluster and load a snapshot's dump into it via `psql`; accepts `SnapshotIdentifier` or a same-region `SnapshotArn`. `OwnerAccount`, or a `SnapshotArn` of another account, restores a snapshot that account has authorized the caller to restore, and is refused with `AccessToSnapshotDenied` otherwise; the dump is read from the owner's directory and the cluster is created in the caller's account |
| `RestoreTableFromClusterSnapshot` | Create one table of a cluster snapshot in the cluster it was taken from, under `NewTableName` and in `TargetSchemaName` (default: the source schema, which defaults to `public`). See [Table restore](#table-restore) |
| `DescribeTableRestoreStatus` | List the table restore requests of a cluster in the order they were made, or one by `TableRestoreRequestId`; `MaxRecords` (20 to 100) and `Marker` page the list |
| `CreateClusterParameterGroup` | Register a parameter group (metadata only) | | `CreateClusterParameterGroup` | Register a parameter group (metadata only) |
| `DescribeClusterParameterGroups` | List parameter groups, optionally filtered by name | | `DescribeClusterParameterGroups` | List parameter groups, optionally filtered by name |
| `DescribeClusterParameters` | Return the parameters of a group, with any values set by `ModifyClusterParameterGroup` | | `DescribeClusterParameters` | Return the parameters of a group, with any values set by `ModifyClusterParameterGroup` |
@@ -660,6 +662,16 @@ Warehouse:
For `AWS::Redshift::ClusterParameterGroup`, `Parameters` is applied via `ModifyClusterParameterGroup` on both create and update. `Description` and `ParameterGroupFamily` are replacement properties, matching AWS: changing either creates a new parameter group instead of reusing the prior one. For `AWS::Redshift::ClusterParameterGroup`, `Parameters` is applied via `ModifyClusterParameterGroup` on both create and update. `Description` and `ParameterGroupFamily` are replacement properties, matching AWS: changing either creates a new parameter group instead of reusing the prior one.
### Table restore
`RestoreTableFromClusterSnapshot` lifts the table's `CREATE TABLE` statement and its rows out of the snapshot's dump and replays them, renamed, in one transaction. The cluster must be `available` and the snapshot must be an available snapshot of it. Floci differs from AWS in these ways:
- The restore runs inside the request. The response shows `PENDING`, and `DescribeTableRestoreStatus` already reports `SUCCEEDED` or `FAILED`, with the reason in `Message`. `InProgressTableRestoreQuotaExceededFault` is never returned.
- A snapshot covers one database, `dev`. A `SourceDatabaseName` or table the snapshot does not hold is refused with `InvalidTableRestoreArgument`. A target table that already exists, or a target schema or database that does not, ends the request in `FAILED` and leaves nothing behind.
- Only the definition and the rows are restored. Constraints, defaults that read a sequence and ownership are not. A partitioned table is refused with `InvalidTableRestoreArgument`, because its rows live in its partitions.
- Names are matched ignoring case unless `EnableCaseSensitiveIdentifier` is `true`, and folded to lower case in the target otherwise.
- The status of a deleted cluster's requests is dropped when they are next listed, so a cluster recreated under its name can inherit a request made against its predecessor if nothing listed them in between.
### Gaps and Limitations ### Gaps and Limitations
- `Port` is ignored: Floci assigns the dynamic host proxy port returned in `Endpoint.Port`. - `Port` is ignored: Floci assigns the dynamic host proxy port returned in `Endpoint.Port`.
@@ -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.Snapshot;
import io.floci.aws.services.redshift.model.SnapshotCopyGrant; import io.floci.aws.services.redshift.model.SnapshotCopyGrant;
import io.floci.aws.services.redshift.model.SnapshotSchedule; import io.floci.aws.services.redshift.model.SnapshotSchedule;
import io.floci.aws.services.redshift.model.TableRestoreStatus;
import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject; import jakarta.inject.Inject;
import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.MediaType;
@@ -66,6 +67,7 @@ public class RedshiftQueryHandler {
private final IamEnforcementFilter iamEnforcementFilter; private final IamEnforcementFilter iamEnforcementFilter;
private final RedshiftResourcePolicies resourcePolicies; private final RedshiftResourcePolicies resourcePolicies;
private final RedshiftScheduledActionService scheduledActions; private final RedshiftScheduledActionService scheduledActions;
private final RedshiftTableRestoreService tableRestores;
@Inject @Inject
public RedshiftQueryHandler(RedshiftService service, RedshiftCredentialBroker credentialBroker, public RedshiftQueryHandler(RedshiftService service, RedshiftCredentialBroker credentialBroker,
@@ -74,7 +76,8 @@ public class RedshiftQueryHandler {
RedshiftDynamoDbZeroEtlConsumer zeroEtlConsumer, RedshiftDynamoDbZeroEtlConsumer zeroEtlConsumer,
IamEnforcementFilter iamEnforcementFilter, IamEnforcementFilter iamEnforcementFilter,
RedshiftResourcePolicies resourcePolicies, RedshiftResourcePolicies resourcePolicies,
RedshiftScheduledActionService scheduledActions) { RedshiftScheduledActionService scheduledActions,
RedshiftTableRestoreService tableRestores) {
this.service = service; this.service = service;
this.credentialBroker = credentialBroker; this.credentialBroker = credentialBroker;
this.config = config; this.config = config;
@@ -84,12 +87,13 @@ public class RedshiftQueryHandler {
this.iamEnforcementFilter = iamEnforcementFilter; this.iamEnforcementFilter = iamEnforcementFilter;
this.resourcePolicies = resourcePolicies; this.resourcePolicies = resourcePolicies;
this.scheduledActions = scheduledActions; this.scheduledActions = scheduledActions;
this.tableRestores = tableRestores;
} }
RedshiftQueryHandler(RedshiftService service, RedshiftCredentialBroker credentialBroker, RedshiftQueryHandler(RedshiftService service, RedshiftCredentialBroker credentialBroker,
EmulatorConfig config, RedshiftIamDbUserResolver iamDbUserResolver, EmulatorConfig config, RedshiftIamDbUserResolver iamDbUserResolver,
RegionResolver regionResolver) { 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) { public Response handle(String action, MultivaluedMap<String, String> params) {
@@ -335,6 +339,49 @@ public class RedshiftQueryHandler {
.build(); .build();
return Response.ok(xml).type(MediaType.APPLICATION_XML).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" -> { case "CreateClusterParameterGroup" -> {
String parameterGroupName = params.getFirst("ParameterGroupName"); String parameterGroupName = params.getFirst("ParameterGroupName");
String parameterGroupFamily = params.getFirst("ParameterGroupFamily"); String parameterGroupFamily = params.getFirst("ParameterGroupFamily");
@@ -1722,6 +1769,30 @@ public class RedshiftQueryHandler {
.end("Event").build(); .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) { private static Boolean booleanParam(MultivaluedMap<String, String> params, String name) {
String raw = params.getFirst(name); String raw = params.getFirst(name);
if (raw == null || raw.isBlank()) { if (raw == null || raw.isBlank()) {
@@ -2493,6 +2493,40 @@ public class RedshiftService implements ManagedSecretRotator {
return snapshot; 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) { public Cluster restoreFromClusterSnapshot(String clusterIdentifier, String snapshotIdentifier) {
return restoreFromClusterSnapshot(clusterIdentifier, snapshotIdentifier, null); 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 " private static final String DROP_USER_SCHEMAS_SQL = "DO $$ DECLARE s text; BEGIN "
+ "PERFORM lo_unlink(oid) FROM pg_largeobject_metadata; " + "PERFORM lo_unlink(oid) FROM pg_largeobject_metadata; "
+ "FOR s IN SELECT nspname FROM pg_namespace WHERE nspname NOT IN ('pg_catalog', 'information_schema') " + "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.core.common.PaginatedResult;
import io.floci.aws.services.redshift.RedshiftIamDbUserResolver; import io.floci.aws.services.redshift.RedshiftIamDbUserResolver;
import io.floci.aws.services.redshift.TempCredential; 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.ConfigParameter;
import io.floci.aws.services.redshiftserverless.model.CustomDomainAssociation; import io.floci.aws.services.redshiftserverless.model.CustomDomainAssociation;
import io.floci.aws.services.redshiftserverless.model.Namespace; import io.floci.aws.services.redshiftserverless.model.Namespace;
@@ -48,6 +49,7 @@ public class RedshiftServerlessJsonHandler {
private final RedshiftServerlessAdminJsonHandler admin; private final RedshiftServerlessAdminJsonHandler admin;
private final RedshiftServerlessCustomDomainService customDomains; private final RedshiftServerlessCustomDomainService customDomains;
private final RedshiftServerlessSharedSnapshots sharedSnapshots; private final RedshiftServerlessSharedSnapshots sharedSnapshots;
private final RedshiftServerlessTableRestoreService tableRestores;
@Inject @Inject
public RedshiftServerlessJsonHandler(RedshiftServerlessService service, ObjectMapper objectMapper, public RedshiftServerlessJsonHandler(RedshiftServerlessService service, ObjectMapper objectMapper,
@@ -55,7 +57,8 @@ public class RedshiftServerlessJsonHandler {
RedshiftServerlessUsageLimitService usageLimits, RedshiftServerlessUsageLimitService usageLimits,
RedshiftServerlessAdminJsonHandler admin, RedshiftServerlessAdminJsonHandler admin,
RedshiftServerlessCustomDomainService customDomains, RedshiftServerlessCustomDomainService customDomains,
RedshiftServerlessSharedSnapshots sharedSnapshots) { RedshiftServerlessSharedSnapshots sharedSnapshots,
RedshiftServerlessTableRestoreService tableRestores) {
this.service = service; this.service = service;
this.objectMapper = objectMapper; this.objectMapper = objectMapper;
this.iamDbUserResolver = iamDbUserResolver; this.iamDbUserResolver = iamDbUserResolver;
@@ -63,6 +66,7 @@ public class RedshiftServerlessJsonHandler {
this.admin = admin; this.admin = admin;
this.customDomains = customDomains; this.customDomains = customDomains;
this.sharedSnapshots = sharedSnapshots; this.sharedSnapshots = sharedSnapshots;
this.tableRestores = tableRestores;
} }
public Response handle(String action, JsonNode request, String region) { public Response handle(String action, JsonNode request, String region) {
@@ -89,6 +93,9 @@ public class RedshiftServerlessJsonHandler {
case "UpdateSnapshot" -> () -> handleUpdateSnapshot(request, region); case "UpdateSnapshot" -> () -> handleUpdateSnapshot(request, region);
case "DeleteSnapshot" -> () -> handleDeleteSnapshot(request, region); case "DeleteSnapshot" -> () -> handleDeleteSnapshot(request, region);
case "RestoreFromSnapshot" -> () -> handleRestoreFromSnapshot(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 "CreateUsageLimit" -> () -> handleCreateUsageLimit(request, region);
case "GetUsageLimit" -> () -> handleGetUsageLimit(request, region); case "GetUsageLimit" -> () -> handleGetUsageLimit(request, region);
case "ListUsageLimits" -> () -> handleListUsageLimits(request, region); case "ListUsageLimits" -> () -> handleListUsageLimits(request, region);
@@ -294,6 +301,72 @@ public class RedshiftServerlessJsonHandler {
ServerlessSupport.text(request, "snapshotName"), ServerlessSupport.integer(request, "retentionPeriod"), region)); 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) { private Response handleDeleteSnapshot(JsonNode request, String region) {
return snapshotResponse(service.deleteSnapshot(ServerlessSupport.text(request, "snapshotName"), 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) {} 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) { public Map<String, String> listTagsForResource(String resourceArn, String region) {
requireResourceArn(resourceArn); requireResourceArn(resourceArn);
Optional<Namespace> namespace = namespaceByArn(resourceArn, region); 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;
}
}
@@ -51,7 +51,7 @@ class RedshiftScheduledActionQueryTest {
Clock.fixed(Instant.parse("2026-11-20T12:15:00Z"), ZoneOffset.UTC)); Clock.fixed(Instant.parse("2026-11-20T12:15:00Z"), ZoneOffset.UTC));
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
handler = new RedshiftQueryHandler(redshift, new RedshiftCredentialBroker(), config, handler = new RedshiftQueryHandler(redshift, new RedshiftCredentialBroker(), config,
mock(RedshiftIamDbUserResolver.class), regionResolver, null, null, null, scheduledActions); mock(RedshiftIamDbUserResolver.class), regionResolver, null, null, null, scheduledActions, null);
} }
private static MultivaluedMap<String, String> createParams(String name) { private static MultivaluedMap<String, String> createParams(String name) {
@@ -2072,6 +2072,22 @@ class RedshiftServiceTest {
verifyNoInteractions(cm); verifyNoInteractions(cm);
} }
@Test
void tableRestoreSourceRefusesASnapshotOfAnotherRegion() {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("c1");
cluster.setClusterStatus("available");
Snapshot snapshot = snapshotOf("snap-1", "c1");
snapshot.setStatus("available");
snapshot.setSnapshotArn("arn:aws:redshift:eu-west-1:111111111111:snapshot:c1/snap-1");
when(clusterBackend.get("c1")).thenReturn(Optional.of(cluster));
when(snapshotBackend.get("snap-1")).thenReturn(Optional.of(snapshot));
AwsException ex = assertThrows(AwsException.class, () -> service.tableRestoreSource("c1", "snap-1"));
assertEquals("ClusterSnapshotNotFound", ex.getErrorCode());
}
@Test @Test
void authorizeSnapshotAccessRecordsTheAccountOnceAndRevokeRemovesIt() { void authorizeSnapshotAccessRecordsTheAccountOnceAndRevokeRemovesIt() {
Snapshot snapshot = snapshotOf("snap-1", "c1"); Snapshot snapshot = snapshotOf("snap-1", "c1");
@@ -0,0 +1,133 @@
package io.floci.aws.services.redshift;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class RedshiftSnapshotTableExtractorTest {
private static final String DUMP = String.join("\n",
"SET search_path = '';",
"CREATE TABLE public.orders (",
" id integer NOT NULL,",
" note character varying(20)",
");",
"COPY public.orders (id, note) FROM stdin;",
"1\tCREATE TABLE public.sneaky (",
"2\thello",
"\\.",
"CREATE TABLE public.empty_table (",
" id integer",
");",
"CREATE TABLE sales.\"Mixed Case\" (",
" id integer",
");",
"COPY sales.\"Mixed Case\" (id) FROM stdin;",
"7",
"\\.",
"");
private Path dump;
@BeforeEach
void writeDump(@TempDir Path directory) throws IOException {
dump = Files.writeString(directory.resolve("snapshot.sql"), DUMP);
}
private Optional<String> script(String schema, String table, String targetSchema, String newTable,
boolean caseSensitive) throws IOException {
return RedshiftSnapshotTableExtractor.restoreScript(dump, schema, table, targetSchema, newTable,
caseSensitive);
}
@Test
void renamesTheTableAndKeepsItsRowsInOneTransaction() throws IOException {
String script = script("public", "orders", "archive", "orders_copy", false).orElseThrow();
assertEquals(String.join("\n",
"BEGIN;",
"CREATE TABLE \"archive\".\"orders_copy\" (",
" id integer NOT NULL,",
" note character varying(20)",
");",
"COPY \"archive\".\"orders_copy\" (id, note) FROM stdin;",
"1\tCREATE TABLE public.sneaky (",
"2\thello",
"\\.",
"COMMIT;",
""), script);
}
@Test
void aTableWithoutRowsHasNoCopyBlock() throws IOException {
String script = script("public", "empty_table", "public", "copy", false).orElseThrow();
assertTrue(script.contains("CREATE TABLE \"public\".\"copy\" ("), script);
assertFalse(script.contains("COPY"), script);
}
@Test
void anUnknownTableOrOneInsideRowDataIsNotFound() throws IOException {
assertTrue(script("public", "missing", "public", "x", false).isEmpty());
assertTrue(script("public", "sneaky", "public", "x", false).isEmpty());
assertTrue(script("other", "orders", "public", "x", false).isEmpty());
}
@Test
void namesMatchIgnoringCaseUnlessTheRequestIsCaseSensitive() throws IOException {
assertTrue(script("SALES", "mixed case", "public", "x", false).isPresent());
assertTrue(script("sales", "mixed case", "public", "x", true).isEmpty());
assertTrue(script("sales", "Mixed Case", "public", "x", true).isPresent());
}
@Test
void anUnloggedTableKeepsItsQualifierAndItsRows() throws IOException {
Files.writeString(dump, String.join("\n",
"CREATE UNLOGGED TABLE public.scratch (",
" id integer",
");",
"COPY public.scratch (id) FROM stdin;",
"5",
"\\.",
""));
String script = script("public", "scratch", "public", "scratch_copy", false).orElseThrow();
assertTrue(script.contains("CREATE UNLOGGED TABLE \"public\".\"scratch_copy\" ("), script);
assertTrue(script.contains("COPY \"public\".\"scratch_copy\" (id) FROM stdin;"), script);
}
@Test
void aPartitionedTableIsRefusedBecauseItsRowsLiveInItsPartitions() throws IOException {
Files.writeString(dump, String.join("\n",
"CREATE TABLE public.events (",
" id integer",
")",
"PARTITION BY RANGE (id);",
"CREATE TABLE public.events_1 (",
" id integer",
");",
""));
assertThrows(RedshiftSnapshotTableExtractor.UnsupportedTableException.class,
() -> script("public", "events", "public", "copy", false));
assertTrue(script("public", "events_1", "public", "copy", false).isPresent());
}
@Test
void aTargetNameWithAQuoteStaysOneIdentifier() throws IOException {
String script = script("public", "orders", "public", "a\"; DROP TABLE x; --", false).orElseThrow();
assertTrue(script.contains("CREATE TABLE \"public\".\"a\"\"; DROP TABLE x; --\" ("), script);
}
}
@@ -0,0 +1,105 @@
package io.floci.aws.services.redshift;
import io.floci.aws.services.redshift.model.Cluster;
import io.floci.aws.services.redshift.model.TableRestoreStatus;
import io.floci.aws.testing.DockerAvailability;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** Restores one table of a snapshot on a real cluster: write rows, snapshot, restore under a new name, read them back. */
@QuarkusTest
class RedshiftTableRestoreIntegrationTest {
@Inject
RedshiftService service;
@Inject
RedshiftTableRestoreService tableRestores;
private String clusterId;
@BeforeAll
static void requireDocker() throws InterruptedException {
Assumptions.assumeTrue(DockerAvailability.isAvailable(),
"Docker daemon must be available for Redshift table restore integration tests");
}
@AfterEach
void cleanUp() {
if (clusterId != null) {
service.deleteCluster(clusterId);
}
}
private RedshiftTableRestoreService.Request restore(String snapshotId, String sourceTable, String newTable) {
return new RedshiftTableRestoreService.Request(clusterId, snapshotId, "dev", null, sourceTable, null, null,
newTable, false);
}
private TableRestoreStatus finished(String requestId) {
return Awaitility.await().atMost(Duration.ofSeconds(30)).until(
() -> tableRestores.describeTableRestoreStatus(clusterId, requestId, null, null).items().getFirst(),
status -> !TableRestoreStatus.PENDING.equals(status.getStatus())
&& !TableRestoreStatus.IN_PROGRESS.equals(status.getStatus()));
}
private static List<String> notes(Connection connection, String table) throws SQLException {
List<String> notes = new ArrayList<>();
try (Statement statement = connection.createStatement();
ResultSet rows = statement.executeQuery("SELECT note FROM " + table + " ORDER BY id")) {
while (rows.next()) {
notes.add(rows.getString(1));
}
}
return notes;
}
@Test
void aTableOfASnapshotIsRestoredUnderANewNameWithItsRows() throws Exception {
clusterId = "tbl-restore-" + UUID.randomUUID().toString().substring(0, 8);
String snapshotId = clusterId + "-snap";
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123");
try (Connection connection = RedshiftConnections.waitForConnection(cluster);
Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE orders (id integer, note varchar(40))");
statement.execute("INSERT INTO orders VALUES (1, 'first'), (2, 'it''s, quoted'), (3, 'third')");
service.createSnapshot(snapshotId, clusterId);
statement.execute("INSERT INTO orders VALUES (4, 'after the snapshot')");
TableRestoreStatus accepted = tableRestores.restoreTable(restore(snapshotId, "orders", "orders_restored"));
assertEquals(TableRestoreStatus.PENDING, accepted.getStatus());
TableRestoreStatus done = finished(accepted.getTableRestoreRequestId());
assertEquals(TableRestoreStatus.SUCCEEDED, done.getStatus(), done.getMessage());
assertEquals(List.of("first", "it's, quoted", "third"), notes(connection, "orders_restored"));
assertEquals(4, notes(connection, "orders").size(), "the source table is left as it was");
TableRestoreStatus again = finished(
tableRestores.restoreTable(restore(snapshotId, "orders", "orders_restored"))
.getTableRestoreRequestId());
assertEquals(TableRestoreStatus.FAILED, again.getStatus());
assertTrue(again.getMessage().contains("already exists"), again.getMessage());
assertEquals(List.of("first", "it's, quoted", "third"), notes(connection, "orders_restored"));
} finally {
service.deleteSnapshot(snapshotId);
}
}
}
@@ -0,0 +1,114 @@
package io.floci.aws.services.redshift;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.services.redshift.model.TableRestoreStatus;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.time.Instant;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class RedshiftTableRestoreQueryTest {
private RedshiftTableRestoreService tableRestores;
private RedshiftQueryHandler handler;
@BeforeEach
void setUp() {
tableRestores = mock(RedshiftTableRestoreService.class);
handler = new RedshiftQueryHandler(mock(RedshiftService.class), new RedshiftCredentialBroker(),
mock(EmulatorConfig.class, RETURNS_DEEP_STUBS), mock(RedshiftIamDbUserResolver.class),
mock(RegionResolver.class), null, null, null, null, tableRestores);
}
private static TableRestoreStatus status(String state) {
TableRestoreStatus status = new TableRestoreStatus();
status.setTableRestoreRequestId("req-1");
status.setStatus(state);
status.setRequestTime(Instant.parse("2026-11-20T12:00:00Z"));
status.setClusterIdentifier("analytics");
status.setSnapshotIdentifier("snap");
status.setSourceDatabaseName("dev");
status.setSourceSchemaName("public");
status.setSourceTableName("orders");
status.setTargetDatabaseName("dev");
status.setTargetSchemaName("public");
status.setNewTableName("orders_copy");
status.setProgressInMegaBytes(0L);
status.setTotalDataInMegaBytes(0L);
return status;
}
private static MultivaluedMap<String, String> restoreParams() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.add("ClusterIdentifier", "analytics");
params.add("SnapshotIdentifier", "snap");
params.add("SourceDatabaseName", "dev");
params.add("SourceTableName", "orders");
params.add("NewTableName", "orders_copy");
return params;
}
@Test
void restoreReturnsTheTableRestoreStatusAndPassesTheRequestMembers() {
when(tableRestores.restoreTable(any())).thenReturn(status("PENDING"));
MultivaluedMap<String, String> params = restoreParams();
params.add("SourceSchemaName", "sales");
params.add("EnableCaseSensitiveIdentifier", "true");
Response response = handler.handle("RestoreTableFromClusterSnapshot", params);
String xml = String.valueOf(response.getEntity());
assertTrue(xml.contains("<RestoreTableFromClusterSnapshotResult><TableRestoreStatus>"), xml);
assertTrue(xml.contains("<TableRestoreRequestId>req-1</TableRestoreRequestId>"), xml);
assertTrue(xml.contains("<Status>PENDING</Status>"), xml);
assertTrue(xml.contains("<RequestTime>2026-11-20T12:00:00Z</RequestTime>"), xml);
assertTrue(xml.contains("<NewTableName>orders_copy</NewTableName>"), xml);
assertFalse(xml.contains("<Message>"), xml);
ArgumentCaptor<RedshiftTableRestoreService.Request> request =
ArgumentCaptor.forClass(RedshiftTableRestoreService.Request.class);
verify(tableRestores).restoreTable(request.capture());
assertEquals("sales", request.getValue().sourceSchemaName());
assertTrue(request.getValue().caseSensitive());
}
@Test
void aMissingRequiredMemberIsRefused() {
MultivaluedMap<String, String> params = restoreParams();
params.remove("NewTableName");
assertEquals("InvalidParameterValue", assertThrows(AwsException.class,
() -> handler.handle("RestoreTableFromClusterSnapshot", params)).getErrorCode());
}
@Test
void describeListsTheRequestsWithTheMarker() {
when(tableRestores.describeTableRestoreStatus("analytics", null, null, null))
.thenReturn(new PaginatedResult<>(List.of(status("SUCCEEDED")), "next"));
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.add("ClusterIdentifier", "analytics");
String xml = String.valueOf(handler.handle("DescribeTableRestoreStatus", params).getEntity());
assertTrue(xml.contains("<TableRestoreStatusDetails><TableRestoreStatus>"), xml);
assertTrue(xml.contains("<Status>SUCCEEDED</Status>"), xml);
assertTrue(xml.contains("<Marker>next</Marker>"), xml);
}
}
@@ -0,0 +1,160 @@
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.RegionResolver;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.redshift.RedshiftService.TableRestoreSource;
import io.floci.aws.services.redshift.container.RedshiftContainerManager;
import io.floci.aws.services.redshift.model.Cluster;
import io.floci.aws.services.redshift.model.TableRestoreStatus;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.function.Supplier;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class RedshiftTableRestoreServiceTest {
private static final String ACCOUNT_ID = "123456789012";
private static final String DUMP = "CREATE TABLE public.orders (\n id integer\n);\n";
private RedshiftService redshift;
private RedshiftContainerManager containerManager;
private final List<String> scripts = new ArrayList<>();
private RedshiftTableRestoreService service;
@BeforeEach
@SuppressWarnings({"unchecked", "rawtypes"})
void setUp(@TempDir Path directory) throws Exception {
AccountAwareStorageBackend<TableRestoreStatus> store =
new AccountAwareStorageBackend<>(new InMemoryStorage<String, TableRestoreStatus>(), null, ACCOUNT_ID);
StorageFactory storageFactory = mock(StorageFactory.class);
when(storageFactory.create(eq("redshift"), eq("redshift-table-restores.json"),
any(TypeReference.class))).thenReturn((AccountAwareStorageBackend) store);
Path dump = Files.writeString(directory.resolve("snapshot.sql"), DUMP);
Cluster cluster = new Cluster();
cluster.setMasterUsername("admin");
redshift = mock(RedshiftService.class);
when(redshift.tableRestoreSource("analytics", "snap")).thenReturn(new TableRestoreSource(cluster, dump, "dev"));
when(redshift.hasCluster("analytics")).thenReturn(true);
when(redshift.withResourceLock(anyString(), anyString(), anyString(), any())).thenAnswer(
call -> ((Supplier<?>) call.getArgument(3)).get());
containerManager = mock(RedshiftContainerManager.class);
doAnswer(call -> {
scripts.add(Files.readString(call.getArgument(4, Path.class)));
return null;
}).when(containerManager).runTableRestoreScript(anyString(), anyString(), anyString(), anyString(),
any(Path.class));
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn(ACCOUNT_ID);
service = new RedshiftTableRestoreService(storageFactory, redshift, new RedshiftTableRestorer(containerManager),
regionResolver,
Clock.fixed(Instant.parse("2026-11-20T12:00:00Z"), ZoneOffset.UTC));
}
private static RedshiftTableRestoreService.Request request(String sourceDatabase, String sourceTable) {
return new RedshiftTableRestoreService.Request("analytics", "snap", sourceDatabase, null, sourceTable, null,
null, "Orders_Copy", false);
}
@Test
void theRequestIsReportedPendingAndLaterDescribedAsSucceeded() {
TableRestoreStatus accepted = service.restoreTable(request("dev", "orders"));
assertEquals(TableRestoreStatus.PENDING, accepted.getStatus());
assertEquals("public", accepted.getSourceSchemaName());
assertEquals("public", accepted.getTargetSchemaName());
assertEquals("dev", accepted.getTargetDatabaseName());
assertEquals("Orders_Copy", accepted.getNewTableName());
verify(containerManager).runTableRestoreScript(eq(ACCOUNT_ID), eq("analytics"), eq("admin"), eq("dev"),
any(Path.class));
assertEquals(List.of("BEGIN;\nCREATE TABLE \"public\".\"orders_copy\" (\n id integer\n);\nCOMMIT;\n"),
scripts);
TableRestoreStatus described = service.describeTableRestoreStatus(
"analytics", accepted.getTableRestoreRequestId(), null, null).items().getFirst();
assertEquals(TableRestoreStatus.SUCCEEDED, described.getStatus());
assertNull(described.getMessage());
}
@Test
void aFailingScriptIsRecordedAsFailedWithItsReason() {
doThrow(new AwsException("InternalFailure", "psql:/tmp/x.sql:2: ERROR: relation already exists", 500))
.when(containerManager).runTableRestoreScript(anyString(), anyString(), anyString(), anyString(),
any(Path.class));
TableRestoreStatus accepted = service.restoreTable(request("dev", "orders"));
TableRestoreStatus described = service.describeTableRestoreStatus(
"analytics", accepted.getTableRestoreRequestId(), null, null).items().getFirst();
assertEquals(TableRestoreStatus.FAILED, described.getStatus());
assertEquals("The table could not be restored: relation already exists", described.getMessage());
}
@Test
void aTargetDatabaseOtherThanTheClustersIsRefused() {
RedshiftTableRestoreService.Request request = new RedshiftTableRestoreService.Request("analytics", "snap",
"dev", null, "orders", "dev host=evil", null, "copy", false);
assertEquals("InvalidTableRestoreArgument",
assertThrows(AwsException.class, () -> service.restoreTable(request)).getErrorCode());
}
@Test
void aSourceTableOrDatabaseThatIsNotInTheSnapshotIsRefused() {
assertEquals("InvalidTableRestoreArgument", assertThrows(AwsException.class,
() -> service.restoreTable(request("dev", "missing"))).getErrorCode());
assertEquals("InvalidTableRestoreArgument", assertThrows(AwsException.class,
() -> service.restoreTable(request("other", "orders"))).getErrorCode());
assertTrue(service.describeTableRestoreStatus("analytics", null, null, null).items().isEmpty());
}
@Test
void describeListsInRequestOrderFiltersAndRefusesUnknownIdsAndBadPageSizes() {
TableRestoreStatus first = service.restoreTable(request("dev", "orders"));
TableRestoreStatus second = service.restoreTable(request("dev", "orders"));
PaginatedResult<TableRestoreStatus> all = service.describeTableRestoreStatus(null, null, null, null);
assertEquals(2, all.items().size());
assertEquals(Set.of(first.getTableRestoreRequestId(), second.getTableRestoreRequestId()),
Set.of(all.items().get(0).getTableRestoreRequestId(),
all.items().get(1).getTableRestoreRequestId()));
assertEquals("TableRestoreNotFoundFault", assertThrows(AwsException.class,
() -> service.describeTableRestoreStatus(null, "nope", null, null)).getErrorCode());
assertEquals("InvalidParameterValue", assertThrows(AwsException.class,
() -> service.describeTableRestoreStatus(null, null, 5, null)).getErrorCode());
}
@Test
void requestsOfADeletedClusterAreDropped() {
service.restoreTable(request("dev", "orders"));
when(redshift.hasCluster("analytics")).thenReturn(false);
assertTrue(service.describeTableRestoreStatus(null, null, null, null).items().isEmpty());
}
}
@@ -0,0 +1,34 @@
package io.floci.aws.services.redshift;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.redshift.container.RedshiftContainerManager;
import org.junit.jupiter.api.Test;
import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
class RedshiftTableRestorerTest {
@Test
void aFailureReportsThePsqlErrorWithoutTheRowsInItsContext() {
RedshiftContainerManager containerManager = mock(RedshiftContainerManager.class);
doThrow(new AwsException("InternalFailure", "Failed to restore snapshot for cluster c: psql:/tmp/x.sql:9: "
+ "ERROR: invalid input syntax for type integer: \"secret-row\"\nCONTEXT: COPY t, line 1: \"secret-row\"",
500)).when(containerManager).runTableRestoreScript(anyString(), anyString(), anyString(), anyString(),
any(Path.class));
AwsException failure = assertThrows(AwsException.class,
() -> new RedshiftTableRestorer(containerManager).run("1", "c", "admin", "dev", "BEGIN;\nCOMMIT;\n"));
assertEquals("The table could not be restored: invalid input syntax for type integer: \"secret-row\"",
failure.getMessage());
assertFalse(failure.getMessage().contains("CONTEXT"));
}
}
@@ -100,7 +100,8 @@ class RedshiftServerlessAdministrationHandlerTest {
new RedshiftServerlessSnapshotCopyService(storageFactory, regionResolver, serverlessService), new RedshiftServerlessSnapshotCopyService(storageFactory, regionResolver, serverlessService),
new RedshiftServerlessScheduledActionService(storageFactory, serverlessService, new RedshiftServerlessScheduledActionService(storageFactory, serverlessService,
mock(RedshiftServerlessScheduledActionAuthorizer.class), regionResolver)), mock(RedshiftServerlessScheduledActionAuthorizer.class), regionResolver)),
customDomains, mock(RedshiftServerlessSharedSnapshots.class)); customDomains, mock(RedshiftServerlessSharedSnapshots.class),
mock(RedshiftServerlessTableRestoreService.class));
} }
@Test @Test
@@ -134,7 +134,8 @@ class RedshiftServerlessJsonHandlerTest {
new RedshiftServerlessSnapshotCopyService(storageFactory, regionResolver, service), new RedshiftServerlessSnapshotCopyService(storageFactory, regionResolver, service),
new RedshiftServerlessScheduledActionService(storageFactory, service, new RedshiftServerlessScheduledActionService(storageFactory, service,
mock(RedshiftServerlessScheduledActionAuthorizer.class), regionResolver)), mock(RedshiftServerlessScheduledActionAuthorizer.class), regionResolver)),
customDomains, mock(RedshiftServerlessSharedSnapshots.class)); customDomains, mock(RedshiftServerlessSharedSnapshots.class),
mock(RedshiftServerlessTableRestoreService.class));
} }
@SuppressWarnings({"unchecked", "rawtypes"}) @SuppressWarnings({"unchecked", "rawtypes"})
@@ -1063,6 +1063,19 @@ class RedshiftServerlessServiceTest {
assertEquals("ResourceNotFoundException", noSnapshot.getErrorCode()); assertEquals("ResourceNotFoundException", noSnapshot.getErrorCode());
} }
@Test
void tableRestoreRefusesAWorkgroupOfAnotherNamespace() {
create("table-ns-a");
create("table-ns-b");
service.createSnapshot("table-snap", "table-ns-a", null, null, REGION);
createWorkgroup("table-wg-b", "table-ns-b");
AwsException mismatch = assertThrows(AwsException.class,
() -> service.tableRestoreSource("table-ns-a", "table-wg-b", "table-snap", REGION));
assertEquals("ValidationException", mismatch.getErrorCode());
}
@Test @Test
void restoreFromSharedSnapshotReadsTheSnapshotOfAnotherAccount() throws Exception { void restoreFromSharedSnapshotReadsTheSnapshotOfAnotherAccount() throws Exception {
String owner = "999999999999"; String owner = "999999999999";
@@ -0,0 +1,160 @@
package io.floci.aws.services.redshiftserverless;
import com.fasterxml.jackson.core.type.TypeReference;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.redshift.RedshiftTableRestorer;
import io.floci.aws.services.redshift.container.RedshiftContainerManager;
import io.floci.aws.services.redshift.model.TableRestoreStatus;
import io.floci.aws.services.redshiftserverless.RedshiftServerlessService.TableRestoreSource;
import io.floci.aws.services.redshiftserverless.model.Namespace;
import io.floci.aws.services.redshiftserverless.model.Workgroup;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class RedshiftServerlessTableRestoreServiceTest {
private static final String ACCOUNT_ID = "123456789012";
private static final String REGION = "us-east-1";
private RedshiftServerlessService serverless;
private RedshiftContainerManager containerManager;
private Path dump;
private RedshiftServerlessTableRestoreService service;
@BeforeEach
@SuppressWarnings({"unchecked", "rawtypes"})
void setUp(@TempDir Path directory) throws Exception {
AccountAwareStorageBackend<TableRestoreStatus> store =
new AccountAwareStorageBackend<>(new InMemoryStorage<String, TableRestoreStatus>(), null, ACCOUNT_ID);
StorageFactory storageFactory = mock(StorageFactory.class);
when(storageFactory.create(eq("redshiftserverless"), eq("redshiftserverless-table-restores.json"),
any(TypeReference.class))).thenReturn((AccountAwareStorageBackend) store);
Namespace namespace = new Namespace();
namespace.setDbName("dev");
Workgroup workgroup = new Workgroup();
workgroup.setMasterUsername("admin");
dump = Files.writeString(directory.resolve("snapshot.sql"),
String.join("\n", "CREATE TABLE public.orders (", " id integer", ");", ""));
serverless = mock(RedshiftServerlessService.class);
when(serverless.tableRestoreSource("ns", "wg", "snap", REGION))
.thenReturn(new TableRestoreSource(workgroup, namespace, dump));
when(serverless.findWorkgroup("wg", REGION)).thenReturn(Optional.of(workgroup));
containerManager = mock(RedshiftContainerManager.class);
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn(ACCOUNT_ID);
service = new RedshiftServerlessTableRestoreService(storageFactory, serverless,
new RedshiftTableRestorer(containerManager), regionResolver,
Clock.fixed(Instant.parse("2026-11-20T12:00:00Z"), ZoneOffset.UTC));
}
private static RedshiftServerlessTableRestoreService.Request request(String sourceTable) {
return new RedshiftServerlessTableRestoreService.Request("ns", "wg", "snap", "dev", null, sourceTable, null,
null, "orders_copy", false);
}
@Test
void theRequestIsReportedPendingAndLaterReadAsSucceeded() {
TableRestoreStatus accepted = service.restoreTable(request("orders"), REGION);
assertEquals(TableRestoreStatus.PENDING, accepted.getStatus());
assertEquals("public", accepted.getTargetSchemaName());
assertEquals("wg", accepted.getWorkgroupName());
verify(containerManager).runTableRestoreScript(eq(ACCOUNT_ID), eq("serverless_us-east-1_wg"), eq("admin"),
eq("dev"), any(Path.class));
TableRestoreStatus read = service.getTableRestoreStatus(accepted.getTableRestoreRequestId(), REGION);
assertEquals(TableRestoreStatus.SUCCEEDED, read.getStatus());
assertEquals(1, service.listTableRestoreStatus("ns", "wg", null, null, REGION).items().size());
assertTrue(service.listTableRestoreStatus("other", null, null, null, REGION).items().isEmpty());
}
@Test
void aTargetDatabaseOtherThanTheNamespacesIsRefused() {
RedshiftServerlessTableRestoreService.Request request = new RedshiftServerlessTableRestoreService.Request(
"ns", "wg", "snap", "dev", null, "orders", "dev host=evil", null, "copy", false);
assertEquals("ValidationException",
assertThrows(AwsException.class, () -> service.restoreTable(request, REGION)).getErrorCode());
}
@Test
void aFailingScriptIsRecordedAsFailed() {
doThrow(new AwsException("InternalFailure", "psql:/tmp/x.sql:2: ERROR: relation already exists", 500))
.when(containerManager).runTableRestoreScript(anyString(), anyString(), anyString(), anyString(),
any(Path.class));
TableRestoreStatus accepted = service.restoreTable(request("orders"), REGION);
TableRestoreStatus read = service.getTableRestoreStatus(accepted.getTableRestoreRequestId(), REGION);
assertEquals(TableRestoreStatus.FAILED, read.getStatus());
assertEquals("The table could not be restored: relation already exists", read.getMessage());
}
@Test
void anUnknownTableDatabaseOrRequestIsRefused() {
assertEquals("ValidationException", assertThrows(AwsException.class,
() -> service.restoreTable(request("missing"), REGION)).getErrorCode());
assertEquals("ValidationException", assertThrows(AwsException.class, () -> service.restoreTable(
new RedshiftServerlessTableRestoreService.Request("ns", "wg", "snap", "other", null, "orders", null,
null, "copy", false), REGION)).getErrorCode());
assertEquals("ResourceNotFoundException", assertThrows(AwsException.class,
() -> service.getTableRestoreStatus("nope", REGION)).getErrorCode());
}
@Test
void missingRequiredMembersAreAValidationErrorAndWriteNothing() {
assertEquals("ValidationException", assertThrows(AwsException.class, () -> service.restoreTable(
new RedshiftServerlessTableRestoreService.Request("ns", "wg", "snap", null, null, "orders", null, null,
"copy", false), REGION)).getErrorCode());
assertEquals("ValidationException", assertThrows(AwsException.class,
() -> service.getTableRestoreStatus(null, REGION)).getErrorCode());
assertTrue(service.listTableRestoreStatus(null, null, null, null, REGION).items().isEmpty());
}
@Test
void aPartitionedTableIsRefused() throws Exception {
Files.writeString(dump, String.join("\n", "CREATE TABLE public.orders (", " id integer", ")",
"PARTITION BY RANGE (id);", ""));
assertEquals("ValidationException", assertThrows(AwsException.class,
() -> service.restoreTable(request("orders"), REGION)).getErrorCode());
}
@Test
void aBadNextTokenIsAnInvalidPaginationException() {
assertEquals("InvalidPaginationException", assertThrows(AwsException.class,
() -> service.listTableRestoreStatus(null, null, null, "not-a-token", REGION)).getErrorCode());
}
@Test
void requestsOfADeletedWorkgroupAreDropped() {
TableRestoreStatus accepted = service.restoreTable(request("orders"), REGION);
when(serverless.findWorkgroup("wg", REGION)).thenReturn(Optional.empty());
assertTrue(service.listTableRestoreStatus(null, null, null, null, REGION).items().isEmpty());
assertEquals("ResourceNotFoundException", assertThrows(AwsException.class,
() -> service.getTableRestoreStatus(accepted.getTableRestoreRequestId(), REGION)).getErrorCode());
}
}