feat(redshift): support pausing and resuming provisioned clusters (#6911)

* feat(redshift): support pausing and resuming provisioned clusters

* docs(redshift): sync supported operation count

* fix(redshift): harden pause and resume failure recovery

* fix(redshift): skip unchanged idle integration writes

* fix: consolidate Redshift pause and resume state persistence
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-29 12:55:50 -04:00
1 parent 85813108c1
commit 1a871392b7
12 files changed
+842 -17

No files matched your search

@@ -16,6 +16,7 @@ import io.github.hectorvent.floci.services.dynamodb.backend.RecordingDynamoDbBac
import io.github.hectorvent.floci.services.dynamodb.backend.RecordingDynamoDbBackend.Invocation;
import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition;
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.services.redshift.model.Integration;
import io.github.hectorvent.floci.services.redshiftdata.RedshiftZeroEtlWriter;
import io.github.hectorvent.floci.testing.ThreadStates;
@@ -69,6 +70,94 @@ class RedshiftDynamoDbZeroEtlConsumerTest {
private static final String SHARD_ID = "shardId-0000000001-00000000001";
@Test
void healthyIdlePollsDoNotRewriteCheckpointState() {
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
RedshiftService service = mock(RedshiftService.class);
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
Integration integration = streamingIntegration();
integration.setStatus("active");
integration.setShardSequenceNumbers(Map.of(SHARD_ID, "s1"));
streams.shard(SHARD_ID, null).add(streamRecord("s1"));
RedshiftDynamoDbZeroEtlConsumer consumer = new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, service, writer);
consumer.pollOnce(integration);
consumer.pollOnce(integration);
verify(service, never()).updateIntegrationRuntime(any(), any(), any(), anyBoolean(), any());
verify(writer, never()).writeBatch(any(), any(), any(), any());
assertEquals(Map.of(SHARD_ID, "s1"), integration.getShardSequenceNumbers());
}
@Test
void pausedClusterSkipsPollingWithoutAdvancingProgressOrFailingIntegration() {
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
RedshiftService service = mock(RedshiftService.class);
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
Integration integration = streamingIntegration();
integration.setStatus("active");
integration.setShardSequenceNumbers(Map.of(SHARD_ID, "s1"));
streams.shard(SHARD_ID, null).addAll(List.of(streamRecord("s1"), streamRecord("s2")));
Cluster cluster = new Cluster();
cluster.setClusterStatus("paused");
when(service.describeClustersForAccount(integration.getAccountId(), "warehouse")).thenReturn(List.of(cluster));
RedshiftDynamoDbZeroEtlConsumer consumer = new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, service, writer);
consumer.pollTask(integration).run();
verifyNoInteractions(writer);
assertTrue(streams.iteratorRequests.isEmpty());
assertEquals(Map.of(SHARD_ID, "s1"), integration.getShardSequenceNumbers());
verify(service, never()).updateIntegrationRuntime(any(), any(), any(), anyBoolean(), any());
cluster.setClusterStatus("available");
consumer.pollOnce(integration);
verify(writer).writeBatch(integration.getAccountId(), "warehouse", "floci_zetl_orders",
List.of(streamRecord("s2").awsRecord()));
assertEquals(Map.of(SHARD_ID, "s2"), integration.getShardSequenceNumbers());
}
@Test
void healthyEmptyPollRecoversFailedIntegrationAfterResume() {
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
RedshiftService service = mock(RedshiftService.class);
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
Integration integration = streamingIntegration();
integration.setStatus("failed");
integration.setLastError("cluster was paused");
integration.setRetryCount(1);
integration.setShardSequenceNumbers(Map.of(SHARD_ID, "s1"));
streams.shard(SHARD_ID, null).add(streamRecord("s1"));
Cluster cluster = new Cluster();
cluster.setClusterStatus("available");
when(service.describeClustersForAccount(integration.getAccountId(), "warehouse")).thenReturn(List.of(cluster));
new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, service, writer).pollOnce(integration);
verify(service).recoverIntegrationRuntime(integration.getAccountId(), integration.getIntegrationArn());
verify(writer, never()).writeBatch(any(), any(), any(), any());
assertEquals(Map.of(SHARD_ID, "s1"), integration.getShardSequenceNumbers());
}
@Test
void pollFailureDuringPauseDoesNotMarkIntegrationFailed() {
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
RedshiftService service = mock(RedshiftService.class);
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
Integration integration = streamingIntegration();
Cluster cluster = new Cluster();
cluster.setClusterStatus("available");
when(service.describeClustersForAccount(integration.getAccountId(), "warehouse")).thenReturn(List.of(cluster));
doAnswer(invocation -> {
cluster.setClusterStatus("paused");
throw new AwsException("InternalFailure", "database stopped during poll", 500);
}).when(writer).createLandingTable(any(), any(), any());
new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, service, writer).pollTask(integration).run();
verify(service, never()).updateIntegrationRuntime(any(), any(), any(), anyBoolean(), any());
assertTrue(integration.getShardSequenceNumbers().isEmpty());
}
/**
* Serves shards from memory the way the native engine does. A cursor is the sequence to read
* after, or empty for the trim horizon, a sequence older than the oldest retained record is
@@ -0,0 +1,79 @@
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.github.hectorvent.floci.services.redshift.proxy.RedshiftProxyManager;
import io.quarkus.test.InjectMock;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.redshift.RedshiftClient;
import software.amazon.awssdk.services.redshift.model.Cluster;
import software.amazon.awssdk.services.redshift.model.ClusterNotFoundException;
import software.amazon.awssdk.services.redshift.model.InvalidClusterStateException;
import java.net.URI;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
@QuarkusTest
class RedshiftPauseResumeIntegrationTest {
@TestHTTPResource
URI endpoint;
@InjectMock
RedshiftContainerManager containers;
@InjectMock
RedshiftProxyManager proxies;
@Test
void sdkRoundTripsPauseResumeAndAwsErrors() {
String identifier = "pause-" + UUID.randomUUID().toString().substring(0, 8);
RedshiftContainerHandle handle = new RedshiftContainerHandle("original", identifier, "localhost", 5432);
when(containers.start(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
.thenReturn(handle);
when(containers.resume(anyString(), anyString(), anyString(), anyString())).thenReturn(handle);
try (RedshiftClient client = client()) {
Cluster original = client.createCluster(request -> request.clusterIdentifier(identifier)
.nodeType("dc2.large").masterUsername("admin").masterUserPassword("Secret123")).cluster();
try {
assertThrows(InvalidClusterStateException.class,
() -> client.resumeCluster(request -> request.clusterIdentifier(identifier)));
Cluster paused = client.pauseCluster(request -> request.clusterIdentifier(identifier)).cluster();
assertEquals("paused", paused.clusterStatus());
assertEquals(original.clusterIdentifier(), paused.clusterIdentifier());
assertEquals(original.endpoint(), paused.endpoint());
assertEquals("paused", client.describeClusters(request -> request.clusterIdentifier(identifier))
.clusters().getFirst().clusterStatus());
assertThrows(InvalidClusterStateException.class,
() -> client.pauseCluster(request -> request.clusterIdentifier(identifier)));
Cluster resumed = client.resumeCluster(request -> request.clusterIdentifier(identifier)).cluster();
assertEquals("available", resumed.clusterStatus());
assertEquals(original.endpoint(), resumed.endpoint());
assertEquals(original.clusterNamespaceArn(), resumed.clusterNamespaceArn());
client.pauseCluster(request -> request.clusterIdentifier(identifier));
} finally {
client.deleteCluster(request -> request.clusterIdentifier(identifier).skipFinalClusterSnapshot(true));
}
assertEquals(404, assertThrows(ClusterNotFoundException.class,
() -> client.pauseCluster(request -> request.clusterIdentifier(identifier))).statusCode());
assertEquals(404, assertThrows(ClusterNotFoundException.class,
() -> client.resumeCluster(request -> request.clusterIdentifier(identifier))).statusCode());
}
}
private RedshiftClient client() {
return RedshiftClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test")))
.build();
}
}
@@ -70,6 +70,38 @@ class RedshiftProxyIntegrationTest {
}
}
@Test
void pauseResumePreservesSqlAndProxyAuthentication() throws SQLException {
clusterId = "it-pause-resume";
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123");
int port = cluster.getEndpoint().getPort();
try (Connection connection = waitForConnection(cluster, "admin", "Secret123");
Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE pause_data (value integer)");
statement.execute("INSERT INTO pause_data VALUES (42)");
statement.execute("CREATE VIEW pause_catalog_view AS SELECT * FROM pg_table_def");
assertEquals("paused", service.pauseCluster(clusterId).getClusterStatus());
assertThrows(SQLException.class, () -> statement.executeQuery("SELECT 1"));
}
assertThrows(SQLException.class,
() -> DriverManager.getConnection(jdbcUrl(cluster), "admin", "Secret123"));
assertEquals("available", service.resumeCluster(clusterId).getClusterStatus());
assertEquals(port, cluster.getEndpoint().getPort());
try (Connection connection = waitForConnection(cluster, "admin", "Secret123");
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery("SELECT value FROM pause_data")) {
assertTrue(result.next());
assertEquals(42, result.getInt(1));
}
try (Connection connection = waitForConnection(cluster, "admin", "Secret123");
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery("SELECT count(*) FROM pause_catalog_view")) {
assertTrue(result.next());
}
assertThrows(SQLException.class,
() -> DriverManager.getConnection(jdbcUrl(cluster), "admin", "wrong-password"));
}
@Test
void rejectsAWrongPasswordAtTheProxy() throws SQLException {
clusterId = "it-proxy-badpass";
@@ -35,6 +35,37 @@ import static org.mockito.Mockito.*;
class RedshiftQueryHandlerTest {
@Test
void pauseAndResumeRequireClusterIdentifier() {
for (String action : List.of("PauseCluster", "ResumeCluster")) {
AwsException error = assertThrows(AwsException.class,
() -> handler.handle(action, new MultivaluedHashMap<>()));
assertEquals("InvalidParameterValue", error.getErrorCode());
}
verifyNoInteractions(service);
}
@Test
void pauseAndResumeUseAwsQueryClusterWrappersAndNamespace() {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("warehouse");
cluster.setClusterStatus("paused");
when(service.pauseCluster("warehouse")).thenReturn(cluster);
when(service.resumeCluster("warehouse")).thenReturn(cluster);
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ClusterIdentifier", "warehouse");
for (String action : List.of("PauseCluster", "ResumeCluster")) {
Response response = handler.handle(action, params);
assertEquals(200, response.getStatus());
String xml = response.getEntity().toString();
assertTrue(xml.contains("<" + action + "Response xmlns=\"" + AwsNamespaces.REDSHIFT + "\">"));
assertTrue(xml.contains("<" + action + "Result><Cluster>"));
assertTrue(xml.contains("<ClusterIdentifier>warehouse</ClusterIdentifier>"));
}
verify(service).pauseCluster("warehouse");
verify(service).resumeCluster("warehouse");
}
@Test
void eventSubscriptionResponsesUseTheRedshiftNamespace() {
EventSubscription subscription = new EventSubscription();
@@ -71,6 +71,288 @@ import static org.mockito.Mockito.*;
class RedshiftServiceTest {
@Test
void pauseAndResumePreserveEndpointAndReservePort() {
Cluster cluster = lifecycleCluster("available");
Endpoint original = cluster.getEndpoint();
service.reserveProxyPort(7107);
when(cm.resume("111111111111", "warehouse", "admin", "dev"))
.thenReturn(new RedshiftContainerHandle("original", "warehouse", "backend", 5433));
assertSame(cluster, service.pauseCluster("warehouse"));
assertEquals("paused", cluster.getClusterStatus());
assertNull(cluster.getContainerHost());
assertEquals(0, cluster.getContainerPort());
assertFalse(service.reserveProxyPort(7107));
InOrder order = inOrder(proxyManager, cm);
order.verify(proxyManager).stopProxy("111111111111:warehouse");
order.verify(cm).pause("111111111111", "warehouse");
assertSame(cluster, service.resumeCluster("warehouse"));
assertEquals("available", cluster.getClusterStatus());
assertEquals(original.getAddress(), cluster.getEndpoint().getAddress());
assertEquals(original.getPort(), cluster.getEndpoint().getPort());
assertEquals(5433, cluster.getContainerPort());
order.verify(cm).resume("111111111111", "warehouse", "admin", "dev");
order.verify(proxyManager).startProxy(eq("111111111111:warehouse"), eq(7107),
eq("backend"), eq(5433), eq("localhost"), eq("admin"), eq("Secret123"), eq("dev"),
any(), anyList(), isNull());
verify(cm, never()).stop(anyString(), anyString());
}
@ParameterizedTest
@ValueSource(strings = {"creating", "deleting", "failed", "unavailable", "pausing", "resuming"})
void pauseAndResumeRejectInvalidStates(String state) {
lifecycleCluster(state);
assertEquals("InvalidClusterState", assertThrows(AwsException.class,
() -> service.pauseCluster("warehouse")).getErrorCode());
assertEquals("InvalidClusterState", assertThrows(AwsException.class,
() -> service.resumeCluster("warehouse")).getErrorCode());
verifyNoInteractions(cm, proxyManager);
}
@Test
void pauseAndResumeRejectMissingClusterAndRepeatedOperations() {
assertEquals("ClusterNotFound", assertThrows(AwsException.class,
() -> service.pauseCluster("missing")).getErrorCode());
assertEquals("ClusterNotFound", assertThrows(AwsException.class,
() -> service.resumeCluster("missing")).getErrorCode());
Cluster cluster = lifecycleCluster("paused");
assertEquals("InvalidClusterState", assertThrows(AwsException.class,
() -> service.pauseCluster("warehouse")).getErrorCode());
cluster.setClusterStatus("available");
assertEquals("InvalidClusterState", assertThrows(AwsException.class,
() -> service.resumeCluster("warehouse")).getErrorCode());
}
@Test
void pauseProxyFailurePreservesDatabaseAndMarksUnavailable() {
Cluster cluster = lifecycleCluster("available");
doThrow(new IllegalStateException("close failed")).when(proxyManager)
.stopProxy("111111111111:warehouse");
assertEquals("InternalFailure", assertThrows(AwsException.class,
() -> service.pauseCluster("warehouse")).getErrorCode());
assertEquals("unavailable", cluster.getClusterStatus());
assertNull(cluster.getContainerHost());
assertEquals(0, cluster.getContainerPort());
verify(clusterBackend).put("warehouse", cluster);
verify(clusterBackend).flush();
verifyNoInteractions(cm);
}
@Test
void resumeRollbackStopsDatabaseEvenWhenProxyCleanupFails() {
Cluster cluster = lifecycleCluster("paused");
service.reserveProxyPort(7107);
when(cm.resume("111111111111", "warehouse", "admin", "dev"))
.thenReturn(new RedshiftContainerHandle("original", "warehouse", "backend", 5432));
doThrow(new IllegalStateException("proxy start failed")).when(proxyManager).startProxy(
anyString(), anyInt(), anyString(), anyInt(), anyString(), anyString(), anyString(), anyString(),
any(), anyList(), isNull());
doThrow(new IllegalStateException("proxy close failed")).when(proxyManager)
.stopProxy("111111111111:warehouse");
assertThrows(AwsException.class, () -> service.resumeCluster("warehouse"));
verify(cm).pause("111111111111", "warehouse");
verify(cm, never()).stop(anyString(), anyString());
assertEquals("unavailable", cluster.getClusterStatus());
assertNull(cluster.getContainerHost());
assertEquals(0, cluster.getContainerPort());
assertFalse(service.reserveProxyPort(7107));
}
@Test
void pollingFailureReportedAfterPauseDoesNotFailIntegration() {
Cluster cluster = lifecycleCluster("paused");
when(clusterBackend.getForAccount("111111111111", "warehouse")).thenReturn(Optional.of(cluster));
Integration integration = new Integration();
integration.setIntegrationArn("arn:aws:redshift:us-east-1:111111111111:integration:one");
integration.setTargetClusterIdentifier("warehouse");
integration.setStatus("active");
when(integrationBackend.keysForAccount("111111111111")).thenReturn(Set.of("one"));
when(integrationBackend.getForAccount("111111111111", "one")).thenReturn(Optional.of(integration));
service.updateIntegrationRuntime("111111111111", integration.getIntegrationArn(), Map.of(), false, "database stopped");
assertEquals("active", integration.getStatus());
assertEquals(0, integration.getRetryCount());
assertNull(integration.getLastError());
verify(integrationBackend, never()).putForAccount(anyString(), anyString(), any());
cluster.setClusterStatus("available");
service.updateIntegrationRuntime("111111111111", integration.getIntegrationArn(), Map.of(), false, "genuine failure");
assertEquals("failed", integration.getStatus());
assertEquals(1, integration.getRetryCount());
assertEquals("genuine failure", integration.getLastError());
}
@Test
void idleRecoveryDoesNotRewriteHealthyIntegration() {
Integration integration = storedIntegrationForIdleRecovery();
service.recoverIntegrationRuntime("111111111111", integration.getIntegrationArn());
service.recoverIntegrationRuntime("111111111111", integration.getIntegrationArn());
verify(integrationBackend, never()).putForAccount(anyString(), anyString(), any());
verify(integrationEvents, never()).queue(any(), any(), any(), any());
assertEquals(Map.of("shard", "s1"), integration.getShardSequenceNumbers());
}
@ParameterizedTest
@ValueSource(strings = {"status", "retryCount", "lastError"})
void idleRecoveryPersistsOnlyChangedHealthFieldsAndKeepsCheckpoints(String field) {
Integration integration = storedIntegrationForIdleRecovery();
switch (field) {
case "status" -> integration.setStatus("failed");
case "retryCount" -> integration.setRetryCount(2);
case "lastError" -> integration.setLastError("transient failure");
default -> throw new IllegalArgumentException(field);
}
Map<String, String> checkpoints = integration.getShardSequenceNumbers();
service.recoverIntegrationRuntime("111111111111", integration.getIntegrationArn());
service.recoverIntegrationRuntime("111111111111", integration.getIntegrationArn());
assertEquals("active", integration.getStatus());
assertEquals(0, integration.getRetryCount());
assertNull(integration.getLastError());
assertSame(checkpoints, integration.getShardSequenceNumbers());
assertEquals(Map.of("shard", "s1"), checkpoints);
verify(integrationBackend).putForAccount("111111111111", "one", integration);
}
@Test
void successfulBatchPersistsCheckpointEvenWhenStoredMapWasMutated() {
Integration integration = storedIntegrationForIdleRecovery();
integration.getShardSequenceNumbers().put("shard", "s2");
service.updateIntegrationRuntime("111111111111", integration.getIntegrationArn(),
integration.getShardSequenceNumbers(), true, null);
verify(integrationBackend).putForAccount("111111111111", "one", integration);
assertEquals(Map.of("shard", "s2"), integration.getShardSequenceNumbers());
}
private Integration storedIntegrationForIdleRecovery() {
Integration integration = new Integration();
integration.setIntegrationArn("arn:aws:redshift:us-east-1:111111111111:integration:one");
integration.setStatus("active");
integration.setShardSequenceNumbers(Map.of("shard", "s1"));
when(integrationBackend.keysForAccount("111111111111")).thenReturn(Set.of("one"));
when(integrationBackend.getForAccount("111111111111", "one")).thenReturn(Optional.of(integration));
return integration;
}
@Test
void pauseContainerFailureRestoresTheOriginalRuntime() {
Cluster cluster = lifecycleCluster("available");
doThrow(new IllegalStateException("stop failed")).when(cm).pause("111111111111", "warehouse");
when(cm.resume("111111111111", "warehouse", "admin", "dev"))
.thenReturn(new RedshiftContainerHandle("original", "warehouse", "backend", 5432));
assertThrows(AwsException.class, () -> service.pauseCluster("warehouse"));
assertEquals("available", cluster.getClusterStatus());
verify(proxyManager).startProxy(anyString(), eq(7107), eq("backend"), eq(5432), anyString(),
eq("admin"), eq("Secret123"), eq("dev"), any(), anyList(), isNull());
verify(cm, never()).stop(anyString(), anyString());
}
@Test
void failedPauseRestorationRetainsDataAndMarksUnavailable() {
Cluster cluster = lifecycleCluster("available");
doThrow(new IllegalStateException("stop failed")).when(cm).pause("111111111111", "warehouse");
when(cm.resume("111111111111", "warehouse", "admin", "dev"))
.thenThrow(new IllegalStateException("restart failed"));
assertThrows(AwsException.class, () -> service.pauseCluster("warehouse"));
assertEquals("unavailable", cluster.getClusterStatus());
assertNull(cluster.getContainerHost());
assertEquals(0, cluster.getContainerPort());
verify(cm, never()).stop(anyString(), anyString());
}
@Test
void failedResumeRollbackRetainsDataAndMarksUnavailable() {
Cluster cluster = lifecycleCluster("paused");
service.reserveProxyPort(7107);
when(cm.resume("111111111111", "warehouse", "admin", "dev"))
.thenThrow(new IllegalStateException("readiness failed"));
doThrow(new IllegalStateException("stop failed")).when(cm).pause("111111111111", "warehouse");
assertThrows(AwsException.class, () -> service.resumeCluster("warehouse"));
assertEquals("unavailable", cluster.getClusterStatus());
assertFalse(service.reserveProxyPort(7107));
verify(cm, never()).stop(anyString(), anyString());
}
@Test
void pauseRejectsClustersWithAutomatedSnapshotsDisabled() {
Cluster cluster = lifecycleCluster("available");
cluster.setAutomatedSnapshotRetentionPeriod(0);
assertEquals("InvalidClusterState", assertThrows(AwsException.class,
() -> service.pauseCluster("warehouse")).getErrorCode());
verifyNoInteractions(cm, proxyManager);
}
@Test
void failedResumeKeepsDataAndCanBeRetried() {
Cluster cluster = lifecycleCluster("paused");
when(cm.resume("111111111111", "warehouse", "admin", "dev"))
.thenReturn(new RedshiftContainerHandle("original", "warehouse", "backend", 5432));
doThrow(new IllegalStateException("bind failed")).doNothing().when(proxyManager).startProxy(
anyString(), anyInt(), anyString(), anyInt(), anyString(), anyString(), anyString(), anyString(),
any(), anyList(), isNull());
assertThrows(AwsException.class, () -> service.resumeCluster("warehouse"));
assertEquals("paused", cluster.getClusterStatus());
verify(cm).pause("111111111111", "warehouse");
verify(cm, never()).stop(anyString(), anyString());
assertEquals("available", service.resumeCluster("warehouse").getClusterStatus());
}
@Test
void startupReservesPausedPortsWithoutStartingTheirRuntime() {
Cluster cluster = lifecycleCluster("paused");
when(clusterBackend.scanAllAccountEntries(any())).thenReturn(List.of(
new AccountAwareStorageBackend.AccountEntry<>("111111111111", "warehouse", cluster)));
service.onStart(null);
assertFalse(service.reserveProxyPort(7107));
assertEquals("paused", cluster.getClusterStatus());
verifyNoInteractions(cm, proxyManager);
}
@Test
void deletingAPausedClusterRemovesContainerAndReleasesPort() {
lifecycleCluster("paused");
service.reserveProxyPort(7107);
service.deleteCluster("warehouse");
verify(cm).stop("111111111111", "warehouse");
verify(clusterBackend).delete("warehouse");
assertTrue(service.reserveProxyPort(7107));
}
@Test
void pausedClusterCannotRebootOrCreateSnapshot() {
lifecycleCluster("paused");
assertEquals("InvalidClusterState", assertThrows(AwsException.class,
() -> service.rebootCluster("warehouse")).getErrorCode());
assertEquals("InvalidClusterState", assertThrows(AwsException.class,
() -> service.createSnapshot("paused-backup", "warehouse")).getErrorCode());
assertEquals("InvalidClusterState", assertThrows(AwsException.class,
() -> service.modifyCluster("warehouse", null, null, "Changed123", null, null)).getErrorCode());
verifyNoInteractions(cm);
}
private Cluster lifecycleCluster(String status) {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("warehouse");
cluster.setMasterUsername("admin");
cluster.setMasterPassword("Secret123");
cluster.setClusterStatus(status);
cluster.setProxyPort(7107);
cluster.setContainerHost("backend");
cluster.setContainerPort(5432);
cluster.setEndpoint(new Endpoint("localhost", 7107));
when(clusterBackend.get("warehouse")).thenReturn(Optional.of(cluster));
return cluster;
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void loggingDestinationRegionSurvivesStorageAndRestart(boolean refresh) throws Exception {
@@ -9,6 +9,7 @@ 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.command.StopContainerCmd;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.StreamType;
@@ -64,6 +65,49 @@ import static org.mockito.Mockito.when;
class RedshiftContainerManagerTest {
@Test
void pauseStopsButNeverRemovesTheDataBearingContainer() {
StopContainerCmd command = mock(StopContainerCmd.class, RETURNS_SELF);
when(dockerClient.stopContainerCmd("floci-aws-redshift-" + ACCOUNT_ID + "-warehouse"))
.thenReturn(command);
manager.pause(ACCOUNT_ID, "warehouse");
verify(command).withTimeout(30);
verify(command).exec();
verify(lifecycleManager, never()).removeIfExistsStrict(anyString(), eq(true));
}
@Test
void pausePropagatesDockerFailure() {
StopContainerCmd command = mock(StopContainerCmd.class, RETURNS_SELF);
when(dockerClient.stopContainerCmd(anyString())).thenReturn(command);
doThrow(new IllegalStateException("daemon unavailable")).when(command).exec();
assertThrows(IllegalStateException.class, () -> manager.pause(ACCOUNT_ID, "warehouse"));
}
@Test
void resumeNeverReplacesAMissingContainerWithAnEmptyDatabase() {
when(lifecycleManager.findByName(anyString())).thenReturn(Optional.empty());
assertThrows(AwsException.class, () -> manager.resume(ACCOUNT_ID, "warehouse", "admin", "dev"));
verify(lifecycleManager, never()).createAndStartEphemeral(any());
}
@Test
void resumeAdoptsTheSameContainerAndRefreshesItsBackendEndpoint() {
Container existing = mock(Container.class);
when(existing.getId()).thenReturn("original");
when(lifecycleManager.findByName(anyString())).thenReturn(Optional.of(existing));
when(lifecycleManager.adopt(eq("original"), eq(List.of(5432)), any())).thenReturn(
new ContainerInfo("original", Map.of(5432, new EndpointInfo("new-host", 5433))));
RedshiftContainerHandle handle = manager.resume(ACCOUNT_ID, "warehouse", "admin", "dev");
assertEquals("original", handle.getContainerId());
assertEquals("new-host", handle.getHost());
assertEquals(5433, handle.getPort());
verify(dockerClient, never()).copyArchiveToContainerCmd(anyString());
verify(lifecycleManager, never()).createAndStartEphemeral(any());
}
@ParameterizedTest
@ValueSource(strings = {"adopt", "readiness", "proxy"})
void startupRollbackPreservesAdoptedDataAndExplicitStopStillRemovesIt(String failureStage) throws IOException {