mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(memorydb): restore persistent cluster runtimes after restart (#7540)
* fix(memorydb): restore persistent cluster runtimes after restart Restore account-scoped cluster backends, authentication and stable proxy endpoints from persisted metadata. Retain data storage across restart and preserve retryable ownership on failed provisioning cleanup. Signed-off-by: Andre Kurait <AndreKurait@gmail.com> * fix(memorydb): retain default backend and log names Keep default-account/default-region container and engine-log names stable while retaining scoped runtime and proxy keys. Pass the logical name and stored owner through creation, restoration, deletion and rollback. Use an unambiguous separator for foreign Docker names in the retained hyphen-prefix collision case, without changing foreign log names or persisted volume identities. Preserve restore and cleanup coverage; new naming regressions fail the former manager. Local mocked-Docker and loopback RESP qualification only, no managed AWS or native runtime claim. Signed-off-by: Andre Kurait <AndreKurait@gmail.com> * test(memorydb): share container naming fixtures Move the two naming cases into MemoryDbContainerManagerTest and reuse its manager setup. Share the four loopback PONG responders through one helper, observing completion and propagating responder failures. Preserve naming, collision, cleanup and lifecycle assertions. No production change. Signed-off-by: Andre Kurait <AndreKurait@gmail.com> --------- Signed-off-by: Andre Kurait <AndreKurait@gmail.com>
This commit is contained in:
1 parent
7b3f5812e2
commit
87c7a9ce7d
10 files changed
+1389
-134
No files matched your search
@@ -30,6 +30,7 @@ import io.github.hectorvent.floci.services.lambda.DynamoDbStreamsEventSourcePoll
|
||||
import io.github.hectorvent.floci.services.lambda.KinesisEventSourcePoller;
|
||||
import io.github.hectorvent.floci.services.lambda.SqsEventSourcePoller;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.DurableExecutionService;
|
||||
import io.github.hectorvent.floci.services.memorydb.MemoryDbService;
|
||||
import io.github.hectorvent.floci.services.memorydb.container.MemoryDbContainerManager;
|
||||
import io.github.hectorvent.floci.services.memorydb.proxy.MemoryDbProxyManager;
|
||||
import io.github.hectorvent.floci.services.neptune.container.NeptuneContainerManager;
|
||||
@@ -104,6 +105,8 @@ class EmulatorLifecycleTest {
|
||||
@Mock private RdsProxyManager rdsProxyManager;
|
||||
@Mock private MemoryDbContainerManager memoryDbContainerManager;
|
||||
@Mock private MemoryDbProxyManager memoryDbProxyManager;
|
||||
@Mock private MemoryDbService memoryDbService;
|
||||
@Mock private EmulatorConfig.MemoryDbServiceConfig memoryDbServiceConfig;
|
||||
@Mock private DocDbContainerManager docDbContainerManager;
|
||||
@Mock private NeptuneContainerManager neptuneContainerManager;
|
||||
@Mock private NeptuneProxyManager neptuneProxyManager;
|
||||
@@ -141,6 +144,7 @@ class EmulatorLifecycleTest {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
Mockito.lenient().when(config.services()).thenReturn(servicesConfig);
|
||||
Mockito.lenient().when(servicesConfig.memorydb()).thenReturn(memoryDbServiceConfig);
|
||||
Mockito.lenient().when(servicesConfig.ec2()).thenReturn(ec2ServiceConfig);
|
||||
Mockito.lenient().when(servicesConfig.ecs()).thenReturn(ecsServiceConfig);
|
||||
Mockito.lenient().when(ecsServiceConfig.taskRoleCredentials()).thenReturn(ecsTaskRoleCredentialsConfig);
|
||||
@@ -170,7 +174,7 @@ class EmulatorLifecycleTest {
|
||||
iamService, elastiCacheService, elastiCacheMemcachedService,
|
||||
elastiCacheContainerManager, elastiCacheMemcachedContainerManager,
|
||||
elastiCacheProxyManager, rdsContainerManager, rdsProxyManager,
|
||||
memoryDbContainerManager, memoryDbProxyManager,
|
||||
memoryDbContainerManager, memoryDbProxyManager, memoryDbService,
|
||||
docDbContainerManager, neptuneContainerManager, neptuneProxyManager,
|
||||
rabbitMqManager, flinkContainerManager, rdsService, timestreamInfluxDbService,
|
||||
elbV2Service, elbClassicService, ecsService,
|
||||
|
||||
+18
@@ -23,6 +23,24 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
*/
|
||||
class MemoryDbPersistenceTest {
|
||||
|
||||
@Test
|
||||
void persistsBackendVolumeIdentityAcrossReload(@TempDir Path dir) {
|
||||
Path file = dir.resolve("memorydb-clusters.json");
|
||||
PersistentStorage<String, Cluster> original =
|
||||
new PersistentStorage<>(file, new TypeReference<Map<String, Cluster>>() {});
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setName("durable");
|
||||
cluster.setVolumeId("incarnation-a");
|
||||
original.put("durable", cluster);
|
||||
original.flush();
|
||||
|
||||
PersistentStorage<String, Cluster> reloaded =
|
||||
new PersistentStorage<>(file, new TypeReference<Map<String, Cluster>>() {});
|
||||
reloaded.load();
|
||||
|
||||
assertEquals("incarnation-a", reloaded.get("durable").orElseThrow().getVolumeId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void loadsLegacySnapshotContainingRemovedAuthFields(@TempDir Path dir) throws Exception {
|
||||
Path file = dir.resolve("memorydb-clusters.json");
|
||||
|
||||
+546
@@ -0,0 +1,546 @@
|
||||
package io.github.hectorvent.floci.services.memorydb;
|
||||
|
||||
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.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.elasticache.proxy.SigV4Validator;
|
||||
import io.github.hectorvent.floci.services.memorydb.container.MemoryDbContainerHandle;
|
||||
import io.github.hectorvent.floci.services.memorydb.container.MemoryDbContainerManager;
|
||||
import io.github.hectorvent.floci.services.memorydb.model.Acl;
|
||||
import io.github.hectorvent.floci.services.memorydb.model.AuthMode;
|
||||
import io.github.hectorvent.floci.services.memorydb.model.Cluster;
|
||||
import io.github.hectorvent.floci.services.memorydb.model.ClusterStatus;
|
||||
import io.github.hectorvent.floci.services.memorydb.model.User;
|
||||
import io.github.hectorvent.floci.services.memorydb.proxy.MemoryDbAuthProxy;
|
||||
import io.github.hectorvent.floci.services.memorydb.proxy.MemoryDbProxyManager;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.InOrder;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class MemoryDbRuntimeRestoreTest {
|
||||
|
||||
private static final String DEFAULT_ACCOUNT = "000000000000";
|
||||
private final InMemoryStorage<String, Cluster> rawClusters = new InMemoryStorage<>();
|
||||
private final AccountAwareStorageBackend<Cluster> clusters =
|
||||
spy(new AccountAwareStorageBackend<>(rawClusters, null, DEFAULT_ACCOUNT));
|
||||
private final AccountAwareStorageBackend<User> users = AccountAwareStorageBackend.inMemory(DEFAULT_ACCOUNT);
|
||||
private final AccountAwareStorageBackend<Acl> acls = AccountAwareStorageBackend.inMemory(DEFAULT_ACCOUNT);
|
||||
private MemoryDbContainerManager containers;
|
||||
private MemoryDbProxyManager proxies;
|
||||
private EmulatorConfig config;
|
||||
private MemoryDbService service;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
containers = mock(MemoryDbContainerManager.class);
|
||||
when(containers.isDockerReachable()).thenReturn(true);
|
||||
proxies = mock(MemoryDbProxyManager.class);
|
||||
config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.services().memorydb().proxyBasePort()).thenReturn(17400);
|
||||
when(config.services().memorydb().proxyMaxPort()).thenReturn(17403);
|
||||
when(config.services().memorydb().defaultImage()).thenReturn("valkey/valkey:8");
|
||||
when(config.storage().mode()).thenReturn("persistent");
|
||||
when(config.hostname()).thenReturn(Optional.of("localhost"));
|
||||
StorageFactory storage = mock(StorageFactory.class);
|
||||
when(storage.create(eq("memorydb"), eq("memorydb-clusters.json"), any())).thenAnswer(inv -> clusters);
|
||||
when(storage.create(eq("memorydb"), eq("memorydb-users.json"), any())).thenAnswer(inv -> users);
|
||||
when(storage.create(eq("memorydb"), eq("memorydb-acls.json"), any())).thenAnswer(inv -> acls);
|
||||
service = new MemoryDbService(containers, proxies, mock(SigV4Validator.class), storage, config,
|
||||
new RegionResolver("us-east-1", DEFAULT_ACCOUNT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void creationPersistsItsOwnerVolumeAndPortBeforeStartingDocker() {
|
||||
when(containers.tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenAnswer(inv -> {
|
||||
Cluster pending = clusters.getForAccount(DEFAULT_ACCOUNT, "us-east-1:new").orElseThrow();
|
||||
assertEquals(ClusterStatus.CREATING, pending.getStatus());
|
||||
assertEquals(DEFAULT_ACCOUNT, pending.getAccountId());
|
||||
assertEquals("us-east-1", pending.getRegion());
|
||||
assertEquals(inv.getArgument(2), pending.getVolumeId());
|
||||
assertEquals(17400, pending.getProxyPort());
|
||||
assertNull(pending.getClusterEndpoint());
|
||||
return new MemoryDbContainerHandle("new-cid", inv.getArgument(0), "localhost", 6379);
|
||||
});
|
||||
|
||||
assertEquals(ClusterStatus.AVAILABLE, service.createCluster(spec("new"), "us-east-1").getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedOwnershipPersistenceDoesNotAllocateRuntimeAndReleasesItsPort() {
|
||||
doThrow(new IllegalStateException("snapshot rejected")).when(clusters)
|
||||
.putAllAtomicallyForAccount(eq(DEFAULT_ACCOUNT), anyMap());
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> service.createCluster(spec("new"), "us-east-1"));
|
||||
|
||||
verifyNoInteractions(containers, proxies);
|
||||
assertTrue(clusters.getForAccount(DEFAULT_ACCOUNT, "us-east-1:new").isEmpty());
|
||||
doCallRealMethod().when(clusters).putAllAtomicallyForAccount(eq(DEFAULT_ACCOUNT), anyMap());
|
||||
when(containers.tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(new MemoryDbContainerHandle("retry-cid", "retry", "localhost", 6379));
|
||||
assertEquals(17400, service.createCluster(spec("retry"), "us-east-1").getProxyPort());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedCleanupRetainsOwnershipAndPortUntilDeletionRetries() {
|
||||
MemoryDbContainerHandle handle = new MemoryDbContainerHandle("failed-cid",
|
||||
"000000000000-us-east-1-failed", "localhost", 6379);
|
||||
when(containers.tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(handle);
|
||||
doThrow(new IllegalStateException("proxy rejected")).when(proxies)
|
||||
.startProxy(eq(handle.getClusterName()), anyBoolean(), anyInt(), anyString(), anyInt(), any());
|
||||
doThrow(new IllegalStateException("Docker cleanup rejected")).when(containers).stop(any(MemoryDbContainerHandle.class));
|
||||
|
||||
IllegalStateException failure = assertThrows(IllegalStateException.class,
|
||||
() -> service.createCluster(spec("failed"), "us-east-1"));
|
||||
|
||||
assertEquals(1, failure.getSuppressed().length);
|
||||
Cluster retained = service.getCluster("failed", "us-east-1");
|
||||
assertEquals(ClusterStatus.CREATING, retained.getStatus());
|
||||
assertNull(retained.getClusterEndpoint());
|
||||
assertEquals("failed-cid", retained.getContainerId());
|
||||
assertNotNull(retained.getVolumeId());
|
||||
assertEquals(17401, service.createCluster(spec("other"), "us-east-1").getProxyPort());
|
||||
doNothing().when(containers).stop(any(MemoryDbContainerHandle.class));
|
||||
service.deleteCluster("failed", "us-east-1");
|
||||
assertThrows(AwsException.class, () -> service.getCluster("failed", "us-east-1"));
|
||||
assertEquals(17400, service.createCluster(spec("replacement"), "us-east-1").getProxyPort());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedRollbackPersistenceKeepsTheClusterUnavailableAndItsPortReserved() {
|
||||
AtomicInteger writes = new AtomicInteger();
|
||||
doAnswer(inv -> {
|
||||
if (writes.incrementAndGet() == 2) {
|
||||
throw new IllegalStateException("final record write rejected");
|
||||
}
|
||||
return inv.callRealMethod();
|
||||
}).when(clusters).putAllAtomicallyForAccount(anyString(), anyMap());
|
||||
doThrow(new IllegalStateException("rollback record deletion rejected"))
|
||||
.when(clusters).deleteAllAtomicallyForAccounts(anyMap());
|
||||
when(containers.tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenAnswer(inv -> new MemoryDbContainerHandle("owned-cid", inv.getArgument(0),
|
||||
"localhost", 6379));
|
||||
|
||||
IllegalStateException failure = assertThrows(IllegalStateException.class,
|
||||
() -> service.createCluster(spec("failed"), "us-east-1"));
|
||||
|
||||
assertEquals(1, failure.getSuppressed().length);
|
||||
Cluster retained = service.getCluster("failed", "us-east-1");
|
||||
assertEquals(ClusterStatus.CREATING, retained.getStatus());
|
||||
assertNull(retained.getClusterEndpoint());
|
||||
assertNull(retained.getContainerId());
|
||||
assertEquals(17401, service.createCluster(spec("other"), "us-east-1").getProxyPort());
|
||||
doCallRealMethod().when(clusters).deleteAllAtomicallyForAccounts(anyMap());
|
||||
service.deleteCluster("failed", "us-east-1");
|
||||
assertEquals(17400, service.createCluster(spec("replacement"), "us-east-1").getProxyPort());
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoresEveryOwnerAndRegionWithTheirOwnAuthenticationAndReservedPorts() throws Exception {
|
||||
Cluster first = persisted(DEFAULT_ACCOUNT, "us-east-1", "same", 17400);
|
||||
Cluster second = persisted("111111111111", "eu-west-1", "same", 17401);
|
||||
passwordAcl(first, "first-secret");
|
||||
passwordAcl(second, "second-secret");
|
||||
Map<Integer, MemoryDbAuthProxy.AuthValidator> validators = new ConcurrentHashMap<>();
|
||||
doAnswer(inv -> {
|
||||
validators.put(inv.getArgument(2), inv.getArgument(5));
|
||||
return null;
|
||||
}).when(proxies).startProxy(anyString(), eq(true), anyInt(), anyString(), anyInt(), any());
|
||||
when(containers.tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenAnswer(inv -> new MemoryDbContainerHandle(inv.getArgument(2), inv.getArgument(0),
|
||||
"127.0.0.1", 6379));
|
||||
|
||||
service.restorePersistedRuntime().get(5, TimeUnit.SECONDS);
|
||||
|
||||
assertEquals(ClusterStatus.AVAILABLE, first.getStatus());
|
||||
assertEquals(ClusterStatus.AVAILABLE, second.getStatus());
|
||||
assertEquals(17400, first.getClusterEndpoint().port());
|
||||
assertEquals(17401, second.getClusterEndpoint().port());
|
||||
assertTrue(validators.get(17400).authenticate("user", "first-secret"));
|
||||
assertFalse(validators.get(17400).authenticate("user", "second-secret"));
|
||||
assertTrue(validators.get(17401).authenticate("user", "second-secret"));
|
||||
assertFalse(validators.get(17401).authenticate("user", "first-secret"));
|
||||
verify(containers).tryStart(eq("000000000000-us-east-1-same"), eq("valkey/valkey:8"), eq(first.getVolumeId()),
|
||||
eq(DEFAULT_ACCOUNT), eq("us-east-1"), eq("same"));
|
||||
verify(containers).tryStart(eq("111111111111-eu-west-1-same"), eq("valkey/valkey:8"), eq(second.getVolumeId()),
|
||||
eq("111111111111"), eq("eu-west-1"), eq("same"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultAccountNameCannotCollideWithAnotherAccountsBackendIdentity() throws Exception {
|
||||
persisted(DEFAULT_ACCOUNT, "us-east-1", "111111111111-eu-west-1-same", 17400);
|
||||
persisted("111111111111", "eu-west-1", "same", 17401);
|
||||
Map<String, String> backendOwners = new ConcurrentHashMap<>();
|
||||
when(containers.tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenAnswer(inv -> {
|
||||
String identity = inv.getArgument(0);
|
||||
String account = inv.getArgument(3);
|
||||
assertNull(backendOwners.putIfAbsent(identity, account),
|
||||
"Backend identities must remain unique across account and region boundaries");
|
||||
return new MemoryDbContainerHandle(inv.getArgument(2), identity, "localhost", 6379);
|
||||
});
|
||||
|
||||
service.restorePersistedRuntime().get(5, TimeUnit.SECONDS);
|
||||
|
||||
assertEquals(2, backendOwners.size());
|
||||
assertEquals(2, backendOwners.values().stream().distinct().count());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletionWhileBackendStartsDoesNotRestoreTheRecordOrReleaseAnotherClustersPort() throws Exception {
|
||||
Cluster old = persisted(DEFAULT_ACCOUNT, "us-east-1", "old", 17400);
|
||||
CountDownLatch started = new CountDownLatch(1);
|
||||
CountDownLatch finish = new CountDownLatch(1);
|
||||
MemoryDbContainerHandle oldHandle = new MemoryDbContainerHandle("old-cid", "old", "localhost", 6379);
|
||||
when(containers.tryStart(eq("000000000000-us-east-1-old"), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenAnswer(inv -> {
|
||||
started.countDown();
|
||||
assertTrue(finish.await(5, TimeUnit.SECONDS));
|
||||
return oldHandle;
|
||||
});
|
||||
when(containers.tryStart(eq("000000000000-us-east-1-replacement"), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(new MemoryDbContainerHandle("new-cid", "replacement", "localhost", 6379));
|
||||
CompletableFuture<Void> restored = service.restorePersistedRuntime();
|
||||
try {
|
||||
assertTrue(started.await(5, TimeUnit.SECONDS));
|
||||
assertEquals(ClusterStatus.CREATING, old.getStatus());
|
||||
service.deleteCluster("old", "us-east-1");
|
||||
Cluster spec = new Cluster();
|
||||
spec.setName("replacement");
|
||||
spec.setAclName("open-access");
|
||||
Cluster replacement = service.createCluster(spec, "us-east-1");
|
||||
assertEquals(17400, replacement.getProxyPort());
|
||||
finish.countDown();
|
||||
restored.get(5, TimeUnit.SECONDS);
|
||||
assertTrue(clusters.getForAccount(DEFAULT_ACCOUNT, "us-east-1:old").isEmpty());
|
||||
verify(containers).stop(oldHandle);
|
||||
verify(proxies, never()).startProxy(eq("000000000000-us-east-1-old"), anyBoolean(), anyInt(), anyString(), anyInt(), any());
|
||||
Cluster nextSpec = new Cluster();
|
||||
nextSpec.setName("next");
|
||||
nextSpec.setAclName("open-access");
|
||||
assertEquals(17401, service.createCluster(nextSpec, "us-east-1").getProxyPort());
|
||||
} finally {
|
||||
finish.countDown();
|
||||
restored.get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingPendingCreateDoesNotResurrectItOrReleaseAReusedPort() throws Exception {
|
||||
CountDownLatch started = new CountDownLatch(1);
|
||||
CountDownLatch finish = new CountDownLatch(1);
|
||||
MemoryDbContainerHandle oldHandle = new MemoryDbContainerHandle("old-cid",
|
||||
"000000000000-us-east-1-old", "localhost", 6379);
|
||||
when(containers.tryStart(eq(oldHandle.getClusterName()), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenAnswer(inv -> {
|
||||
started.countDown();
|
||||
assertTrue(finish.await(5, TimeUnit.SECONDS));
|
||||
return oldHandle;
|
||||
});
|
||||
when(containers.tryStart(eq("000000000000-us-east-1-other"), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(new MemoryDbContainerHandle("other-cid", "other", "localhost", 6379));
|
||||
CompletableFuture<Cluster> creation = CompletableFuture.supplyAsync(
|
||||
() -> service.createCluster(spec("old"), "us-east-1"));
|
||||
try {
|
||||
assertTrue(started.await(5, TimeUnit.SECONDS));
|
||||
assertEquals(ClusterStatus.CREATING, service.getCluster("old", "us-east-1").getStatus());
|
||||
service.deleteCluster("old", "us-east-1");
|
||||
assertEquals(17400, service.createCluster(spec("other"), "us-east-1").getProxyPort());
|
||||
finish.countDown();
|
||||
assertThrows(ExecutionException.class, () -> creation.get(5, TimeUnit.SECONDS));
|
||||
assertThrows(AwsException.class, () -> service.getCluster("old", "us-east-1"));
|
||||
verify(containers).stop(oldHandle);
|
||||
verify(proxies, never()).startProxy(eq(oldHandle.getClusterName()),
|
||||
anyBoolean(), anyInt(), anyString(), anyInt(), any());
|
||||
assertEquals(17401, service.createCluster(spec("next"), "us-east-1").getProxyPort());
|
||||
} finally {
|
||||
finish.countDown();
|
||||
assertThrows(ExecutionException.class, () -> creation.get(5, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedBackendIsNotAdvertisedAsAvailableAndOtherClustersStillRestore() throws Exception {
|
||||
Cluster failed = persisted(DEFAULT_ACCOUNT, "us-east-1", "failed", 17400);
|
||||
Cluster healthy = persisted(DEFAULT_ACCOUNT, "us-east-1", "healthy", 17401);
|
||||
when(containers.tryStart(eq("000000000000-us-east-1-failed"), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenThrow(new IllegalStateException("backend rejected"));
|
||||
when(containers.tryStart(eq("000000000000-us-east-1-healthy"), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(new MemoryDbContainerHandle("healthy-cid", "healthy", "localhost", 6379));
|
||||
|
||||
assertThrows(ExecutionException.class, () -> service.restorePersistedRuntime().get(5, TimeUnit.SECONDS));
|
||||
|
||||
assertEquals(ClusterStatus.CREATING, failed.getStatus());
|
||||
assertNull(failed.getClusterEndpoint());
|
||||
assertNull(failed.getContainerId());
|
||||
assertEquals(ClusterStatus.AVAILABLE, healthy.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unprefixedLegacyArnRestoresItsOwnAccountAndRegion() throws Exception {
|
||||
Cluster legacy = spec("legacy");
|
||||
legacy.setArn("arn:aws:memorydb:eu-west-1:111111111111:cluster/legacy");
|
||||
rawClusters.put("legacy", legacy);
|
||||
when(containers.tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(new MemoryDbContainerHandle("legacy-cid", "legacy", "localhost", 6379));
|
||||
|
||||
service.restorePersistedRuntime().get(5, TimeUnit.SECONDS);
|
||||
|
||||
assertSame(legacy, clusters.getForAccount("111111111111", "eu-west-1:legacy").orElseThrow());
|
||||
assertEquals("111111111111", legacy.getAccountId());
|
||||
assertEquals("eu-west-1", legacy.getRegion());
|
||||
assertTrue(rawClusters.get("legacy").isEmpty());
|
||||
assertTrue(service.describeClusters(null, "eu-west-1").isEmpty());
|
||||
verify(containers).tryStart(eq("111111111111-eu-west-1-legacy"), eq("valkey/valkey:8"), eq(legacy.getVolumeId()),
|
||||
eq("111111111111"), eq("eu-west-1"), eq("legacy"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void oldAccountPrefixedNameMigratesToItsRegionalKey() throws Exception {
|
||||
Cluster legacy = spec("legacy");
|
||||
legacy.setAccountId("111111111111");
|
||||
legacy.setRegion("eu-west-1");
|
||||
rawClusters.put("111111111111/legacy", legacy);
|
||||
|
||||
service.restorePersistedRuntime().get(5, TimeUnit.SECONDS);
|
||||
|
||||
assertSame(legacy, clusters.getForAccount("111111111111", "eu-west-1:legacy").orElseThrow());
|
||||
assertTrue(rawClusters.get("111111111111/legacy").isEmpty());
|
||||
assertTrue(service.describeClusters(null, "eu-west-1").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void existingScopedRecordWinsWithoutDiscardingConflictingLegacyData() throws Exception {
|
||||
Cluster current = persisted(DEFAULT_ACCOUNT, "us-east-1", "same", 17400);
|
||||
Cluster legacy = spec("same");
|
||||
legacy.setVolumeId("retained-legacy-data");
|
||||
rawClusters.put("same", legacy);
|
||||
|
||||
service.restorePersistedRuntime().get(5, TimeUnit.SECONDS);
|
||||
|
||||
assertEquals(List.of(current), List.copyOf(service.describeClusters(null, "us-east-1")));
|
||||
assertEquals(List.of(current), List.copyOf(service.describeClusters("same", "us-east-1")));
|
||||
assertSame(current, service.getCluster("same", "us-east-1"));
|
||||
assertEquals(List.of(legacy), rawClusters.scan(
|
||||
key -> key.startsWith(DEFAULT_ACCOUNT + "/legacy-clusters/")));
|
||||
assertTrue(rawClusters.get("same").isEmpty());
|
||||
verify(containers, times(1)).tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void contradictoryStoredOwnerIsReportedWithoutAllocatingOrReassigningIt() {
|
||||
Cluster inconsistent = spec("conflict");
|
||||
inconsistent.setAccountId(DEFAULT_ACCOUNT);
|
||||
inconsistent.setRegion("eu-west-1");
|
||||
rawClusters.put("111111111111/eu-west-1:conflict", inconsistent);
|
||||
|
||||
assertThrows(ExecutionException.class, () -> service.restorePersistedRuntime().get(5, TimeUnit.SECONDS));
|
||||
|
||||
assertEquals(DEFAULT_ACCOUNT, inconsistent.getAccountId());
|
||||
assertSame(inconsistent, rawClusters.get("111111111111/eu-west-1:conflict").orElseThrow());
|
||||
verifyNoInteractions(containers, proxies);
|
||||
}
|
||||
|
||||
@Test
|
||||
void restorationUsesThePersistedArnRegionWhenTheLegacyRegionFieldIsMissing() throws Exception {
|
||||
Cluster cluster = persisted(DEFAULT_ACCOUNT, "eu-west-1", "legacy", 17400);
|
||||
cluster.setRegion(null);
|
||||
cluster.setArn("arn:aws:memorydb:eu-west-1:000000000000:cluster/legacy");
|
||||
when(containers.tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(new MemoryDbContainerHandle("restored-cid", "legacy", "localhost", 6379));
|
||||
|
||||
service.restorePersistedRuntime().get(5, TimeUnit.SECONDS);
|
||||
|
||||
assertEquals("eu-west-1", cluster.getRegion());
|
||||
verify(containers).tryStart(eq("000000000000-eu-west-1-legacy"), eq("valkey/valkey:8"), eq(cluster.getVolumeId()),
|
||||
eq(DEFAULT_ACCOUNT), eq("eu-west-1"), eq("legacy"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingLegacyRecordKeepsItsStoredOwnerAndCanBeDeletedAfterRestart() throws Exception {
|
||||
Cluster cluster = persisted(DEFAULT_ACCOUNT, "us-east-1", "deleting", 17400);
|
||||
cluster.setAccountId(null);
|
||||
cluster.setRegion(null);
|
||||
cluster.setStatus(ClusterStatus.DELETING);
|
||||
|
||||
service.restorePersistedRuntime().get(5, TimeUnit.SECONDS);
|
||||
|
||||
verifyNoInteractions(containers, proxies);
|
||||
assertEquals(DEFAULT_ACCOUNT, cluster.getAccountId());
|
||||
assertEquals("us-east-1", cluster.getRegion());
|
||||
service.deleteCluster("deleting", "us-east-1");
|
||||
assertThrows(AwsException.class, () -> service.getCluster("deleting", "us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void restorationRetiresPersistedBackendBeforeReplacingIt() throws Exception {
|
||||
Cluster cluster = persisted(DEFAULT_ACCOUNT, "us-east-1", "legacy", 17400);
|
||||
cluster.setContainerId("legacy-cid");
|
||||
cluster.setContainerHost("localhost");
|
||||
cluster.setContainerPort(6379);
|
||||
when(containers.isDockerReachable()).thenReturn(true);
|
||||
when(containers.tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(new MemoryDbContainerHandle("replacement-cid", "legacy", "localhost", 6379));
|
||||
|
||||
service.restorePersistedRuntime().get(5, TimeUnit.SECONDS);
|
||||
|
||||
InOrder ordering = inOrder(containers);
|
||||
ordering.verify(containers).isDockerReachable();
|
||||
ordering.verify(containers).stop(argThat(handle -> "legacy-cid".equals(handle.getContainerId())));
|
||||
ordering.verify(containers).tryStart(eq("000000000000-us-east-1-legacy"), eq("valkey/valkey:8"),
|
||||
eq(cluster.getVolumeId()), eq(DEFAULT_ACCOUNT), eq("us-east-1"), eq("legacy"));
|
||||
assertEquals("replacement-cid", cluster.getContainerId());
|
||||
assertEquals(ClusterStatus.AVAILABLE, cluster.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unavailableDaemonDoesNotDiscardPersistedBackendOwnership() throws Exception {
|
||||
Cluster cluster = persisted(DEFAULT_ACCOUNT, "us-east-1", "legacy", 17400);
|
||||
cluster.setContainerId("legacy-cid");
|
||||
cluster.setContainerHost("localhost");
|
||||
cluster.setContainerPort(6379);
|
||||
String volumeId = cluster.getVolumeId();
|
||||
when(containers.isDockerReachable()).thenReturn(false);
|
||||
|
||||
service.restorePersistedRuntime().get(5, TimeUnit.SECONDS);
|
||||
|
||||
assertEquals("legacy-cid", cluster.getContainerId());
|
||||
assertEquals(volumeId, cluster.getVolumeId());
|
||||
assertEquals(ClusterStatus.AVAILABLE, cluster.getStatus());
|
||||
verify(containers, never()).stop(any(MemoryDbContainerHandle.class));
|
||||
verify(containers, never()).tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
verifyNoInteractions(proxies);
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedPersistedBackendCleanupKeepsTheExactOldBackendForRetry() throws Exception {
|
||||
Cluster cluster = persisted(DEFAULT_ACCOUNT, "us-east-1", "legacy", 17400);
|
||||
cluster.setContainerId("legacy-cid");
|
||||
cluster.setContainerHost("localhost");
|
||||
cluster.setContainerPort(6379);
|
||||
when(containers.isDockerReachable()).thenReturn(true);
|
||||
doThrow(new IllegalStateException("legacy cleanup rejected")).when(containers)
|
||||
.stop(any(MemoryDbContainerHandle.class));
|
||||
|
||||
assertThrows(ExecutionException.class, () -> service.restorePersistedRuntime().get(5, TimeUnit.SECONDS));
|
||||
|
||||
assertEquals("legacy-cid", cluster.getContainerId());
|
||||
assertEquals(ClusterStatus.CREATING, cluster.getStatus());
|
||||
assertNull(cluster.getClusterEndpoint());
|
||||
verify(containers, never()).tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
assertEquals(17401, service.createCluster(spec("other"), "us-east-1").getProxyPort());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedRestoreCleanupRetainsItsBackendPortAndDataForDeletionRetry() throws Exception {
|
||||
Cluster failed = persisted(DEFAULT_ACCOUNT, "us-east-1", "failed", 17400);
|
||||
String volumeId = failed.getVolumeId();
|
||||
MemoryDbContainerHandle handle = new MemoryDbContainerHandle("restore-cid",
|
||||
"000000000000-us-east-1-failed", "localhost", 6379);
|
||||
when(containers.tryStart(eq(handle.getClusterName()), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(handle);
|
||||
when(containers.tryStart(eq("000000000000-us-east-1-other"), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(new MemoryDbContainerHandle("other-cid", "other", "localhost", 6379));
|
||||
doThrow(new IllegalStateException("proxy rejected")).when(proxies)
|
||||
.startProxy(eq(handle.getClusterName()), anyBoolean(), anyInt(), anyString(), anyInt(), any());
|
||||
doThrow(new IllegalStateException("Docker cleanup rejected")).when(containers).stop(any(MemoryDbContainerHandle.class));
|
||||
|
||||
ExecutionException failure = assertThrows(ExecutionException.class,
|
||||
() -> service.restorePersistedRuntime().get(5, TimeUnit.SECONDS));
|
||||
|
||||
assertEquals(1, failure.getCause().getSuppressed().length);
|
||||
assertEquals(ClusterStatus.CREATING, failed.getStatus());
|
||||
assertNull(failed.getClusterEndpoint());
|
||||
assertEquals("restore-cid", failed.getContainerId());
|
||||
assertEquals(volumeId, failed.getVolumeId());
|
||||
assertEquals(17401, service.createCluster(spec("other"), "us-east-1").getProxyPort());
|
||||
verify(containers, never()).removeStorage(anyString(), anyString());
|
||||
doNothing().when(containers).stop(any(MemoryDbContainerHandle.class));
|
||||
service.deleteCluster("failed", "us-east-1");
|
||||
verify(containers).removeStorage(handle.getClusterName(), volumeId);
|
||||
assertThrows(AwsException.class, () -> service.getCluster("failed", "us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void retryingRestorationReusesThePortRetainedAfterCleanupFailure() throws Exception {
|
||||
Cluster failed = persisted(DEFAULT_ACCOUNT, "us-east-1", "failed", 17400);
|
||||
MemoryDbContainerHandle handle = new MemoryDbContainerHandle("restore-cid",
|
||||
"000000000000-us-east-1-failed", "localhost", 6379);
|
||||
when(containers.tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(handle);
|
||||
doThrow(new IllegalStateException("proxy rejected")).when(proxies)
|
||||
.startProxy(eq(handle.getClusterName()), anyBoolean(), anyInt(), anyString(), anyInt(), any());
|
||||
doThrow(new IllegalStateException("Docker cleanup rejected")).when(containers).stop(any(MemoryDbContainerHandle.class));
|
||||
assertThrows(ExecutionException.class, () -> service.restorePersistedRuntime().get(5, TimeUnit.SECONDS));
|
||||
doNothing().when(proxies)
|
||||
.startProxy(eq(handle.getClusterName()), anyBoolean(), anyInt(), anyString(), anyInt(), any());
|
||||
doNothing().when(containers).stop(any(MemoryDbContainerHandle.class));
|
||||
|
||||
service.restorePersistedRuntime().get(5, TimeUnit.SECONDS);
|
||||
|
||||
assertEquals(ClusterStatus.AVAILABLE, failed.getStatus());
|
||||
assertEquals(17400, failed.getClusterEndpoint().port());
|
||||
assertEquals(17401, service.createCluster(spec("other"), "us-east-1").getProxyPort());
|
||||
}
|
||||
|
||||
@Test
|
||||
void mockRestorationDoesNotAllocateContainersOrProxies() throws Exception {
|
||||
persisted(DEFAULT_ACCOUNT, "us-east-1", "mocked", 17400);
|
||||
when(config.services().memorydb().mock()).thenReturn(true);
|
||||
|
||||
service.restorePersistedRuntime().get(5, TimeUnit.SECONDS);
|
||||
|
||||
verifyNoInteractions(containers, proxies);
|
||||
}
|
||||
|
||||
private Cluster persisted(String account, String region, String name, int port) {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setName(name);
|
||||
cluster.setAccountId(account);
|
||||
cluster.setRegion(region);
|
||||
cluster.setStatus(ClusterStatus.AVAILABLE);
|
||||
cluster.setAclName("open-access");
|
||||
cluster.setProxyPort(port);
|
||||
cluster.setVolumeId(account + "-" + region + "-" + name);
|
||||
clusters.putForAccount(account, region + ":" + name, cluster);
|
||||
return cluster;
|
||||
}
|
||||
|
||||
private Cluster spec(String name) {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setName(name);
|
||||
cluster.setAclName("open-access");
|
||||
return cluster;
|
||||
}
|
||||
|
||||
private void passwordAcl(Cluster cluster, String password) {
|
||||
cluster.setAclName("private");
|
||||
Acl acl = new Acl();
|
||||
acl.setName("private");
|
||||
acl.setUserNames(List.of("user"));
|
||||
acls.putForAccount(cluster.getAccountId(), cluster.getRegion() + ":private", acl);
|
||||
User user = new User();
|
||||
user.setName("user");
|
||||
user.setAuthMode(AuthMode.PASSWORD);
|
||||
user.setPasswords(List.of(password));
|
||||
users.putForAccount(cluster.getAccountId(), cluster.getRegion() + ":user", user);
|
||||
}
|
||||
}
|
||||
+38
-13
@@ -30,6 +30,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
@@ -81,7 +82,7 @@ class MemoryDbServiceTest {
|
||||
"000000000000", inv.getArgument(2)).toString());
|
||||
|
||||
when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000"));
|
||||
when(containerManager.tryStart(anyString(), anyString()))
|
||||
when(containerManager.tryStart(anyString(), anyString(), any(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(new MemoryDbContainerHandle("cid", "cluster", "localhost", 6379));
|
||||
doNothing().when(proxyManager).startProxy(anyString(), anyBoolean(), anyInt(), anyString(), anyInt(), any());
|
||||
|
||||
@@ -89,6 +90,29 @@ class MemoryDbServiceTest {
|
||||
storageFactory, config, regionResolver);
|
||||
}
|
||||
|
||||
@Test
|
||||
void recreatedPersistentClusterDoesNotReuseRetainedDataVolume() {
|
||||
EmulatorConfig.StorageConfig storage = mock(EmulatorConfig.StorageConfig.class);
|
||||
when(config.storage()).thenReturn(storage);
|
||||
when(storage.mode()).thenReturn("persistent");
|
||||
when(containerManager.tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(new MemoryDbContainerHandle("cid", "durable", "localhost", 6379));
|
||||
Cluster spec = new Cluster();
|
||||
spec.setName("durable");
|
||||
spec.setAclName("open-access");
|
||||
|
||||
Cluster first = service.createCluster(spec, "us-east-1");
|
||||
service.deleteCluster("durable", "us-east-1");
|
||||
Cluster replacement = service.createCluster(spec, "us-east-1");
|
||||
|
||||
assertNotEquals(first.getVolumeId(), replacement.getVolumeId());
|
||||
verify(containerManager).removeStorage("000000000000-us-east-1-durable", first.getVolumeId());
|
||||
verify(containerManager).tryStart(eq("000000000000-us-east-1-durable"), eq("valkey/valkey:8"),
|
||||
eq(first.getVolumeId()), eq("000000000000"), eq("us-east-1"), eq("durable"));
|
||||
verify(containerManager).tryStart(eq("000000000000-us-east-1-durable"), eq("valkey/valkey:8"),
|
||||
eq(replacement.getVolumeId()), eq("000000000000"), eq("us-east-1"), eq("durable"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createAndDescribeCluster() {
|
||||
Cluster spec = new Cluster();
|
||||
@@ -341,7 +365,7 @@ class MemoryDbServiceTest {
|
||||
void failedProvisioningReleasesProxyPort() {
|
||||
when(mdbConfig.proxyBasePort()).thenReturn(16400);
|
||||
when(mdbConfig.proxyMaxPort()).thenReturn(16400); // exactly one port available
|
||||
when(containerManager.tryStart(anyString(), anyString()))
|
||||
when(containerManager.tryStart(anyString(), anyString(), any(), anyString(), anyString(), anyString()))
|
||||
.thenThrow(new RuntimeException("docker unavailable"))
|
||||
.thenReturn(new MemoryDbContainerHandle("cid", "c2", "localhost", 6379));
|
||||
|
||||
@@ -361,11 +385,11 @@ class MemoryDbServiceTest {
|
||||
@Test
|
||||
void failedProvisioningRollsBackContainerAndReleasesProxyPort() {
|
||||
MemoryDbContainerHandle handle = new MemoryDbContainerHandle("cid", "c1", "localhost", 6379);
|
||||
when(containerManager.tryStart(anyString(), anyString())).thenReturn(handle);
|
||||
when(containerManager.tryStart(anyString(), anyString(), any(), anyString(), anyString(), anyString())).thenReturn(handle);
|
||||
|
||||
// Proxy startup blows up after the port is reserved and the container is started.
|
||||
doThrow(new RuntimeException("proxy boom"))
|
||||
.when(proxyManager).startProxy(eq("c1"), anyBoolean(), anyInt(), anyString(), anyInt(), any());
|
||||
.when(proxyManager).startProxy(eq("000000000000-us-east-1-c1"), anyBoolean(), anyInt(), anyString(), anyInt(), any());
|
||||
|
||||
Cluster spec = new Cluster();
|
||||
spec.setName("c1");
|
||||
@@ -378,9 +402,9 @@ class MemoryDbServiceTest {
|
||||
// handle from this request, not by name: a concurrent create for the same cluster name
|
||||
// could have raced ahead and overwritten the registered container, and looking it up by
|
||||
// name here would risk stopping that other request's container instead of this one's.
|
||||
verify(proxyManager).stopProxy("c1");
|
||||
verify(proxyManager).stopProxy("000000000000-us-east-1-c1");
|
||||
verify(containerManager).stop(handle);
|
||||
verify(containerManager, never()).stopByClusterName(anyString());
|
||||
verify(containerManager, never()).stopByClusterName(anyString(), anyString(), anyString(), anyString());
|
||||
|
||||
// The reserved proxy port was released: a subsequent successful create reuses the base port
|
||||
// instead of skipping to the next one (which is what a leak would cause).
|
||||
@@ -400,7 +424,8 @@ class MemoryDbServiceTest {
|
||||
// and (crucially) a readiness timeout, where start() created + registered the container
|
||||
// before throwing, so no handle ever reaches the service.
|
||||
doThrow(new RuntimeException("readiness boom"))
|
||||
.when(containerManager).tryStart(eq("c1"), anyString());
|
||||
.when(containerManager).tryStart(eq("000000000000-us-east-1-c1"), anyString(), any(),
|
||||
anyString(), anyString(), anyString());
|
||||
|
||||
Cluster spec = new Cluster();
|
||||
spec.setName("c1");
|
||||
@@ -413,10 +438,10 @@ class MemoryDbServiceTest {
|
||||
verify(proxyManager, never()).stopProxy(anyString());
|
||||
// ...but the container must still be cleaned up by name, since start() may have created
|
||||
// and registered it before failing. Cleaning up by handle here would orphan it.
|
||||
verify(containerManager).stopByClusterName("c1");
|
||||
verify(containerManager).stopByClusterName(eq("000000000000-us-east-1-c1"), anyString(), anyString(), anyString());
|
||||
|
||||
// The reserved proxy port was still released: a subsequent successful create reuses the base port.
|
||||
when(containerManager.tryStart(anyString(), anyString()))
|
||||
when(containerManager.tryStart(anyString(), anyString(), any(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(new MemoryDbContainerHandle("cid", "c2", "localhost", 6379));
|
||||
Cluster second = new Cluster();
|
||||
second.setName("c2");
|
||||
@@ -445,7 +470,7 @@ class MemoryDbServiceTest {
|
||||
void concurrentCreateForSameNameIsRejectedWhileFirstIsProvisioning() throws InterruptedException {
|
||||
CountDownLatch startedLatch = new CountDownLatch(1);
|
||||
CountDownLatch releaseLatch = new CountDownLatch(1);
|
||||
when(containerManager.tryStart(anyString(), anyString())).thenAnswer(inv -> {
|
||||
when(containerManager.tryStart(anyString(), anyString(), any(), anyString(), anyString(), anyString())).thenAnswer(inv -> {
|
||||
startedLatch.countDown();
|
||||
assertTrue(releaseLatch.await(5, TimeUnit.SECONDS), "test timed out waiting for release");
|
||||
return new MemoryDbContainerHandle("cid", "c1", "localhost", 6379);
|
||||
@@ -465,7 +490,7 @@ class MemoryDbServiceTest {
|
||||
AwsException ex = assertThrows(AwsException.class, () -> service.createCluster(spec2, "us-east-1"));
|
||||
assertEquals("ClusterAlreadyExistsFault", ex.jsonType());
|
||||
verify(containerManager, never()).stop(any());
|
||||
verify(containerManager, never()).stopByClusterName(anyString());
|
||||
verify(containerManager, never()).stopByClusterName(anyString(), anyString(), anyString(), anyString());
|
||||
|
||||
releaseLatch.countDown();
|
||||
firstRequest.join(5000);
|
||||
@@ -530,7 +555,7 @@ class MemoryDbServiceTest {
|
||||
}
|
||||
}
|
||||
assertEquals(1, succeeded, "exactly one create of the name succeeds");
|
||||
verify(containerManager, times(1)).tryStart(anyString(), anyString());
|
||||
verify(containerManager, times(1)).tryStart(anyString(), anyString(), any(), anyString(), anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -589,7 +614,7 @@ class MemoryDbServiceTest {
|
||||
// tryStart() returns null when no Docker daemon is reachable. The cluster record is
|
||||
// metadata, so the create still succeeds, the cluster reaches 'available' on the first
|
||||
// describe (what SDK/Terraform waiters poll), and no auth proxy is started.
|
||||
when(containerManager.tryStart(anyString(), anyString())).thenReturn(null);
|
||||
when(containerManager.tryStart(anyString(), anyString(), any(), anyString(), anyString(), anyString())).thenReturn(null);
|
||||
|
||||
Cluster spec = new Cluster();
|
||||
spec.setName("no-docker-cluster");
|
||||
|
||||
+201
-36
@@ -8,32 +8,107 @@ import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
|
||||
import org.jboss.logging.Logger;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class MemoryDbContainerManagerTest {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(MemoryDbContainerManagerTest.class);
|
||||
@Test
|
||||
void failedStartPreservesTheCleanupAwareLifecycleFailure() {
|
||||
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
|
||||
RuntimeException failure = new RuntimeException("backend start denied");
|
||||
when(lifecycle.createAndStartEphemeral(any())).thenThrow(failure);
|
||||
MemoryDbContainerManager manager = newManager(lifecycle);
|
||||
|
||||
assertSame(failure, assertThrows(RuntimeException.class,
|
||||
() -> manager.start("cache", "valkey/valkey:8")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stoppingBackendReclaimsImageDeclaredAnonymousVolumes() {
|
||||
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
|
||||
MemoryDbContainerManager manager = newManager(lifecycle);
|
||||
MemoryDbContainerHandle handle = new MemoryDbContainerHandle("owned-cid", "cache", "localhost", 6379);
|
||||
|
||||
manager.stop(handle);
|
||||
|
||||
verify(lifecycle).stopAndRemoveStrict("owned-cid", null, 5, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shutdownRejectsNewBackendStarts() {
|
||||
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
|
||||
MemoryDbContainerManager manager = newManager(lifecycle);
|
||||
|
||||
manager.stopAll();
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> manager.start("late", "valkey/valkey:8"));
|
||||
verify(lifecycle, Mockito.never()).createAndStartEphemeral(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shutdownWaitsForAdmittedCreateAndRemovesItsLateBackend() throws Exception {
|
||||
CountDownLatch entered = new CountDownLatch(1);
|
||||
CountDownLatch finish = new CountDownLatch(1);
|
||||
CountDownLatch shutdownStarted = new CountDownLatch(1);
|
||||
try (ServerSocket backend = new ServerSocket(0)) {
|
||||
CompletableFuture<Void> responder = startPongResponder(backend, 1);
|
||||
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
|
||||
when(lifecycle.createAndStartEphemeral(any())).thenAnswer(inv -> {
|
||||
entered.countDown();
|
||||
assertTrue(finish.await(5, TimeUnit.SECONDS));
|
||||
return new ContainerLifecycleManager.ContainerInfo("late-cid",
|
||||
Map.of(6379, new ContainerLifecycleManager.EndpointInfo(
|
||||
"127.0.0.1", backend.getLocalPort())));
|
||||
});
|
||||
MemoryDbContainerManager manager = newManager(lifecycle);
|
||||
CompletableFuture<MemoryDbContainerHandle> starting =
|
||||
CompletableFuture.supplyAsync(() -> manager.start("late", "valkey/valkey:8"));
|
||||
assertTrue(entered.await(5, TimeUnit.SECONDS));
|
||||
CompletableFuture<Void> shutdown = CompletableFuture.runAsync(() -> {
|
||||
shutdownStarted.countDown();
|
||||
manager.stopAll();
|
||||
});
|
||||
try {
|
||||
assertTrue(shutdownStarted.await(5, TimeUnit.SECONDS));
|
||||
assertThrows(TimeoutException.class, () -> shutdown.get(1, TimeUnit.SECONDS));
|
||||
} finally {
|
||||
finish.countDown();
|
||||
assertThrows(ExecutionException.class, () -> starting.get(5, TimeUnit.SECONDS));
|
||||
shutdown.get(5, TimeUnit.SECONDS);
|
||||
responder.get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
verify(lifecycle).stopAndRemoveStrict("late-cid", null, 5, true);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopByClusterNameRemovesByDeterministicNameWhenNothingRegistered() {
|
||||
@@ -46,7 +121,7 @@ class MemoryDbContainerManagerTest {
|
||||
// Rollback must still fall back to the deterministic name so nothing is orphaned.
|
||||
manager.stopByClusterName("my-cluster");
|
||||
|
||||
verify(lifecycleManager).removeIfExists("floci-aws-memorydb-my-cluster");
|
||||
verify(lifecycleManager).removeIfExistsStrict("floci-aws-memorydb-my-cluster", true);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -54,7 +129,7 @@ class MemoryDbContainerManagerTest {
|
||||
// Floci running inside Docker without a mounted daemon socket: the MemoryDB control
|
||||
// plane must keep working, so the failure is reported rather than propagated.
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
when(lifecycleManager.createAndStart(any()))
|
||||
when(lifecycleManager.createAndStartEphemeral(any()))
|
||||
.thenThrow(new RuntimeException("java.net.SocketException: No such file or directory"));
|
||||
when(lifecycleManager.getDockerClient()).thenThrow(
|
||||
new RuntimeException("java.net.SocketException: No such file or directory"));
|
||||
@@ -73,7 +148,7 @@ class MemoryDbContainerManagerTest {
|
||||
// A reachable daemon that cannot start the container is a genuine failure, not a
|
||||
// degraded mode: CreateCluster must still surface it.
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
when(lifecycleManager.createAndStart(any()))
|
||||
when(lifecycleManager.createAndStartEphemeral(any()))
|
||||
.thenThrow(new RuntimeException("no such image: valkey/valkey:8"));
|
||||
DockerClient dockerClient = mock(DockerClient.class, Mockito.RETURNS_DEEP_STUBS);
|
||||
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
|
||||
@@ -86,26 +161,14 @@ class MemoryDbContainerManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void tryStartReturnsTheHandleOnceADaemonIsReachable() throws IOException, InterruptedException {
|
||||
void tryStartReturnsTheHandleOnceADaemonIsReachable() throws Exception {
|
||||
// Real loopback socket standing in for the backend container's Redis port, so the
|
||||
// manager's PING/PONG readiness probe succeeds without a real container.
|
||||
try (ServerSocket serverSocket = new ServerSocket(0)) {
|
||||
Thread responder = new Thread(() -> {
|
||||
try (Socket socket = serverSocket.accept()) {
|
||||
socket.getInputStream().read(new byte[64]);
|
||||
OutputStream out = socket.getOutputStream();
|
||||
out.write("+PONG\r\n".getBytes(StandardCharsets.UTF_8));
|
||||
out.flush();
|
||||
} catch (IOException e) {
|
||||
// Test teardown races the socket close; nothing left to assert on.
|
||||
LOG.debugv(e, "Acceptor socket closed during test teardown");
|
||||
}
|
||||
});
|
||||
responder.setDaemon(true);
|
||||
responder.start();
|
||||
CompletableFuture<Void> responder = startPongResponder(serverSocket, 1);
|
||||
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo(
|
||||
when(lifecycleManager.createAndStartEphemeral(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo(
|
||||
"container-id", Map.of(6379, new ContainerLifecycleManager.EndpointInfo(
|
||||
"127.0.0.1", serverSocket.getLocalPort()))));
|
||||
|
||||
@@ -115,28 +178,23 @@ class MemoryDbContainerManagerTest {
|
||||
|
||||
assertEquals("container-id", handle.getContainerId());
|
||||
assertEquals(serverSocket.getLocalPort(), handle.getPort());
|
||||
responder.join(5000);
|
||||
Mockito.doThrow(new RuntimeException("cleanup rejected")).doNothing()
|
||||
.when(lifecycleManager).stopAndRemoveStrict("container-id", null, 5, true);
|
||||
assertThrows(RuntimeException.class, () -> manager.stop(handle));
|
||||
manager.stopAll();
|
||||
manager.stopAll();
|
||||
verify(lifecycleManager, Mockito.times(2)).stopAndRemoveStrict("container-id", null, 5, true);
|
||||
responder.get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void startLabelsContainerWithResourceIdentity() throws IOException {
|
||||
void startLabelsContainerWithResourceIdentity() throws Exception {
|
||||
try (ServerSocket serverSocket = new ServerSocket(0)) {
|
||||
Thread responder = new Thread(() -> {
|
||||
try (Socket socket = serverSocket.accept()) {
|
||||
socket.getInputStream().read(new byte[64]);
|
||||
OutputStream out = socket.getOutputStream();
|
||||
out.write("+PONG\r\n".getBytes(StandardCharsets.UTF_8));
|
||||
out.flush();
|
||||
} catch (IOException e) {
|
||||
LOG.debugv(e, "Acceptor socket closed during test teardown");
|
||||
}
|
||||
});
|
||||
responder.setDaemon(true);
|
||||
responder.start();
|
||||
CompletableFuture<Void> responder = startPongResponder(serverSocket, 1);
|
||||
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo(
|
||||
when(lifecycleManager.createAndStartEphemeral(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo(
|
||||
"container-id", Map.of(6379, new ContainerLifecycleManager.EndpointInfo(
|
||||
"127.0.0.1", serverSocket.getLocalPort()))));
|
||||
|
||||
@@ -164,9 +222,110 @@ class MemoryDbContainerManagerTest {
|
||||
"io.floci.resource-id", "cluster1",
|
||||
"io.floci.account", "000000000000",
|
||||
"io.floci.region", "us-east-1"));
|
||||
responder.get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void logicalDefaultNamesKeepLogsAndContainersWhileRuntimeKeysStayScoped() throws Exception {
|
||||
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
|
||||
ContainerBuilder containers = mock(ContainerBuilder.class);
|
||||
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);
|
||||
when(containers.newContainer(anyString())).thenReturn(builder);
|
||||
when(builder.build()).thenReturn(new ContainerSpec("valkey/valkey:8"));
|
||||
ContainerLogStreamer logs = mock(ContainerLogStreamer.class);
|
||||
when(logs.generateLogStreamName(anyString())).thenReturn("engine");
|
||||
MemoryDbContainerManager manager = newManager(containers, lifecycle, logs);
|
||||
String defaultIdentity = "000000000000-us-east-1-cache";
|
||||
String collisionIdentity = "000000000000-us-east-1-111111111111-eu-west-1-same";
|
||||
String foreignIdentity = "111111111111-eu-west-1-same";
|
||||
try (ServerSocket backend = new ServerSocket(0)) {
|
||||
CompletableFuture<Void> responder = startPongResponder(backend, 3);
|
||||
when(lifecycle.createAndStartEphemeral(any())).thenReturn(
|
||||
new ContainerLifecycleManager.ContainerInfo("default-cid", Map.of(6379,
|
||||
new ContainerLifecycleManager.EndpointInfo("127.0.0.1", backend.getLocalPort()))),
|
||||
new ContainerLifecycleManager.ContainerInfo("collision-cid", Map.of(6379,
|
||||
new ContainerLifecycleManager.EndpointInfo("127.0.0.1", backend.getLocalPort()))),
|
||||
new ContainerLifecycleManager.ContainerInfo("foreign-cid", Map.of(6379,
|
||||
new ContainerLifecycleManager.EndpointInfo("127.0.0.1", backend.getLocalPort()))));
|
||||
try {
|
||||
MemoryDbContainerHandle first = manager.tryStart(defaultIdentity, "valkey/valkey:8", null,
|
||||
"000000000000", "us-east-1", "cache");
|
||||
MemoryDbContainerHandle collision = manager.tryStart(collisionIdentity, "valkey/valkey:8", null,
|
||||
"000000000000", "us-east-1", "111111111111-eu-west-1-same");
|
||||
MemoryDbContainerHandle foreign = manager.tryStart(foreignIdentity, "valkey/valkey:8", null,
|
||||
"111111111111", "eu-west-1", "same");
|
||||
assertEquals(defaultIdentity, first.getClusterName());
|
||||
assertEquals(collisionIdentity, collision.getClusterName());
|
||||
assertEquals(foreignIdentity, foreign.getClusterName());
|
||||
ArgumentCaptor<String> names = ArgumentCaptor.forClass(String.class);
|
||||
verify(builder, times(3)).withName(names.capture());
|
||||
assertEquals(List.of("floci-aws-memorydb-cache",
|
||||
"floci-aws-memorydb-111111111111-eu-west-1-same",
|
||||
"floci-aws-memorydb-111111111111_eu-west-1_same"), names.getAllValues());
|
||||
verify(logs).attach("default-cid", "/aws/memorydb/cluster/cache/engine-log", "engine",
|
||||
"us-east-1", "memorydb:" + defaultIdentity);
|
||||
verify(logs).attach("collision-cid",
|
||||
"/aws/memorydb/cluster/111111111111-eu-west-1-same/engine-log", "engine",
|
||||
"us-east-1", "memorydb:" + collisionIdentity);
|
||||
verify(logs).attach("foreign-cid",
|
||||
"/aws/memorydb/cluster/111111111111-eu-west-1-same/engine-log", "engine",
|
||||
"eu-west-1", "memorydb:" + foreignIdentity);
|
||||
responder.get(5, TimeUnit.SECONDS);
|
||||
} finally {
|
||||
backend.close();
|
||||
manager.stopAll();
|
||||
}
|
||||
}
|
||||
verify(lifecycle).stopAndRemoveStrict("default-cid", null, 5, true);
|
||||
verify(lifecycle).stopAndRemoveStrict("collision-cid", null, 5, true);
|
||||
verify(lifecycle).stopAndRemoveStrict("foreign-cid", null, 5, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedCreationRollbackUsesTheSameDefaultAndForeignContainerNames() {
|
||||
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
|
||||
ContainerBuilder containers = mock(ContainerBuilder.class);
|
||||
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);
|
||||
when(containers.newContainer(anyString())).thenReturn(builder);
|
||||
when(builder.build()).thenReturn(new ContainerSpec("valkey/valkey:8"));
|
||||
RuntimeException failure = new IllegalStateException("creation failed before registration");
|
||||
when(lifecycle.createAndStartEphemeral(any())).thenThrow(failure);
|
||||
MemoryDbContainerManager manager = newManager(containers, lifecycle, mock(ContainerLogStreamer.class));
|
||||
assertSame(failure, assertThrows(IllegalStateException.class,
|
||||
() -> manager.start("000000000000-us-east-1-cache", "valkey/valkey:8", null,
|
||||
"000000000000", "us-east-1", "cache")));
|
||||
manager.stopByClusterName("000000000000-us-east-1-cache", "000000000000", "us-east-1", "cache");
|
||||
assertSame(failure, assertThrows(IllegalStateException.class,
|
||||
() -> manager.start("111111111111-eu-west-1-cache", "valkey/valkey:8", null,
|
||||
"111111111111", "eu-west-1", "cache")));
|
||||
manager.stopByClusterName("111111111111-eu-west-1-cache", "111111111111", "eu-west-1", "cache");
|
||||
verify(lifecycle, times(2)).removeIfExistsStrict("floci-aws-memorydb-cache", true);
|
||||
verify(lifecycle, times(2)).removeIfExistsStrict("floci-aws-memorydb-111111111111_eu-west-1_cache", true);
|
||||
}
|
||||
|
||||
private static CompletableFuture<Void> startPongResponder(ServerSocket backend, int connections) {
|
||||
CompletableFuture<Void> completed = new CompletableFuture<>();
|
||||
Thread responder = new Thread(() -> {
|
||||
try {
|
||||
for (int i = 0; i < connections; i++) {
|
||||
try (Socket socket = backend.accept()) {
|
||||
socket.setSoTimeout(5000);
|
||||
socket.getInputStream().read(new byte[64]);
|
||||
socket.getOutputStream().write("+PONG\r\n".getBytes(StandardCharsets.UTF_8));
|
||||
socket.getOutputStream().flush();
|
||||
}
|
||||
}
|
||||
completed.complete(null);
|
||||
} catch (IOException e) {
|
||||
completed.completeExceptionally(e);
|
||||
}
|
||||
});
|
||||
responder.setDaemon(true);
|
||||
responder.start();
|
||||
return completed;
|
||||
}
|
||||
|
||||
private MemoryDbContainerManager newManager(ContainerLifecycleManager lifecycleManager) {
|
||||
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
|
||||
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);
|
||||
@@ -176,6 +335,12 @@ class MemoryDbContainerManagerTest {
|
||||
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
|
||||
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
|
||||
|
||||
return newManager(containerBuilder, lifecycleManager, logStreamer);
|
||||
}
|
||||
|
||||
private MemoryDbContainerManager newManager(ContainerBuilder containerBuilder,
|
||||
ContainerLifecycleManager lifecycleManager,
|
||||
ContainerLogStreamer logStreamer) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.MemoryDbServiceConfig memorydb = mock(EmulatorConfig.MemoryDbServiceConfig.class);
|
||||
|
||||
Reference in new issue
Block a user