diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index 62f9ec2cbf..5e42bfb8a1 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -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 dockerNetwork(); } diff --git a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java index 455a08da1f..ef1e566cd6 100644 --- a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java +++ b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java @@ -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(); diff --git a/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheMemcachedService.java b/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheMemcachedService.java new file mode 100644 index 0000000000..cc61a2d522 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheMemcachedService.java @@ -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 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>() {}); + } + + 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 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; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheQueryHandler.java index faced73199..d0a34fc3f6 100644 --- a/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheQueryHandler.java @@ -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 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 params) { + String filterId = params.getFirst("CacheClusterId"); + try { + Collection 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 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 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; diff --git a/src/main/java/io/github/hectorvent/floci/services/elasticache/container/ElastiCacheMemcachedContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/elasticache/container/ElastiCacheMemcachedContainerManager.java new file mode 100644 index 0000000000..6c58082109 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/elasticache/container/ElastiCacheMemcachedContainerManager.java @@ -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 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 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); + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/elasticache/model/CacheCluster.java b/src/main/java/io/github/hectorvent/floci/services/elasticache/model/CacheCluster.java new file mode 100644 index 0000000000..d0b652eaa1 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/elasticache/model/CacheCluster.java @@ -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; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/elasticache/model/CacheClusterStatus.java b/src/main/java/io/github/hectorvent/floci/services/elasticache/model/CacheClusterStatus.java new file mode 100644 index 0000000000..b417ac75d5 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/elasticache/model/CacheClusterStatus.java @@ -0,0 +1,5 @@ +package io.github.hectorvent.floci.services.elasticache.model; + +public enum CacheClusterStatus { + AVAILABLE, CREATING, DELETING +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 1b75649869..873efbcfb5 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -155,6 +155,7 @@ floci: proxy-base-port: 6379 proxy-max-port: 6399 default-image: "valkey/valkey:8" + default-memcached-image: "memcached:1.6" rds: enabled: true proxy-base-port: 7001 diff --git a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java index 6cd3cf2cfb..235bcbdf2b 100644 --- a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java +++ b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java @@ -7,6 +7,7 @@ import io.github.hectorvent.floci.lifecycle.InitLifecycleState; import io.github.hectorvent.floci.lifecycle.inithook.InitializationHook; import io.github.hectorvent.floci.lifecycle.inithook.InitializationHooksRunner; 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; @@ -43,6 +44,7 @@ class EmulatorLifecycleTest { @Mock private EmulatorConfig.ServicesConfig servicesConfig; @Mock private EmulatorConfig.Ec2ServiceConfig ec2ServiceConfig; @Mock private ElastiCacheContainerManager elastiCacheContainerManager; + @Mock private ElastiCacheMemcachedContainerManager elastiCacheMemcachedContainerManager; @Mock private ElastiCacheProxyManager elastiCacheProxyManager; @Mock private RdsContainerManager rdsContainerManager; @Mock private RdsProxyManager rdsProxyManager; @@ -67,10 +69,10 @@ class EmulatorLifecycleTest { emulatorLifecycle = new EmulatorLifecycle( storageFactory, serviceRegistry, config, - elastiCacheContainerManager, elastiCacheProxyManager, - rdsContainerManager, rdsProxyManager, initializationHooksRunner, - sqsPoller, kinesisPoller, dynamodbStreamsPoller, pipesService, - ec2MetadataServer, initLifecycleState); + elastiCacheContainerManager, elastiCacheMemcachedContainerManager, + elastiCacheProxyManager, rdsContainerManager, rdsProxyManager, + initializationHooksRunner, sqsPoller, kinesisPoller, dynamodbStreamsPoller, + pipesService, ec2MetadataServer, initLifecycleState); } private void stubStorageConfig() { diff --git a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheMemcachedIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheMemcachedIntegrationTest.java new file mode 100644 index 0000000000..c52dd54ff8 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheMemcachedIntegrationTest.java @@ -0,0 +1,186 @@ +package io.github.hectorvent.floci.services.elasticache; + +import io.quarkus.test.junit.QuarkusTest; +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.nio.charset.StandardCharsets; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class ElastiCacheMemcachedIntegrationTest { + + private static final String AUTH_HEADER = + "AWS4-HMAC-SHA256 Credential=test/20260412/us-east-1/elasticache/aws4_request"; + private static final String CLUSTER_ID = "it-memcached-cluster"; + private static final int SOCKET_TIMEOUT_MS = 10_000; + + private static int clusterPort; + + @BeforeAll + static void requireDocker() { + Assumptions.assumeTrue(isDockerAvailable(), "Docker daemon must be available for Memcached integration tests"); + } + + @AfterAll + static void cleanup() { + try { + given() + .formParam("Action", "DeleteCacheCluster") + .formParam("CacheClusterId", CLUSTER_ID) + .header("Authorization", AUTH_HEADER) + .post("/"); + } catch (Exception ignored) {} + } + + @Test + @Order(1) + void createCacheCluster() { + clusterPort = + given() + .formParam("Action", "CreateCacheCluster") + .formParam("CacheClusterId", CLUSTER_ID) + .formParam("Engine", "memcached") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .contentType("application/xml") + .body("CreateCacheClusterResponse.CreateCacheClusterResult.CacheCluster.CacheClusterId", equalTo(CLUSTER_ID)) + .body("CreateCacheClusterResponse.CreateCacheClusterResult.CacheCluster.CacheClusterStatus", equalTo("available")) + .body("CreateCacheClusterResponse.CreateCacheClusterResult.CacheCluster.Engine", equalTo("memcached")) + .body("CreateCacheClusterResponse.CreateCacheClusterResult.CacheCluster.ConfigurationEndpoint.Address", notNullValue()) + .body("CreateCacheClusterResponse.CreateCacheClusterResult.CacheCluster.ConfigurationEndpoint.Port", notNullValue()) + .extract() + .xmlPath() + .getInt("CreateCacheClusterResponse.CreateCacheClusterResult.CacheCluster.ConfigurationEndpoint.Port"); + } + + @Test + @Order(2) + void describeCacheClustersIncludesCreatedCluster() { + given() + .formParam("Action", "DescribeCacheClusters") + .formParam("CacheClusterId", CLUSTER_ID) + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("DescribeCacheClustersResponse.DescribeCacheClustersResult.CacheClusters.CacheCluster.CacheClusterId", + equalTo(CLUSTER_ID)) + .body("DescribeCacheClustersResponse.DescribeCacheClustersResult.CacheClusters.CacheCluster.Engine", + equalTo("memcached")); + } + + @Test + @Order(3) + void createCacheClusterWithInvalidEngineReturnsError() { + given() + .formParam("Action", "CreateCacheCluster") + .formParam("CacheClusterId", "redis-attempt") + .formParam("Engine", "redis") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(400); + } + + @Test + @Order(4) + void memcachedAcceptsSetAndGet() throws Exception { + try (Socket socket = new Socket("localhost", clusterPort)) { + socket.setSoTimeout(SOCKET_TIMEOUT_MS); + OutputStream out = socket.getOutputStream(); + InputStream in = socket.getInputStream(); + + String setCmd = "set testkey 0 0 5\r\nhello\r\n"; + out.write(setCmd.getBytes(StandardCharsets.UTF_8)); + out.flush(); + assertEquals("STORED", readLine(in)); + + out.write("get testkey\r\n".getBytes(StandardCharsets.UTF_8)); + out.flush(); + String valueLine = readLine(in); + assertTrue(valueLine.startsWith("VALUE testkey"), "Expected VALUE line, got: " + valueLine); + assertEquals("hello", readLine(in)); + assertEquals("END", readLine(in)); + } + } + + @Test + @Order(5) + void versionCommandResponds() throws Exception { + try (Socket socket = new Socket("localhost", clusterPort)) { + socket.setSoTimeout(SOCKET_TIMEOUT_MS); + socket.getOutputStream().write("version\r\n".getBytes(StandardCharsets.UTF_8)); + socket.getOutputStream().flush(); + String response = readLine(socket.getInputStream()); + assertTrue(response.startsWith("VERSION"), "Expected VERSION response, got: " + response); + } + } + + @Test + @Order(6) + void deleteCacheCluster() { + given() + .formParam("Action", "DeleteCacheCluster") + .formParam("CacheClusterId", CLUSTER_ID) + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("DeleteCacheClusterResponse.DeleteCacheClusterResult.CacheCluster.CacheClusterId", equalTo(CLUSTER_ID)); + + given() + .formParam("Action", "DescribeCacheClusters") + .formParam("CacheClusterId", CLUSTER_ID) + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(404); + } + + 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(); + } + + private static boolean isDockerAvailable() { + try { + Process process = new ProcessBuilder("docker", "version", "--format", "{{.Server.Version}}") + .redirectErrorStream(true) + .start(); + return process.waitFor() == 0; + } catch (Exception e) { + return false; + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheMemcachedServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheMemcachedServiceTest.java new file mode 100644 index 0000000000..4489595d09 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheMemcachedServiceTest.java @@ -0,0 +1,99 @@ +package io.github.hectorvent.floci.services.elasticache; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +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 org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Collection; +import java.util.Optional; + +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.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class ElastiCacheMemcachedServiceTest { + + private ElastiCacheMemcachedService service; + + @BeforeEach + void setUp() { + ElastiCacheMemcachedContainerManager containerManager = mock(ElastiCacheMemcachedContainerManager.class); + StorageFactory storageFactory = mock(StorageFactory.class); + EmulatorConfig config = mock(EmulatorConfig.class); + + EmulatorConfig.ServicesConfig servicesConfig = mock(EmulatorConfig.ServicesConfig.class); + EmulatorConfig.ElastiCacheServiceConfig ecConfig = mock(EmulatorConfig.ElastiCacheServiceConfig.class); + when(config.services()).thenReturn(servicesConfig); + when(servicesConfig.elasticache()).thenReturn(ecConfig); + when(ecConfig.defaultMemcachedImage()).thenReturn("memcached:1.6"); + when(config.hostname()).thenReturn(Optional.of("localhost")); + + when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv -> new InMemoryStorage<>()); + when(containerManager.start(anyString(), anyString())) + .thenReturn(new ElastiCacheContainerHandle("cid", "cluster", "localhost", 11211)); + + service = new ElastiCacheMemcachedService(containerManager, storageFactory, config); + } + + @Test + void createClusterReturnsAvailableCluster() { + CacheCluster cluster = service.createCacheCluster("my-cluster"); + + assertEquals("my-cluster", cluster.getCacheClusterId()); + assertEquals(CacheClusterStatus.AVAILABLE, cluster.getCacheClusterStatus()); + assertEquals("memcached", cluster.getEngine()); + assertEquals("localhost", cluster.getConfigurationEndpoint().address()); + } + + @Test + void createDuplicateClusterThrows() { + service.createCacheCluster("my-cluster"); + + AwsException ex = assertThrows(AwsException.class, () -> service.createCacheCluster("my-cluster")); + assertEquals("CacheClusterAlreadyExistsFault", ex.getErrorCode()); + } + + @Test + void getUnknownClusterThrows() { + AwsException ex = assertThrows(AwsException.class, () -> service.getCacheCluster("no-such-cluster")); + assertEquals("CacheClusterNotFound", ex.getErrorCode()); + } + + @Test + void listClustersReturnsAll() { + service.createCacheCluster("cluster-a"); + service.createCacheCluster("cluster-b"); + + Collection list = service.listCacheClusters(null); + assertEquals(2, list.size()); + } + + @Test + void listClustersFiltersById() { + service.createCacheCluster("cluster-a"); + service.createCacheCluster("cluster-b"); + + Collection list = service.listCacheClusters("cluster-a"); + assertEquals(1, list.size()); + assertEquals("cluster-a", list.iterator().next().getCacheClusterId()); + } + + @Test + void deleteClusterRemovesIt() { + service.createCacheCluster("my-cluster"); + service.deleteCacheCluster("my-cluster"); + + AwsException ex = assertThrows(AwsException.class, () -> service.getCacheCluster("my-cluster")); + assertEquals("CacheClusterNotFound", ex.getErrorCode()); + } +} diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index b4d36da54c..b6beb79bf7 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -88,6 +88,7 @@ floci: proxy-base-port: 6379 proxy-max-port: 6399 default-image: "valkey/valkey:8" + default-memcached-image: "memcached:1.6" rds: enabled: true proxy-base-port: 7001