mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 14:10:49 -05:00
feat(redshift): implement Redshift emulation with snapshot and parameter group support (#2472)
* feat: add redshift domain models
* feat: add redshift service and test
* feat: add redshift query handler and routing
* feat(redshift): implement data plane container manager and wire storage
This commit implements Redshift Container Manager, wires the StorageFactory into RedshiftService, uses AwsException for error handling, implements Describe/Delete Clusters, and adds integration tests with AWS SDK in the compatibility tests project.
* feat: add redshift operations models and service logic
* fix: correct yaml indentation for redshift storage config
* fix: remove invalid redshift storage properties
* feat: implement pg_dump and psql for redshift snapshots
* feat: add redshift core operations query actions
* test: add redshift operations integration test
* fix(redshift): Write snapshot SQL dumps to file storage and add Parameter model
* docs: add redshift implementation plan, design spec, and PR description
* chore: remove superpowers working files
* fix(redshift): scope snapshots and cluster recovery per account, restore original password
- Scope snapshot SQL dump files under redshift-dumps/{accountId}/ so
same-identifier snapshots from different accounts no longer collide,
overwrite, or delete each other's data.
- Restore uses the source cluster's real master password instead of a
hardcoded value, falling back to "admin" only when the source cluster
no longer exists.
- Recreate Docker containers for all persisted "available" clusters on
startup, across every account (not just the default), fixing clusters
that were reloaded with stale endpoints but no running container.
- Add AccountAwareStorageBackend.accountId() accessor needed for the
account-scoped dump path.
* fix(redshift): add logging for cleanup failures in RedshiftOperationsTest
* fix(redshift): scope container identity per account, persist snapshot password
- RedshiftContainerManager now keys its in-memory container map and Docker
container name by accountId + clusterIdentifier, instead of just the
cluster identifier. Previously two accounts creating a cluster with the
same identifier would share (and clobber) the same Docker container,
so startup recovery for the second account silently skipped its own
cluster and left it advertised with a stale endpoint.
- Snapshot now captures masterPassword at snapshot-creation time, so
restoreFromClusterSnapshot can recover the original credential even
after the source cluster has been deleted, instead of falling back to
"admin".
- Clean up fully-qualified java.nio.file / commons-compress references in
RedshiftContainerManager in favor of imports.
* feat(redshift): implement adoptOrStart method to reuse existing containers
* chore: gitignore subagent-driven-development scratch workspace
* feat(redshift): add tagging support to RedshiftService
- Add tags field to Cluster, Snapshot, and ClusterParameterGroup models
- Inject RegionResolver into RedshiftService constructor
- Implement tag CRUD methods: createTags, deleteTags, describeTags, listTagsForResource
- Add resolveTagHandle ARN resolver for tagging operations
- Add 6 new unit tests covering tag operations and error cases
* feat(redshift): wire CreateTags/DeleteTags/DescribeTags into the query handler
* feat(redshift): store real parameter values on ClusterParameterGroup
* fix(redshift): use proper imports and preserve parameter metadata on modify
* feat(redshift): wire ModifyClusterParameterGroup, return real DescribeClusterParameters values
* feat(redshift): add ClusterSubnetGroup model and CRUD
* feat(redshift): wire ClusterSubnetGroup CRUD into the query handler
* feat(redshift): add ClusterSubnetGroupName/VpcSecurityGroupIds metadata to Cluster
* feat(redshift): add RedshiftContainerManager.alterUserPassword
* fix(redshift): prevent SQL injection in alterUserPassword via username validation
* feat(redshift): add RedshiftService.modifyCluster
* feat(redshift): add RedshiftService.rebootCluster (dump/restore based, no data loss)
* feat(redshift): wire ModifyCluster/RebootCluster into the query handler
* test(redshift): add compatibility coverage for tagging, subnet groups, modify/reboot
* fix(redshift): use imports and unique names in compatibility test
Follow this file's established conventions: proper imports instead of
fully-qualified SDK types, and TestFixtures.uniqueName() instead of
hardcoded resource names, matching the pattern used by the sibling
test methods.
* fix(redshift): address final whole-branch review findings
* fix(redshift): address PR review feedback and green the CI
Review comments:
- Translate three Vietnamese comments in RedshiftContainerManager and
RedshiftService to English (repo is English-only).
- alterUserPassword: reword the single-quote guard to cite the AWS
ModifyCluster MasterUserPassword constraint rather than the psql SQL
literal, and enforce the full documented set for parity — reject
' " \ / @, require length 8-64 and at least one upper/lower/digit.
- adoptOrStart: LOG.warnv on the container-gone branch so a fresh empty
cluster after a lost container is a searchable line, not a silent one.
- Move the .superpowers/ scratch ignore from the shared .gitignore to
.git/info/exclude (local tooling, not project output).
CI failures:
- Register redshift.model.Parameter for reflection so
PersistedModelReflectionTest passes and native-image persistence works
(fixes CI shard 3 and the native sdk-test-java compat run).
- Convert RedshiftQueryHandler.handle() from an if/else chain to
switch (action) so the docs action-table generator can extract the
action list, matching every other Query handler. Bodies unchanged.
- Register redshift in tools/docs/services.yaml, add docs/services/redshift.md
with the generated action table, and add the Service Matrix row in
docs/services/index.md (fixes Docs Action Tables / Action tables in sync).
* fix(redshift): reject path traversal in SnapshotIdentifier
createSnapshot spliced the request's SnapshotIdentifier straight into a
host path (<persistentPath>/redshift-dumps/<accountId>/<id>.sql). A value
with traversal segments or an absolute prefix escaped the account dump
directory: snapshot creation would write pg_dump output over an arbitrary
host file, and the resulting absolute path was persisted so a later
restore (arbitrary read into an attacker-controlled DB) or delete
(arbitrary unlink) trusted it.
- validateSnapshotIdentifier: enforce AWS's format (1-255 chars, leading
letter, letters/digits/non-consecutive hyphens) — rejects '.', '/', '\'
so no separator can appear.
- Keep a normalise + startsWith(dumpDir) containment check as defence in
depth.
- restore/delete now verify the stored sqlDump path still resolves inside
the account dump dir before touching it, so a path written by the
pre-fix code can't be acted on.
Also replace inline java.* fully-qualified names in RedshiftService and
RedshiftQueryHandler with top-of-file imports.
* fix(redshift): validate snapshot dump path before restore provisioning
The trusted-dump-path check added in the previous commit ran inside the
try block, after restoreFromClusterSnapshot had already persisted the
target cluster as "creating" and started its container. Rejecting an
untrusted path then left the container running and a "failed" cluster
record behind, blocking a retry with the same identifier
(ClusterAlreadyExists).
Move the check ahead of all provisioning — right after the snapshot is
loaded, before clusters.put and containerManager.start — so a rejected
restore creates no resources.
---------
Signed-off-by: Vũ Thế Huy <31652864+vuthehuyht@users.noreply.github.com>
This commit is contained in:
1 parent
08e532ab1a
commit
a1383fdd3d
29 files changed
+4600
No files matched your search
@@ -96,6 +96,10 @@
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>ssm</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>redshift</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>sns</artifactId>
|
||||
|
||||
@@ -26,6 +26,7 @@ import software.amazon.awssdk.services.lambda.LambdaClient;
|
||||
import software.amazon.awssdk.services.opensearch.OpenSearchClient;
|
||||
import software.amazon.awssdk.services.neptune.NeptuneClient;
|
||||
import software.amazon.awssdk.services.rds.RdsClient;
|
||||
import software.amazon.awssdk.services.redshift.RedshiftClient;
|
||||
import software.amazon.awssdk.services.guardduty.GuardDutyClient;
|
||||
import software.amazon.awssdk.services.fis.FisClient;
|
||||
import software.amazon.awssdk.services.organizations.OrganizationsClient;
|
||||
@@ -1030,4 +1031,12 @@ public final class TestFixtures {
|
||||
.credentialsProvider(CREDENTIALS)
|
||||
.build();
|
||||
}
|
||||
|
||||
public static RedshiftClient redshiftClient() {
|
||||
return RedshiftClient.builder()
|
||||
.endpointOverride(ENDPOINT)
|
||||
.region(REGION)
|
||||
.credentialsProvider(CREDENTIALS)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+336
@@ -0,0 +1,336 @@
|
||||
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.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import software.amazon.awssdk.services.redshift.RedshiftClient;
|
||||
import software.amazon.awssdk.services.redshift.model.Cluster;
|
||||
import software.amazon.awssdk.services.redshift.model.ClusterParameterGroup;
|
||||
import software.amazon.awssdk.services.redshift.model.CreateClusterParameterGroupRequest;
|
||||
import software.amazon.awssdk.services.redshift.model.CreateClusterParameterGroupResponse;
|
||||
import software.amazon.awssdk.services.redshift.model.CreateClusterRequest;
|
||||
import software.amazon.awssdk.services.redshift.model.CreateClusterResponse;
|
||||
import software.amazon.awssdk.services.redshift.model.CreateClusterSnapshotRequest;
|
||||
import software.amazon.awssdk.services.redshift.model.CreateClusterSnapshotResponse;
|
||||
import software.amazon.awssdk.services.redshift.model.CreateClusterSubnetGroupRequest;
|
||||
import software.amazon.awssdk.services.redshift.model.CreateTagsRequest;
|
||||
import software.amazon.awssdk.services.redshift.model.DeleteClusterParameterGroupRequest;
|
||||
import software.amazon.awssdk.services.redshift.model.DeleteClusterRequest;
|
||||
import software.amazon.awssdk.services.redshift.model.DeleteClusterSnapshotRequest;
|
||||
import software.amazon.awssdk.services.redshift.model.DeleteClusterSubnetGroupRequest;
|
||||
import software.amazon.awssdk.services.redshift.model.DeleteTagsRequest;
|
||||
import software.amazon.awssdk.services.redshift.model.DescribeClusterParameterGroupsRequest;
|
||||
import software.amazon.awssdk.services.redshift.model.DescribeClusterParameterGroupsResponse;
|
||||
import software.amazon.awssdk.services.redshift.model.DescribeClusterSnapshotsRequest;
|
||||
import software.amazon.awssdk.services.redshift.model.DescribeClusterSnapshotsResponse;
|
||||
import software.amazon.awssdk.services.redshift.model.DescribeClusterSubnetGroupsRequest;
|
||||
import software.amazon.awssdk.services.redshift.model.DescribeClustersRequest;
|
||||
import software.amazon.awssdk.services.redshift.model.DescribeClustersResponse;
|
||||
import software.amazon.awssdk.services.redshift.model.DescribeTagsRequest;
|
||||
import software.amazon.awssdk.services.redshift.model.ModifyClusterRequest;
|
||||
import software.amazon.awssdk.services.redshift.model.RebootClusterRequest;
|
||||
import software.amazon.awssdk.services.redshift.model.RestoreFromClusterSnapshotRequest;
|
||||
import software.amazon.awssdk.services.redshift.model.RestoreFromClusterSnapshotResponse;
|
||||
import software.amazon.awssdk.services.redshift.model.Snapshot;
|
||||
import software.amazon.awssdk.services.redshift.model.Tag;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@DisplayName("Redshift Operations")
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class RedshiftOperationsTest {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(RedshiftOperationsTest.class.getName());
|
||||
|
||||
private static final String USERNAME = "admin";
|
||||
private static final String PASSWORD = "password123";
|
||||
private static final String DATABASE = "dev";
|
||||
|
||||
private static RedshiftClient client;
|
||||
private static final List<String> clustersToCleanup = new ArrayList<>();
|
||||
private static final List<String> snapshotsToCleanup = new ArrayList<>();
|
||||
private static final List<String> parameterGroupsToCleanup = new ArrayList<>();
|
||||
private static final List<String> subnetGroupsToCleanup = new ArrayList<>();
|
||||
|
||||
@BeforeAll
|
||||
static void setup() {
|
||||
client = TestFixtures.redshiftClient();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void cleanup() {
|
||||
if (client != null) {
|
||||
for (String clusterId : clustersToCleanup) {
|
||||
try {
|
||||
client.deleteCluster(DeleteClusterRequest.builder()
|
||||
.clusterIdentifier(clusterId)
|
||||
.build());
|
||||
} catch (Exception e) {
|
||||
LOG.log(Level.WARNING, "Failed to clean up Redshift cluster " + clusterId, e);
|
||||
}
|
||||
}
|
||||
for (String snapId : snapshotsToCleanup) {
|
||||
try {
|
||||
client.deleteClusterSnapshot(DeleteClusterSnapshotRequest.builder()
|
||||
.snapshotIdentifier(snapId)
|
||||
.build());
|
||||
} catch (Exception e) {
|
||||
LOG.log(Level.WARNING, "Failed to clean up Redshift snapshot " + snapId, e);
|
||||
}
|
||||
}
|
||||
for (String pgName : parameterGroupsToCleanup) {
|
||||
try {
|
||||
client.deleteClusterParameterGroup(DeleteClusterParameterGroupRequest.builder()
|
||||
.parameterGroupName(pgName)
|
||||
.build());
|
||||
} catch (Exception e) {
|
||||
LOG.log(Level.WARNING, "Failed to clean up Redshift parameter group " + pgName, e);
|
||||
}
|
||||
}
|
||||
for (String subnetGroupName : subnetGroupsToCleanup) {
|
||||
try {
|
||||
client.deleteClusterSubnetGroup(DeleteClusterSubnetGroupRequest.builder()
|
||||
.clusterSubnetGroupName(subnetGroupName)
|
||||
.build());
|
||||
} catch (Exception e) {
|
||||
LOG.log(Level.WARNING, "Failed to clean up Redshift cluster subnet group " + subnetGroupName, e);
|
||||
}
|
||||
}
|
||||
client.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
@DisplayName("Create cluster, insert data, snapshot, restore to new cluster, verify data")
|
||||
void testSnapshotAndRestoreLifecycle() throws Exception {
|
||||
String sourceClusterId = TestFixtures.uniqueName("rs-source");
|
||||
String restoredClusterId = TestFixtures.uniqueName("rs-restored");
|
||||
String snapshotId = TestFixtures.uniqueName("rs-snap");
|
||||
|
||||
clustersToCleanup.add(sourceClusterId);
|
||||
clustersToCleanup.add(restoredClusterId);
|
||||
snapshotsToCleanup.add(snapshotId);
|
||||
|
||||
// 1. Create source cluster
|
||||
CreateClusterResponse createRes = client.createCluster(CreateClusterRequest.builder()
|
||||
.clusterIdentifier(sourceClusterId)
|
||||
.nodeType("dc2.large")
|
||||
.masterUsername(USERNAME)
|
||||
.masterUserPassword(PASSWORD)
|
||||
.build());
|
||||
|
||||
assertThat(createRes.cluster()).isNotNull();
|
||||
assertThat(createRes.cluster().clusterIdentifier()).isEqualTo(sourceClusterId);
|
||||
|
||||
DescribeClustersResponse descRes = client.describeClusters(DescribeClustersRequest.builder()
|
||||
.clusterIdentifier(sourceClusterId)
|
||||
.build());
|
||||
Cluster sourceCluster = descRes.clusters().get(0);
|
||||
assertThat(sourceCluster.endpoint()).isNotNull();
|
||||
String sourceHost = sourceCluster.endpoint().address();
|
||||
int sourcePort = sourceCluster.endpoint().port();
|
||||
|
||||
// 2. Use JDBC to create a table and insert a row
|
||||
try (Connection conn = awaitPostgresConnection(sourceHost, sourcePort, USERNAME, PASSWORD);
|
||||
Statement stmt = conn.createStatement()) {
|
||||
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');");
|
||||
}
|
||||
|
||||
// 3. Call createClusterSnapshot via AWS SDK
|
||||
CreateClusterSnapshotResponse snapRes = client.createClusterSnapshot(CreateClusterSnapshotRequest.builder()
|
||||
.snapshotIdentifier(snapshotId)
|
||||
.clusterIdentifier(sourceClusterId)
|
||||
.build());
|
||||
|
||||
Snapshot snapshot = snapRes.snapshot();
|
||||
assertThat(snapshot).isNotNull();
|
||||
assertThat(snapshot.snapshotIdentifier()).isEqualTo(snapshotId);
|
||||
assertThat(snapshot.clusterIdentifier()).isEqualTo(sourceClusterId);
|
||||
assertThat(snapshot.status()).isEqualTo("available");
|
||||
|
||||
DescribeClusterSnapshotsResponse descSnapRes = client.describeClusterSnapshots(DescribeClusterSnapshotsRequest.builder()
|
||||
.snapshotIdentifier(snapshotId)
|
||||
.build());
|
||||
assertThat(descSnapRes.snapshots()).isNotEmpty();
|
||||
assertThat(descSnapRes.snapshots().get(0).snapshotIdentifier()).isEqualTo(snapshotId);
|
||||
|
||||
// 4. Delete source cluster
|
||||
client.deleteCluster(DeleteClusterRequest.builder()
|
||||
.clusterIdentifier(sourceClusterId)
|
||||
.build());
|
||||
clustersToCleanup.remove(sourceClusterId);
|
||||
|
||||
// 5. Restore from snapshot to a new cluster identifier
|
||||
RestoreFromClusterSnapshotResponse restoreRes = client.restoreFromClusterSnapshot(
|
||||
RestoreFromClusterSnapshotRequest.builder()
|
||||
.clusterIdentifier(restoredClusterId)
|
||||
.snapshotIdentifier(snapshotId)
|
||||
.nodeType("dc2.large")
|
||||
.build());
|
||||
|
||||
Cluster restoredCluster = restoreRes.cluster();
|
||||
assertThat(restoredCluster).isNotNull();
|
||||
assertThat(restoredCluster.clusterIdentifier()).isEqualTo(restoredClusterId);
|
||||
assertThat(restoredCluster.endpoint()).isNotNull();
|
||||
|
||||
String restoredHost = restoredCluster.endpoint().address();
|
||||
int restoredPort = restoredCluster.endpoint().port();
|
||||
|
||||
// 6. Use JDBC to query restored cluster and verify row exists
|
||||
try (Connection conn = awaitPostgresConnection(restoredHost, restoredPort, USERNAME, PASSWORD);
|
||||
Statement stmt = conn.createStatement();
|
||||
ResultSet rs = stmt.executeQuery("SELECT name FROM test_data WHERE id = 1;")) {
|
||||
assertThat(rs.next()).isTrue();
|
||||
assertThat(rs.getString("name")).isEqualTo("floci-redshift-snapshot-val");
|
||||
}
|
||||
|
||||
// Cleanup restored cluster and snapshot
|
||||
client.deleteCluster(DeleteClusterRequest.builder()
|
||||
.clusterIdentifier(restoredClusterId)
|
||||
.build());
|
||||
clustersToCleanup.remove(restoredClusterId);
|
||||
|
||||
client.deleteClusterSnapshot(DeleteClusterSnapshotRequest.builder()
|
||||
.snapshotIdentifier(snapshotId)
|
||||
.build());
|
||||
snapshotsToCleanup.remove(snapshotId);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
@DisplayName("Create, describe, and delete cluster parameter group")
|
||||
void testClusterParameterGroupLifecycle() {
|
||||
String pgName = TestFixtures.uniqueName("rs-pg");
|
||||
parameterGroupsToCleanup.add(pgName);
|
||||
|
||||
// 1. Create cluster parameter group
|
||||
CreateClusterParameterGroupResponse createPgRes = client.createClusterParameterGroup(
|
||||
CreateClusterParameterGroupRequest.builder()
|
||||
.parameterGroupName(pgName)
|
||||
.parameterGroupFamily("redshift-1.0")
|
||||
.description("Test parameter group for Redshift")
|
||||
.build());
|
||||
|
||||
ClusterParameterGroup pg = createPgRes.clusterParameterGroup();
|
||||
assertThat(pg).isNotNull();
|
||||
assertThat(pg.parameterGroupName()).isEqualTo(pgName);
|
||||
assertThat(pg.parameterGroupFamily()).isEqualTo("redshift-1.0");
|
||||
assertThat(pg.description()).isEqualTo("Test parameter group for Redshift");
|
||||
|
||||
// 2. Describe cluster parameter groups
|
||||
DescribeClusterParameterGroupsResponse descPgRes = client.describeClusterParameterGroups(
|
||||
DescribeClusterParameterGroupsRequest.builder()
|
||||
.parameterGroupName(pgName)
|
||||
.build());
|
||||
|
||||
assertThat(descPgRes.parameterGroups()).isNotEmpty();
|
||||
ClusterParameterGroup foundPg = descPgRes.parameterGroups().stream()
|
||||
.filter(g -> pgName.equals(g.parameterGroupName()))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
assertThat(foundPg).isNotNull();
|
||||
assertThat(foundPg.parameterGroupFamily()).isEqualTo("redshift-1.0");
|
||||
assertThat(foundPg.description()).isEqualTo("Test parameter group for Redshift");
|
||||
|
||||
// 3. Delete cluster parameter group
|
||||
client.deleteClusterParameterGroup(DeleteClusterParameterGroupRequest.builder()
|
||||
.parameterGroupName(pgName)
|
||||
.build());
|
||||
parameterGroupsToCleanup.remove(pgName);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void testTaggingAndSubnetGroupAndModify() {
|
||||
// Cluster subnet group
|
||||
String subnetGroupName = TestFixtures.uniqueName("rs-subnet-group");
|
||||
client.createClusterSubnetGroup(CreateClusterSubnetGroupRequest.builder()
|
||||
.clusterSubnetGroupName(subnetGroupName)
|
||||
.description("SDK test subnet group")
|
||||
.subnetIds("subnet-aaa", "subnet-bbb")
|
||||
.build());
|
||||
subnetGroupsToCleanup.add(subnetGroupName);
|
||||
|
||||
var describedGroups = client.describeClusterSubnetGroups(
|
||||
DescribeClusterSubnetGroupsRequest.builder()
|
||||
.clusterSubnetGroupName(subnetGroupName)
|
||||
.build());
|
||||
assertThat(describedGroups.clusterSubnetGroups()).hasSize(1);
|
||||
assertThat(describedGroups.clusterSubnetGroups().get(0).subnets()).hasSize(2);
|
||||
|
||||
// Cluster + tagging + modify + reboot
|
||||
String clusterId = TestFixtures.uniqueName("rs-tag-cluster");
|
||||
CreateClusterResponse created = client.createCluster(CreateClusterRequest.builder()
|
||||
.clusterIdentifier(clusterId)
|
||||
.nodeType("dc2.large")
|
||||
.masterUsername(USERNAME)
|
||||
.masterUserPassword(PASSWORD)
|
||||
.build());
|
||||
clustersToCleanup.add(clusterId);
|
||||
String arn = "arn:aws:redshift:us-east-1:000000000000:cluster:" + clusterId;
|
||||
|
||||
client.createTags(CreateTagsRequest.builder()
|
||||
.resourceName(arn)
|
||||
.tags(Tag.builder().key("env").value("test").build())
|
||||
.build());
|
||||
|
||||
var described = client.describeTags(DescribeTagsRequest.builder()
|
||||
.resourceName(arn)
|
||||
.build());
|
||||
assertThat(described.taggedResources()).anyMatch(t -> "env".equals(t.tag().key()) && "test".equals(t.tag().value()));
|
||||
|
||||
client.deleteTags(DeleteTagsRequest.builder()
|
||||
.resourceName(arn)
|
||||
.tagKeys("env")
|
||||
.build());
|
||||
|
||||
var modified = client.modifyCluster(ModifyClusterRequest.builder()
|
||||
.clusterIdentifier(clusterId)
|
||||
.nodeType("ra3.xlplus")
|
||||
.build());
|
||||
assertThat(modified.cluster().nodeType()).isEqualTo("ra3.xlplus");
|
||||
|
||||
var rebooted = client.rebootCluster(RebootClusterRequest.builder()
|
||||
.clusterIdentifier(clusterId)
|
||||
.build());
|
||||
assertThat(rebooted.cluster().clusterStatus()).isEqualTo("available");
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package io.github.hectorvent.floci.compat;
|
||||
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import software.amazon.awssdk.services.redshift.RedshiftClient;
|
||||
import software.amazon.awssdk.services.redshift.model.Cluster;
|
||||
import software.amazon.awssdk.services.redshift.model.CreateClusterRequest;
|
||||
import software.amazon.awssdk.services.redshift.model.CreateClusterResponse;
|
||||
import software.amazon.awssdk.services.redshift.model.DescribeClustersRequest;
|
||||
import software.amazon.awssdk.services.redshift.model.DescribeClustersResponse;
|
||||
import software.amazon.awssdk.services.redshift.model.DeleteClusterRequest;
|
||||
import software.amazon.awssdk.services.redshift.model.DeleteClusterResponse;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
public class RedshiftTest {
|
||||
|
||||
private RedshiftClient getClient() {
|
||||
return RedshiftClient.builder()
|
||||
.region(software.amazon.awssdk.regions.Region.US_EAST_1)
|
||||
.credentialsProvider(software.amazon.awssdk.auth.credentials.StaticCredentialsProvider.create(
|
||||
software.amazon.awssdk.auth.credentials.AwsBasicCredentials.create("test", "test")))
|
||||
.endpointOverride(java.net.URI.create("http://localhost:4566"))
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
public void testCreateCluster() throws Exception {
|
||||
RedshiftClient client = getClient();
|
||||
CreateClusterResponse res = client.createCluster(CreateClusterRequest.builder()
|
||||
.clusterIdentifier("test-cluster")
|
||||
.nodeType("dc2.large")
|
||||
.masterUsername("admin")
|
||||
.masterUserPassword("Password123")
|
||||
.build());
|
||||
|
||||
assertEquals("test-cluster", res.cluster().clusterIdentifier());
|
||||
|
||||
DescribeClustersResponse describeRes = client.describeClusters(DescribeClustersRequest.builder()
|
||||
.clusterIdentifier("test-cluster")
|
||||
.build());
|
||||
|
||||
Cluster cluster = describeRes.clusters().get(0);
|
||||
assertEquals("test-cluster", cluster.clusterIdentifier());
|
||||
assertNotNull(cluster.endpoint());
|
||||
|
||||
String address = cluster.endpoint().address();
|
||||
int port = cluster.endpoint().port();
|
||||
|
||||
String jdbcUrl = "jdbc:postgresql://" + address + ":" + port + "/dev";
|
||||
try (Connection conn = DriverManager.getConnection(jdbcUrl, "admin", "Password123")) {
|
||||
assertTrue(conn.isValid(5));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
public void testDeleteCluster() {
|
||||
RedshiftClient client = getClient();
|
||||
DeleteClusterResponse res = client.deleteCluster(DeleteClusterRequest.builder()
|
||||
.clusterIdentifier("test-cluster")
|
||||
.build());
|
||||
assertEquals("test-cluster", res.cluster().clusterIdentifier());
|
||||
assertEquals("deleting", res.cluster().clusterStatus());
|
||||
}
|
||||
}
|
||||
@@ -55,6 +55,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
|
||||
| [Lake Formation](lakeformation.md) | `POST /<Action>` | REST JSON | 16 |
|
||||
| [Neptune](neptune.md) | `POST /` with `Action=` param + Gremlin TCP proxy | Query + WebSocket | 8 |
|
||||
| [DocumentDB](docdb.md) | `POST /` with `Action=` param + MongoDB container | Query + MongoDB wire | 8 |
|
||||
| [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire | 21 |
|
||||
| [EMR](emr.md) | `POST /` + `X-Amz-Target: ElasticMapReduce.*` | JSON 1.1 | 24 |
|
||||
| [EMR Serverless](emr-serverless.md) | `/applications/*` | REST JSON | 7 |
|
||||
| [Data Firehose](firehose.md) | `POST /` + `X-Amz-Target: Firehose_20150804.*` | JSON 1.1 | 6 |
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
# Redshift
|
||||
|
||||
**Protocol:** Query (XML) for the management API
|
||||
**Management Endpoint:** `POST http://localhost:4566/` with `Action=` param
|
||||
**Data Endpoint:** the `Endpoint` and `Port` returned by `DescribeClusters` (PostgreSQL wire protocol)
|
||||
|
||||
Floci emulates Amazon Redshift by managing a real [PostgreSQL](https://www.postgresql.org/) Docker container per cluster behind a Redshift-shaped control plane. Redshift speaks the PostgreSQL wire protocol, so the cluster endpoint returned by `DescribeClusters` works with any standard PostgreSQL driver (`psql`, JDBC, `psycopg`, …).
|
||||
|
||||
> **Always read the host and port from `DescribeClusters`** rather than assuming a fixed port. PostgreSQL listens on `5432` *inside* the container; the port you connect to is dynamically assigned on the host and returned as `Clusters[0].Endpoint.Port`. Redshift's conventional port is `5439`, but the emulator does not bind it — use whatever `DescribeClusters` reports.
|
||||
|
||||
The container has **no persistent volume**: if the physical container survives a Floci restart it is adopted and its data is kept, but if the container itself is gone (host reboot, `docker rm`, a pruned dev box) the cluster comes back empty. Use `CreateClusterSnapshot` / `RestoreFromClusterSnapshot` to preserve data explicitly.
|
||||
|
||||
## Supported Actions
|
||||
|
||||
<!-- floci:actions:start -->
|
||||
| Action | Description |
|
||||
| --- | --- |
|
||||
| `CreateCluster` | Create a cluster and start a PostgreSQL container for it |
|
||||
| `DescribeClusters` | List clusters and their connection details |
|
||||
| `DeleteCluster` | Stop and remove a cluster and its container |
|
||||
| `CreateClusterSnapshot` | Back up a cluster to a SQL dump via `pg_dump` |
|
||||
| `DescribeClusterSnapshots` | List snapshots, optionally filtered by snapshot or cluster identifier |
|
||||
| `DeleteClusterSnapshot` | Remove a snapshot and its stored dump |
|
||||
| `RestoreFromClusterSnapshot` | Create a new cluster and load a snapshot's dump into it via `psql` |
|
||||
| `CreateClusterParameterGroup` | Register a parameter group (metadata only) |
|
||||
| `DescribeClusterParameterGroups` | List parameter groups, optionally filtered by name |
|
||||
| `DescribeClusterParameters` | Return the parameters of a group, with any values set by `ModifyClusterParameterGroup` |
|
||||
| `ModifyClusterParameterGroup` | Update parameter values on a group |
|
||||
| `DeleteClusterParameterGroup` | Remove a parameter group |
|
||||
| `CreateTags` | Add or overwrite tags on a cluster, snapshot, subnet group or parameter group |
|
||||
| `DeleteTags` | Remove tags by key from a resource |
|
||||
| `DescribeTags` | List tagged resources and their tags |
|
||||
| `CreateClusterSubnetGroup` | Register a cluster subnet group (metadata only) |
|
||||
| `DescribeClusterSubnetGroups` | List subnet groups, optionally filtered by name |
|
||||
| `ModifyClusterSubnetGroup` | Update a subnet group's description or subnet list |
|
||||
| `DeleteClusterSubnetGroup` | Remove a subnet group |
|
||||
| `ModifyCluster` | Update node type, parameter group, security groups, or the master password |
|
||||
| `RebootCluster` | Restart a cluster's container |
|
||||
<!-- floci:actions:end -->
|
||||
|
||||
## Configuration
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `FLOCI_SERVICES_REDSHIFT_ENABLED` | `true` | Enable or disable Redshift |
|
||||
| `FLOCI_SERVICES_REDSHIFT_IMAGE_VERSION` | `postgres:15-alpine` | PostgreSQL Docker image backing each cluster |
|
||||
| `FLOCI_SERVICES_REDSHIFT_DEFAULT_PORT` | `5439` | Reported Redshift port hint (the real host port is dynamic and comes from `DescribeClusters`) |
|
||||
|
||||
Redshift needs the Docker socket so it can launch PostgreSQL containers. Each cluster's container is published on a dynamically assigned host port, returned by `DescribeClusters`.
|
||||
|
||||
### Docker Compose
|
||||
|
||||
```yaml
|
||||
services:
|
||||
floci:
|
||||
image: floci/floci:latest
|
||||
ports:
|
||||
- "4566:4566"
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
```
|
||||
|
||||
For private registry authentication and other Docker settings see [Docker Configuration](../configuration/docker.md).
|
||||
|
||||
## Examples
|
||||
|
||||
### Management API (AWS CLI)
|
||||
|
||||
```bash
|
||||
export AWS_ENDPOINT_URL=http://localhost:4566
|
||||
export AWS_DEFAULT_REGION=us-east-1
|
||||
export AWS_ACCESS_KEY_ID=test
|
||||
export AWS_SECRET_ACCESS_KEY=test
|
||||
|
||||
# Create a cluster (starts a PostgreSQL container)
|
||||
aws redshift create-cluster \
|
||||
--cluster-identifier my-warehouse \
|
||||
--node-type dc2.large \
|
||||
--master-username admin \
|
||||
--master-user-password Secret123
|
||||
|
||||
# Read the cluster endpoint and port
|
||||
aws redshift describe-clusters \
|
||||
--cluster-identifier my-warehouse \
|
||||
--query 'Clusters[0].Endpoint'
|
||||
|
||||
# Snapshot and restore
|
||||
aws redshift create-cluster-snapshot \
|
||||
--snapshot-identifier snap-1 \
|
||||
--cluster-identifier my-warehouse
|
||||
aws redshift restore-from-cluster-snapshot \
|
||||
--cluster-identifier my-warehouse-restored \
|
||||
--snapshot-identifier snap-1
|
||||
|
||||
# Delete
|
||||
aws redshift delete-cluster \
|
||||
--cluster-identifier my-warehouse \
|
||||
--skip-final-cluster-snapshot
|
||||
```
|
||||
|
||||
### Data plane (Python + psycopg)
|
||||
|
||||
```python
|
||||
import psycopg
|
||||
|
||||
# Read host and port from DescribeClusters — the host port is dynamic.
|
||||
host, port = "localhost", 32768 # e.g. Clusters[0].Endpoint.Address / .Port
|
||||
with psycopg.connect(f"host={host} port={port} dbname=dev user=admin password=Secret123") as conn:
|
||||
conn.execute("CREATE TABLE people (name text)")
|
||||
conn.execute("INSERT INTO people VALUES ('Alice')")
|
||||
for row in conn.execute("SELECT * FROM people"):
|
||||
print(row)
|
||||
```
|
||||
|
||||
### Management API (Python / boto3)
|
||||
|
||||
```python
|
||||
import boto3
|
||||
|
||||
redshift = boto3.client(
|
||||
"redshift",
|
||||
endpoint_url="http://localhost:4566",
|
||||
region_name="us-east-1",
|
||||
)
|
||||
|
||||
cluster = redshift.create_cluster(
|
||||
ClusterIdentifier="my-warehouse",
|
||||
NodeType="dc2.large",
|
||||
MasterUsername="admin",
|
||||
MasterUserPassword="Secret123",
|
||||
)
|
||||
print(cluster["Cluster"]["Endpoint"])
|
||||
```
|
||||
|
||||
## Out of Scope
|
||||
|
||||
- Real Redshift SQL semantics — the data plane is stock PostgreSQL, so Redshift-only SQL (distribution/sort keys, `COPY`/`UNLOAD` from S3, `SUPER`/`SPECTRUM`) is not emulated.
|
||||
- Multi-node clusters — `NodeType` and `NumberOfNodes` are stored as metadata; every cluster is a single PostgreSQL container.
|
||||
- Parameter groups apply no real engine settings; values are stored and echoed back only.
|
||||
- Subnet groups, VPC routing, and security groups are metadata only.
|
||||
- Resize, pause/resume, IAM authentication, snapshot schedules, and cross-region snapshot copy.
|
||||
@@ -263,6 +263,7 @@ public interface EmulatorConfig {
|
||||
ElastiCacheStorageConfig elasticache();
|
||||
MemoryDbStorageConfig memorydb();
|
||||
RdsStorageConfig rds();
|
||||
RedshiftStorageConfig redshift();
|
||||
Ec2StorageConfig ec2();
|
||||
NeptuneStorageConfig neptune();
|
||||
BackupStorageConfig backup();
|
||||
@@ -401,6 +402,10 @@ public interface EmulatorConfig {
|
||||
long flushIntervalMs();
|
||||
}
|
||||
|
||||
interface RedshiftStorageConfig {
|
||||
Optional<String> mode();
|
||||
}
|
||||
|
||||
interface RdsStorageConfig {
|
||||
Optional<String> mode();
|
||||
}
|
||||
@@ -609,6 +614,7 @@ public interface EmulatorConfig {
|
||||
ElastiCacheServiceConfig elasticache();
|
||||
MemoryDbServiceConfig memorydb();
|
||||
RdsServiceConfig rds();
|
||||
RedshiftServiceConfig redshift();
|
||||
RdsDataServiceConfig rdsData();
|
||||
EventBridgeServiceConfig eventbridge();
|
||||
CloudMapServiceConfig cloudmap();
|
||||
@@ -1095,6 +1101,16 @@ public interface EmulatorConfig {
|
||||
Optional<String> dockerNetwork();
|
||||
}
|
||||
|
||||
interface RedshiftServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
@WithDefault("5439")
|
||||
int defaultPort();
|
||||
@WithDefault("postgres:15-alpine")
|
||||
String imageVersion();
|
||||
Optional<String> dockerNetwork();
|
||||
}
|
||||
|
||||
interface RdsServiceConfig {
|
||||
String DEFAULT_POSTGRES_IMAGE = "postgres:16-alpine";
|
||||
String DEFAULT_MYSQL_IMAGE = "mysql:8.0";
|
||||
|
||||
@@ -22,6 +22,7 @@ public final class AwsNamespaces {
|
||||
public static final String ELASTIC_BEANSTALK = "https://elasticbeanstalk.amazonaws.com/docs/2010-12-01/";
|
||||
public static final String ROUTE53 = "https://route53.amazonaws.com/doc/2013-04-01/";
|
||||
public static final String CLOUDFRONT = "http://cloudfront.amazonaws.com/doc/2020-05-31/";
|
||||
public static final String REDSHIFT = "http://redshift.amazonaws.com/doc/2012-12-01/";
|
||||
|
||||
private AwsNamespaces() {}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import io.github.hectorvent.floci.services.iam.IamQueryHandler;
|
||||
import io.github.hectorvent.floci.services.iam.StsQueryHandler;
|
||||
import io.github.hectorvent.floci.services.rds.RdsQueryHandler;
|
||||
import io.github.hectorvent.floci.services.rds.RdsService;
|
||||
import io.github.hectorvent.floci.services.redshift.RedshiftQueryHandler;
|
||||
import io.github.hectorvent.floci.services.sns.SnsQueryHandler;
|
||||
import io.github.hectorvent.floci.services.ses.SesQueryHandler;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsQueryHandler;
|
||||
@@ -196,6 +197,7 @@ public class AwsQueryController {
|
||||
private final ElbV2QueryHandler elbV2QueryHandler;
|
||||
private final AutoScalingQueryHandler autoScalingQueryHandler;
|
||||
private final ElasticBeanstalkQueryHandler elasticBeanstalkQueryHandler;
|
||||
private final RedshiftQueryHandler redshiftQueryHandler;
|
||||
private final ResolvedServiceCatalog catalog;
|
||||
private final RegionResolver regionResolver;
|
||||
|
||||
@@ -217,6 +219,7 @@ public class AwsQueryController {
|
||||
ElbV2QueryHandler elbV2QueryHandler,
|
||||
AutoScalingQueryHandler autoScalingQueryHandler,
|
||||
ElasticBeanstalkQueryHandler elasticBeanstalkQueryHandler,
|
||||
RedshiftQueryHandler redshiftQueryHandler,
|
||||
ResolvedServiceCatalog catalog,
|
||||
RegionResolver regionResolver) {
|
||||
this.cloudFormationQueryHandler = cloudFormationQueryHandler;
|
||||
@@ -238,6 +241,7 @@ public class AwsQueryController {
|
||||
this.elbV2QueryHandler = elbV2QueryHandler;
|
||||
this.autoScalingQueryHandler = autoScalingQueryHandler;
|
||||
this.elasticBeanstalkQueryHandler = elasticBeanstalkQueryHandler;
|
||||
this.redshiftQueryHandler = redshiftQueryHandler;
|
||||
this.catalog = catalog;
|
||||
this.regionResolver = regionResolver;
|
||||
}
|
||||
@@ -342,6 +346,7 @@ public class AwsQueryController {
|
||||
case "elasticloadbalancing" -> elbV2QueryHandler.handle(action, formParams, region);
|
||||
case "autoscaling" -> autoScalingQueryHandler.handle(action, formParams, region);
|
||||
case "elasticbeanstalk" -> elasticBeanstalkQueryHandler.handle(action, formParams, region);
|
||||
case "redshift" -> redshiftQueryHandler.handle(action, formParams);
|
||||
default -> xmlErrorResponse("UnknownService",
|
||||
"Unknown or unsupported service: " + service, 400);
|
||||
};
|
||||
@@ -533,6 +538,16 @@ public class AwsQueryController {
|
||||
"AdminAddUserToGroup", "AdminRemoveUserFromGroup", "AdminListGroupsForUser"
|
||||
);
|
||||
|
||||
private static final Set<String> REDSHIFT_ACTIONS = Set.of(
|
||||
"CreateCluster", "DescribeClusters", "DeleteCluster",
|
||||
"CreateClusterSnapshot", "DescribeClusterSnapshots", "DeleteClusterSnapshot", "RestoreFromClusterSnapshot",
|
||||
"ModifyCluster", "RebootCluster",
|
||||
"CreateClusterParameterGroup", "DescribeClusterParameterGroups", "DescribeClusterParameters", "DeleteClusterParameterGroup",
|
||||
"ModifyClusterParameterGroup",
|
||||
"CreateClusterSubnetGroup", "DescribeClusterSubnetGroups", "ModifyClusterSubnetGroup", "DeleteClusterSubnetGroup",
|
||||
"CreateTags", "DeleteTags", "DescribeTags"
|
||||
);
|
||||
|
||||
private String resolveService(String authorization, String action) {
|
||||
ServiceDescriptor descriptor = SigV4CredentialScope.serviceName(authorization)
|
||||
.flatMap(catalog::byCredentialScope)
|
||||
@@ -583,6 +598,9 @@ public class AwsQueryController {
|
||||
if (ELASTIC_BEANSTALK_ACTIONS.contains(action)) {
|
||||
return "elasticbeanstalk";
|
||||
}
|
||||
if (REDSHIFT_ACTIONS.contains(action)) {
|
||||
return "redshift";
|
||||
}
|
||||
// SQS actions are numerous and not enumerated — fall back to sqs only for
|
||||
// requests that arrived without an Authorization header (raw/test clients)
|
||||
return "sqs";
|
||||
|
||||
@@ -156,6 +156,11 @@ public class ResolvedServiceCatalog {
|
||||
5000L, AwsNamespaces.RDS, ServiceProtocol.QUERY,
|
||||
protocols(ServiceProtocol.QUERY),
|
||||
Set.of(), Set.of("docdb"), Set.of(), Set.of()),
|
||||
descriptor("redshift", "redshift", config.services().redshift().enabled(), true,
|
||||
"redshift", storageMode(config.storage().services().redshift().mode(), config.storage().mode()),
|
||||
5000L, AwsNamespaces.REDSHIFT, ServiceProtocol.QUERY,
|
||||
protocols(ServiceProtocol.QUERY),
|
||||
Set.of(), Set.of("redshift"), Set.of(), Set.of()),
|
||||
|
||||
descriptor("events", "eventbridge", config.services().eventbridge().enabled(), true,
|
||||
"eventbridge", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,
|
||||
|
||||
@@ -380,6 +380,11 @@ public class AccountAwareStorageBackend<V> implements StorageBackend<String, V>
|
||||
|
||||
// ---
|
||||
|
||||
/** Returns the account ID that keys are currently being prefixed with. */
|
||||
public String accountId() {
|
||||
return prefix();
|
||||
}
|
||||
|
||||
private String prefix() {
|
||||
if (requestContextInstance != null) {
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,598 @@
|
||||
package io.github.hectorvent.floci.services.redshift;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.XmlBuilder;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Cluster;
|
||||
import io.github.hectorvent.floci.services.redshift.model.ClusterParameterGroup;
|
||||
import io.github.hectorvent.floci.services.redshift.model.ClusterSubnetGroup;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Parameter;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Snapshot;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@ApplicationScoped
|
||||
public class RedshiftQueryHandler {
|
||||
private final RedshiftService service;
|
||||
|
||||
@Inject
|
||||
public RedshiftQueryHandler(RedshiftService service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
public Response handle(String action, MultivaluedMap<String, String> params) {
|
||||
switch (action) {
|
||||
case "CreateCluster" -> {
|
||||
String identifier = params.getFirst("ClusterIdentifier");
|
||||
String nodeType = params.getFirst("NodeType");
|
||||
String masterUsername = params.getFirst("MasterUsername");
|
||||
String masterUserPassword = params.getFirst("MasterUserPassword");
|
||||
String clusterSubnetGroupName = params.getFirst("ClusterSubnetGroupName");
|
||||
List<String> vpcSecurityGroupIds = memberList(params, "VpcSecurityGroupIds");
|
||||
|
||||
Cluster cluster = service.createCluster(identifier, nodeType, masterUsername, masterUserPassword,
|
||||
clusterSubnetGroupName, vpcSecurityGroupIds);
|
||||
String xml = new XmlBuilder()
|
||||
.start("CreateClusterResponse")
|
||||
.start("CreateClusterResult")
|
||||
.raw(buildClusterXml(cluster))
|
||||
.end("CreateClusterResult")
|
||||
.start("ResponseMetadata")
|
||||
.elem("RequestId", "test-req-id")
|
||||
.end("ResponseMetadata")
|
||||
.end("CreateClusterResponse")
|
||||
.build();
|
||||
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
case "DescribeClusters" -> {
|
||||
String identifier = params.getFirst("ClusterIdentifier");
|
||||
List<Cluster> clusters = service.describeClusters(identifier);
|
||||
XmlBuilder xmlBuilder = new XmlBuilder()
|
||||
.start("DescribeClustersResponse")
|
||||
.start("DescribeClustersResult")
|
||||
.start("Clusters");
|
||||
for (Cluster cluster : clusters) {
|
||||
xmlBuilder.raw(buildClusterXml(cluster));
|
||||
}
|
||||
String xml = xmlBuilder
|
||||
.end("Clusters")
|
||||
.end("DescribeClustersResult")
|
||||
.start("ResponseMetadata")
|
||||
.elem("RequestId", "test-req-id")
|
||||
.end("ResponseMetadata")
|
||||
.end("DescribeClustersResponse")
|
||||
.build();
|
||||
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
case "DeleteCluster" -> {
|
||||
String identifier = params.getFirst("ClusterIdentifier");
|
||||
Cluster cluster = service.deleteCluster(identifier);
|
||||
String xml = new XmlBuilder()
|
||||
.start("DeleteClusterResponse")
|
||||
.start("DeleteClusterResult")
|
||||
.raw(buildClusterXml(cluster))
|
||||
.end("DeleteClusterResult")
|
||||
.start("ResponseMetadata")
|
||||
.elem("RequestId", "test-req-id")
|
||||
.end("ResponseMetadata")
|
||||
.end("DeleteClusterResponse")
|
||||
.build();
|
||||
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
case "CreateClusterSnapshot" -> {
|
||||
String snapshotIdentifier = params.getFirst("SnapshotIdentifier");
|
||||
String clusterIdentifier = params.getFirst("ClusterIdentifier");
|
||||
Snapshot snapshot = service.createSnapshot(snapshotIdentifier, clusterIdentifier);
|
||||
String xml = new XmlBuilder()
|
||||
.start("CreateClusterSnapshotResponse")
|
||||
.start("CreateClusterSnapshotResult")
|
||||
.raw(buildSnapshotXml(snapshot))
|
||||
.end("CreateClusterSnapshotResult")
|
||||
.start("ResponseMetadata")
|
||||
.elem("RequestId", "test-req-id")
|
||||
.end("ResponseMetadata")
|
||||
.end("CreateClusterSnapshotResponse")
|
||||
.build();
|
||||
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
case "DescribeClusterSnapshots" -> {
|
||||
String snapshotIdentifier = params.getFirst("SnapshotIdentifier");
|
||||
String clusterIdentifier = params.getFirst("ClusterIdentifier");
|
||||
List<Snapshot> snapshots = service.describeSnapshots(snapshotIdentifier, clusterIdentifier);
|
||||
XmlBuilder xmlBuilder = new XmlBuilder()
|
||||
.start("DescribeClusterSnapshotsResponse")
|
||||
.start("DescribeClusterSnapshotsResult")
|
||||
.start("Snapshots");
|
||||
for (Snapshot snapshot : snapshots) {
|
||||
xmlBuilder.raw(buildSnapshotXml(snapshot));
|
||||
}
|
||||
String xml = xmlBuilder
|
||||
.end("Snapshots")
|
||||
.end("DescribeClusterSnapshotsResult")
|
||||
.start("ResponseMetadata")
|
||||
.elem("RequestId", "test-req-id")
|
||||
.end("ResponseMetadata")
|
||||
.end("DescribeClusterSnapshotsResponse")
|
||||
.build();
|
||||
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
case "DeleteClusterSnapshot" -> {
|
||||
String snapshotIdentifier = params.getFirst("SnapshotIdentifier");
|
||||
Snapshot snapshot = service.deleteSnapshot(snapshotIdentifier);
|
||||
String xml = new XmlBuilder()
|
||||
.start("DeleteClusterSnapshotResponse")
|
||||
.start("DeleteClusterSnapshotResult")
|
||||
.raw(buildSnapshotXml(snapshot))
|
||||
.end("DeleteClusterSnapshotResult")
|
||||
.start("ResponseMetadata")
|
||||
.elem("RequestId", "test-req-id")
|
||||
.end("ResponseMetadata")
|
||||
.end("DeleteClusterSnapshotResponse")
|
||||
.build();
|
||||
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
case "RestoreFromClusterSnapshot" -> {
|
||||
String clusterIdentifier = params.getFirst("ClusterIdentifier");
|
||||
String snapshotIdentifier = params.getFirst("SnapshotIdentifier");
|
||||
String nodeType = params.getFirst("NodeType");
|
||||
Cluster cluster = service.restoreFromClusterSnapshot(clusterIdentifier, snapshotIdentifier, nodeType);
|
||||
String xml = new XmlBuilder()
|
||||
.start("RestoreFromClusterSnapshotResponse")
|
||||
.start("RestoreFromClusterSnapshotResult")
|
||||
.raw(buildClusterXml(cluster))
|
||||
.end("RestoreFromClusterSnapshotResult")
|
||||
.start("ResponseMetadata")
|
||||
.elem("RequestId", "test-req-id")
|
||||
.end("ResponseMetadata")
|
||||
.end("RestoreFromClusterSnapshotResponse")
|
||||
.build();
|
||||
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
case "CreateClusterParameterGroup" -> {
|
||||
String parameterGroupName = params.getFirst("ParameterGroupName");
|
||||
String parameterGroupFamily = params.getFirst("ParameterGroupFamily");
|
||||
String description = params.getFirst("Description");
|
||||
ClusterParameterGroup group = service.createClusterParameterGroup(parameterGroupName, parameterGroupFamily, description);
|
||||
String xml = new XmlBuilder()
|
||||
.start("CreateClusterParameterGroupResponse")
|
||||
.start("CreateClusterParameterGroupResult")
|
||||
.raw(buildClusterParameterGroupXml(group))
|
||||
.end("CreateClusterParameterGroupResult")
|
||||
.start("ResponseMetadata")
|
||||
.elem("RequestId", "test-req-id")
|
||||
.end("ResponseMetadata")
|
||||
.end("CreateClusterParameterGroupResponse")
|
||||
.build();
|
||||
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
case "DescribeClusterParameterGroups" -> {
|
||||
String parameterGroupName = params.getFirst("ParameterGroupName");
|
||||
List<ClusterParameterGroup> groups = service.describeClusterParameterGroups(parameterGroupName);
|
||||
XmlBuilder xmlBuilder = new XmlBuilder()
|
||||
.start("DescribeClusterParameterGroupsResponse")
|
||||
.start("DescribeClusterParameterGroupsResult")
|
||||
.start("ParameterGroups");
|
||||
for (ClusterParameterGroup group : groups) {
|
||||
xmlBuilder.raw(buildClusterParameterGroupXml(group));
|
||||
}
|
||||
String xml = xmlBuilder
|
||||
.end("ParameterGroups")
|
||||
.end("DescribeClusterParameterGroupsResult")
|
||||
.start("ResponseMetadata")
|
||||
.elem("RequestId", "test-req-id")
|
||||
.end("ResponseMetadata")
|
||||
.end("DescribeClusterParameterGroupsResponse")
|
||||
.build();
|
||||
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
case "DescribeClusterParameters" -> {
|
||||
String parameterGroupName = params.getFirst("ParameterGroupName");
|
||||
if (parameterGroupName == null || parameterGroupName.isBlank()) {
|
||||
throw new AwsException("InvalidParameterValue", "ParameterGroupName is required", 400);
|
||||
}
|
||||
List<Parameter> parameters = service.describeClusterParameters(parameterGroupName);
|
||||
|
||||
XmlBuilder xmlBuilder = new XmlBuilder()
|
||||
.start("DescribeClusterParametersResponse")
|
||||
.start("DescribeClusterParametersResult")
|
||||
.start("Parameters");
|
||||
for (Parameter param : parameters) {
|
||||
xmlBuilder.raw(buildParameterXml(param));
|
||||
}
|
||||
String xml = xmlBuilder.end("Parameters")
|
||||
.end("DescribeClusterParametersResult")
|
||||
.start("ResponseMetadata")
|
||||
.elem("RequestId", "test-req-id")
|
||||
.end("ResponseMetadata")
|
||||
.end("DescribeClusterParametersResponse")
|
||||
.build();
|
||||
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
case "ModifyClusterParameterGroup" -> {
|
||||
String parameterGroupName = params.getFirst("ParameterGroupName");
|
||||
if (parameterGroupName == null || parameterGroupName.isBlank()) {
|
||||
throw new AwsException("InvalidParameterValue", "ParameterGroupName is required", 400);
|
||||
}
|
||||
List<Parameter> updates = parseParameters(params);
|
||||
service.modifyClusterParameterGroup(parameterGroupName, updates);
|
||||
String xml = new XmlBuilder()
|
||||
.start("ModifyClusterParameterGroupResponse")
|
||||
.start("ModifyClusterParameterGroupResult")
|
||||
.elem("ParameterGroupName", parameterGroupName)
|
||||
.elem("ParameterGroupStatus", "pending-reboot")
|
||||
.end("ModifyClusterParameterGroupResult")
|
||||
.start("ResponseMetadata")
|
||||
.elem("RequestId", "test-req-id")
|
||||
.end("ResponseMetadata")
|
||||
.end("ModifyClusterParameterGroupResponse")
|
||||
.build();
|
||||
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
case "DeleteClusterParameterGroup" -> {
|
||||
String parameterGroupName = params.getFirst("ParameterGroupName");
|
||||
service.deleteClusterParameterGroup(parameterGroupName);
|
||||
String xml = new XmlBuilder()
|
||||
.start("DeleteClusterParameterGroupResponse")
|
||||
.start("ResponseMetadata")
|
||||
.elem("RequestId", "test-req-id")
|
||||
.end("ResponseMetadata")
|
||||
.end("DeleteClusterParameterGroupResponse")
|
||||
.build();
|
||||
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
case "CreateTags" -> {
|
||||
String resourceName = params.getFirst("ResourceName");
|
||||
service.createTags(resourceName, parseTags(params));
|
||||
String xml = new XmlBuilder()
|
||||
.start("CreateTagsResponse")
|
||||
.start("ResponseMetadata")
|
||||
.elem("RequestId", "test-req-id")
|
||||
.end("ResponseMetadata")
|
||||
.end("CreateTagsResponse")
|
||||
.build();
|
||||
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
case "DeleteTags" -> {
|
||||
String resourceName = params.getFirst("ResourceName");
|
||||
List<String> tagKeys = memberList(params, "TagKeys");
|
||||
service.deleteTags(resourceName, tagKeys);
|
||||
String xml = new XmlBuilder()
|
||||
.start("DeleteTagsResponse")
|
||||
.start("ResponseMetadata")
|
||||
.elem("RequestId", "test-req-id")
|
||||
.end("ResponseMetadata")
|
||||
.end("DeleteTagsResponse")
|
||||
.build();
|
||||
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
case "DescribeTags" -> {
|
||||
String resourceName = params.getFirst("ResourceName");
|
||||
String resourceType = params.getFirst("ResourceType");
|
||||
List<String> tagKeys = memberList(params, "TagKeys");
|
||||
List<RedshiftService.TaggedResource> tagged = service.describeTags(resourceName, resourceType, tagKeys);
|
||||
XmlBuilder xmlBuilder = new XmlBuilder()
|
||||
.start("DescribeTagsResponse")
|
||||
.start("DescribeTagsResult")
|
||||
.start("TaggedResources");
|
||||
for (RedshiftService.TaggedResource t : tagged) {
|
||||
xmlBuilder.start("TaggedResource")
|
||||
.elem("ResourceName", t.resourceName())
|
||||
.elem("ResourceType", t.resourceType())
|
||||
.start("Tag")
|
||||
.elem("Key", t.tagKey())
|
||||
.elem("Value", t.tagValue())
|
||||
.end("Tag")
|
||||
.end("TaggedResource");
|
||||
}
|
||||
String xml = xmlBuilder
|
||||
.end("TaggedResources")
|
||||
.end("DescribeTagsResult")
|
||||
.start("ResponseMetadata")
|
||||
.elem("RequestId", "test-req-id")
|
||||
.end("ResponseMetadata")
|
||||
.end("DescribeTagsResponse")
|
||||
.build();
|
||||
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
case "CreateClusterSubnetGroup" -> {
|
||||
String name = params.getFirst("ClusterSubnetGroupName");
|
||||
if (name == null || name.isBlank()) {
|
||||
throw new AwsException("InvalidParameterValue", "ClusterSubnetGroupName is required", 400);
|
||||
}
|
||||
String description = params.getFirst("Description");
|
||||
List<String> subnetIds = memberList(params, "SubnetIds");
|
||||
ClusterSubnetGroup group = service.createClusterSubnetGroup(name, description, null, subnetIds);
|
||||
String xml = new XmlBuilder()
|
||||
.start("CreateClusterSubnetGroupResponse")
|
||||
.start("CreateClusterSubnetGroupResult")
|
||||
.raw(buildClusterSubnetGroupXml(group))
|
||||
.end("CreateClusterSubnetGroupResult")
|
||||
.start("ResponseMetadata")
|
||||
.elem("RequestId", "test-req-id")
|
||||
.end("ResponseMetadata")
|
||||
.end("CreateClusterSubnetGroupResponse")
|
||||
.build();
|
||||
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
case "DescribeClusterSubnetGroups" -> {
|
||||
String name = params.getFirst("ClusterSubnetGroupName");
|
||||
List<ClusterSubnetGroup> groups = service.describeClusterSubnetGroups(name);
|
||||
XmlBuilder xmlBuilder = new XmlBuilder()
|
||||
.start("DescribeClusterSubnetGroupsResponse")
|
||||
.start("DescribeClusterSubnetGroupsResult")
|
||||
.start("ClusterSubnetGroups");
|
||||
for (ClusterSubnetGroup group : groups) {
|
||||
xmlBuilder.raw(buildClusterSubnetGroupXml(group));
|
||||
}
|
||||
String xml = xmlBuilder
|
||||
.end("ClusterSubnetGroups")
|
||||
.end("DescribeClusterSubnetGroupsResult")
|
||||
.start("ResponseMetadata")
|
||||
.elem("RequestId", "test-req-id")
|
||||
.end("ResponseMetadata")
|
||||
.end("DescribeClusterSubnetGroupsResponse")
|
||||
.build();
|
||||
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
case "ModifyClusterSubnetGroup" -> {
|
||||
String name = params.getFirst("ClusterSubnetGroupName");
|
||||
String description = params.getFirst("Description");
|
||||
List<String> subnetIds = memberList(params, "SubnetIds");
|
||||
ClusterSubnetGroup group = service.modifyClusterSubnetGroup(name, description, subnetIds);
|
||||
String xml = new XmlBuilder()
|
||||
.start("ModifyClusterSubnetGroupResponse")
|
||||
.start("ModifyClusterSubnetGroupResult")
|
||||
.raw(buildClusterSubnetGroupXml(group))
|
||||
.end("ModifyClusterSubnetGroupResult")
|
||||
.start("ResponseMetadata")
|
||||
.elem("RequestId", "test-req-id")
|
||||
.end("ResponseMetadata")
|
||||
.end("ModifyClusterSubnetGroupResponse")
|
||||
.build();
|
||||
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
case "DeleteClusterSubnetGroup" -> {
|
||||
String name = params.getFirst("ClusterSubnetGroupName");
|
||||
service.deleteClusterSubnetGroup(name);
|
||||
String xml = new XmlBuilder()
|
||||
.start("DeleteClusterSubnetGroupResponse")
|
||||
.start("ResponseMetadata")
|
||||
.elem("RequestId", "test-req-id")
|
||||
.end("ResponseMetadata")
|
||||
.end("DeleteClusterSubnetGroupResponse")
|
||||
.build();
|
||||
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
case "ModifyCluster" -> {
|
||||
String clusterIdentifier = params.getFirst("ClusterIdentifier");
|
||||
if (clusterIdentifier == null || clusterIdentifier.isBlank()) {
|
||||
throw new AwsException("InvalidParameterValue", "ClusterIdentifier is required", 400);
|
||||
}
|
||||
String nodeType = params.getFirst("NodeType");
|
||||
Integer numberOfNodes = parseOptionalInteger(params, "NumberOfNodes");
|
||||
String masterUserPassword = params.getFirst("MasterUserPassword");
|
||||
String clusterParameterGroupName = params.getFirst("ClusterParameterGroupName");
|
||||
List<String> vpcSecurityGroupIds = memberList(params, "VpcSecurityGroupIds");
|
||||
Cluster cluster = service.modifyCluster(clusterIdentifier, nodeType, numberOfNodes,
|
||||
masterUserPassword, clusterParameterGroupName, vpcSecurityGroupIds);
|
||||
String xml = new XmlBuilder()
|
||||
.start("ModifyClusterResponse")
|
||||
.start("ModifyClusterResult")
|
||||
.raw(buildClusterXml(cluster))
|
||||
.end("ModifyClusterResult")
|
||||
.start("ResponseMetadata")
|
||||
.elem("RequestId", "test-req-id")
|
||||
.end("ResponseMetadata")
|
||||
.end("ModifyClusterResponse")
|
||||
.build();
|
||||
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
case "RebootCluster" -> {
|
||||
String clusterIdentifier = params.getFirst("ClusterIdentifier");
|
||||
if (clusterIdentifier == null || clusterIdentifier.isBlank()) {
|
||||
throw new AwsException("InvalidParameterValue", "ClusterIdentifier is required", 400);
|
||||
}
|
||||
Cluster cluster = service.rebootCluster(clusterIdentifier);
|
||||
String xml = new XmlBuilder()
|
||||
.start("RebootClusterResponse")
|
||||
.start("RebootClusterResult")
|
||||
.raw(buildClusterXml(cluster))
|
||||
.end("RebootClusterResult")
|
||||
.start("ResponseMetadata")
|
||||
.elem("RequestId", "test-req-id")
|
||||
.end("ResponseMetadata")
|
||||
.end("RebootClusterResponse")
|
||||
.build();
|
||||
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
default -> throw new AwsException("InvalidAction", "Action " + action + " is not supported", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private String buildClusterXml(Cluster cluster) {
|
||||
XmlBuilder builder = new XmlBuilder()
|
||||
.start("Cluster")
|
||||
.elem("ClusterIdentifier", cluster.getClusterIdentifier())
|
||||
.elem("NodeType", cluster.getNodeType())
|
||||
.elem("MasterUsername", cluster.getMasterUsername())
|
||||
.elem("ClusterStatus", cluster.getClusterStatus())
|
||||
.elem("ClusterSubnetGroupName", cluster.getClusterSubnetGroupName());
|
||||
|
||||
if (cluster.getVpcSecurityGroupIds() != null && !cluster.getVpcSecurityGroupIds().isEmpty()) {
|
||||
builder.start("VpcSecurityGroups");
|
||||
for (String sgId : cluster.getVpcSecurityGroupIds()) {
|
||||
builder.start("VpcSecurityGroup").elem("VpcSecurityGroupId", sgId).end("VpcSecurityGroup");
|
||||
}
|
||||
builder.end("VpcSecurityGroups");
|
||||
}
|
||||
|
||||
if (cluster.getClusterParameterGroupName() != null) {
|
||||
builder.start("ClusterParameterGroups")
|
||||
.start("ClusterParameterGroup")
|
||||
.elem("ParameterGroupName", cluster.getClusterParameterGroupName())
|
||||
.elem("ParameterApplyStatus", "in-sync")
|
||||
.end("ClusterParameterGroup")
|
||||
.end("ClusterParameterGroups");
|
||||
}
|
||||
|
||||
if (cluster.getTags() != null && !cluster.getTags().isEmpty()) {
|
||||
builder.start("Tags");
|
||||
for (Map.Entry<String, String> tag : cluster.getTags().entrySet()) {
|
||||
builder.start("Tag")
|
||||
.elem("Key", tag.getKey())
|
||||
.elem("Value", tag.getValue())
|
||||
.end("Tag");
|
||||
}
|
||||
builder.end("Tags");
|
||||
}
|
||||
|
||||
if (cluster.getEndpoint() != null) {
|
||||
builder.start("Endpoint")
|
||||
.elem("Address", cluster.getEndpoint().getAddress())
|
||||
.elem("Port", String.valueOf(cluster.getEndpoint().getPort()))
|
||||
.end("Endpoint");
|
||||
}
|
||||
|
||||
return builder.end("Cluster").build();
|
||||
}
|
||||
|
||||
private String buildSnapshotXml(Snapshot snapshot) {
|
||||
XmlBuilder builder = new XmlBuilder()
|
||||
.start("Snapshot")
|
||||
.elem("SnapshotIdentifier", snapshot.getSnapshotIdentifier())
|
||||
.elem("ClusterIdentifier", snapshot.getClusterIdentifier())
|
||||
.elem("Status", snapshot.getStatus())
|
||||
.elem("Port", String.valueOf(snapshot.getPort()))
|
||||
.elem("MasterUsername", snapshot.getMasterUsername());
|
||||
|
||||
return builder.end("Snapshot").build();
|
||||
}
|
||||
|
||||
private String buildClusterParameterGroupXml(ClusterParameterGroup group) {
|
||||
XmlBuilder builder = new XmlBuilder()
|
||||
.start("ClusterParameterGroup")
|
||||
.elem("ParameterGroupName", group.getParameterGroupName())
|
||||
.elem("ParameterGroupFamily", group.getParameterGroupFamily())
|
||||
.elem("Description", group.getDescription());
|
||||
|
||||
return builder.end("ClusterParameterGroup").build();
|
||||
}
|
||||
|
||||
private String buildClusterSubnetGroupXml(ClusterSubnetGroup group) {
|
||||
XmlBuilder builder = new XmlBuilder()
|
||||
.start("ClusterSubnetGroup")
|
||||
.elem("ClusterSubnetGroupName", group.getClusterSubnetGroupName())
|
||||
.elem("Description", group.getDescription())
|
||||
.elem("VpcId", group.getVpcId())
|
||||
.start("Subnets");
|
||||
for (String subnetId : group.getSubnetIds()) {
|
||||
builder.start("Subnet").elem("SubnetIdentifier", subnetId).end("Subnet");
|
||||
}
|
||||
return builder.end("Subnets").end("ClusterSubnetGroup").build();
|
||||
}
|
||||
|
||||
private String buildParameterXml(Parameter param) {
|
||||
XmlBuilder builder = new XmlBuilder()
|
||||
.start("Parameter")
|
||||
.elem("ParameterName", param.getParameterName())
|
||||
.elem("ParameterValue", param.getParameterValue());
|
||||
|
||||
if (param.getDescription() != null) {
|
||||
builder.elem("Description", param.getDescription());
|
||||
}
|
||||
if (param.getDataType() != null) {
|
||||
builder.elem("DataType", param.getDataType());
|
||||
}
|
||||
return builder.end("Parameter").build();
|
||||
}
|
||||
|
||||
private static List<String> memberList(MultivaluedMap<String, String> params, String baseName) {
|
||||
return params.keySet().stream()
|
||||
.filter(key -> key.matches(memberKeyRegex(baseName)))
|
||||
.sorted(Comparator.comparingInt(RedshiftQueryHandler::numericSuffix))
|
||||
.map(params::getFirst)
|
||||
.filter(value -> value != null && !value.isBlank())
|
||||
.toList();
|
||||
}
|
||||
|
||||
// The AWS Query protocol accepts both the generic ".member.N" form and each shape's own
|
||||
// locationName (e.g. the real Redshift SDK sends "SubnetIds.SubnetIdentifier.N", not "SubnetIds.member.N").
|
||||
private static String memberKeyRegex(String baseName) {
|
||||
String quoted = Pattern.quote(baseName);
|
||||
return switch (baseName) {
|
||||
case "SubnetIds" -> quoted + "(\\.member|\\.SubnetIdentifier)?\\.\\d+";
|
||||
case "VpcSecurityGroupIds" -> quoted + "(\\.member|\\.VpcSecurityGroupId)?\\.\\d+";
|
||||
case "TagKeys" -> quoted + "(\\.member|\\.TagKey)?\\.\\d+";
|
||||
default -> quoted + "(\\.member)?\\.\\d+";
|
||||
};
|
||||
}
|
||||
|
||||
private static int numericSuffix(String key) {
|
||||
int lastDot = key.lastIndexOf('.');
|
||||
if (lastDot < 0 || lastDot == key.length() - 1) {
|
||||
return Integer.MAX_VALUE;
|
||||
}
|
||||
try {
|
||||
return Integer.parseInt(key.substring(lastDot + 1));
|
||||
} catch (NumberFormatException e) {
|
||||
return Integer.MAX_VALUE;
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Parameter> parseParameters(MultivaluedMap<String, String> params) {
|
||||
List<Parameter> parsed = new ArrayList<>();
|
||||
readParameters(params, "Parameters.member", parsed);
|
||||
readParameters(params, "Parameters.Parameter", parsed);
|
||||
return parsed;
|
||||
}
|
||||
|
||||
private static void readParameters(MultivaluedMap<String, String> params, String prefix, List<Parameter> parsed) {
|
||||
for (int i = 1; ; i++) {
|
||||
String name = params.getFirst(prefix + "." + i + ".ParameterName");
|
||||
if (name == null) {
|
||||
break;
|
||||
}
|
||||
String value = params.getFirst(prefix + "." + i + ".ParameterValue");
|
||||
parsed.add(new Parameter(name, value));
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, String> parseTags(MultivaluedMap<String, String> params) {
|
||||
Map<String, String> tags = new LinkedHashMap<>();
|
||||
readTags(params, "Tags.member", tags);
|
||||
readTags(params, "Tags.Tag", tags);
|
||||
return tags;
|
||||
}
|
||||
|
||||
private static void readTags(MultivaluedMap<String, String> params, String prefix, Map<String, String> tags) {
|
||||
for (int i = 1; ; i++) {
|
||||
String key = params.getFirst(prefix + "." + i + ".Key");
|
||||
if (key == null) {
|
||||
break;
|
||||
}
|
||||
String value = params.getFirst(prefix + "." + i + ".Value");
|
||||
tags.put(key, value == null ? "" : value);
|
||||
}
|
||||
}
|
||||
|
||||
private static Integer parseOptionalInteger(MultivaluedMap<String, String> params, String parameterName) {
|
||||
String value = params.getFirst(parameterName);
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return Integer.valueOf(value);
|
||||
} catch (NumberFormatException e) {
|
||||
throw new AwsException("InvalidParameterValue", parameterName + " must be an integer.", 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,728 @@
|
||||
package io.github.hectorvent.floci.services.redshift;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerHandle;
|
||||
import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerManager;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Cluster;
|
||||
import io.github.hectorvent.floci.services.redshift.model.ClusterParameterGroup;
|
||||
import io.github.hectorvent.floci.services.redshift.model.ClusterSubnetGroup;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Endpoint;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Parameter;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Snapshot;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.event.Observes;
|
||||
import jakarta.inject.Inject;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.quarkus.runtime.StartupEvent;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
@ApplicationScoped
|
||||
public class RedshiftService {
|
||||
private static final Logger LOG = Logger.getLogger(RedshiftService.class);
|
||||
|
||||
private final AccountAwareStorageBackend<Cluster> clusters;
|
||||
private final AccountAwareStorageBackend<Snapshot> snapshots;
|
||||
private final AccountAwareStorageBackend<ClusterParameterGroup> parameterGroups;
|
||||
private final AccountAwareStorageBackend<ClusterSubnetGroup> subnetGroups;
|
||||
private final RedshiftContainerManager containerManager;
|
||||
private final EmulatorConfig config;
|
||||
private final RegionResolver regionResolver;
|
||||
|
||||
@Inject
|
||||
public RedshiftService(StorageFactory storageFactory, RedshiftContainerManager containerManager,
|
||||
EmulatorConfig config, RegionResolver regionResolver) {
|
||||
this.clusters = storageFactory.create("redshift", "redshift-clusters.json", new TypeReference<Map<String, Cluster>>() {});
|
||||
this.snapshots = storageFactory.create("redshift", "redshift-snapshots.json", new TypeReference<Map<String, Snapshot>>() {});
|
||||
this.parameterGroups = storageFactory.create("redshift", "redshift-parameter-groups.json", new TypeReference<Map<String, ClusterParameterGroup>>() {});
|
||||
this.subnetGroups = storageFactory.create("redshift", "redshift-subnet-groups.json", new TypeReference<Map<String, ClusterSubnetGroup>>() {});
|
||||
this.containerManager = containerManager;
|
||||
this.config = config;
|
||||
this.regionResolver = regionResolver;
|
||||
}
|
||||
|
||||
// Recreate Docker containers for persisted clusters on app restart (across every account, not just default)
|
||||
void onStart(@Observes StartupEvent event) {
|
||||
List<AccountAwareStorageBackend.AccountEntry<Cluster>> availableClusters =
|
||||
clusters.scanAllAccountEntries(k -> true).stream()
|
||||
.filter(entry -> "available".equals(entry.value().getClusterStatus()))
|
||||
.toList();
|
||||
for (AccountAwareStorageBackend.AccountEntry<Cluster> entry : availableClusters) {
|
||||
Cluster cluster = entry.value();
|
||||
if (containerManager.getContainer(entry.accountId(), cluster.getClusterIdentifier()).isPresent()) {
|
||||
continue;
|
||||
}
|
||||
String password = cluster.getMasterPassword() != null ? cluster.getMasterPassword() : "admin";
|
||||
try {
|
||||
LOG.infov("Recovering container for persisted cluster: {0}", cluster.getClusterIdentifier());
|
||||
RedshiftContainerHandle handle = containerManager.adoptOrStart(
|
||||
entry.accountId(), cluster.getClusterIdentifier(), cluster.getMasterUsername(), password);
|
||||
Endpoint endpoint = new Endpoint();
|
||||
endpoint.setAddress(handle.getHost());
|
||||
endpoint.setPort(handle.getPort());
|
||||
cluster.setEndpoint(endpoint);
|
||||
clusters.putForAccount(entry.accountId(), entry.key(), cluster);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv(e, "Failed to recover container for cluster {0}, marking as unavailable",
|
||||
cluster.getClusterIdentifier());
|
||||
cluster.setClusterStatus("unavailable");
|
||||
clusters.putForAccount(entry.accountId(), entry.key(), cluster);
|
||||
}
|
||||
}
|
||||
clusters.flush();
|
||||
}
|
||||
|
||||
public Cluster createCluster(String identifier, String nodeType, String username, String password) {
|
||||
return createCluster(identifier, nodeType, username, password, null, List.of());
|
||||
}
|
||||
|
||||
public Cluster createCluster(String identifier, String nodeType, String username, String password,
|
||||
String clusterSubnetGroupName, List<String> vpcSecurityGroupIds) {
|
||||
if (clusters.get(identifier).isPresent()) {
|
||||
throw new AwsException("ClusterAlreadyExists", "Cluster " + identifier + " already exists", 400);
|
||||
}
|
||||
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier(identifier);
|
||||
cluster.setNodeType(nodeType);
|
||||
cluster.setMasterUsername(username);
|
||||
cluster.setMasterPassword(password);
|
||||
cluster.setClusterSubnetGroupName(clusterSubnetGroupName);
|
||||
cluster.setVpcSecurityGroupIds(vpcSecurityGroupIds != null ? vpcSecurityGroupIds : List.of());
|
||||
cluster.setClusterStatus("creating");
|
||||
clusters.put(identifier, cluster);
|
||||
clusters.flush();
|
||||
|
||||
// Start container
|
||||
try {
|
||||
RedshiftContainerHandle handle = containerManager.start(clusters.accountId(), identifier, username, password);
|
||||
Endpoint endpoint = new Endpoint();
|
||||
endpoint.setAddress(handle.getHost());
|
||||
endpoint.setPort(handle.getPort());
|
||||
cluster.setEndpoint(endpoint);
|
||||
cluster.setClusterStatus("available");
|
||||
} catch (Exception e) {
|
||||
cluster.setClusterStatus("failed");
|
||||
clusters.flush();
|
||||
throw new AwsException("InternalFailure", "Failed to start container: " + e.getMessage(), 500);
|
||||
}
|
||||
|
||||
clusters.put(identifier, cluster);
|
||||
clusters.flush();
|
||||
return cluster;
|
||||
}
|
||||
|
||||
public List<Cluster> describeClusters(String identifier) {
|
||||
if (identifier != null) {
|
||||
Optional<Cluster> cluster = clusters.get(identifier);
|
||||
if (cluster.isEmpty()) {
|
||||
throw new AwsException("ClusterNotFound", "Cluster " + identifier + " not found", 404);
|
||||
}
|
||||
return List.of(cluster.get());
|
||||
}
|
||||
return clusters.scan(k -> true);
|
||||
}
|
||||
|
||||
public Cluster deleteCluster(String identifier) {
|
||||
Optional<Cluster> clusterOpt = clusters.get(identifier);
|
||||
if (clusterOpt.isEmpty()) {
|
||||
throw new AwsException("ClusterNotFound", "Cluster " + identifier + " not found", 404);
|
||||
}
|
||||
Cluster cluster = clusterOpt.get();
|
||||
|
||||
containerManager.stop(clusters.accountId(), identifier);
|
||||
clusters.delete(identifier);
|
||||
clusters.flush();
|
||||
|
||||
cluster.setClusterStatus("deleting");
|
||||
return cluster;
|
||||
}
|
||||
|
||||
public synchronized Cluster modifyCluster(String clusterIdentifier, String nodeType, Integer numberOfNodes,
|
||||
String masterUserPassword, String clusterParameterGroupName,
|
||||
List<String> vpcSecurityGroupIds) {
|
||||
Cluster cluster = clusters.get(clusterIdentifier)
|
||||
.orElseThrow(() -> new AwsException("ClusterNotFound", "Cluster " + clusterIdentifier + " not found", 404));
|
||||
|
||||
// alterUserPassword runs before any mutation of the cluster object (a live reference
|
||||
// from HybridStorage, not a copy) — if it throws, no metadata has been changed yet.
|
||||
if (masterUserPassword != null && !masterUserPassword.isBlank()) {
|
||||
containerManager.alterUserPassword(clusters.accountId(), clusterIdentifier,
|
||||
cluster.getMasterUsername(), masterUserPassword);
|
||||
cluster.setMasterPassword(masterUserPassword);
|
||||
}
|
||||
|
||||
// NodeType only updates metadata — it does not resize the underlying Postgres container
|
||||
// (Redshift node-count has no equivalent here). NumberOfNodes is accepted for API-shape
|
||||
// compatibility but is not modelled or stored anywhere — known gap, see plan Task 9.
|
||||
if (nodeType != null && !nodeType.isBlank()) {
|
||||
cluster.setNodeType(nodeType);
|
||||
}
|
||||
if (clusterParameterGroupName != null && !clusterParameterGroupName.isBlank()) {
|
||||
cluster.setClusterParameterGroupName(clusterParameterGroupName);
|
||||
}
|
||||
if (vpcSecurityGroupIds != null && !vpcSecurityGroupIds.isEmpty()) {
|
||||
cluster.setVpcSecurityGroupIds(vpcSecurityGroupIds);
|
||||
}
|
||||
|
||||
clusters.put(clusterIdentifier, cluster);
|
||||
clusters.flush();
|
||||
return cluster;
|
||||
}
|
||||
|
||||
public synchronized Cluster rebootCluster(String clusterIdentifier) {
|
||||
Cluster cluster = clusters.get(clusterIdentifier)
|
||||
.orElseThrow(() -> new AwsException("ClusterNotFound", "Cluster " + clusterIdentifier + " not found", 404));
|
||||
|
||||
// The container backing a cluster has no persistent volume (see RedshiftContainerManager),
|
||||
// so a plain stop+recreate would silently drop the cluster's data. Dump before stopping and
|
||||
// restore immediately after starting, using a throwaway temp file — no Snapshot resource is
|
||||
// created or exposed to the caller.
|
||||
Path tempDump;
|
||||
try {
|
||||
tempDump = Files.createTempFile("redshift-reboot-" + clusterIdentifier, ".sql");
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("InternalFailure", "Failed to prepare reboot dump file: " + e.getMessage(), 500);
|
||||
}
|
||||
|
||||
try {
|
||||
containerManager.takeSnapshot(clusters.accountId(), clusterIdentifier, cluster.getMasterUsername(), tempDump);
|
||||
containerManager.stop(clusters.accountId(), clusterIdentifier);
|
||||
|
||||
String password = cluster.getMasterPassword() != null ? cluster.getMasterPassword() : "admin";
|
||||
RedshiftContainerHandle handle = containerManager.start(
|
||||
clusters.accountId(), clusterIdentifier, cluster.getMasterUsername(), password);
|
||||
Endpoint endpoint = new Endpoint();
|
||||
endpoint.setAddress(handle.getHost());
|
||||
endpoint.setPort(handle.getPort());
|
||||
cluster.setEndpoint(endpoint);
|
||||
|
||||
containerManager.restoreSnapshot(clusters.accountId(), clusterIdentifier, cluster.getMasterUsername(), tempDump);
|
||||
|
||||
cluster.setClusterStatus("available");
|
||||
} catch (AwsException e) {
|
||||
cluster.setClusterStatus("failed");
|
||||
clusters.flush();
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
cluster.setClusterStatus("failed");
|
||||
clusters.flush();
|
||||
throw new AwsException("InternalFailure", "Failed to reboot cluster " + clusterIdentifier + ": " + e.getMessage(), 500);
|
||||
} finally {
|
||||
try {
|
||||
Files.deleteIfExists(tempDump);
|
||||
} catch (IOException ignored) {
|
||||
// best-effort cleanup of a temp file
|
||||
}
|
||||
}
|
||||
|
||||
clusters.put(clusterIdentifier, cluster);
|
||||
clusters.flush();
|
||||
return cluster;
|
||||
}
|
||||
|
||||
// ── Snapshot Operations ──────────────────────────────────────────────────
|
||||
|
||||
// AWS constrains a snapshot identifier to 1-255 characters, first a letter, then
|
||||
// letters, digits or single hyphens (no trailing or doubled hyphen). Enforcing that
|
||||
// here also keeps the value safe to splice into the dump file path below: '.', '/'
|
||||
// and '\' can never appear, so it cannot escape the account's dump directory.
|
||||
private static void validateSnapshotIdentifier(String id) {
|
||||
if (id == null || !id.matches("[a-zA-Z][a-zA-Z0-9-]{0,254}")
|
||||
|| id.contains("--") || id.endsWith("-")) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"SnapshotIdentifier must be 1-255 characters, start with a letter, and contain "
|
||||
+ "only letters, digits and non-consecutive hyphens", 400);
|
||||
}
|
||||
}
|
||||
|
||||
/** Absolute, normalised {@code <persistentPath>/redshift-dumps/<accountId>} for this request's account. */
|
||||
private Path accountDumpDir() {
|
||||
return Paths.get(config.storage().persistentPath())
|
||||
.resolve("redshift-dumps")
|
||||
.resolve(clusters.accountId())
|
||||
.toAbsolutePath()
|
||||
.normalize();
|
||||
}
|
||||
|
||||
/**
|
||||
* A stored {@code sqlDump} path is trusted only if it still resolves inside this account's
|
||||
* dump directory. Guards restore/delete against a path persisted by an older, unvalidated
|
||||
* createSnapshot (or by a different account).
|
||||
*/
|
||||
private boolean isTrustedDumpPath(String storedPath) {
|
||||
if (storedPath == null || storedPath.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
Path dir = accountDumpDir();
|
||||
return Paths.get(storedPath).toAbsolutePath().normalize().startsWith(dir);
|
||||
}
|
||||
|
||||
public Snapshot createSnapshot(String snapshotIdentifier, String clusterIdentifier) {
|
||||
validateSnapshotIdentifier(snapshotIdentifier);
|
||||
Optional<Cluster> clusterOpt = clusters.get(clusterIdentifier);
|
||||
if (clusterOpt.isEmpty()) {
|
||||
throw new AwsException("ClusterNotFound", "Cluster " + clusterIdentifier + " not found", 404);
|
||||
}
|
||||
if (snapshots.get(snapshotIdentifier).isPresent()) {
|
||||
throw new AwsException("ClusterSnapshotAlreadyExists", "Snapshot " + snapshotIdentifier + " already exists", 400);
|
||||
}
|
||||
|
||||
Cluster cluster = clusterOpt.get();
|
||||
Snapshot snapshot = new Snapshot();
|
||||
snapshot.setSnapshotIdentifier(snapshotIdentifier);
|
||||
snapshot.setClusterIdentifier(clusterIdentifier);
|
||||
snapshot.setStatus("available");
|
||||
snapshot.setMasterUsername(cluster.getMasterUsername());
|
||||
snapshot.setMasterPassword(cluster.getMasterPassword());
|
||||
if (cluster.getEndpoint() != null) {
|
||||
snapshot.setPort(cluster.getEndpoint().getPort());
|
||||
} else {
|
||||
snapshot.setPort(5439);
|
||||
}
|
||||
|
||||
Path dumpDir = accountDumpDir();
|
||||
// Defence in depth: validateSnapshotIdentifier already rejects path separators,
|
||||
// but keep the containment check so the dump can never land outside the account dir.
|
||||
Path dumpFile = dumpDir.resolve(snapshotIdentifier + ".sql").normalize();
|
||||
if (!dumpFile.startsWith(dumpDir)) {
|
||||
throw new AwsException("InvalidParameterValue", "Invalid snapshot identifier", 400);
|
||||
}
|
||||
try {
|
||||
Files.createDirectories(dumpDir);
|
||||
containerManager.takeSnapshot(clusters.accountId(), clusterIdentifier, cluster.getMasterUsername(), dumpFile);
|
||||
snapshot.setSqlDump(dumpFile.toString());
|
||||
} catch (AwsException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new AwsException("InternalFailure", "Failed to take snapshot for cluster " + clusterIdentifier + ": " + e.getMessage(), 500);
|
||||
}
|
||||
|
||||
snapshots.put(snapshotIdentifier, snapshot);
|
||||
snapshots.flush();
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
public List<Snapshot> describeSnapshots(String snapshotIdentifier, String clusterIdentifier) {
|
||||
if (snapshotIdentifier != null && !snapshotIdentifier.isBlank()) {
|
||||
Optional<Snapshot> snapshot = snapshots.get(snapshotIdentifier);
|
||||
if (snapshot.isEmpty()) {
|
||||
throw new AwsException("ClusterSnapshotNotFound", "Snapshot " + snapshotIdentifier + " not found", 404);
|
||||
}
|
||||
return List.of(snapshot.get());
|
||||
}
|
||||
if (clusterIdentifier != null && !clusterIdentifier.isBlank()) {
|
||||
return snapshots.scan(k -> true).stream()
|
||||
.filter(s -> clusterIdentifier.equals(s.getClusterIdentifier()))
|
||||
.toList();
|
||||
}
|
||||
return snapshots.scan(k -> true);
|
||||
}
|
||||
|
||||
public List<Snapshot> describeSnapshots(String snapshotIdentifier) {
|
||||
return describeSnapshots(snapshotIdentifier, null);
|
||||
}
|
||||
|
||||
public Optional<Snapshot> getSnapshot(String snapshotIdentifier) {
|
||||
return snapshots.get(snapshotIdentifier);
|
||||
}
|
||||
|
||||
public Snapshot deleteSnapshot(String snapshotIdentifier) {
|
||||
Optional<Snapshot> snapshotOpt = snapshots.get(snapshotIdentifier);
|
||||
if (snapshotOpt.isEmpty()) {
|
||||
throw new AwsException("ClusterSnapshotNotFound", "Snapshot " + snapshotIdentifier + " not found", 404);
|
||||
}
|
||||
Snapshot snapshot = snapshotOpt.get();
|
||||
snapshots.delete(snapshotIdentifier);
|
||||
snapshots.flush();
|
||||
if (isTrustedDumpPath(snapshot.getSqlDump())) {
|
||||
try {
|
||||
Files.deleteIfExists(Paths.get(snapshot.getSqlDump()));
|
||||
} catch (IOException e) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
snapshot.setStatus("deleted");
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
public Cluster restoreFromClusterSnapshot(String clusterIdentifier, String snapshotIdentifier) {
|
||||
return restoreFromClusterSnapshot(clusterIdentifier, snapshotIdentifier, null);
|
||||
}
|
||||
|
||||
public Cluster restoreFromClusterSnapshot(String clusterIdentifier, String snapshotIdentifier, String nodeType) {
|
||||
if (clusters.get(clusterIdentifier).isPresent()) {
|
||||
throw new AwsException("ClusterAlreadyExists", "Cluster " + clusterIdentifier + " already exists", 400);
|
||||
}
|
||||
|
||||
Optional<Snapshot> snapshotOpt = snapshots.get(snapshotIdentifier);
|
||||
if (snapshotOpt.isEmpty()) {
|
||||
throw new AwsException("ClusterSnapshotNotFound", "Snapshot " + snapshotIdentifier + " not found", 404);
|
||||
}
|
||||
|
||||
Snapshot snapshot = snapshotOpt.get();
|
||||
|
||||
// Validate the stored dump location up front, before any provisioning. A snapshot whose
|
||||
// sqlDump was written by pre-validation code could point outside this account's dump dir;
|
||||
// rejecting it here (rather than mid-restore) avoids leaving a half-created cluster record
|
||||
// and an orphaned container behind.
|
||||
String sqlDump = snapshot.getSqlDump();
|
||||
boolean hasDump = sqlDump != null && !sqlDump.isBlank();
|
||||
if (hasDump && !isTrustedDumpPath(sqlDump)) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"Snapshot " + snapshotIdentifier + " has an unusable dump location", 400);
|
||||
}
|
||||
|
||||
String effectiveNodeType = (nodeType != null && !nodeType.isBlank()) ? nodeType : "dc2.large";
|
||||
String username = snapshot.getMasterUsername() != null ? snapshot.getMasterUsername() : "admin";
|
||||
String sourceCluster = snapshot.getClusterIdentifier();
|
||||
String password = Optional.ofNullable(snapshot.getMasterPassword())
|
||||
.filter(p -> !p.isBlank())
|
||||
.or(() -> clusters.get(sourceCluster).map(Cluster::getMasterPassword))
|
||||
.filter(p -> p != null && !p.isBlank())
|
||||
.orElse("admin");
|
||||
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier(clusterIdentifier);
|
||||
cluster.setNodeType(effectiveNodeType);
|
||||
cluster.setMasterUsername(username);
|
||||
cluster.setMasterPassword(password);
|
||||
cluster.setClusterStatus("creating");
|
||||
clusters.put(clusterIdentifier, cluster);
|
||||
clusters.flush();
|
||||
|
||||
try {
|
||||
RedshiftContainerHandle handle = containerManager.start(clusters.accountId(), clusterIdentifier, username, password);
|
||||
Endpoint endpoint = new Endpoint();
|
||||
endpoint.setAddress(handle.getHost());
|
||||
endpoint.setPort(handle.getPort());
|
||||
cluster.setEndpoint(endpoint);
|
||||
|
||||
if (hasDump) {
|
||||
containerManager.restoreSnapshot(clusters.accountId(), clusterIdentifier, username, Paths.get(sqlDump));
|
||||
}
|
||||
|
||||
cluster.setClusterStatus("available");
|
||||
} catch (AwsException e) {
|
||||
cluster.setClusterStatus("failed");
|
||||
clusters.flush();
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
cluster.setClusterStatus("failed");
|
||||
clusters.flush();
|
||||
throw new AwsException("InternalFailure", "Failed to restore cluster from snapshot: " + e.getMessage(), 500);
|
||||
}
|
||||
|
||||
clusters.put(clusterIdentifier, cluster);
|
||||
clusters.flush();
|
||||
return cluster;
|
||||
}
|
||||
|
||||
// ── Parameter Group Operations ───────────────────────────────────────────
|
||||
|
||||
public ClusterParameterGroup createClusterParameterGroup(String parameterGroupName, String parameterGroupFamily, String description) {
|
||||
if (parameterGroups.get(parameterGroupName).isPresent()) {
|
||||
throw new AwsException("ClusterParameterGroupAlreadyExists", "Cluster parameter group " + parameterGroupName + " already exists", 400);
|
||||
}
|
||||
|
||||
ClusterParameterGroup group = new ClusterParameterGroup(parameterGroupName, parameterGroupFamily, description);
|
||||
parameterGroups.put(parameterGroupName, group);
|
||||
parameterGroups.flush();
|
||||
return group;
|
||||
}
|
||||
|
||||
public List<ClusterParameterGroup> describeClusterParameterGroups(String parameterGroupName) {
|
||||
if (parameterGroupName != null && !parameterGroupName.isBlank()) {
|
||||
Optional<ClusterParameterGroup> group = parameterGroups.get(parameterGroupName);
|
||||
if (group.isEmpty()) {
|
||||
throw new AwsException("ClusterParameterGroupNotFound", "Cluster parameter group " + parameterGroupName + " not found", 404);
|
||||
}
|
||||
return List.of(group.get());
|
||||
}
|
||||
return parameterGroups.scan(k -> true);
|
||||
}
|
||||
|
||||
public Optional<ClusterParameterGroup> getClusterParameterGroup(String parameterGroupName) {
|
||||
return parameterGroups.get(parameterGroupName);
|
||||
}
|
||||
|
||||
public List<Parameter> describeClusterParameters(String parameterGroupName) {
|
||||
ClusterParameterGroup group = parameterGroups.get(parameterGroupName)
|
||||
.orElseThrow(() -> new AwsException("ClusterParameterGroupNotFound",
|
||||
"Cluster parameter group " + parameterGroupName + " not found", 404));
|
||||
return group.getParameters();
|
||||
}
|
||||
|
||||
public synchronized ClusterParameterGroup modifyClusterParameterGroup(
|
||||
String parameterGroupName, List<Parameter> updates) {
|
||||
ClusterParameterGroup group = parameterGroups.get(parameterGroupName)
|
||||
.orElseThrow(() -> new AwsException("ClusterParameterGroupNotFound",
|
||||
"Cluster parameter group " + parameterGroupName + " not found", 404));
|
||||
|
||||
List<Parameter> current = new ArrayList<>(group.getParameters());
|
||||
for (Parameter update : updates) {
|
||||
boolean matched = false;
|
||||
for (int i = 0; i < current.size(); i++) {
|
||||
Parameter existing = current.get(i);
|
||||
if (existing.getParameterName().equals(update.getParameterName())) {
|
||||
// Preserve metadata (description, dataType) from existing parameter if not provided in update
|
||||
existing.setParameterValue(update.getParameterValue());
|
||||
if (update.getDescription() != null) {
|
||||
existing.setDescription(update.getDescription());
|
||||
}
|
||||
if (update.getDataType() != null) {
|
||||
existing.setDataType(update.getDataType());
|
||||
}
|
||||
matched = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!matched) {
|
||||
current.add(update);
|
||||
}
|
||||
}
|
||||
group.setParameters(current);
|
||||
parameterGroups.put(parameterGroupName, group);
|
||||
parameterGroups.flush();
|
||||
return group;
|
||||
}
|
||||
|
||||
public ClusterParameterGroup deleteClusterParameterGroup(String parameterGroupName) {
|
||||
Optional<ClusterParameterGroup> groupOpt = parameterGroups.get(parameterGroupName);
|
||||
if (groupOpt.isEmpty()) {
|
||||
throw new AwsException("ClusterParameterGroupNotFound", "Cluster parameter group " + parameterGroupName + " not found", 404);
|
||||
}
|
||||
ClusterParameterGroup group = groupOpt.get();
|
||||
parameterGroups.delete(parameterGroupName);
|
||||
parameterGroups.flush();
|
||||
return group;
|
||||
}
|
||||
|
||||
// ── Cluster Subnet Group Operations ──────────────────────────────────────
|
||||
|
||||
public ClusterSubnetGroup createClusterSubnetGroup(String name, String description, String vpcId, List<String> subnetIds) {
|
||||
if (subnetGroups.get(name).isPresent()) {
|
||||
throw new AwsException("ClusterSubnetGroupAlreadyExists", "Cluster subnet group " + name + " already exists", 400);
|
||||
}
|
||||
ClusterSubnetGroup group = new ClusterSubnetGroup(name, description, vpcId, subnetIds);
|
||||
subnetGroups.put(name, group);
|
||||
subnetGroups.flush();
|
||||
return group;
|
||||
}
|
||||
|
||||
public List<ClusterSubnetGroup> describeClusterSubnetGroups(String name) {
|
||||
if (name != null && !name.isBlank()) {
|
||||
ClusterSubnetGroup group = subnetGroups.get(name)
|
||||
.orElseThrow(() -> new AwsException("ClusterSubnetGroupNotFound", "Cluster subnet group " + name + " not found", 404));
|
||||
return List.of(group);
|
||||
}
|
||||
return subnetGroups.scan(k -> true);
|
||||
}
|
||||
|
||||
public synchronized ClusterSubnetGroup modifyClusterSubnetGroup(String name, String description, List<String> subnetIds) {
|
||||
ClusterSubnetGroup group = subnetGroups.get(name)
|
||||
.orElseThrow(() -> new AwsException("ClusterSubnetGroupNotFound", "Cluster subnet group " + name + " not found", 404));
|
||||
if (description != null) {
|
||||
group.setDescription(description);
|
||||
}
|
||||
if (subnetIds != null && !subnetIds.isEmpty()) {
|
||||
group.setSubnetIds(subnetIds);
|
||||
}
|
||||
subnetGroups.put(name, group);
|
||||
subnetGroups.flush();
|
||||
return group;
|
||||
}
|
||||
|
||||
public ClusterSubnetGroup deleteClusterSubnetGroup(String name) {
|
||||
ClusterSubnetGroup group = subnetGroups.get(name)
|
||||
.orElseThrow(() -> new AwsException("ClusterSubnetGroupNotFound", "Cluster subnet group " + name + " not found", 404));
|
||||
subnetGroups.delete(name);
|
||||
subnetGroups.flush();
|
||||
return group;
|
||||
}
|
||||
|
||||
// ── Tagging Operations ───────────────────────────────────────────────────
|
||||
|
||||
/** A resolved tag target: its current tags plus a sink that persists an updated map. */
|
||||
private record TagHandle(Map<String, String> tags, Consumer<Map<String, String>> save) {}
|
||||
|
||||
public record TaggedResource(String resourceName, String resourceType, String tagKey, String tagValue) {}
|
||||
|
||||
public Map<String, String> listTagsForResource(String resourceName) {
|
||||
return Map.copyOf(resolveTagHandle(resourceName).tags());
|
||||
}
|
||||
|
||||
public synchronized void createTags(String resourceName, Map<String, String> tags) {
|
||||
TagHandle handle = resolveTagHandle(resourceName);
|
||||
Map<String, String> updated = new LinkedHashMap<>(handle.tags());
|
||||
updated.putAll(tags);
|
||||
handle.save().accept(updated);
|
||||
}
|
||||
|
||||
public synchronized void deleteTags(String resourceName, Collection<String> tagKeys) {
|
||||
TagHandle handle = resolveTagHandle(resourceName);
|
||||
Map<String, String> updated = new LinkedHashMap<>(handle.tags());
|
||||
tagKeys.forEach(updated::remove);
|
||||
handle.save().accept(updated);
|
||||
}
|
||||
|
||||
public List<TaggedResource> describeTags(String resourceName, String resourceType, List<String> tagKeysFilter) {
|
||||
List<TaggedResource> result = new ArrayList<>();
|
||||
if (resourceName != null && !resourceName.isBlank()) {
|
||||
TagHandle handle = resolveTagHandle(resourceName);
|
||||
String type = arnResourceType(resourceName);
|
||||
addTaggedResources(result, resourceName, type, handle.tags(), tagKeysFilter);
|
||||
return result;
|
||||
}
|
||||
if (resourceType == null || "cluster".equalsIgnoreCase(resourceType)) {
|
||||
for (Cluster c : clusters.scan(k -> true)) {
|
||||
addTaggedResources(result, clusterArn(c.getClusterIdentifier()), "cluster", c.getTags(), tagKeysFilter);
|
||||
}
|
||||
}
|
||||
if (resourceType == null || "snapshot".equalsIgnoreCase(resourceType)) {
|
||||
for (Snapshot s : snapshots.scan(k -> true)) {
|
||||
addTaggedResources(result, snapshotArn(s.getClusterIdentifier(), s.getSnapshotIdentifier()),
|
||||
"snapshot", s.getTags(), tagKeysFilter);
|
||||
}
|
||||
}
|
||||
if (resourceType == null || "parametergroup".equalsIgnoreCase(resourceType)) {
|
||||
for (ClusterParameterGroup g : parameterGroups.scan(k -> true)) {
|
||||
addTaggedResources(result, parameterGroupArn(g.getParameterGroupName()),
|
||||
"parametergroup", g.getTags(), tagKeysFilter);
|
||||
}
|
||||
}
|
||||
if (resourceType == null || "subnetgroup".equalsIgnoreCase(resourceType)) {
|
||||
for (ClusterSubnetGroup g : subnetGroups.scan(k -> true)) {
|
||||
addTaggedResources(result, subnetGroupArn(g.getClusterSubnetGroupName()),
|
||||
"subnetgroup", g.getTags(), tagKeysFilter);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private void addTaggedResources(List<TaggedResource> out, String arn, String type,
|
||||
Map<String, String> tags, List<String> tagKeysFilter) {
|
||||
for (Map.Entry<String, String> e : tags.entrySet()) {
|
||||
if (tagKeysFilter != null && !tagKeysFilter.isEmpty() && !tagKeysFilter.contains(e.getKey())) {
|
||||
continue;
|
||||
}
|
||||
out.add(new TaggedResource(arn, type, e.getKey(), e.getValue()));
|
||||
}
|
||||
}
|
||||
|
||||
private String arnResourceType(String resourceName) {
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(resourceName);
|
||||
String resource = arn.resource();
|
||||
int sep = resource.indexOf(':');
|
||||
return resource.substring(0, sep);
|
||||
}
|
||||
|
||||
private String clusterArn(String clusterIdentifier) {
|
||||
return regionResolver.buildArn("redshift", regionResolver.getRegion(), "cluster:" + clusterIdentifier);
|
||||
}
|
||||
|
||||
private String snapshotArn(String clusterIdentifier, String snapshotIdentifier) {
|
||||
return regionResolver.buildArn("redshift", regionResolver.getRegion(),
|
||||
"snapshot:" + clusterIdentifier + "/" + snapshotIdentifier);
|
||||
}
|
||||
|
||||
private String parameterGroupArn(String parameterGroupName) {
|
||||
return regionResolver.buildArn("redshift", regionResolver.getRegion(), "parametergroup:" + parameterGroupName);
|
||||
}
|
||||
|
||||
private String subnetGroupArn(String name) {
|
||||
return regionResolver.buildArn("redshift", regionResolver.getRegion(), "subnetgroup:" + name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a tagging ResourceName to its backing resource.
|
||||
*
|
||||
* Redshift ARNs have the shape {@code arn:aws:redshift:<region>:<account>:<type>:<id>},
|
||||
* where {@code <type>} is one of {@code cluster}, {@code snapshot} (id shape
|
||||
* {@code <clusterId>/<snapshotId>}), or {@code parametergroup}. Unlike RDS's tag
|
||||
* resolution, there is no bare-name fallback — Redshift tagging is new, so there is no
|
||||
* existing caller to stay backward compatible with.
|
||||
*/
|
||||
private TagHandle resolveTagHandle(String resourceName) {
|
||||
if (resourceName == null || resourceName.isBlank()) {
|
||||
throw new AwsException("InvalidParameterValue", "ResourceName is required.", 400);
|
||||
}
|
||||
if (!resourceName.startsWith("arn:")) {
|
||||
throw new AwsException("InvalidParameterValue", "ResourceName must be a Redshift ARN: " + resourceName, 400);
|
||||
}
|
||||
AwsArnUtils.Arn arn;
|
||||
try {
|
||||
arn = AwsArnUtils.parse(resourceName);
|
||||
} catch (IllegalArgumentException malformed) {
|
||||
throw new AwsException("InvalidParameterValue", "Invalid resource name: " + resourceName, 400);
|
||||
}
|
||||
if (!"redshift".equals(arn.service())) {
|
||||
throw new AwsException("InvalidParameterValue", "Invalid resource name: " + resourceName, 400);
|
||||
}
|
||||
String resource = arn.resource();
|
||||
int sep = resource.indexOf(':');
|
||||
if (sep < 0) {
|
||||
throw new AwsException("InvalidParameterValue", "Invalid resource name: " + resourceName, 400);
|
||||
}
|
||||
String type = resource.substring(0, sep);
|
||||
String id = resource.substring(sep + 1);
|
||||
|
||||
return switch (type) {
|
||||
case "cluster" -> {
|
||||
Cluster cluster = clusters.get(id)
|
||||
.orElseThrow(() -> new AwsException("ClusterNotFound", "Cluster " + id + " not found", 404));
|
||||
yield new TagHandle(cluster.getTags(), updated -> {
|
||||
cluster.setTags(updated);
|
||||
clusters.put(id, cluster);
|
||||
clusters.flush();
|
||||
});
|
||||
}
|
||||
case "snapshot" -> {
|
||||
String snapshotId = id.contains("/") ? id.substring(id.lastIndexOf('/') + 1) : id;
|
||||
Snapshot snapshot = snapshots.get(snapshotId)
|
||||
.orElseThrow(() -> new AwsException("ClusterSnapshotNotFound", "Snapshot " + snapshotId + " not found", 404));
|
||||
yield new TagHandle(snapshot.getTags(), updated -> {
|
||||
snapshot.setTags(updated);
|
||||
snapshots.put(snapshotId, snapshot);
|
||||
snapshots.flush();
|
||||
});
|
||||
}
|
||||
case "parametergroup" -> {
|
||||
ClusterParameterGroup group = parameterGroups.get(id)
|
||||
.orElseThrow(() -> new AwsException("ClusterParameterGroupNotFound", "Cluster parameter group " + id + " not found", 404));
|
||||
yield new TagHandle(group.getTags(), updated -> {
|
||||
group.setTags(updated);
|
||||
parameterGroups.put(id, group);
|
||||
parameterGroups.flush();
|
||||
});
|
||||
}
|
||||
case "subnetgroup" -> {
|
||||
ClusterSubnetGroup group = subnetGroups.get(id)
|
||||
.orElseThrow(() -> new AwsException("ClusterSubnetGroupNotFound", "Cluster subnet group " + id + " not found", 404));
|
||||
yield new TagHandle(group.getTags(), updated -> {
|
||||
group.setTags(updated);
|
||||
subnetGroups.put(id, group);
|
||||
subnetGroups.flush();
|
||||
});
|
||||
}
|
||||
default -> throw new AwsException("InvalidParameterValue",
|
||||
"Tagging for resource type '" + type + "' is not supported: " + resourceName, 400);
|
||||
};
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package io.github.hectorvent.floci.services.redshift.container;
|
||||
|
||||
import java.io.Closeable;
|
||||
|
||||
public class RedshiftContainerHandle {
|
||||
private final String containerId;
|
||||
private final String clusterIdentifier;
|
||||
private final String host;
|
||||
private final int port;
|
||||
private Closeable logStream;
|
||||
|
||||
public RedshiftContainerHandle(String containerId, String clusterIdentifier, String host, int port) {
|
||||
this.containerId = containerId;
|
||||
this.clusterIdentifier = clusterIdentifier;
|
||||
this.host = host;
|
||||
this.port = port;
|
||||
}
|
||||
|
||||
public String getContainerId() { return containerId; }
|
||||
public String getClusterIdentifier() { return clusterIdentifier; }
|
||||
public String getHost() { return host; }
|
||||
public int getPort() { return port; }
|
||||
public void setLogStream(Closeable logStream) { this.logStream = logStream; }
|
||||
public Closeable getLogStream() { return logStream; }
|
||||
}
|
||||
+386
@@ -0,0 +1,386 @@
|
||||
package io.github.hectorvent.floci.services.redshift.container;
|
||||
|
||||
import com.github.dockerjava.api.async.ResultCallback;
|
||||
import com.github.dockerjava.api.model.Frame;
|
||||
import com.github.dockerjava.api.model.StreamType;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerInfo;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.EndpointInfo;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Cluster;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.Closeable;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@ApplicationScoped
|
||||
public class RedshiftContainerManager {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(RedshiftContainerManager.class);
|
||||
|
||||
private final ContainerBuilder containerBuilder;
|
||||
private final ContainerLifecycleManager lifecycleManager;
|
||||
private final ContainerLogStreamer logStreamer;
|
||||
private final ContainerDetector containerDetector;
|
||||
private final EmulatorConfig config;
|
||||
private final Map<String, RedshiftContainerHandle> containers = new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
public RedshiftContainerManager(ContainerBuilder containerBuilder,
|
||||
ContainerLifecycleManager lifecycleManager,
|
||||
ContainerLogStreamer logStreamer,
|
||||
ContainerDetector containerDetector,
|
||||
EmulatorConfig config) {
|
||||
this.containerBuilder = containerBuilder;
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
this.logStreamer = logStreamer;
|
||||
this.containerDetector = containerDetector;
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
public RedshiftContainerHandle start(String accountId, String clusterIdentifier, String masterUsername, String masterPassword) {
|
||||
String image = config.services().redshift().imageVersion();
|
||||
String containerName = containerName(accountId, clusterIdentifier);
|
||||
|
||||
List<String> envVars = List.of(
|
||||
"POSTGRES_USER=" + masterUsername,
|
||||
"POSTGRES_PASSWORD=" + masterPassword,
|
||||
"POSTGRES_DB=dev"
|
||||
);
|
||||
|
||||
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)
|
||||
.withName(containerName)
|
||||
.withEnv(envVars)
|
||||
.withDockerNetwork(config.services().redshift().dockerNetwork())
|
||||
.withLogRotation();
|
||||
|
||||
int enginePort = 5432; // Default postgres port
|
||||
if (!containerDetector.isRunningInContainer()) {
|
||||
specBuilder.withDynamicPort(enginePort);
|
||||
} else {
|
||||
specBuilder.withExposedPort(enginePort);
|
||||
}
|
||||
|
||||
ContainerSpec spec = specBuilder.build();
|
||||
ContainerInfo info = lifecycleManager.createAndStart(spec);
|
||||
EndpointInfo endpoint = info.getEndpoint(enginePort);
|
||||
|
||||
RedshiftContainerHandle handle = new RedshiftContainerHandle(
|
||||
info.containerId(), clusterIdentifier, endpoint.host(), endpoint.port());
|
||||
|
||||
try {
|
||||
Closeable stream = logStreamer.attach(info.containerId(), "/floci/redshift", clusterIdentifier, "us-east-1", "redshift:" + clusterIdentifier);
|
||||
handle.setLogStream(stream);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to stream logs for {0}", containerName);
|
||||
}
|
||||
|
||||
try {
|
||||
Thread.sleep(3000);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
|
||||
containers.put(containerKey(accountId, clusterIdentifier), handle);
|
||||
return handle;
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a cluster's container the same way {@link #start}, except that a container
|
||||
* already running under this cluster's name (e.g. Floci's own process restarted but
|
||||
* Docker did not) is adopted instead of destroyed and recreated. The container has no
|
||||
* persistent volume, so a blind recreate would silently discard the cluster's data;
|
||||
* adopting preserves it whenever the physical container survived. If no such container
|
||||
* exists (first start, or the container itself was removed), this falls back to
|
||||
* {@link #start} — in that case the previous data is unrecoverable, matching this
|
||||
* project's decision not to back Redshift containers with a Docker volume.
|
||||
*/
|
||||
public RedshiftContainerHandle adoptOrStart(String accountId, String clusterIdentifier, String masterUsername, String masterPassword) {
|
||||
String containerName = containerName(accountId, clusterIdentifier);
|
||||
var existing = lifecycleManager.findByName(containerName);
|
||||
if (existing.isEmpty()) {
|
||||
LOG.warnv("No surviving container for cluster {0}; starting a fresh empty one — the previous"
|
||||
+ " contents are not recoverable (no Docker volume backs Redshift containers)", clusterIdentifier);
|
||||
return start(accountId, clusterIdentifier, masterUsername, masterPassword);
|
||||
}
|
||||
|
||||
LOG.infov("Adopting existing container {0} for cluster {1} to avoid discarding its data",
|
||||
containerName, clusterIdentifier);
|
||||
int enginePort = 5432;
|
||||
ContainerInfo info = lifecycleManager.adopt(existing.get().getId(), List.of(enginePort));
|
||||
EndpointInfo endpoint = info.getEndpoint(enginePort);
|
||||
|
||||
RedshiftContainerHandle handle = new RedshiftContainerHandle(
|
||||
info.containerId(), clusterIdentifier, endpoint.host(), endpoint.port());
|
||||
try {
|
||||
Closeable stream = logStreamer.attach(info.containerId(), "/floci/redshift", clusterIdentifier, "us-east-1", "redshift:" + clusterIdentifier);
|
||||
handle.setLogStream(stream);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to stream logs for {0}", containerName);
|
||||
}
|
||||
|
||||
containers.put(containerKey(accountId, clusterIdentifier), handle);
|
||||
return handle;
|
||||
}
|
||||
|
||||
public void stop(String accountId, String clusterIdentifier) {
|
||||
containers.remove(containerKey(accountId, clusterIdentifier));
|
||||
lifecycleManager.removeIfExists(containerName(accountId, clusterIdentifier));
|
||||
}
|
||||
|
||||
public Optional<RedshiftContainerHandle> getContainer(String accountId, String clusterIdentifier) {
|
||||
return Optional.ofNullable(containers.get(containerKey(accountId, clusterIdentifier)));
|
||||
}
|
||||
|
||||
/** Distinguishes clusters that share an identifier across accounts, e.g. for the in-memory map key and Docker container name. */
|
||||
private static String containerKey(String accountId, String clusterIdentifier) {
|
||||
return accountId + "/" + clusterIdentifier;
|
||||
}
|
||||
|
||||
private static String containerName(String accountId, String clusterIdentifier) {
|
||||
return "floci-redshift-" + accountId + "-" + clusterIdentifier;
|
||||
}
|
||||
|
||||
public void takeSnapshot(String accountId, String clusterIdentifier, String username, String dbname, Path outputFile) {
|
||||
RedshiftContainerHandle handle = containers.get(containerKey(accountId, clusterIdentifier));
|
||||
if (handle == null) {
|
||||
throw new AwsException("ClusterNotFound", "Cluster container for " + clusterIdentifier + " not found", 404);
|
||||
}
|
||||
|
||||
String effectiveUser = (username != null && !username.isBlank()) ? username : "postgres";
|
||||
String effectiveDb = (dbname != null && !dbname.isBlank()) ? dbname : "dev";
|
||||
|
||||
String[] cmd = new String[]{"pg_dump", "-U", effectiveUser, effectiveDb, "-f", "/tmp/dump.sql"};
|
||||
try {
|
||||
ExecResult result = execInContainer(handle.getContainerId(), cmd, 30);
|
||||
if (result.exitCode() != 0) {
|
||||
LOG.warnv("pg_dump failed for cluster {0} (exit {1}): {2}", clusterIdentifier, result.exitCode(), result.stderr());
|
||||
throw new AwsException("InternalFailure", "Failed to create snapshot for cluster " + clusterIdentifier + ": " + result.stderr(), 500);
|
||||
}
|
||||
|
||||
try (InputStream in = lifecycleManager.getDockerClient().copyArchiveFromContainerCmd(handle.getContainerId(), "/tmp/dump.sql").exec();
|
||||
TarArchiveInputStream tar = new TarArchiveInputStream(in)) {
|
||||
tar.getNextTarEntry();
|
||||
Files.copy(tar, outputFile, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
} catch (AwsException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
LOG.errorv(e, "Error executing pg_dump for cluster {0}", clusterIdentifier);
|
||||
throw new AwsException("InternalFailure", "Failed to execute pg_dump for cluster " + clusterIdentifier + ": " + e.getMessage(), 500);
|
||||
}
|
||||
}
|
||||
|
||||
public void takeSnapshot(String accountId, String clusterIdentifier, String username, Path outputFile) {
|
||||
takeSnapshot(accountId, clusterIdentifier, username, "dev", outputFile);
|
||||
}
|
||||
|
||||
public void alterUserPassword(String accountId, String clusterIdentifier, String username, String newPassword) {
|
||||
RedshiftContainerHandle handle = containers.get(containerKey(accountId, clusterIdentifier));
|
||||
if (handle == null) {
|
||||
throw new AwsException("ClusterNotFound", "Cluster container for " + clusterIdentifier + " not found", 404);
|
||||
}
|
||||
String effectiveUser = (username != null && !username.isBlank()) ? username : "postgres";
|
||||
// Validate effectiveUser against safe SQL identifier pattern to prevent SQL injection.
|
||||
// psql -c sends the query string to Postgres, which allows multiple ;-separated statements,
|
||||
// so even argv-escaping doesn't protect against a username like "postgres; DROP TABLE ..."
|
||||
if (!effectiveUser.matches("^[A-Za-z_][A-Za-z0-9_]*$")) {
|
||||
throw new AwsException("InvalidParameterValue", "Username must be a valid SQL identifier", 400);
|
||||
}
|
||||
// AWS ModifyCluster rejects ', ", \, / and @ in MasterUserPassword and enforces an
|
||||
// 8-64 length plus at least one uppercase, one lowercase and one digit — we enforce
|
||||
// the same set for parity. The single-quote rejection is doubly load-bearing: the
|
||||
// password is spliced into a psql -c SQL literal here, so ' would also break that
|
||||
// literal — but it is AWS-correct regardless, so do not "fix" it away by escaping.
|
||||
if (newPassword != null) {
|
||||
for (char forbidden : new char[]{'\'', '"', '\\', '/', '@'}) {
|
||||
if (newPassword.indexOf(forbidden) >= 0) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"MasterUserPassword must not contain ', \", \\, / or @", 400);
|
||||
}
|
||||
}
|
||||
if (newPassword.length() < 8 || newPassword.length() > 64) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"MasterUserPassword must be between 8 and 64 characters in length", 400);
|
||||
}
|
||||
if (!newPassword.matches(".*[A-Z].*") || !newPassword.matches(".*[a-z].*")
|
||||
|| !newPassword.matches(".*[0-9].*")) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"MasterUserPassword must contain at least one uppercase letter, one lowercase letter and one number", 400);
|
||||
}
|
||||
}
|
||||
String sql = "ALTER USER " + effectiveUser + " PASSWORD '" + newPassword + "'";
|
||||
String[] cmd = new String[]{"psql", "-U", effectiveUser, "-d", "dev", "-c", sql};
|
||||
try {
|
||||
ExecResult result = execInContainer(handle.getContainerId(), cmd, 15);
|
||||
if (result.exitCode() != 0) {
|
||||
// Deliberately omit result.stderr() from the log and the exception: psql echoes
|
||||
// the failing ALTER USER statement, which contains the password literal.
|
||||
LOG.warnv("ALTER USER command failed for cluster {0} (exit {1})", clusterIdentifier, result.exitCode());
|
||||
throw new AwsException("InternalFailure", "Failed to change master password for cluster " + clusterIdentifier, 500);
|
||||
}
|
||||
} catch (AwsException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
LOG.errorv(e, "Error changing master password for cluster {0}", clusterIdentifier);
|
||||
throw new AwsException("InternalFailure", "Failed to change master password for cluster " + clusterIdentifier + ": " + e.getMessage(), 500);
|
||||
}
|
||||
}
|
||||
|
||||
public void createSnapshot(String accountId, Cluster cluster, Path outputFile) {
|
||||
if (cluster == null) {
|
||||
throw new AwsException("InvalidParameterValue", "Cluster cannot be null", 400);
|
||||
}
|
||||
takeSnapshot(accountId, cluster.getClusterIdentifier(), cluster.getMasterUsername(), "dev", outputFile);
|
||||
}
|
||||
|
||||
public void restoreSnapshot(String accountId, String clusterIdentifier, String username, String dbname, Path sqlDumpFile) {
|
||||
RedshiftContainerHandle handle = containers.get(containerKey(accountId, clusterIdentifier));
|
||||
if (handle == null) {
|
||||
throw new AwsException("ClusterNotFound", "Cluster container for " + clusterIdentifier + " not found", 404);
|
||||
}
|
||||
|
||||
if (sqlDumpFile == null || !Files.exists(sqlDumpFile)) {
|
||||
LOG.infov("Empty snapshot dump for cluster {0}, skipping restore", clusterIdentifier);
|
||||
return;
|
||||
}
|
||||
|
||||
String effectiveUser = (username != null && !username.isBlank()) ? username : "postgres";
|
||||
String effectiveDb = (dbname != null && !dbname.isBlank()) ? dbname : "dev";
|
||||
String fileName = sqlDumpFile.getFileName().toString();
|
||||
|
||||
try {
|
||||
lifecycleManager.getDockerClient().copyArchiveToContainerCmd(handle.getContainerId())
|
||||
.withHostResource(sqlDumpFile.toString())
|
||||
.withRemotePath("/tmp")
|
||||
.exec();
|
||||
|
||||
String[] cmd = new String[]{"psql", "-U", effectiveUser, "-d", effectiveDb, "-f", "/tmp/" + fileName};
|
||||
ExecResult result = execInContainer(handle.getContainerId(), cmd, 60);
|
||||
if (result.exitCode() != 0) {
|
||||
LOG.warnv("psql restore failed for cluster {0} (exit {1}): {2}", clusterIdentifier, result.exitCode(), result.stderr());
|
||||
throw new AwsException("InternalFailure", "Failed to restore snapshot for cluster " + clusterIdentifier + ": " + result.stderr(), 500);
|
||||
}
|
||||
} catch (AwsException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
LOG.errorv(e, "Error restoring snapshot for cluster {0}", clusterIdentifier);
|
||||
throw new AwsException("InternalFailure", "Failed to restore snapshot for cluster " + clusterIdentifier + ": " + e.getMessage(), 500);
|
||||
}
|
||||
}
|
||||
|
||||
public void restoreSnapshot(String accountId, String clusterIdentifier, String username, Path sqlDumpFile) {
|
||||
restoreSnapshot(accountId, clusterIdentifier, username, "dev", sqlDumpFile);
|
||||
}
|
||||
|
||||
public void restoreSnapshot(String accountId, Cluster cluster, Path sqlDumpFile) {
|
||||
if (cluster == null) {
|
||||
throw new AwsException("InvalidParameterValue", "Cluster cannot be null", 400);
|
||||
}
|
||||
restoreSnapshot(accountId, cluster.getClusterIdentifier(), cluster.getMasterUsername(), "dev", sqlDumpFile);
|
||||
}
|
||||
|
||||
private ExecResult execInContainer(String containerId, String[] cmd, int timeoutSeconds) throws Exception {
|
||||
ByteArrayOutputStream stdout = new ByteArrayOutputStream();
|
||||
ExecResult res = execInContainer(containerId, cmd, timeoutSeconds, stdout);
|
||||
return new ExecResult(res.exitCode(), stdout.toString(StandardCharsets.UTF_8), res.stderr());
|
||||
}
|
||||
|
||||
private ExecResult execInContainer(String containerId, String[] cmd, int timeoutSeconds, OutputStream out) throws Exception {
|
||||
String execId = lifecycleManager.getDockerClient().execCreateCmd(containerId)
|
||||
.withCmd(cmd)
|
||||
.withAttachStdout(true)
|
||||
.withAttachStderr(true)
|
||||
.exec()
|
||||
.getId();
|
||||
|
||||
CountDownLatch latch = new CountDownLatch(1);
|
||||
ByteArrayOutputStream stderr = new ByteArrayOutputStream();
|
||||
|
||||
Closeable callback = lifecycleManager.getDockerClient().execStartCmd(execId).exec(new ResultCallback.Adapter<Frame>() {
|
||||
@Override
|
||||
public void onNext(Frame frame) {
|
||||
byte[] payload = frame.getPayload();
|
||||
if (payload == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (frame.getStreamType() == StreamType.STDERR) {
|
||||
stderr.write(payload);
|
||||
} else {
|
||||
out.write(payload);
|
||||
}
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onComplete() {
|
||||
latch.countDown();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(Throwable t) {
|
||||
LOG.warnv(t, "Container exec {0} failed", execId);
|
||||
latch.countDown();
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
boolean completed = latch.await(timeoutSeconds, TimeUnit.SECONDS);
|
||||
if (!completed) {
|
||||
return new ExecResult(-1, "", "Timed out after " + timeoutSeconds + "s");
|
||||
}
|
||||
Long exitCode = lifecycleManager.getDockerClient().inspectExecCmd(execId).exec().getExitCodeLong();
|
||||
return new ExecResult(
|
||||
exitCode != null ? exitCode : -1,
|
||||
"",
|
||||
stderr.toString(StandardCharsets.UTF_8));
|
||||
} finally {
|
||||
try {
|
||||
callback.close();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] buildSingleFileTar(String filename, byte[] content, int mode) throws IOException {
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
try (TarArchiveOutputStream tar = new TarArchiveOutputStream(bos)) {
|
||||
tar.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
|
||||
TarArchiveEntry entry = new TarArchiveEntry(filename);
|
||||
entry.setSize(content.length);
|
||||
entry.setMode(mode);
|
||||
tar.putArchiveEntry(entry);
|
||||
tar.write(content);
|
||||
tar.closeArchiveEntry();
|
||||
}
|
||||
return bos.toByteArray();
|
||||
}
|
||||
|
||||
public record ExecResult(long exitCode, String stdout, String stderr) {}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package io.github.hectorvent.floci.services.redshift.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
public class Cluster {
|
||||
private String clusterIdentifier;
|
||||
private String nodeType;
|
||||
private String masterUsername;
|
||||
private String masterPassword;
|
||||
private String clusterStatus;
|
||||
private Endpoint endpoint;
|
||||
private String clusterSubnetGroupName;
|
||||
private String clusterParameterGroupName;
|
||||
private List<String> vpcSecurityGroupIds = new ArrayList<>();
|
||||
|
||||
public String getClusterIdentifier() { return clusterIdentifier; }
|
||||
public void setClusterIdentifier(String clusterIdentifier) { this.clusterIdentifier = clusterIdentifier; }
|
||||
public String getNodeType() { return nodeType; }
|
||||
public void setNodeType(String nodeType) { this.nodeType = nodeType; }
|
||||
public String getMasterUsername() { return masterUsername; }
|
||||
public void setMasterUsername(String masterUsername) { this.masterUsername = masterUsername; }
|
||||
public String getMasterPassword() { return masterPassword; }
|
||||
public void setMasterPassword(String masterPassword) { this.masterPassword = masterPassword; }
|
||||
public String getClusterStatus() { return clusterStatus; }
|
||||
public void setClusterStatus(String clusterStatus) { this.clusterStatus = clusterStatus; }
|
||||
public Endpoint getEndpoint() { return endpoint; }
|
||||
public void setEndpoint(Endpoint endpoint) { this.endpoint = endpoint; }
|
||||
public String getClusterSubnetGroupName() { return clusterSubnetGroupName; }
|
||||
public void setClusterSubnetGroupName(String clusterSubnetGroupName) { this.clusterSubnetGroupName = clusterSubnetGroupName; }
|
||||
public String getClusterParameterGroupName() { return clusterParameterGroupName; }
|
||||
public void setClusterParameterGroupName(String clusterParameterGroupName) { this.clusterParameterGroupName = clusterParameterGroupName; }
|
||||
public List<String> getVpcSecurityGroupIds() { return vpcSecurityGroupIds; }
|
||||
public void setVpcSecurityGroupIds(List<String> vpcSecurityGroupIds) { this.vpcSecurityGroupIds = vpcSecurityGroupIds; }
|
||||
|
||||
private Map<String, String> tags = new LinkedHashMap<>();
|
||||
|
||||
public Map<String, String> getTags() { return tags; }
|
||||
public void setTags(Map<String, String> tags) { this.tags = tags; }
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package io.github.hectorvent.floci.services.redshift.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
public class ClusterParameterGroup {
|
||||
private String parameterGroupName;
|
||||
private String parameterGroupFamily;
|
||||
private String description;
|
||||
|
||||
public ClusterParameterGroup() {}
|
||||
|
||||
public ClusterParameterGroup(String parameterGroupName, String parameterGroupFamily, String description) {
|
||||
this.parameterGroupName = parameterGroupName;
|
||||
this.parameterGroupFamily = parameterGroupFamily;
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public String getParameterGroupName() {
|
||||
return parameterGroupName;
|
||||
}
|
||||
|
||||
public void setParameterGroupName(String parameterGroupName) {
|
||||
this.parameterGroupName = parameterGroupName;
|
||||
}
|
||||
|
||||
public String getParameterGroupFamily() {
|
||||
return parameterGroupFamily;
|
||||
}
|
||||
|
||||
public void setParameterGroupFamily(String parameterGroupFamily) {
|
||||
this.parameterGroupFamily = parameterGroupFamily;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
private Map<String, String> tags = new LinkedHashMap<>();
|
||||
|
||||
public Map<String, String> getTags() { return tags; }
|
||||
public void setTags(Map<String, String> tags) { this.tags = tags; }
|
||||
|
||||
private List<Parameter> parameters = new ArrayList<>(List.of(
|
||||
new Parameter("max_cursor_result_set_size", "0", "Maximum cursor result set size", "integer"),
|
||||
new Parameter("wlm_json_configuration", "{}", "WLM configuration", "string")
|
||||
));
|
||||
|
||||
public List<Parameter> getParameters() { return parameters; }
|
||||
public void setParameters(List<Parameter> parameters) { this.parameters = parameters; }
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package io.github.hectorvent.floci.services.redshift.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
public class ClusterSubnetGroup {
|
||||
private String clusterSubnetGroupName;
|
||||
private String description;
|
||||
private String vpcId;
|
||||
private List<String> subnetIds = new ArrayList<>();
|
||||
private Map<String, String> tags = new LinkedHashMap<>();
|
||||
|
||||
public ClusterSubnetGroup() {}
|
||||
|
||||
public ClusterSubnetGroup(String clusterSubnetGroupName, String description, String vpcId, List<String> subnetIds) {
|
||||
this.clusterSubnetGroupName = clusterSubnetGroupName;
|
||||
this.description = description;
|
||||
this.vpcId = vpcId;
|
||||
this.subnetIds = subnetIds;
|
||||
}
|
||||
|
||||
public String getClusterSubnetGroupName() { return clusterSubnetGroupName; }
|
||||
public void setClusterSubnetGroupName(String clusterSubnetGroupName) { this.clusterSubnetGroupName = clusterSubnetGroupName; }
|
||||
public String getDescription() { return description; }
|
||||
public void setDescription(String description) { this.description = description; }
|
||||
public String getVpcId() { return vpcId; }
|
||||
public void setVpcId(String vpcId) { this.vpcId = vpcId; }
|
||||
public List<String> getSubnetIds() { return subnetIds; }
|
||||
public void setSubnetIds(List<String> subnetIds) { this.subnetIds = subnetIds; }
|
||||
public Map<String, String> getTags() { return tags; }
|
||||
public void setTags(Map<String, String> tags) { this.tags = tags; }
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package io.github.hectorvent.floci.services.redshift.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
public class Endpoint {
|
||||
private String address;
|
||||
private int port;
|
||||
|
||||
public Endpoint() {}
|
||||
|
||||
public Endpoint(String address, int port) {
|
||||
this.address = address;
|
||||
this.port = port;
|
||||
}
|
||||
|
||||
public String getAddress() { return address; }
|
||||
public void setAddress(String address) { this.address = address; }
|
||||
public int getPort() { return port; }
|
||||
public void setPort(int port) { this.port = port; }
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package io.github.hectorvent.floci.services.redshift.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
public class Parameter {
|
||||
private String parameterName;
|
||||
private String parameterValue;
|
||||
private String description;
|
||||
private String dataType;
|
||||
|
||||
public Parameter() {}
|
||||
|
||||
public Parameter(String parameterName, String parameterValue) {
|
||||
this.parameterName = parameterName;
|
||||
this.parameterValue = parameterValue;
|
||||
}
|
||||
|
||||
public Parameter(String parameterName, String parameterValue, String description, String dataType) {
|
||||
this.parameterName = parameterName;
|
||||
this.parameterValue = parameterValue;
|
||||
this.description = description;
|
||||
this.dataType = dataType;
|
||||
}
|
||||
|
||||
public String getParameterName() {
|
||||
return parameterName;
|
||||
}
|
||||
|
||||
public void setParameterName(String parameterName) {
|
||||
this.parameterName = parameterName;
|
||||
}
|
||||
|
||||
public String getParameterValue() {
|
||||
return parameterValue;
|
||||
}
|
||||
|
||||
public void setParameterValue(String parameterValue) {
|
||||
this.parameterValue = parameterValue;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public String getDataType() {
|
||||
return dataType;
|
||||
}
|
||||
|
||||
public void setDataType(String dataType) {
|
||||
this.dataType = dataType;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package io.github.hectorvent.floci.services.redshift.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
public class Snapshot {
|
||||
private String snapshotIdentifier;
|
||||
private String clusterIdentifier;
|
||||
private String status;
|
||||
private int port;
|
||||
private String masterUsername;
|
||||
private String masterPassword;
|
||||
private String sqlDump;
|
||||
|
||||
public Snapshot() {}
|
||||
|
||||
public Snapshot(String snapshotIdentifier, String clusterIdentifier, String status, int port, String masterUsername) {
|
||||
this.snapshotIdentifier = snapshotIdentifier;
|
||||
this.clusterIdentifier = clusterIdentifier;
|
||||
this.status = status;
|
||||
this.port = port;
|
||||
this.masterUsername = masterUsername;
|
||||
}
|
||||
|
||||
public Snapshot(String snapshotIdentifier, String clusterIdentifier, String status, int port, String masterUsername, String sqlDump) {
|
||||
this.snapshotIdentifier = snapshotIdentifier;
|
||||
this.clusterIdentifier = clusterIdentifier;
|
||||
this.status = status;
|
||||
this.port = port;
|
||||
this.masterUsername = masterUsername;
|
||||
this.sqlDump = sqlDump;
|
||||
}
|
||||
|
||||
public String getSnapshotIdentifier() {
|
||||
return snapshotIdentifier;
|
||||
}
|
||||
|
||||
public void setSnapshotIdentifier(String snapshotIdentifier) {
|
||||
this.snapshotIdentifier = snapshotIdentifier;
|
||||
}
|
||||
|
||||
public String getClusterIdentifier() {
|
||||
return clusterIdentifier;
|
||||
}
|
||||
|
||||
public void setClusterIdentifier(String clusterIdentifier) {
|
||||
this.clusterIdentifier = clusterIdentifier;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public int getPort() {
|
||||
return port;
|
||||
}
|
||||
|
||||
public void setPort(int port) {
|
||||
this.port = port;
|
||||
}
|
||||
|
||||
public String getMasterUsername() {
|
||||
return masterUsername;
|
||||
}
|
||||
|
||||
public void setMasterUsername(String masterUsername) {
|
||||
this.masterUsername = masterUsername;
|
||||
}
|
||||
|
||||
public String getMasterPassword() {
|
||||
return masterPassword;
|
||||
}
|
||||
|
||||
public void setMasterPassword(String masterPassword) {
|
||||
this.masterPassword = masterPassword;
|
||||
}
|
||||
|
||||
public String getSqlDump() {
|
||||
return sqlDump;
|
||||
}
|
||||
|
||||
public void setSqlDump(String sqlDump) {
|
||||
this.sqlDump = sqlDump;
|
||||
}
|
||||
|
||||
private Map<String, String> tags = new LinkedHashMap<>();
|
||||
|
||||
public Map<String, String> getTags() { return tags; }
|
||||
public void setTags(Map<String, String> tags) { this.tags = tags; }
|
||||
}
|
||||
@@ -312,6 +312,10 @@ floci:
|
||||
proxy-base-port: 6400
|
||||
proxy-max-port: 6419
|
||||
default-image: "valkey/valkey:8"
|
||||
redshift:
|
||||
enabled: true
|
||||
default-port: 5439
|
||||
image-version: postgres:15-alpine
|
||||
rds:
|
||||
enabled: true
|
||||
mock: false # FLOCI_SERVICES_RDS_MOCK — true = metadata only, no Docker (useful for CI)
|
||||
|
||||
+8
@@ -12,6 +12,14 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class AccountAwareStorageBackendTest {
|
||||
|
||||
@Test
|
||||
void accountIdReturnsDefaultOutsideRequestScope() {
|
||||
AccountAwareStorageBackend<String> storage =
|
||||
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, "111111111111");
|
||||
|
||||
assertEquals("111111111111", storage.accountId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void guardedLegacyLookupMigratesMatchingRawValue() {
|
||||
InMemoryStorage<String, String> raw = new InMemoryStorage<>();
|
||||
|
||||
+371
@@ -0,0 +1,371 @@
|
||||
package io.github.hectorvent.floci.services.redshift;
|
||||
|
||||
import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerHandle;
|
||||
import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerManager;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@QuarkusTest
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
public class RedshiftOperationsTest {
|
||||
|
||||
private static final String AUTH_HEADER =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260822/us-east-1/redshift/aws4_request";
|
||||
|
||||
@InjectMock
|
||||
RedshiftContainerManager containerManager;
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void testParameterGroupLifecycle() {
|
||||
// 1. CreateClusterParameterGroup
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.formParam("Action", "CreateClusterParameterGroup")
|
||||
.formParam("ParameterGroupName", "pg-test-1")
|
||||
.formParam("ParameterGroupFamily", "redshift-1.0")
|
||||
.formParam("Description", "Test Redshift Parameter Group")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.contentType("application/xml")
|
||||
.body(containsString("<ParameterGroupName>pg-test-1</ParameterGroupName>"))
|
||||
.body(containsString("<ParameterGroupFamily>redshift-1.0</ParameterGroupFamily>"));
|
||||
|
||||
// 2. DescribeClusterParameterGroups
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.formParam("Action", "DescribeClusterParameterGroups")
|
||||
.formParam("ParameterGroupName", "pg-test-1")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.contentType("application/xml")
|
||||
.body(containsString("<ParameterGroupName>pg-test-1</ParameterGroupName>"));
|
||||
|
||||
// 2b. ModifyClusterParameterGroup
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.formParam("Action", "ModifyClusterParameterGroup")
|
||||
.formParam("ParameterGroupName", "pg-test-1")
|
||||
.formParam("Parameters.member.1.ParameterName", "statement_timeout")
|
||||
.formParam("Parameters.member.1.ParameterValue", "5000")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.contentType("application/xml")
|
||||
.body(containsString("<ParameterGroupName>pg-test-1</ParameterGroupName>"));
|
||||
|
||||
// 3. DescribeClusterParameters
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.formParam("Action", "DescribeClusterParameters")
|
||||
.formParam("ParameterGroupName", "pg-test-1")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.contentType("application/xml")
|
||||
.body(containsString("<DescribeClusterParametersResponse>"))
|
||||
.body(containsString("<ParameterName>statement_timeout</ParameterName>"))
|
||||
.body(containsString("<ParameterValue>5000</ParameterValue>"));
|
||||
|
||||
// 4. DeleteClusterParameterGroup
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.formParam("Action", "DeleteClusterParameterGroup")
|
||||
.formParam("ParameterGroupName", "pg-test-1")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.contentType("application/xml")
|
||||
.body(containsString("<DeleteClusterParameterGroupResponse>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void testClusterAndSnapshotLifecycle() {
|
||||
when(containerManager.start(any(), eq("cluster-src"), any(), any()))
|
||||
.thenReturn(new RedshiftContainerHandle("c1", "cluster-src", "localhost", 5439));
|
||||
org.mockito.Mockito.doAnswer(invocation -> {
|
||||
java.nio.file.Path p = invocation.getArgument(3);
|
||||
java.nio.file.Files.writeString(p, "-- dump sql table test_data;");
|
||||
return null;
|
||||
}).when(containerManager).takeSnapshot(any(), eq("cluster-src"), eq("admin"), any(java.nio.file.Path.class));
|
||||
when(containerManager.start(any(), eq("cluster-restored"), any(), any()))
|
||||
.thenReturn(new RedshiftContainerHandle("c2", "cluster-restored", "localhost", 5440));
|
||||
|
||||
// 1. CreateCluster
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.formParam("Action", "CreateCluster")
|
||||
.formParam("ClusterIdentifier", "cluster-src")
|
||||
.formParam("NodeType", "dc2.large")
|
||||
.formParam("MasterUsername", "admin")
|
||||
.formParam("MasterUserPassword", "password123")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.contentType("application/xml")
|
||||
.body(containsString("<ClusterIdentifier>cluster-src</ClusterIdentifier>"))
|
||||
.body(containsString("<ClusterStatus>available</ClusterStatus>"));
|
||||
|
||||
// 1b. RebootCluster — must preserve data (no Docker volume backs this container)
|
||||
when(containerManager.getContainer(any(), eq("cluster-src")))
|
||||
.thenReturn(java.util.Optional.of(new RedshiftContainerHandle("c1", "cluster-src", "localhost", 5439)));
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.formParam("Action", "RebootCluster")
|
||||
.formParam("ClusterIdentifier", "cluster-src")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.contentType("application/xml")
|
||||
.body(containsString("<ClusterIdentifier>cluster-src</ClusterIdentifier>"))
|
||||
.body(containsString("<ClusterStatus>available</ClusterStatus>"));
|
||||
|
||||
// 1c. ModifyCluster
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.formParam("Action", "ModifyCluster")
|
||||
.formParam("ClusterIdentifier", "cluster-src")
|
||||
.formParam("NodeType", "ra3.xlplus")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<NodeType>ra3.xlplus</NodeType>"));
|
||||
|
||||
// 2. CreateClusterSnapshot
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.formParam("Action", "CreateClusterSnapshot")
|
||||
.formParam("SnapshotIdentifier", "snap-test-1")
|
||||
.formParam("ClusterIdentifier", "cluster-src")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.contentType("application/xml")
|
||||
.body(containsString("<SnapshotIdentifier>snap-test-1</SnapshotIdentifier>"))
|
||||
.body(containsString("<ClusterIdentifier>cluster-src</ClusterIdentifier>"));
|
||||
|
||||
// 3. DescribeClusterSnapshots
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.formParam("Action", "DescribeClusterSnapshots")
|
||||
.formParam("SnapshotIdentifier", "snap-test-1")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.contentType("application/xml")
|
||||
.body(containsString("<SnapshotIdentifier>snap-test-1</SnapshotIdentifier>"));
|
||||
|
||||
// 4. DeleteCluster
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.formParam("Action", "DeleteCluster")
|
||||
.formParam("ClusterIdentifier", "cluster-src")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.contentType("application/xml")
|
||||
.body(containsString("<ClusterIdentifier>cluster-src</ClusterIdentifier>"))
|
||||
.body(containsString("<ClusterStatus>deleting</ClusterStatus>"));
|
||||
|
||||
// 5. RestoreFromClusterSnapshot
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.formParam("Action", "RestoreFromClusterSnapshot")
|
||||
.formParam("ClusterIdentifier", "cluster-restored")
|
||||
.formParam("SnapshotIdentifier", "snap-test-1")
|
||||
.formParam("NodeType", "dc2.large")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.contentType("application/xml")
|
||||
.body(containsString("<ClusterIdentifier>cluster-restored</ClusterIdentifier>"))
|
||||
.body(containsString("<ClusterStatus>available</ClusterStatus>"))
|
||||
.body(containsString("<Port>5440</Port>"));
|
||||
|
||||
// 6. DeleteClusterSnapshot
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.formParam("Action", "DeleteClusterSnapshot")
|
||||
.formParam("SnapshotIdentifier", "snap-test-1")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.contentType("application/xml")
|
||||
.body(containsString("<SnapshotIdentifier>snap-test-1</SnapshotIdentifier>"))
|
||||
.body(containsString("<Status>deleted</Status>"));
|
||||
|
||||
// 7. Delete restored cluster
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.formParam("Action", "DeleteCluster")
|
||||
.formParam("ClusterIdentifier", "cluster-restored")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.contentType("application/xml")
|
||||
.body(containsString("<ClusterIdentifier>cluster-restored</ClusterIdentifier>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void testClusterSubnetGroupLifecycle() {
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.formParam("Action", "CreateClusterSubnetGroup")
|
||||
.formParam("ClusterSubnetGroupName", "subnet-group-1")
|
||||
.formParam("Description", "Test subnet group")
|
||||
.formParam("SubnetIds.member.1", "subnet-aaa")
|
||||
.formParam("SubnetIds.member.2", "subnet-bbb")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.contentType("application/xml")
|
||||
.body(containsString("<ClusterSubnetGroupName>subnet-group-1</ClusterSubnetGroupName>"))
|
||||
.body(containsString("<SubnetIdentifier>subnet-aaa</SubnetIdentifier>"));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.formParam("Action", "DescribeClusterSubnetGroups")
|
||||
.formParam("ClusterSubnetGroupName", "subnet-group-1")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<ClusterSubnetGroupName>subnet-group-1</ClusterSubnetGroupName>"));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.formParam("Action", "ModifyClusterSubnetGroup")
|
||||
.formParam("ClusterSubnetGroupName", "subnet-group-1")
|
||||
.formParam("Description", "Updated")
|
||||
.formParam("SubnetIds.member.1", "subnet-ccc")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<SubnetIdentifier>subnet-ccc</SubnetIdentifier>"));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.formParam("Action", "DeleteClusterSubnetGroup")
|
||||
.formParam("ClusterSubnetGroupName", "subnet-group-1")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void testTagLifecycle() {
|
||||
when(containerManager.start(any(), eq("cluster-tags"), any(), any()))
|
||||
.thenReturn(new RedshiftContainerHandle("c3", "cluster-tags", "localhost", 5441));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.formParam("Action", "CreateCluster")
|
||||
.formParam("ClusterIdentifier", "cluster-tags")
|
||||
.formParam("NodeType", "dc2.large")
|
||||
.formParam("MasterUsername", "admin")
|
||||
.formParam("MasterUserPassword", "password123")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
String clusterArn = "arn:aws:redshift:us-east-1:000000000000:cluster:cluster-tags";
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.formParam("Action", "CreateTags")
|
||||
.formParam("ResourceName", clusterArn)
|
||||
.formParam("Tags.member.1.Key", "env")
|
||||
.formParam("Tags.member.1.Value", "test")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.contentType("application/xml");
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.formParam("Action", "DescribeTags")
|
||||
.formParam("ResourceName", clusterArn)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<Key>env</Key>"))
|
||||
.body(containsString("<Value>test</Value>"));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.formParam("Action", "DeleteTags")
|
||||
.formParam("ResourceName", clusterArn)
|
||||
.formParam("TagKeys.member.1", "env")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.formParam("Action", "DeleteCluster")
|
||||
.formParam("ClusterIdentifier", "cluster-tags")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
}
|
||||
+329
@@ -0,0 +1,329 @@
|
||||
package io.github.hectorvent.floci.services.redshift;
|
||||
|
||||
import io.github.hectorvent.floci.services.redshift.model.Cluster;
|
||||
import io.github.hectorvent.floci.services.redshift.model.ClusterParameterGroup;
|
||||
import io.github.hectorvent.floci.services.redshift.model.ClusterSubnetGroup;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Endpoint;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Parameter;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Snapshot;
|
||||
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.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class RedshiftQueryHandlerTest {
|
||||
|
||||
private RedshiftQueryHandler handler;
|
||||
private RedshiftService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = mock(RedshiftService.class);
|
||||
handler = new RedshiftQueryHandler(service);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateClusterAction() {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("ClusterIdentifier", "test-cluster");
|
||||
params.putSingle("NodeType", "dc2.large");
|
||||
params.putSingle("MasterUsername", "admin");
|
||||
params.putSingle("MasterUserPassword", "password123");
|
||||
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("test-cluster");
|
||||
cluster.setClusterStatus("available");
|
||||
when(service.createCluster(any(), any(), any(), any(), any(), any())).thenReturn(cluster);
|
||||
|
||||
Response response = handler.handle("CreateCluster", params);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertNotNull(response.getEntity());
|
||||
String xml = (String) response.getEntity();
|
||||
assertTrue(xml.contains("<ClusterIdentifier>test-cluster</ClusterIdentifier>"));
|
||||
assertTrue(xml.contains("<ClusterStatus>available</ClusterStatus>"));
|
||||
assertTrue(xml.contains("<RequestId>test-req-id</RequestId>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDescribeClusters() {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("ClusterIdentifier", "test-cluster");
|
||||
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("test-cluster");
|
||||
cluster.setClusterStatus("available");
|
||||
when(service.describeClusters(any())).thenReturn(List.of(cluster));
|
||||
|
||||
Response response = handler.handle("DescribeClusters", params);
|
||||
assertEquals(200, response.getStatus());
|
||||
String xml = (String) response.getEntity();
|
||||
assertTrue(xml.contains("<ClusterIdentifier>test-cluster</ClusterIdentifier>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteCluster() {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("ClusterIdentifier", "test-cluster");
|
||||
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("test-cluster");
|
||||
cluster.setClusterStatus("deleting");
|
||||
when(service.deleteCluster(any())).thenReturn(cluster);
|
||||
|
||||
Response response = handler.handle("DeleteCluster", params);
|
||||
assertEquals(200, response.getStatus());
|
||||
String xml = (String) response.getEntity();
|
||||
assertTrue(xml.contains("<ClusterIdentifier>test-cluster</ClusterIdentifier>"));
|
||||
assertTrue(xml.contains("<ClusterStatus>deleting</ClusterStatus>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateClusterSnapshot() {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("SnapshotIdentifier", "test-snapshot");
|
||||
params.putSingle("ClusterIdentifier", "test-cluster");
|
||||
|
||||
Snapshot snapshot = new Snapshot("test-snapshot", "test-cluster", "available", 5439, "admin");
|
||||
when(service.createSnapshot("test-snapshot", "test-cluster")).thenReturn(snapshot);
|
||||
|
||||
Response response = handler.handle("CreateClusterSnapshot", params);
|
||||
assertEquals(200, response.getStatus());
|
||||
String xml = (String) response.getEntity();
|
||||
assertTrue(xml.contains("<SnapshotIdentifier>test-snapshot</SnapshotIdentifier>"));
|
||||
assertTrue(xml.contains("<ClusterIdentifier>test-cluster</ClusterIdentifier>"));
|
||||
assertTrue(xml.contains("<Status>available</Status>"));
|
||||
assertTrue(xml.contains("<Port>5439</Port>"));
|
||||
assertTrue(xml.contains("<MasterUsername>admin</MasterUsername>"));
|
||||
assertTrue(xml.contains("<RequestId>test-req-id</RequestId>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDescribeClusterSnapshots() {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("SnapshotIdentifier", "test-snapshot");
|
||||
params.putSingle("ClusterIdentifier", "test-cluster");
|
||||
|
||||
Snapshot snapshot = new Snapshot("test-snapshot", "test-cluster", "available", 5439, "admin");
|
||||
when(service.describeSnapshots("test-snapshot", "test-cluster")).thenReturn(List.of(snapshot));
|
||||
|
||||
Response response = handler.handle("DescribeClusterSnapshots", params);
|
||||
assertEquals(200, response.getStatus());
|
||||
String xml = (String) response.getEntity();
|
||||
assertTrue(xml.contains("<Snapshots>"));
|
||||
assertTrue(xml.contains("<SnapshotIdentifier>test-snapshot</SnapshotIdentifier>"));
|
||||
assertTrue(xml.contains("</Snapshots>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteClusterSnapshot() {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("SnapshotIdentifier", "test-snapshot");
|
||||
|
||||
Snapshot snapshot = new Snapshot("test-snapshot", "test-cluster", "deleted", 5439, "admin");
|
||||
when(service.deleteSnapshot("test-snapshot")).thenReturn(snapshot);
|
||||
|
||||
Response response = handler.handle("DeleteClusterSnapshot", params);
|
||||
assertEquals(200, response.getStatus());
|
||||
String xml = (String) response.getEntity();
|
||||
assertTrue(xml.contains("<SnapshotIdentifier>test-snapshot</SnapshotIdentifier>"));
|
||||
assertTrue(xml.contains("<Status>deleted</Status>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRestoreFromClusterSnapshot() {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("ClusterIdentifier", "restored-cluster");
|
||||
params.putSingle("SnapshotIdentifier", "test-snapshot");
|
||||
params.putSingle("NodeType", "dc2.large");
|
||||
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("restored-cluster");
|
||||
cluster.setNodeType("dc2.large");
|
||||
cluster.setMasterUsername("admin");
|
||||
cluster.setClusterStatus("available");
|
||||
cluster.setEndpoint(new Endpoint("localhost", 5439));
|
||||
when(service.restoreFromClusterSnapshot("restored-cluster", "test-snapshot", "dc2.large")).thenReturn(cluster);
|
||||
|
||||
Response response = handler.handle("RestoreFromClusterSnapshot", params);
|
||||
assertEquals(200, response.getStatus());
|
||||
String xml = (String) response.getEntity();
|
||||
assertTrue(xml.contains("<ClusterIdentifier>restored-cluster</ClusterIdentifier>"));
|
||||
assertTrue(xml.contains("<ClusterStatus>available</ClusterStatus>"));
|
||||
assertTrue(xml.contains("<Address>localhost</Address>"));
|
||||
assertTrue(xml.contains("<Port>5439</Port>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateClusterParameterGroup() {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("ParameterGroupName", "test-pg");
|
||||
params.putSingle("ParameterGroupFamily", "redshift-1.0");
|
||||
params.putSingle("Description", "custom redshift param group");
|
||||
|
||||
ClusterParameterGroup group = new ClusterParameterGroup("test-pg", "redshift-1.0", "custom redshift param group");
|
||||
when(service.createClusterParameterGroup("test-pg", "redshift-1.0", "custom redshift param group")).thenReturn(group);
|
||||
|
||||
Response response = handler.handle("CreateClusterParameterGroup", params);
|
||||
assertEquals(200, response.getStatus());
|
||||
String xml = (String) response.getEntity();
|
||||
assertTrue(xml.contains("<ParameterGroupName>test-pg</ParameterGroupName>"));
|
||||
assertTrue(xml.contains("<ParameterGroupFamily>redshift-1.0</ParameterGroupFamily>"));
|
||||
assertTrue(xml.contains("<Description>custom redshift param group</Description>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDescribeClusterParameterGroups() {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("ParameterGroupName", "test-pg");
|
||||
|
||||
ClusterParameterGroup group = new ClusterParameterGroup("test-pg", "redshift-1.0", "custom redshift param group");
|
||||
when(service.describeClusterParameterGroups("test-pg")).thenReturn(List.of(group));
|
||||
|
||||
Response response = handler.handle("DescribeClusterParameterGroups", params);
|
||||
assertEquals(200, response.getStatus());
|
||||
String xml = (String) response.getEntity();
|
||||
assertTrue(xml.contains("<ParameterGroups>"));
|
||||
assertTrue(xml.contains("<ParameterGroupName>test-pg</ParameterGroupName>"));
|
||||
assertTrue(xml.contains("</ParameterGroups>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDescribeClusterParameters() {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("ParameterGroupName", "test-pg");
|
||||
|
||||
ClusterParameterGroup group = new ClusterParameterGroup("test-pg", "redshift-1.0", "custom redshift param group");
|
||||
when(service.describeClusterParameterGroups("test-pg")).thenReturn(List.of(group));
|
||||
|
||||
Response response = handler.handle("DescribeClusterParameters", params);
|
||||
assertEquals(200, response.getStatus());
|
||||
String xml = (String) response.getEntity();
|
||||
assertTrue(xml.contains("<Parameters>"));
|
||||
assertTrue(xml.contains("</Parameters>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteClusterParameterGroup() {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("ParameterGroupName", "test-pg");
|
||||
|
||||
ClusterParameterGroup group = new ClusterParameterGroup("test-pg", "redshift-1.0", "custom redshift param group");
|
||||
when(service.deleteClusterParameterGroup("test-pg")).thenReturn(group);
|
||||
|
||||
Response response = handler.handle("DeleteClusterParameterGroup", params);
|
||||
assertEquals(200, response.getStatus());
|
||||
String xml = (String) response.getEntity();
|
||||
assertTrue(xml.contains("<DeleteClusterParameterGroupResponse>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateTagsAcceptsNamedMemberForm() {
|
||||
// Real Redshift SDK sends "Tags.Tag.N.Key/.Value", không phải "Tags.member.N...".
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("ResourceName", "arn:aws:redshift:us-east-1:000000000000:cluster:test-cluster");
|
||||
params.putSingle("Tags.Tag.1.Key", "env");
|
||||
params.putSingle("Tags.Tag.1.Value", "prod");
|
||||
|
||||
Response response = handler.handle("CreateTags", params);
|
||||
assertEquals(200, response.getStatus());
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<Map<String, String>> captor = ArgumentCaptor.forClass(Map.class);
|
||||
verify(service).createTags(eq("arn:aws:redshift:us-east-1:000000000000:cluster:test-cluster"), captor.capture());
|
||||
assertEquals(Map.of("env", "prod"), captor.getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateClusterSubnetGroupAcceptsNamedMemberForm() {
|
||||
// Real Redshift SDK sends "SubnetIds.SubnetIdentifier.N", không phải "SubnetIds.member.N".
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("ClusterSubnetGroupName", "test-sng");
|
||||
params.putSingle("Description", "desc");
|
||||
params.putSingle("SubnetIds.SubnetIdentifier.1", "subnet-aaa");
|
||||
params.putSingle("SubnetIds.SubnetIdentifier.2", "subnet-bbb");
|
||||
|
||||
ClusterSubnetGroup group = new ClusterSubnetGroup("test-sng", "desc", null, List.of("subnet-aaa", "subnet-bbb"));
|
||||
when(service.createClusterSubnetGroup(any(), any(), any(), any())).thenReturn(group);
|
||||
|
||||
Response response = handler.handle("CreateClusterSubnetGroup", params);
|
||||
assertEquals(200, response.getStatus());
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<String>> captor = ArgumentCaptor.forClass(List.class);
|
||||
verify(service).createClusterSubnetGroup(eq("test-sng"), eq("desc"), any(), captor.capture());
|
||||
assertEquals(List.of("subnet-aaa", "subnet-bbb"), captor.getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testModifyClusterParameterGroupAcceptsNamedMemberForm() {
|
||||
// Real Redshift SDK sends "Parameters.Parameter.N.ParameterName/.ParameterValue".
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("ParameterGroupName", "test-pg");
|
||||
params.putSingle("Parameters.Parameter.1.ParameterName", "statement_timeout");
|
||||
params.putSingle("Parameters.Parameter.1.ParameterValue", "5000");
|
||||
|
||||
Response response = handler.handle("ModifyClusterParameterGroup", params);
|
||||
assertEquals(200, response.getStatus());
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<Parameter>> captor = ArgumentCaptor.forClass(List.class);
|
||||
verify(service).modifyClusterParameterGroup(eq("test-pg"), captor.capture());
|
||||
assertEquals(1, captor.getValue().size());
|
||||
assertEquals("statement_timeout", captor.getValue().get(0).getParameterName());
|
||||
assertEquals("5000", captor.getValue().get(0).getParameterValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateClusterSubnetGroupRequiresName() {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("Description", "desc");
|
||||
|
||||
io.github.hectorvent.floci.core.common.AwsException ex = org.junit.jupiter.api.Assertions.assertThrows(
|
||||
io.github.hectorvent.floci.core.common.AwsException.class,
|
||||
() -> handler.handle("CreateClusterSubnetGroup", params));
|
||||
assertEquals("InvalidParameterValue", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testModifyClusterRequiresClusterIdentifier() {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("NodeType", "dc2.large");
|
||||
|
||||
io.github.hectorvent.floci.core.common.AwsException ex = org.junit.jupiter.api.Assertions.assertThrows(
|
||||
io.github.hectorvent.floci.core.common.AwsException.class,
|
||||
() -> handler.handle("ModifyCluster", params));
|
||||
assertEquals("InvalidParameterValue", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testBuildClusterXmlIncludesParameterGroupAndTags() {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("ClusterIdentifier", "test-cluster");
|
||||
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("test-cluster");
|
||||
cluster.setClusterStatus("available");
|
||||
cluster.setClusterParameterGroupName("test-pg");
|
||||
cluster.setTags(Map.of("env", "prod"));
|
||||
when(service.describeClusters(any())).thenReturn(List.of(cluster));
|
||||
|
||||
Response response = handler.handle("DescribeClusters", params);
|
||||
String xml = (String) response.getEntity();
|
||||
assertTrue(xml.contains("<ClusterParameterGroups>"));
|
||||
assertTrue(xml.contains("<ParameterGroupName>test-pg</ParameterGroupName>"));
|
||||
assertTrue(xml.contains("<ParameterApplyStatus>in-sync</ParameterApplyStatus>"));
|
||||
assertTrue(xml.contains("<Tags>"));
|
||||
assertTrue(xml.contains("<Key>env</Key>"));
|
||||
assertTrue(xml.contains("<Value>prod</Value>"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,748 @@
|
||||
package io.github.hectorvent.floci.services.redshift;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerHandle;
|
||||
import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerManager;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Cluster;
|
||||
import io.github.hectorvent.floci.services.redshift.model.ClusterParameterGroup;
|
||||
import io.github.hectorvent.floci.services.redshift.model.ClusterSubnetGroup;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Endpoint;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Parameter;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Snapshot;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class RedshiftServiceTest {
|
||||
|
||||
private StorageFactory sf;
|
||||
private AccountAwareStorageBackend<Cluster> clusterBackend;
|
||||
private AccountAwareStorageBackend<Snapshot> snapshotBackend;
|
||||
private AccountAwareStorageBackend<String> snapshotDumpBackend;
|
||||
private AccountAwareStorageBackend<ClusterParameterGroup> parameterGroupBackend;
|
||||
private AccountAwareStorageBackend<ClusterSubnetGroup> subnetGroupBackend;
|
||||
private RedshiftContainerManager cm;
|
||||
private io.github.hectorvent.floci.core.common.RegionResolver regionResolver;
|
||||
private RedshiftService service;
|
||||
|
||||
@BeforeEach
|
||||
@SuppressWarnings("unchecked")
|
||||
void setUp() {
|
||||
sf = mock(StorageFactory.class);
|
||||
clusterBackend = mock(AccountAwareStorageBackend.class);
|
||||
snapshotBackend = mock(AccountAwareStorageBackend.class);
|
||||
snapshotDumpBackend = mock(AccountAwareStorageBackend.class);
|
||||
parameterGroupBackend = mock(AccountAwareStorageBackend.class);
|
||||
subnetGroupBackend = mock(AccountAwareStorageBackend.class);
|
||||
cm = mock(RedshiftContainerManager.class);
|
||||
|
||||
io.github.hectorvent.floci.config.EmulatorConfig config = mock(io.github.hectorvent.floci.config.EmulatorConfig.class);
|
||||
io.github.hectorvent.floci.config.EmulatorConfig.StorageConfig storageConfig = mock(io.github.hectorvent.floci.config.EmulatorConfig.StorageConfig.class);
|
||||
when(config.storage()).thenReturn(storageConfig);
|
||||
when(storageConfig.persistentPath()).thenReturn("target/test-data");
|
||||
|
||||
when(sf.<Cluster>create(eq("redshift"), eq("redshift-clusters.json"), any())).thenReturn(clusterBackend);
|
||||
when(sf.<Snapshot>create(eq("redshift"), eq("redshift-snapshots.json"), any())).thenReturn(snapshotBackend);
|
||||
when(sf.<ClusterParameterGroup>create(eq("redshift"), eq("redshift-parameter-groups.json"), any())).thenReturn(parameterGroupBackend);
|
||||
when(sf.<ClusterSubnetGroup>create(eq("redshift"), eq("redshift-subnet-groups.json"), any())).thenReturn(subnetGroupBackend);
|
||||
when(clusterBackend.accountId()).thenReturn("111111111111");
|
||||
|
||||
regionResolver = new io.github.hectorvent.floci.core.common.RegionResolver("us-east-1", "111111111111");
|
||||
|
||||
service = new RedshiftService(sf, cm, config, regionResolver);
|
||||
}
|
||||
|
||||
/** Absolute dump path as {@code createSnapshot} now stores it: under {@code <persistentPath>/redshift-dumps/<accountId>}. */
|
||||
private static String dumpPath(String snapshotId) {
|
||||
return java.nio.file.Paths.get("target/test-data", "redshift-dumps", "111111111111", snapshotId + ".sql")
|
||||
.toAbsolutePath().normalize().toString();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testOnStartRecreatesContainersAcrossAccounts() {
|
||||
Cluster clusterA = new Cluster();
|
||||
clusterA.setClusterIdentifier("cluster-a");
|
||||
clusterA.setMasterUsername("admin");
|
||||
clusterA.setMasterPassword("pw-a");
|
||||
clusterA.setClusterStatus("available");
|
||||
|
||||
Cluster clusterB = new Cluster();
|
||||
clusterB.setClusterIdentifier("cluster-b");
|
||||
clusterB.setMasterUsername("admin");
|
||||
clusterB.setMasterPassword("pw-b");
|
||||
clusterB.setClusterStatus("available");
|
||||
|
||||
when(clusterBackend.scanAllAccountEntries(any())).thenReturn(List.of(
|
||||
new AccountAwareStorageBackend.AccountEntry<>("111111111111", "cluster-a", clusterA),
|
||||
new AccountAwareStorageBackend.AccountEntry<>("222222222222", "cluster-b", clusterB)));
|
||||
when(cm.getContainer(anyString(), anyString())).thenReturn(Optional.empty());
|
||||
when(cm.adoptOrStart(eq("111111111111"), eq("cluster-a"), eq("admin"), eq("pw-a")))
|
||||
.thenReturn(new RedshiftContainerHandle("c-a", "cluster-a", "localhost", 5432));
|
||||
when(cm.adoptOrStart(eq("222222222222"), eq("cluster-b"), eq("admin"), eq("pw-b")))
|
||||
.thenReturn(new RedshiftContainerHandle("c-b", "cluster-b", "localhost", 5433));
|
||||
|
||||
service.onStart(null);
|
||||
|
||||
// Cluster owned by a second, non-default account must also be recovered
|
||||
verify(cm).adoptOrStart("111111111111", "cluster-a", "admin", "pw-a");
|
||||
verify(cm).adoptOrStart("222222222222", "cluster-b", "admin", "pw-b");
|
||||
verify(clusterBackend).putForAccount(eq("111111111111"), eq("cluster-a"), any(Cluster.class));
|
||||
verify(clusterBackend).putForAccount(eq("222222222222"), eq("cluster-b"), any(Cluster.class));
|
||||
verify(clusterBackend).flush();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testOnStartSkipsClusterWithRunningContainer() {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("cluster-a");
|
||||
cluster.setClusterStatus("available");
|
||||
when(clusterBackend.scanAllAccountEntries(any())).thenReturn(List.of(
|
||||
new AccountAwareStorageBackend.AccountEntry<>("111111111111", "cluster-a", cluster)));
|
||||
when(cm.getContainer("111111111111", "cluster-a"))
|
||||
.thenReturn(Optional.of(new RedshiftContainerHandle("c-a", "cluster-a", "localhost", 5432)));
|
||||
|
||||
service.onStart(null);
|
||||
|
||||
verify(cm, never()).adoptOrStart(any(), any(), any(), any());
|
||||
verify(clusterBackend, never()).putForAccount(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testOnStartMarksClusterUnavailableOnStartFailure() {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("cluster-a");
|
||||
cluster.setMasterUsername("admin");
|
||||
cluster.setMasterPassword("pw-a");
|
||||
cluster.setClusterStatus("available");
|
||||
when(clusterBackend.scanAllAccountEntries(any())).thenReturn(List.of(
|
||||
new AccountAwareStorageBackend.AccountEntry<>("111111111111", "cluster-a", cluster)));
|
||||
when(cm.getContainer("111111111111", "cluster-a")).thenReturn(Optional.empty());
|
||||
when(cm.adoptOrStart(eq("111111111111"), eq("cluster-a"), eq("admin"), eq("pw-a"))).thenThrow(new RuntimeException("docker down"));
|
||||
|
||||
service.onStart(null);
|
||||
|
||||
ArgumentCaptor<Cluster> captor = ArgumentCaptor.forClass(Cluster.class);
|
||||
verify(clusterBackend).putForAccount(eq("111111111111"), eq("cluster-a"), captor.capture());
|
||||
assertEquals("unavailable", captor.getValue().getClusterStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateCluster() {
|
||||
when(clusterBackend.get(anyString())).thenReturn(Optional.empty());
|
||||
when(cm.start(any(), any(), any(), any())).thenReturn(new RedshiftContainerHandle("c1", "my-cluster", "localhost", 5432));
|
||||
|
||||
Cluster cluster = service.createCluster("my-cluster", "dc2.large", "admin", "password123");
|
||||
assertNotNull(cluster);
|
||||
assertEquals("my-cluster", cluster.getClusterIdentifier());
|
||||
assertEquals("available", cluster.getClusterStatus());
|
||||
assertEquals("localhost", cluster.getEndpoint().getAddress());
|
||||
verify(clusterBackend, times(2)).put(eq("my-cluster"), any(Cluster.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateClusterWithVpcMetadata() {
|
||||
when(clusterBackend.get(anyString())).thenReturn(Optional.empty());
|
||||
when(cm.start(any(), any(), any(), any())).thenReturn(new RedshiftContainerHandle("c1", "my-cluster", "localhost", 5432));
|
||||
|
||||
Cluster cluster = service.createCluster("my-cluster", "dc2.large", "admin", "password123",
|
||||
"my-subnet-group", List.of("sg-1", "sg-2"));
|
||||
|
||||
assertEquals("my-subnet-group", cluster.getClusterSubnetGroupName());
|
||||
assertEquals(List.of("sg-1", "sg-2"), cluster.getVpcSecurityGroupIds());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateClusterAlreadyExists() {
|
||||
when(clusterBackend.get("existing-cluster")).thenReturn(Optional.of(new Cluster()));
|
||||
|
||||
assertThrows(AwsException.class, () ->
|
||||
service.createCluster("existing-cluster", "dc2.large", "admin", "password123"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDescribeClusters() {
|
||||
Cluster c = new Cluster();
|
||||
c.setClusterIdentifier("test-c");
|
||||
when(clusterBackend.get("test-c")).thenReturn(Optional.of(c));
|
||||
|
||||
List<Cluster> list = service.describeClusters("test-c");
|
||||
assertEquals(1, list.size());
|
||||
assertEquals("test-c", list.get(0).getClusterIdentifier());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteCluster() {
|
||||
Cluster c = new Cluster();
|
||||
c.setClusterIdentifier("test-c");
|
||||
when(clusterBackend.get("test-c")).thenReturn(Optional.of(c));
|
||||
|
||||
Cluster deleted = service.deleteCluster("test-c");
|
||||
assertEquals("deleting", deleted.getClusterStatus());
|
||||
verify(cm).stop("111111111111", "test-c");
|
||||
verify(clusterBackend).delete("test-c");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRebootClusterDumpsAndRestoresData() throws Exception {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("my-cluster");
|
||||
cluster.setMasterUsername("admin");
|
||||
cluster.setMasterPassword("pw");
|
||||
cluster.setClusterStatus("available");
|
||||
when(clusterBackend.get("my-cluster")).thenReturn(Optional.of(cluster));
|
||||
when(cm.start(eq("111111111111"), eq("my-cluster"), eq("admin"), eq("pw")))
|
||||
.thenReturn(new RedshiftContainerHandle("c-rebooted", "my-cluster", "localhost", 5555));
|
||||
doAnswer(invocation -> {
|
||||
java.nio.file.Path dumpFile = invocation.getArgument(3);
|
||||
java.nio.file.Files.writeString(dumpFile, "-- dump");
|
||||
return null;
|
||||
}).when(cm).takeSnapshot(eq("111111111111"), eq("my-cluster"), eq("admin"), any(java.nio.file.Path.class));
|
||||
|
||||
Cluster rebooted = service.rebootCluster("my-cluster");
|
||||
|
||||
assertEquals("available", rebooted.getClusterStatus());
|
||||
assertEquals(5555, rebooted.getEndpoint().getPort());
|
||||
verify(cm).stop("111111111111", "my-cluster");
|
||||
verify(cm).start("111111111111", "my-cluster", "admin", "pw");
|
||||
verify(cm).restoreSnapshot(eq("111111111111"), eq("my-cluster"), eq("admin"), any(java.nio.file.Path.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRebootClusterNotFound() {
|
||||
when(clusterBackend.get("missing")).thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(AwsException.class, () -> service.rebootCluster("missing"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateSnapshot() {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("my-cluster");
|
||||
cluster.setMasterUsername("admin");
|
||||
cluster.setMasterPassword("secret-pw");
|
||||
cluster.setEndpoint(new Endpoint("localhost", 5439));
|
||||
|
||||
when(clusterBackend.get("my-cluster")).thenReturn(Optional.of(cluster));
|
||||
when(snapshotBackend.get("my-snapshot")).thenReturn(Optional.empty());
|
||||
doNothing().when(cm).takeSnapshot(eq("111111111111"), eq("my-cluster"), eq("admin"), any(java.nio.file.Path.class));
|
||||
|
||||
Snapshot snapshot = service.createSnapshot("my-snapshot", "my-cluster");
|
||||
assertNotNull(snapshot);
|
||||
assertEquals("my-snapshot", snapshot.getSnapshotIdentifier());
|
||||
assertEquals("my-cluster", snapshot.getClusterIdentifier());
|
||||
assertEquals("available", snapshot.getStatus());
|
||||
assertEquals("admin", snapshot.getMasterUsername());
|
||||
// Password captured at snapshot time so restore can recover it after the source cluster is gone
|
||||
assertEquals("secret-pw", snapshot.getMasterPassword());
|
||||
assertEquals(5439, snapshot.getPort());
|
||||
// sqlDump is now an absolute path scoped by account to avoid collisions across accounts
|
||||
assertTrue(snapshot.getSqlDump().contains("111111111111"));
|
||||
assertTrue(snapshot.getSqlDump().endsWith("my-snapshot.sql"));
|
||||
verify(snapshotBackend).put(eq("my-snapshot"), any(Snapshot.class));
|
||||
verify(snapshotBackend).flush();
|
||||
verify(cm).takeSnapshot(eq("111111111111"), eq("my-cluster"), eq("admin"), any(java.nio.file.Path.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateSnapshotClusterNotFound() {
|
||||
when(clusterBackend.get("missing-cluster")).thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(AwsException.class, () ->
|
||||
service.createSnapshot("snap-1", "missing-cluster"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateSnapshotAlreadyExists() {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("my-cluster");
|
||||
when(clusterBackend.get("my-cluster")).thenReturn(Optional.of(cluster));
|
||||
when(snapshotBackend.get("snap-1")).thenReturn(Optional.of(new Snapshot()));
|
||||
|
||||
assertThrows(AwsException.class, () ->
|
||||
service.createSnapshot("snap-1", "my-cluster"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateSnapshotRejectsTraversalOrMalformedIdentifier() {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("my-cluster");
|
||||
cluster.setMasterUsername("admin");
|
||||
when(clusterBackend.get("my-cluster")).thenReturn(Optional.of(cluster));
|
||||
when(snapshotBackend.get(anyString())).thenReturn(Optional.empty());
|
||||
|
||||
String[] bad = {
|
||||
"../evil", "../../etc/cron.d/x", "/etc/passwd", "a/b", "a\\b",
|
||||
"foo/../bar", "-leading", "trailing-", "double--hyphen", "1startsdigit", "", "has space",
|
||||
};
|
||||
for (String id : bad) {
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> service.createSnapshot(id, "my-cluster"), "expected rejection for: " + id);
|
||||
assertEquals("InvalidParameterValue", ex.getErrorCode(), id);
|
||||
assertEquals(400, ex.getHttpStatus(), id);
|
||||
}
|
||||
verify(cm, never()).takeSnapshot(any(), any(), any(), any(java.nio.file.Path.class));
|
||||
verify(snapshotBackend, never()).put(anyString(), any(Snapshot.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testModifyClusterUpdatesMetadataAndPassword() {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("my-cluster");
|
||||
cluster.setNodeType("dc2.large");
|
||||
cluster.setMasterUsername("admin");
|
||||
cluster.setMasterPassword("old-pw");
|
||||
when(clusterBackend.get("my-cluster")).thenReturn(Optional.of(cluster));
|
||||
|
||||
Cluster updated = service.modifyCluster("my-cluster", "ra3.xlplus", null, "new-pw", null, null);
|
||||
|
||||
assertEquals("ra3.xlplus", updated.getNodeType());
|
||||
assertEquals("new-pw", updated.getMasterPassword());
|
||||
verify(cm).alterUserPassword("111111111111", "my-cluster", "admin", "new-pw");
|
||||
verify(clusterBackend).put(eq("my-cluster"), any(Cluster.class));
|
||||
verify(clusterBackend).flush();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testModifyClusterUpdatesVpcSecurityGroups() {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("my-cluster");
|
||||
cluster.setMasterUsername("admin");
|
||||
when(clusterBackend.get("my-cluster")).thenReturn(Optional.of(cluster));
|
||||
|
||||
Cluster updated = service.modifyCluster("my-cluster", null, null, null, "custom-pg", List.of("sg-9"));
|
||||
|
||||
assertEquals("custom-pg", updated.getClusterParameterGroupName());
|
||||
assertEquals(List.of("sg-9"), updated.getVpcSecurityGroupIds());
|
||||
verify(cm, never()).alterUserPassword(any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testModifyClusterNotFound() {
|
||||
when(clusterBackend.get("missing")).thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(AwsException.class, () ->
|
||||
service.modifyCluster("missing", "ra3.xlplus", null, null, null, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDescribeSnapshots() {
|
||||
Snapshot s = new Snapshot("snap-1", "my-cluster", "available", 5439, "admin");
|
||||
when(snapshotBackend.get("snap-1")).thenReturn(Optional.of(s));
|
||||
|
||||
List<Snapshot> list = service.describeSnapshots("snap-1");
|
||||
assertEquals(1, list.size());
|
||||
assertEquals("snap-1", list.get(0).getSnapshotIdentifier());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDescribeSnapshotsNotFound() {
|
||||
when(snapshotBackend.get("missing-snap")).thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(AwsException.class, () -> service.describeSnapshots("missing-snap"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteSnapshot() {
|
||||
Snapshot s = new Snapshot("snap-1", "my-cluster", "available", 5439, "admin");
|
||||
s.setSqlDump(dumpPath("snap-1"));
|
||||
when(snapshotBackend.get("snap-1")).thenReturn(Optional.of(s));
|
||||
|
||||
Snapshot deleted = service.deleteSnapshot("snap-1");
|
||||
assertNotNull(deleted);
|
||||
assertEquals("deleted", deleted.getStatus());
|
||||
verify(snapshotBackend).delete("snap-1");
|
||||
verify(snapshotBackend).flush();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteSnapshotNotFound() {
|
||||
when(snapshotBackend.get("missing-snap")).thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(AwsException.class, () -> service.deleteSnapshot("missing-snap"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRestoreFromClusterSnapshot() {
|
||||
Cluster sourceCluster = new Cluster();
|
||||
sourceCluster.setClusterIdentifier("source-cluster");
|
||||
sourceCluster.setMasterPassword("password123");
|
||||
|
||||
Snapshot snapshot = new Snapshot("my-snapshot", "source-cluster", "available", 5439, "admin");
|
||||
snapshot.setSqlDump(dumpPath("my-snapshot"));
|
||||
when(clusterBackend.get("restored-cluster")).thenReturn(Optional.empty());
|
||||
when(clusterBackend.get("source-cluster")).thenReturn(Optional.of(sourceCluster));
|
||||
when(snapshotBackend.get("my-snapshot")).thenReturn(Optional.of(snapshot));
|
||||
when(cm.start(eq("111111111111"), eq("restored-cluster"), eq("admin"), eq("password123")))
|
||||
.thenReturn(new RedshiftContainerHandle("c-new", "restored-cluster", "localhost", 5432));
|
||||
doNothing().when(cm).restoreSnapshot(eq("111111111111"), eq("restored-cluster"), eq("admin"), any(java.nio.file.Path.class));
|
||||
|
||||
Cluster cluster = service.restoreFromClusterSnapshot("restored-cluster", "my-snapshot", "dc2.large");
|
||||
assertNotNull(cluster);
|
||||
assertEquals("restored-cluster", cluster.getClusterIdentifier());
|
||||
assertEquals("available", cluster.getClusterStatus());
|
||||
assertEquals("admin", cluster.getMasterUsername());
|
||||
assertEquals("password123", cluster.getMasterPassword());
|
||||
assertEquals("dc2.large", cluster.getNodeType());
|
||||
assertEquals("localhost", cluster.getEndpoint().getAddress());
|
||||
|
||||
// Restore must use the source cluster's actual password, not a hardcoded one
|
||||
verify(cm).start("111111111111", "restored-cluster", "admin", "password123");
|
||||
verify(cm).restoreSnapshot(eq("111111111111"), eq("restored-cluster"), eq("admin"), any(java.nio.file.Path.class));
|
||||
verify(clusterBackend, times(2)).put(eq("restored-cluster"), any(Cluster.class));
|
||||
verify(clusterBackend, times(2)).flush();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRestoreFromClusterSnapshotUsesStoredPasswordAfterSourceClusterDeleted() {
|
||||
Snapshot snapshot = new Snapshot("my-snapshot", "deleted-source", "available", 5439, "admin");
|
||||
snapshot.setMasterPassword("original-secret");
|
||||
snapshot.setSqlDump(dumpPath("my-snapshot"));
|
||||
when(clusterBackend.get("restored-cluster")).thenReturn(Optional.empty());
|
||||
// Source cluster no longer exists, but the snapshot itself still carries the original password
|
||||
when(clusterBackend.get("deleted-source")).thenReturn(Optional.empty());
|
||||
when(snapshotBackend.get("my-snapshot")).thenReturn(Optional.of(snapshot));
|
||||
when(cm.start(eq("111111111111"), eq("restored-cluster"), eq("admin"), eq("original-secret")))
|
||||
.thenReturn(new RedshiftContainerHandle("c-new", "restored-cluster", "localhost", 5432));
|
||||
doNothing().when(cm).restoreSnapshot(eq("111111111111"), eq("restored-cluster"), eq("admin"), any(java.nio.file.Path.class));
|
||||
|
||||
Cluster cluster = service.restoreFromClusterSnapshot("restored-cluster", "my-snapshot", "dc2.large");
|
||||
assertEquals("original-secret", cluster.getMasterPassword());
|
||||
verify(cm).start("111111111111", "restored-cluster", "admin", "original-secret");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRestoreFromClusterSnapshotFallsBackToAdminWhenSourceClusterGone() {
|
||||
Snapshot snapshot = new Snapshot("my-snapshot", "deleted-source", "available", 5439, "admin");
|
||||
snapshot.setSqlDump(dumpPath("my-snapshot"));
|
||||
when(clusterBackend.get("restored-cluster")).thenReturn(Optional.empty());
|
||||
when(clusterBackend.get("deleted-source")).thenReturn(Optional.empty());
|
||||
when(snapshotBackend.get("my-snapshot")).thenReturn(Optional.of(snapshot));
|
||||
when(cm.start(eq("111111111111"), eq("restored-cluster"), eq("admin"), eq("admin")))
|
||||
.thenReturn(new RedshiftContainerHandle("c-new", "restored-cluster", "localhost", 5432));
|
||||
doNothing().when(cm).restoreSnapshot(eq("111111111111"), eq("restored-cluster"), eq("admin"), any(java.nio.file.Path.class));
|
||||
|
||||
Cluster cluster = service.restoreFromClusterSnapshot("restored-cluster", "my-snapshot", "dc2.large");
|
||||
assertEquals("admin", cluster.getMasterPassword());
|
||||
verify(cm).start("111111111111", "restored-cluster", "admin", "admin");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRestoreFromClusterSnapshotAlreadyExists() {
|
||||
when(clusterBackend.get("existing-cluster")).thenReturn(Optional.of(new Cluster()));
|
||||
|
||||
assertThrows(AwsException.class, () ->
|
||||
service.restoreFromClusterSnapshot("existing-cluster", "my-snapshot"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRestoreFromClusterSnapshotNotFound() {
|
||||
when(clusterBackend.get("new-cluster")).thenReturn(Optional.empty());
|
||||
when(snapshotBackend.get("missing-snapshot")).thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(AwsException.class, () ->
|
||||
service.restoreFromClusterSnapshot("new-cluster", "missing-snapshot"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRestoreFromClusterSnapshotFailure() {
|
||||
Snapshot snapshot = new Snapshot("my-snapshot", "source-cluster", "available", 5439, "admin", dumpPath("my-snapshot"));
|
||||
when(clusterBackend.get("failed-cluster")).thenReturn(Optional.empty());
|
||||
when(snapshotBackend.get("my-snapshot")).thenReturn(Optional.of(snapshot));
|
||||
when(cm.start(any(), any(), any(), any())).thenThrow(new RuntimeException("Docker error"));
|
||||
|
||||
assertThrows(AwsException.class, () ->
|
||||
service.restoreFromClusterSnapshot("failed-cluster", "my-snapshot"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRestoreFromClusterSnapshotRejectsUntrustedDumpPathBeforeProvisioning() {
|
||||
// A dump path persisted outside the account dir (e.g. by pre-validation code) must be
|
||||
// rejected up front — no cluster record, no container.
|
||||
Snapshot snapshot = new Snapshot("my-snapshot", "source-cluster", "available", 5439, "admin", "/etc/shadow");
|
||||
when(clusterBackend.get("restored-cluster")).thenReturn(Optional.empty());
|
||||
when(snapshotBackend.get("my-snapshot")).thenReturn(Optional.of(snapshot));
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
service.restoreFromClusterSnapshot("restored-cluster", "my-snapshot", "dc2.large"));
|
||||
assertEquals("InvalidParameterValue", ex.getErrorCode());
|
||||
assertEquals(400, ex.getHttpStatus());
|
||||
verify(cm, never()).start(any(), any(), any(), any());
|
||||
verify(cm, never()).restoreSnapshot(any(), any(), any(), any());
|
||||
verify(clusterBackend, never()).put(anyString(), any(Cluster.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateClusterParameterGroup() {
|
||||
when(parameterGroupBackend.get("my-pg")).thenReturn(Optional.empty());
|
||||
|
||||
ClusterParameterGroup pg = service.createClusterParameterGroup("my-pg", "redshift-1.0", "custom pg");
|
||||
assertNotNull(pg);
|
||||
assertEquals("my-pg", pg.getParameterGroupName());
|
||||
assertEquals("redshift-1.0", pg.getParameterGroupFamily());
|
||||
assertEquals("custom pg", pg.getDescription());
|
||||
verify(parameterGroupBackend).put(eq("my-pg"), any(ClusterParameterGroup.class));
|
||||
verify(parameterGroupBackend).flush();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateClusterParameterGroupAlreadyExists() {
|
||||
when(parameterGroupBackend.get("my-pg")).thenReturn(Optional.of(new ClusterParameterGroup()));
|
||||
|
||||
assertThrows(AwsException.class, () ->
|
||||
service.createClusterParameterGroup("my-pg", "redshift-1.0", "custom pg"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDescribeClusterParameterGroups() {
|
||||
ClusterParameterGroup pg = new ClusterParameterGroup("my-pg", "redshift-1.0", "custom pg");
|
||||
when(parameterGroupBackend.get("my-pg")).thenReturn(Optional.of(pg));
|
||||
|
||||
List<ClusterParameterGroup> list = service.describeClusterParameterGroups("my-pg");
|
||||
assertEquals(1, list.size());
|
||||
assertEquals("my-pg", list.get(0).getParameterGroupName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDescribeClusterParameterGroupsNotFound() {
|
||||
when(parameterGroupBackend.get("missing-pg")).thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(AwsException.class, () ->
|
||||
service.describeClusterParameterGroups("missing-pg"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteClusterParameterGroup() {
|
||||
ClusterParameterGroup pg = new ClusterParameterGroup("my-pg", "redshift-1.0", "custom pg");
|
||||
when(parameterGroupBackend.get("my-pg")).thenReturn(Optional.of(pg));
|
||||
|
||||
ClusterParameterGroup deleted = service.deleteClusterParameterGroup("my-pg");
|
||||
assertNotNull(deleted);
|
||||
assertEquals("my-pg", deleted.getParameterGroupName());
|
||||
verify(parameterGroupBackend).delete("my-pg");
|
||||
verify(parameterGroupBackend).flush();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteClusterParameterGroupNotFound() {
|
||||
when(parameterGroupBackend.get("missing-pg")).thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(AwsException.class, () ->
|
||||
service.deleteClusterParameterGroup("missing-pg"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testModifyClusterParameterGroup() {
|
||||
ClusterParameterGroup group = new ClusterParameterGroup("my-pg", "redshift-1.0", "custom pg");
|
||||
when(parameterGroupBackend.get("my-pg")).thenReturn(Optional.of(group));
|
||||
|
||||
ClusterParameterGroup updated = service.modifyClusterParameterGroup("my-pg",
|
||||
List.of(new Parameter("max_cursor_result_set_size", "1000")));
|
||||
|
||||
assertEquals("1000", updated.getParameters().stream()
|
||||
.filter(p -> "max_cursor_result_set_size".equals(p.getParameterName()))
|
||||
.findFirst().orElseThrow().getParameterValue());
|
||||
verify(parameterGroupBackend).put(eq("my-pg"), any(ClusterParameterGroup.class));
|
||||
verify(parameterGroupBackend).flush();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testModifyClusterParameterGroupAppendsUnknownParameter() {
|
||||
ClusterParameterGroup group = new ClusterParameterGroup("my-pg", "redshift-1.0", "custom pg");
|
||||
when(parameterGroupBackend.get("my-pg")).thenReturn(Optional.of(group));
|
||||
|
||||
ClusterParameterGroup updated = service.modifyClusterParameterGroup("my-pg",
|
||||
List.of(new Parameter("statement_timeout", "5000")));
|
||||
|
||||
assertTrue(updated.getParameters().stream()
|
||||
.anyMatch(p -> "statement_timeout".equals(p.getParameterName()) && "5000".equals(p.getParameterValue())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testModifyClusterParameterGroupNotFound() {
|
||||
when(parameterGroupBackend.get("missing")).thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(AwsException.class, () ->
|
||||
service.modifyClusterParameterGroup("missing", List.of(new Parameter("x", "y"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDescribeClusterParametersReturnsStoredValues() {
|
||||
ClusterParameterGroup group = new ClusterParameterGroup("my-pg", "redshift-1.0", "custom pg");
|
||||
group.setParameters(new java.util.ArrayList<>(List.of(new Parameter("statement_timeout", "5000"))));
|
||||
when(parameterGroupBackend.get("my-pg")).thenReturn(Optional.of(group));
|
||||
|
||||
List<Parameter> params = service.describeClusterParameters("my-pg");
|
||||
|
||||
assertEquals(1, params.size());
|
||||
assertEquals("statement_timeout", params.get(0).getParameterName());
|
||||
assertEquals("5000", params.get(0).getParameterValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testModifyClusterParameterGroupPreservesMetadata() {
|
||||
ClusterParameterGroup group = new ClusterParameterGroup("my-pg", "redshift-1.0", "custom pg");
|
||||
when(parameterGroupBackend.get("my-pg")).thenReturn(Optional.of(group));
|
||||
|
||||
// Modify using 2-arg constructor (only name and value) - should preserve description and dataType
|
||||
ClusterParameterGroup updated = service.modifyClusterParameterGroup("my-pg",
|
||||
List.of(new Parameter("max_cursor_result_set_size", "1000")));
|
||||
|
||||
Parameter modified = updated.getParameters().stream()
|
||||
.filter(p -> "max_cursor_result_set_size".equals(p.getParameterName()))
|
||||
.findFirst().orElseThrow();
|
||||
assertEquals("1000", modified.getParameterValue());
|
||||
assertEquals("Maximum cursor result set size", modified.getDescription());
|
||||
assertEquals("integer", modified.getDataType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateAndListTagsForCluster() {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("my-cluster");
|
||||
when(clusterBackend.get("my-cluster")).thenReturn(Optional.of(cluster));
|
||||
|
||||
service.createTags("arn:aws:redshift:us-east-1:111111111111:cluster:my-cluster",
|
||||
java.util.Map.of("env", "test"));
|
||||
|
||||
assertEquals("test", cluster.getTags().get("env"));
|
||||
verify(clusterBackend).put(eq("my-cluster"), any(Cluster.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteTagsForCluster() {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("my-cluster");
|
||||
cluster.setTags(new java.util.LinkedHashMap<>(java.util.Map.of("env", "test", "team", "data")));
|
||||
when(clusterBackend.get("my-cluster")).thenReturn(Optional.of(cluster));
|
||||
|
||||
service.deleteTags("arn:aws:redshift:us-east-1:111111111111:cluster:my-cluster", java.util.List.of("env"));
|
||||
|
||||
assertEquals(java.util.Map.of("team", "data"), cluster.getTags());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateTagsRejectsNonArnResourceName() {
|
||||
assertThrows(AwsException.class, () ->
|
||||
service.createTags("my-cluster", java.util.Map.of("env", "test")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateTagsRejectsUnknownResourceType() {
|
||||
assertThrows(AwsException.class, () ->
|
||||
service.createTags("arn:aws:redshift:us-east-1:111111111111:reservednode:foo", java.util.Map.of("env", "test")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDescribeTagsForSpecificResource() {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setClusterIdentifier("my-cluster");
|
||||
cluster.setTags(new java.util.LinkedHashMap<>(java.util.Map.of("env", "test")));
|
||||
when(clusterBackend.get("my-cluster")).thenReturn(Optional.of(cluster));
|
||||
|
||||
List<RedshiftService.TaggedResource> tagged =
|
||||
service.describeTags("arn:aws:redshift:us-east-1:111111111111:cluster:my-cluster", null, null);
|
||||
|
||||
assertEquals(1, tagged.size());
|
||||
assertEquals("cluster", tagged.get(0).resourceType());
|
||||
assertEquals("env", tagged.get(0).tagKey());
|
||||
assertEquals("test", tagged.get(0).tagValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDescribeTagsScansAllResourcesOfType() {
|
||||
Cluster a = new Cluster();
|
||||
a.setClusterIdentifier("cluster-a");
|
||||
a.setTags(new java.util.LinkedHashMap<>(java.util.Map.of("env", "prod")));
|
||||
Cluster b = new Cluster();
|
||||
b.setClusterIdentifier("cluster-b");
|
||||
b.setTags(new java.util.LinkedHashMap<>());
|
||||
when(clusterBackend.scan(any())).thenReturn(java.util.List.of(a, b));
|
||||
when(snapshotBackend.scan(any())).thenReturn(java.util.List.of());
|
||||
when(parameterGroupBackend.scan(any())).thenReturn(java.util.List.of());
|
||||
when(subnetGroupBackend.scan(any())).thenReturn(java.util.List.of());
|
||||
|
||||
List<RedshiftService.TaggedResource> tagged = service.describeTags(null, "cluster", null);
|
||||
|
||||
assertEquals(1, tagged.size());
|
||||
assertEquals("cluster-a", extractResourceId(tagged.get(0).resourceName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateClusterSubnetGroup() {
|
||||
when(subnetGroupBackend.get("my-subnet-group")).thenReturn(Optional.empty());
|
||||
|
||||
ClusterSubnetGroup group = service.createClusterSubnetGroup(
|
||||
"my-subnet-group", "test group", "vpc-123", List.of("subnet-1", "subnet-2"));
|
||||
|
||||
assertEquals("my-subnet-group", group.getClusterSubnetGroupName());
|
||||
assertEquals(List.of("subnet-1", "subnet-2"), group.getSubnetIds());
|
||||
verify(subnetGroupBackend).put(eq("my-subnet-group"), any(ClusterSubnetGroup.class));
|
||||
verify(subnetGroupBackend).flush();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateClusterSubnetGroupAlreadyExists() {
|
||||
when(subnetGroupBackend.get("existing")).thenReturn(Optional.of(new ClusterSubnetGroup()));
|
||||
|
||||
assertThrows(AwsException.class, () ->
|
||||
service.createClusterSubnetGroup("existing", "d", "vpc-1", List.of("subnet-1")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDescribeClusterSubnetGroups() {
|
||||
ClusterSubnetGroup group = new ClusterSubnetGroup("my-group", "d", "vpc-1", List.of("subnet-1"));
|
||||
when(subnetGroupBackend.get("my-group")).thenReturn(Optional.of(group));
|
||||
|
||||
List<ClusterSubnetGroup> list = service.describeClusterSubnetGroups("my-group");
|
||||
|
||||
assertEquals(1, list.size());
|
||||
assertEquals("my-group", list.get(0).getClusterSubnetGroupName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testModifyClusterSubnetGroup() {
|
||||
ClusterSubnetGroup group = new ClusterSubnetGroup("my-group", "old", "vpc-1", List.of("subnet-1"));
|
||||
when(subnetGroupBackend.get("my-group")).thenReturn(Optional.of(group));
|
||||
|
||||
ClusterSubnetGroup updated = service.modifyClusterSubnetGroup("my-group", "new", List.of("subnet-2", "subnet-3"));
|
||||
|
||||
assertEquals("new", updated.getDescription());
|
||||
assertEquals(List.of("subnet-2", "subnet-3"), updated.getSubnetIds());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteClusterSubnetGroup() {
|
||||
ClusterSubnetGroup group = new ClusterSubnetGroup("my-group", "d", "vpc-1", List.of("subnet-1"));
|
||||
when(subnetGroupBackend.get("my-group")).thenReturn(Optional.of(group));
|
||||
|
||||
ClusterSubnetGroup deleted = service.deleteClusterSubnetGroup("my-group");
|
||||
|
||||
assertEquals("my-group", deleted.getClusterSubnetGroupName());
|
||||
verify(subnetGroupBackend).delete("my-group");
|
||||
verify(subnetGroupBackend).flush();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteClusterSubnetGroupNotFound() {
|
||||
when(subnetGroupBackend.get("missing")).thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(AwsException.class, () -> service.deleteClusterSubnetGroup("missing"));
|
||||
}
|
||||
|
||||
private static String extractResourceId(String arn) {
|
||||
String resource = arn.substring(arn.lastIndexOf(':') + 1);
|
||||
return resource.contains("/") ? resource.substring(resource.lastIndexOf('/') + 1) : resource;
|
||||
}
|
||||
}
|
||||
+467
@@ -0,0 +1,467 @@
|
||||
package io.github.hectorvent.floci.services.redshift.container;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.async.ResultCallback;
|
||||
import com.github.dockerjava.api.command.CopyArchiveToContainerCmd;
|
||||
import com.github.dockerjava.api.command.ExecCreateCmd;
|
||||
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
|
||||
import com.github.dockerjava.api.command.ExecStartCmd;
|
||||
import com.github.dockerjava.api.command.InspectExecCmd;
|
||||
import com.github.dockerjava.api.command.InspectExecResponse;
|
||||
import com.github.dockerjava.api.model.Container;
|
||||
import com.github.dockerjava.api.model.Frame;
|
||||
import com.github.dockerjava.api.model.StreamType;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerInfo;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.EndpointInfo;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Cluster;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.Closeable;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
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.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class RedshiftContainerManagerTest {
|
||||
|
||||
private ContainerBuilder containerBuilder;
|
||||
private ContainerLifecycleManager lifecycleManager;
|
||||
private ContainerLogStreamer logStreamer;
|
||||
private ContainerDetector containerDetector;
|
||||
private EmulatorConfig config;
|
||||
private DockerClient dockerClient;
|
||||
private RedshiftContainerManager manager;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
containerBuilder = mock(ContainerBuilder.class);
|
||||
lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
logStreamer = mock(ContainerLogStreamer.class);
|
||||
containerDetector = mock(ContainerDetector.class);
|
||||
config = mock(EmulatorConfig.class, org.mockito.Mockito.RETURNS_DEEP_STUBS);
|
||||
dockerClient = mock(DockerClient.class);
|
||||
|
||||
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
|
||||
when(config.services().redshift().imageVersion()).thenReturn("postgres:16-alpine");
|
||||
when(config.services().redshift().dockerNetwork()).thenReturn(Optional.empty());
|
||||
|
||||
manager = new RedshiftContainerManager(
|
||||
containerBuilder,
|
||||
lifecycleManager,
|
||||
logStreamer,
|
||||
containerDetector,
|
||||
config
|
||||
);
|
||||
}
|
||||
|
||||
private static final String ACCOUNT_ID = "111111111111";
|
||||
|
||||
@Test
|
||||
void testTakeSnapshotContainerNotFound() {
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
manager.takeSnapshot(ACCOUNT_ID, "non-existent-cluster", "admin", "dev", java.nio.file.Path.of("dummy.sql")));
|
||||
assertEquals("ClusterNotFound", ex.getErrorCode());
|
||||
assertEquals(404, ex.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRestoreSnapshotContainerNotFound() {
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
manager.restoreSnapshot(ACCOUNT_ID, "non-existent-cluster", "admin", "dev", java.nio.file.Path.of("dummy.sql")));
|
||||
assertEquals("ClusterNotFound", ex.getErrorCode());
|
||||
assertEquals(404, ex.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateSnapshotNullCluster() {
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
manager.createSnapshot(ACCOUNT_ID, null, java.nio.file.Path.of("dummy.sql")));
|
||||
assertEquals("InvalidParameterValue", ex.getErrorCode());
|
||||
assertEquals(400, ex.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRestoreSnapshotNullCluster() {
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
manager.restoreSnapshot(ACCOUNT_ID, (Cluster) null, java.nio.file.Path.of("dummy.sql")));
|
||||
assertEquals("InvalidParameterValue", ex.getErrorCode());
|
||||
assertEquals(400, ex.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testTakeSnapshotSuccess() throws Exception {
|
||||
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, org.mockito.Mockito.RETURNS_SELF);
|
||||
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
|
||||
ContainerInfo info = new ContainerInfo("cont-123", Map.of(5432, new EndpointInfo("localhost", 5432)));
|
||||
when(lifecycleManager.createAndStart(any())).thenReturn(info);
|
||||
|
||||
RedshiftContainerHandle handle = manager.start(ACCOUNT_ID, "test-cluster", "admin", "pass");
|
||||
assertNotNull(handle);
|
||||
assertEquals("cont-123", handle.getContainerId());
|
||||
assertTrue(manager.getContainer(ACCOUNT_ID, "test-cluster").isPresent());
|
||||
|
||||
// Mock docker exec for pg_dump
|
||||
ExecCreateCmd createCmd = mock(ExecCreateCmd.class, org.mockito.Mockito.RETURNS_SELF);
|
||||
ExecCreateCmdResponse createResponse = mock(ExecCreateCmdResponse.class);
|
||||
when(createResponse.getId()).thenReturn("exec-1");
|
||||
when(createCmd.exec()).thenReturn(createResponse);
|
||||
when(dockerClient.execCreateCmd("cont-123")).thenReturn(createCmd);
|
||||
|
||||
ExecStartCmd startCmd = mock(ExecStartCmd.class);
|
||||
when(startCmd.exec(any())).thenAnswer(invocation -> {
|
||||
@SuppressWarnings("unchecked")
|
||||
ResultCallback.Adapter<Frame> adapter = invocation.getArgument(0);
|
||||
adapter.onComplete();
|
||||
return adapter;
|
||||
});
|
||||
when(dockerClient.execStartCmd("exec-1")).thenReturn(startCmd);
|
||||
|
||||
InspectExecCmd inspectCmd = mock(InspectExecCmd.class);
|
||||
InspectExecResponse inspectResponse = mock(InspectExecResponse.class);
|
||||
when(inspectResponse.getExitCodeLong()).thenReturn(0L);
|
||||
when(inspectCmd.exec()).thenReturn(inspectResponse);
|
||||
when(dockerClient.inspectExecCmd("exec-1")).thenReturn(inspectCmd);
|
||||
|
||||
// mock copyArchiveFromContainerCmd
|
||||
com.github.dockerjava.api.command.CopyArchiveFromContainerCmd copyCmd = mock(com.github.dockerjava.api.command.CopyArchiveFromContainerCmd.class, org.mockito.Mockito.RETURNS_SELF);
|
||||
byte[] tarBytes = "-- PostgreSQL dump\nCREATE TABLE foo (id int);\n".getBytes(StandardCharsets.UTF_8);
|
||||
java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
|
||||
try (org.apache.commons.compress.archivers.tar.TarArchiveOutputStream tar = new org.apache.commons.compress.archivers.tar.TarArchiveOutputStream(bos)) {
|
||||
org.apache.commons.compress.archivers.tar.TarArchiveEntry entry = new org.apache.commons.compress.archivers.tar.TarArchiveEntry("dump.sql");
|
||||
entry.setSize(tarBytes.length);
|
||||
tar.putArchiveEntry(entry);
|
||||
tar.write(tarBytes);
|
||||
tar.closeArchiveEntry();
|
||||
}
|
||||
when(copyCmd.exec()).thenReturn(new java.io.ByteArrayInputStream(bos.toByteArray()));
|
||||
when(dockerClient.copyArchiveFromContainerCmd("cont-123", "/tmp/dump.sql")).thenReturn(copyCmd);
|
||||
|
||||
java.nio.file.Path tempFile = java.nio.file.Files.createTempFile("test-take-snapshot", ".sql");
|
||||
try {
|
||||
manager.takeSnapshot(ACCOUNT_ID, "test-cluster", "admin", "dev",tempFile);
|
||||
String dump = java.nio.file.Files.readString(tempFile);
|
||||
assertTrue(dump.contains("PostgreSQL dump"));
|
||||
assertTrue(dump.contains("CREATE TABLE foo"));
|
||||
} finally {
|
||||
java.nio.file.Files.deleteIfExists(tempFile);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testTakeSnapshotFailureExitCode() throws Exception {
|
||||
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, org.mockito.Mockito.RETURNS_SELF);
|
||||
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
|
||||
ContainerInfo info = new ContainerInfo("cont-123", Map.of(5432, new EndpointInfo("localhost", 5432)));
|
||||
when(lifecycleManager.createAndStart(any())).thenReturn(info);
|
||||
|
||||
manager.start(ACCOUNT_ID, "test-cluster", "admin", "pass");
|
||||
|
||||
ExecCreateCmd createCmd = mock(ExecCreateCmd.class, org.mockito.Mockito.RETURNS_SELF);
|
||||
ExecCreateCmdResponse createResponse = mock(ExecCreateCmdResponse.class);
|
||||
when(createResponse.getId()).thenReturn("exec-fail");
|
||||
when(createCmd.exec()).thenReturn(createResponse);
|
||||
when(dockerClient.execCreateCmd("cont-123")).thenReturn(createCmd);
|
||||
|
||||
ExecStartCmd startCmd = mock(ExecStartCmd.class);
|
||||
when(startCmd.exec(any())).thenAnswer(invocation -> {
|
||||
@SuppressWarnings("unchecked")
|
||||
ResultCallback.Adapter<Frame> adapter = invocation.getArgument(0);
|
||||
byte[] err = "pg_dump: error: connection failed".getBytes(StandardCharsets.UTF_8);
|
||||
adapter.onNext(new Frame(StreamType.STDERR, err));
|
||||
adapter.onComplete();
|
||||
return adapter;
|
||||
});
|
||||
when(dockerClient.execStartCmd("exec-fail")).thenReturn(startCmd);
|
||||
|
||||
InspectExecCmd inspectCmd = mock(InspectExecCmd.class);
|
||||
InspectExecResponse inspectResponse = mock(InspectExecResponse.class);
|
||||
when(inspectResponse.getExitCodeLong()).thenReturn(1L);
|
||||
when(inspectCmd.exec()).thenReturn(inspectResponse);
|
||||
when(dockerClient.inspectExecCmd("exec-fail")).thenReturn(inspectCmd);
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
manager.takeSnapshot(ACCOUNT_ID, "test-cluster", "admin", "dev",java.nio.file.Path.of("dummy.sql")));
|
||||
assertEquals("InternalFailure", ex.getErrorCode());
|
||||
assertEquals(500, ex.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRestoreSnapshotEmptyDump() {
|
||||
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, org.mockito.Mockito.RETURNS_SELF);
|
||||
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
|
||||
ContainerInfo info = new ContainerInfo("cont-123", Map.of(5432, new EndpointInfo("localhost", 5432)));
|
||||
when(lifecycleManager.createAndStart(any())).thenReturn(info);
|
||||
|
||||
manager.start(ACCOUNT_ID, "test-cluster", "admin", "pass");
|
||||
|
||||
// Should return cleanly without touching dockerClient
|
||||
manager.restoreSnapshot(ACCOUNT_ID, "test-cluster", "admin", "dev",java.nio.file.Path.of("non-existent-dump.sql"));
|
||||
manager.restoreSnapshot(ACCOUNT_ID, "test-cluster", "admin", "dev",(java.nio.file.Path) null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRestoreSnapshotSuccess() throws Exception {
|
||||
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, org.mockito.Mockito.RETURNS_SELF);
|
||||
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
|
||||
ContainerInfo info = new ContainerInfo("cont-123", Map.of(5432, new EndpointInfo("localhost", 5432)));
|
||||
when(lifecycleManager.createAndStart(any())).thenReturn(info);
|
||||
|
||||
manager.start(ACCOUNT_ID, "test-cluster", "admin", "pass");
|
||||
|
||||
// Mock copyArchiveToContainerCmd
|
||||
CopyArchiveToContainerCmd copyCmd = mock(CopyArchiveToContainerCmd.class, org.mockito.Mockito.RETURNS_SELF);
|
||||
when(dockerClient.copyArchiveToContainerCmd("cont-123")).thenReturn(copyCmd);
|
||||
|
||||
// Mock docker exec for psql
|
||||
ExecCreateCmd createCmd = mock(ExecCreateCmd.class, org.mockito.Mockito.RETURNS_SELF);
|
||||
ExecCreateCmdResponse createResponse = mock(ExecCreateCmdResponse.class);
|
||||
when(createResponse.getId()).thenReturn("exec-restore");
|
||||
when(createCmd.exec()).thenReturn(createResponse);
|
||||
when(dockerClient.execCreateCmd("cont-123")).thenReturn(createCmd);
|
||||
|
||||
ExecStartCmd startCmd = mock(ExecStartCmd.class);
|
||||
when(startCmd.exec(any())).thenAnswer(invocation -> {
|
||||
@SuppressWarnings("unchecked")
|
||||
ResultCallback.Adapter<Frame> adapter = invocation.getArgument(0);
|
||||
adapter.onComplete();
|
||||
return adapter;
|
||||
});
|
||||
when(dockerClient.execStartCmd("exec-restore")).thenReturn(startCmd);
|
||||
|
||||
InspectExecCmd inspectCmd = mock(InspectExecCmd.class);
|
||||
InspectExecResponse inspectResponse = mock(InspectExecResponse.class);
|
||||
when(inspectResponse.getExitCodeLong()).thenReturn(0L);
|
||||
when(inspectCmd.exec()).thenReturn(inspectResponse);
|
||||
when(dockerClient.inspectExecCmd("exec-restore")).thenReturn(inspectCmd);
|
||||
|
||||
java.nio.file.Path tempFile = java.nio.file.Files.createTempFile("test-restore-snapshot", ".sql");
|
||||
try {
|
||||
manager.restoreSnapshot(ACCOUNT_ID, "test-cluster", "admin", "dev",tempFile);
|
||||
verify(dockerClient).copyArchiveToContainerCmd("cont-123");
|
||||
verify(dockerClient).execCreateCmd("cont-123");
|
||||
} finally {
|
||||
java.nio.file.Files.deleteIfExists(tempFile);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testStopRemovesContainer() {
|
||||
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, org.mockito.Mockito.RETURNS_SELF);
|
||||
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
|
||||
ContainerInfo info = new ContainerInfo("cont-123", Map.of(5432, new EndpointInfo("localhost", 5432)));
|
||||
when(lifecycleManager.createAndStart(any())).thenReturn(info);
|
||||
|
||||
manager.start(ACCOUNT_ID, "test-cluster", "admin", "pass");
|
||||
assertTrue(manager.getContainer(ACCOUNT_ID, "test-cluster").isPresent());
|
||||
|
||||
manager.stop(ACCOUNT_ID, "test-cluster");
|
||||
assertTrue(manager.getContainer(ACCOUNT_ID, "test-cluster").isEmpty());
|
||||
verify(lifecycleManager).removeIfExists("floci-redshift-" + ACCOUNT_ID + "-test-cluster");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSameClusterIdentifierAcrossAccountsDoesNotCollide() {
|
||||
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, org.mockito.Mockito.RETURNS_SELF);
|
||||
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
|
||||
ContainerInfo infoA = new ContainerInfo("cont-account-a", Map.of(5432, new EndpointInfo("localhost", 5432)));
|
||||
ContainerInfo infoB = new ContainerInfo("cont-account-b", Map.of(5432, new EndpointInfo("localhost", 5433)));
|
||||
when(lifecycleManager.createAndStart(any())).thenReturn(infoA, infoB);
|
||||
|
||||
String otherAccountId = "222222222222";
|
||||
manager.start(ACCOUNT_ID, "shared-id", "admin", "pass");
|
||||
manager.start(otherAccountId, "shared-id", "admin", "pass");
|
||||
|
||||
// Both accounts keep their own running container despite the shared cluster identifier
|
||||
assertTrue(manager.getContainer(ACCOUNT_ID, "shared-id").isPresent());
|
||||
assertTrue(manager.getContainer(otherAccountId, "shared-id").isPresent());
|
||||
assertEquals("cont-account-a", manager.getContainer(ACCOUNT_ID, "shared-id").get().getContainerId());
|
||||
assertEquals("cont-account-b", manager.getContainer(otherAccountId, "shared-id").get().getContainerId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAdoptOrStartAdoptsExistingContainerInsteadOfRecreatingIt() {
|
||||
String containerName = "floci-redshift-" + ACCOUNT_ID + "-test-cluster";
|
||||
Container existing = mock(Container.class);
|
||||
when(existing.getId()).thenReturn("cont-existing");
|
||||
when(lifecycleManager.findByName(containerName)).thenReturn(Optional.of(existing));
|
||||
ContainerInfo adopted = new ContainerInfo("cont-existing", Map.of(5432, new EndpointInfo("localhost", 6000)));
|
||||
when(lifecycleManager.adopt(eq("cont-existing"), any())).thenReturn(adopted);
|
||||
|
||||
RedshiftContainerHandle handle = manager.adoptOrStart(ACCOUNT_ID, "test-cluster", "admin", "pass");
|
||||
|
||||
assertEquals("cont-existing", handle.getContainerId());
|
||||
assertEquals(6000, handle.getPort());
|
||||
assertTrue(manager.getContainer(ACCOUNT_ID, "test-cluster").isPresent());
|
||||
// Data lives only in the container's writable layer (no volume) — recreating it
|
||||
// would silently discard it, so a container found by name must never be recreated.
|
||||
verify(lifecycleManager, never()).createAndStart(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAdoptOrStartFallsBackToStartWhenNoExistingContainer() {
|
||||
String containerName = "floci-redshift-" + ACCOUNT_ID + "-test-cluster";
|
||||
when(lifecycleManager.findByName(containerName)).thenReturn(Optional.empty());
|
||||
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, org.mockito.Mockito.RETURNS_SELF);
|
||||
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
|
||||
ContainerInfo info = new ContainerInfo("cont-fresh", Map.of(5432, new EndpointInfo("localhost", 5432)));
|
||||
when(lifecycleManager.createAndStart(any())).thenReturn(info);
|
||||
|
||||
RedshiftContainerHandle handle = manager.adoptOrStart(ACCOUNT_ID, "test-cluster", "admin", "pass");
|
||||
|
||||
assertEquals("cont-fresh", handle.getContainerId());
|
||||
verify(lifecycleManager, never()).adopt(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAlterUserPasswordSuccess() throws Exception {
|
||||
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, org.mockito.Mockito.RETURNS_SELF);
|
||||
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
|
||||
ContainerInfo info = new ContainerInfo("cont-123", Map.of(5432, new EndpointInfo("localhost", 5432)));
|
||||
when(lifecycleManager.createAndStart(any())).thenReturn(info);
|
||||
manager.start(ACCOUNT_ID, "test-cluster", "admin", "pass");
|
||||
|
||||
ExecCreateCmd createCmd = mock(ExecCreateCmd.class, org.mockito.Mockito.RETURNS_SELF);
|
||||
ExecCreateCmdResponse createResponse = mock(ExecCreateCmdResponse.class);
|
||||
when(createResponse.getId()).thenReturn("exec-alter");
|
||||
when(createCmd.exec()).thenReturn(createResponse);
|
||||
when(dockerClient.execCreateCmd("cont-123")).thenReturn(createCmd);
|
||||
|
||||
ExecStartCmd startCmd = mock(ExecStartCmd.class);
|
||||
when(startCmd.exec(any())).thenAnswer(invocation -> {
|
||||
@SuppressWarnings("unchecked")
|
||||
ResultCallback.Adapter<Frame> adapter = invocation.getArgument(0);
|
||||
adapter.onComplete();
|
||||
return adapter;
|
||||
});
|
||||
when(dockerClient.execStartCmd("exec-alter")).thenReturn(startCmd);
|
||||
|
||||
InspectExecCmd inspectCmd = mock(InspectExecCmd.class);
|
||||
InspectExecResponse inspectResponse = mock(InspectExecResponse.class);
|
||||
when(inspectResponse.getExitCodeLong()).thenReturn(0L);
|
||||
when(inspectCmd.exec()).thenReturn(inspectResponse);
|
||||
when(dockerClient.inspectExecCmd("exec-alter")).thenReturn(inspectCmd);
|
||||
|
||||
manager.alterUserPassword(ACCOUNT_ID, "test-cluster", "admin", "NewSecret1");
|
||||
|
||||
verify(dockerClient).execCreateCmd("cont-123");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAlterUserPasswordContainerNotFound() {
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
manager.alterUserPassword(ACCOUNT_ID, "non-existent-cluster", "admin", "new-secret"));
|
||||
assertEquals("ClusterNotFound", ex.getErrorCode());
|
||||
assertEquals(404, ex.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAlterUserPasswordInvalidUsername() throws Exception {
|
||||
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, org.mockito.Mockito.RETURNS_SELF);
|
||||
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
|
||||
ContainerInfo info = new ContainerInfo("cont-123", Map.of(5432, new EndpointInfo("localhost", 5432)));
|
||||
when(lifecycleManager.createAndStart(any())).thenReturn(info);
|
||||
manager.start(ACCOUNT_ID, "test-cluster", "admin", "pass");
|
||||
|
||||
// Test SQL injection attempt with semicolon
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
manager.alterUserPassword(ACCOUNT_ID, "test-cluster", "postgres; DROP TABLE some_table; --", "new-secret"));
|
||||
assertEquals("InvalidParameterValue", ex.getErrorCode());
|
||||
assertEquals(400, ex.getHttpStatus());
|
||||
|
||||
// Test SQL injection attempt with space
|
||||
ex = assertThrows(AwsException.class, () ->
|
||||
manager.alterUserPassword(ACCOUNT_ID, "test-cluster", "admin user", "new-secret"));
|
||||
assertEquals("InvalidParameterValue", ex.getErrorCode());
|
||||
assertEquals(400, ex.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAlterUserPasswordInvalidPassword() throws Exception {
|
||||
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, org.mockito.Mockito.RETURNS_SELF);
|
||||
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
|
||||
ContainerInfo info = new ContainerInfo("cont-123", Map.of(5432, new EndpointInfo("localhost", 5432)));
|
||||
when(lifecycleManager.createAndStart(any())).thenReturn(info);
|
||||
manager.start(ACCOUNT_ID, "test-cluster", "admin", "pass");
|
||||
|
||||
// Forbidden characters: ', ", \, / and @ (AWS ModifyCluster rejects the same set)
|
||||
for (String bad : new String[]{"Pass'word1", "Pass\"word1", "Pass\\word1", "Pass/word1", "Pass@word1"}) {
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
manager.alterUserPassword(ACCOUNT_ID, "test-cluster", "admin", bad));
|
||||
assertEquals("InvalidParameterValue", ex.getErrorCode());
|
||||
assertEquals(400, ex.getHttpStatus());
|
||||
}
|
||||
|
||||
// Too short (< 8) and too long (> 64)
|
||||
for (String bad : new String[]{"Ab1cde", "A1" + "a".repeat(63)}) {
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
manager.alterUserPassword(ACCOUNT_ID, "test-cluster", "admin", bad));
|
||||
assertEquals("InvalidParameterValue", ex.getErrorCode());
|
||||
assertEquals(400, ex.getHttpStatus());
|
||||
}
|
||||
|
||||
// Missing a required class: no uppercase, no lowercase, no digit
|
||||
for (String bad : new String[]{"lowercase1", "UPPERCASE1", "NoDigitsHere"}) {
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
manager.alterUserPassword(ACCOUNT_ID, "test-cluster", "admin", bad));
|
||||
assertEquals("InvalidParameterValue", ex.getErrorCode());
|
||||
assertEquals(400, ex.getHttpStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAlterUserPasswordExecFailure() throws Exception {
|
||||
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, org.mockito.Mockito.RETURNS_SELF);
|
||||
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
|
||||
ContainerInfo info = new ContainerInfo("cont-123", Map.of(5432, new EndpointInfo("localhost", 5432)));
|
||||
when(lifecycleManager.createAndStart(any())).thenReturn(info);
|
||||
manager.start(ACCOUNT_ID, "test-cluster", "admin", "pass");
|
||||
|
||||
ExecCreateCmd createCmd = mock(ExecCreateCmd.class, org.mockito.Mockito.RETURNS_SELF);
|
||||
ExecCreateCmdResponse createResponse = mock(ExecCreateCmdResponse.class);
|
||||
when(createResponse.getId()).thenReturn("exec-fail");
|
||||
when(createCmd.exec()).thenReturn(createResponse);
|
||||
when(dockerClient.execCreateCmd("cont-123")).thenReturn(createCmd);
|
||||
|
||||
ExecStartCmd startCmd = mock(ExecStartCmd.class);
|
||||
when(startCmd.exec(any())).thenAnswer(invocation -> {
|
||||
@SuppressWarnings("unchecked")
|
||||
ResultCallback.Adapter<Frame> adapter = invocation.getArgument(0);
|
||||
byte[] err = "ERROR: role \"admin\" does not exist".getBytes(StandardCharsets.UTF_8);
|
||||
adapter.onNext(new Frame(StreamType.STDERR, err));
|
||||
adapter.onComplete();
|
||||
return adapter;
|
||||
});
|
||||
when(dockerClient.execStartCmd("exec-fail")).thenReturn(startCmd);
|
||||
|
||||
InspectExecCmd inspectCmd = mock(InspectExecCmd.class);
|
||||
InspectExecResponse inspectResponse = mock(InspectExecResponse.class);
|
||||
when(inspectResponse.getExitCodeLong()).thenReturn(1L);
|
||||
when(inspectCmd.exec()).thenReturn(inspectResponse);
|
||||
when(dockerClient.inspectExecCmd("exec-fail")).thenReturn(inspectCmd);
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
manager.alterUserPassword(ACCOUNT_ID, "test-cluster", "admin", "NewSecret1"));
|
||||
assertEquals("InternalFailure", ex.getErrorCode());
|
||||
assertEquals(500, ex.getHttpStatus());
|
||||
}
|
||||
}
|
||||
@@ -162,6 +162,10 @@ floci:
|
||||
proxy-base-port: 6400
|
||||
proxy-max-port: 6419
|
||||
default-image: "valkey/valkey:8"
|
||||
redshift:
|
||||
enabled: true
|
||||
default-port: 5439
|
||||
image-version: postgres:15-alpine
|
||||
rds:
|
||||
enabled: true
|
||||
mock: false
|
||||
|
||||
@@ -129,6 +129,13 @@ services:
|
||||
sources:
|
||||
- { path: src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java, mode: switch }
|
||||
exclude_actions: [SubnetIds, VpcSecurityGroupIds, OptionsToRemove]
|
||||
- service: redshift
|
||||
doc: docs/services/redshift.md
|
||||
sources:
|
||||
- { path: src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandler.java, mode: switch }
|
||||
# SubnetIds / VpcSecurityGroupIds / TagKeys are labels of an inner member-name
|
||||
# switch (memberKeyRegex), not actions — same shape as the rds exclusions above.
|
||||
exclude_actions: [SubnetIds, VpcSecurityGroupIds, TagKeys]
|
||||
- service: route53resolver
|
||||
doc: docs/services/route53resolver.md
|
||||
sources:
|
||||
|
||||
Reference in new issue
Block a user