feat(redshift): create final snapshots before deleting clusters (#6346)

* feat(redshift): create final snapshots before deleting clusters

* fix(redshift): clean failed dumps and scope snapshot locking

* fix(redshift): default manual snapshot retention and fix Spectrum cleanup
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-23 14:06:47 -04:00
1 parent 1f31f5bf48
commit 1b8548a0af
14 files changed
+923 -37

No files matched your search

@@ -0,0 +1,188 @@
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.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
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.RedshiftException;
import software.amazon.awssdk.services.redshift.model.Snapshot;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
@QuarkusTest
class RedshiftFinalSnapshotIntegrationTest {
private static final String ACCOUNT = "111111111111";
private static final String DUMP = "CREATE TABLE preserved (id integer); INSERT INTO preserved VALUES (42);";
@InjectMock
RedshiftContainerManager containerManager;
@InjectMock
RedshiftProxyManager proxyManager;
@TestHTTPResource
URI endpoint;
@BeforeEach
void prepareRuntime() {
when(containerManager.start(anyString(), anyString(), anyString(), anyString()))
.thenReturn(new RedshiftContainerHandle("mock-container", "cluster", "localhost", 5432));
doAnswer(invocation -> {
Files.writeString(invocation.getArgument(3, Path.class), DUMP);
return null;
}).when(containerManager).takeSnapshot(anyString(), anyString(), anyString(), any(Path.class));
}
@ParameterizedTest
@ValueSource(ints = {-1, 1, 3653})
void sdkFinalSnapshotSurvivesDeletionAndFeedsRestore(int retention) {
String source = "sdk-final-source";
String backup = "sdk-final-backup";
String restored = "sdk-final-restored";
AtomicReference<String> restoredDump = new AtomicReference<>();
doAnswer(invocation -> {
restoredDump.set(Files.readString(invocation.getArgument(3, Path.class)));
return null;
}).when(containerManager).restoreSnapshot(eq(ACCOUNT), eq(restored), eq("admin"), any(Path.class));
try (RedshiftClient client = client(ACCOUNT); RedshiftClient other = client("222222222222")) {
create(client, source);
try {
assertEquals("deleting", client.deleteCluster(request -> request.clusterIdentifier(source)
.finalClusterSnapshotIdentifier(backup).finalClusterSnapshotRetentionPeriod(retention))
.cluster().clusterStatus());
RedshiftException gone = assertThrows(RedshiftException.class,
() -> client.describeClusters(request -> request.clusterIdentifier(source)));
assertEquals("ClusterNotFound", gone.awsErrorDetails().errorCode());
Snapshot snapshot = client.describeClusterSnapshots(request -> request.snapshotIdentifier(backup))
.snapshots().getFirst();
assertEquals(retention, snapshot.manualSnapshotRetentionPeriod());
assertEquals(source, snapshot.clusterIdentifier());
assertEquals("available", snapshot.status());
assertNotNull(snapshot.snapshotCreateTime());
RedshiftException hidden = assertThrows(RedshiftException.class,
() -> other.describeClusterSnapshots(request -> request.snapshotIdentifier(backup)));
assertEquals("ClusterSnapshotNotFound", hidden.awsErrorDetails().errorCode());
client.restoreFromClusterSnapshot(request -> request.clusterIdentifier(restored).snapshotIdentifier(backup));
assertEquals(DUMP, restoredDump.get());
} finally {
deleteIfPresent(client, source);
deleteIfPresent(client, restored);
try {
client.deleteClusterSnapshot(request -> request.snapshotIdentifier(backup));
} catch (RedshiftException expected) {
if (!"ClusterSnapshotNotFound".equals(expected.awsErrorDetails().errorCode())) {
throw expected;
}
}
}
}
}
@Test
void sdkDefaultNeedsSnapshotNameAndExplicitSkipLeavesNoSnapshot() {
String source = "sdk-final-validation";
try (RedshiftClient client = client(ACCOUNT)) {
create(client, source);
try {
RedshiftException missing = assertThrows(RedshiftException.class,
() -> client.deleteCluster(request -> request.clusterIdentifier(source)));
assertEquals("InvalidParameterCombination", missing.awsErrorDetails().errorCode());
assertEquals("available", client.describeClusters(request -> request.clusterIdentifier(source))
.clusters().getFirst().clusterStatus());
client.deleteCluster(request -> request.clusterIdentifier(source).skipFinalClusterSnapshot(true));
assertTrue(client.describeClusterSnapshots(request -> request.clusterIdentifier(source)).snapshots().isEmpty());
verify(containerManager, never()).takeSnapshot(eq(ACCOUNT), eq(source), anyString(), any(Path.class));
} finally {
deleteIfPresent(client, source);
}
}
}
@Test
void slowSnapshotDoesNotBlockTheSameNamesInAnotherAccount() throws Exception {
String source = "sdk-account-source";
String backup = "sdk-account-backup";
CountDownLatch dumping = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
doAnswer(invocation -> {
dumping.countDown();
assertTrue(release.await(5, TimeUnit.SECONDS));
Files.writeString(invocation.getArgument(3, Path.class), DUMP);
return null;
}).when(containerManager).takeSnapshot(eq(ACCOUNT), eq(source), anyString(), any(Path.class));
try (RedshiftClient first = client(ACCOUNT); RedshiftClient other = client("222222222222");
ExecutorService callers = Executors.newFixedThreadPool(2)) {
create(first, source);
Future<?> snapshot = callers.submit(() -> first.createClusterSnapshot(request -> request
.clusterIdentifier(source).snapshotIdentifier(backup)));
try {
assertTrue(dumping.await(2, TimeUnit.SECONDS));
Future<Snapshot> independent = callers.submit(() -> {
create(other, source);
return other.createClusterSnapshot(request -> request.clusterIdentifier(source)
.snapshotIdentifier(backup)).snapshot();
});
Snapshot created = independent.get(2, TimeUnit.SECONDS);
assertTrue(created.snapshotArn().contains(":222222222222:"));
assertEquals(-1, created.manualSnapshotRetentionPeriod());
assertEquals(-1, other.describeClusterSnapshots(request -> request.snapshotIdentifier(backup))
.snapshots().getFirst().manualSnapshotRetentionPeriod());
} finally {
release.countDown();
snapshot.get(3, TimeUnit.SECONDS);
for (RedshiftClient client : new RedshiftClient[]{first, other}) {
deleteIfPresent(client, source);
try {
client.deleteClusterSnapshot(request -> request.snapshotIdentifier(backup));
} catch (RedshiftException expected) {
if (!"ClusterSnapshotNotFound".equals(expected.awsErrorDetails().errorCode())) {
throw expected;
}
}
}
}
}
}
private RedshiftClient client(String account) {
return RedshiftClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(account, "test"))).build();
}
private static void create(RedshiftClient client, String name) {
client.createCluster(request -> request.clusterIdentifier(name).nodeType("dc2.large")
.masterUsername("admin").masterUserPassword("Secret123"));
}
private static void deleteIfPresent(RedshiftClient client, String name) {
try {
client.deleteCluster(request -> request.clusterIdentifier(name).skipFinalClusterSnapshot(true));
} catch (RedshiftException expected) {
if (!"ClusterNotFound".equals(expected.awsErrorDetails().errorCode())) {
throw expected;
}
}
}
}
@@ -0,0 +1,150 @@
package io.github.hectorvent.floci.services.redshift;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
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.Snapshot;
import io.github.hectorvent.floci.services.redshift.proxy.RedshiftProxyManager;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class RedshiftFinalSnapshotStorageTest {
private static final String ACCOUNT = "111111111111";
@TempDir
Path directory;
@Test
void persistentFinalSnapshotAndRetentionSurviveRestartAndRestore() throws Exception {
Fixture first = fixture();
seedCluster(first);
delete(first, "FinalClusterSnapshotRetentionPeriod", "7");
Fixture restarted = fixture();
Snapshot snapshot = restarted.service().describeSnapshots("final-backup").getFirst();
assertEquals(7, snapshot.getManualSnapshotRetentionPeriod());
assertEquals("backup contents", Files.readString(Path.of(snapshot.getSqlDump())));
assertTrue(restarted.service().describeClusters(null).isEmpty());
restarted.service().restoreFromClusterSnapshot("restored", "final-backup");
verify(restarted.manager()).restoreSnapshot(ACCOUNT, "restored", "admin", Path.of(snapshot.getSqlDump()));
}
@Test
void actualPersistentCommitFailurePreservesClusterAndRejectsSnapshot() throws Exception {
Fixture fixture = fixture();
seedCluster(fixture);
Path snapshotFile = directory.resolve("redshift-snapshots.json");
Files.createDirectory(snapshotFile);
Files.writeString(snapshotFile.resolve("block-replacement"), "keep");
assertThrows(AwsException.class, () -> delete(fixture));
assertEquals("available", fixture.service().describeClusters("final-cluster").getFirst().getClusterStatus());
assertTrue(fixture.service().getSnapshot("final-backup").isEmpty());
assertFalse(Files.exists(directory.resolve("redshift-dumps").resolve(ACCOUNT).resolve("final-backup.sql")));
verifyNoInteractions(fixture.proxy());
verify(fixture.manager(), never()).stop(anyString(), anyString());
assertTrue(Files.readString(directory.resolve("redshift-clusters.json")).contains("final-cluster"));
}
@Test
void failedDumpRemovesPartialOutputAndPreservesOriginalFailure() {
Fixture fixture = fixture();
seedCluster(fixture);
AwsException original = new AwsException("InternalFailure", "dump failed", 500);
doAnswer(invocation -> {
Files.writeString(invocation.getArgument(3, Path.class), "partial dump");
throw original;
}).when(fixture.manager()).takeSnapshot(anyString(), anyString(), anyString(), any(Path.class));
assertSame(original, assertThrows(AwsException.class, () -> delete(fixture)));
assertFalse(Files.exists(directory.resolve("redshift-dumps").resolve(ACCOUNT).resolve("final-backup.sql")));
assertTrue(fixture.service().getSnapshot("final-backup").isEmpty());
verifyNoInteractions(fixture.proxy());
}
@Test
void failedCleanupIsSuppressedOnTheOriginalDumpFailure() {
Fixture fixture = fixture();
seedCluster(fixture);
AwsException original = new AwsException("InternalFailure", "dump failed", 500);
doAnswer(invocation -> {
Path output = invocation.getArgument(3, Path.class);
Files.createDirectory(output);
Files.writeString(output.resolve("block-cleanup"), "partial output");
throw original;
}).when(fixture.manager()).takeSnapshot(anyString(), anyString(), anyString(), any(Path.class));
assertSame(original, assertThrows(AwsException.class, () -> delete(fixture)));
assertEquals(1, original.getSuppressed().length);
assertTrue(fixture.service().getSnapshot("final-backup").isEmpty());
verifyNoInteractions(fixture.proxy());
}
private Fixture fixture() {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.storage().persistentPath()).thenReturn(directory.toString());
when(config.defaultAccountId()).thenReturn(ACCOUNT);
when(config.services().redshift().proxyBasePort()).thenReturn(7100);
when(config.services().redshift().proxyMaxPort()).thenReturn(7199);
ServiceConfigAccess access = mock(ServiceConfigAccess.class);
when(access.storageMode("redshift")).thenReturn("persistent");
StorageFactory factory = new StorageFactory(config, access);
RedshiftContainerManager manager = mock(RedshiftContainerManager.class);
when(manager.start(anyString(), anyString(), anyString(), anyString()))
.thenReturn(new RedshiftContainerHandle("container", "restored", "localhost", 5432));
doAnswer(invocation -> {
Files.writeString(invocation.getArgument(3, Path.class), "backup contents");
return null;
}).when(manager).takeSnapshot(anyString(), anyString(), anyString(), any(Path.class));
RedshiftProxyManager proxy = mock(RedshiftProxyManager.class);
DockerHostResolver dockerHost = mock(DockerHostResolver.class);
when(dockerHost.resolve()).thenReturn("localhost");
RedshiftService service = new RedshiftService(factory, manager, config,
new RegionResolver("us-east-1", ACCOUNT), proxy, dockerHost, new RedshiftCredentialBroker());
return new Fixture(service, manager, proxy, config, factory);
}
private static void seedCluster(Fixture fixture) {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("final-cluster");
cluster.setClusterStatus("available");
cluster.setMasterUsername("admin");
cluster.setMasterPassword("secret-pw");
AccountAwareStorageBackend<Cluster> clusters = fixture.factory().create("redshift", "redshift-clusters.json",
new TypeReference<Map<String, Cluster>>() { });
clusters.put("final-cluster", cluster);
}
private static void delete(Fixture fixture, String... options) {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ClusterIdentifier", "final-cluster");
params.putSingle("FinalClusterSnapshotIdentifier", "final-backup");
for (int index = 0; index < options.length; index += 2) {
params.putSingle(options[index], options[index + 1]);
}
new RedshiftQueryHandler(fixture.service(), new RedshiftCredentialBroker(), fixture.config(),
mock(RedshiftIamDbUserResolver.class), new RegionResolver("us-east-1", ACCOUNT))
.handle("DeleteCluster", params);
}
private record Fixture(RedshiftService service, RedshiftContainerManager manager, RedshiftProxyManager proxy,
EmulatorConfig config, StorageFactory factory) { }
}
@@ -453,6 +453,7 @@ public class RedshiftOperationsTest {
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "DeleteCluster")
.formParam("SkipFinalClusterSnapshot", "true")
.formParam("ClusterIdentifier", "cluster-src")
.when()
.post("/")
@@ -512,6 +513,7 @@ public class RedshiftOperationsTest {
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "DeleteCluster")
.formParam("SkipFinalClusterSnapshot", "true")
.formParam("ClusterIdentifier", "cluster-restored")
.when()
.post("/")
@@ -898,6 +900,7 @@ public class RedshiftOperationsTest {
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "DeleteCluster")
.formParam("SkipFinalClusterSnapshot", "true")
.formParam("ClusterIdentifier", "cluster-tags")
.when()
.post("/")
@@ -1083,7 +1086,8 @@ public class RedshiftOperationsTest {
400, "InvalidSnapshotCopyGrantStateFault");
assertEquals(200, redshift("DisableSnapshotCopy", "ClusterIdentifier", "cluster-copy").statusCode());
assertEquals(200, redshift("DeleteCluster", "ClusterIdentifier", "cluster-copy").statusCode());
assertEquals(200, redshift("DeleteCluster", "ClusterIdentifier", "cluster-copy",
"SkipFinalClusterSnapshot", "true").statusCode());
assertEquals(200, redshift("DeleteSnapshotCopyGrant", "SnapshotCopyGrantName", "copy-lifecycle-grant").statusCode());
}
@@ -1186,7 +1190,8 @@ public class RedshiftOperationsTest {
assertEquals(0, describeSchedules("ScheduleIdentifier", "sched-1").getList("SnapshotSchedule").size());
assertFault(redshift("DeleteSnapshotSchedule", "ScheduleIdentifier", "sched-1"), 400, "SnapshotScheduleNotFound");
assertEquals(200, redshift("DeleteCluster", "ClusterIdentifier", "cluster-sched").statusCode());
assertEquals(200, redshift("DeleteCluster", "ClusterIdentifier", "cluster-sched",
"SkipFinalClusterSnapshot", "true").statusCode());
}
@Test
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.redshift;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.PaginatedResult;
@@ -462,7 +463,7 @@ class RedshiftQueryHandlerTest {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("test-cluster");
cluster.setClusterStatus("deleting");
when(service.deleteCluster(any())).thenReturn(cluster);
when(service.deleteCluster("test-cluster", null, null, null)).thenReturn(cluster);
Response response = handler.handle("DeleteCluster", params);
assertEquals(200, response.getStatus());
@@ -489,12 +490,29 @@ class RedshiftQueryHandlerTest {
assertTrue(xml.contains("<Port>5439</Port>"));
assertTrue(xml.contains("<MasterUsername>admin</MasterUsername>"));
assertTrue(xml.contains("<RequestId>test-req-id</RequestId>"));
assertTrue(xml.contains("<ManualSnapshotRetentionPeriod>-1</ManualSnapshotRetentionPeriod>"));
// A Snapshot built via this constructor carries no ARN/CreateTime; the elements
// must be omitted rather than serialized as empty or "null".
assertFalse(xml.contains("<SnapshotArn>"));
assertFalse(xml.contains("<SnapshotCreateTime>"));
}
@Test
void describeLegacySnapshotsDefaultsMissingAndNullRetention() throws Exception {
ObjectMapper mapper = new ObjectMapper();
for (String json : List.of("{\"snapshotIdentifier\":\"legacy\"}",
"{\"snapshotIdentifier\":\"legacy\",\"manualSnapshotRetentionPeriod\":null}")) {
Snapshot snapshot = mapper.readValue(json, Snapshot.class);
when(service.describeSnapshots("legacy", null)).thenReturn(List.of(snapshot));
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("SnapshotIdentifier", "legacy");
String xml = handler.handle("DescribeClusterSnapshots", params).getEntity().toString();
assertTrue(xml.contains("<ManualSnapshotRetentionPeriod>-1</ManualSnapshotRetentionPeriod>"));
}
}
@Test
void describeClusterSnapshots() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
@@ -26,11 +26,14 @@ import io.github.hectorvent.floci.services.redshift.model.SnapshotSchedule;
import io.github.hectorvent.floci.services.redshift.proxy.RedshiftProxyManager;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.secretsmanager.model.Secret;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -44,6 +47,14 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
import static io.github.hectorvent.floci.testing.InlineMocks.inlineMock;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -56,6 +67,277 @@ import static org.mockito.Mockito.*;
class RedshiftServiceTest {
@ParameterizedTest
@ValueSource(booleans = {false, true})
void slowSnapshotDoesNotBlockOtherClusterMutation(boolean finalSnapshot) throws Exception {
finalSnapshotCluster();
Cluster other = new Cluster();
other.setClusterIdentifier("other-cluster");
when(clusterBackend.get("other-cluster")).thenReturn(Optional.of(other));
CountDownLatch dumping = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
doAnswer(invocation -> {
dumping.countDown();
assertTrue(release.await(5, TimeUnit.SECONDS));
return null;
}).when(cm).takeSnapshot(eq("111111111111"), eq("final-cluster"), eq("admin"), any(Path.class));
try (ExecutorService callers = Executors.newFixedThreadPool(2)) {
Future<?> snapshot = callers.submit(() -> {
if (finalSnapshot) {
finalSnapshotDelete("FinalClusterSnapshotIdentifier", "final-backup");
} else {
service.createSnapshot("final-backup", "final-cluster");
}
});
try {
assertTrue(dumping.await(2, TimeUnit.SECONDS));
Future<Cluster> mutation = callers.submit(() -> service.modifyCluster("other-cluster", "ra3.large",
null, null, null, null));
assertEquals("ra3.large", mutation.get(1, TimeUnit.SECONDS).getNodeType());
} finally {
release.countDown();
snapshot.get(3, TimeUnit.SECONDS);
}
}
}
@Test
void snapshotFlushFailureKeepsCommittedDump() throws Exception {
finalSnapshotCluster();
AtomicReference<Path> dump = new AtomicReference<>();
doAnswer(invocation -> {
Path path = invocation.getArgument(3, Path.class);
Files.writeString(path, "committed backup");
dump.set(path);
return null;
}).when(cm).takeSnapshot(eq("111111111111"), eq("final-cluster"), eq("admin"), any(Path.class));
doThrow(new IllegalStateException("flush failed")).when(snapshotBackend).flush();
try {
assertThrows(AwsException.class,
() -> finalSnapshotDelete("FinalClusterSnapshotIdentifier", "final-backup"));
verify(snapshotBackend).putAllAtomically(anyMap());
assertEquals("committed backup", Files.readString(dump.get()));
verify(cm, never()).stop(anyString(), anyString());
} finally {
if (dump.get() != null) {
Files.deleteIfExists(dump.get());
}
}
}
@Test
void snapshotKeepsSameClusterMutationSerializedWithoutHoldingServiceMonitor() throws Exception {
finalSnapshotCluster();
CountDownLatch dumping = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
CountDownLatch attemptingMutation = new CountDownLatch(1);
doAnswer(invocation -> {
dumping.countDown();
assertTrue(release.await(5, TimeUnit.SECONDS));
return null;
}).when(cm).takeSnapshot(anyString(), anyString(), anyString(), any(Path.class));
try (ExecutorService callers = Executors.newFixedThreadPool(2)) {
Future<Snapshot> snapshot = callers.submit(() -> service.createSnapshot("backup", "final-cluster"));
try {
assertTrue(dumping.await(2, TimeUnit.SECONDS));
Future<Cluster> mutation = callers.submit(() -> {
attemptingMutation.countDown();
return service.modifyCluster("final-cluster", "ra3.large", null, null, null, null);
});
assertTrue(attemptingMutation.await(2, TimeUnit.SECONDS));
assertThrows(TimeoutException.class, () -> mutation.get(150, TimeUnit.MILLISECONDS));
release.countDown();
assertNotNull(snapshot.get(2, TimeUnit.SECONDS));
assertEquals("ra3.large", mutation.get(2, TimeUnit.SECONDS).getNodeType());
} finally {
release.countDown();
}
}
}
@Test
void concurrentSnapshotsOnDifferentClustersCannotOverwriteTheSameBackup() throws Exception {
Cluster source = finalSnapshotCluster();
when(clusterBackend.get("other-cluster")).thenReturn(Optional.of(source));
Map<String, Snapshot> committed = new ConcurrentHashMap<>();
when(snapshotBackend.get(anyString())).thenAnswer(invocation -> Optional.ofNullable(committed.get(invocation.getArgument(0))));
doAnswer(invocation -> {
committed.putAll(invocation.getArgument(0));
return null;
}).when(snapshotBackend).putAllAtomically(anyMap());
CountDownLatch dumping = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
CountDownLatch attempting = new CountDownLatch(1);
doAnswer(invocation -> {
dumping.countDown();
assertTrue(release.await(5, TimeUnit.SECONDS));
return null;
}).when(cm).takeSnapshot(anyString(), anyString(), anyString(), any(Path.class));
try (ExecutorService callers = Executors.newFixedThreadPool(2)) {
Future<Snapshot> first = callers.submit(() -> service.createSnapshot("backup", "final-cluster"));
try {
assertTrue(dumping.await(2, TimeUnit.SECONDS));
Future<AwsException> second = callers.submit(() -> {
attempting.countDown();
return assertThrows(AwsException.class, () -> service.createSnapshot("backup", "other-cluster"));
});
assertTrue(attempting.await(2, TimeUnit.SECONDS));
assertThrows(TimeoutException.class, () -> second.get(150, TimeUnit.MILLISECONDS));
release.countDown();
assertEquals("final-cluster", first.get(2, TimeUnit.SECONDS).getClusterIdentifier());
assertEquals("ClusterSnapshotAlreadyExists", second.get(2, TimeUnit.SECONDS).getErrorCode());
verify(cm, times(1)).takeSnapshot(anyString(), anyString(), anyString(), any(Path.class));
} finally {
release.countDown();
}
}
}
@Test
void deleteWithFinalSnapshotCommitsBackupBeforeStoppingCluster() {
Cluster cluster = finalSnapshotCluster();
finalSnapshotDelete("FinalClusterSnapshotIdentifier", "final-backup",
"FinalClusterSnapshotRetentionPeriod", "7");
ArgumentCaptor<Map<String, Snapshot>> committed = ArgumentCaptor.captor();
InOrder order = inOrder(cm, snapshotBackend, proxyManager, clusterBackend);
order.verify(cm).takeSnapshot(eq("111111111111"), eq("final-cluster"), eq("admin"), any(Path.class));
order.verify(snapshotBackend).putAllAtomically(committed.capture());
order.verify(snapshotBackend).flush();
order.verify(proxyManager).stopProxy("111111111111:final-cluster");
order.verify(cm).stop("111111111111", "final-cluster");
order.verify(clusterBackend).delete("final-cluster");
Snapshot snapshot = committed.getValue().get("final-backup");
assertEquals("final-cluster", snapshot.getClusterIdentifier());
assertEquals("secret-pw", snapshot.getMasterPassword());
assertEquals(7, snapshot.getManualSnapshotRetentionPeriod());
assertEquals("deleting", cluster.getClusterStatus());
}
@Test
void deleteDefaultsToRequiringFinalSnapshotName() {
finalSnapshotCluster();
AwsException failure = assertThrows(AwsException.class, () -> finalSnapshotDelete());
assertEquals("InvalidParameterCombination", failure.getErrorCode());
verifyNoInteractions(cm, proxyManager);
verify(clusterBackend, never()).delete(anyString());
}
@Test
void finalSnapshotDefaultsToIndefiniteRetentionAndSurvivesTeardownFailure() {
Cluster cluster = finalSnapshotCluster();
doThrow(new IllegalStateException("proxy busy")).when(proxyManager).stopProxy(anyString());
assertThrows(AwsException.class,
() -> finalSnapshotDelete("FinalClusterSnapshotIdentifier", "final-backup"));
ArgumentCaptor<Map<String, Snapshot>> committed = ArgumentCaptor.captor();
verify(snapshotBackend).putAllAtomically(committed.capture());
assertEquals(-1, committed.getValue().get("final-backup").getManualSnapshotRetentionPeriod());
verify(snapshotBackend, never()).delete(anyString());
verify(cm, never()).stop(anyString(), anyString());
assertEquals("available", cluster.getClusterStatus());
}
@ParameterizedTest
@ValueSource(strings = {"../escape", "bad--name", "bad-", "1bad", " "})
void deleteRejectsMalformedFinalSnapshotName(String name) {
finalSnapshotCluster();
assertThrows(AwsException.class, () -> finalSnapshotDelete("FinalClusterSnapshotIdentifier", name));
verifyNoInteractions(cm, proxyManager);
verify(clusterBackend, never()).delete(anyString());
}
@ParameterizedTest
@ValueSource(strings = {"0", "-2", "3654"})
void deleteRejectsInvalidRetentionBeforeDumpOrTeardown(String retention) {
finalSnapshotCluster();
AwsException failure = assertThrows(AwsException.class, () -> finalSnapshotDelete(
"FinalClusterSnapshotIdentifier", "final-backup", "FinalClusterSnapshotRetentionPeriod", retention));
assertEquals("InvalidRetentionPeriodFault", failure.getErrorCode());
verifyNoInteractions(cm, proxyManager);
verify(clusterBackend, never()).delete(anyString());
}
@Test
void deleteRejectsSkipWithFinalSnapshotName() {
finalSnapshotCluster();
AwsException failure = assertThrows(AwsException.class, () -> finalSnapshotDelete(
"SkipFinalClusterSnapshot", "true", "FinalClusterSnapshotIdentifier", "final-backup"));
assertEquals("InvalidParameterCombination", failure.getErrorCode());
verifyNoInteractions(cm, proxyManager);
}
@Test
void deleteRejectsMalformedSkipAndRetention() {
finalSnapshotCluster();
for (String[] option : List.of(new String[]{"SkipFinalClusterSnapshot", "yes"},
new String[]{"FinalClusterSnapshotRetentionPeriod", "abc"},
new String[]{"FinalClusterSnapshotRetentionPeriod", "2147483648"})) {
AwsException failure = assertThrows(AwsException.class, () -> finalSnapshotDelete(option));
assertEquals("InvalidParameterValue", failure.getErrorCode());
}
verifyNoInteractions(cm, proxyManager);
}
@Test
void deleteKeepsClusterWhenDumpFails() {
Cluster cluster = finalSnapshotCluster();
doThrow(new AwsException("InternalFailure", "dump failed", 500)).when(cm)
.takeSnapshot(eq("111111111111"), eq("final-cluster"), eq("admin"), any(Path.class));
assertThrows(AwsException.class,
() -> finalSnapshotDelete("FinalClusterSnapshotIdentifier", "final-backup"));
verifyNoInteractions(proxyManager);
verify(cm, never()).stop(anyString(), anyString());
verify(clusterBackend, never()).delete(anyString());
assertEquals("available", cluster.getClusterStatus());
}
@Test
void deleteKeepsClusterWhenSnapshotCommitFails() {
Cluster cluster = finalSnapshotCluster();
doThrow(new IllegalStateException("storage failed")).when(snapshotBackend).putAllAtomically(anyMap());
assertThrows(RuntimeException.class,
() -> finalSnapshotDelete("FinalClusterSnapshotIdentifier", "final-backup"));
verifyNoInteractions(proxyManager);
verify(cm, never()).stop(anyString(), anyString());
verify(clusterBackend, never()).delete(anyString());
assertEquals("available", cluster.getClusterStatus());
}
@Test
void deleteRejectsDuplicateBackupAndUnavailableCluster() {
Cluster cluster = finalSnapshotCluster();
when(snapshotBackend.get("existing-backup")).thenReturn(Optional.of(new Snapshot()));
AwsException duplicate = assertThrows(AwsException.class,
() -> finalSnapshotDelete("FinalClusterSnapshotIdentifier", "existing-backup"));
assertEquals("ClusterSnapshotAlreadyExists", duplicate.getErrorCode());
cluster.setClusterStatus("unavailable");
AwsException unavailable = assertThrows(AwsException.class,
() -> finalSnapshotDelete("FinalClusterSnapshotIdentifier", "final-backup"));
assertEquals("InvalidClusterState", unavailable.getErrorCode());
verifyNoInteractions(cm, proxyManager);
}
private Cluster finalSnapshotCluster() {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("final-cluster");
cluster.setClusterStatus("available");
cluster.setMasterUsername("admin");
cluster.setMasterPassword("secret-pw");
when(clusterBackend.get("final-cluster")).thenReturn(Optional.of(cluster));
return cluster;
}
private void finalSnapshotDelete(String... options) {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ClusterIdentifier", "final-cluster");
for (int index = 0; index < options.length; index += 2) {
params.putSingle(options[index], options[index + 1]);
}
RedshiftQueryHandler query = new RedshiftQueryHandler(service, credentialBroker,
mock(EmulatorConfig.class), mock(RedshiftIamDbUserResolver.class), regionResolver);
query.handle("DeleteCluster", params);
}
@Test
void blankDefaultRoleCreatesWithoutDefaultAndClearsExistingDefault() {
String role = "arn:aws:iam::111111111111:role/copy";
@@ -871,7 +1153,7 @@ class RedshiftServiceTest {
// 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).putAllAtomically(Map.of("my-snapshot", snapshot));
verify(snapshotBackend).flush();
verify(cm).takeSnapshot(eq("111111111111"), eq("my-cluster"), eq("admin"), any(Path.class));
}