diff --git a/docs/services/index.md b/docs/services/index.md index 3fb5d86fec..cb1b945cd8 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -76,7 +76,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [Neptune](neptune.md) | `POST /` with `Action=` param + Gremlin TCP proxy | Query + WebSocket | 14 | | [DocumentDB](docdb.md) | `POST /` with `Action=` param + MongoDB container | Query + MongoDB wire | 13 | | [DMS](dms.md) | `POST /` + `X-Amz-Target: AmazonDMSv20160101.*` | JSON 1.1 | 20 | -| [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire (+ CFN) | 50 | +| [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire (+ CFN) | 52 | | [Redshift Data API](redshift-data.md) | `POST /` + `X-Amz-Target: RedshiftData.*` | JSON 1.1 | 12 | | [Redshift Serverless](redshift-serverless.md) | `POST /` + `X-Amz-Target: RedshiftServerless.*` | JSON 1.1 | 55 | | [EMR](emr.md) | `POST /` + `X-Amz-Target: ElasticMapReduce.*` | JSON 1.1 | 40 | diff --git a/docs/services/redshift.md b/docs/services/redshift.md index dd1503c952..c7bcd6ce10 100644 --- a/docs/services/redshift.md +++ b/docs/services/redshift.md @@ -14,6 +14,45 @@ Snapshot-dump and catalog-seed uploads retry transient Docker I/O failures for u For running SQL without a PostgreSQL wire connection (the way Lambda and Step Functions do), see the [Redshift Data API](redshift-data.md). +## Pausing and resuming provisioned clusters + +`PauseCluster` accepts an `available` cluster and returns it as `paused`. +It closes the auth proxy and stops PostgreSQL without removing the container or its +data volume. Existing SQL connections are disconnected. `ResumeCluster` accepts a +`paused` cluster, starts the same container, waits for PostgreSQL readiness, and +restores the auth proxy with the same endpoint and authentication settings. +Both operations complete synchronously in Floci. Repeating either operation in the +wrong state returns `InvalidClusterState`; an unknown identifier returns `ClusterNotFound`. +Clusters with automated snapshots disabled cannot be paused. Resume the cluster +before modifying it, rebooting it, or creating a snapshot. + +Floci preserves the original container directly instead of creating an additional +automated snapshot for pause. It retains all user tables and views, including +no-backup tables, and does not simulate maintenance-version upgrades on resume. + +The proxy port remains reserved while paused, including after a Floci restart with +persistent cluster metadata. Startup leaves paused clusters stopped. Resume requires +the original container to still exist: if it was removed externally, Floci returns +an error instead of creating an empty replacement database. A failed resume attempts +to stop the container again so it can be retried. If that rollback also fails, the +cluster is marked `unavailable` and its data-bearing container is retained. +Failure to close the proxy during pause also marks the cluster `unavailable`, +because its listener may have partially stopped. Resume rollback attempts proxy +shutdown and database shutdown independently and keeps the proxy port reserved. +Delete a paused cluster with `SkipFinalClusterSnapshot=true`, or resume it before +requesting a final snapshot. + +Zero-ETL polling skips paused targets without consuming stream records or changing +their checkpoints. Polling continues after resume; a healthy poll clears an earlier +integration failure even when the stream has no new records. +Healthy idle polls do not rewrite integration state; recovery persists only changed +health fields and retains the stored stream checkpoints. + +```bash +aws --endpoint-url http://localhost:4566 redshift pause-cluster --cluster-identifier warehouse +aws --endpoint-url http://localhost:4566 redshift resume-cluster --cluster-identifier warehouse +``` + ## Events and notifications `DescribeEvents` returns the last hour by default, accepts `StartTime`, `EndTime`, @@ -131,6 +170,8 @@ The attributes follow the [CloudFormation resource schema](https://docs.aws.amaz | `DescribeLoggingStatus` | Return a cluster's stored audit-logging configuration | | `EnableLogging` | Store audit-logging configuration and deliver the selected connection, user, and user-activity audit records to CloudWatch Logs for provisioned clusters | | `DisableLogging` | Clear a cluster's audit-logging configuration | +| `PauseCluster` | Stop a provisioned cluster and its auth proxy while retaining the container and data | +| `ResumeCluster` | Restart a paused cluster and restore its auth proxy on the same endpoint | | `RebootCluster` | Restart a cluster's container | | `GetClusterCredentials` | Issue a short-lived DbUser / DbPassword pair the auth proxy and Data API accept for a non-master user | | `GetClusterCredentialsWithIAM` | Issue short-lived credentials with the DbUser derived from the caller's IAM identity | diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftDynamoDbZeroEtlConsumer.java b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftDynamoDbZeroEtlConsumer.java index 45c291fb1a..6dced63c57 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftDynamoDbZeroEtlConsumer.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftDynamoDbZeroEtlConsumer.java @@ -134,6 +134,9 @@ public class RedshiftDynamoDbZeroEtlConsumer implements Resettable { } private void poll(Integration integration) { + if (targetPaused(integration)) { + return; + } writer.createLandingTable(integration.getAccountId(), integration.getTargetClusterIdentifier(), integration.getLandingTableName()); if (!integration.isBackfillCompleted()) { @@ -145,8 +148,28 @@ public class RedshiftDynamoDbZeroEtlConsumer implements Resettable { ignored -> ConcurrentHashMap.newKeySet()); // ponytail: a shard whose read or write throws ends the tick for the shards after it; the next // tick starts over from committed progress, so it only delays them. + boolean checkpointPersisted = false; for (DynamoDbStreamReader.Shard shard : DynamoDbStreamReader.readable(streamReader.shards(stream), finished)) { - pollShard(integration, stream, shard.shardId(), finished); + if (pollShard(integration, stream, shard.shardId(), finished)) { + checkpointPersisted = true; + } + } + if (!checkpointPersisted) { + redshiftService.recoverIntegrationRuntime(integration.getAccountId(), integration.getIntegrationArn()); + } + } + + private boolean targetPaused(Integration integration) { + try { + return redshiftService.describeClustersForAccount(integration.getAccountId(), + integration.getTargetClusterIdentifier()).stream() + .anyMatch(cluster -> "paused".equals(cluster.getClusterStatus())); + } catch (AwsException expected) { + if (!"ClusterNotFound".equals(expected.getErrorCode())) { + throw expected; + } + // A missing target is a polling failure, not an intentional pause; let the writer report it. + return false; } } @@ -154,7 +177,7 @@ public class RedshiftDynamoDbZeroEtlConsumer implements Resettable { * Writes one batch after the shard's committed sequence and commits it only once written, so a * failed write is read and written again next poll. */ - private void pollShard(Integration integration, DynamoDbStreamReader.Stream stream, String shardId, + private boolean pollShard(Integration integration, DynamoDbStreamReader.Stream stream, String shardId, Set finished) { Map committed = integration.getShardSequenceNumbers(); DynamoDbStreamReader.RecordsPage page; @@ -171,7 +194,7 @@ public class RedshiftDynamoDbZeroEtlConsumer implements Resettable { if (page.closed()) { finished.add(shardId); } - return; + return false; } writer.writeBatch(integration.getAccountId(), integration.getTargetClusterIdentifier(), integration.getLandingTableName(), @@ -179,6 +202,7 @@ public class RedshiftDynamoDbZeroEtlConsumer implements Resettable { committed.put(shardId, records.get(records.size() - 1).sequenceNumber()); redshiftService.updateIntegrationRuntime(integration.getAccountId(), integration.getIntegrationArn(), committed, true, null); + return true; } private void pollBackfillPage(Integration integration) { @@ -351,10 +375,14 @@ public class RedshiftDynamoDbZeroEtlConsumer implements Resettable { try { unlessQuiesced(submittedAt, () -> poll(integration)); } catch (Exception e) { - LOG.warnv(e, "Zero-ETL polling failed for integration {0}", integration.getIntegrationArn()); try { - unlessQuiesced(submittedAt, () -> redshiftService.updateIntegrationRuntime(integration.getAccountId(), - integration.getIntegrationArn(), integration.getShardSequenceNumbers(), false, e.getMessage())); + unlessQuiesced(submittedAt, () -> { + if (!targetPaused(integration)) { + LOG.warnv(e, "Zero-ETL polling failed for integration {0}", integration.getIntegrationArn()); + redshiftService.updateIntegrationRuntime(integration.getAccountId(), integration.getIntegrationArn(), + integration.getShardSequenceNumbers(), false, e.getMessage()); + } + }); } catch (Exception updateError) { LOG.warnv(updateError, "Could not persist zero-ETL failure for integration {0}", integration.getIntegrationArn()); diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandler.java index 79f63aa3cf..a5925b7c4d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandler.java @@ -924,6 +924,22 @@ public class RedshiftQueryHandler { String clusterIdentifier = requireParam(params, "ClusterIdentifier"); return loggingStatusResponse(action, service.disableLogging(clusterIdentifier)); } + case "PauseCluster", "ResumeCluster" -> { + String clusterIdentifier = requireParam(params, "ClusterIdentifier"); + Cluster cluster = "PauseCluster".equals(action) + ? service.pauseCluster(clusterIdentifier) : service.resumeCluster(clusterIdentifier); + String xml = new XmlBuilder() + .start(action + "Response", AwsNamespaces.REDSHIFT) + .start(action + "Result") + .raw(buildClusterXml(cluster)) + .end(action + "Result") + .start("ResponseMetadata") + .elem("RequestId", "test-req-id") + .end("ResponseMetadata") + .end(action + "Response") + .build(); + return Response.ok(xml).type(MediaType.APPLICATION_XML).build(); + } case "RebootCluster" -> { String clusterIdentifier = params.getFirst("ClusterIdentifier"); if (clusterIdentifier == null || clusterIdentifier.isBlank()) { diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.java b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.java index 6b487bc5e7..672b7d1602 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.java @@ -249,8 +249,15 @@ public class RedshiftService implements ManagedSecretRotator { // Recreate Docker containers for persisted clusters on app restart (across every account, not just default) void onStart(@Observes StartupEvent event) { + List> persistedClusters = + clusters.scanAllAccountEntries(k -> true); + for (AccountAwareStorageBackend.AccountEntry entry : persistedClusters) { + if (entry.value().getProxyPort() > 0) { + usedPorts.add(entry.value().getProxyPort()); + } + } List> availableClusters = - clusters.scanAllAccountEntries(k -> true).stream() + persistedClusters.stream() .filter(entry -> "available".equals(entry.value().getClusterStatus())) .toList(); for (AccountAwareStorageBackend.AccountEntry entry : availableClusters) { @@ -697,22 +704,39 @@ public class RedshiftService implements ManagedSecretRotator { public void updateIntegrationRuntime(String accountId, String integrationArn, Map shardSequenceNumbers, boolean successful, String error) { - updateIntegrationRuntimeLocked(accountId, integrationArn, shardSequenceNumbers, successful, error); + updateIntegrationRuntimeLocked(accountId, integrationArn, shardSequenceNumbers, successful, error, false); + publishIntegrationEvents(); + } + + /** Recovers idle polling health without replacing checkpoints or persisting unchanged state. */ + public void recoverIntegrationRuntime(String accountId, String integrationArn) { + updateIntegrationRuntimeLocked(accountId, integrationArn, null, true, null, true); publishIntegrationEvents(); } private synchronized void updateIntegrationRuntimeLocked(String accountId, String integrationArn, Map shardSequenceNumbers, - boolean successful, String error) { + boolean successful, String error, boolean recoveryOnly) { for (String key : integrations.keysForAccount(accountId)) { Optional stored = integrations.getForAccount(accountId, key); if (stored.isEmpty() || !integrationArn.equals(stored.get().getIntegrationArn())) { continue; } Integration integration = stored.get(); + String targetIdentifier = integration.getTargetClusterIdentifier(); + if (!successful && targetIdentifier != null && clusters.getForAccount(accountId, targetIdentifier) + .filter(cluster -> "paused".equals(cluster.getClusterStatus())).isPresent()) { + return; + } String previousStatus = integration.getStatus(); + if (recoveryOnly && "active".equals(previousStatus) + && integration.getRetryCount() == 0 && integration.getLastError() == null) { + return; + } if (successful) { - integration.setShardSequenceNumbers(shardSequenceNumbers); + if (!recoveryOnly) { + integration.setShardSequenceNumbers(shardSequenceNumbers); + } integration.setRetryCount(0); integration.setLastError(null); integration.setStatus("active"); @@ -1004,6 +1028,7 @@ public class RedshiftService implements ManagedSecretRotator { Integer automatedRetention) { Cluster cluster = clusters.get(clusterIdentifier) .orElseThrow(() -> new AwsException("ClusterNotFound", "Cluster " + clusterIdentifier + " not found", 404)); + rejectPausedCluster(cluster); validateAutomatedRetention(nodeType == null ? cluster.getNodeType() : nodeType, automatedRetention == null ? cluster.getAutomatedSnapshotRetentionPeriod() : automatedRetention); @@ -1314,6 +1339,126 @@ public class RedshiftService implements ManagedSecretRotator { return cluster; } + public Cluster pauseCluster(String clusterIdentifier) { + return mutateCluster(clusterIdentifier, () -> { + Cluster cluster = clusterInState(clusterIdentifier, "available"); + if (cluster.getAutomatedSnapshotRetentionPeriod() == 0) { + throw new AwsException("InvalidClusterState", + "Clusters with automated snapshots disabled cannot be paused", 400); + } + String accountId = clusters.accountId(); + try { + proxyManager.stopProxy(relayKey(accountId, clusterIdentifier)); + } catch (RuntimeException failure) { + LOG.warnv(failure, "Failed to stop auth proxy while pausing cluster {0}", clusterIdentifier); + persistClusterWithoutBackend(cluster, "unavailable"); + throw new AwsException("InternalFailure", "Failed to stop auth proxy for cluster " + + clusterIdentifier, 500); + } + try { + containerManager.pause(accountId, clusterIdentifier); + persistClusterWithoutBackend(cluster, "paused"); + return cluster; + } catch (RuntimeException failure) { + boolean restored = false; + try { + RedshiftContainerHandle handle = containerManager.resume(accountId, clusterIdentifier, + cluster.getMasterUsername(), CLUSTER_DB_NAME); + startResumedProxy(accountId, cluster, handle); + cluster.setClusterStatus("available"); + restored = true; + } catch (RuntimeException rollbackFailure) { + LOG.warnv(rollbackFailure, "Failed to restore cluster {0} after unsuccessful pause", clusterIdentifier); + } + if (restored) { + clusters.put(clusterIdentifier, cluster); + clusters.flush(); + } else { + persistClusterWithoutBackend(cluster, "unavailable"); + } + LOG.warnv(failure, "Failed to pause Redshift cluster {0}", clusterIdentifier); + throw new AwsException("InternalFailure", "Failed to pause cluster " + clusterIdentifier, 500); + } + }); + } + + public Cluster resumeCluster(String clusterIdentifier) { + return mutateCluster(clusterIdentifier, () -> { + Cluster cluster = clusterInState(clusterIdentifier, "paused"); + String accountId = clusters.accountId(); + try { + RedshiftContainerHandle handle = containerManager.resume(accountId, clusterIdentifier, + cluster.getMasterUsername(), CLUSTER_DB_NAME); + startResumedProxy(accountId, cluster, handle); + cluster.setClusterStatus("available"); + clusters.put(clusterIdentifier, cluster); + clusters.flush(); + registerAuditLogging(accountId, cluster); + return cluster; + } catch (RuntimeException failure) { + cluster.setClusterStatus("paused"); + try { + proxyManager.stopProxy(relayKey(accountId, clusterIdentifier)); + } catch (RuntimeException rollbackFailure) { + LOG.warnv(rollbackFailure, "Failed to stop proxy during resume rollback for cluster {0}", clusterIdentifier); + cluster.setClusterStatus("unavailable"); + } + try { + containerManager.pause(accountId, clusterIdentifier); + } catch (RuntimeException rollbackFailure) { + LOG.warnv(rollbackFailure, "Failed to return cluster {0} to paused state", clusterIdentifier); + cluster.setClusterStatus("unavailable"); + } + persistClusterWithoutBackend(cluster, cluster.getClusterStatus()); + if (failure instanceof AwsException awsFailure) { + throw awsFailure; + } + LOG.warnv(failure, "Failed to resume Redshift cluster {0}", clusterIdentifier); + throw new AwsException("InternalFailure", "Failed to resume cluster " + clusterIdentifier, 500); + } + }); + } + + private void persistClusterWithoutBackend(Cluster cluster, String status) { + cluster.setClusterStatus(status); + cluster.setContainerHost(null); + cluster.setContainerPort(0); + clusters.put(cluster.getClusterIdentifier(), cluster); + clusters.flush(); + } + + private Cluster clusterInState(String identifier, String requiredState) { + Cluster cluster = clusters.get(identifier).orElseThrow(() -> + new AwsException("ClusterNotFound", "Cluster " + identifier + " not found", 404)); + if (!requiredState.equals(cluster.getClusterStatus())) { + throw new AwsException("InvalidClusterState", "Cluster " + identifier + + " must be " + requiredState + " for this operation", 400); + } + return cluster; + } + + private static void rejectPausedCluster(Cluster cluster) { + if ("paused".equals(cluster.getClusterStatus())) { + throw new AwsException("InvalidClusterState", "Cluster " + cluster.getClusterIdentifier() + + " must be resumed before this operation", 400); + } + } + + private void startResumedProxy(String accountId, Cluster cluster, RedshiftContainerHandle handle) { + int port = cluster.getProxyPort() > 0 ? cluster.getProxyPort() : allocateProxyPort(); + usedPorts.add(port); + cluster.setProxyPort(port); + Endpoint endpoint = cluster.getEndpoint() != null ? cluster.getEndpoint() : proxyEndpoint(port); + String password = cluster.getMasterPassword() != null ? cluster.getMasterPassword() : "admin"; + proxyManager.startProxy(relayKey(accountId, cluster.getClusterIdentifier()), port, + handle.getHost(), handle.getPort(), endpoint.getAddress(), cluster.getMasterUsername(), password, + CLUSTER_DB_NAME, passwordValidatorFor(accountId, cluster.getClusterIdentifier()), + cluster.getIamRoleArns(), cluster.getDefaultIamRoleArn()); + cluster.setContainerHost(handle.getHost()); + cluster.setContainerPort(handle.getPort()); + cluster.setEndpoint(endpoint); + } + public Cluster rebootCluster(String clusterIdentifier) { return mutateCluster(clusterIdentifier, () -> rebootClusterLocked(clusterIdentifier)); } @@ -1321,6 +1466,7 @@ public class RedshiftService implements ManagedSecretRotator { private Cluster rebootClusterLocked(String clusterIdentifier) { Cluster cluster = clusters.get(clusterIdentifier) .orElseThrow(() -> new AwsException("ClusterNotFound", "Cluster " + clusterIdentifier + " not found", 404)); + rejectPausedCluster(cluster); // Replacement containers do not reattach the old anonymous volume, so a plain stop+recreate // would silently drop the cluster's data. Dump before stopping and @@ -1473,6 +1619,7 @@ public class RedshiftService implements ManagedSecretRotator { private Snapshot createSnapshot(String accountId, String snapshotIdentifier, Cluster cluster, Integer retentionPeriod, Instant now, Instant scheduledTime) { + rejectPausedCluster(cluster); validateSnapshotIdentifier(snapshotIdentifier); String clusterIdentifier = cluster.getClusterIdentifier(); if ((scheduledTime == null ? snapshots.get(snapshotIdentifier) diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/container/RedshiftContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/redshift/container/RedshiftContainerManager.java index 5b24fe40e8..0e7992a083 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/container/RedshiftContainerManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/container/RedshiftContainerManager.java @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.redshift.container; +import com.github.dockerjava.api.exception.NotModifiedException; import com.github.dockerjava.api.model.Container; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; @@ -112,7 +113,7 @@ public class RedshiftContainerManager { ContainerSpec spec = specBuilder.build(); ContainerInfo info = lifecycleManager.createAndStartEphemeral(spec); return initializeAndRegisterHandle(info, accountId, clusterIdentifier, masterUsername, containerName, enginePort, - effectiveDb); + effectiveDb, true); } /** @@ -145,15 +146,48 @@ public class RedshiftContainerManager { return start(accountId, clusterIdentifier, masterUsername, masterPassword, databaseName, nodeType); } + return adoptExisting(accountId, clusterIdentifier, masterUsername, databaseName, existing.get(), true); + } + + /** Stops PostgreSQL without removing its container or data volume. Docker failures propagate. */ + public void pause(String accountId, String clusterIdentifier) { + String key = containerKey(accountId, clusterIdentifier); + RedshiftContainerHandle handle = containers.get(key); + String id = handle == null ? containerName(accountId, clusterIdentifier) : handle.getContainerId(); + try { + lifecycleManager.getDockerClient().stopContainerCmd(id).withTimeout(30).exec(); + } catch (NotModifiedException alreadyStopped) { + LOG.debugv("Redshift container {0} was already stopped", id); + } + if (handle != null && handle.getLogStream() != null) { + lifecycleManager.closeLogStreamAfterContainerStop(handle.getLogStream()); + handle.setLogStream(null); + } + containers.remove(key); + } + + /** Resumes only the existing data-bearing container; never creates an empty replacement. */ + public RedshiftContainerHandle resume(String accountId, String clusterIdentifier, + String masterUsername, String databaseName) { + Container existing = lifecycleManager.findByName(containerName(accountId, clusterIdentifier)) + .orElseThrow(() -> new AwsException("InvalidClusterState", + "The paused container for cluster " + clusterIdentifier + " no longer exists", 400)); + return adoptExisting(accountId, clusterIdentifier, masterUsername, databaseName, existing, false); + } + + private RedshiftContainerHandle adoptExisting(String accountId, String clusterIdentifier, + String masterUsername, String databaseName, Container existing, + boolean bootstrap) { + String containerName = containerName(accountId, clusterIdentifier); String effectiveDb = (databaseName != null && !databaseName.isBlank()) ? databaseName : DEFAULT_DATABASE; - adoptedContainers.put(containerKey(accountId, clusterIdentifier), existing.get().getId()); + adoptedContainers.put(containerKey(accountId, clusterIdentifier), existing.getId()); 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), + ContainerInfo info = lifecycleManager.adopt(existing.getId(), List.of(enginePort), containerBuilder.resolveDockerNetwork(config.services().redshift().dockerNetwork())); return initializeAndRegisterHandle(info, accountId, clusterIdentifier, masterUsername, containerName, enginePort, - effectiveDb); + effectiveDb, bootstrap); } static int maxConnections(String clusterIdentifier, String nodeType) { @@ -180,7 +214,7 @@ public class RedshiftContainerManager { String masterUsername, String containerName, int enginePort, - String databaseName) { + String databaseName, boolean bootstrap) { EndpointInfo endpoint = info.getEndpoint(enginePort); RedshiftContainerHandle handle = new RedshiftContainerHandle( info.containerId(), clusterIdentifier, endpoint.host(), endpoint.port()); @@ -199,7 +233,9 @@ public class RedshiftContainerManager { try { waitForReady(containerName, info.containerId(), masterUsername, databaseName); - bootstrapCatalog(info.containerId(), masterUsername, databaseName); + if (bootstrap) { + bootstrapCatalog(info.containerId(), masterUsername, databaseName); + } } catch (RuntimeException e) { containers.put(containerKey(accountId, clusterIdentifier), handle); throw e; diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftDynamoDbZeroEtlConsumerTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftDynamoDbZeroEtlConsumerTest.java index 016b0bf417..9500ce45e4 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftDynamoDbZeroEtlConsumerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftDynamoDbZeroEtlConsumerTest.java @@ -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 diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftPauseResumeIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftPauseResumeIntegrationTest.java new file mode 100644 index 0000000000..cd3a27abf1 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftPauseResumeIntegrationTest.java @@ -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(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftProxyIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftProxyIntegrationTest.java index 3a9340bf9d..b464a98d47 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftProxyIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftProxyIntegrationTest.java @@ -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"; diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandlerTest.java index b971320861..f2d108b04b 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandlerTest.java @@ -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 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>")); + assertTrue(xml.contains("warehouse")); + } + verify(service).pauseCluster("warehouse"); + verify(service).resumeCluster("warehouse"); + } + @Test void eventSubscriptionResponsesUseTheRedshiftNamespace() { EventSubscription subscription = new EventSubscription(); diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftServiceTest.java index d7e86f26cb..7a6db3e2d1 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftServiceTest.java @@ -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 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 { diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/container/RedshiftContainerManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/container/RedshiftContainerManagerTest.java index 6310da2b5c..5c8aaecf53 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshift/container/RedshiftContainerManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/container/RedshiftContainerManagerTest.java @@ -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 {