diff --git a/.github/ci/prefetch-images.sh b/.github/ci/prefetch-images.sh index 5779e53444..dffc1c658d 100755 --- a/.github/ci/prefetch-images.sh +++ b/.github/ci/prefetch-images.sh @@ -200,6 +200,11 @@ if grep -q '/neptune/' "$SHARD_FILE"; then configured_image neptune default-neo4j-image configured_image neptune default-image fi +# NeptuneGraphVolumeDockerNightlyIntegrationTest keeps a graph across containers on both engines' configured images. +if starts NeptuneGraphVolumeDockerNightlyIntegrationTest; then + configured_image neptune default-image + configured_image neptune default-neo4j-image +fi # DocDbClusterRestartDockerNightlyIntegrationTest restarts clusters on the configured MongoDB image. starts DocDbClusterRestartDockerNightlyIntegrationTest && configured_image docdb default-image grep -q '/elasticache/' "$SHARD_FILE" && { pull valkey/valkey:8; pull memcached:1.6; } diff --git a/docs/services/neptune.md b/docs/services/neptune.md index bb5b3526c9..a5f9e3bd6f 100644 --- a/docs/services/neptune.md +++ b/docs/services/neptune.md @@ -78,6 +78,33 @@ A requested `Port` is honoured when it is free and inside the proxy port range ( | `FLOCI_SERVICES_NEPTUNE_DEFAULT_NEO4J_IMAGE` | `neo4j:5-community` | Image used when `db-type=neo4j` | | `FLOCI_SERVICES_NEPTUNE_DOCKER_NETWORK` | _(host default)_ | Docker network for container connectivity | +### Graph data + +When Neptune's records are kept, with `FLOCI_STORAGE_MODE` (or `FLOCI_STORAGE_SERVICES_NEPTUNE_MODE`) +set to `persistent`, `hybrid` or `wal`, each cluster keeps its graph in a Docker volume of its own, +`floci-aws-neptune-` (`floci-aws--neptune-` when +`FLOCI_DOCKER_RESOURCE_NAMESPACE` is set), so the graph outlives the cluster's container. When +`FLOCI_STORAGE_HOST_PERSISTENT_PATH` is an absolute path, the graph goes in +`/[/]neptune/` on the Docker host instead. + +- **`neo4j`:** the volume is Neo4j's data directory, `/data`. +- **`gremlin`:** the volume is the image's `/opt/gremlin-server/data`, and the server's TinkerGraph + saves the graph there, to `floci-graph.kryo`, when the server stops, and loads it from there when + it starts. The graph is written only when the server stops, which Floci gives a container 30 + seconds to do before Docker kills it, so a container that is killed rather than stopped loses + what changed since it started. Under the host path the server runs as + root, since the directory there belongs to whoever created it rather than to the image's + `gremlin` user. Floci writes the graph settings into the image's + `/opt/gremlin-server/conf/tinkergraph-empty.properties`, so an image configured in place of the + default needs the same layout; one laid out otherwise keeps its graph in memory, and Floci logs a + warning. + +Deleting the cluster keeps its volume, for you to remove with `docker volume rm`, unless +`FLOCI_STORAGE_PRUNE_VOLUMES_ON_DELETE=true`; a directory under the host path is always kept. A +create that fails leaves no volume behind. A cluster created again under a deleted one's identifier +starts on a new, empty volume. In `memory` mode a cluster's graph lasts only as long as its +container. + ### Docker Compose Neptune requires the Docker socket and the Gremlin proxy port range to be exposed. The first cluster claims `PROXY_BASE_PORT`; each additional cluster increments the port. diff --git a/src/main/java/io/floci/aws/core/common/docker/ContainerStorageHelper.java b/src/main/java/io/floci/aws/core/common/docker/ContainerStorageHelper.java index 826292b51b..9beee1f18a 100644 --- a/src/main/java/io/floci/aws/core/common/docker/ContainerStorageHelper.java +++ b/src/main/java/io/floci/aws/core/common/docker/ContainerStorageHelper.java @@ -389,7 +389,19 @@ public final class ContainerStorageHelper { EmulatorConfig config, ContainerLifecycleManager lifecycleManager, String volumeName) { - boolean isMemory = "memory".equals(config.storage().mode()); + removeNamedVolume(config, lifecycleManager, volumeName, config.storage().mode()); + } + + /** + * {@link #removeNamedVolume(EmulatorConfig, ContainerLifecycleManager, String)} for a service whose own storage + * mode, {@code storageMode}, is the one its records are kept under, rather than the global mode. + */ + public static void removeNamedVolume( + EmulatorConfig config, + ContainerLifecycleManager lifecycleManager, + String volumeName, + String storageMode) { + boolean isMemory = "memory".equals(storageMode); if (isMemory || config.storage().pruneVolumesOnDelete()) { lifecycleManager.removeVolume(volumeName); } else { diff --git a/src/main/java/io/floci/aws/services/neptune/NeptuneService.java b/src/main/java/io/floci/aws/services/neptune/NeptuneService.java index 4a45c2e9e9..3c4f9d317e 100644 --- a/src/main/java/io/floci/aws/services/neptune/NeptuneService.java +++ b/src/main/java/io/floci/aws/services/neptune/NeptuneService.java @@ -98,8 +98,10 @@ public class NeptuneService { // Open the try immediately after reserving the port so config reads below can't leak it. int proxyPort = allocateProxyPort(settings.port()); NeptuneContainerHandle handle = null; + String volumeId = null; boolean provisioned = false; try { + volumeId = keepsClusters() ? UUID.randomUUID().toString() : null; String configuredDbType = config.services().neptune().dbType(); NeptuneDbType dbType = NeptuneDbType.fromConfig(configuredDbType).orElseGet(() -> { LOG.warnv("Unsupported Neptune db-type ''{0}'', falling back to {1}. Supported: gremlin, neo4j.", @@ -121,7 +123,7 @@ public class NeptuneService { String accountId = currentAccount(); String identity = resourceIdentity(accountId, region, id); // graph database needs the container. - handle = containerManager.tryStart(id, image, dbType, accountId, region); + handle = containerManager.tryStart(id, image, dbType, accountId, region, volumeId); String endpointHost = resolveEndpointHost(); NeptuneCluster cluster = new NeptuneCluster(); @@ -138,6 +140,7 @@ public class NeptuneService { cluster.setCreatedAt(Instant.now()); cluster.setDbClusterMembers(new ArrayList<>()); cluster.setProxyPort(proxyPort); + cluster.setVolumeId(volumeId); settings.applyTo(cluster); if (tags != null && !tags.isEmpty()) { cluster.setTags(tags); @@ -168,12 +171,13 @@ public class NeptuneService { // catch (RuntimeException) would miss — so a failed create never leaks the // reserved port or leaves a container behind. Idempotent and a no-op on success. if (!provisioned) { - rollbackDbCluster(resourceIdentity(currentAccount(), currentRegion(), id), handle, proxyPort); + rollbackDbCluster(resourceIdentity(currentAccount(), currentRegion(), id), handle, proxyPort, + volumeId); } } } - private void rollbackDbCluster(String identity, NeptuneContainerHandle handle, int proxyPort) { + private void rollbackDbCluster(String identity, NeptuneContainerHandle handle, int proxyPort, String volumeId) { try { try { // The proxy only starts after the container is ready, so a null handle means it @@ -193,6 +197,8 @@ public class NeptuneService { } catch (RuntimeException e) { LOG.warnv("Error stopping container for Neptune cluster {0}: {1}", identity, e.getMessage()); } + // The cluster never reached the caller, so the volume made for it goes too. + containerManager.discardStorage(volumeId); } finally { // Always release the port — even if a cleanup step throws a non-RuntimeException // (e.g. an Error) — since leaking the port is the exact failure this rollback prevents. @@ -292,6 +298,7 @@ public class NeptuneService { cluster.getContainerHost(), cluster.getContainerPort())); } + containerManager.removeStorage(cluster.getVolumeId()); releaseProxyPort(cluster.getProxyPort()); deleteCluster(cluster); LOG.infov("Neptune cluster {0} deleted", id); @@ -711,6 +718,14 @@ public class NeptuneService { cluster.getDbClusterIdentifier()); } + /** + * Whether Neptune's records outlive Floci, under its own storage mode or the global one, so that a cluster's + * data is kept in a volume of its own as well. + */ + private boolean keepsClusters() { + return !"memory".equals(NeptuneContainerManager.storageMode(config)); + } + private String resolveEndpointHost() { return config.hostname().orElse("localhost"); } diff --git a/src/main/java/io/floci/aws/services/neptune/container/NeptuneContainerManager.java b/src/main/java/io/floci/aws/services/neptune/container/NeptuneContainerManager.java index c5f99381ff..931281b3fb 100644 --- a/src/main/java/io/floci/aws/services/neptune/container/NeptuneContainerManager.java +++ b/src/main/java/io/floci/aws/services/neptune/container/NeptuneContainerManager.java @@ -10,6 +10,7 @@ import io.floci.aws.core.common.docker.ContainerLifecycleManager.EndpointInfo; import io.floci.aws.core.common.docker.ContainerLogStreamer; import io.floci.aws.core.common.docker.ContainerSpec; import io.floci.aws.core.common.docker.ContainerStorageHelper; +import io.floci.aws.core.common.docker.RetryingTarCopier; import io.floci.aws.services.neptune.model.NeptuneDbType; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; @@ -38,6 +39,29 @@ public class NeptuneContainerManager { private static final int BACKEND_READY_DEADLINE_MS = 60_000; private static final int BACKEND_READY_RETRY_MS = 200; private static final int BACKEND_PROBE_CONNECT_MS = 2_000; + /** + * Seconds a container has to stop before Docker kills it. Gremlin Server saves its graph only once its network + * threads have shut down gracefully, a few seconds after the stop signal, and Neo4j flushes its store on the way + * down, so they get longer than the usual grace. + */ + private static final int STOP_TIMEOUT_SECONDS = 30; + /** Neo4j's data directory, which its entrypoint gives to the neo4j user. */ + private static final String NEO4J_DATA_PATH = "/data"; + /** The Gremlin Server image's data directory, owned by the user it runs as, so a fresh volume there is too. */ + private static final String GREMLIN_DATA_PATH = "/opt/gremlin-server/data"; + private static final String GREMLIN_CONF_PATH = "/opt/gremlin-server/conf"; + /** The graph properties the image's {@code gremlin-server.yaml} opens its one graph with. */ + private static final String GREMLIN_GRAPH_PROPERTIES = "tinkergraph-empty.properties"; + /** + * The image's TinkerGraph properties, saving the graph to the data directory when the graph closes, which + * Gremlin Server's shutdown hook does on the stop signal, and loading it from there when it opens. + */ + private static final String PERSISTENT_TINKERGRAPH = String.join("\n", + "gremlin.graph=org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph", + "gremlin.tinkergraph.vertexIdManager=LONG", + "gremlin.tinkergraph.graphLocation=" + GREMLIN_DATA_PATH + "/floci-graph.kryo", + "gremlin.tinkergraph.graphFormat=gryo", + ""); private final ContainerBuilder containerBuilder; private final ContainerLifecycleManager lifecycleManager; @@ -73,9 +97,9 @@ public class NeptuneContainerManager { * @return the container handle, or {@code null} when no Docker daemon is reachable */ public NeptuneContainerHandle tryStart(String clusterId, String image, NeptuneDbType dbType, - String accountId, String region) { + String accountId, String region, String volumeId) { try { - NeptuneContainerHandle handle = start(clusterId, image, dbType, accountId, region); + NeptuneContainerHandle handle = start(clusterId, image, dbType, accountId, region, volumeId); dockerUnavailableLogged = false; return handle; } catch (RuntimeException e) { @@ -101,8 +125,14 @@ public class NeptuneContainerManager { return lifecycleManager.isDockerReachable(); } + /** + * Starts the cluster's graph database container. With a {@code volumeId} its data lives in the cluster's own + * volume, or its directory under the host persistent path, which outlives the container: Neo4j's data directory, + * or, for Gremlin Server, the file its TinkerGraph is saved to when the server stops and loaded from when it + * starts. Without one the graph goes when the container does. + */ public NeptuneContainerHandle start(String clusterId, String image, NeptuneDbType dbType, - String accountId, String region) { + String accountId, String region, String volumeId) { LOG.infov("Starting Neptune backend container ({0}) for cluster: {1}", dbType, clusterId); int backendPort = dbType.backendPort(); @@ -119,6 +149,22 @@ public class NeptuneContainerManager { .withLabels(ContainerStorageHelper.resourceIdentityLabels( "neptune", clusterId, accountId, region)); + if (volumeId != null) { + String dataPath = dbType == NeptuneDbType.NEO4J ? NEO4J_DATA_PATH : GREMLIN_DATA_PATH; + if (ContainerStorageHelper.isNamedVolumeMode(config)) { + ContainerStorageHelper.applyNamedVolume(specBuilder, lifecycleManager, volumeName(volumeId), dataPath); + } else { + String path = ContainerStorageHelper.hostResourcePath(config, "neptune", volumeId).toString(); + ContainerStorageHelper.ensureHostDir(containerDetector, path); + specBuilder.withBind(path, dataPath); + if (dbType == NeptuneDbType.GREMLIN) { + // A host directory belongs to its creator, not to the image's gremlin user, so the server runs + // as root to write the graph there; Neo4j's entrypoint hands its data directory over itself. + specBuilder.withUser("0"); + } + } + } + if (!containerDetector.isRunningInContainer()) { specBuilder.withDynamicPort(backendPort); } else { @@ -126,7 +172,9 @@ public class NeptuneContainerManager { } ContainerSpec spec = specBuilder.build(); - ContainerInfo info = lifecycleManager.createAndStart(spec); + ContainerInfo info = volumeId != null && dbType == NeptuneDbType.GREMLIN + ? lifecycleManager.createAndStart(spec, containerId -> persistGraph(containerId, clusterId)) + : lifecycleManager.createAndStart(spec); EndpointInfo endpoint = info.getEndpoint(backendPort); LOG.infov("Neptune {0} backend for cluster {1}: {2}", dbType, clusterId, endpoint); @@ -150,6 +198,47 @@ public class NeptuneContainerManager { return handle; } + /** + * Gives the created container's TinkerGraph the properties that keep it in the data directory. An image laid + * out otherwise than the default one keeps its graph in memory, as it did before, rather than failing to start. + */ + private void persistGraph(String containerId, String clusterId) { + try { + RetryingTarCopier.copyBytes(lifecycleManager.getDockerClient(), containerId, GREMLIN_CONF_PATH, + GREMLIN_GRAPH_PROPERTIES, PERSISTENT_TINKERGRAPH.getBytes(StandardCharsets.UTF_8), 0644); + } catch (RuntimeException e) { + LOG.warnv("Neptune cluster {0} keeps its graph in memory only: its image has no {1} to configure ({2})", + clusterId, GREMLIN_CONF_PATH + "/" + GREMLIN_GRAPH_PROPERTIES, e.getMessage()); + } + } + + /** + * Removes a deleted cluster's data volume, unless the storage policy keeps volumes on delete. + * A directory under the host persistent path is left in place. + */ + public void removeStorage(String volumeId) { + if (volumeId != null && ContainerStorageHelper.isNamedVolumeMode(config)) { + ContainerStorageHelper.removeNamedVolume(config, lifecycleManager, volumeName(volumeId), + storageMode(config)); + } + } + + /** The storage mode Neptune's records are kept under: its own, or the global one when it names none. */ + public static String storageMode(EmulatorConfig config) { + return config.storage().services().neptune().mode().orElse(config.storage().mode()); + } + + /** Removes the data volume of a cluster that never reached its caller, whatever the storage policy. */ + public void discardStorage(String volumeId) { + if (volumeId != null && ContainerStorageHelper.isNamedVolumeMode(config)) { + lifecycleManager.removeVolume(volumeName(volumeId)); + } + } + + private String volumeName(String volumeId) { + return ContainerStorageHelper.dockerName(config, "neptune-" + volumeId); + } + /** * Environment for the backend container. Neo4j's Bolt endpoint requires auth to be * explicitly disabled so the transparent proxy can relay openCypher sessions without @@ -168,7 +257,7 @@ public class NeptuneContainerManager { return; } activeContainers.remove(handle.getClusterId()); - lifecycleManager.stopAndRemove(handle.getContainerId(), handle.getLogStream()); + lifecycleManager.stopAndRemove(handle.getContainerId(), handle.getLogStream(), STOP_TIMEOUT_SECONDS); } /** diff --git a/src/main/java/io/floci/aws/services/neptune/model/NeptuneCluster.java b/src/main/java/io/floci/aws/services/neptune/model/NeptuneCluster.java index 2317ee4bc8..0b2df0d9a8 100644 --- a/src/main/java/io/floci/aws/services/neptune/model/NeptuneCluster.java +++ b/src/main/java/io/floci/aws/services/neptune/model/NeptuneCluster.java @@ -46,6 +46,8 @@ public class NeptuneCluster { private String containerHost; private int containerPort; private int proxyPort; + /** Names the cluster's data volume; null for a cluster whose data is not kept, in memory mode. */ + private String volumeId; public NeptuneCluster() {} @@ -168,4 +170,7 @@ public class NeptuneCluster { public int getProxyPort() { return proxyPort; } public void setProxyPort(int proxyPort) { this.proxyPort = proxyPort; } + + public String getVolumeId() { return volumeId; } + public void setVolumeId(String volumeId) { this.volumeId = volumeId; } } diff --git a/src/test/java/io/floci/aws/services/neptune/NeptuneCreateScopeIntegrationTest.java b/src/test/java/io/floci/aws/services/neptune/NeptuneCreateScopeIntegrationTest.java index 1dd2fca8bb..98df402f70 100644 --- a/src/test/java/io/floci/aws/services/neptune/NeptuneCreateScopeIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/neptune/NeptuneCreateScopeIntegrationTest.java @@ -48,7 +48,7 @@ class NeptuneCreateScopeIntegrationTest { new InMemoryStorageFactory("000000000000")); CountDownLatch started = new CountDownLatch(1); CountDownLatch finish = new CountDownLatch(1); - when(containers.tryStart(anyString(), anyString(), any(NeptuneDbType.class), anyString(), anyString())) + when(containers.tryStart(anyString(), anyString(), any(NeptuneDbType.class), anyString(), anyString(), any())) .thenAnswer(call -> { if ("000000000000".equals(call.getArgument(3)) && "us-east-1".equals(call.getArgument(4))) { started.countDown(); @@ -69,7 +69,7 @@ class NeptuneCreateScopeIntegrationTest { () -> service.createDbCluster("shared", "1.3.2.1", false)); assertEquals("DBClusterAlreadyExistsFault", duplicate.getErrorCode()); verify(containers, times(1)).tryStart( - anyString(), anyString(), any(NeptuneDbType.class), anyString(), anyString()); + anyString(), anyString(), any(NeptuneDbType.class), anyString(), anyString(), any()); }); RequestScopes.runAs("111111111111", "us-east-1", () -> { NeptuneCluster cluster = service.createDbCluster("shared", "1.3.2.1", false); diff --git a/src/test/java/io/floci/aws/services/neptune/NeptuneGraphVolumeDockerNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/neptune/NeptuneGraphVolumeDockerNightlyIntegrationTest.java new file mode 100644 index 0000000000..98d83ee542 --- /dev/null +++ b/src/test/java/io/floci/aws/services/neptune/NeptuneGraphVolumeDockerNightlyIntegrationTest.java @@ -0,0 +1,186 @@ +package io.floci.aws.services.neptune; + +import com.github.dockerjava.api.DockerClient; +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.docker.ContainerLifecycleManager; +import io.floci.aws.core.common.docker.ContainerStorageHelper; +import io.floci.aws.services.neptune.container.NeptuneContainerHandle; +import io.floci.aws.services.neptune.container.NeptuneContainerManager; +import io.floci.aws.services.neptune.model.NeptuneDbType; +import io.floci.aws.testing.DockerAvailability; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.neo4j.driver.AuthTokens; +import org.neo4j.driver.Driver; +import org.neo4j.driver.GraphDatabase; +import org.neo4j.driver.Session; + +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.WebSocket; +import java.time.Duration; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.TimeUnit; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * #5664: a Neptune cluster's graph outlives its container when the cluster has a volume. Each engine writes a + * vertex, its container is stopped and removed as Floci's shutdown does, and a new container started on the same + * volume reads the vertex back: Neo4j from its data directory, Gremlin Server from the file its TinkerGraph saved + * when it stopped. + * + *

A Docker end-to-end check: it runs real Gremlin Server and Neo4j containers. + */ +@QuarkusTest +@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true") +@Timeout(value = 10, unit = TimeUnit.MINUTES) +class NeptuneGraphVolumeDockerNightlyIntegrationTest { + + private static final String ACCOUNT = "000000000000"; + private static final String REGION = "us-east-1"; + + @Inject + DockerClient dockerClient; + + @Inject + NeptuneContainerManager containerManager; + + @Inject + ContainerLifecycleManager lifecycleManager; + + @Inject + EmulatorConfig config; + + @BeforeEach + void requireDocker() { + Assumptions.assumeTrue(DockerAvailability.answers(dockerClient), + "Docker daemon must be available for the Neptune graph volume check"); + } + + @Test + void aGremlinGraphIsBackOnANewContainer() throws Exception { + String id = "graph-" + UUID.randomUUID().toString().substring(0, 8); + String volumeId = UUID.randomUUID().toString(); + String image = config.services().neptune().defaultImage(); + try { + NeptuneContainerHandle first = containerManager.start(id, image, NeptuneDbType.GREMLIN, ACCOUNT, REGION, + volumeId); + String added = gremlin(first, "g.addV('person').property('name','kept').count()"); + assertTrue(added.contains("\"code\":200"), added); + containerManager.stop(first); + + NeptuneContainerHandle second = containerManager.start(id, image, NeptuneDbType.GREMLIN, ACCOUNT, + REGION, volumeId); + try { + assertNotEquals(first.getContainerId(), second.getContainerId()); + String found = gremlin(second, "g.V().has('person','name','kept').values('name')"); + assertTrue(found.contains("kept"), found); + } finally { + containerManager.stop(second); + } + } finally { + cleanUp(id, volumeId); + } + } + + @Test + void aNeo4jGraphIsBackOnANewContainer() { + String id = "graph-" + UUID.randomUUID().toString().substring(0, 8); + String volumeId = UUID.randomUUID().toString(); + String image = config.services().neptune().defaultNeo4jImage(); + try { + NeptuneContainerHandle first = containerManager.start(id, image, NeptuneDbType.NEO4J, ACCOUNT, REGION, + volumeId); + try (Driver driver = bolt(first); Session session = driver.session()) { + session.run("CREATE (:Person {name: 'kept'})").consume(); + } + containerManager.stop(first); + + NeptuneContainerHandle second = containerManager.start(id, image, NeptuneDbType.NEO4J, ACCOUNT, REGION, + volumeId); + try (Driver driver = bolt(second); Session session = driver.session()) { + assertNotEquals(first.getContainerId(), second.getContainerId()); + long count = session.run("MATCH (p:Person {name: 'kept'}) RETURN count(p) AS c") + .single().get("c").asLong(); + assertEquals(1L, count); + } finally { + containerManager.stop(second); + } + } finally { + cleanUp(id, volumeId); + } + } + + /** + * Removes whatever container the cluster still has, by its identity, whether or not a start returned its handle, + * and then the volume, which no container holds any more. + */ + private void cleanUp(String id, String volumeId) { + containerManager.stopByClusterId(ACCOUNT + "-" + REGION + "-" + id); + lifecycleManager.removeVolume(volumeName(volumeId)); + } + + private String volumeName(String volumeId) { + return ContainerStorageHelper.dockerName(config, "neptune-" + volumeId); + } + + private static Driver bolt(NeptuneContainerHandle handle) { + return GraphDatabase.driver("bolt://" + handle.getHost() + ":" + handle.getPort(), AuthTokens.none()); + } + + /** + * Evaluates {@code script} on the container's Gremlin Server over its WebSocket endpoint, as a GraphSON text + * frame, and returns the response frame. A server that has just opened its port can still be loading its graph, + * so the request is retried until it is answered. + */ + private static String gremlin(NeptuneContainerHandle handle, String script) { + String request = """ + {"requestId":"%s","op":"eval","processor":"","args":{"gremlin":"%s","language":"gremlin-groovy"}}""" + .formatted(UUID.randomUUID(), script); + return await("gremlin answer").atMost(Duration.ofMinutes(1)).pollInterval(Duration.ofSeconds(2)) + .ignoreExceptions() + .until(() -> send(handle, request), response -> response.contains("\"status\"")); + } + + private static String send(NeptuneContainerHandle handle, String request) throws Exception { + CompletableFuture response = new CompletableFuture<>(); + StringBuilder text = new StringBuilder(); + WebSocket socket = HttpClient.newHttpClient().newWebSocketBuilder() + .connectTimeout(Duration.ofSeconds(5)) + .buildAsync(URI.create("ws://" + handle.getHost() + ":" + handle.getPort() + "/gremlin"), + new WebSocket.Listener() { + @Override + public CompletionStage onText(WebSocket webSocket, CharSequence data, boolean last) { + text.append(data); + if (last) { + response.complete(text.toString()); + } + webSocket.request(1); + return null; + } + + @Override + public void onError(WebSocket webSocket, Throwable error) { + response.completeExceptionally(error); + } + }) + .get(10, TimeUnit.SECONDS); + try { + socket.sendText(request, true).get(10, TimeUnit.SECONDS); + return response.get(30, TimeUnit.SECONDS); + } finally { + socket.abort(); + } + } +} diff --git a/src/test/java/io/floci/aws/services/neptune/NeptuneServiceTest.java b/src/test/java/io/floci/aws/services/neptune/NeptuneServiceTest.java index 0282a0c475..4baaf3b208 100644 --- a/src/test/java/io/floci/aws/services/neptune/NeptuneServiceTest.java +++ b/src/test/java/io/floci/aws/services/neptune/NeptuneServiceTest.java @@ -15,6 +15,7 @@ import io.floci.aws.services.neptune.model.NeptuneInstanceSettings; import io.floci.aws.services.neptune.proxy.NeptuneProxyManager; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import java.util.List; import java.util.Map; @@ -23,6 +24,7 @@ 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.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -30,6 +32,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; @@ -48,6 +51,9 @@ class NeptuneServiceTest { private String currentAccount; private String currentRegion; private AccountAwareStorageBackend clusterStorage; + private String storageMode = "memory"; + /** Neptune's own storage mode, or null when it names none. */ + private String neptuneStorageMode; @BeforeEach void setUp() { @@ -77,6 +83,14 @@ class NeptuneServiceTest { when(neptuneConfig.defaultImage()).thenReturn("tinkerpop/gremlin-server:3.7"); when(neptuneConfig.defaultNeo4jImage()).thenReturn("neo4j:5"); when(config.hostname()).thenReturn(Optional.of("localhost")); + EmulatorConfig.StorageConfig storage = mock(EmulatorConfig.StorageConfig.class); + EmulatorConfig.ServiceStorageOverrides storageOverrides = mock(EmulatorConfig.ServiceStorageOverrides.class); + EmulatorConfig.NeptuneStorageConfig neptuneStorage = mock(EmulatorConfig.NeptuneStorageConfig.class); + when(config.storage()).thenReturn(storage); + when(storage.mode()).thenAnswer(invocation -> storageMode); + when(storage.services()).thenReturn(storageOverrides); + when(storageOverrides.neptune()).thenReturn(neptuneStorage); + when(neptuneStorage.mode()).thenAnswer(invocation -> Optional.ofNullable(neptuneStorageMode)); when(storageFactory.create(anyString(), anyString(), any())) .thenAnswer(inv -> { @@ -86,16 +100,68 @@ class NeptuneServiceTest { } return store; }); - when(containerManager.tryStart(anyString(), anyString(), any(NeptuneDbType.class), anyString(), anyString())) + when(containerManager.tryStart(anyString(), anyString(), any(NeptuneDbType.class), anyString(), anyString(), any())) .thenReturn(new NeptuneContainerHandle("cid", "c", "localhost", 8182)); doNothing().when(proxyManager).startProxy(anyString(), anyInt(), anyString(), anyInt()); service = new NeptuneService(config, regionResolver, containerManager, proxyManager, storageFactory); } + @Test + void aClusterKeepsItsGraphInAVolumeOfItsOwnWhenNeptuneKeepsItsRecords() { + storageMode = "persistent"; + + String first = service.createDbCluster("first", null, false).getVolumeId(); + String second = service.createDbCluster("second", null, false).getVolumeId(); + + assertNotNull(first); + assertNotEquals(first, second); + assertEquals(first, service.getDbCluster("first").getVolumeId()); + verify(containerManager).tryStart(eq("first"), anyString(), eq(NeptuneDbType.GREMLIN), eq("000000000000"), + eq("us-east-1"), eq(first)); + service.deleteDbCluster("first"); + verify(containerManager).removeStorage(first); + verify(containerManager, never()).discardStorage(any()); + String recreated = service.createDbCluster("first", null, false).getVolumeId(); + assertNotNull(recreated); + assertNotEquals(first, recreated); + } + + @Test + void neptunesOwnStorageModeDecidesWhetherAClusterGetsAVolume() { + storageMode = "persistent"; + neptuneStorageMode = "memory"; + assertNull(service.createDbCluster("neptune-in-memory", null, false).getVolumeId()); + + storageMode = "memory"; + neptuneStorageMode = "persistent"; + assertNotNull(service.createDbCluster("neptune-on-disk", null, false).getVolumeId()); + + neptuneStorageMode = null; + assertNull(service.createDbCluster("all-in-memory", null, false).getVolumeId()); + verify(containerManager).tryStart(eq("all-in-memory"), anyString(), any(NeptuneDbType.class), anyString(), + anyString(), isNull()); + } + + @Test + void aFailedCreateDiscardsTheVolumeMadeForIt() { + storageMode = "persistent"; + doThrow(new IllegalStateException("Backend startup failed")).when(containerManager) + .tryStart(anyString(), anyString(), any(NeptuneDbType.class), anyString(), anyString(), any()); + + assertThrows(IllegalStateException.class, () -> service.createDbCluster("c", null, false)); + + ArgumentCaptor volume = ArgumentCaptor.forClass(String.class); + verify(containerManager).tryStart(eq("c"), anyString(), any(NeptuneDbType.class), anyString(), anyString(), + volume.capture()); + assertNotNull(volume.getValue()); + verify(containerManager).discardStorage(volume.getValue()); + assertFalse(service.hasCluster("c")); + } + @Test void failedCreateReleasesItsIdentifierForAnExplicitRetry() { - when(containerManager.tryStart(anyString(), anyString(), any(NeptuneDbType.class), anyString(), anyString())) + when(containerManager.tryStart(anyString(), anyString(), any(NeptuneDbType.class), anyString(), anyString(), any())) .thenThrow(new IllegalStateException("Backend startup failed")) .thenReturn(new NeptuneContainerHandle("retry-container", "same", "localhost", 8182)); @@ -151,7 +217,7 @@ class NeptuneServiceTest { @Test void failedProvisioningRollsBackContainerAndReleasesProxyPort() { NeptuneContainerHandle handle = new NeptuneContainerHandle("cid", "c", "localhost", 8182); - when(containerManager.tryStart(anyString(), anyString(), any(NeptuneDbType.class), anyString(), anyString())) + when(containerManager.tryStart(anyString(), anyString(), any(NeptuneDbType.class), anyString(), anyString(), any())) .thenReturn(handle); // Proxy startup blows up after the port is reserved and the container is started. @@ -177,7 +243,7 @@ class NeptuneServiceTest { @Test void jvmErrorDuringProvisioningStillRollsBack() { NeptuneContainerHandle handle = new NeptuneContainerHandle("cid", "c", "localhost", 8182); - when(containerManager.tryStart(anyString(), anyString(), any(NeptuneDbType.class), anyString(), anyString())) + when(containerManager.tryStart(anyString(), anyString(), any(NeptuneDbType.class), anyString(), anyString(), any())) .thenReturn(handle); // A JVM Error (not a RuntimeException) escapes provisioning — a catch (RuntimeException) @@ -204,7 +270,7 @@ class NeptuneServiceTest { // 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("c"), anyString(), any(NeptuneDbType.class), anyString(), anyString()); + .when(containerManager).tryStart(eq("c"), anyString(), any(NeptuneDbType.class), anyString(), anyString(), any()); // The original failure must propagate to the caller (we clean up, then rethrow). assertThrows(RuntimeException.class, @@ -217,7 +283,7 @@ class NeptuneServiceTest { verify(containerManager).stopByClusterId("000000000000-us-east-1-c"); // The reserved proxy port was still released: a subsequent successful create reuses the base port. - when(containerManager.tryStart(anyString(), anyString(), any(NeptuneDbType.class), anyString(), anyString())) + when(containerManager.tryStart(anyString(), anyString(), any(NeptuneDbType.class), anyString(), anyString(), any())) .thenReturn(new NeptuneContainerHandle("cid", "c2", "localhost", 8182)); NeptuneCluster recovered = service.createDbCluster("c2", "1.3.2.1", false); assertEquals(18182, recovered.getProxyPort(), @@ -269,7 +335,7 @@ class NeptuneServiceTest { // 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), anyString(), anyString())).thenReturn(null); + when(containerManager.tryStart(anyString(), anyString(), any(NeptuneDbType.class), anyString(), anyString(), any())).thenReturn(null); NeptuneCluster created = service.createDbCluster("no-docker-cluster", "1.3.2.1", false); diff --git a/src/test/java/io/floci/aws/services/neptune/container/NeptuneContainerManagerTest.java b/src/test/java/io/floci/aws/services/neptune/container/NeptuneContainerManagerTest.java index 3fdbffeec5..270c0298e2 100644 --- a/src/test/java/io/floci/aws/services/neptune/container/NeptuneContainerManagerTest.java +++ b/src/test/java/io/floci/aws/services/neptune/container/NeptuneContainerManagerTest.java @@ -1,5 +1,8 @@ package io.floci.aws.services.neptune.container; +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.CopyArchiveToContainerCmd; +import com.github.dockerjava.api.exception.NotFoundException; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.docker.ContainerBuilder; @@ -11,26 +14,36 @@ import io.floci.aws.services.neptune.model.NeptuneDbType; import io.floci.aws.testing.ParallelLocks; import org.jboss.logging.Logger; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.api.parallel.ResourceAccessMode; import org.junit.jupiter.api.parallel.ResourceLock; +import org.mockito.ArgumentCaptor; +import org.mockito.ArgumentMatchers; import org.mockito.Mockito; import java.io.IOException; +import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.Map; import java.util.Optional; +import java.util.function.Consumer; 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.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.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -66,7 +79,7 @@ class NeptuneContainerManagerTest { for (int attempt = 0; attempt < 3; attempt++) { assertNull(manager.tryStart("cluster1", "tinkerpop/gremlin-server:3.7.3", NeptuneDbType.GREMLIN, - "000000000000", "us-east-1"), + "000000000000", "us-east-1", null), "attempt " + attempt + " should report unavailable"); } assertFalse(manager.isDockerReachable()); @@ -85,7 +98,7 @@ class NeptuneContainerManagerTest { RuntimeException failure = assertThrows(RuntimeException.class, () -> manager.tryStart("cluster1", "tinkerpop/gremlin-server:3.7.3", NeptuneDbType.GREMLIN, - "000000000000", "us-east-1")); + "000000000000", "us-east-1", null)); assertEquals("no such image: tinkerpop/gremlin-server:3.7.3", failure.getMessage()); } @@ -117,7 +130,7 @@ class NeptuneContainerManagerTest { NeptuneContainerHandle handle = manager.tryStart("cluster1", "tinkerpop/gremlin-server:3.7.3", NeptuneDbType.GREMLIN, - "000000000000", "us-east-1"); + "000000000000", "us-east-1", null); assertEquals("container-id", handle.getContainerId()); assertEquals(serverSocket.getLocalPort(), handle.getPort()); @@ -163,7 +176,7 @@ class NeptuneContainerManagerTest { new RegionResolver("us-east-1", "000000000000")); manager.start("cluster1", "tinkerpop/gremlin-server:3.7.3", NeptuneDbType.GREMLIN, - "111111111111", "eu-west-1"); + "111111111111", "eu-west-1", null); verify(builder).withLabels(Map.of( "io.floci", "aws", @@ -175,6 +188,257 @@ class NeptuneContainerManagerTest { } } + @Test + void aNeo4jClusterWithAVolumeKeepsItsDataDirectoryThere() throws IOException { + try (ServerSocket backend = backend(BOLT_REPLY)) { + ContainerLifecycleManager lifecycle = startsOn(backend, 7687); + ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF); + NeptuneContainerManager manager = newManager(lifecycle, builder, storage("persistent", null, false)); + + manager.start("cluster1", "neo4j:5-community", NeptuneDbType.NEO4J, "000000000000", "us-east-1", + "vol-1"); + + verify(lifecycle).ensureVolume("floci-aws-neptune-vol-1"); + verify(builder).withNamedVolume("floci-aws-neptune-vol-1", "/data"); + verify(builder, never()).withUser(anyString()); + verify(lifecycle).createAndStart(any(ContainerSpec.class)); + } + } + + @Test + void aGremlinClusterWithAVolumeSavesItsGraphThere() throws IOException { + try (ServerSocket backend = backend(GREMLIN_REPLY)) { + ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class); + ArgumentCaptor> beforeStart = ArgumentCaptor.captor(); + when(lifecycle.createAndStart(any(ContainerSpec.class), beforeStart.capture())) + .thenReturn(info(backend, 8182)); + DockerClient docker = mock(DockerClient.class); + CopyArchiveToContainerCmd copy = mock(CopyArchiveToContainerCmd.class, Mockito.RETURNS_SELF); + when(lifecycle.getDockerClient()).thenReturn(docker); + when(docker.copyArchiveToContainerCmd("container-id")).thenReturn(copy); + ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF); + NeptuneContainerManager manager = newManager(lifecycle, builder, storage("persistent", null, false)); + + manager.start("cluster1", "tinkerpop/gremlin-server:3.7.3", NeptuneDbType.GREMLIN, "000000000000", + "us-east-1", "vol-1"); + beforeStart.getValue().accept("container-id"); + + verify(builder).withNamedVolume("floci-aws-neptune-vol-1", "/opt/gremlin-server/data"); + verify(builder, never()).withUser(anyString()); + verify(copy).withRemotePath("/opt/gremlin-server/conf"); + ArgumentCaptor tar = ArgumentCaptor.forClass(InputStream.class); + verify(copy).withTarInputStream(tar.capture()); + String archive = new String(tar.getValue().readAllBytes(), StandardCharsets.UTF_8); + assertTrue(archive.contains("tinkergraph-empty.properties"), archive); + assertTrue(archive.contains( + "gremlin.tinkergraph.graphLocation=/opt/gremlin-server/data/floci-graph.kryo\n"), archive); + assertTrue(archive.contains("gremlin.tinkergraph.graphFormat=gryo\n"), archive); + assertTrue(archive.contains("gremlin.tinkergraph.vertexIdManager=LONG\n"), archive); + verify(copy).exec(); + } + } + + @Test + void aGremlinImageLaidOutOtherwiseStillStartsWithItsGraphInMemory() { + ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class); + ArgumentCaptor> beforeStart = ArgumentCaptor.captor(); + DockerClient docker = mock(DockerClient.class); + when(lifecycle.getDockerClient()).thenReturn(docker); + when(docker.copyArchiveToContainerCmd("container-id")) + .thenThrow(new NotFoundException("Could not find the file /opt/gremlin-server/conf in container")); + when(lifecycle.createAndStart(any(ContainerSpec.class), beforeStart.capture())) + .thenThrow(new IllegalStateException("stop after capturing the setup")); + NeptuneContainerManager manager = newManager(lifecycle, mock(ContainerBuilder.Builder.class, + Mockito.RETURNS_SELF), storage("persistent", null, false)); + assertThrows(IllegalStateException.class, () -> manager.start("cluster1", "custom/gremlin:1", + NeptuneDbType.GREMLIN, "000000000000", "us-east-1", "vol-1")); + + beforeStart.getValue().accept("container-id"); + + verify(docker, Mockito.atLeastOnce()).copyArchiveToContainerCmd("container-id"); + } + + @Test + void aGremlinClusterUnderTheHostPathRunsAsRootToWriteItsGraph(@TempDir Path hostPath) throws IOException { + try (ServerSocket backend = backend(GREMLIN_REPLY)) { + ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class); + when(lifecycle.createAndStart(any(ContainerSpec.class), ArgumentMatchers.>any())) + .thenReturn(info(backend, 8182)); + ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF); + NeptuneContainerManager manager = newManager(lifecycle, builder, + storage("persistent", hostPath.toString(), false)); + + manager.start("cluster1", "tinkerpop/gremlin-server:3.7.3", NeptuneDbType.GREMLIN, "000000000000", + "us-east-1", "vol-1"); + + Path dataDir = hostPath.resolve("neptune").resolve("vol-1"); + verify(builder).withBind(dataDir.toString(), "/opt/gremlin-server/data"); + assertTrue(Files.isDirectory(dataDir)); + verify(builder).withUser("0"); + verify(builder, never()).withNamedVolume(anyString(), anyString()); + } + } + + @Test + void aNeo4jClusterUnderTheHostPathKeepsTheImagesUser(@TempDir Path hostPath) throws IOException { + try (ServerSocket backend = backend(BOLT_REPLY)) { + ContainerLifecycleManager lifecycle = startsOn(backend, 7687); + ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF); + NeptuneContainerManager manager = newManager(lifecycle, builder, + storage("persistent", hostPath.toString(), false)); + + manager.start("cluster1", "neo4j:5-community", NeptuneDbType.NEO4J, "000000000000", "us-east-1", + "vol-1"); + + verify(builder).withBind(hostPath.resolve("neptune").resolve("vol-1").toString(), "/data"); + verify(builder, never()).withUser(anyString()); + } + } + + @Test + void aClusterWithoutAVolumeMountsNothingAndKeepsTheImagesGraph() throws IOException { + try (ServerSocket backend = backend(GREMLIN_REPLY)) { + ContainerLifecycleManager lifecycle = startsOn(backend, 8182); + ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF); + NeptuneContainerManager manager = newManager(lifecycle, builder, storage("memory", null, false)); + + manager.start("cluster1", "tinkerpop/gremlin-server:3.7.3", NeptuneDbType.GREMLIN, "000000000000", + "us-east-1", null); + + verify(builder, never()).withNamedVolume(anyString(), anyString()); + verify(builder, never()).withBind(anyString(), anyString()); + verify(lifecycle).createAndStart(any(ContainerSpec.class)); + verify(lifecycle, never()).createAndStart(any(ContainerSpec.class), + ArgumentMatchers.>any()); + } + } + + @Test + void aContainerHasTimeToSaveItsGraphWhenItStops() { + ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class); + NeptuneContainerHandle handle = new NeptuneContainerHandle("container-id", "cluster1", "127.0.0.1", 8182); + + newManager(lifecycle).stop(handle); + + verify(lifecycle).stopAndRemove("container-id", null, 30); + } + + @Test + void removingStorageFollowsThePolicyAndLeavesHostDirectoriesAlone(@TempDir Path hostPath) { + ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class); + newManager(lifecycle, mock(ContainerBuilder.Builder.class), storage("persistent", null, false)) + .removeStorage("kept"); + newManager(lifecycle, mock(ContainerBuilder.Builder.class), storage("persistent", hostPath.toString(), true)) + .removeStorage("host"); + NeptuneContainerManager pruning = newManager(lifecycle, mock(ContainerBuilder.Builder.class), + storage("persistent", null, true)); + pruning.removeStorage(null); + pruning.removeStorage("pruned"); + + verify(lifecycle).removeVolume("floci-aws-neptune-pruned"); + verify(lifecycle, times(1)).removeVolume(anyString()); + } + + @Test + void removingStorageFollowsNeptunesOwnStorageMode() { + ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class); + newManager(lifecycle, mock(ContainerBuilder.Builder.class), storage("memory", "persistent", null, false)) + .removeStorage("kept-by-neptune"); + newManager(lifecycle, mock(ContainerBuilder.Builder.class), storage("persistent", "memory", null, false)) + .removeStorage("neptune-in-memory"); + newManager(lifecycle, mock(ContainerBuilder.Builder.class), storage("memory", null, null, false)) + .removeStorage("all-in-memory"); + + verify(lifecycle, never()).removeVolume("floci-aws-neptune-kept-by-neptune"); + verify(lifecycle).removeVolume("floci-aws-neptune-neptune-in-memory"); + verify(lifecycle).removeVolume("floci-aws-neptune-all-in-memory"); + } + + @Test + void discardingStorageDropsTheVolumeEvenWhenThePolicyRetainsVolumes(@TempDir Path hostPath) { + ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class); + NeptuneContainerManager manager = newManager(lifecycle, mock(ContainerBuilder.Builder.class), + storage("persistent", null, false)); + + manager.discardStorage("vol-1"); + manager.discardStorage(null); + newManager(lifecycle, mock(ContainerBuilder.Builder.class), storage("persistent", hostPath.toString(), false)) + .discardStorage("vol-2"); + + verify(lifecycle).removeVolume("floci-aws-neptune-vol-1"); + verify(lifecycle, times(1)).removeVolume(anyString()); + } + + private static final byte[] GREMLIN_REPLY = "HTTP/1.1 400 Bad Request\r\n\r\n".getBytes(StandardCharsets.UTF_8); + private static final byte[] BOLT_REPLY = {0x00, 0x00, 0x00, 0x05}; + + /** A loopback backend that answers one readiness probe with {@code reply}. */ + private static ServerSocket backend(byte[] reply) throws IOException { + 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(reply); + out.flush(); + } catch (IOException e) { + LOG.debugv(e, "Acceptor socket closed during test teardown"); + } + }); + responder.setDaemon(true); + responder.start(); + return serverSocket; + } + + private static ContainerLifecycleManager.ContainerInfo info(ServerSocket backend, int backendPort) { + return new ContainerLifecycleManager.ContainerInfo("container-id", Map.of(backendPort, + new ContainerLifecycleManager.EndpointInfo("127.0.0.1", backend.getLocalPort()))); + } + + private static ContainerLifecycleManager startsOn(ServerSocket backend, int backendPort) { + ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class); + when(lifecycle.createAndStart(any(ContainerSpec.class))).thenReturn(info(backend, backendPort)); + return lifecycle; + } + + private static EmulatorConfig.StorageConfig storage(String mode, String hostPersistentPath, boolean prune) { + return storage(mode, null, hostPersistentPath, prune); + } + + /** Storage settings with {@code neptuneMode} as Neptune's own storage mode, none when null. */ + private static EmulatorConfig.StorageConfig storage(String mode, String neptuneMode, String hostPersistentPath, + boolean prune) { + EmulatorConfig.StorageConfig storage = mock(EmulatorConfig.StorageConfig.class); + EmulatorConfig.ServiceStorageOverrides overrides = mock(EmulatorConfig.ServiceStorageOverrides.class); + EmulatorConfig.NeptuneStorageConfig neptune = mock(EmulatorConfig.NeptuneStorageConfig.class); + when(storage.mode()).thenReturn(mode); + when(storage.hostPersistentPath()).thenReturn(hostPersistentPath); + when(storage.pruneVolumesOnDelete()).thenReturn(prune); + lenient().when(storage.services()).thenReturn(overrides); + lenient().when(overrides.neptune()).thenReturn(neptune); + lenient().when(neptune.mode()).thenReturn(Optional.ofNullable(neptuneMode)); + return storage; + } + + private NeptuneContainerManager newManager(ContainerLifecycleManager lifecycleManager, + ContainerBuilder.Builder builder, + EmulatorConfig.StorageConfig storage) { + ContainerBuilder containerBuilder = mock(ContainerBuilder.class); + when(containerBuilder.newContainer(anyString())).thenReturn(builder); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); + 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()); + when(config.storage()).thenReturn(storage); + return new NeptuneContainerManager(containerBuilder, lifecycleManager, logStreamer, + mock(ContainerDetector.class), config, new RegionResolver("us-east-1", "000000000000")); + } + private NeptuneContainerManager newManager(ContainerLifecycleManager lifecycleManager) { ContainerBuilder containerBuilder = mock(ContainerBuilder.class); ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);