Light, fluffy, and always free - The AWS Local Emulator alternative
fix(memorydb,neptune,docdb): degrade gracefully with no Docker daemon (#2386)
lex0065b22ff01e3f
diff --git a/src/main/java/io/github/hectorvent/floci/services/docdb/DocDbService.java b/src/main/java/io/github/hectorvent/floci/services/docdb/DocDbService.javaindex cf2462af24..054102547b 100644--- a/src/main/java/io/github/hectorvent/floci/services/docdb/DocDbService.java+++ b/src/main/java/io/github/hectorvent/floci/services/docdb/DocDbService.java@@ -79,13 +79,25 @@ public class DocDbService {} else {String image = config.services().docdb().defaultImage();LOG.infov("Creating DocDB cluster {0}, image={1}", id, image);- DocDbContainerHandle handle = containerManager.start(id, image, masterUsername, masterPassword);- cluster.setEndpoint(handle.getHost());- cluster.setReaderEndpoint(handle.getHost());- cluster.setPort(handle.getPort());- cluster.setContainerId(handle.getContainerId());- cluster.setContainerHost(handle.getHost());- cluster.setContainerPort(handle.getPort());+ // A cluster record is metadata: its identifier, ARN and tags need no Docker, so the+ // cluster is created and reaches 'available' even when no daemon is reachable. Only+ // connecting to the database needs the container.+ DocDbContainerHandle handle = containerManager.tryStart(id, image, masterUsername, masterPassword);+ if (handle != null) {+ cluster.setEndpoint(handle.getHost());+ cluster.setReaderEndpoint(handle.getHost());+ cluster.setPort(handle.getPort());+ cluster.setContainerId(handle.getContainerId());+ cluster.setContainerHost(handle.getHost());+ cluster.setContainerPort(handle.getPort());+ } else {+ cluster.setEndpoint(resolveEndpointHost());+ cluster.setReaderEndpoint(resolveEndpointHost());+ cluster.setPort(MONGO_PORT);+ LOG.warnv("DocDB cluster {0} created without a backing MongoDB container: no "+ + "Docker daemon is reachable. Metadata operations work; connections to "+ + "the cluster do not until a daemon appears.", id);+ }}clusters.put(id, cluster);diff --git a/src/main/java/io/github/hectorvent/floci/services/docdb/container/DocDbContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/docdb/container/DocDbContainerManager.javaindex e7b264c9ee..aaa5fa0c99 100644--- a/src/main/java/io/github/hectorvent/floci/services/docdb/container/DocDbContainerManager.java+++ b/src/main/java/io/github/hectorvent/floci/services/docdb/container/DocDbContainerManager.java@@ -40,6 +40,7 @@ public class DocDbContainerManager {private final EmulatorConfig config;private final RegionResolver regionResolver;private final Map<String, DocDbContainerHandle> activeContainers = new ConcurrentHashMap<>();+ private volatile boolean dockerUnavailableLogged;@Injectpublic DocDbContainerManager(ContainerBuilder containerBuilder,@@ -56,6 +57,49 @@ public class DocDbContainerManager {this.regionResolver = regionResolver;}+ /**+ * Attempts {@link #start} and reports the backend as unavailable instead of propagating the+ * failure, when the cause is that no Docker daemon is reachable from Floci — Floci running+ * inside Docker without a mounted socket, or a stopped daemon on the host. A failure raised+ * while the daemon <em>is</em> reachable is a genuine container problem and still propagates,+ * so nothing changes for a Floci that can start DocumentDB containers.+ *+ * @return the container handle, or {@code null} when no Docker daemon is reachable+ */+ public DocDbContainerHandle tryStart(String clusterId, String image, String masterUsername, String masterPassword) {+ try {+ DocDbContainerHandle handle = start(clusterId, image, masterUsername, masterPassword);+ dockerUnavailableLogged = false;+ return handle;+ } catch (RuntimeException e) {+ if (isDockerReachable()) {+ throw e;+ }+ if (!dockerUnavailableLogged) {+ dockerUnavailableLogged = true;+ LOG.warnv("No Docker daemon is reachable from Floci ({0}). DocumentDB metadata "+ + "operations keep working and clusters still reach 'available', but they "+ + "have no backing MongoDB container until a daemon becomes reachable.",+ e.getMessage());+ }+ return null;+ }+ }++ /**+ * Probes the configured Docker endpoint, which is how a missing daemon is told apart from a+ * container that failed for its own reasons.+ */+ public boolean isDockerReachable() {+ try {+ lifecycleManager.getDockerClient().pingCmd().exec();+ return true;+ } catch (Exception e) {+ LOG.debugv("Docker daemon is not reachable: {0}", e.getMessage());+ return false;+ }+ }+public DocDbContainerHandle start(String clusterId, String image, String masterUsername, String masterPassword) {LOG.infov("Starting DocumentDB container for cluster: {0}", clusterId);diff --git a/src/main/java/io/github/hectorvent/floci/services/memorydb/MemoryDbService.java b/src/main/java/io/github/hectorvent/floci/services/memorydb/MemoryDbService.javaindex 08e782c776..e659d6d601 100644--- a/src/main/java/io/github/hectorvent/floci/services/memorydb/MemoryDbService.java+++ b/src/main/java/io/github/hectorvent/floci/services/memorydb/MemoryDbService.java@@ -488,16 +488,27 @@ public class MemoryDbService {MemoryDbContainerHandle handle = null;try {- handle = containerManager.start(name, image);+ // A cluster record is metadata: its name, endpoint host and proxy port are derived+ // from configuration and need no Docker, so the cluster is created and reaches+ // 'available' even when no daemon is reachable. Only connecting to the cache needs+ // the container.+ handle = containerManager.tryStart(name, image);cluster.setClusterEndpoint(new Endpoint(resolveEndpointHost(), proxyPort));cluster.setProxyPort(proxyPort);- cluster.setContainerId(handle.getContainerId());- cluster.setContainerHost(handle.getHost());- cluster.setContainerPort(handle.getPort());- proxyManager.startProxy(name, authRequired, proxyPort,- handle.getHost(), handle.getPort(),- (username, secret) -> authenticate(name, username, secret));+ if (handle != null) {+ cluster.setContainerId(handle.getContainerId());+ cluster.setContainerHost(handle.getHost());+ cluster.setContainerPort(handle.getPort());++ proxyManager.startProxy(name, authRequired, proxyPort,+ handle.getHost(), handle.getPort(),+ (username, secret) -> authenticate(name, username, secret));+ } else {+ LOG.warnv("MemoryDB cluster {0} created without a backing container: no Docker "+ + "daemon is reachable. Metadata operations work; connections to the "+ + "cluster do not until a daemon appears.", name);+ }} catch (RuntimeException e) {LOG.warnv("MemoryDB cluster {0} provisioning failed, rolling back: {1}", name, e.getMessage());rollbackBackend(name, handle, proxyPort);diff --git a/src/main/java/io/github/hectorvent/floci/services/memorydb/container/MemoryDbContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/memorydb/container/MemoryDbContainerManager.javaindex 60d207b26e..1a441b5bdb 100644--- a/src/main/java/io/github/hectorvent/floci/services/memorydb/container/MemoryDbContainerManager.java+++ b/src/main/java/io/github/hectorvent/floci/services/memorydb/container/MemoryDbContainerManager.java@@ -49,6 +49,7 @@ public class MemoryDbContainerManager {private final EmulatorConfig config;private final RegionResolver regionResolver;private final Map<String, MemoryDbContainerHandle> activeContainers = new ConcurrentHashMap<>();+ private volatile boolean dockerUnavailableLogged;@Injectpublic MemoryDbContainerManager(ContainerBuilder containerBuilder,@@ -65,6 +66,49 @@ public class MemoryDbContainerManager {this.regionResolver = regionResolver;}+ /**+ * Attempts {@link #start} and reports the backend as unavailable instead of propagating the+ * failure, when the cause is that no Docker daemon is reachable from Floci — Floci running+ * inside Docker without a mounted socket, or a stopped daemon on the host. A failure raised+ * while the daemon <em>is</em> reachable is a genuine container problem and still propagates,+ * so nothing changes for a Floci that can start MemoryDB containers.+ *+ * @return the container handle, or {@code null} when no Docker daemon is reachable+ */+ public MemoryDbContainerHandle tryStart(String clusterName, String image) {+ try {+ MemoryDbContainerHandle handle = start(clusterName, image);+ dockerUnavailableLogged = false;+ return handle;+ } catch (RuntimeException e) {+ if (isDockerReachable()) {+ throw e;+ }+ if (!dockerUnavailableLogged) {+ dockerUnavailableLogged = true;+ LOG.warnv("No Docker daemon is reachable from Floci ({0}). MemoryDB metadata "+ + "operations keep working and clusters still reach 'available', but they "+ + "have no backing Redis/Valkey container until a daemon becomes reachable.",+ e.getMessage());+ }+ return null;+ }+ }++ /**+ * Probes the configured Docker endpoint, which is how a missing daemon is told apart from a+ * container that failed for its own reasons.+ */+ public boolean isDockerReachable() {+ try {+ lifecycleManager.getDockerClient().pingCmd().exec();+ return true;+ } catch (Exception e) {+ LOG.debugv("Docker daemon is not reachable: {0}", e.getMessage());+ return false;+ }+ }+public MemoryDbContainerHandle start(String clusterName, String image) {LOG.infov("Starting MemoryDB backend container for cluster: {0}", clusterName);diff --git a/src/main/java/io/github/hectorvent/floci/services/neptune/NeptuneService.java b/src/main/java/io/github/hectorvent/floci/services/neptune/NeptuneService.javaindex a3bdf7088a..85406e6e0e 100644--- a/src/main/java/io/github/hectorvent/floci/services/neptune/NeptuneService.java+++ b/src/main/java/io/github/hectorvent/floci/services/neptune/NeptuneService.java@@ -81,7 +81,11 @@ public class NeptuneService {LOG.infov("Creating Neptune cluster {0} on proxy port {1}, dbType={2}, image={3}",id, String.valueOf(proxyPort), dbType, image);- handle = containerManager.start(id, image, dbType);+ // A cluster record is metadata: its identifier, ARN, endpoint host and proxy port+ // are derived from configuration and need no Docker, so the cluster is created and+ // reaches 'available' even when no daemon is reachable. Only connecting to the+ // graph database needs the container.+ handle = containerManager.tryStart(id, image, dbType);String region = regionResolver.getDefaultRegion();String endpointHost = resolveEndpointHost();@@ -99,12 +103,19 @@ public class NeptuneService {.replace("-", "").substring(0, 24).toUpperCase());cluster.setCreatedAt(Instant.now());cluster.setDbClusterMembers(new ArrayList<>());- cluster.setContainerId(handle.getContainerId());- cluster.setContainerHost(handle.getHost());- cluster.setContainerPort(handle.getPort());cluster.setProxyPort(proxyPort);- proxyManager.startProxy(id, proxyPort, handle.getHost(), handle.getPort());+ if (handle != null) {+ cluster.setContainerId(handle.getContainerId());+ cluster.setContainerHost(handle.getHost());+ cluster.setContainerPort(handle.getPort());++ proxyManager.startProxy(id, proxyPort, handle.getHost(), handle.getPort());+ } else {+ LOG.warnv("Neptune cluster {0} created without a backing graph database container: "+ + "no Docker daemon is reachable. Metadata operations work; connections to "+ + "the cluster do not until a daemon appears.", id);+ }clusters.put(id, cluster);provisioned = true;diff --git a/src/main/java/io/github/hectorvent/floci/services/neptune/container/NeptuneContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/neptune/container/NeptuneContainerManager.javaindex 01ef2f9cc0..365e7b941e 100644--- a/src/main/java/io/github/hectorvent/floci/services/neptune/container/NeptuneContainerManager.java+++ b/src/main/java/io/github/hectorvent/floci/services/neptune/container/NeptuneContainerManager.java@@ -46,6 +46,7 @@ public class NeptuneContainerManager {private final EmulatorConfig config;private final RegionResolver regionResolver;private final Map<String, NeptuneContainerHandle> activeContainers = new ConcurrentHashMap<>();+ private volatile boolean dockerUnavailableLogged;@Injectpublic NeptuneContainerManager(ContainerBuilder containerBuilder,@@ -62,6 +63,49 @@ public class NeptuneContainerManager {this.regionResolver = regionResolver;}+ /**+ * Attempts {@link #start} and reports the backend as unavailable instead of propagating the+ * failure, when the cause is that no Docker daemon is reachable from Floci — Floci running+ * inside Docker without a mounted socket, or a stopped daemon on the host. A failure raised+ * while the daemon <em>is</em> reachable is a genuine container problem and still propagates,+ * so nothing changes for a Floci that can start Neptune containers.+ *+ * @return the container handle, or {@code null} when no Docker daemon is reachable+ */+ public NeptuneContainerHandle tryStart(String clusterId, String image, NeptuneDbType dbType) {+ try {+ NeptuneContainerHandle handle = start(clusterId, image, dbType);+ dockerUnavailableLogged = false;+ return handle;+ } catch (RuntimeException e) {+ if (isDockerReachable()) {+ throw e;+ }+ if (!dockerUnavailableLogged) {+ dockerUnavailableLogged = true;+ LOG.warnv("No Docker daemon is reachable from Floci ({0}). Neptune metadata "+ + "operations keep working and clusters still reach 'available', but they "+ + "have no backing graph database container until a daemon becomes "+ + "reachable.", e.getMessage());+ }+ return null;+ }+ }++ /**+ * Probes the configured Docker endpoint, which is how a missing daemon is told apart from a+ * container that failed for its own reasons.+ */+ public boolean isDockerReachable() {+ try {+ lifecycleManager.getDockerClient().pingCmd().exec();+ return true;+ } catch (Exception e) {+ LOG.debugv("Docker daemon is not reachable: {0}", e.getMessage());+ return false;+ }+ }+public NeptuneContainerHandle start(String clusterId, String image, NeptuneDbType dbType) {LOG.infov("Starting Neptune backend container ({0}) for cluster: {1}", dbType, clusterId);diff --git a/src/test/java/io/github/hectorvent/floci/services/docdb/DocDbServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/docdb/DocDbServiceTest.javaindex 21f7197078..1651c7b39e 100644--- a/src/test/java/io/github/hectorvent/floci/services/docdb/DocDbServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/docdb/DocDbServiceTest.java@@ -118,4 +118,42 @@ class DocDbServiceTest {assertTrue(docDbService.listDbClusters(null).isEmpty());verify(containerManager, never()).stop(any());}++ @Test+ void createWithoutDockerDaemonStillReachesAvailable() {+ // tryStart() returns null when no Docker daemon is reachable. The cluster record is+ // metadata, so the create still succeeds and the cluster reaches 'available' on the+ // first describe (what SDK/Terraform waiters poll).+ StorageFactory storageFactory = Mockito.mock(StorageFactory.class);+ when(storageFactory.create(anyString(), anyString(), any()))+ .thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000"));+ EmulatorConfig config = Mockito.mock(EmulatorConfig.class);+ var servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);+ var docdbConfig = Mockito.mock(EmulatorConfig.DocDbServiceConfig.class);+ when(config.services()).thenReturn(servicesConfig);+ when(servicesConfig.docdb()).thenReturn(docdbConfig);+ when(docdbConfig.mock()).thenReturn(false);+ when(docdbConfig.defaultImage()).thenReturn("mongo:7.0");+ when(config.hostname()).thenReturn(java.util.Optional.of("localhost"));++ DocDbContainerManager noDaemonContainerManager = Mockito.mock(DocDbContainerManager.class);+ when(noDaemonContainerManager.tryStart(anyString(), anyString(), anyString(), anyString()))+ .thenReturn(null);+ RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");+ DocDbService noDaemonService = new DocDbService(config, regionResolver, noDaemonContainerManager, storageFactory);++ DocDbCluster created = noDaemonService.createDbCluster(+ "no-docker-cluster", null, "admin", "secret", false);++ assertEquals("available", created.getStatus());+ assertEquals("localhost", created.getEndpoint());+ assertEquals(27017, created.getPort());++ assertEquals("no-docker-cluster",+ noDaemonService.getDbCluster("no-docker-cluster").getDbClusterIdentifier());++ // Delete must not reach for a container that was never created.+ noDaemonService.deleteDbCluster("no-docker-cluster");+ verify(noDaemonContainerManager, never()).stop(any());+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/docdb/container/DocDbContainerManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/docdb/container/DocDbContainerManagerTest.javanew file mode 100644index 0000000000..3a4a57681b--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/docdb/container/DocDbContainerManagerTest.java@@ -0,0 +1,121 @@+package io.github.hectorvent.floci.services.docdb.container;++import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;+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 com.github.dockerjava.api.DockerClient;+import org.jboss.logging.Logger;+import org.junit.jupiter.api.Test;+import org.mockito.Mockito;++import java.io.IOException;+import java.net.ServerSocket;+import java.net.Socket;+import java.util.Map;+import java.util.Optional;++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.assertThrows;+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.when;++class DocDbContainerManagerTest {++ private static final Logger LOG = Logger.getLogger(DocDbContainerManagerTest.class);++ @Test+ void tryStartReportsUnavailableInsteadOfThrowingWhenNoDockerDaemonIsReachable() {+ // Floci running inside Docker without a mounted daemon socket: the DocumentDB control+ // plane must keep working, so the failure is reported rather than propagated.+ ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);+ when(lifecycleManager.createAndStart(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"));++ DocDbContainerManager manager = newManager(lifecycleManager);++ for (int attempt = 0; attempt < 3; attempt++) {+ assertNull(manager.tryStart("cluster1", "mongo:7.0", "admin", "secret"),+ "attempt " + attempt + " should report unavailable");+ }+ assertFalse(manager.isDockerReachable());+ }++ @Test+ void tryStartPropagatesFailuresRaisedWhileTheDaemonIsReachable() {+ // A reachable daemon that cannot start the container is a genuine failure, not a+ // degraded mode: CreateDBCluster must still surface it.+ ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);+ when(lifecycleManager.createAndStart(any()))+ .thenThrow(new RuntimeException("no such image: mongo:7.0"));+ DockerClient dockerClient = mock(DockerClient.class, Mockito.RETURNS_DEEP_STUBS);+ when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);++ DocDbContainerManager manager = newManager(lifecycleManager);++ RuntimeException failure = assertThrows(RuntimeException.class,+ () -> manager.tryStart("cluster1", "mongo:7.0", "admin", "secret"));+ assertEquals("no such image: mongo:7.0", failure.getMessage());+ }++ @Test+ void tryStartReturnsTheHandleOnceADaemonIsReachable() throws IOException, InterruptedException {+ // Real loopback socket standing in for the Mongo backend's port: the manager's+ // readiness probe only needs a successful TCP connect.+ try (ServerSocket serverSocket = new ServerSocket(0)) {+ Thread acceptor = new Thread(() -> {+ try (Socket socket = serverSocket.accept()) {+ socket.getInputStream().read(new byte[1]);+ } catch (IOException e) {+ // Test teardown races the socket close; nothing left to assert on.+ LOG.debugv(e, "Acceptor socket closed during test teardown");+ }+ });+ acceptor.setDaemon(true);+ acceptor.start();++ ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);+ when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo(+ "container-id", Map.of(27017, new ContainerLifecycleManager.EndpointInfo(+ "127.0.0.1", serverSocket.getLocalPort()))));++ DocDbContainerManager manager = newManager(lifecycleManager);++ DocDbContainerHandle handle = manager.tryStart("cluster1", "mongo:7.0", "admin", "secret");++ assertEquals("container-id", handle.getContainerId());+ assertEquals(serverSocket.getLocalPort(), handle.getPort());+ acceptor.join(5000);+ }+ }++ private DocDbContainerManager newManager(ContainerLifecycleManager lifecycleManager) {+ ContainerBuilder containerBuilder = mock(ContainerBuilder.class);+ ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);+ when(containerBuilder.newContainer(anyString())).thenReturn(builder);+ when(builder.build()).thenReturn(mock(ContainerSpec.class));++ ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);+ lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");++ EmulatorConfig config = mock(EmulatorConfig.class);+ EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);+ EmulatorConfig.DocDbServiceConfig docdb = mock(EmulatorConfig.DocDbServiceConfig.class);+ when(config.services()).thenReturn(services);+ when(services.docdb()).thenReturn(docdb);+ when(docdb.dockerNetwork()).thenReturn(Optional.empty());++ return new DocDbContainerManager(containerBuilder, lifecycleManager, logStreamer,+ mock(ContainerDetector.class), config, new RegionResolver("us-east-1", "000000000000"));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbServiceTest.javaindex f28a67aef5..e5b8d4b677 100644--- a/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbServiceTest.java@@ -72,7 +72,7 @@ class MemoryDbServiceTest {"000000000000", inv.getArgument(2)).toString());when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000"));- when(containerManager.start(anyString(), anyString()))+ when(containerManager.tryStart(anyString(), anyString())).thenReturn(new MemoryDbContainerHandle("cid", "cluster", "localhost", 6379));doNothing().when(proxyManager).startProxy(anyString(), anyBoolean(), anyInt(), anyString(), anyInt(), any());@@ -332,7 +332,7 @@ class MemoryDbServiceTest {void failedProvisioningReleasesProxyPort() {when(mdbConfig.proxyBasePort()).thenReturn(16400);when(mdbConfig.proxyMaxPort()).thenReturn(16400); // exactly one port available- when(containerManager.start(anyString(), anyString()))+ when(containerManager.tryStart(anyString(), anyString())).thenThrow(new RuntimeException("docker unavailable")).thenReturn(new MemoryDbContainerHandle("cid", "c2", "localhost", 6379));@@ -352,7 +352,7 @@ class MemoryDbServiceTest {@Testvoid failedProvisioningRollsBackContainerAndReleasesProxyPort() {MemoryDbContainerHandle handle = new MemoryDbContainerHandle("cid", "c1", "localhost", 6379);- when(containerManager.start(anyString(), anyString())).thenReturn(handle);+ when(containerManager.tryStart(anyString(), anyString())).thenReturn(handle);// Proxy startup blows up after the port is reserved and the container is started.doThrow(new RuntimeException("proxy boom"))@@ -387,11 +387,11 @@ class MemoryDbServiceTest {@Testvoid failedContainerStartupCleansUpContainerByNameAndReleasesPort() {- // containerManager.start(...) throws — this models both a container that never started+ // containerManager.tryStart(...) throws — this models both a container that never started// 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).start(eq("c1"), anyString());+ .when(containerManager).tryStart(eq("c1"), anyString());Cluster spec = new Cluster();spec.setName("c1");@@ -407,7 +407,7 @@ class MemoryDbServiceTest {verify(containerManager).stopByClusterName("c1");// The reserved proxy port was still released: a subsequent successful create reuses the base port.- when(containerManager.start(anyString(), anyString()))+ when(containerManager.tryStart(anyString(), anyString())).thenReturn(new MemoryDbContainerHandle("cid", "c2", "localhost", 6379));Cluster second = new Cluster();second.setName("c2");@@ -436,7 +436,7 @@ class MemoryDbServiceTest {void concurrentCreateForSameNameIsRejectedWhileFirstIsProvisioning() throws InterruptedException {CountDownLatch startedLatch = new CountDownLatch(1);CountDownLatch releaseLatch = new CountDownLatch(1);- when(containerManager.start(anyString(), anyString())).thenAnswer(inv -> {+ when(containerManager.tryStart(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);@@ -463,4 +463,28 @@ class MemoryDbServiceTest {assertEquals(ClusterStatus.AVAILABLE, service.getCluster("c1").getStatus());}++ @Test+ void createWithoutDockerDaemonStillReachesAvailable() {+ // 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);++ Cluster spec = new Cluster();+ spec.setName("no-docker-cluster");+ spec.setAclName("open-access");+ Cluster created = service.createCluster(spec, "us-east-1");++ assertEquals(ClusterStatus.AVAILABLE, created.getStatus());+ assertEquals("localhost", created.getClusterEndpoint().address());+ assertEquals(16400, created.getProxyPort());+ verify(proxyManager, never()).startProxy(anyString(), anyBoolean(), anyInt(), anyString(), anyInt(), any());++ assertEquals("no-docker-cluster", service.getCluster("no-docker-cluster").getName());++ // Delete must not reach for a container that was never created.+ service.deleteCluster("no-docker-cluster");+ verify(containerManager, never()).stop(any());+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/memorydb/container/MemoryDbContainerManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/memorydb/container/MemoryDbContainerManagerTest.javaindex bed9d4ab6b..c17f330884 100644--- a/src/test/java/io/github/hectorvent/floci/services/memorydb/container/MemoryDbContainerManagerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/memorydb/container/MemoryDbContainerManagerTest.java@@ -6,13 +6,34 @@ import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;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 com.github.dockerjava.api.DockerClient;+import org.jboss.logging.Logger;import org.junit.jupiter.api.Test;+import org.mockito.Mockito;+import java.io.IOException;+import java.io.OutputStream;+import java.net.ServerSocket;+import java.net.Socket;+import java.util.Map;+import java.util.Optional;++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.assertThrows;+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.verify;+import static org.mockito.Mockito.when;class MemoryDbContainerManagerTest {+ private static final Logger LOG = Logger.getLogger(MemoryDbContainerManagerTest.class);+@Testvoid stopByClusterNameRemovesByDeterministicNameWhenNothingRegistered() {ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);@@ -26,4 +47,94 @@ class MemoryDbContainerManagerTest {verify(lifecycleManager).removeIfExists("floci-memorydb-my-cluster");}++ @Test+ void tryStartReportsUnavailableInsteadOfThrowingWhenNoDockerDaemonIsReachable() {+ // 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()))+ .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"));++ MemoryDbContainerManager manager = newManager(lifecycleManager);++ for (int attempt = 0; attempt < 3; attempt++) {+ assertNull(manager.tryStart("cluster1", "valkey/valkey:8"),+ "attempt " + attempt + " should report unavailable");+ }+ assertFalse(manager.isDockerReachable());+ }++ @Test+ void tryStartPropagatesFailuresRaisedWhileTheDaemonIsReachable() {+ // 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()))+ .thenThrow(new RuntimeException("no such image: valkey/valkey:8"));+ DockerClient dockerClient = mock(DockerClient.class, Mockito.RETURNS_DEEP_STUBS);+ when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);++ MemoryDbContainerManager manager = newManager(lifecycleManager);++ RuntimeException failure = assertThrows(RuntimeException.class,+ () -> manager.tryStart("cluster1", "valkey/valkey:8"));+ assertEquals("no such image: valkey/valkey:8", failure.getMessage());+ }++ @Test+ void tryStartReturnsTheHandleOnceADaemonIsReachable() throws IOException, InterruptedException {+ // 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(java.nio.charset.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();++ ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);+ when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo(+ "container-id", Map.of(6379, new ContainerLifecycleManager.EndpointInfo(+ "127.0.0.1", serverSocket.getLocalPort()))));++ MemoryDbContainerManager manager = newManager(lifecycleManager);++ MemoryDbContainerHandle handle = manager.tryStart("cluster1", "valkey/valkey:8");++ assertEquals("container-id", handle.getContainerId());+ assertEquals(serverSocket.getLocalPort(), handle.getPort());+ responder.join(5000);+ }+ }++ private MemoryDbContainerManager newManager(ContainerLifecycleManager lifecycleManager) {+ ContainerBuilder containerBuilder = mock(ContainerBuilder.class);+ ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);+ when(containerBuilder.newContainer(anyString())).thenReturn(builder);+ when(builder.build()).thenReturn(mock(ContainerSpec.class));++ ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);+ lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");++ EmulatorConfig config = mock(EmulatorConfig.class);+ EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);+ EmulatorConfig.MemoryDbServiceConfig memorydb = mock(EmulatorConfig.MemoryDbServiceConfig.class);+ when(config.services()).thenReturn(services);+ when(services.memorydb()).thenReturn(memorydb);+ when(memorydb.dockerNetwork()).thenReturn(Optional.empty());++ return new MemoryDbContainerManager(containerBuilder, lifecycleManager, logStreamer,+ mock(ContainerDetector.class), config, new RegionResolver("us-east-1", "000000000000"));+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/neptune/NeptuneServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/neptune/NeptuneServiceTest.javaindex d0214324d3..8cabad6ac8 100644--- a/src/test/java/io/github/hectorvent/floci/services/neptune/NeptuneServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/neptune/NeptuneServiceTest.java@@ -58,7 +58,7 @@ class NeptuneServiceTest {when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000"));- when(containerManager.start(anyString(), anyString(), any(NeptuneDbType.class)))+ when(containerManager.tryStart(anyString(), anyString(), any(NeptuneDbType.class))).thenReturn(new NeptuneContainerHandle("cid", "c", "localhost", 8182));doNothing().when(proxyManager).startProxy(anyString(), anyInt(), anyString(), anyInt());@@ -68,7 +68,7 @@ class NeptuneServiceTest {@Testvoid failedProvisioningRollsBackContainerAndReleasesProxyPort() {NeptuneContainerHandle handle = new NeptuneContainerHandle("cid", "c", "localhost", 8182);- when(containerManager.start(anyString(), anyString(), any(NeptuneDbType.class)))+ when(containerManager.tryStart(anyString(), anyString(), any(NeptuneDbType.class))).thenReturn(handle);// Proxy startup blows up after the port is reserved and the container is started.@@ -94,7 +94,7 @@ class NeptuneServiceTest {@Testvoid jvmErrorDuringProvisioningStillRollsBack() {NeptuneContainerHandle handle = new NeptuneContainerHandle("cid", "c", "localhost", 8182);- when(containerManager.start(anyString(), anyString(), any(NeptuneDbType.class)))+ when(containerManager.tryStart(anyString(), anyString(), any(NeptuneDbType.class))).thenReturn(handle);// A JVM Error (not a RuntimeException) escapes provisioning — a catch (RuntimeException)@@ -117,11 +117,11 @@ class NeptuneServiceTest {@Testvoid failedContainerStartupCleansUpContainerByIdAndReleasesPort() {- // containerManager.start(...) throws — this models both a container that never started+ // containerManager.tryStart(...) throws — this models both a container that never started// 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).start(eq("c"), anyString(), any(NeptuneDbType.class));+ .when(containerManager).tryStart(eq("c"), anyString(), any(NeptuneDbType.class));// The original failure must propagate to the caller (we clean up, then rethrow).assertThrows(RuntimeException.class,@@ -134,7 +134,7 @@ class NeptuneServiceTest {verify(containerManager).stopByClusterId("c");// The reserved proxy port was still released: a subsequent successful create reuses the base port.- when(containerManager.start(anyString(), anyString(), any(NeptuneDbType.class)))+ when(containerManager.tryStart(anyString(), anyString(), any(NeptuneDbType.class))).thenReturn(new NeptuneContainerHandle("cid", "c2", "localhost", 8182));NeptuneCluster recovered = service.createDbCluster("c2", "1.3.2.1", false);assertEquals(18182, recovered.getProxyPort(),@@ -180,4 +180,25 @@ class NeptuneServiceTest {assertEquals("InsufficientStorageClusterCapacity", e.getErrorCode());assertEquals(400, e.getHttpStatus());}++ @Test+ void createWithoutDockerDaemonStillReachesAvailable() {+ // 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 proxy is started.+ when(containerManager.tryStart(anyString(), anyString(), any(NeptuneDbType.class))).thenReturn(null);++ NeptuneCluster created = service.createDbCluster("no-docker-cluster", "1.3.2.1", false);++ assertEquals("available", created.getStatus());+ assertEquals("localhost", created.getEndpoint());+ assertEquals(18182, created.getProxyPort());+ verify(proxyManager, never()).startProxy(anyString(), anyInt(), anyString(), anyInt());++ assertEquals("no-docker-cluster", service.getDbCluster("no-docker-cluster").getDbClusterIdentifier());++ // Delete must not reach for a container that was never created.+ service.deleteDbCluster("no-docker-cluster");+ verify(containerManager, never()).stop(any());+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/neptune/container/NeptuneContainerManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/neptune/container/NeptuneContainerManagerTest.javaindex a14eb186cf..eef1dd44a8 100644--- a/src/test/java/io/github/hectorvent/floci/services/neptune/container/NeptuneContainerManagerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/neptune/container/NeptuneContainerManagerTest.java@@ -6,13 +6,35 @@ import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;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 io.github.hectorvent.floci.services.neptune.model.NeptuneDbType;+import com.github.dockerjava.api.DockerClient;+import org.jboss.logging.Logger;import org.junit.jupiter.api.Test;+import org.mockito.Mockito;+import java.io.IOException;+import java.io.OutputStream;+import java.net.ServerSocket;+import java.net.Socket;+import java.util.Map;+import java.util.Optional;++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.assertThrows;+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.verify;+import static org.mockito.Mockito.when;class NeptuneContainerManagerTest {+ private static final Logger LOG = Logger.getLogger(NeptuneContainerManagerTest.class);+@Testvoid stopByClusterIdRemovesByDeterministicNameWhenNothingRegistered() {ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);@@ -26,4 +48,95 @@ class NeptuneContainerManagerTest {verify(lifecycleManager).removeIfExists("floci-neptune-my-cluster");}++ @Test+ void tryStartReportsUnavailableInsteadOfThrowingWhenNoDockerDaemonIsReachable() {+ // Floci running inside Docker without a mounted daemon socket: the Neptune control+ // plane must keep working, so the failure is reported rather than propagated.+ ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);+ when(lifecycleManager.createAndStart(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"));++ NeptuneContainerManager manager = newManager(lifecycleManager);++ for (int attempt = 0; attempt < 3; attempt++) {+ assertNull(manager.tryStart("cluster1", "tinkerpop/gremlin-server:3.7.3", NeptuneDbType.GREMLIN),+ "attempt " + attempt + " should report unavailable");+ }+ assertFalse(manager.isDockerReachable());+ }++ @Test+ void tryStartPropagatesFailuresRaisedWhileTheDaemonIsReachable() {+ // A reachable daemon that cannot start the container is a genuine failure, not a+ // degraded mode: CreateDBCluster must still surface it.+ ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);+ when(lifecycleManager.createAndStart(any()))+ .thenThrow(new RuntimeException("no such image: tinkerpop/gremlin-server:3.7.3"));+ DockerClient dockerClient = mock(DockerClient.class, Mockito.RETURNS_DEEP_STUBS);+ when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);++ NeptuneContainerManager manager = newManager(lifecycleManager);++ RuntimeException failure = assertThrows(RuntimeException.class,+ () -> manager.tryStart("cluster1", "tinkerpop/gremlin-server:3.7.3", NeptuneDbType.GREMLIN));+ assertEquals("no such image: tinkerpop/gremlin-server:3.7.3", failure.getMessage());+ }++ @Test+ void tryStartReturnsTheHandleOnceADaemonIsReachable() throws IOException, InterruptedException {+ // Real loopback socket standing in for the Gremlin backend's port: any reply to the+ // manager's readiness probe confirms it is listening.+ 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("HTTP/1.1 400 Bad Request\r\n\r\n".getBytes(java.nio.charset.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();++ ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);+ when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo(+ "container-id", Map.of(8182, new ContainerLifecycleManager.EndpointInfo(+ "127.0.0.1", serverSocket.getLocalPort()))));++ NeptuneContainerManager manager = newManager(lifecycleManager);++ NeptuneContainerHandle handle =+ manager.tryStart("cluster1", "tinkerpop/gremlin-server:3.7.3", NeptuneDbType.GREMLIN);++ assertEquals("container-id", handle.getContainerId());+ assertEquals(serverSocket.getLocalPort(), handle.getPort());+ responder.join(5000);+ }+ }++ private NeptuneContainerManager newManager(ContainerLifecycleManager lifecycleManager) {+ ContainerBuilder containerBuilder = mock(ContainerBuilder.class);+ ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);+ when(containerBuilder.newContainer(anyString())).thenReturn(builder);+ when(builder.build()).thenReturn(mock(ContainerSpec.class));++ ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);+ lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");++ EmulatorConfig config = mock(EmulatorConfig.class);+ EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);+ EmulatorConfig.NeptuneServiceConfig neptune = mock(EmulatorConfig.NeptuneServiceConfig.class);+ when(config.services()).thenReturn(services);+ when(services.neptune()).thenReturn(neptune);+ when(neptune.dockerNetwork()).thenReturn(Optional.empty());++ return new NeptuneContainerManager(containerBuilder, lifecycleManager, logStreamer,+ mock(ContainerDetector.class), config, new RegionResolver("us-east-1", "000000000000"));+ }}