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
This commit is contained in:
Murtaza Shajapurwala authored and GitHub committed 2026-11-16 16:43:40 -04:00
1 parent e281defa12
commit b7a95fc920
17 files changed
+1315 -19

No files matched your search

@@ -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<String> dockerNetwork();
@@ -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<String> 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<String> 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);
@@ -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);
}
@@ -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<String> 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<String> 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<String> 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);
@@ -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();
}