mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(redshift-serverless): expire snapshots after their retention period (#6966)
* feat(redshift-serverless): expire snapshots after their retention period * fix(redshift-serverless): stop the snapshot expiration worker before storage closes * fix(redshift-serverless): mark pending snapshot cleanup DELETED and test the sweep lock without timing * refactor(redshift-serverless): run snapshot expiration on a shared sweep worker
This commit is contained in:
1 parent
9c00c8c70e
commit
80edd853de
14 files changed
+958
-3
No files matched your search
@@ -0,0 +1,177 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
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.AtomicInteger;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class SweepWorkerTest {
|
||||
private static final Instant NOW = Instant.parse("2030-01-07T02:00:00Z");
|
||||
|
||||
private final List<Instant> swept = new CopyOnWriteArrayList<>();
|
||||
|
||||
private SweepWorker worker(boolean enabled, Consumer<Instant> sweep) {
|
||||
return new SweepWorker("test-sweep", enabled, 60, false, sweep);
|
||||
}
|
||||
|
||||
private static void awaitQueuedSweeps(SweepWorker worker, int expected) {
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
|
||||
while (worker.queuedSweeps() < expected) {
|
||||
assertTrue(System.nanoTime() < deadline, "Expected " + expected + " thread(s) waiting for the sweep");
|
||||
Thread.onSpinWait();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void backgroundThreadExistsOnlyWhenEnabled() {
|
||||
assertTrue(worker(true, swept::add).active());
|
||||
assertFalse(worker(false, swept::add).active());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tickRunsTheSweepAtTheGivenInstantEvenWithoutABackgroundThread() {
|
||||
worker(false, swept::add).tick(NOW);
|
||||
assertEquals(List.of(NOW), swept);
|
||||
}
|
||||
|
||||
@Test
|
||||
void tickIsSkippedBetweenPauseAndResume() {
|
||||
SweepWorker worker = worker(false, swept::add);
|
||||
worker.pause();
|
||||
worker.tick(NOW);
|
||||
assertTrue(swept.isEmpty());
|
||||
|
||||
worker.resume();
|
||||
worker.tick(NOW);
|
||||
assertEquals(List.of(NOW), swept);
|
||||
}
|
||||
|
||||
@Test
|
||||
void pauseDrainsARunningSweepAndHoldsLaterOnesUntilResume() throws Exception {
|
||||
CountDownLatch running = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
SweepWorker worker = worker(false, now -> {
|
||||
swept.add(now);
|
||||
running.countDown();
|
||||
try {
|
||||
release.await(10, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
});
|
||||
ExecutorService executor = Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
Future<?> sweep = executor.submit(() -> worker.tick(NOW));
|
||||
assertTrue(running.await(5, TimeUnit.SECONDS));
|
||||
Future<?> pause = executor.submit(worker::pause);
|
||||
awaitQueuedSweeps(worker, 1);
|
||||
assertFalse(pause.isDone());
|
||||
|
||||
release.countDown();
|
||||
pause.get(5, TimeUnit.SECONDS);
|
||||
sweep.get(5, TimeUnit.SECONDS);
|
||||
worker.tick(NOW.plusSeconds(60));
|
||||
assertEquals(List.of(NOW), swept);
|
||||
|
||||
worker.resume();
|
||||
worker.tick(NOW.plusSeconds(120));
|
||||
assertEquals(List.of(NOW, NOW.plusSeconds(120)), swept);
|
||||
} finally {
|
||||
release.countDown();
|
||||
executor.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void overlappingTicksNeverRunTheSweepConcurrently() throws Exception {
|
||||
AtomicInteger concurrent = new AtomicInteger();
|
||||
AtomicInteger peak = new AtomicInteger();
|
||||
CountDownLatch running = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
SweepWorker worker = worker(false, now -> {
|
||||
peak.accumulateAndGet(concurrent.incrementAndGet(), Math::max);
|
||||
running.countDown();
|
||||
try {
|
||||
release.await(10, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
concurrent.decrementAndGet();
|
||||
});
|
||||
ExecutorService executor = Executors.newFixedThreadPool(3);
|
||||
try {
|
||||
Future<?> first = executor.submit(() -> worker.tick(NOW));
|
||||
assertTrue(running.await(5, TimeUnit.SECONDS));
|
||||
Future<?> second = executor.submit(() -> worker.tick(NOW));
|
||||
Future<?> third = executor.submit(() -> worker.tick(NOW));
|
||||
awaitQueuedSweeps(worker, 2);
|
||||
assertEquals(1, concurrent.get());
|
||||
|
||||
release.countDown();
|
||||
first.get(5, TimeUnit.SECONDS);
|
||||
second.get(5, TimeUnit.SECONDS);
|
||||
third.get(5, TimeUnit.SECONDS);
|
||||
} finally {
|
||||
release.countDown();
|
||||
executor.shutdownNow();
|
||||
}
|
||||
assertEquals(1, peak.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedSweepReleasesTheLock() {
|
||||
List<Instant> attempts = new ArrayList<>();
|
||||
SweepWorker worker = worker(false, now -> {
|
||||
attempts.add(now);
|
||||
if (attempts.size() == 1) {
|
||||
throw new IllegalStateException("boom");
|
||||
}
|
||||
});
|
||||
assertThrows(IllegalStateException.class, () -> worker.tick(NOW));
|
||||
worker.tick(NOW.plusSeconds(60));
|
||||
assertEquals(List.of(NOW, NOW.plusSeconds(60)), attempts);
|
||||
}
|
||||
|
||||
@Test
|
||||
void startRunsTheFirstSweepAtOnceWhenAskedTo() throws Exception {
|
||||
CountDownLatch first = new CountDownLatch(1);
|
||||
SweepWorker worker = new SweepWorker("test-sweep", true, 3600, true, now -> first.countDown());
|
||||
try {
|
||||
worker.start();
|
||||
assertTrue(first.await(5, TimeUnit.SECONDS));
|
||||
} finally {
|
||||
worker.stop();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void startWaitsOneIntervalBeforeTheFirstSweepByDefault() throws Exception {
|
||||
CountDownLatch first = new CountDownLatch(1);
|
||||
SweepWorker worker = new SweepWorker("test-sweep", true, 3600, false, now -> first.countDown());
|
||||
try {
|
||||
worker.start();
|
||||
assertEquals(1, first.getCount());
|
||||
} finally {
|
||||
worker.stop();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopWithoutABackgroundThreadDoesNothing() {
|
||||
SweepWorker worker = worker(false, swept::add);
|
||||
worker.start();
|
||||
worker.stop();
|
||||
assertTrue(swept.isEmpty());
|
||||
}
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
package io.github.hectorvent.floci.services.redshiftserverless;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.redshiftserverless.model.RedshiftServerlessSnapshot;
|
||||
import io.github.hectorvent.floci.services.redshiftserverless.model.ResourcePolicy;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class RedshiftServerlessResourcePolicyExpirationTest {
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
void expirationRemovesLegacySnapshotAndPolicyWithoutAnApiReadFirst(boolean scopedSnapshot) {
|
||||
String account = "123456789012";
|
||||
String region = "us-east-1";
|
||||
String arn = "arn:aws:redshift-serverless:us-east-1:123456789012:snapshot/legacy-snap";
|
||||
InMemoryStorage<String, RedshiftServerlessSnapshot> rawSnapshots = new InMemoryStorage<>();
|
||||
InMemoryStorage<String, ResourcePolicy> rawPolicies = new InMemoryStorage<>();
|
||||
AccountAwareStorageBackend<RedshiftServerlessSnapshot> snapshots =
|
||||
new AccountAwareStorageBackend<>(rawSnapshots, null, account);
|
||||
AccountAwareStorageBackend<ResourcePolicy> policies = new AccountAwareStorageBackend<>(rawPolicies, null, account);
|
||||
StorageFactory factory = mock(StorageFactory.class);
|
||||
when(factory.create(eq("redshiftserverless"), eq("redshiftserverless-snapshots.json"),
|
||||
any(TypeReference.class))).thenReturn((AccountAwareStorageBackend) snapshots);
|
||||
when(factory.create(eq("redshiftserverless"), eq("redshiftserverless-resourcepolicies.json"),
|
||||
any(TypeReference.class))).thenReturn((AccountAwareStorageBackend) policies);
|
||||
RedshiftServerlessService serverless = new RedshiftServerlessService(factory,
|
||||
new RegionResolver(region, account), mock(RedshiftServerlessEndpoints.class),
|
||||
mock(RedshiftServerlessRuntime.class), mock(EmulatorConfig.class));
|
||||
RedshiftServerlessResourcePolicyService service = new RedshiftServerlessResourcePolicyService(
|
||||
factory, serverless, new ObjectMapper());
|
||||
RedshiftServerlessSnapshot snapshot = new RedshiftServerlessSnapshot();
|
||||
snapshot.setSnapshotName("legacy-snap");
|
||||
snapshot.setSnapshotArn(arn);
|
||||
snapshot.setSnapshotCreateTime(Instant.EPOCH);
|
||||
snapshot.setRetentionPeriod(1);
|
||||
ResourcePolicy policy = new ResourcePolicy(arn, "{}");
|
||||
policy.setSnapshotCreateTime(Instant.EPOCH);
|
||||
rawSnapshots.put((scopedSnapshot ? account + "/" : "") + region + "::legacy-snap", snapshot);
|
||||
rawPolicies.put(region + "::" + arn, policy);
|
||||
|
||||
serverless.expireSnapshots(Instant.EPOCH.plusSeconds(86400), service::deleteExpiredSnapshotPolicy);
|
||||
assertTrue(rawSnapshots.keys().isEmpty());
|
||||
assertTrue(rawPolicies.keys().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
void expirationRemovesOnlyThePolicyOfThatAccountAndSnapshotGeneration() {
|
||||
String account = "123456789012";
|
||||
String otherAccount = "999999999999";
|
||||
String region = "us-east-1";
|
||||
String arn = "arn:aws:redshift-serverless:us-east-1:123456789012:snapshot/expiry-snap";
|
||||
String key = region + "::" + arn;
|
||||
Instant created = Instant.parse("2030-01-01T00:00:00Z");
|
||||
AccountAwareStorageBackend<ResourcePolicy> store = AccountAwareStorageBackend.inMemory(account);
|
||||
StorageFactory factory = mock(StorageFactory.class);
|
||||
when(factory.create(eq("redshiftserverless"), eq("redshiftserverless-resourcepolicies.json"),
|
||||
any(TypeReference.class))).thenReturn((AccountAwareStorageBackend) store);
|
||||
RedshiftServerlessResourcePolicyService service = new RedshiftServerlessResourcePolicyService(
|
||||
factory, mock(RedshiftServerlessService.class), new ObjectMapper());
|
||||
RedshiftServerlessSnapshot snapshot = new RedshiftServerlessSnapshot();
|
||||
snapshot.setSnapshotArn(arn);
|
||||
snapshot.setSnapshotCreateTime(created);
|
||||
ResourcePolicy policy = new ResourcePolicy(arn, "{}");
|
||||
policy.setSnapshotCreateTime(created);
|
||||
store.putForAccount(account, key, policy);
|
||||
store.putForAccount(otherAccount, key, policy);
|
||||
AccountAwareStorageBackend.AccountEntry<RedshiftServerlessSnapshot> entry =
|
||||
new AccountAwareStorageBackend.AccountEntry<>(account, region + "::expiry-snap", snapshot);
|
||||
|
||||
service.deleteExpiredSnapshotPolicy(entry);
|
||||
service.deleteExpiredSnapshotPolicy(entry);
|
||||
assertTrue(store.getForAccount(account, key).isEmpty());
|
||||
assertTrue(store.getForAccount(otherAccount, key).isPresent());
|
||||
|
||||
ResourcePolicy replacement = new ResourcePolicy(arn, "{}");
|
||||
replacement.setSnapshotCreateTime(created.plusSeconds(1));
|
||||
store.putForAccount(account, key, replacement);
|
||||
service.deleteExpiredSnapshotPolicy(entry);
|
||||
assertTrue(store.getForAccount(account, key).isPresent());
|
||||
}
|
||||
}
|
||||
+184
-1
@@ -27,7 +27,14 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
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.function.Supplier;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
@@ -56,6 +63,7 @@ class RedshiftServerlessServiceTest {
|
||||
private RedshiftServerlessService service;
|
||||
private AccountAwareStorageBackend<Namespace> store;
|
||||
private AccountAwareStorageBackend<Workgroup> workgroupStore;
|
||||
private AccountAwareStorageBackend<RedshiftServerlessSnapshot> snapshotStore;
|
||||
private RedshiftServerlessEndpoints endpoints;
|
||||
private RedshiftServerlessRuntime runtime;
|
||||
private int nextPort;
|
||||
@@ -78,8 +86,9 @@ class RedshiftServerlessServiceTest {
|
||||
when(storageFactory.create(eq("redshiftserverless"), eq("redshiftserverless-workgroups.json"),
|
||||
any(TypeReference.class))).thenReturn((AccountAwareStorageBackend) workgroupStore);
|
||||
|
||||
snapshotStore = spy(AccountAwareStorageBackend.inMemory(ACCOUNT_ID));
|
||||
when(storageFactory.create(eq("redshiftserverless"), eq("redshiftserverless-snapshots.json"),
|
||||
any(TypeReference.class))).thenReturn(AccountAwareStorageBackend.inMemory(ACCOUNT_ID));
|
||||
any(TypeReference.class))).thenReturn((AccountAwareStorageBackend) snapshotStore);
|
||||
|
||||
RegionResolver regionResolver = mock(RegionResolver.class);
|
||||
when(regionResolver.getAccountId()).thenReturn(ACCOUNT_ID);
|
||||
@@ -104,6 +113,180 @@ class RedshiftServerlessServiceTest {
|
||||
service = new RedshiftServerlessService(storageFactory, regionResolver, endpoints, runtime, config);
|
||||
}
|
||||
|
||||
@Test
|
||||
void expirationHonorsTheExactBoundaryAndIndefiniteRetention() {
|
||||
create("expiry-ns");
|
||||
RedshiftServerlessSnapshot finite = service.createSnapshot("finite-snap", "expiry-ns", 1, null, REGION);
|
||||
service.createSnapshot("default-snap", "expiry-ns", null, null, REGION);
|
||||
service.createSnapshot("indefinite-snap", "expiry-ns", -1, null, REGION);
|
||||
Instant deadline = finite.getSnapshotCreateTime().plusSeconds(86400);
|
||||
|
||||
service.expireSnapshots(deadline.minusNanos(1), entry -> { });
|
||||
assertTrue(service.findSnapshot("finite-snap", REGION).isPresent());
|
||||
service.expireSnapshots(deadline, entry -> { });
|
||||
assertTrue(service.findSnapshot("finite-snap", REGION).isEmpty());
|
||||
service.expireSnapshots(deadline.plusSeconds(86400 * 4000L), entry -> { });
|
||||
assertTrue(service.findSnapshot("default-snap", REGION).isPresent());
|
||||
assertTrue(service.findSnapshot("indefinite-snap", REGION).isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void expirationUsesUpdatedRetentionFromTheOriginalCreationTime() {
|
||||
create("expiry-ns");
|
||||
RedshiftServerlessSnapshot snapshot = service.createSnapshot("extend-snap", "expiry-ns", 1, null, REGION);
|
||||
Instant created = snapshot.getSnapshotCreateTime();
|
||||
service.updateSnapshot("extend-snap", 3, REGION);
|
||||
service.expireSnapshots(created.plusSeconds(86400), entry -> { });
|
||||
assertTrue(service.findSnapshot("extend-snap", REGION).isPresent());
|
||||
service.updateSnapshot("extend-snap", 1, REGION);
|
||||
service.expireSnapshots(created.plusSeconds(86400), entry -> { });
|
||||
assertTrue(service.findSnapshot("extend-snap", REGION).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void expirationDeletesDumpsAcrossAccountsAndRegionsAndIsIdempotent() throws Exception {
|
||||
Instant created = Instant.parse("2030-01-01T00:00:00Z");
|
||||
for (String account : List.of(ACCOUNT_ID, "999999999999")) {
|
||||
for (String region : List.of(REGION, "cn-north-1")) {
|
||||
RedshiftServerlessSnapshot snapshot = new RedshiftServerlessSnapshot();
|
||||
snapshot.setSnapshotName("same-snap");
|
||||
snapshot.setSnapshotCreateTime(created);
|
||||
snapshot.setRetentionPeriod(1);
|
||||
Path dump = dumpDir.resolve("redshift-serverless-dumps").resolve(account).resolve(region)
|
||||
.resolve("same-snap.sql");
|
||||
Files.createDirectories(dump.getParent());
|
||||
Files.writeString(dump, "data");
|
||||
snapshot.setSqlDump(dump.toString());
|
||||
snapshotStore.putForAccount(account, region + "::same-snap", snapshot);
|
||||
}
|
||||
}
|
||||
service.expireSnapshots(created.plusSeconds(86400), entry -> { });
|
||||
service.expireSnapshots(created.plusSeconds(86400), entry -> { });
|
||||
assertTrue(snapshotStore.scanAllAccounts().isEmpty());
|
||||
try (Stream<Path> files = Files.walk(dumpDir)) {
|
||||
assertEquals(0, files.filter(Files::isRegularFile).count());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void expirationRetriesAFailedDumpAndContinuesOtherSnapshots() throws Exception {
|
||||
create("expiry-ns");
|
||||
RedshiftServerlessSnapshot failed = service.createSnapshot("failed-snap", "expiry-ns", 1, null, REGION);
|
||||
RedshiftServerlessSnapshot other = service.createSnapshot("other-snap", "expiry-ns", 1, null, REGION);
|
||||
Path dump = dumpDir.resolve("redshift-serverless-dumps").resolve(ACCOUNT_ID).resolve(REGION)
|
||||
.resolve("failed-snap.sql");
|
||||
Files.createDirectories(dump);
|
||||
Path blocker = Files.writeString(dump.resolve("blocker"), "not an empty directory");
|
||||
failed.setSqlDump(dump.toString());
|
||||
Instant now = other.getSnapshotCreateTime().plusSeconds(86400);
|
||||
|
||||
service.expireSnapshots(now, entry -> { });
|
||||
assertEquals("DELETED", service.getSnapshot("failed-snap", REGION).getStatus());
|
||||
assertTrue(service.findSnapshot("other-snap", REGION).isEmpty());
|
||||
assertEquals("ConflictException", assertThrows(AwsException.class,
|
||||
() -> service.updateSnapshot("failed-snap", -1, REGION)).getErrorCode());
|
||||
assertEquals("ConflictException", assertThrows(AwsException.class,
|
||||
() -> service.restoreFromSnapshot("expiry-ns", "any-workgroup", "failed-snap", null, REGION))
|
||||
.getErrorCode());
|
||||
|
||||
Files.delete(blocker);
|
||||
service.expireSnapshots(now, entry -> { });
|
||||
assertTrue(service.findSnapshot("failed-snap", REGION).isEmpty());
|
||||
assertFalse(Files.exists(dump));
|
||||
}
|
||||
|
||||
@Test
|
||||
void expirationRetriesPersistedDeletionAndPolicyFailures() {
|
||||
create("expiry-ns");
|
||||
RedshiftServerlessSnapshot snapshot = service.createSnapshot("retry-snap", "expiry-ns", null, null, REGION);
|
||||
snapshot.setStatus("DELETED");
|
||||
service.expireSnapshots(Instant.EPOCH, entry -> {
|
||||
throw new IllegalStateException("policy store unavailable");
|
||||
});
|
||||
assertTrue(service.findSnapshot("retry-snap", REGION).isPresent());
|
||||
service.expireSnapshots(Instant.EPOCH, entry -> { });
|
||||
assertTrue(service.findSnapshot("retry-snap", REGION).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void expirationNeverDeletesAnUntrustedDump() throws Exception {
|
||||
create("expiry-ns");
|
||||
RedshiftServerlessSnapshot snapshot = service.createSnapshot("untrusted-snap", "expiry-ns", 1, null, REGION);
|
||||
Path outside = Files.writeString(dumpDir.resolve("outside.sql"), "unrelated");
|
||||
snapshot.setSqlDump(outside.toString());
|
||||
service.expireSnapshots(snapshot.getSnapshotCreateTime().plusSeconds(86400), entry -> { });
|
||||
assertTrue(Files.exists(outside));
|
||||
assertTrue(service.findSnapshot("untrusted-snap", REGION).isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void expirationWaitsForAnInProgressRestore() throws Exception {
|
||||
create("restore-expiry-ns");
|
||||
createWorkgroup("restore-expiry-wg", "restore-expiry-ns");
|
||||
doAnswer(invocation -> {
|
||||
Files.writeString(invocation.getArgument(5, Path.class), "snapshot data");
|
||||
return null;
|
||||
}).when(runtime).takeSnapshot(any(), any(), any(), any(), any(), any());
|
||||
RedshiftServerlessSnapshot snapshot = service.createSnapshot(
|
||||
"restore-expiry-snap", "restore-expiry-ns", 1, null, REGION);
|
||||
CountDownLatch restoring = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
doAnswer(invocation -> {
|
||||
restoring.countDown();
|
||||
assertTrue(release.await(10, TimeUnit.SECONDS));
|
||||
assertTrue(Files.exists(invocation.getArgument(5, Path.class)));
|
||||
return null;
|
||||
}).when(runtime).restoreSnapshot(any(), any(), any(), any(), any(), any(), any());
|
||||
ExecutorService executor = Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
Future<?> restore = executor.submit(() -> service.restoreFromSnapshot(
|
||||
"restore-expiry-ns", "restore-expiry-wg", "restore-expiry-snap", null, REGION));
|
||||
assertTrue(restoring.await(5, TimeUnit.SECONDS));
|
||||
Future<?> sweep = executor.submit(() -> service.expireSnapshots(
|
||||
snapshot.getSnapshotCreateTime().plusSeconds(86400), entry -> { }));
|
||||
assertThrows(TimeoutException.class, () -> sweep.get(200, TimeUnit.MILLISECONDS));
|
||||
release.countDown();
|
||||
restore.get(5, TimeUnit.SECONDS);
|
||||
sweep.get(5, TimeUnit.SECONDS);
|
||||
assertTrue(service.findSnapshot("restore-expiry-snap", REGION).isEmpty());
|
||||
} finally {
|
||||
release.countDown();
|
||||
executor.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void expirationRetainsMetadataWhenTheFinalStorageDeleteFails() {
|
||||
create("expiry-ns");
|
||||
RedshiftServerlessSnapshot snapshot = service.createSnapshot("store-fail-snap", "expiry-ns", 1, null, REGION);
|
||||
doThrow(new IllegalStateException("storage unavailable")).doCallRealMethod()
|
||||
.when(snapshotStore).deleteAllAtomicallyForAccounts(any());
|
||||
Instant deadline = snapshot.getSnapshotCreateTime().plusSeconds(86400);
|
||||
service.expireSnapshots(deadline, entry -> { });
|
||||
assertEquals("DELETED", service.getSnapshot("store-fail-snap", REGION).getStatus());
|
||||
service.expireSnapshots(deadline, entry -> { });
|
||||
assertTrue(service.findSnapshot("store-fail-snap", REGION).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void expirationNeverDeletesDataWhenTheDeletionMarkerCannotBeStored() throws Exception {
|
||||
create("expiry-ns");
|
||||
RedshiftServerlessSnapshot snapshot = service.createSnapshot("marker-fail-snap", "expiry-ns", 1, null, REGION);
|
||||
Path dump = dumpDir.resolve("redshift-serverless-dumps").resolve(ACCOUNT_ID).resolve(REGION)
|
||||
.resolve("marker-fail-snap.sql");
|
||||
Files.createDirectories(dump.getParent());
|
||||
Files.writeString(dump, "data");
|
||||
snapshot.setSqlDump(dump.toString());
|
||||
doThrow(new IllegalStateException("storage unavailable")).when(snapshotStore)
|
||||
.putAllAtomicallyForAccount(any(), any());
|
||||
|
||||
service.expireSnapshots(snapshot.getSnapshotCreateTime().plusSeconds(86400), entry -> {
|
||||
throw new AssertionError("Policy cleanup must not run before the deletion marker is stored");
|
||||
});
|
||||
assertEquals("AVAILABLE", service.getSnapshot("marker-fail-snap", REGION).getStatus());
|
||||
assertTrue(Files.exists(dump));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createAppliesAwsDefaultsAndAUniqueNamespaceId() {
|
||||
Namespace first = create("first-ns");
|
||||
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
package io.github.hectorvent.floci.services.redshiftserverless;
|
||||
|
||||
import io.github.hectorvent.floci.testing.PartitionCleanup;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
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.redshiftserverless.RedshiftServerlessClient;
|
||||
import software.amazon.awssdk.services.redshiftserverless.model.ResourceNotFoundException;
|
||||
import software.amazon.awssdk.services.redshiftserverless.model.Snapshot;
|
||||
|
||||
import java.net.URI;
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
class RedshiftServerlessSnapshotExpirationIntegrationTest {
|
||||
@TestHTTPResource("/")
|
||||
URI endpoint;
|
||||
|
||||
@InjectMock
|
||||
RedshiftServerlessRuntime runtime;
|
||||
|
||||
@Inject
|
||||
RedshiftServerlessSnapshotExpirationScheduler scheduler;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@Test
|
||||
void sdkObservesExpirationAndRecreationWithoutInheritingPolicy() {
|
||||
String namespace = "expiry-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
try (RedshiftServerlessClient client = RedshiftServerlessClient.builder().endpointOverride(endpoint)
|
||||
.region(Region.US_EAST_1).credentialsProvider(StaticCredentialsProvider.create(
|
||||
AwsBasicCredentials.create("test", "test"))).build()) {
|
||||
client.createNamespace(request -> request.namespaceName(namespace).adminUsername("admin")
|
||||
.adminUserPassword("Password123!"));
|
||||
Snapshot finite = client.createSnapshot(request -> request.namespaceName(namespace)
|
||||
.snapshotName(namespace + "-finite").retentionPeriod(1)).snapshot();
|
||||
Snapshot indefinite = client.createSnapshot(request -> request.namespaceName(namespace)
|
||||
.snapshotName(namespace + "-indefinite").retentionPeriod(-1)).snapshot();
|
||||
client.putResourcePolicy(request -> request.resourceArn(finite.snapshotArn()).policy("{}"));
|
||||
Instant deadline = finite.snapshotCreateTime().plusSeconds(86400);
|
||||
|
||||
scheduler.tick(deadline.minusSeconds(1));
|
||||
assertEquals("AVAILABLE", client.getSnapshot(request -> request.snapshotName(finite.snapshotName()))
|
||||
.snapshot().statusAsString());
|
||||
scheduler.tick(deadline.plusSeconds(1));
|
||||
assertThrows(ResourceNotFoundException.class,
|
||||
() -> client.getSnapshot(request -> request.snapshotName(finite.snapshotName())));
|
||||
assertThrows(ResourceNotFoundException.class,
|
||||
() -> client.getSnapshot(request -> request.snapshotArn(finite.snapshotArn())));
|
||||
assertThrows(ResourceNotFoundException.class,
|
||||
() -> client.updateSnapshot(request -> request.snapshotName(finite.snapshotName()).retentionPeriod(7)));
|
||||
assertThrows(ResourceNotFoundException.class,
|
||||
() -> client.getResourcePolicy(request -> request.resourceArn(finite.snapshotArn())));
|
||||
assertTrue(client.listSnapshots(request -> request.namespaceName(namespace)).snapshots().stream()
|
||||
.noneMatch(snapshot -> finite.snapshotName().equals(snapshot.snapshotName())));
|
||||
assertEquals(indefinite.snapshotName(), client.getSnapshot(request -> request
|
||||
.snapshotName(indefinite.snapshotName())).snapshot().snapshotName());
|
||||
|
||||
client.createSnapshot(request -> request.namespaceName(namespace).snapshotName(finite.snapshotName()));
|
||||
assertThrows(ResourceNotFoundException.class,
|
||||
() -> client.getResourcePolicy(request -> request.resourceArn(finite.snapshotArn())));
|
||||
}
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package io.github.hectorvent.floci.services.redshiftserverless;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.quarkus.runtime.ShutdownEvent;
|
||||
import jakarta.annotation.Priority;
|
||||
import jakarta.interceptor.Interceptor;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Method;
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class RedshiftServerlessSnapshotExpirationSchedulerTest {
|
||||
private static final Instant NOW = Instant.parse("2030-01-07T02:00:00Z");
|
||||
|
||||
private final RedshiftServerlessService service = mock(RedshiftServerlessService.class);
|
||||
|
||||
private RedshiftServerlessSnapshotExpirationScheduler scheduler(boolean serviceEnabled, boolean actionsEnabled) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.services().redshiftServerless().enabled()).thenReturn(serviceEnabled);
|
||||
when(config.services().redshiftServerless().snapshotExpirationEnabled()).thenReturn(actionsEnabled);
|
||||
when(config.services().redshiftServerless().snapshotExpirationSweepIntervalSeconds()).thenReturn(60);
|
||||
return new RedshiftServerlessSnapshotExpirationScheduler(service, mock(RedshiftServerlessResourcePolicyService.class), config);
|
||||
}
|
||||
|
||||
@Test
|
||||
void workerExistsOnlyWhenTheServiceAndTheSwitchAreBothOn() {
|
||||
assertTrue(scheduler(true, true).active());
|
||||
assertFalse(scheduler(true, false).active());
|
||||
assertFalse(scheduler(false, true).active());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shutdownObserverRunsBeforeStorageIsFlushedAndClosed() throws Exception {
|
||||
Method onStop = RedshiftServerlessSnapshotExpirationScheduler.class
|
||||
.getDeclaredMethod("onStop", ShutdownEvent.class);
|
||||
Annotation priority = Arrays.stream(onStop.getParameterAnnotations()[0])
|
||||
.filter(Priority.class::isInstance)
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
assertTrue(((Priority) priority).value() < Interceptor.Priority.APPLICATION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void tickRunsTheSweepAtTheGivenInstant() {
|
||||
scheduler(true, false).tick(NOW);
|
||||
verify(service).expireSnapshots(eq(NOW), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tickIsSkippedBetweenBeforeResetAndAfterReset() {
|
||||
RedshiftServerlessSnapshotExpirationScheduler scheduler = scheduler(true, false);
|
||||
scheduler.beforeReset();
|
||||
scheduler.tick(NOW);
|
||||
verify(service, never()).expireSnapshots(any(), any());
|
||||
|
||||
scheduler.afterReset();
|
||||
scheduler.tick(NOW);
|
||||
verify(service).expireSnapshots(eq(NOW), any());
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package io.github.hectorvent.floci.services.redshiftserverless;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.redshiftserverless.model.RedshiftServerlessSnapshot;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class RedshiftServerlessSnapshotExpirationStorageTest {
|
||||
private static final String ACCOUNT = "123456789012";
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
@TempDir
|
||||
Path directory;
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"memory", "persistent", "hybrid", "wal"})
|
||||
void deletionResumesAfterStorageReload(String mode) throws Exception {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.storage().persistentPath()).thenReturn(directory.toString());
|
||||
when(config.defaultAccountId()).thenReturn(ACCOUNT);
|
||||
when(config.storage().wal().compactionIntervalMs()).thenReturn(3600000L);
|
||||
ServiceConfigAccess access = mock(ServiceConfigAccess.class);
|
||||
when(access.storageMode("redshiftserverless")).thenReturn(mode);
|
||||
when(access.storageFlushInterval("redshiftserverless")).thenReturn(3600000L);
|
||||
StorageFactory factory = new StorageFactory(config, access);
|
||||
Path dump = directory.resolve("redshift-serverless-dumps").resolve(ACCOUNT).resolve(REGION)
|
||||
.resolve("retry-snap.sql");
|
||||
Files.createDirectories(dump);
|
||||
Path blocker = Files.writeString(dump.resolve("blocker"), "partial dump");
|
||||
try {
|
||||
AccountAwareStorageBackend<RedshiftServerlessSnapshot> snapshots = factory.create(
|
||||
"redshiftserverless", "redshiftserverless-snapshots.json", new TypeReference<>() { });
|
||||
RedshiftServerlessSnapshot snapshot = new RedshiftServerlessSnapshot();
|
||||
snapshot.setSnapshotName("retry-snap");
|
||||
snapshot.setSnapshotCreateTime(Instant.EPOCH);
|
||||
snapshot.setRetentionPeriod(1);
|
||||
snapshot.setSqlDump(dump.toString());
|
||||
snapshots.put(REGION + "::retry-snap", snapshot);
|
||||
service(factory, config).expireSnapshots(Instant.EPOCH.plusSeconds(86400), entry -> { });
|
||||
assertEquals("DELETED", snapshots.get(REGION + "::retry-snap").orElseThrow().getStatus());
|
||||
if ("memory".equals(mode)) {
|
||||
Files.delete(blocker);
|
||||
service(factory, config).expireSnapshots(Instant.EPOCH, entry -> { });
|
||||
assertTrue(snapshots.scanAllAccounts().isEmpty());
|
||||
assertFalse(Files.exists(dump));
|
||||
return;
|
||||
}
|
||||
} finally {
|
||||
factory.shutdownAll();
|
||||
}
|
||||
|
||||
StorageFactory reloaded = new StorageFactory(config, access);
|
||||
try {
|
||||
RedshiftServerlessService service = service(reloaded, config);
|
||||
assertEquals("DELETED", service.getSnapshot("retry-snap", REGION).getStatus());
|
||||
Files.delete(blocker);
|
||||
service.expireSnapshots(Instant.EPOCH, entry -> { });
|
||||
assertTrue(service.findSnapshot("retry-snap", REGION).isEmpty());
|
||||
assertFalse(Files.exists(dump));
|
||||
} finally {
|
||||
reloaded.shutdownAll();
|
||||
}
|
||||
}
|
||||
|
||||
private RedshiftServerlessService service(StorageFactory factory, EmulatorConfig config) {
|
||||
return new RedshiftServerlessService(factory, new RegionResolver(REGION, ACCOUNT),
|
||||
mock(RedshiftServerlessEndpoints.class), mock(RedshiftServerlessRuntime.class), config);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user