From b7a95fc920ad6d291dea8994d3adb99912cc2cd0 Mon Sep 17 00:00:00 2001 From: Murtaza Shajapurwala <65263321+murtazayusuf@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:13:40 +0530 Subject: [PATCH] feat(elasticache): add an explicit shell-less backend path for Redis-compatible images (#8642) * feat(elasticache): add an explicit shell-less backend path for Redis-compatible images --- .../configuration/advanced/application-yml.md | 2 + docs/configuration/environment-variables.md | 2 + docs/services/elasticache.md | 62 ++++ .../io/floci/aws/config/EmulatorConfig.java | 21 ++ .../docker/ContainerLifecycleManager.java | 20 +- .../elasticache/ElastiCacheService.java | 16 +- .../ElastiCacheContainerManager.java | 217 ++++++++++- .../container/ValkeyClusterFormation.java | 6 +- src/main/resources/application.yml | 1 + ...iCacheShellLessBackendIntegrationTest.java | 343 ++++++++++++++++++ ...iCacheShellLessClusterIntegrationTest.java | 138 +++++++ ...astiCacheShellLessSnapshotServiceTest.java | 109 ++++++ .../ElastiCacheTestConnections.java | 82 ++++- .../elasticache/ShellLessBackendProfile.java | 29 ++ .../elasticache/ShellLessClusterProfile.java | 19 + ...stiCacheShellLessContainerManagerTest.java | 266 ++++++++++++++ src/test/resources/application.yml | 1 + 17 files changed, 1315 insertions(+), 19 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/elasticache/ElastiCacheShellLessBackendIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/elasticache/ElastiCacheShellLessClusterIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/elasticache/ElastiCacheShellLessSnapshotServiceTest.java create mode 100644 src/test/java/io/floci/aws/services/elasticache/ShellLessBackendProfile.java create mode 100644 src/test/java/io/floci/aws/services/elasticache/ShellLessClusterProfile.java create mode 100644 src/test/java/io/floci/aws/services/elasticache/container/ElastiCacheShellLessContainerManagerTest.java diff --git a/docs/configuration/advanced/application-yml.md b/docs/configuration/advanced/application-yml.md index 5be5f1ed73..d8ed368b3a 100644 --- a/docs/configuration/advanced/application-yml.md +++ b/docs/configuration/advanced/application-yml.md @@ -222,6 +222,8 @@ floci: proxy-base-port: 6379 proxy-max-port: 6399 default-image: "valkey/valkey:8" + shell-less-backend: false # true = image has no shell or CLI: flags as container arguments, snapshots via SAVE over RESP + Docker archive API + shell-less-backend-dbfilename: dump.rdb # snapshot file the server loads at startup (used with shell-less-backend) rds: enabled: true diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md index 358336bafc..d040a6c478 100644 --- a/docs/configuration/environment-variables.md +++ b/docs/configuration/environment-variables.md @@ -462,6 +462,8 @@ These services spawn Docker containers. They require access to the Docker socket | `FLOCI_SERVICES_ELASTICACHE_PROXY_BASE_PORT` | `6379` | First port in the ElastiCache proxy range | | `FLOCI_SERVICES_ELASTICACHE_PROXY_MAX_PORT` | `6399` | Last port in the ElastiCache proxy range | | `FLOCI_SERVICES_ELASTICACHE_DEFAULT_IMAGE` | `valkey/valkey:8` | Default Docker image for cache clusters | +| `FLOCI_SERVICES_ELASTICACHE_SHELL_LESS_BACKEND` | `false` | Pass server flags as container arguments and take and restore snapshots without a shell or CLI in the image (`SAVE` over RESP, the Docker archive API, the snapshot file placed before the server starts). Never inferred from the image; see [ElastiCache](../services/elasticache.md#images-with-no-shell-or-cli) | +| `FLOCI_SERVICES_ELASTICACHE_SHELL_LESS_BACKEND_DBFILENAME` | `dump.rdb` | Snapshot file name the server loads at startup; used only with `FLOCI_SERVICES_ELASTICACHE_SHELL_LESS_BACKEND` | | `FLOCI_SERVICES_ELASTICACHE_DOCKER_NETWORK` | _(none)_ | Docker network for ElastiCache containers (overrides `FLOCI_SERVICES_DOCKER_NETWORK`) | | `FLOCI_SERVICES_ELASTICACHE_CLUSTER_ANNOUNCE_HOSTNAME` | _(none)_ | Hostname cluster-mode nodes announce in `MOVED`/`ASK` redirects and topology responses, and report as the `ConfigurationEndpoint`. Set to a name every client resolves (e.g. `localhost.floci.io`) when `FLOCI_HOSTNAME` only resolves inside Floci's Docker network. Defaults to `FLOCI_HOSTNAME` | diff --git a/docs/services/elasticache.md b/docs/services/elasticache.md index e92800555c..19f87f0a0f 100644 --- a/docs/services/elasticache.md +++ b/docs/services/elasticache.md @@ -367,6 +367,8 @@ cluster or a group without a running backend is refused, as is seeding a cluster group. Automatic snapshots, `CopySnapshot` and `FinalSnapshotIdentifier` are not modeled. To reload the dataset, the backend runs with `--enable-debug-command local`, which allows `DEBUG` only for connections from inside its own container; clients always connect through the proxy. +With [`shell-less-backend`](#images-with-no-shell-or-cli) the snapshot file is placed before the +server starts instead, and `DEBUG` is not enabled. ## Engine version and backend image @@ -395,6 +397,64 @@ describe responses report the stored request metadata. Memcached uses the separate `floci.services.elasticache.default-memcached-image` (`FLOCI_SERVICES_ELASTICACHE_DEFAULT_MEMCACHED_IMAGE`) setting, default `memcached:1.6`. +### Images with no shell or CLI + +By default Floci starts the backend through the image's `VALKEY_EXTRA_FLAGS` hook and takes and +restores snapshots with the `valkey-cli` or `redis-cli` inside the container, which only images +built like `valkey/valkey` provide. An image that has no shell and no CLI, such as a distroless +Redis-compatible image, needs the other path, which is selected by +`floci.services.elasticache.shell-less-backend` (`FLOCI_SERVICES_ELASTICACHE_SHELL_LESS_BACKEND`). +It is `false` by default and is never inferred from the image name, so which path runs is always the +one you configured. MemoryDB is not affected by it. + +With `shell-less-backend` set to `true`: + +- The server flags are passed as container arguments (`--port 6379 --protected-mode no + --loglevel verbose`, plus the cluster-mode flags for a cluster-mode group) instead of the + `VALKEY_EXTRA_FLAGS` environment variable. The image's own default arguments are replaced by + these, and the image must accept them. +- `CreateSnapshot` runs `SAVE`, reads `CONFIG GET dir` and `CONFIG GET dbfilename` over the RESP + connection to the backend, and copies the file out of the container through the Docker archive + API. No command is executed inside the container. +- `CreateReplicationGroup` with `SnapshotName` places the snapshot file in the container's data + directory (the image's working directory, which is where a server started without `--dir` keeps + its data) before the server starts, so the server loads it itself. No `DEBUG` command is used and + `--enable-debug-command` is not passed. If the file cannot be placed, or the server cannot start + with it, the new group's container is removed and the create fails with `InvalidSnapshotState`; + the group the snapshot came from and the snapshot are not touched. +- `floci.services.elasticache.shell-less-backend-dbfilename` + (`FLOCI_SERVICES_ELASTICACHE_SHELL_LESS_BACKEND_DBFILENAME`, default `dump.rdb`) names the file + the server loads from its data directory at startup. A restore places the snapshot under this + name, and a snapshot falls back to it when the server does not report `dbfilename`. Set it to the + name your image's server uses. + +An image used this way has to: + +- accept the server flags above as arguments, including the cluster-mode flags + (`--cluster-enabled`, `--cluster-announce-*`) for a cluster-mode group; +- answer `SAVE`, `CONFIG GET dir` and `CONFIG GET dbfilename`, write its snapshot to a file in its + data directory and load a file of that name from there at startup (Floci checks `dir`, and + `dbfilename` when the server reports one, after a restore); +- support ACL users with access strings (`ACL SETUSER`, `AUTH`), because the proxy enforces user + groups through the backend's ACL and passes the backend's `-NOPERM` replies on to the client. + An image without ACL support works only for groups with no user group. + +The backend's port is published the way it is for the default image, so the container is reached +only through the proxy in the usual setup. A snapshot of a group that has user groups, taken once +a user has connected, is refused because Floci's own connection to the backend is not +authenticated; the default path has the same limit. + +For example, with the KiviDB image, whose server keeps its snapshot as `dump.kdb`: + +```bash +FLOCI_SERVICES_ELASTICACHE_DEFAULT_IMAGE=ghcr.io/kividbio/kividb:v1.2.2 +FLOCI_SERVICES_ELASTICACHE_SHELL_LESS_BACKEND=true +FLOCI_SERVICES_ELASTICACHE_SHELL_LESS_BACKEND_DBFILENAME=dump.kdb +``` + +A snapshot is a file in the server's own format, so it restores into a backend of the same kind: +do not restore a snapshot taken from one engine into another. + ## Configuration | Variable | Default | Description | @@ -403,6 +463,8 @@ Memcached uses the separate `floci.services.elasticache.default-memcached-image` | `FLOCI_SERVICES_ELASTICACHE_PROXY_BASE_PORT` | `6379` | First host port in the ElastiCache proxy range | | `FLOCI_SERVICES_ELASTICACHE_PROXY_MAX_PORT` | `6399` | Last host port in the ElastiCache proxy range | | `FLOCI_SERVICES_ELASTICACHE_DEFAULT_IMAGE` | `valkey/valkey:8` | Docker image for Redis/Valkey containers | +| `FLOCI_SERVICES_ELASTICACHE_SHELL_LESS_BACKEND` | `false` | Start and snapshot the backend for an image with no shell or CLI: [see above](#images-with-no-shell-or-cli) | +| `FLOCI_SERVICES_ELASTICACHE_SHELL_LESS_BACKEND_DBFILENAME` | `dump.rdb` | Snapshot file name the server loads at startup, used with the setting above | ### Docker Compose diff --git a/src/main/java/io/floci/aws/config/EmulatorConfig.java b/src/main/java/io/floci/aws/config/EmulatorConfig.java index c6d9bf7a2d..38b303be60 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -1842,6 +1842,27 @@ public interface EmulatorConfig { @WithDefault("memcached:1.6") String defaultMemcachedImage(); + /** + * Start and snapshot the backend of a Redis or Valkey replication group the way an image + * with no shell and no CLI needs: server flags go to the container as arguments instead of + * the {@code VALKEY_EXTRA_FLAGS} hook, a snapshot is taken with {@code SAVE} over the RESP + * connection and read out of the container through the Docker archive API, and a snapshot + * is restored by placing its file in the data directory before the server starts, so no + * {@code DEBUG} command is involved. Off by default and never inferred from the image name: + * the default image keeps the {@code VALKEY_EXTRA_FLAGS} and CLI path. + */ + @WithDefault("false") + boolean shellLessBackend(); + + /** + * Name of the snapshot file the server loads from its data directory at startup. Only used + * with {@link #shellLessBackend()}: a restore places the snapshot under this name, and a + * snapshot export falls back to it when the server does not report {@code dbfilename}. + * Set it to the name the image's server uses ({@code dump.rdb} for Redis and Valkey). + */ + @WithDefault("dump.rdb") + String shellLessBackendDbfilename(); + /** Docker network to attach ElastiCache containers to. Empty = default bridge. */ Optional dockerNetwork(); diff --git a/src/main/java/io/floci/aws/core/common/docker/ContainerLifecycleManager.java b/src/main/java/io/floci/aws/core/common/docker/ContainerLifecycleManager.java index 979487f625..ccb05f7f90 100644 --- a/src/main/java/io/floci/aws/core/common/docker/ContainerLifecycleManager.java +++ b/src/main/java/io/floci/aws/core/common/docker/ContainerLifecycleManager.java @@ -57,6 +57,7 @@ import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; import java.util.regex.Pattern; /** @@ -148,6 +149,16 @@ public class ContainerLifecycleManager { return createAndStart(spec, platform, false); } + /** + * Creates a container, runs {@code beforeStart} against its id, then starts it, for a launch + * that must put files into the container before the process inside it runs. The container is + * removed again if the setup or the start fails. + */ + public ContainerInfo createAndStart(ContainerSpec spec, Consumer beforeStart) { + String resolvedImage = imageCacheService.ensureImageExists(spec.image()); + return createAndStart(spec, resolvedImage, null, false, beforeStart); + } + /** Starts a disposable container, reclaiming its anonymous volumes if startup fails. */ public ContainerInfo createAndStartEphemeral(ContainerSpec spec) { return createAndStart(spec, true); @@ -165,18 +176,21 @@ public class ContainerLifecycleManager { private ContainerInfo createAndStart(ContainerSpec spec, boolean removeAnonymousVolumes) { String resolvedImage = imageCacheService.ensureImageExists(spec.image()); - return createAndStart(spec, resolvedImage, null, removeAnonymousVolumes); + return createAndStart(spec, resolvedImage, null, removeAnonymousVolumes, null); } private ContainerInfo createAndStart(ContainerSpec spec, String platform, boolean removeAnonymousVolumes) { String resolvedImage = imageCacheService.ensureImageExists(spec.image(), platform); - return createAndStart(spec, resolvedImage, platform, removeAnonymousVolumes); + return createAndStart(spec, resolvedImage, platform, removeAnonymousVolumes, null); } private ContainerInfo createAndStart(ContainerSpec spec, String resolvedImage, String platform, - boolean removeAnonymousVolumes) { + boolean removeAnonymousVolumes, Consumer beforeStart) { String containerId = create(spec, resolvedImage, platform, removeAnonymousVolumes); try { + if (beforeStart != null) { + beforeStart.accept(containerId); + } return withPublishedHostPorts(startCreated(containerId, spec), spec); } catch (RuntimeException failure) { removeFailedContainer(containerId, failure, removeAnonymousVolumes); diff --git a/src/main/java/io/floci/aws/services/elasticache/ElastiCacheService.java b/src/main/java/io/floci/aws/services/elasticache/ElastiCacheService.java index 461b96b208..c73731122c 100644 --- a/src/main/java/io/floci/aws/services/elasticache/ElastiCacheService.java +++ b/src/main/java/io/floci/aws/services/elasticache/ElastiCacheService.java @@ -419,8 +419,20 @@ public class ElastiCacheService implements ResourceProvider { // derived from configuration and need no Docker, so the group is created and reaches // 'available' even when no daemon is reachable. Only connecting to the cache needs // the container. - handle = containerManager.tryStart(groupId, image, request.region()); - if (seed != null) { + // With the shell-less backend the snapshot is placed in the data directory before the + // server starts; otherwise it is loaded into the running server below. + String startupSeed = seed != null && containerManager.isShellLessBackend() ? seed.rdbBase64() : null; + try { + handle = startupSeed == null + ? containerManager.tryStart(groupId, image, request.region()) + : containerManager.tryStart(groupId, image, request.region(), startupSeed); + } catch (ElastiCacheContainerManager.SnapshotRestoreException e) { + LOG.warnv(e, "Failed to restore snapshot {0} into replication group {1}", + seed.snapshotName(), groupId); + throw new AwsException("InvalidSnapshotState", "Failed to restore snapshot " + seed.snapshotName() + + " into replication group " + groupId + ": " + e.getMessage(), 400); + } + if (seed != null && (startupSeed == null || handle == null)) { loadSnapshot(groupId, handle, seed); } diff --git a/src/main/java/io/floci/aws/services/elasticache/container/ElastiCacheContainerManager.java b/src/main/java/io/floci/aws/services/elasticache/container/ElastiCacheContainerManager.java index a57bdc3619..d6a80e6bb0 100644 --- a/src/main/java/io/floci/aws/services/elasticache/container/ElastiCacheContainerManager.java +++ b/src/main/java/io/floci/aws/services/elasticache/container/ElastiCacheContainerManager.java @@ -1,5 +1,6 @@ package io.floci.aws.services.elasticache.container; +import com.github.dockerjava.api.DockerClient; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.docker.ContainerBuilder; @@ -8,16 +9,20 @@ import io.floci.aws.core.common.docker.ContainerExec; import io.floci.aws.core.common.docker.ContainerLifecycleManager; import io.floci.aws.core.common.docker.ContainerLifecycleManager.ContainerInfo; import io.floci.aws.core.common.docker.ContainerLifecycleManager.EndpointInfo; +import io.floci.aws.core.common.docker.ContainerLiveness; 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 jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; +import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.jboss.logging.Logger; import java.io.Closeable; import java.io.IOException; +import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; @@ -27,6 +32,7 @@ import java.util.Base64; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import java.util.function.BooleanSupplier; /** * Manages backend Docker container lifecycle for ElastiCache replication groups. @@ -38,6 +44,7 @@ public class ElastiCacheContainerManager { private static final Logger LOG = Logger.getLogger(ElastiCacheContainerManager.class); private static final int BACKEND_PORT = 6379; + private static final int SNAPSHOT_SAVE_TIMEOUT_MS = 300_000; /** * Docker can publish a host port before Valkey inside the container is listening. Without a probe, @@ -83,8 +90,17 @@ public class ElastiCacheContainerManager { * container was created */ public ElastiCacheContainerHandle tryStart(String groupId, String image, String region) { + return tryStart(groupId, image, region, null); + } + + /** + * {@link #tryStart(String, String, String)} for a backend that starts from a snapshot: see + * {@link #start(String, String, List, String, String)} for {@code seedRdbBase64}. + */ + public ElastiCacheContainerHandle tryStart(String groupId, String image, String region, + String seedRdbBase64) { try { - ElastiCacheContainerHandle handle = start(groupId, image, region); + ElastiCacheContainerHandle handle = start(groupId, image, List.of(), region, seedRdbBase64); dockerUnavailableLogged = false; return handle; } catch (RuntimeException e) { @@ -132,30 +148,63 @@ public class ElastiCacheContainerManager { */ public ElastiCacheContainerHandle start(String groupId, String image, List extraServerFlags, String region) { + return start(groupId, image, extraServerFlags, region, null); + } + + /** Whether backends start and snapshot the way an image with no shell or CLI needs. */ + public boolean isShellLessBackend() { + return config.services().elasticache().shellLessBackend(); + } + + /** + * {@link #start(String, String, List, String)} that also loads a snapshot at startup, for the + * shell-less path only: the RDB file is placed in the container's data directory before the + * server process starts, so it loads the dataset itself and no {@code DEBUG} command is needed. + * A container that cannot be seeded is removed and reported as a {@link SnapshotRestoreException}. + * + * @param seedRdbBase64 a {@link #snapshot} archive to start from, or {@code null} for an empty cache + */ + public ElastiCacheContainerHandle start(String groupId, String image, List extraServerFlags, + String region, String seedRdbBase64) { LOG.infov("Starting ElastiCache backend container for group: {0}", groupId); + boolean shellLess = isShellLessBackend(); + if (seedRdbBase64 != null && !shellLess) { + throw new IllegalArgumentException( + "A snapshot is loaded at startup only with floci.services.elasticache.shell-less-backend"); + } String containerName = containerName(groupId); // Remove any stale container with the same name lifecycleManager.removeIfExists(containerName); - // DEBUG is enabled for connections from inside the container only, so a snapshot restore - // can reload the dataset (DEBUG RELOAD NOSAVE); clients reach the server through the proxy. - StringBuilder serverFlags = new StringBuilder("--loglevel verbose --enable-debug-command local"); - for (String flag : extraServerFlags) { - serverFlags.append(' ').append(flag); - } - // Build container spec. Only publish the backend port to the host in // native mode — in Docker mode the JVM reaches the container via its // network IP, no host binding needed. ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image) .withName(containerName) - .withEnv("VALKEY_EXTRA_FLAGS", serverFlags.toString()) .withDockerNetwork(config.services().elasticache().dockerNetwork()) .withLogRotation() .withLabels(ContainerStorageHelper.resourceIdentityLabels( "elasticache", groupId, regionResolver.getAccountId(), region)); + if (shellLess) { + // The server flags are the container's arguments, after the image's own entrypoint. + // Replacing the image's default arguments drops whatever they set, so the listening + // port and protected mode, which the proxy and the readiness probe rely on, are + // stated here. DEBUG is not enabled: a snapshot is restored by file, before start. + List arguments = new ArrayList<>(List.of("--port", String.valueOf(BACKEND_PORT), + "--protected-mode", "no", "--loglevel", "verbose")); + arguments.addAll(extraServerFlags); + specBuilder.withCmd(arguments); + } else { + // DEBUG is enabled for connections from inside the container only, so a snapshot restore + // can reload the dataset (DEBUG RELOAD NOSAVE); clients reach the server through the proxy. + StringBuilder serverFlags = new StringBuilder("--loglevel verbose --enable-debug-command local"); + for (String flag : extraServerFlags) { + serverFlags.append(' ').append(flag); + } + specBuilder.withEnv("VALKEY_EXTRA_FLAGS", serverFlags.toString()); + } if (!containerDetector.isRunningInContainer()) { specBuilder.withDynamicPort(BACKEND_PORT); @@ -166,7 +215,15 @@ public class ElastiCacheContainerManager { ContainerSpec spec = specBuilder.build(); // Create and start container - ContainerInfo info = lifecycleManager.createAndStart(spec); + String seededDirectory = null; + ContainerInfo info; + if (seedRdbBase64 == null) { + info = lifecycleManager.createAndStart(spec); + } else { + String[] placedIn = new String[1]; + info = lifecycleManager.createAndStart(spec, id -> placedIn[0] = placeSnapshot(id, seedRdbBase64)); + seededDirectory = placedIn[0]; + } EndpointInfo endpoint = info.getEndpoint(BACKEND_PORT); LOG.infov("ElastiCache backend for group {0}: {1}", groupId, endpoint); @@ -193,12 +250,96 @@ public class ElastiCacheContainerManager { info.containerId(), logGroup, logStream, region, "elasticache:" + groupId); handle.setLogStream(logHandle); - waitForBackendReady(groupId, endpoint.host(), endpoint.port()); + if (seededDirectory == null) { + waitForBackendReady(groupId, endpoint.host(), endpoint.port(), () -> false); + } else { + // A server that cannot load the snapshot exits instead of starting empty; noticing that + // saves waiting out the whole readiness deadline. + try { + waitForBackendReady(groupId, endpoint.host(), endpoint.port(), + () -> lifecycleManager.probeContainer(info.containerId()) == ContainerLiveness.NOT_RUNNING); + } catch (RuntimeException e) { + throw new SnapshotRestoreException("the backend did not become ready with the snapshot in " + + "place: " + e.getMessage(), e); + } + verifySnapshotDirectory(endpoint.host(), endpoint.port(), seededDirectory, + config.services().elasticache().shellLessBackendDbfilename()); + } return handle; } - private static void waitForBackendReady(String groupId, String host, int port) { + /** A snapshot that could not be placed in, or loaded by, a starting backend. */ + public static class SnapshotRestoreException extends RuntimeException { + public SnapshotRestoreException(String message, Throwable cause) { + super(message, cause); + } + + public SnapshotRestoreException(String message) { + super(message); + } + } + + /** + * Puts the snapshot into the data directory of a created, not yet started container, under the + * file name the server loads at startup. The data directory is the one a server started without + * {@code --dir} uses, the image's working directory. + * + * @return the directory the file was placed in + */ + private String placeSnapshot(String containerId, String rdbBase64) { + try { + byte[] rdb = Base64.getDecoder().decode(rdbBase64); + DockerClient docker = lifecycleManager.getDockerClient(); + String workingDir = docker.inspectContainerCmd(containerId).exec().getConfig().getWorkingDir(); + String directory = workingDir == null || workingDir.isBlank() ? "/" : workingDir; + RetryingTarCopier.copyBytes(docker, containerId, directory, + config.services().elasticache().shellLessBackendDbfilename(), rdb, 0644); + return directory; + } catch (RuntimeException e) { + throw new SnapshotRestoreException("could not place the snapshot in the backend's data directory: " + + e.getMessage(), e); + } + } + + /** + * Checks over RESP that the running server uses the directory and file name the snapshot was placed + * under, since a server that reads another file would start empty and the restore would look + * successful. + */ + private static void verifySnapshotDirectory(String host, int port, String placedIn, + String placedFileName) { + try (ValkeyClusterFormation.RespClient client = new ValkeyClusterFormation.RespClient(host, port)) { + String directory = configValue(client, "dir"); + if (directory == null || !directory.equals(placedIn)) { + throw new SnapshotRestoreException("the backend's data directory is " + directory + + ", not " + placedIn + " where the snapshot was placed"); + } + // A server that reports another snapshot file name loads that one and starts empty. + String fileName = configValue(client, "dbfilename"); + String placedAs = placedFileName; + if (fileName != null && !fileName.isBlank() && !fileName.equals(placedAs)) { + throw new SnapshotRestoreException("the backend loads its snapshot from " + fileName + + ", not " + placedAs + " where the snapshot was placed; set " + + "floci.services.elasticache.shell-less-backend-dbfilename to " + fileName); + } + } catch (IOException e) { + throw new SnapshotRestoreException("could not confirm the backend's data directory: " + + e.getMessage(), e); + } + } + + private static String configValue(ValkeyClusterFormation.RespClient client, String parameter) + throws IOException { + Object reply = client.call("CONFIG", "GET", parameter); + if (reply instanceof List items && items.size() >= 2 && items.get(1) != null) { + return items.get(1).toString(); + } + return null; + } + + private static void waitForBackendReady(String groupId, String host, int port, + BooleanSupplier backendExited) { long deadline = System.currentTimeMillis() + BACKEND_READY_DEADLINE_MS; int attempt = 0; while (System.currentTimeMillis() < deadline) { @@ -225,6 +366,9 @@ public class ElastiCacheContainerManager { LOG.debugv("ElastiCache backend probe for group {0} attempt {1}: {2}", groupId, attempt, e.getMessage()); } } + if (backendExited.getAsBoolean()) { + throw new RuntimeException("ElastiCache backend for group " + groupId + " exited before it was ready"); + } try { Thread.sleep(BACKEND_READY_RETRY_MS); } catch (InterruptedException ie) { @@ -247,6 +391,9 @@ public class ElastiCacheContainerManager { * RDB file. */ public String snapshot(String containerId) { + if (isShellLessBackend()) { + return snapshotWithoutShell(containerId); + } String[] cmd = {"sh", "-c", CLI + "R=$($C SAVE); if [ \"$R\" != OK ]; then echo \"SAVE: $R\" >&2; exit 1; fi;" + " base64 -w0 \"$($C CONFIG GET dir | sed -n 2p)/$($C CONFIG GET dbfilename | sed -n 2p)\""}; ContainerExec.Result result = ContainerExec.run(lifecycleManager.getDockerClient(), containerId, cmd, 300); @@ -256,6 +403,52 @@ public class ElastiCacheContainerManager { return result.stdout().trim(); } + /** + * {@link #snapshot} for a backend with no shell or CLI: {@code SAVE} and the server's + * {@code dir} and {@code dbfilename} are asked over a RESP connection, and the file is read + * out of the container through the Docker archive API. + */ + private String snapshotWithoutShell(String containerId) { + ElastiCacheContainerHandle handle = activeContainers.values().stream() + .filter(h -> containerId.equals(h.getContainerId())) + .findFirst() + .orElseThrow(() -> new IllegalStateException("no running backend for container " + containerId)); + String directory; + String fileName; + try (ValkeyClusterFormation.RespClient client = new ValkeyClusterFormation.RespClient( + handle.getHost(), handle.getPort(), SNAPSHOT_SAVE_TIMEOUT_MS)) { + Object reply = client.call("SAVE"); + if (!"OK".equals(reply)) { + throw new IllegalStateException("SAVE: " + reply); + } + directory = configValue(client, "dir"); + fileName = configValue(client, "dbfilename"); + } catch (IOException e) { + throw new IllegalStateException("SAVE failed: " + e.getMessage(), e); + } + if (directory == null || directory.isBlank()) { + throw new IllegalStateException("the backend did not report its data directory"); + } + if (fileName == null || fileName.isBlank()) { + fileName = config.services().elasticache().shellLessBackendDbfilename(); + } + String path = directory.endsWith("/") ? directory + fileName : directory + "/" + fileName; + try (InputStream tar = lifecycleManager.getDockerClient() + .copyArchiveFromContainerCmd(containerId, path).exec(); + TarArchiveInputStream entries = new TarArchiveInputStream(tar)) { + TarArchiveEntry entry = entries.getNextEntry(); + while (entry != null && !entry.isFile()) { + entry = entries.getNextEntry(); + } + if (entry == null) { + throw new IllegalStateException("the snapshot file " + path + " is not in the backend"); + } + return Base64.getEncoder().encodeToString(entries.readAllBytes()); + } catch (IOException e) { + throw new IllegalStateException("could not read the snapshot file " + path + ": " + e.getMessage(), e); + } + } + /** Replaces the dataset with a {@link #snapshot} RDB file and reloads it without saving first. */ public void restore(String containerId, String rdbBase64) { byte[] rdb = Base64.getDecoder().decode(rdbBase64); diff --git a/src/main/java/io/floci/aws/services/elasticache/container/ValkeyClusterFormation.java b/src/main/java/io/floci/aws/services/elasticache/container/ValkeyClusterFormation.java index 23866d1072..4b4d4dc5dc 100644 --- a/src/main/java/io/floci/aws/services/elasticache/container/ValkeyClusterFormation.java +++ b/src/main/java/io/floci/aws/services/elasticache/container/ValkeyClusterFormation.java @@ -205,10 +205,14 @@ public class ValkeyClusterFormation { private final OutputStream out; RespClient(String host, int port) throws IOException { + this(host, port, READ_TIMEOUT_MS); + } + + RespClient(String host, int port, int readTimeoutMs) throws IOException { socket = new Socket(); socket.connect(new InetSocketAddress(host, port), CONNECT_TIMEOUT_MS); socket.setTcpNoDelay(true); - socket.setSoTimeout(READ_TIMEOUT_MS); + socket.setSoTimeout(readTimeoutMs); in = socket.getInputStream(); out = socket.getOutputStream(); } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 4cff82d8c0..2b990e545c 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -567,6 +567,7 @@ floci: proxy-max-port: 6399 default-image: "valkey/valkey:8" default-memcached-image: "memcached:1.6" + shell-less-backend: false memorydb: enabled: true mock: false diff --git a/src/test/java/io/floci/aws/services/elasticache/ElastiCacheShellLessBackendIntegrationTest.java b/src/test/java/io/floci/aws/services/elasticache/ElastiCacheShellLessBackendIntegrationTest.java new file mode 100644 index 0000000000..0b73b67508 --- /dev/null +++ b/src/test/java/io/floci/aws/services/elasticache/ElastiCacheShellLessBackendIntegrationTest.java @@ -0,0 +1,343 @@ +package io.floci.aws.services.elasticache; + +import io.floci.aws.services.elasticache.container.ElastiCacheContainerManager; +import io.floci.aws.testing.DockerAvailability; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.specification.RequestSpecification; +import jakarta.enterprise.inject.spi.CDI; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.Socket; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import static io.floci.aws.services.elasticache.ElastiCacheTestConnections.bulk; +import static io.floci.aws.services.elasticache.ElastiCacheTestConnections.command; +import static io.floci.aws.services.elasticache.ElastiCacheTestConnections.containerOf; +import static io.floci.aws.services.elasticache.ElastiCacheTestConnections.docker; +import static io.floci.aws.services.elasticache.ElastiCacheTestConnections.dockerExit; +import static io.restassured.RestAssured.given; +import static org.awaitility.Awaitility.await; +import static org.hamcrest.Matchers.equalTo; +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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The shell-less ElastiCache backend ({@code floci.services.elasticache.shell-less-backend}) against + * a real image with no shell and no CLI, pinned by digest in {@link ShellLessBackendProfile}: server + * flags as container arguments, snapshot export over RESP and the Docker archive API, restore by + * placing the file before the server starts, authentication and ACLs through the proxy, and cleanup + * of the containers on delete and on a failed restore. + */ +@QuarkusTest +@TestProfile(ShellLessBackendProfile.class) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class ElastiCacheShellLessBackendIntegrationTest { + + private static final String AUTH_HEADER = + "AWS4-HMAC-SHA256 Credential=test/20260412/us-east-1/elasticache/aws4_request"; + private static final String SOURCE_ID = "it-sl-source"; + private static final String RESTORED_ID = "it-sl-restored"; + private static final String TOKEN_ID = "it-sl-token"; + private static final String RBAC_ID = "it-sl-rbac"; + private static final String BAD_SEED_ID = "it-sl-bad-seed"; + private static final String SNAPSHOT_NAME = "it-sl-snap"; + private static final String TOKEN = "shell-less-group-token"; + private static final String DEFAULT_USER_ID = "it-sl-default-user"; + private static final String APP_USER_ID = "it-sl-app-user"; + private static final String APP_USER_NAME = "it-sl-app"; + private static final String APP_PASSWORD = "app-secret-123456"; + private static final int SOCKET_TIMEOUT_MS = 10_000; + + @TestHTTPResource("/") + static URI baseUri; + + private static int sourcePort; + private static int restoredPort; + + @BeforeAll + static void requireDocker() throws InterruptedException { + Assumptions.assumeTrue(DockerAvailability.isAvailable(), + "Docker daemon must be available for ElastiCache integration tests"); + } + + @AfterAll + static void cleanup() { + for (String groupId : List.of(RBAC_ID, TOKEN_ID, RESTORED_ID, SOURCE_ID)) { + try { + request("DeleteReplicationGroup").port(baseUri.getPort()).formParam("ReplicationGroupId", groupId).post("/"); + } catch (RuntimeException expected) { + // Best effort: the group may not exist when a test failed before creating it. + } + } + for (String userId : List.of(APP_USER_ID, DEFAULT_USER_ID)) { + try { + request("DeleteUser").port(baseUri.getPort()).formParam("UserId", userId).post("/"); + } catch (RuntimeException expected) { + // Best effort, as above. + } + } + try { + request("DeleteSnapshot").port(baseUri.getPort()).formParam("SnapshotName", SNAPSHOT_NAME).post("/"); + } catch (RuntimeException expected) { + // Best effort, as above. + } + try { + CDI.current().select(ElastiCacheContainerManager.class).get().stopByGroupId(BAD_SEED_ID); + } catch (RuntimeException expected) { + // Best effort, as above. + } + } + + @Test + @Order(1) + void createGroupOnAnImageWithNoShell() { + sourcePort = createGroup(SOURCE_ID, null, null); + } + + @Test + @Order(2) + void theImageReallyHasNoShell() throws Exception { + String container = containerOf(SOURCE_ID); + assertFalse(container.isEmpty(), "the backend container exists"); + assertNotEquals(0, dockerExit("exec", container, "sh", "-c", "true"), + "the fixture image must have no shell, or the test proves nothing"); + } + + @Test + @Order(3) + void serverFlagsAreDeliveredAsContainerArguments() throws Exception { + String container = containerOf(SOURCE_ID); + String command = docker("inspect", "--format", "{{json .Config.Cmd}}", container); + assertTrue(command.contains("\"--port\",\"6379\""), command); + assertTrue(command.contains("\"--protected-mode\",\"no\""), command); + assertFalse(command.contains("enable-debug-command"), "DEBUG is not enabled anywhere: " + command); + String environment = docker("inspect", "--format", "{{json .Config.Env}}", container); + assertFalse(environment.contains("VALKEY_EXTRA_FLAGS"), environment); + } + + @Test + @Order(4) + void dataIsServedThroughTheProxy() throws Exception { + try (Socket socket = open(sourcePort)) { + assertEquals("+OK", command(socket, "SET", "snapshot-key", "kept")); + assertEquals("kept", bulk(socket, "GET", "snapshot-key")); + } + } + + @Test + @Order(5) + void snapshotIsExportedAndRestoredBeforeTheServerStarts() throws Exception { + request("CreateSnapshot") + .formParam("SnapshotName", SNAPSHOT_NAME) + .formParam("ReplicationGroupId", SOURCE_ID) + .when() + .post("/") + .then() + .statusCode(200) + .body("CreateSnapshotResponse.CreateSnapshotResult.Snapshot.SnapshotStatus", equalTo("available")); + // Written after the snapshot: the restored group must not see it. + try (Socket socket = open(sourcePort)) { + assertEquals("+OK", command(socket, "SET", "later-key", "after")); + } + + restoredPort = createGroup(RESTORED_ID, SNAPSHOT_NAME, null); + + try (Socket socket = open(restoredPort)) { + assertEquals("kept", bulk(socket, "GET", "snapshot-key")); + assertEquals("$-1", command(socket, "GET", "later-key")); + } + String command = docker("inspect", "--format", "{{json .Config.Cmd}}", containerOf(RESTORED_ID)); + assertFalse(command.contains("enable-debug-command"), "no DEBUG for a restore: " + command); + } + + @Test + @Order(6) + void theSourceKeepsItsDataAndItsSnapshotSurvivesTheRestore() throws Exception { + try (Socket socket = open(sourcePort)) { + assertEquals("after", bulk(socket, "GET", "later-key")); + } + request("DescribeSnapshots") + .formParam("SnapshotName", SNAPSHOT_NAME) + .when() + .post("/") + .then() + .statusCode(200) + .body("DescribeSnapshotsResponse.DescribeSnapshotsResult.Snapshots.Snapshot.SnapshotStatus", + equalTo("available")); + } + + @Test + @Order(7) + void groupAuthTokenIsEnforcedByTheProxy() throws Exception { + int port = createGroup(TOKEN_ID, null, TOKEN); + try (Socket socket = open(port)) { + assertTrue(command(socket, "PING").startsWith("-NOAUTH")); + } + try (Socket socket = open(port)) { + assertEquals("-ERR invalid username-password pair or user is disabled.", + command(socket, "AUTH", "wrong-token")); + } + try (Socket socket = open(port)) { + assertEquals("+OK", command(socket, "AUTH", TOKEN)); + assertEquals("+PONG", command(socket, "PING")); + assertEquals("+OK", command(socket, "SET", "token-key", "value")); + } + } + + @Test + @Order(8) + void commandsAnAccessStringRefusesAreRefusedAndTheRefusalReachesTheClient() throws Exception { + int port = createGroup(RBAC_ID, null, null); + createUser(DEFAULT_USER_ID, "default", "no-password-required", null, "on ~* +@all"); + createUser(APP_USER_ID, APP_USER_NAME, "password", APP_PASSWORD, "on ~app:* -@all +get +set +ping"); + request("ModifyReplicationGroup") + .formParam("ReplicationGroupId", RBAC_ID) + .formParam("UserGroupIdsToAdd.member.1", DEFAULT_USER_ID) + .formParam("UserGroupIdsToAdd.member.2", APP_USER_ID) + .when() + .post("/") + .then() + .statusCode(200); + + try (Socket socket = open(port)) { + assertEquals("-ERR invalid username-password pair or user is disabled.", + command(socket, "AUTH", APP_USER_NAME, "wrong-password")); + } + try (Socket socket = open(port)) { + assertEquals("+OK", command(socket, "AUTH", APP_USER_NAME, APP_PASSWORD)); + assertEquals("+OK", command(socket, "SET", "app:key", "allowed")); + assertEquals("allowed", bulk(socket, "GET", "app:key")); + String otherKey = command(socket, "SET", "other:key", "refused"); + assertTrue(otherKey.startsWith("-NOPERM"), otherKey); + String flush = command(socket, "FLUSHALL"); + assertTrue(flush.startsWith("-NOPERM"), flush); + assertEquals("allowed", bulk(socket, "GET", "app:key")); + } + // Floci's own connection to the backend is not authenticated, so once the proxy has set up + // the backend's ACL a snapshot is refused rather than hanging or returning stale data. + request("CreateSnapshot") + .formParam("SnapshotName", "it-sl-acl-snap") + .formParam("ReplicationGroupId", RBAC_ID) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("InvalidReplicationGroupState")); + } + + @Test + @Order(9) + void aSnapshotTheServerCannotLoadFailsTheStartAndLeavesNoContainer() throws Exception { + ElastiCacheContainerManager manager = CDI.current().select(ElastiCacheContainerManager.class).get(); + String garbage = Base64.getEncoder().encodeToString("not a snapshot".getBytes(StandardCharsets.UTF_8)); + + assertThrows(ElastiCacheContainerManager.SnapshotRestoreException.class, () -> + manager.start(BAD_SEED_ID, ShellLessBackendProfile.IMAGE, List.of(), "us-east-1", garbage)); + // The caller cleans up as the service's rollback does; the failed container is not left behind. + manager.stopByGroupId(BAD_SEED_ID); + assertEquals("", containerOf(BAD_SEED_ID)); + + // The failure touched neither the cluster the snapshot came from nor the snapshot itself. + try (Socket socket = open(sourcePort)) { + assertEquals("after", bulk(socket, "GET", "later-key")); + } + request("DescribeSnapshots") + .formParam("SnapshotName", SNAPSHOT_NAME) + .when() + .post("/") + .then() + .statusCode(200) + .body("DescribeSnapshotsResponse.DescribeSnapshotsResult.Snapshots.Snapshot.SnapshotStatus", + equalTo("available")); + } + + @Test + @Order(10) + void deletingTheGroupsRemovesTheirContainers() throws Exception { + for (String groupId : List.of(RBAC_ID, TOKEN_ID, RESTORED_ID, SOURCE_ID)) { + assertFalse(containerOf(groupId).isEmpty(), groupId + " has a container before the delete"); + request("DeleteReplicationGroup") + .formParam("ReplicationGroupId", groupId) + .when() + .post("/") + .then() + .statusCode(200); + await().atMost(60, TimeUnit.SECONDS).untilAsserted(() -> + assertEquals("", containerOf(groupId), groupId + " container is removed")); + } + request("DeleteSnapshot") + .formParam("SnapshotName", SNAPSHOT_NAME) + .when() + .post("/") + .then() + .statusCode(200); + for (String userId : List.of(APP_USER_ID, DEFAULT_USER_ID)) { + request("DeleteUser").formParam("UserId", userId).post("/").then().statusCode(200); + } + } + + // ── helpers ────────────────────────────────────────────────────────────── + + private static RequestSpecification request(String action) { + return given().formParam("Action", action).header("Authorization", AUTH_HEADER); + } + + private static int createGroup(String groupId, String snapshotName, String authToken) { + RequestSpecification request = request("CreateReplicationGroup") + .formParam("ReplicationGroupId", groupId) + .formParam("ReplicationGroupDescription", "shell-less backend"); + if (snapshotName != null) { + request = request.formParam("SnapshotName", snapshotName); + } + if (authToken != null) { + request = request.formParam("AuthToken", authToken); + } + return request + .when() + .post("/") + .then() + .statusCode(200) + .extract() + .xmlPath() + .getInt("CreateReplicationGroupResponse.CreateReplicationGroupResult.ReplicationGroup" + + ".NodeGroups.NodeGroup.PrimaryEndpoint.Port"); + } + + private static void createUser(String userId, String userName, String authType, String password, + String accessString) { + RequestSpecification request = request("CreateUser") + .formParam("UserId", userId) + .formParam("UserName", userName) + .formParam("AuthenticationMode.Type", authType) + .formParam("AccessString", accessString); + if (password != null) { + request = request.formParam("AuthenticationMode.Passwords.member.1", password); + } + request.when().post("/").then().statusCode(200); + } + + private static Socket open(int port) throws IOException { + Socket socket = ElastiCacheTestConnections.openSocket("localhost", port); + socket.setSoTimeout(SOCKET_TIMEOUT_MS); + return socket; + } +} diff --git a/src/test/java/io/floci/aws/services/elasticache/ElastiCacheShellLessClusterIntegrationTest.java b/src/test/java/io/floci/aws/services/elasticache/ElastiCacheShellLessClusterIntegrationTest.java new file mode 100644 index 0000000000..4347b1961a --- /dev/null +++ b/src/test/java/io/floci/aws/services/elasticache/ElastiCacheShellLessClusterIntegrationTest.java @@ -0,0 +1,138 @@ +package io.floci.aws.services.elasticache; + +import io.floci.aws.testing.DockerAvailability; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import java.io.IOException; +import java.io.InputStream; +import java.net.Socket; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import static io.floci.aws.services.elasticache.ElastiCacheTestConnections.command; +import static io.floci.aws.services.elasticache.ElastiCacheTestConnections.containerOf; +import static io.floci.aws.services.elasticache.ElastiCacheTestConnections.docker; +import static io.restassured.RestAssured.given; +import static org.awaitility.Awaitility.await; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Cluster-mode flags reach the nodes as container arguments with the shell-less backend, and the + * cluster forms and serves from them. Key slots: {@code bar} is 5061, the first of two shards, and + * {@code foo} is 12182, the second. + */ +@QuarkusTest +@TestProfile(ShellLessClusterProfile.class) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class ElastiCacheShellLessClusterIntegrationTest { + + private static final String AUTH_HEADER = + "AWS4-HMAC-SHA256 Credential=test/20260412/us-east-1/elasticache/aws4_request"; + private static final String GROUP_ID = "it-sl-cluster"; + private static final List NODES = List.of(GROUP_ID + "-0001-001", GROUP_ID + "-0002-001"); + + @TestHTTPResource("/") + static URI baseUri; + + private static int configurationEndpointPort; + + @BeforeAll + static void requireDocker() throws InterruptedException { + Assumptions.assumeTrue(DockerAvailability.isAvailable(), + "Docker daemon must be available for ElastiCache integration tests"); + } + + @AfterAll + static void cleanup() { + try { + given().port(baseUri.getPort()) + .formParam("Action", "DeleteReplicationGroup") + .formParam("ReplicationGroupId", GROUP_ID) + .header("Authorization", AUTH_HEADER) + .post("/"); + } catch (RuntimeException expected) { + // Best effort: the group is already gone when the delete test ran. + } + } + + @Test + @Order(1) + void createClusterModeGroup() { + configurationEndpointPort = given() + .formParam("Action", "CreateReplicationGroup") + .formParam("ReplicationGroupId", GROUP_ID) + .formParam("ReplicationGroupDescription", "shell-less cluster mode") + .formParam("NumNodeGroups", "2") + .formParam("ReplicasPerNodeGroup", "0") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("CreateReplicationGroupResponse.CreateReplicationGroupResult.ReplicationGroup.Status", + equalTo("available")) + .body("CreateReplicationGroupResponse.CreateReplicationGroupResult.ReplicationGroup.ClusterEnabled", + equalTo("true")) + .extract() + .xmlPath() + .getInt("CreateReplicationGroupResponse.CreateReplicationGroupResult.ReplicationGroup" + + ".ConfigurationEndpoint.Port"); + } + + @Test + @Order(2) + void clusterFlagsAreContainerArgumentsOnEveryNode() throws Exception { + for (String node : NODES) { + String container = containerOf(node); + assertFalse(container.isEmpty(), node + " has a container"); + String command = docker("inspect", "--format", "{{json .Config.Cmd}}", container); + assertTrue(command.contains("\"--cluster-enabled\",\"yes\""), command); + assertTrue(command.contains("\"--cluster-announce-bus-port\",\"16379\""), command); + assertFalse(command.contains("enable-debug-command"), command); + String environment = docker("inspect", "--format", "{{json .Config.Env}}", container); + assertFalse(environment.contains("VALKEY_EXTRA_FLAGS"), environment); + } + } + + @Test + @Order(3) + void theClusterServesItsSlots() throws Exception { + try (Socket socket = new Socket("localhost", configurationEndpointPort)) { + socket.setSoTimeout(10_000); + assertEquals("+OK", command(socket, "SET", "bar", "1")); + assertTrue(command(socket, "SET", "foo", "1").startsWith("-MOVED 12182 ")); + } + } + + @Test + @Order(4) + void deletingTheGroupRemovesEveryNodeContainer() throws Exception { + given() + .formParam("Action", "DeleteReplicationGroup") + .formParam("ReplicationGroupId", GROUP_ID) + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200); + for (String node : NODES) { + await().atMost(60, TimeUnit.SECONDS).untilAsserted(() -> + assertEquals("", containerOf(node), node + " container is removed")); + } + } +} diff --git a/src/test/java/io/floci/aws/services/elasticache/ElastiCacheShellLessSnapshotServiceTest.java b/src/test/java/io/floci/aws/services/elasticache/ElastiCacheShellLessSnapshotServiceTest.java new file mode 100644 index 0000000000..e41fef8c1d --- /dev/null +++ b/src/test/java/io/floci/aws/services/elasticache/ElastiCacheShellLessSnapshotServiceTest.java @@ -0,0 +1,109 @@ +package io.floci.aws.services.elasticache; + +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.elasticache.container.ElastiCacheContainerManager; +import io.floci.aws.services.elasticache.model.AuthMode; +import io.floci.aws.services.elasticache.proxy.ElastiCacheProxyManager; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +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.Mockito.doAnswer; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * A group created from a snapshot when the backend is the shell-less one: the snapshot goes to the + * container manager with the start, so it is loaded by the server at startup and never through + * {@code restore}, and a group that cannot be started with it is rolled back without touching the + * group or the snapshot it came from. + */ +class ElastiCacheShellLessSnapshotServiceTest { + + private static final String RDB = "UkVESVMwMDEx+gl2YWxrZXktdmVyBTguMC4x/w=="; + + private ElastiCacheService service; + private ElastiCacheContainerManager containerManager; + private ElastiCacheProxyManager proxyManager; + + @BeforeEach + void setUp() { + ElastiCacheServiceFixture fixture = new ElastiCacheServiceFixture(); + service = fixture.service; + containerManager = fixture.containerManager; + proxyManager = fixture.proxyManager; + when(containerManager.isShellLessBackend()).thenReturn(true); + doAnswer(inv -> ElastiCacheServiceFixture.containerHandle(inv.getArgument(0))) + .when(containerManager).tryStart(anyString(), anyString(), any(), any()); + when(containerManager.snapshot("container-source")).thenReturn(RDB); + service.createReplicationGroup("source", "group source", AuthMode.NO_AUTH, null, "us-east-1"); + service.createSnapshot("snap", "source", null); + } + + @Test + void theSnapshotIsHandedToTheStartAndNeverRestoredIntoARunningServer() { + service.createReplicationGroupFromSnapshot(request("restored"), "snap"); + + verify(containerManager).tryStart("restored", "valkey/valkey:8", "us-east-1", RDB); + verify(containerManager, never()).restore(anyString(), anyString()); + verify(proxyManager).startProxy(eq("restored"), any(), anyInt(), anyString(), anyInt(), any()); + assertEquals("restored", service.getReplicationGroup("restored").getReplicationGroupId()); + } + + @Test + void aGroupWithoutASnapshotStartsWithoutOne() { + service.createReplicationGroup("plain", "group plain", AuthMode.NO_AUTH, null, "us-east-1"); + + verify(containerManager).tryStart("plain", "valkey/valkey:8", "us-east-1"); + verify(containerManager, never()).tryStart(eq("plain"), anyString(), anyString(), any()); + } + + @Test + void aStartTheSnapshotCannotBeLoadedInRollsTheNewGroupBackAndKeepsTheRest() { + doAnswer(inv -> { + throw new ElastiCacheContainerManager.SnapshotRestoreException("the server could not load it"); + }).when(containerManager).tryStart(eq("restored"), anyString(), anyString(), any()); + + AwsException failure = assertThrows(AwsException.class, + () -> service.createReplicationGroupFromSnapshot(request("restored"), "snap")); + + assertEquals("InvalidSnapshotState", failure.getErrorCode()); + // The container of the failed start is removed by id, since no handle came back. + verify(containerManager).stopByGroupId("restored"); + verify(proxyManager, never()).startProxy(eq("restored"), any(), anyInt(), anyString(), anyInt(), any()); + assertEquals("ReplicationGroupNotFoundFault", fault(() -> service.getReplicationGroup("restored"))); + // Neither the group the snapshot came from nor the snapshot is lost. + assertEquals("source", service.getReplicationGroup("source").getReplicationGroupId()); + assertEquals("available", service.getSnapshot("snap").getSnapshotStatus()); + // The failed group's name and port are free again. + service.createReplicationGroupFromSnapshot(request("restored-again"), "snap"); + } + + @Test + void withoutADockerDaemonASnapshotCannotBeRestoredAndNothingIsLeftBehind() { + doAnswer(inv -> null).when(containerManager).tryStart(eq("headless"), anyString(), anyString(), any()); + + assertEquals("InvalidReplicationGroupState", + fault(() -> service.createReplicationGroupFromSnapshot(request("headless"), "snap"))); + assertEquals("ReplicationGroupNotFoundFault", fault(() -> service.getReplicationGroup("headless"))); + verify(containerManager).stopByGroupId("headless"); + } + + private static ElastiCacheService.CreateReplicationGroupRequest request(String id) { + return new ElastiCacheService.CreateReplicationGroupRequest(id, "group " + id, AuthMode.NO_AUTH, null, + "us-east-1", null, null, null, null, null, null, null, null, null, null, null, null, null, + Map.of(), null, null); + } + + private static String fault(Runnable call) { + return assertThrows(AwsException.class, call::run).getErrorCode(); + } +} diff --git a/src/test/java/io/floci/aws/services/elasticache/ElastiCacheTestConnections.java b/src/test/java/io/floci/aws/services/elasticache/ElastiCacheTestConnections.java index 98ce1b50f6..8b8bb04baa 100644 --- a/src/test/java/io/floci/aws/services/elasticache/ElastiCacheTestConnections.java +++ b/src/test/java/io/floci/aws/services/elasticache/ElastiCacheTestConnections.java @@ -11,9 +11,20 @@ import jakarta.enterprise.inject.spi.CDI; import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLSocket; import java.io.IOException; +import java.io.InputStream; import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; -/** Real CA validation for cache data-plane tests; never uses a trust-all manager. */ +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Real CA validation for cache data-plane tests, which never uses a trust-all manager, and the Docker + * CLI and RESP helpers the Docker-backed cache tests share. + */ public final class ElastiCacheTestConnections { private ElastiCacheTestConnections() {} @@ -59,4 +70,73 @@ public final class ElastiCacheTestConnections { throw new IOException("Could not establish a trusted cache TLS connection", e); } } + + /** The id of the backend container of {@code resourceId}, or the empty string when there is none. */ + static String containerOf(String resourceId) throws Exception { + return docker("ps", "-aq", "--filter", "label=io.floci.service=elasticache", + "--filter", "label=io.floci.resource-id=" + resourceId); + } + + /** Runs the Docker CLI, which must succeed, and returns its trimmed output. */ + static String docker(String... arguments) throws Exception { + Process process = startDocker(arguments); + String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8).trim(); + assertTrue(process.waitFor(60, TimeUnit.SECONDS), "docker timed out"); + assertEquals(0, process.exitValue(), "docker " + String.join(" ", arguments) + ": " + output); + return output; + } + + /** Runs the Docker CLI and returns its exit code. */ + static int dockerExit(String... arguments) throws Exception { + Process process = startDocker(arguments); + process.getInputStream().readAllBytes(); + assertTrue(process.waitFor(60, TimeUnit.SECONDS), "docker timed out"); + return process.exitValue(); + } + + private static Process startDocker(String... arguments) throws IOException { + List command = new ArrayList<>(List.of("docker")); + command.addAll(List.of(arguments)); + return new ProcessBuilder(command).redirectErrorStream(true).start(); + } + + /** Sends one command and returns the first reply line, without its line ending. */ + static String command(Socket socket, String... parts) throws IOException { + write(socket, parts); + return readLine(socket.getInputStream()); + } + + /** Sends one command whose reply is a bulk string and returns its content. */ + static String bulk(Socket socket, String... parts) throws IOException { + write(socket, parts); + InputStream in = socket.getInputStream(); + String header = readLine(in); + assertTrue(header.startsWith("$"), "bulk reply expected, got " + header); + int length = Integer.parseInt(header.substring(1)); + byte[] payload = in.readNBytes(length + 2); + return new String(payload, 0, length, StandardCharsets.UTF_8); + } + + static void write(Socket socket, String... parts) throws IOException { + StringBuilder request = new StringBuilder("*").append(parts.length).append("\r\n"); + for (String part : parts) { + request.append('$').append(part.getBytes(StandardCharsets.UTF_8).length).append("\r\n") + .append(part).append("\r\n"); + } + socket.getOutputStream().write(request.toString().getBytes(StandardCharsets.UTF_8)); + socket.getOutputStream().flush(); + } + + static String readLine(InputStream in) throws IOException { + StringBuilder line = new StringBuilder(); + int read; + while ((read = in.read()) != -1) { + if (read == '\r') { + in.read(); + break; + } + line.append((char) read); + } + return line.toString(); + } } diff --git a/src/test/java/io/floci/aws/services/elasticache/ShellLessBackendProfile.java b/src/test/java/io/floci/aws/services/elasticache/ShellLessBackendProfile.java new file mode 100644 index 0000000000..7acc995ae1 --- /dev/null +++ b/src/test/java/io/floci/aws/services/elasticache/ShellLessBackendProfile.java @@ -0,0 +1,29 @@ +package io.floci.aws.services.elasticache; + +import io.quarkus.test.junit.QuarkusTestProfile; + +import java.util.Map; + +/** + * Runs the ElastiCache backend the way an image with no shell and no CLI needs + * ({@code floci.services.elasticache.shell-less-backend}), against a real image of that kind: the + * public KiviDB image, which is distroless. The image is pinned by digest, so the tests exercise + * the same bytes every time; bumping it is a deliberate change to {@link #IMAGE}. + * + *

KiviDB names its snapshot file {@code dump.kdb} and does not report it as {@code dbfilename}, + * hence the file name override. + */ +public class ShellLessBackendProfile implements QuarkusTestProfile { + + /** KiviDB v1.2.2, the multi-arch index digest. */ + public static final String IMAGE = + "ghcr.io/kividbio/kividb:v1.2.2@sha256:8853c7b1e73e604502fd584533440cb1205ae311fe805d520543b4e85a4b71e9"; + + @Override + public Map getConfigOverrides() { + return Map.of( + "floci.services.elasticache.default-image", IMAGE, + "floci.services.elasticache.shell-less-backend", "true", + "floci.services.elasticache.shell-less-backend-dbfilename", "dump.kdb"); + } +} diff --git a/src/test/java/io/floci/aws/services/elasticache/ShellLessClusterProfile.java b/src/test/java/io/floci/aws/services/elasticache/ShellLessClusterProfile.java new file mode 100644 index 0000000000..519c9699d1 --- /dev/null +++ b/src/test/java/io/floci/aws/services/elasticache/ShellLessClusterProfile.java @@ -0,0 +1,19 @@ +package io.floci.aws.services.elasticache; + +import io.quarkus.test.junit.QuarkusTestProfile; + +import java.util.Map; + +/** + * The shell-less backend path with the default Valkey image, for cluster mode. KiviDB, the image + * {@link ShellLessBackendProfile} uses, has no {@code --cluster-announce-client-ipv4} flag, which + * Floci passes to every cluster-mode node, so it cannot form a Floci cluster yet; Valkey takes the + * same container arguments and shows that the cluster-mode flags arrive and the cluster forms. + */ +public class ShellLessClusterProfile implements QuarkusTestProfile { + + @Override + public Map getConfigOverrides() { + return Map.of("floci.services.elasticache.shell-less-backend", "true"); + } +} diff --git a/src/test/java/io/floci/aws/services/elasticache/container/ElastiCacheShellLessContainerManagerTest.java b/src/test/java/io/floci/aws/services/elasticache/container/ElastiCacheShellLessContainerManagerTest.java new file mode 100644 index 0000000000..f5f156c0d0 --- /dev/null +++ b/src/test/java/io/floci/aws/services/elasticache/container/ElastiCacheShellLessContainerManagerTest.java @@ -0,0 +1,266 @@ +package io.floci.aws.services.elasticache.container; + +import com.github.dockerjava.api.DockerClient; +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.docker.ContainerBuilder; +import io.floci.aws.core.common.docker.ContainerDetector; +import io.floci.aws.core.common.docker.ContainerLifecycleManager; +import io.floci.aws.core.common.docker.ContainerLogStreamer; +import io.floci.aws.core.common.docker.ContainerSpec; +import org.jboss.logging.Logger; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +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.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.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.RETURNS_SELF; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * How the backend container is configured with and without + * {@code floci.services.elasticache.shell-less-backend}: the server flags go to the container as + * arguments or through the image's {@code VALKEY_EXTRA_FLAGS} hook, never both. + */ +class ElastiCacheShellLessContainerManagerTest { + + private static final Logger LOG = Logger.getLogger(ElastiCacheShellLessContainerManagerTest.class); + + private static final List CLUSTER_FLAGS = List.of( + "--cluster-enabled", "yes", + "--cluster-announce-hostname", "localhost", + "--cluster-preferred-endpoint-type", "hostname", + "--cluster-announce-client-ipv4", "127.0.0.1", + "--cluster-announce-port", "6379", + "--cluster-announce-bus-port", "16379"); + + private final ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class); + private final ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF); + private final EmulatorConfig.ElastiCacheServiceConfig elasticache = + mock(EmulatorConfig.ElastiCacheServiceConfig.class); + + private ElastiCacheContainerManager manager(boolean shellLess) { + ContainerBuilder containerBuilder = mock(ContainerBuilder.class); + when(containerBuilder.newContainer(anyString())).thenReturn(builder); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); + EmulatorConfig config = mock(EmulatorConfig.class); + EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class); + when(config.services()).thenReturn(services); + when(services.elasticache()).thenReturn(elasticache); + when(elasticache.dockerNetwork()).thenReturn(Optional.empty()); + when(elasticache.shellLessBackend()).thenReturn(shellLess); + RegionResolver regionResolver = mock(RegionResolver.class); + when(regionResolver.getAccountId()).thenReturn("000000000000"); + return new ElastiCacheContainerManager(containerBuilder, lifecycleManager, + mock(ContainerLogStreamer.class), mock(ContainerDetector.class), config, regionResolver); + } + + /** Runs {@code start} against a fake backend that answers the readiness probe. */ + private void startAgainstFakeBackend(ElastiCacheContainerManager manager, List flags) + throws IOException { + try (ServerSocket serverSocket = new ServerSocket(0)) { + Thread acceptor = new Thread(() -> { + try (Socket socket = serverSocket.accept()) { + socket.getInputStream().read(new byte[1024]); + socket.getOutputStream().write("+PONG\r\n".getBytes(StandardCharsets.UTF_8)); + socket.getOutputStream().flush(); + } catch (IOException e) { + LOG.debugv(e, "Acceptor socket closed during test teardown"); + } + }); + acceptor.setDaemon(true); + acceptor.start(); + when(lifecycleManager.createAndStart(any(ContainerSpec.class))) + .thenReturn(new ContainerLifecycleManager.ContainerInfo("container-id", Map.of(6379, + new ContainerLifecycleManager.EndpointInfo("127.0.0.1", serverSocket.getLocalPort())))); + manager.start("my-group", "kividb/test", flags, "us-east-1"); + } + } + + @Test + void shellLessBackendPassesTheServerFlagsAsContainerArguments() throws IOException { + startAgainstFakeBackend(manager(true), List.of()); + + ArgumentCaptor> command = ArgumentCaptor.forClass(List.class); + verify(builder).withCmd(command.capture()); + assertEquals(List.of("--port", "6379", "--protected-mode", "no", "--loglevel", "verbose"), + command.getValue()); + verify(builder, never()).withEnv(anyString(), anyString()); + } + + @Test + void shellLessBackendPassesClusterModeFlagsAsContainerArguments() throws IOException { + startAgainstFakeBackend(manager(true), CLUSTER_FLAGS); + + ArgumentCaptor> command = ArgumentCaptor.forClass(List.class); + verify(builder).withCmd(command.capture()); + List expected = new ArrayList<>( + List.of("--port", "6379", "--protected-mode", "no", "--loglevel", "verbose")); + expected.addAll(CLUSTER_FLAGS); + assertEquals(expected, command.getValue()); + verify(builder, never()).withEnv(anyString(), anyString()); + } + + @Test + void shellLessBackendNeverEnablesTheDebugCommand() throws IOException { + startAgainstFakeBackend(manager(true), CLUSTER_FLAGS); + + ArgumentCaptor> command = ArgumentCaptor.forClass(List.class); + verify(builder).withCmd(command.capture()); + assertFalse(command.getValue().contains("--enable-debug-command")); + } + + @Test + void theDefaultPathStillUsesTheValkeyExtraFlagsHook() throws IOException { + startAgainstFakeBackend(manager(false), CLUSTER_FLAGS); + + verify(builder).withEnv("VALKEY_EXTRA_FLAGS", "--loglevel verbose --enable-debug-command local " + + String.join(" ", CLUSTER_FLAGS)); + verify(builder, never()).withCmd(any(List.class)); + } + + @Test + void aSnapshotIsLoadedAtStartupOnlyWithTheShellLessBackend() { + ElastiCacheContainerManager manager = manager(false); + + assertThrows(IllegalArgumentException.class, + () -> manager.start("my-group", "valkey/valkey:8", List.of(), "us-east-1", "UkVESVM=")); + + verify(lifecycleManager, never()).createAndStart(any(ContainerSpec.class)); + } + + @Test + void aSnapshotIsReadOnlyFromABackendThatIsRunning() { + ElastiCacheContainerManager manager = manager(true); + + assertThrows(IllegalStateException.class, () -> manager.snapshot("no-such-container")); + } + + /** + * A server that answers PING and reports the given data directory and snapshot file name, on + * as many connections as the start opens. + */ + private ServerSocket fakeBackend(String directory, String fileName) throws IOException { + ServerSocket serverSocket = new ServerSocket(0); + Thread acceptor = new Thread(() -> { + while (!serverSocket.isClosed()) { + try { + Socket socket = serverSocket.accept(); + Thread handler = new Thread(() -> answer(socket, directory, fileName)); + handler.setDaemon(true); + handler.start(); + } catch (IOException e) { + LOG.debugv(e, "Fake backend closed during test teardown"); + } + } + }); + acceptor.setDaemon(true); + acceptor.start(); + return serverSocket; + } + + private static void answer(Socket socket, String directory, String fileName) { + try (socket) { + BufferedReader in = new BufferedReader( + new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8)); + String header; + while ((header = in.readLine()) != null) { + int count = Integer.parseInt(header.substring(1)); + StringBuilder request = new StringBuilder(); + for (int i = 0; i < count; i++) { + in.readLine(); + request.append(in.readLine()).append(' '); + } + String reply; + if (request.toString().startsWith("PING")) { + reply = "+PONG\r\n"; + } else if (request.toString().endsWith("dbfilename ")) { + reply = fileName.isEmpty() ? "*0\r\n" + : "*2\r\n$10\r\ndbfilename\r\n$" + fileName.length() + "\r\n" + fileName + "\r\n"; + } else { + reply = "*2\r\n$3\r\ndir\r\n$" + directory.length() + "\r\n" + directory + "\r\n"; + } + socket.getOutputStream().write(reply.getBytes(StandardCharsets.UTF_8)); + socket.getOutputStream().flush(); + } + } catch (IOException e) { + LOG.debugv(e, "Fake backend connection closed"); + } + } + + private ElastiCacheContainerManager seededManager(ServerSocket backend, String configuredFileName) { + DockerClient docker = mock(DockerClient.class, RETURNS_DEEP_STUBS); + when(docker.inspectContainerCmd(anyString()).exec().getConfig().getWorkingDir()).thenReturn("/data"); + when(lifecycleManager.getDockerClient()).thenReturn(docker); + when(lifecycleManager.createAndStart(any(ContainerSpec.class), any(Consumer.class))).thenAnswer(inv -> { + Consumer beforeStart = inv.getArgument(1); + beforeStart.accept("container-id"); + return new ContainerLifecycleManager.ContainerInfo("container-id", Map.of(6379, + new ContainerLifecycleManager.EndpointInfo("127.0.0.1", backend.getLocalPort()))); + }); + ElastiCacheContainerManager manager = manager(true); + when(elasticache.shellLessBackendDbfilename()).thenReturn(configuredFileName); + return manager; + } + + @Test + void aRestoreIsConfirmedWhenTheServerLoadsTheFileThatWasPlaced() throws IOException { + try (ServerSocket backend = fakeBackend("/data", "dump.rdb")) { + ElastiCacheContainerManager manager = seededManager(backend, "dump.rdb"); + + manager.start("my-group", "kividb/test", List.of(), "us-east-1", "UkVESVM="); + } + } + + @Test + void aRestoreIsRefusedWhenTheServerLoadsAnotherFileName() throws IOException { + try (ServerSocket backend = fakeBackend("/data", "dump.kdb")) { + ElastiCacheContainerManager manager = seededManager(backend, "dump.rdb"); + + ElastiCacheContainerManager.SnapshotRestoreException failure = assertThrows( + ElastiCacheContainerManager.SnapshotRestoreException.class, + () -> manager.start("my-group", "kividb/test", List.of(), "us-east-1", "UkVESVM=")); + + assertTrue(failure.getMessage().contains("dump.kdb"), failure.getMessage()); + } + } + + @Test + void aRestoreIsRefusedWhenTheServerUsesAnotherDirectory() throws IOException { + try (ServerSocket backend = fakeBackend("/elsewhere", "")) { + ElastiCacheContainerManager manager = seededManager(backend, "dump.rdb"); + + assertThrows(ElastiCacheContainerManager.SnapshotRestoreException.class, + () -> manager.start("my-group", "kividb/test", List.of(), "us-east-1", "UkVESVM=")); + } + } + + @Test + void aServerThatReportsNoFileNameIsAcceptedWhenTheDirectoryMatches() throws IOException { + try (ServerSocket backend = fakeBackend("/data", "")) { + ElastiCacheContainerManager manager = seededManager(backend, "dump.kdb"); + + manager.start("my-group", "kividb/test", List.of(), "us-east-1", "UkVESVM="); + } + } +} diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index c593e463e7..008dd2074e 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -212,6 +212,7 @@ floci: proxy-max-port: 6399 default-image: "valkey/valkey:8" default-memcached-image: "memcached:1.6" + shell-less-backend: false memorydb: enabled: true mock: false