feat(elasticache): add Memcached CreateCacheCluster/DescribeCacheClus… (#930)

* feat(elasticache): add Memcached CreateCacheCluster/DescribeCacheClusters/DeleteCacheCluster support

Closes #928

* fix(elasticache): stop Memcached containers on emulator shutdown

Wire ElastiCacheMemcachedContainerManager into EmulatorLifecycle so that
Memcached containers are stopped and removed when the emulator shuts down,
preventing orphaned containers.
This commit is contained in:
Lucas Costa authored and GitHub committed 2026-05-19 00:22:33 -05:00
1 parent c426289879
commit 6a9af6057c
12 files changed
+720 -5

No files matched your search

@@ -438,7 +438,10 @@ public interface EmulatorConfig {
@WithDefault("valkey/valkey:8")
String defaultImage();
/** Docker network to attach Valkey containers to. Empty = default bridge. */
@WithDefault("memcached:1.6")
String defaultMemcachedImage();
/** Docker network to attach ElastiCache containers to. Empty = default bridge. */
Optional<String> dockerNetwork();
}
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.lifecycle.inithook.InitializationHook;
import io.github.hectorvent.floci.lifecycle.inithook.InitializationHooksRunner;
import io.github.hectorvent.floci.services.ec2.Ec2MetadataServer;
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheContainerManager;
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheMemcachedContainerManager;
import io.github.hectorvent.floci.services.elasticache.proxy.ElastiCacheProxyManager;
import io.github.hectorvent.floci.services.lambda.DynamoDbStreamsEventSourcePoller;
import io.github.hectorvent.floci.services.lambda.KinesisEventSourcePoller;
@@ -42,6 +43,7 @@ public class EmulatorLifecycle {
private final ServiceRegistry serviceRegistry;
private final EmulatorConfig config;
private final ElastiCacheContainerManager elastiCacheContainerManager;
private final ElastiCacheMemcachedContainerManager elastiCacheMemcachedContainerManager;
private final ElastiCacheProxyManager elastiCacheProxyManager;
private final RdsContainerManager rdsContainerManager;
private final RdsProxyManager rdsProxyManager;
@@ -57,6 +59,7 @@ public class EmulatorLifecycle {
public EmulatorLifecycle(StorageFactory storageFactory, ServiceRegistry serviceRegistry,
EmulatorConfig config,
ElastiCacheContainerManager elastiCacheContainerManager,
ElastiCacheMemcachedContainerManager elastiCacheMemcachedContainerManager,
ElastiCacheProxyManager elastiCacheProxyManager,
RdsContainerManager rdsContainerManager,
RdsProxyManager rdsProxyManager,
@@ -71,6 +74,7 @@ public class EmulatorLifecycle {
this.serviceRegistry = serviceRegistry;
this.config = config;
this.elastiCacheContainerManager = elastiCacheContainerManager;
this.elastiCacheMemcachedContainerManager = elastiCacheMemcachedContainerManager;
this.elastiCacheProxyManager = elastiCacheProxyManager;
this.rdsContainerManager = rdsContainerManager;
this.rdsProxyManager = rdsProxyManager;
@@ -178,6 +182,7 @@ public class EmulatorLifecycle {
elastiCacheProxyManager.stopAll();
rdsProxyManager.stopAll();
elastiCacheContainerManager.stopAll();
elastiCacheMemcachedContainerManager.stopAll();
rdsContainerManager.stopAll();
storageFactory.shutdownAll();
@@ -0,0 +1,101 @@
package io.github.hectorvent.floci.services.elasticache;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheContainerHandle;
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheMemcachedContainerManager;
import io.github.hectorvent.floci.services.elasticache.model.CacheCluster;
import io.github.hectorvent.floci.services.elasticache.model.CacheClusterStatus;
import io.github.hectorvent.floci.services.elasticache.model.Endpoint;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Instant;
import java.util.Collection;
import java.util.List;
import java.util.Map;
@ApplicationScoped
public class ElastiCacheMemcachedService {
private static final Logger LOG = Logger.getLogger(ElastiCacheMemcachedService.class);
private static final String ENGINE = "memcached";
private static final String ENGINE_VERSION = "1.6.22";
private final StorageBackend<String, CacheCluster> clusters;
private final ElastiCacheMemcachedContainerManager containerManager;
private final EmulatorConfig config;
@Inject
public ElastiCacheMemcachedService(ElastiCacheMemcachedContainerManager containerManager,
StorageFactory storageFactory,
EmulatorConfig config) {
this.containerManager = containerManager;
this.config = config;
this.clusters = storageFactory.create("elasticache", "elasticache-cache-clusters.json",
new TypeReference<Map<String, CacheCluster>>() {});
}
public CacheCluster createCacheCluster(String clusterId) {
if (clusters.get(clusterId).isPresent()) {
throw new AwsException("CacheClusterAlreadyExistsFault",
"Cache cluster " + clusterId + " already exists.", 400);
}
String image = config.services().elasticache().defaultMemcachedImage();
LOG.infov("Creating Memcached cluster {0} with image {1}", clusterId, image);
ElastiCacheContainerHandle handle = containerManager.start(clusterId, image);
String endpointHost = config.hostname().orElse("localhost");
Endpoint endpoint = new Endpoint(endpointHost, handle.getPort());
CacheCluster cluster = new CacheCluster(
clusterId, CacheClusterStatus.AVAILABLE, ENGINE, ENGINE_VERSION,
endpoint, Instant.now());
cluster.setContainerId(handle.getContainerId());
cluster.setContainerHost(handle.getHost());
cluster.setContainerPort(handle.getPort());
clusters.put(clusterId, cluster);
LOG.infov("Memcached cluster {0} created, endpoint={1}:{2}", clusterId, endpointHost, handle.getPort());
return cluster;
}
public CacheCluster getCacheCluster(String clusterId) {
return clusters.get(clusterId).orElseThrow(() ->
new AwsException("CacheClusterNotFound",
"Cache cluster " + clusterId + " not found.", 404));
}
public Collection<CacheCluster> listCacheClusters(String filterClusterId) {
if (filterClusterId != null && !filterClusterId.isBlank()) {
return clusters.get(filterClusterId)
.map(List::of)
.orElseThrow(() -> new AwsException("CacheClusterNotFound",
"Cache cluster " + filterClusterId + " not found.", 404));
}
return clusters.scan(k -> true);
}
public CacheCluster deleteCacheCluster(String clusterId) {
CacheCluster cluster = getCacheCluster(clusterId);
cluster.setCacheClusterStatus(CacheClusterStatus.DELETING);
clusters.put(clusterId, cluster);
if (cluster.getContainerId() != null) {
containerManager.stop(new ElastiCacheContainerHandle(
cluster.getContainerId(), clusterId,
cluster.getContainerHost(), cluster.getContainerPort()));
}
clusters.delete(clusterId);
LOG.infov("Memcached cluster {0} deleted", clusterId);
return cluster;
}
}
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.common.AwsNamespaces;
import io.github.hectorvent.floci.core.common.AwsQueryResponse;
import io.github.hectorvent.floci.core.common.XmlBuilder;
import io.github.hectorvent.floci.services.elasticache.model.AuthMode;
import io.github.hectorvent.floci.services.elasticache.model.CacheCluster;
import io.github.hectorvent.floci.services.elasticache.model.ElastiCacheUser;
import io.github.hectorvent.floci.services.elasticache.model.Endpoint;
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroup;
@@ -33,13 +34,16 @@ public class ElastiCacheQueryHandler {
private final SigV4Validator sigV4Validator;
private final ElastiCacheService service;
private final ElastiCacheMemcachedService memcachedService;
private final RegionResolver regionResolver;
@Inject
public ElastiCacheQueryHandler(SigV4Validator sigV4Validator, ElastiCacheService service,
ElastiCacheMemcachedService memcachedService,
RegionResolver regionResolver) {
this.sigV4Validator = sigV4Validator;
this.service = service;
this.memcachedService = memcachedService;
this.regionResolver = regionResolver;
}
@@ -55,6 +59,9 @@ public class ElastiCacheQueryHandler {
case "DescribeUsers" -> handleDescribeUsers(params);
case "ModifyUser" -> handleModifyUser(params);
case "DeleteUser" -> handleDeleteUser(params);
case "CreateCacheCluster" -> handleCreateCacheCluster(params);
case "DescribeCacheClusters" -> handleDescribeCacheClusters(params);
case "DeleteCacheCluster" -> handleDeleteCacheCluster(params);
default -> AwsQueryResponse.error("UnsupportedOperation",
"Operation " + action + " is not supported.", AwsNamespaces.EC, 400);
};
@@ -219,6 +226,58 @@ public class ElastiCacheQueryHandler {
}
}
// ── Cache Clusters (Memcached) ────────────────────────────────────────────
private Response handleCreateCacheCluster(MultivaluedMap<String, String> params) {
String clusterId = params.getFirst("CacheClusterId");
String engine = params.getFirst("Engine");
if (clusterId == null || clusterId.isBlank()) {
return AwsQueryResponse.error("InvalidParameterValue",
"CacheClusterId is required.", AwsNamespaces.EC, 400);
}
if (!"memcached".equalsIgnoreCase(engine)) {
return AwsQueryResponse.error("InvalidParameterValue",
"Engine must be 'memcached'. For Redis/Valkey use CreateReplicationGroup.", AwsNamespaces.EC, 400);
}
try {
CacheCluster cluster = memcachedService.createCacheCluster(clusterId);
return Response.ok(AwsQueryResponse.envelope("CreateCacheCluster", AwsNamespaces.EC, cacheClusterXml(cluster))).build();
} catch (AwsException e) {
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.EC, e.getHttpStatus());
}
}
private Response handleDescribeCacheClusters(MultivaluedMap<String, String> params) {
String filterId = params.getFirst("CacheClusterId");
try {
Collection<CacheCluster> clusterList = memcachedService.listCacheClusters(filterId);
var xml = new XmlBuilder().start("CacheClusters");
for (CacheCluster c : clusterList) {
xml.raw(cacheClusterXml(c));
}
xml.end("CacheClusters").start("Marker").end("Marker");
return Response.ok(AwsQueryResponse.envelope("DescribeCacheClusters", AwsNamespaces.EC, xml.build())).build();
} catch (AwsException e) {
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.EC, e.getHttpStatus());
}
}
private Response handleDeleteCacheCluster(MultivaluedMap<String, String> params) {
String clusterId = params.getFirst("CacheClusterId");
if (clusterId == null || clusterId.isBlank()) {
return AwsQueryResponse.error("InvalidParameterValue",
"CacheClusterId is required.", AwsNamespaces.EC, 400);
}
try {
CacheCluster cluster = memcachedService.deleteCacheCluster(clusterId);
return Response.ok(AwsQueryResponse.envelope("DeleteCacheCluster", AwsNamespaces.EC, cacheClusterXml(cluster))).build();
} catch (AwsException e) {
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.EC, e.getHttpStatus());
}
}
// ── IAM Token Validation ──────────────────────────────────────────────────
private Response handleValidateIamAuthToken(MultivaluedMap<String, String> params) {
@@ -250,6 +309,23 @@ public class ElastiCacheQueryHandler {
// ── XML helpers ───────────────────────────────────────────────────────────
private String cacheClusterXml(CacheCluster c) {
Endpoint ep = c.getConfigurationEndpoint();
var xml = new XmlBuilder()
.start("CacheCluster")
.elem("CacheClusterId", c.getCacheClusterId())
.elem("CacheClusterStatus", c.getCacheClusterStatus().name().toLowerCase())
.elem("Engine", c.getEngine())
.elem("EngineVersion", c.getEngineVersion());
if (ep != null) {
xml.start("ConfigurationEndpoint")
.elem("Address", ep.address())
.elem("Port", (long) ep.port())
.end("ConfigurationEndpoint");
}
return xml.end("CacheCluster").build();
}
private String replicationGroupXml(ReplicationGroup g) {
Endpoint ep = g.getConfigurationEndpoint();
boolean authTokenEnabled = g.getAuthMode() == AuthMode.PASSWORD;
@@ -0,0 +1,175 @@
package io.github.hectorvent.floci.services.elasticache.container;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.EndpointInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
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;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Manages backend Docker container lifecycle for ElastiCache Memcached clusters.
* In native (dev) mode, binds container port 11211 to a random host port.
* In Docker mode, uses the container's internal network IP directly.
*/
@ApplicationScoped
public class ElastiCacheMemcachedContainerManager {
private static final Logger LOG = Logger.getLogger(ElastiCacheMemcachedContainerManager.class);
private static final int BACKEND_PORT = 11211;
private static final int BACKEND_READY_DEADLINE_MS = 60_000;
private static final int BACKEND_READY_RETRY_MS = 100;
private static final int BACKEND_PROBE_CONNECT_MS = 2_000;
private static final byte[] TEXT_VERSION = "version\r\n".getBytes(StandardCharsets.UTF_8);
private final ContainerBuilder containerBuilder;
private final ContainerLifecycleManager lifecycleManager;
private final ContainerLogStreamer logStreamer;
private final ContainerDetector containerDetector;
private final EmulatorConfig config;
private final RegionResolver regionResolver;
private final Map<String, ElastiCacheContainerHandle> activeContainers = new ConcurrentHashMap<>();
@Inject
public ElastiCacheMemcachedContainerManager(ContainerBuilder containerBuilder,
ContainerLifecycleManager lifecycleManager,
ContainerLogStreamer logStreamer,
ContainerDetector containerDetector,
EmulatorConfig config,
RegionResolver regionResolver) {
this.containerBuilder = containerBuilder;
this.lifecycleManager = lifecycleManager;
this.logStreamer = logStreamer;
this.containerDetector = containerDetector;
this.config = config;
this.regionResolver = regionResolver;
}
public ElastiCacheContainerHandle start(String clusterId, String image) {
LOG.infov("Starting Memcached container for cluster: {0}", clusterId);
String containerName = "floci-memcached-" + clusterId;
lifecycleManager.removeIfExists(containerName);
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)
.withName(containerName)
.withDockerNetwork(config.services().elasticache().dockerNetwork())
.withLogRotation();
if (!containerDetector.isRunningInContainer()) {
specBuilder.withDynamicPort(BACKEND_PORT);
} else {
specBuilder.withExposedPort(BACKEND_PORT);
}
ContainerSpec spec = specBuilder.build();
ContainerInfo info = lifecycleManager.createAndStart(spec);
EndpointInfo endpoint = info.getEndpoint(BACKEND_PORT);
LOG.infov("Memcached backend for cluster {0}: {1}", clusterId, endpoint);
ElastiCacheContainerHandle handle = new ElastiCacheContainerHandle(
info.containerId(), clusterId, endpoint.host(), endpoint.port());
activeContainers.put(clusterId, handle);
String shortId = info.containerId().length() >= 8
? info.containerId().substring(0, 8)
: info.containerId();
String logGroup = "/aws/elasticache/cluster/" + clusterId + "/engine-log";
String logStream = logStreamer.generateLogStreamName(shortId);
String region = regionResolver.getDefaultRegion();
Closeable logHandle = logStreamer.attach(
info.containerId(), logGroup, logStream, region, "elasticache-memcached:" + clusterId);
handle.setLogStream(logHandle);
waitForBackendReady(clusterId, endpoint.host(), endpoint.port());
return handle;
}
private static void waitForBackendReady(String clusterId, String host, int port) {
long deadline = System.currentTimeMillis() + BACKEND_READY_DEADLINE_MS;
int attempt = 0;
while (System.currentTimeMillis() < deadline) {
attempt++;
try (Socket s = new Socket()) {
s.connect(new InetSocketAddress(host, port), BACKEND_PROBE_CONNECT_MS);
s.setSoTimeout(BACKEND_PROBE_CONNECT_MS);
OutputStream out = s.getOutputStream();
out.write(TEXT_VERSION);
out.flush();
String line = readLine(s.getInputStream());
if (line.startsWith("VERSION")) {
if (attempt > 1) {
LOG.infov("Memcached backend ready for cluster {0} after {1} probe attempt(s)", clusterId, attempt);
}
return;
}
} catch (IOException e) {
if (LOG.isDebugEnabled()) {
LOG.debugv("Memcached probe for cluster {0} attempt {1}: {2}", clusterId, attempt, e.getMessage());
}
}
try {
Thread.sleep(BACKEND_READY_RETRY_MS);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw new RuntimeException("Interrupted while waiting for Memcached backend " + clusterId, ie);
}
}
throw new RuntimeException(
"Memcached backend for cluster " + clusterId + " did not become ready on " + host + ":" + port
+ " within " + BACKEND_READY_DEADLINE_MS + "ms");
}
private static String readLine(InputStream in) throws IOException {
StringBuilder sb = new StringBuilder();
int b;
while ((b = in.read()) != -1) {
if (b == '\r') {
in.read(); // consume \n
break;
}
sb.append((char) b);
}
return sb.toString();
}
public void stop(ElastiCacheContainerHandle handle) {
if (handle == null) {
return;
}
activeContainers.remove(handle.getGroupId());
lifecycleManager.stopAndRemove(handle.getContainerId(), handle.getLogStream());
}
public void stopAll() {
List<ElastiCacheContainerHandle> handles = new ArrayList<>(activeContainers.values());
if (!handles.isEmpty()) {
LOG.infov("Stopping {0} Memcached container(s) on shutdown", handles.size());
}
for (ElastiCacheContainerHandle handle : handles) {
stop(handle);
}
}
}
@@ -0,0 +1,61 @@
package io.github.hectorvent.floci.services.elasticache.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
@RegisterForReflection
public class CacheCluster {
private String cacheClusterId;
private CacheClusterStatus cacheClusterStatus;
private String engine;
private String engineVersion;
private Endpoint configurationEndpoint;
private Instant cacheClusterCreateTime;
// Transient — not persisted, restored on container restart
private transient String containerId;
private transient String containerHost;
private transient int containerPort;
public CacheCluster() {}
public CacheCluster(String cacheClusterId, CacheClusterStatus cacheClusterStatus,
String engine, String engineVersion,
Endpoint configurationEndpoint, Instant cacheClusterCreateTime) {
this.cacheClusterId = cacheClusterId;
this.cacheClusterStatus = cacheClusterStatus;
this.engine = engine;
this.engineVersion = engineVersion;
this.configurationEndpoint = configurationEndpoint;
this.cacheClusterCreateTime = cacheClusterCreateTime;
}
public String getCacheClusterId() { return cacheClusterId; }
public void setCacheClusterId(String cacheClusterId) { this.cacheClusterId = cacheClusterId; }
public CacheClusterStatus getCacheClusterStatus() { return cacheClusterStatus; }
public void setCacheClusterStatus(CacheClusterStatus cacheClusterStatus) { this.cacheClusterStatus = cacheClusterStatus; }
public String getEngine() { return engine; }
public void setEngine(String engine) { this.engine = engine; }
public String getEngineVersion() { return engineVersion; }
public void setEngineVersion(String engineVersion) { this.engineVersion = engineVersion; }
public Endpoint getConfigurationEndpoint() { return configurationEndpoint; }
public void setConfigurationEndpoint(Endpoint configurationEndpoint) { this.configurationEndpoint = configurationEndpoint; }
public Instant getCacheClusterCreateTime() { return cacheClusterCreateTime; }
public void setCacheClusterCreateTime(Instant cacheClusterCreateTime) { this.cacheClusterCreateTime = cacheClusterCreateTime; }
public String getContainerId() { return containerId; }
public void setContainerId(String containerId) { this.containerId = containerId; }
public String getContainerHost() { return containerHost; }
public void setContainerHost(String containerHost) { this.containerHost = containerHost; }
public int getContainerPort() { return containerPort; }
public void setContainerPort(int containerPort) { this.containerPort = containerPort; }
}
@@ -0,0 +1,5 @@
package io.github.hectorvent.floci.services.elasticache.model;
public enum CacheClusterStatus {
AVAILABLE, CREATING, DELETING
}