feat(elasticache): add serverless cache APIs (#5366)

* feat(elasticache): add serverless cache APIs

Add CreateServerlessCache, DescribeServerlessCaches, ModifyServerlessCache and DeleteServerlessCache over the Query protocol. Each cache is backed by a hidden cluster that the ordinary cluster APIs do not list, with its own user-group authentication path in the proxy.

* fix(elasticache): sua loi container rollback, validation tag, leak log stream va npipe hang

- Thu hoi container va storage khi tao Memcached provisioning that bai
- Format thong bao loi deleteCacheCluster chua cluster id
- Validate tag key trong CreateServerlessCache khi co tag value
- Chuan hoa case-insensitive cho userGroupId va region key cho nhom attachment
- Giai phong dung logStream khi stop container trong ElastiCache va Memcached container manager
- Tat validateAfterInactivity tren npipe trong FlociDockerHttpClient de tranh deadlock tren Windows

* fix(elasticache): release serverless backing on reset and make delete and list tolerant

- release backing clusters and user group attachments in clear()
- let DeleteServerlessCache be retried after the backing cluster is already gone
- keep DescribeServerlessCaches working when one cache has lost its backing
- drop the unused replaceTags and document that tags are create-only

* fix(core): drop the named-pipe stale-connection change, #5400 makes it
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-11 08:53:07 -04:00
1 parent 379086f818
commit bac2c7cbf9
21 files changed
+1892 -85

No files matched your search

@@ -536,7 +536,8 @@ public class AwsQueryController {
"ValidateIamAuthToken",
"CreateReplicationGroup", "DescribeReplicationGroups", "ModifyReplicationGroup", "DeleteReplicationGroup",
"CreateUser", "DescribeUsers", "ModifyUser", "DeleteUser",
"CreateUserGroup", "DescribeUserGroups", "ModifyUserGroup", "DeleteUserGroup"
"CreateUserGroup", "DescribeUserGroups", "ModifyUserGroup", "DeleteUserGroup",
"CreateServerlessCache", "DescribeServerlessCaches", "ModifyServerlessCache", "DeleteServerlessCache"
);
private static final Set<String> CLOUDWATCH_ACTIONS = Set.of(
@@ -4,6 +4,7 @@ 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.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
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;
@@ -37,7 +38,7 @@ public class ElastiCacheMemcachedService {
private static final String DEFAULT_CACHE_NODE_TYPE = "cache.t4g.micro";
private static final int MAX_CACHE_NODES = 40;
private final StorageBackend<String, CacheCluster> clusters;
private final AccountAwareStorageBackend<CacheCluster> clusters;
/**
* The two stores {@link ElastiCacheService} writes, read here for the id check alone.
* {@link StorageFactory#create} keys backends by file path and hands back the instance that
@@ -79,6 +80,16 @@ public class ElastiCacheMemcachedService {
* the members a Memcached cluster has are read; the rest are redis-only and ignored.
*/
public CacheCluster createCacheCluster(ElastiCacheService.CreateCacheClusterRequest request) {
return createCacheCluster(request, null, null);
}
CacheCluster createServerlessBacking(ElastiCacheService.CreateCacheClusterRequest request,
String cacheName, String accountId) {
return createCacheCluster(request, cacheName, accountId);
}
private CacheCluster createCacheCluster(ElastiCacheService.CreateCacheClusterRequest request,
String cacheName, String accountId) {
String clusterId = request.cacheClusterId();
if (request.numCacheNodes() != null && request.numCacheNodes() < 1) {
throw new AwsException("InvalidParameterValue",
@@ -102,13 +113,14 @@ public class ElastiCacheMemcachedService {
"Cache cluster " + clusterId + " is already being created.", 400);
}
try {
return provisionCacheCluster(request);
return provisionCacheCluster(request, cacheName, accountId);
} finally {
provisioningIds.release(clusterId);
}
}
private CacheCluster provisionCacheCluster(ElastiCacheService.CreateCacheClusterRequest request) {
private CacheCluster provisionCacheCluster(ElastiCacheService.CreateCacheClusterRequest request,
String cacheName, String accountId) {
String clusterId = request.cacheClusterId();
// Every store that answers DescribeCacheClusters, not just this one: two records sharing
// an id would have one describe report it twice, each with a different engine.
@@ -126,44 +138,67 @@ public class ElastiCacheMemcachedService {
// so the cluster is created and reaches 'available' even when no Docker daemon is
// reachable. Only connecting to the cache needs the container.
ElastiCacheContainerHandle handle = containerManager.tryStart(clusterId, image, request.region());
try {
String endpointHost = resolveEndpointHost(handle);
int endpointPort = handle != null ? handle.getPort() : BACKEND_PORT;
Endpoint endpoint = new Endpoint(endpointHost, endpointPort);
String endpointHost = resolveEndpointHost(handle);
int endpointPort = handle != null ? handle.getPort() : BACKEND_PORT;
Endpoint endpoint = new Endpoint(endpointHost, endpointPort);
CacheCluster cluster = new CacheCluster(
clusterId, CacheClusterStatus.AVAILABLE, ENGINE, ENGINE_VERSION,
endpoint, Instant.now());
// What terraform's aws_elasticache_cluster reads back: anything the request set and the
// describe omitted would be a diff no apply can settle.
cluster.setNumCacheNodes(request.numCacheNodes() != null ? request.numCacheNodes() : 1);
cluster.setCacheNodeType(request.cacheNodeType() != null && !request.cacheNodeType().isBlank()
? request.cacheNodeType() : DEFAULT_CACHE_NODE_TYPE);
cluster.setCacheParameterGroupName(request.cacheParameterGroupName());
cluster.setCacheSubnetGroupName(request.cacheSubnetGroupName());
cluster.setNetworkType(request.networkType() != null && !request.networkType().isBlank()
? request.networkType() : "ipv4");
cluster.setSecurityGroupIds(request.securityGroupIds() != null
? new ArrayList<>(request.securityGroupIds()) : null);
cluster.setPreferredAvailabilityZone(request.preferredAvailabilityZone() != null
&& !request.preferredAvailabilityZone().isBlank()
? request.preferredAvailabilityZone() : regionResolver.getRegion() + "a");
cluster.setArn(regionResolver.buildArn("elasticache", request.region(), "cluster:" + clusterId));
cluster.setTags(request.tags());
if (handle != null) {
cluster.setContainerId(handle.getContainerId());
cluster.setContainerHost(handle.getHost());
cluster.setContainerPort(handle.getPort());
} else {
LOG.warnv("Memcached cluster {0} created without a backing container: no Docker daemon "
+ "is reachable. Metadata operations work; connections to the cache do not "
+ "until a daemon appears.", clusterId);
}
cluster.setRegion(request.region());
cluster.setServerlessCacheName(cacheName);
cluster.setOwnerAccountId(accountId);
CacheCluster cluster = new CacheCluster(
clusterId, CacheClusterStatus.AVAILABLE, ENGINE, ENGINE_VERSION,
endpoint, Instant.now());
// What terraform's aws_elasticache_cluster reads back: anything the request set and the
// describe omitted would be a diff no apply can settle.
cluster.setNumCacheNodes(request.numCacheNodes() != null ? request.numCacheNodes() : 1);
cluster.setCacheNodeType(request.cacheNodeType() != null && !request.cacheNodeType().isBlank()
? request.cacheNodeType() : DEFAULT_CACHE_NODE_TYPE);
cluster.setCacheParameterGroupName(request.cacheParameterGroupName());
cluster.setCacheSubnetGroupName(request.cacheSubnetGroupName());
cluster.setNetworkType(request.networkType() != null && !request.networkType().isBlank()
? request.networkType() : "ipv4");
cluster.setSecurityGroupIds(request.securityGroupIds() != null
? new ArrayList<>(request.securityGroupIds()) : null);
cluster.setPreferredAvailabilityZone(request.preferredAvailabilityZone() != null
&& !request.preferredAvailabilityZone().isBlank()
? request.preferredAvailabilityZone() : regionResolver.getRegion() + "a");
cluster.setArn(regionResolver.buildArn("elasticache", request.region(), "cluster:" + clusterId));
cluster.setTags(request.tags());
if (handle != null) {
cluster.setContainerId(handle.getContainerId());
cluster.setContainerHost(handle.getHost());
cluster.setContainerPort(handle.getPort());
} else {
LOG.warnv("Memcached cluster {0} created without a backing container: no Docker daemon "
+ "is reachable. Metadata operations work; connections to the cache do not "
+ "until a daemon appears.", clusterId);
putRuntimeCluster(cluster);
LOG.infov("Memcached cluster {0} created, endpoint={1}:{2}", clusterId, endpointHost, endpointPort);
return cluster;
} catch (RuntimeException e) {
LOG.warnv("Memcached cluster {0} provisioning failed, rolling back: {1}", clusterId, e.getMessage());
rollbackCacheCluster(clusterId, handle, accountId);
throw e;
}
cluster.setRegion(request.region());
}
clusters.put(clusterId, cluster);
LOG.infov("Memcached cluster {0} created, endpoint={1}:{2}", clusterId, endpointHost, endpointPort);
return cluster;
private void rollbackCacheCluster(String clusterId, ElastiCacheContainerHandle handle, String accountId) {
try {
if (handle != null) {
containerManager.stop(handle);
}
} catch (RuntimeException e) {
LOG.warnv("Error stopping container for Memcached cluster {0}: {1}", clusterId, e.getMessage());
} finally {
if (accountId == null) {
clusters.delete(clusterId);
} else {
clusters.deleteForAccount(accountId, clusterId);
}
}
}
/**
@@ -181,12 +216,15 @@ public class ElastiCacheMemcachedService {
*/
public CompletableFuture<Void> restorePersistedRuntime() {
List<CacheCluster> toRestore = new ArrayList<>();
for (CacheCluster cluster : clusters.scan(k -> true)) {
List<CacheCluster> records = new ArrayList<>(listCacheClusters(null));
records.addAll(clusters.scanAllAccounts().stream()
.filter(cluster -> cluster.getServerlessCacheName() != null).toList());
for (CacheCluster cluster : records) {
if (cluster.getCacheClusterStatus() == CacheClusterStatus.DELETING) {
continue;
}
cluster.setCacheClusterStatus(CacheClusterStatus.CREATING);
clusters.put(cluster.getCacheClusterId(), cluster);
putRuntimeCluster(cluster);
toRestore.add(cluster);
}
if (toRestore.isEmpty()) {
@@ -215,7 +253,7 @@ public class ElastiCacheMemcachedService {
// to the default region.
ElastiCacheContainerHandle handle = containerManager.tryStart(clusterId, image, cluster.getRegion());
synchronized (lockFor(clusterId)) {
if (restoreTargetLost(clusterId)) {
if (restoreTargetLost(cluster)) {
abandonRestoredContainer(clusterId, handle);
return;
}
@@ -236,7 +274,7 @@ public class ElastiCacheMemcachedService {
+ "do not until a daemon appears.", clusterId);
}
cluster.setCacheClusterStatus(CacheClusterStatus.AVAILABLE);
clusters.put(clusterId, cluster);
putRuntimeCluster(cluster);
LOG.infov("Restored Memcached cluster {0}, endpoint={1}:{2}", clusterId,
cluster.getConfigurationEndpoint().address(),
String.valueOf(cluster.getConfigurationEndpoint().port()));
@@ -255,7 +293,7 @@ public class ElastiCacheMemcachedService {
private void failRestore(CacheCluster cluster, RuntimeException cause) {
String clusterId = cluster.getCacheClusterId();
synchronized (lockFor(clusterId)) {
if (restoreTargetLost(clusterId)) {
if (restoreTargetLost(cluster)) {
LOG.warnv(cause, "Failed to restore Memcached cluster {0}, which was deleted while "
+ "it was being restored", clusterId);
return;
@@ -266,7 +304,7 @@ public class ElastiCacheMemcachedService {
cluster.setCacheClusterStatus(CacheClusterStatus.RESTORE_FAILED);
cluster.setConfigurationEndpoint(null);
try {
clusters.put(clusterId, cluster);
putRuntimeCluster(cluster);
} catch (RuntimeException persistFailure) {
cause.addSuppressed(persistFailure);
}
@@ -280,8 +318,9 @@ public class ElastiCacheMemcachedService {
* under that same monitor, and putting the cluster back afterwards would resurrect one the
* caller was told had been deleted.
*/
private boolean restoreTargetLost(String clusterId) {
return clusters.get(clusterId)
private boolean restoreTargetLost(CacheCluster cluster) {
return (cluster.getOwnerAccountId() == null ? clusters.get(cluster.getCacheClusterId())
: clusters.getForAccount(cluster.getOwnerAccountId(), cluster.getCacheClusterId()))
.map(current -> current.getCacheClusterStatus() == CacheClusterStatus.DELETING)
.orElse(true);
}
@@ -310,26 +349,36 @@ public class ElastiCacheMemcachedService {
}
public CacheCluster getCacheCluster(String clusterId) {
return clusters.get(clusterId).orElseThrow(() ->
return clusters.get(clusterId).filter(cluster -> cluster.getServerlessCacheName() == null).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)
return clusters.get(filterClusterId).filter(cluster -> cluster.getServerlessCacheName() == null)
.map(List::of)
.orElseThrow(() -> new AwsException("CacheClusterNotFound",
"Cache cluster " + filterClusterId + " not found.", 404));
}
return clusters.scan(k -> true);
return clusters.scan(k -> true).stream().filter(cluster -> cluster.getServerlessCacheName() == null).toList();
}
public CacheCluster deleteCacheCluster(String clusterId) {
return deleteCacheCluster(clusterId, false);
}
CacheCluster deleteServerlessBacking(String clusterId) {
return deleteCacheCluster(clusterId, true);
}
private CacheCluster deleteCacheCluster(String clusterId, boolean internal) {
// one monitor per cluster for delete and restore: a restore's read-modify-write could
// otherwise write the cluster back after this removed it
synchronized (lockFor(clusterId)) {
CacheCluster cluster = getCacheCluster(clusterId);
CacheCluster cluster = clusters.get(clusterId)
.filter(record -> internal || record.getServerlessCacheName() == null).orElseThrow(() ->
new AwsException("CacheClusterNotFound", "Cache cluster " + clusterId + " not found.", 404));
cluster.setCacheClusterStatus(CacheClusterStatus.DELETING);
clusters.put(clusterId, cluster);
@@ -349,4 +398,17 @@ public class ElastiCacheMemcachedService {
private String resolveEndpointHost(ElastiCacheContainerHandle handle) {
return config.hostname().orElse(handle != null ? handle.getHost() : "localhost");
}
CacheCluster getServerlessBacking(String id, String accountId) {
return clusters.getForAccount(accountId, id).filter(cluster -> cluster.getServerlessCacheName() != null)
.orElseThrow(() -> new AwsException("CacheClusterNotFound", "Serverless backing cache not found.", 404));
}
private void putRuntimeCluster(CacheCluster cluster) {
if (cluster.getOwnerAccountId() == null) {
clusters.put(cluster.getCacheClusterId(), cluster);
} else {
clusters.putForAccount(cluster.getOwnerAccountId(), cluster.getCacheClusterId(), cluster);
}
}
}
@@ -50,15 +50,18 @@ public class ElastiCacheQueryHandler {
private final ElastiCacheService service;
private final ElastiCacheMemcachedService memcachedService;
private final RegionResolver regionResolver;
private final ElastiCacheServerlessQueryHandler serverlessHandler;
@Inject
public ElastiCacheQueryHandler(SigV4Validator sigV4Validator, ElastiCacheService service,
ElastiCacheMemcachedService memcachedService,
RegionResolver regionResolver) {
RegionResolver regionResolver,
ElastiCacheServerlessQueryHandler serverlessHandler) {
this.sigV4Validator = sigV4Validator;
this.service = service;
this.memcachedService = memcachedService;
this.regionResolver = regionResolver;
this.serverlessHandler = serverlessHandler;
}
public Response handle(String action, MultivaluedMap<String, String> params, String region) {
@@ -78,6 +81,8 @@ public class ElastiCacheQueryHandler {
case "ModifyUserGroup" -> handleModifyUserGroup(params);
case "DeleteUserGroup" -> handleDeleteUserGroup(params);
case "CreateCacheCluster" -> handleCreateCacheCluster(params, region);
case "CreateServerlessCache", "DescribeServerlessCaches", "ModifyServerlessCache", "DeleteServerlessCache" ->
serverlessHandler.handle(action, params);
case "DescribeCacheClusters" -> handleDescribeCacheClusters(params);
case "DeleteCacheCluster" -> handleDeleteCacheCluster(params);
case "CreateCacheSubnetGroup" -> handleCreateCacheSubnetGroup(params);
@@ -396,7 +401,10 @@ public class ElastiCacheQueryHandler {
xml.elem("member", replicationGroupId);
}
xml.end("ReplicationGroups");
xml.start("ServerlessCaches").end("ServerlessCaches");
xml.raw(memberListXml("ServerlessCaches", g.getServerlessCacheEngines().keySet().stream()
.map(key -> key.contains("/") ? key.substring(key.indexOf('/') + 1) : key)
.distinct()
.toList()));
xml.elem("ARN", g.getArn());
return xml.build();
}
@@ -762,6 +770,9 @@ private Response handleCreateCacheParameterGroup(MultivaluedMap<String, String>
}
Map<String, String> tags = Map.of();
if ("serverlesscache".equals(arn[5])) {
tags = serverlessHandler.getTags(arn[6]);
}
if ("replicationgroup".equals(arn[5])) {
// the store keys groups by id alone; the record must be the one the ARN names
ReplicationGroup group = service.getReplicationGroup(arn[6]);
@@ -0,0 +1,208 @@
package io.github.hectorvent.floci.services.elasticache;
import io.github.hectorvent.floci.core.common.AwsException;
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.Endpoint;
import io.github.hectorvent.floci.services.elasticache.model.ServerlessCache;
import io.github.hectorvent.floci.services.elasticache.model.ServerlessCache.CacheUsageLimits;
import io.github.hectorvent.floci.services.elasticache.model.ServerlessCache.DataStorage;
import io.github.hectorvent.floci.services.elasticache.model.ServerlessCache.EcpuPerSecond;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@ApplicationScoped
public class ElastiCacheServerlessQueryHandler {
private final ElastiCacheServerlessService service;
@Inject
public ElastiCacheServerlessQueryHandler(ElastiCacheServerlessService service) {
this.service = service;
}
public Response handle(String action, MultivaluedMap<String, String> params) {
try {
String name = params.getFirst("ServerlessCacheName");
String body = switch (action) {
case "CreateServerlessCache" -> cacheXml(service.createServerlessCache(
new ElastiCacheServerlessService.CreateServerlessCacheRequest(name, params.getFirst("Engine"),
params.getFirst("MajorEngineVersion"), params.getFirst("Description"),
members(params, "SubnetIds"), members(params, "SecurityGroupIds"), params.getFirst("UserGroupId"),
params.getFirst("KmsKeyId"), usageLimits(params), integer(params, "SnapshotRetentionLimit"),
params.getFirst("DailySnapshotTime"), members(params, "SnapshotArnsToRestore"), tags(params))));
case "ModifyServerlessCache" -> cacheXml(service.modifyServerlessCache(
new ElastiCacheServerlessService.ModifyServerlessCacheRequest(name, params.getFirst("Description"),
params.getFirst("Engine"), params.getFirst("MajorEngineVersion"),
present(params, "SecurityGroupIds") ? members(params, "SecurityGroupIds") : null,
params.getFirst("UserGroupId"), bool(params, "RemoveUserGroup"), usageLimits(params),
integer(params, "SnapshotRetentionLimit"), params.getFirst("DailySnapshotTime"))));
case "DeleteServerlessCache" -> cacheXml(service.deleteServerlessCache(name, params.getFirst("FinalSnapshotName")));
case "DescribeServerlessCaches" -> {
XmlBuilder xml = new XmlBuilder().start("ServerlessCaches");
for (ServerlessCache cache : service.describeServerlessCaches(name)) {
xml.start("member").raw(cacheFields(cache)).end("member");
}
yield xml.end("ServerlessCaches").build();
}
default -> throw new AwsException("UnsupportedOperation", "Unsupported serverless cache action.", 400);
};
return Response.ok(AwsQueryResponse.envelope(action, AwsNamespaces.EC, body)).build();
} catch (AwsException exception) {
return AwsQueryResponse.error(exception.getErrorCode(), exception.getMessage(), AwsNamespaces.EC, exception.getHttpStatus());
}
}
public Map<String, String> getTags(String name) {
return service.getServerlessCache(name).getTags();
}
private static String cacheXml(ServerlessCache cache) {
return new XmlBuilder().start("ServerlessCache").raw(cacheFields(cache)).end("ServerlessCache").build();
}
private static String cacheFields(ServerlessCache cache) {
XmlBuilder xml = new XmlBuilder().elem("ServerlessCacheName", cache.getServerlessCacheName())
.elem("Description", cache.getDescription()).elem("Status", cache.getStatus()).elem("Engine", cache.getEngine())
.elem("MajorEngineVersion", cache.getMajorEngineVersion()).elem("FullEngineVersion", cache.getFullEngineVersion())
.elem("ARN", cache.getArn()).elem("CreateTime", cache.getCreateTime().toString());
optional(xml, "UserGroupId", cache.getUserGroupId());
optional(xml, "KmsKeyId", cache.getKmsKeyId());
optional(xml, "SnapshotRetentionLimit", cache.getSnapshotRetentionLimit());
optional(xml, "DailySnapshotTime", cache.getDailySnapshotTime());
endpoint(xml, "Endpoint", cache.getEndpoint());
endpoint(xml, "ReaderEndpoint", cache.getReaderEndpoint());
list(xml, "SubnetIds", cache.getSubnetIds());
list(xml, "SecurityGroupIds", cache.getSecurityGroupIds());
CacheUsageLimits limits = cache.getCacheUsageLimits();
if (limits != null) {
xml.start("CacheUsageLimits");
if (limits.dataStorage() != null) {
xml.start("DataStorage");
optional(xml, "Minimum", limits.dataStorage().minimum());
optional(xml, "Maximum", limits.dataStorage().maximum());
optional(xml, "Unit", limits.dataStorage().unit());
xml.end("DataStorage");
}
if (limits.ecpuPerSecond() != null) {
xml.start("ECPUPerSecond");
optional(xml, "Minimum", limits.ecpuPerSecond().minimum());
optional(xml, "Maximum", limits.ecpuPerSecond().maximum());
xml.end("ECPUPerSecond");
}
xml.end("CacheUsageLimits");
}
return xml.build();
}
private static void optional(XmlBuilder xml, String name, Object value) {
if (value != null) {
xml.elem(name, value.toString());
}
}
private static void endpoint(XmlBuilder xml, String name, Endpoint endpoint) {
if (endpoint != null) {
xml.start(name).elem("Address", endpoint.address()).elem("Port", String.valueOf(endpoint.port())).end(name);
}
}
private static void list(XmlBuilder xml, String name, List<String> values) {
xml.start(name);
for (String value : values) {
xml.elem(memberName(name), value);
}
xml.end(name);
}
private static boolean present(MultivaluedMap<String, String> params, String prefix) {
return params.keySet().stream().anyMatch(key -> key.equals(prefix) || key.startsWith(prefix + "."));
}
private static List<String> members(MultivaluedMap<String, String> params, String name) {
List<String> result = new ArrayList<>();
for (int index = 1; ; index++) {
String value = params.getFirst(name + "." + memberName(name) + "." + index);
if (value == null) {
value = params.getFirst(name + ".member." + index);
}
if (value == null) {
break;
}
result.add(value);
}
return result;
}
private static String memberName(String name) {
return switch (name) {
case "SubnetIds" -> "SubnetId";
case "SecurityGroupIds" -> "SecurityGroupId";
case "SnapshotArnsToRestore" -> "SnapshotArn";
default -> "member";
};
}
private static Map<String, String> tags(MultivaluedMap<String, String> params) {
Map<String, String> result = new LinkedHashMap<>();
for (int index = 1; ; index++) {
String key = params.getFirst("Tags.Tag." + index + ".Key");
String value = params.getFirst("Tags.Tag." + index + ".Value");
if (key == null && value == null) {
key = params.getFirst("Tags.member." + index + ".Key");
value = params.getFirst("Tags.member." + index + ".Value");
}
if (key == null && value == null) {
break;
}
if (key == null || key.isBlank()) {
throw new AwsException("InvalidParameterValue", "Tag key cannot be null or empty.", 400);
}
result.put(key, value == null ? "" : value);
}
return result;
}
private static Integer integer(MultivaluedMap<String, String> params, String name) {
String value = params.getFirst(name);
if (value == null) {
return null;
}
try {
return Integer.valueOf(value);
} catch (NumberFormatException exception) {
throw new AwsException("InvalidParameterValue", name + " must be an integer.", 400);
}
}
private static Boolean bool(MultivaluedMap<String, String> params, String name) {
String value = params.getFirst(name);
if (value == null) {
return null;
}
if (!"true".equalsIgnoreCase(value) && !"false".equalsIgnoreCase(value)) {
throw new AwsException("InvalidParameterValue", name + " must be true or false.", 400);
}
return Boolean.valueOf(value);
}
private static CacheUsageLimits usageLimits(MultivaluedMap<String, String> params) {
if (!present(params, "CacheUsageLimits")) {
return null;
}
DataStorage storage = present(params, "CacheUsageLimits.DataStorage")
? new DataStorage(integer(params, "CacheUsageLimits.DataStorage.Minimum"),
integer(params, "CacheUsageLimits.DataStorage.Maximum"), params.getFirst("CacheUsageLimits.DataStorage.Unit")) : null;
EcpuPerSecond ecpu = present(params, "CacheUsageLimits.ECPUPerSecond")
? new EcpuPerSecond(integer(params, "CacheUsageLimits.ECPUPerSecond.Minimum"),
integer(params, "CacheUsageLimits.ECPUPerSecond.Maximum")) : null;
return new CacheUsageLimits(storage, ecpu);
}
}
@@ -0,0 +1,411 @@
package io.github.hectorvent.floci.services.elasticache;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
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.ServerlessCache;
import io.github.hectorvent.floci.services.elasticache.model.ServerlessCache.CacheUsageLimits;
import io.github.hectorvent.floci.services.elasticache.model.ServerlessCache.DataStorage;
import io.github.hectorvent.floci.services.elasticache.model.ServerlessCache.EcpuPerSecond;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Instant;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
@ApplicationScoped
public class ElastiCacheServerlessService implements Resettable {
private static final Logger LOG = Logger.getLogger(ElastiCacheServerlessService.class);
private final AccountAwareStorageBackend<ServerlessCache> caches;
private final RegionResolver resolver;
private final ElastiCacheService runtime;
private final ElastiCacheMemcachedService memcached;
private final ElastiCacheService groups;
private final ConcurrentHashMap<String, Object> locks = new ConcurrentHashMap<>();
@Inject
public ElastiCacheServerlessService(StorageFactory factory, RegionResolver resolver, ElastiCacheService runtime,
ElastiCacheMemcachedService memcached, ElastiCacheService groups) {
this.caches = factory.create("elasticache", "elasticache-serverless-caches.json",
new TypeReference<Map<String, ServerlessCache>>() {});
this.resolver = resolver;
this.runtime = runtime;
this.memcached = memcached;
this.groups = groups;
}
public record CreateServerlessCacheRequest(String serverlessCacheName, String engine, String majorEngineVersion,
String description, List<String> subnetIds, List<String> securityGroupIds,
String userGroupId, String kmsKeyId, CacheUsageLimits cacheUsageLimits,
Integer snapshotRetentionLimit, String dailySnapshotTime,
List<String> snapshotArnsToRestore, Map<String, String> tags) {}
public record ModifyServerlessCacheRequest(String serverlessCacheName, String description, String engine,
String majorEngineVersion, List<String> securityGroupIds,
String userGroupId, Boolean removeUserGroup, CacheUsageLimits cacheUsageLimits,
Integer snapshotRetentionLimit, String dailySnapshotTime) {}
public ServerlessCache createServerlessCache(CreateServerlessCacheRequest request) {
String name = normalizedName(request.serverlessCacheName());
String engine = normalizedEngine(request.engine());
String major = request.majorEngineVersion() == null ? defaultMajor(engine) : request.majorEngineVersion();
if (!defaultMajor(engine).equals(major)) {
throw invalid("Only engine version " + defaultMajor(engine) + " is supported for " + engine + ".");
}
validateMetadata(request.description(), request.cacheUsageLimits(), request.snapshotRetentionLimit(),
request.dailySnapshotTime());
if (request.snapshotArnsToRestore() != null && !request.snapshotArnsToRestore().isEmpty()) {
throw invalid("Snapshot restore is not supported locally.");
}
if (request.tags() != null && request.tags().size() > 50) {
throw new AwsException("TagQuotaPerResourceExceeded", "At most 50 tags are supported.", 400);
}
String rawGroup = request.userGroupId();
String group = normalizedUserGroupId(rawGroup);
String region = resolver.getRegion();
validateGroup(group, engine, region);
runtime.validateServerlessDependencies(request.subnetIds(), request.securityGroupIds(), request.kmsKeyId(), region);
synchronized (lockFor(name)) {
if (caches.get(key(name)).isPresent()) {
throw new AwsException("ServerlessCacheAlreadyExistsFault", "Serverless cache " + name + " already exists.", 400);
}
boolean attached = false;
CacheCluster backing = null;
try {
if (group != null) {
groups.attachServerlessCache(group, key(name), engine);
attached = true;
}
String runtimeId = "serverless-" + UUID.randomUUID();
ElastiCacheService.CreateCacheClusterRequest backingRequest = new ElastiCacheService.CreateCacheClusterRequest(
runtimeId, engine, null, null, 1, null, AuthMode.NO_AUTH, null, null, null,
0, null, null, null, null, null, null, false, region, Map.of());
String account = resolver.getAccountId();
backing = "memcached".equals(engine)
? memcached.createServerlessBacking(backingRequest, name, account)
: runtime.createServerlessBacking(backingRequest, name, account, group);
ServerlessCache cache = new ServerlessCache();
cache.setServerlessCacheName(name);
cache.setEngine(engine);
cache.setMajorEngineVersion(major);
cache.setFullEngineVersion(backing.getEngineVersion());
cache.setDescription(request.description() == null ? "" : request.description());
cache.setStatus("available");
cache.setCreateTime(Instant.now());
cache.setArn(resolver.buildArn("elasticache", region, "serverlesscache:" + name));
cache.setEndpoint(backing.getConfigurationEndpoint());
cache.setReaderEndpoint(backing.getConfigurationEndpoint());
cache.setRegion(region);
cache.setAccountId(account);
cache.setBackingCacheClusterId(runtimeId);
cache.setSubnetIds(request.subnetIds());
cache.setSecurityGroupIds(request.securityGroupIds());
cache.setUserGroupId(group);
cache.setKmsKeyId(request.kmsKeyId());
cache.setCacheUsageLimits(request.cacheUsageLimits());
cache.setSnapshotRetentionLimit(request.snapshotRetentionLimit() == null ? 0 : request.snapshotRetentionLimit());
cache.setDailySnapshotTime(request.dailySnapshotTime());
cache.setTags(request.tags());
caches.put(key(name), cache);
return copy(cache);
} catch (RuntimeException exception) {
// Each step runs on its own so a failed backing delete never leaves the group attached.
if (backing != null) {
try {
deleteBacking(engine, backing.getCacheClusterId());
} catch (RuntimeException cleanupFailure) {
exception.addSuppressed(cleanupFailure);
}
}
if (attached) {
try {
groups.detachServerlessCache(group, key(name));
} catch (RuntimeException cleanupFailure) {
exception.addSuppressed(cleanupFailure);
}
}
throw exception;
}
}
}
public ServerlessCache getServerlessCache(String name) {
String normalized = normalizedName(name);
synchronized (lockFor(normalized)) {
return current(requireCache(normalized));
}
}
public List<ServerlessCache> describeServerlessCaches(String name) {
if (name != null && !name.isBlank()) {
return List.of(getServerlessCache(name));
}
return caches.scan(key -> key.startsWith(resolver.getRegion() + "/")).stream()
.map(this::currentOrStored).toList();
}
public ServerlessCache modifyServerlessCache(ModifyServerlessCacheRequest request) {
String name = normalizedName(request.serverlessCacheName());
validateMetadata(request.description(), request.cacheUsageLimits(), request.snapshotRetentionLimit(),
request.dailySnapshotTime());
if (Boolean.TRUE.equals(request.removeUserGroup()) && request.userGroupId() != null) {
throw new AwsException("InvalidParameterCombination", "UserGroupId and RemoveUserGroup conflict.", 400);
}
synchronized (lockFor(name)) {
ServerlessCache previous = requireCache(name);
if (request.securityGroupIds() != null) {
runtime.validateServerlessDependencies(previous.getSubnetIds(), request.securityGroupIds(), null, previous.getRegion());
}
if (request.engine() != null && !previous.getEngine().equals(normalizedEngine(request.engine()))
|| request.majorEngineVersion() != null && !previous.getMajorEngineVersion().equals(request.majorEngineVersion())) {
throw invalid("Changing engine or engine version is not supported locally.");
}
ServerlessCache updated = copy(previous);
String group = Boolean.TRUE.equals(request.removeUserGroup()) ? null
: request.userGroupId() == null ? previous.getUserGroupId() : normalizedUserGroupId(request.userGroupId());
validateGroup(group, previous.getEngine(), previous.getRegion());
boolean changedGroup = !Objects.equals(group, previous.getUserGroupId());
if (changedGroup && group != null) {
groups.attachServerlessCache(group, key(name), previous.getEngine());
}
try {
if (changedGroup && !"memcached".equals(previous.getEngine())) {
runtime.updateServerlessUserGroup(previous.getBackingCacheClusterId(), previous.getAccountId(), group);
}
updated.setUserGroupId(group);
if (request.description() != null) {
updated.setDescription(request.description());
}
if (request.securityGroupIds() != null) {
updated.setSecurityGroupIds(request.securityGroupIds());
}
if (request.cacheUsageLimits() != null) {
updated.setCacheUsageLimits(request.cacheUsageLimits());
}
if (request.snapshotRetentionLimit() != null) {
updated.setSnapshotRetentionLimit(request.snapshotRetentionLimit());
}
if (request.dailySnapshotTime() != null) {
updated.setDailySnapshotTime(request.dailySnapshotTime());
}
caches.put(key(name), updated);
} catch (RuntimeException exception) {
if (changedGroup) {
try {
runtime.updateServerlessUserGroup(previous.getBackingCacheClusterId(), previous.getAccountId(), previous.getUserGroupId());
if (group != null) {
groups.detachServerlessCache(group, key(name));
}
} catch (RuntimeException rollbackFailure) {
exception.addSuppressed(rollbackFailure);
}
}
throw exception;
}
if (changedGroup && previous.getUserGroupId() != null) {
groups.detachServerlessCache(previous.getUserGroupId(), key(name));
}
return current(updated);
}
}
public ServerlessCache deleteServerlessCache(String name) {
return deleteServerlessCache(name, null);
}
public ServerlessCache deleteServerlessCache(String name, String finalSnapshotName) {
if (finalSnapshotName != null) {
throw invalid("Final snapshots are not supported locally.");
}
String normalized = normalizedName(name);
synchronized (lockFor(normalized)) {
ServerlessCache cache = requireCache(normalized);
try {
deleteBacking(cache.getEngine(), cache.getBackingCacheClusterId());
} catch (AwsException e) {
if (!"CacheClusterNotFound".equals(e.getErrorCode())) {
throw e;
}
LOG.warnv("Backing cluster {0} of serverless cache {1} is already gone, finishing the delete",
cache.getBackingCacheClusterId(), normalized);
}
if (cache.getUserGroupId() != null) {
groups.detachServerlessCache(cache.getUserGroupId(), key(normalized));
}
caches.delete(key(normalized));
ServerlessCache deleted = copy(cache);
deleted.setStatus("deleting");
return deleted;
}
}
private void deleteBacking(String engine, String id) {
if ("memcached".equals(engine)) {
memcached.deleteServerlessBacking(id);
} else {
runtime.deleteServerlessBacking(id);
}
}
private ServerlessCache current(ServerlessCache cache) {
ServerlessCache snapshot = copy(cache);
CacheCluster backing = "memcached".equals(cache.getEngine())
? memcached.getServerlessBacking(cache.getBackingCacheClusterId(), cache.getAccountId())
: runtime.getServerlessBacking(cache.getBackingCacheClusterId(), cache.getAccountId());
snapshot.setEndpoint(backing.getConfigurationEndpoint());
snapshot.setReaderEndpoint(backing.getConfigurationEndpoint());
snapshot.setStatus(backing.getCacheClusterStatus().wireName());
return snapshot;
}
private ServerlessCache currentOrStored(ServerlessCache cache) {
try {
return current(cache);
} catch (AwsException e) {
LOG.warnv("Serverless cache {0} has no backing cluster, listing its stored state: {1}",
cache.getServerlessCacheName(), e.getMessage());
return copy(cache);
}
}
private ServerlessCache requireCache(String name) {
return caches.get(key(name)).orElseThrow(() -> new AwsException("ServerlessCacheNotFoundFault",
"Serverless cache " + name + " not found.", 404));
}
private String key(String name) {
return resolver.getRegion() + "/" + name;
}
private Object lockFor(String name) {
return locks.computeIfAbsent(resolver.getAccountId() + "/" + key(name), key -> new Object());
}
private void validateGroup(String group, String engine, String region) {
if (group == null) {
return;
}
if ("memcached".equals(engine)) {
throw new AwsException("InvalidParameterCombination", "Memcached does not support user groups.", 400);
}
groups.validateServerlessAssociation(group, engine);
}
private static String normalizedName(String name) {
if (name == null || !name.matches("[a-zA-Z][a-zA-Z0-9-]{0,39}") || name.endsWith("-") || name.contains("--")) {
throw invalid("ServerlessCacheName must contain 1 to 40 letters, digits and hyphens and begin with a letter.");
}
return name.toLowerCase(Locale.ROOT);
}
private static String normalizedUserGroupId(String userGroupId) {
return userGroupId == null ? null : userGroupId.toLowerCase(Locale.ROOT);
}
private static String normalizedEngine(String engine) {
if (engine == null || !List.of("valkey", "redis", "memcached").contains(engine.toLowerCase(Locale.ROOT))) {
throw invalid("Engine must be valkey, redis or memcached.");
}
return engine.toLowerCase(Locale.ROOT);
}
private static String defaultMajor(String engine) {
return switch (engine) {
case "valkey" -> "8";
case "redis" -> "7";
default -> "1.6";
};
}
private static void validateMetadata(String description, CacheUsageLimits limits, Integer retention, String time) {
if (description != null && description.length() > 255) {
throw invalid("Description cannot exceed 255 characters.");
}
if (retention != null && (retention < 0 || retention > 35)) {
throw invalid("SnapshotRetentionLimit must be between 0 and 35.");
}
if (time != null && !time.matches("(?:[01][0-9]|2[0-3]):[0-5][0-9]")) {
throw invalid("DailySnapshotTime must be HH:mm.");
}
if (limits != null) {
DataStorage storage = limits.dataStorage();
if (storage != null) {
if (!"GB".equals(storage.unit())) {
throw invalid("DataStorage.Unit must be GB.");
}
validateBounds(storage.minimum(), storage.maximum());
}
EcpuPerSecond ecpu = limits.ecpuPerSecond();
if (ecpu != null) {
validateBounds(ecpu.minimum(), ecpu.maximum());
}
}
}
private static void validateBounds(Integer minimum, Integer maximum) {
if (minimum != null && minimum < 0 || maximum != null && maximum < 1
|| minimum != null && maximum != null && minimum > maximum) {
throw invalid("Usage limits must be nonnegative and minimum cannot exceed maximum.");
}
}
private static AwsException invalid(String message) {
return new AwsException("InvalidParameterValue", message, 400);
}
@Override
public void clear() {
for (ServerlessCache cache : caches.scanAllAccounts()) {
try {
deleteBacking(cache.getEngine(), cache.getBackingCacheClusterId());
} catch (RuntimeException e) {
LOG.warnv(e, "Could not release backing cluster {0} of serverless cache {1} on reset",
cache.getBackingCacheClusterId(), cache.getServerlessCacheName());
}
if (cache.getUserGroupId() != null) {
groups.detachServerlessCache(cache.getUserGroupId(),
cache.getRegion() + "/" + cache.getServerlessCacheName());
}
}
caches.clear();
}
private static ServerlessCache copy(ServerlessCache cache) {
ServerlessCache copy = new ServerlessCache();
copy.setServerlessCacheName(cache.getServerlessCacheName());
copy.setEngine(cache.getEngine());
copy.setMajorEngineVersion(cache.getMajorEngineVersion());
copy.setFullEngineVersion(cache.getFullEngineVersion());
copy.setDescription(cache.getDescription());
copy.setStatus(cache.getStatus());
copy.setArn(cache.getArn());
copy.setCreateTime(cache.getCreateTime());
copy.setEndpoint(cache.getEndpoint());
copy.setReaderEndpoint(cache.getReaderEndpoint());
copy.setRegion(cache.getRegion());
copy.setAccountId(cache.getAccountId());
copy.setBackingCacheClusterId(cache.getBackingCacheClusterId());
copy.setUserGroupId(cache.getUserGroupId());
copy.setKmsKeyId(cache.getKmsKeyId());
copy.setSnapshotRetentionLimit(cache.getSnapshotRetentionLimit());
copy.setDailySnapshotTime(cache.getDailySnapshotTime());
copy.setCacheUsageLimits(cache.getCacheUsageLimits());
copy.setSubnetIds(cache.getSubnetIds());
copy.setSecurityGroupIds(cache.getSecurityGroupIds());
copy.setTags(cache.getTags());
return copy;
}
}
@@ -13,6 +13,7 @@ import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;
import io.github.hectorvent.floci.services.ec2.model.Subnet;
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheContainerHandle;
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheContainerManager;
@@ -33,6 +34,8 @@ import io.github.hectorvent.floci.services.elasticache.proxy.ElastiCacheAuthProx
import io.github.hectorvent.floci.services.elasticache.proxy.ElastiCacheProxyManager;
import io.github.hectorvent.floci.services.kms.KmsService;
import io.github.hectorvent.floci.services.kms.model.KmsKey;
import io.github.hectorvent.floci.services.kms.model.KmsKeySpec;
import io.github.hectorvent.floci.services.kms.model.KmsKeyUsage;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -66,7 +69,7 @@ public class ElastiCacheService implements ResourceProvider {
private static final Logger LOG = Logger.getLogger(ElastiCacheService.class);
private final StorageBackend<String, ReplicationGroup> groups;
private final StorageBackend<String, CacheCluster> cacheClusters;
private final AccountAwareStorageBackend<CacheCluster> cacheClusters;
/**
* The Memcached cluster store, the one {@link ElastiCacheMemcachedService} writes.
* {@link StorageFactory#create} keys backends by file path and hands the second caller the
@@ -74,7 +77,7 @@ public class ElastiCacheService implements ResourceProvider {
* is one namespace whatever engine claims it, and only a reader of both can say it is free.
*/
private final StorageBackend<String, CacheCluster> memcachedClusters;
private final StorageBackend<String, ElastiCacheUser> users;
private final AccountAwareStorageBackend<ElastiCacheUser> users;
private final AccountAwareStorageBackend<ElastiCacheUserGroup> userGroups;
private final AccountAwareStorageBackend<CacheParameterGroup> parameterGroups;
private final StorageBackend<String, CacheSubnetGroup> subnetGroups;
@@ -659,12 +662,12 @@ public class ElastiCacheService implements ResourceProvider {
}
groups.put(group.getReplicationGroupId(), group);
}
for (CacheCluster cluster : cacheClusters.scan(k -> true)) {
for (CacheCluster cluster : runtimeCacheClusters()) {
if (cluster.getCacheClusterStatus() == CacheClusterStatus.DELETING) {
continue;
}
reserveCacheCluster(cluster, cacheClustersToRestore);
cacheClusters.put(cluster.getCacheClusterId(), cluster);
putRuntimeCluster(cluster);
}
if (clusterModeToRestore.isEmpty() && singleNodeToRestore.isEmpty()
&& cacheClustersToRestore.isEmpty()) {
@@ -774,7 +777,7 @@ public class ElastiCacheService implements ResourceProvider {
try {
ElastiCacheContainerHandle handle = containerManager.tryStart(clusterId, image, regionOf(cluster.getArn()));
synchronized (lockFor("cc:" + clusterId)) {
if (cacheClusterRestoreTargetLost(clusterId)) {
if (cacheClusterRestoreTargetLost(cluster)) {
abandonRestoredCacheClusterContainer(clusterId, handle);
return;
}
@@ -782,9 +785,7 @@ public class ElastiCacheService implements ResourceProvider {
cluster.setContainerId(handle.getContainerId());
cluster.setContainerHost(handle.getHost());
cluster.setContainerPort(handle.getPort());
proxyManager.startProxy(clusterId, cluster.getAuthMode(),
cluster.getConfigurationEndpoint().port(), handle.getHost(), handle.getPort(),
(username, password) -> validateCacheClusterPassword(clusterId, username, password));
startCacheClusterProxy(cluster, handle);
} else {
// Cleared rather than left alone: whatever the record carried describes a
// container from the previous process, and nothing must read it as live.
@@ -796,7 +797,7 @@ public class ElastiCacheService implements ResourceProvider {
+ "the cache do not until a daemon appears.", clusterId);
}
cluster.setCacheClusterStatus(CacheClusterStatus.AVAILABLE);
cacheClusters.put(clusterId, cluster);
putRuntimeCluster(cluster);
LOG.infov("Restored cache cluster {0}, endpoint={1}:{2}", clusterId,
cluster.getConfigurationEndpoint().address(),
String.valueOf(cluster.getConfigurationEndpoint().port()));
@@ -811,8 +812,8 @@ public class ElastiCacheService implements ResourceProvider {
* Callers must hold the cluster's monitor, for the reason given on
* {@link #restoreTargetLost}.
*/
private boolean cacheClusterRestoreTargetLost(String clusterId) {
return cacheClusters.get(clusterId)
private boolean cacheClusterRestoreTargetLost(CacheCluster cluster) {
return runtimeCluster(cluster.getCacheClusterId(), cluster.getOwnerAccountId())
.map(current -> current.getCacheClusterStatus() == CacheClusterStatus.DELETING)
.orElse(true);
}
@@ -859,7 +860,7 @@ public class ElastiCacheService implements ResourceProvider {
} catch (RuntimeException e) {
LOG.warnv("Error stopping container for cache cluster {0}: {1}", clusterId, e.getMessage());
}
if (cacheClusterRestoreTargetLost(clusterId)) {
if (cacheClusterRestoreTargetLost(cluster)) {
LOG.warnv(cause, "Failed to restore cache cluster {0}, which was deleted while it "
+ "was being restored", clusterId);
return;
@@ -874,7 +875,7 @@ public class ElastiCacheService implements ResourceProvider {
cluster.setCacheClusterStatus(CacheClusterStatus.RESTORE_FAILED);
cluster.setConfigurationEndpoint(null);
try {
cacheClusters.put(clusterId, cluster);
putRuntimeCluster(cluster);
} catch (RuntimeException persistFailure) {
cause.addSuppressed(persistFailure);
}
@@ -1234,6 +1235,62 @@ public class ElastiCacheService implements ResourceProvider {
}
public CacheCluster createCacheCluster(CreateCacheClusterRequest request) {
return createCacheCluster(request, null, null, null);
}
CacheCluster createServerlessBacking(CreateCacheClusterRequest request, String cacheName,
String accountId, String userGroupId) {
return createCacheCluster(request, cacheName, accountId, userGroupId);
}
void validateServerlessDependencies(List<String> subnetIds, List<String> securityGroupIds,
String kmsKeyId, String region) {
String vpc = null;
if (subnetIds != null && !subnetIds.isEmpty()) {
List<Subnet> resolved = ec2Service.describeSubnets(region, subnetIds, Map.of());
if (new HashSet<>(subnetIds).size() != subnetIds.size() || resolved.size() != subnetIds.size()) {
throw new AwsException("InvalidParameterValue", "SubnetIds contain duplicate or missing subnets.", 400);
}
vpc = resolved.getFirst().getVpcId();
for (Subnet subnet : resolved) {
if (!vpc.equals(subnet.getVpcId())) {
throw new AwsException("InvalidParameterValue", "All subnets must belong to the same VPC.", 400);
}
}
}
if (securityGroupIds != null && !securityGroupIds.isEmpty()) {
List<SecurityGroup> resolved = ec2Service.describeSecurityGroups(region, securityGroupIds, List.of(), Map.of());
if (new HashSet<>(securityGroupIds).size() != securityGroupIds.size() || resolved.size() != securityGroupIds.size()) {
throw new AwsException("InvalidParameterValue", "SecurityGroupIds contain duplicate or missing groups.", 400);
}
if (vpc == null) {
vpc = resolved.getFirst().getVpcId();
}
for (SecurityGroup group : resolved) {
if (!vpc.equals(group.getVpcId())) {
throw new AwsException("InvalidParameterValue", "Security groups and subnets must belong to the same VPC.", 400);
}
}
}
if (kmsKeyId != null) {
KmsKey key;
try {
key = kmsService.describeKey(kmsKeyId, region);
} catch (AwsException exception) {
if ("NotFoundException".equals(exception.getErrorCode())) {
throw new AwsException("InvalidParameterValue", "KmsKeyId does not identify a key in this account and region.", 400);
}
throw exception;
}
if (!key.isEnabled() || key.getKeySpec() != KmsKeySpec.SYMMETRIC_DEFAULT
|| key.getKeyUsage() != KmsKeyUsage.ENCRYPT_DECRYPT) {
throw new AwsException("InvalidParameterValue", "KmsKeyId must identify an enabled symmetric encryption key.", 400);
}
}
}
private CacheCluster createCacheCluster(CreateCacheClusterRequest request, String cacheName,
String accountId, String userGroupId) {
String clusterId = request.cacheClusterId();
String engine = normalizeEngine(request.engine());
if (request.numCacheNodes() != null && request.numCacheNodes() != 1) {
@@ -1258,7 +1315,7 @@ public class ElastiCacheService implements ResourceProvider {
"Cache cluster " + clusterId + " is already being created.", 400);
}
try {
return provisionCacheCluster(request, engine);
return provisionCacheCluster(request, engine, cacheName, accountId, userGroupId);
} finally {
provisioningIds.release(clusterId);
}
@@ -1309,7 +1366,8 @@ public class ElastiCacheService implements ResourceProvider {
* cluster-mode-disabled replication group: the same Valkey container, fronted by the same
* auth proxy on a port from the same range, so the endpoint a describe reports answers RESP.
*/
private CacheCluster provisionCacheCluster(CreateCacheClusterRequest request, String engine) {
private CacheCluster provisionCacheCluster(CreateCacheClusterRequest request, String engine,
String cacheName, String accountId, String userGroupId) {
String clusterId = request.cacheClusterId();
AuthMode authMode = request.authMode() != null ? request.authMode() : AuthMode.NO_AUTH;
int proxyPort = allocateProxyPort(request.port());
@@ -1336,6 +1394,10 @@ public class ElastiCacheService implements ResourceProvider {
: "cache.t4g.micro");
cluster.setAuthMode(authMode);
cluster.setAuthToken(request.authToken());
cluster.setRegion(request.region());
cluster.setServerlessCacheName(cacheName);
cluster.setOwnerAccountId(accountId);
cluster.setUserGroupId(userGroupId);
cluster.setArn(regionResolver.buildArn("elasticache", request.region(), "cluster:" + clusterId));
cluster.setCacheParameterGroupName(request.cacheParameterGroupName());
cluster.setCacheSubnetGroupName(request.cacheSubnetGroupName());
@@ -1352,9 +1414,7 @@ public class ElastiCacheService implements ResourceProvider {
synchronized (lockFor("cc:" + clusterId)) {
cacheClusters.put(clusterId, cluster);
if (handle != null) {
proxyManager.startProxy(clusterId, authMode, proxyPort,
handle.getHost(), handle.getPort(),
(username, password) -> validateCacheClusterPassword(clusterId, username, password));
startCacheClusterProxy(cluster, handle);
} else {
LOG.warnv("Cache cluster {0} created without a backing cache container: no "
+ "Docker daemon is reachable. Metadata operations work; connections to "
@@ -1434,14 +1494,24 @@ public class ElastiCacheService implements ResourceProvider {
*/
public List<CacheCluster> findCacheClusters(String filterClusterId) {
if (filterClusterId != null && !filterClusterId.isBlank()) {
return cacheClusters.get(filterClusterId).map(List::of).orElseGet(List::of);
return cacheClusters.get(filterClusterId).filter(cluster -> cluster.getServerlessCacheName() == null)
.map(List::of).orElseGet(List::of);
}
return cacheClusters.scan(k -> true);
return cacheClusters.scan(k -> true).stream().filter(cluster -> cluster.getServerlessCacheName() == null).toList();
}
public CacheCluster deleteCacheCluster(String clusterId) {
return deleteCacheCluster(clusterId, false);
}
CacheCluster deleteServerlessBacking(String clusterId) {
return deleteCacheCluster(clusterId, true);
}
private CacheCluster deleteCacheCluster(String clusterId, boolean internal) {
synchronized (lockFor("cc:" + clusterId)) {
CacheCluster cluster = cacheClusters.get(clusterId).orElseThrow(() ->
CacheCluster cluster = cacheClusters.get(clusterId)
.filter(record -> internal || record.getServerlessCacheName() == null).orElseThrow(() ->
new AwsException("CacheClusterNotFound",
"Cache cluster " + clusterId + " not found.", 404));
@@ -1483,6 +1553,93 @@ public class ElastiCacheService implements ResourceProvider {
return (username == null || username.isEmpty()) && cluster.getAuthToken().equals(password);
}
private List<CacheCluster> runtimeCacheClusters() {
List<CacheCluster> records = new ArrayList<>(findCacheClusters(null));
records.addAll(cacheClusters.scanAllAccounts().stream()
.filter(cluster -> cluster.getServerlessCacheName() != null).toList());
return records;
}
private Optional<CacheCluster> runtimeCluster(String id, String accountId) {
return accountId == null ? cacheClusters.get(id) : cacheClusters.getForAccount(accountId, id);
}
private void putRuntimeCluster(CacheCluster cluster) {
if (cluster.getOwnerAccountId() == null) {
cacheClusters.put(cluster.getCacheClusterId(), cluster);
} else {
cacheClusters.putForAccount(cluster.getOwnerAccountId(), cluster.getCacheClusterId(), cluster);
}
}
CacheCluster getServerlessBacking(String id, String accountId) {
return cacheClusters.getForAccount(accountId, id)
.filter(cluster -> cluster.getServerlessCacheName() != null)
.orElseThrow(() -> new AwsException("CacheClusterNotFound", "Serverless backing cache not found.", 404));
}
void updateServerlessUserGroup(String id, String accountId, String groupId) {
synchronized (lockFor("cc:" + id)) {
CacheCluster cluster = getServerlessBacking(id, accountId);
cluster.setUserGroupId(groupId);
putRuntimeCluster(cluster);
}
}
private void startCacheClusterProxy(CacheCluster cluster, ElastiCacheContainerHandle handle) {
if (cluster.getServerlessCacheName() == null) {
proxyManager.startProxy(cluster.getCacheClusterId(), cluster.getAuthMode(),
cluster.getConfigurationEndpoint().port(), handle.getHost(), handle.getPort(),
(username, password) -> validateCacheClusterPassword(cluster.getCacheClusterId(), username, password));
} else {
proxyManager.startProxy(cluster.getCacheClusterId(), AuthMode.NO_AUTH,
cluster.getConfigurationEndpoint().port(), handle.getHost(), handle.getPort(),
serverlessAuthenticator(cluster), cluster.getServerlessCacheName());
}
}
private ElastiCacheAuthProxy.PasswordValidator serverlessAuthenticator(CacheCluster original) {
String id = original.getCacheClusterId();
String account = original.getOwnerAccountId();
return new ElastiCacheAuthProxy.PasswordValidator() {
private ElastiCacheUser member(String username) {
String name = username == null || username.isEmpty() ? "default" : username;
synchronized (users) {
CacheCluster cluster = cacheClusters.getForAccount(account, id).orElse(null);
if (cluster == null || cluster.getUserGroupId() == null) {
return null;
}
ElastiCacheUserGroup group = userGroups.getForAccount(account, normalizeUserGroupId(cluster.getUserGroupId())).orElse(null);
if (group == null) {
return null;
}
return group.getUserIds().stream().map(userId -> users.getForAccount(account, userId).orElse(null))
.filter(user -> user != null && name.equals(user.getUserName()) && user.isEnabled())
.findFirst().orElse(null);
}
}
@Override
public boolean validatePassword(String username, String password) {
ElastiCacheUser user = member(username);
return user != null && (user.getAuthMode() == AuthMode.NO_AUTH
|| user.getAuthMode() == AuthMode.PASSWORD && user.getPasswords().contains(password));
}
@Override
public boolean hasMembers() {
return cacheClusters.getForAccount(account, id).map(cluster -> cluster.getUserGroupId() != null)
.orElse(true);
}
@Override
public AuthMode memberAuthMode(String username) {
ElastiCacheUser user = member(username);
return user == null ? null : user.getAuthMode();
}
};
}
/**
* A replication-group member viewed as the cache cluster AWS reports it as. The terraform
* provider follows {@code MemberClusters} into DescribeCacheClusters, so every member name
@@ -1806,6 +1963,9 @@ public class ElastiCacheService implements ResourceProvider {
for (ReplicationGroup group : replicationGroupsUsing(id)) {
requireEngineCompatible(newEngine, id, group.getEngine());
}
for (String cacheEngine : userGroup.getServerlessCacheEngines().values()) {
requireEngineCompatible(newEngine, id, cacheEngine);
}
}
userGroup.setEngine(newEngine);
userGroup.setUserIds(members);
@@ -1823,6 +1983,10 @@ public class ElastiCacheService implements ResourceProvider {
throw new AwsException("InvalidUserGroupState",
"User group " + id + " is in use by a replication group. Disassociate it before deleting it.", 400);
}
if (!userGroup.getServerlessCacheEngines().isEmpty()) {
throw new AwsException("InvalidUserGroupState",
"User group " + id + " is in use by a serverless cache. Disassociate it before deleting it.", 400);
}
userGroups.delete(id);
userGroup.setStatus("deleting");
LOG.infov("ElastiCache user group {0} deleted", id);
@@ -1830,6 +1994,32 @@ public class ElastiCacheService implements ResourceProvider {
}
}
/** Checks, under the user group lock, that a serverless cache of this engine may use the group. */
void validateServerlessAssociation(String userGroupId, String cacheEngine) {
synchronized (userGroupLock) {
ElastiCacheUserGroup userGroup = getUserGroup(userGroupId);
requireEngineCompatible(userGroup.getEngine(), userGroup.getUserGroupId(), normalizeEngine(cacheEngine));
}
}
void attachServerlessCache(String userGroupId, String cacheName, String cacheEngine) {
synchronized (userGroupLock) {
ElastiCacheUserGroup userGroup = getUserGroup(userGroupId);
requireEngineCompatible(userGroup.getEngine(), userGroup.getUserGroupId(), normalizeEngine(cacheEngine));
userGroup.getServerlessCacheEngines().put(cacheName, normalizeEngine(cacheEngine));
userGroups.put(userGroup.getUserGroupId(), userGroup);
}
}
void detachServerlessCache(String userGroupId, String cacheName) {
synchronized (userGroupLock) {
Optional<ElastiCacheUserGroup> userGroup = userGroups.get(normalizeUserGroupId(userGroupId));
if (userGroup.isPresent() && userGroup.get().getServerlessCacheEngines().remove(cacheName) != null) {
userGroups.put(userGroup.get().getUserGroupId(), userGroup.get());
}
}
}
public List<String> replicationGroupIdsUsing(String userGroupId) {
return replicationGroupsUsing(normalizeUserGroupId(userGroupId)).stream()
.map(ReplicationGroup::getReplicationGroupId)
@@ -2468,7 +2658,7 @@ public class ElastiCacheService implements ResourceProvider {
Map.of()));
}
for (CacheCluster cluster : cacheClusters.scan(k -> true)) {
if (cluster.getArn() == null) {
if (cluster.getArn() == null || cluster.getServerlessCacheName() != null) {
continue;
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(cluster.getArn());
@@ -236,8 +236,10 @@ public class ElastiCacheContainerManager {
if (handle == null) {
return;
}
activeContainers.remove(handle.getGroupId());
lifecycleManager.stopAndRemove(handle.getContainerId(), handle.getLogStream());
ElastiCacheContainerHandle existing = activeContainers.remove(handle.getGroupId());
Closeable logStream = handle.getLogStream() != null ? handle.getLogStream()
: (existing != null ? existing.getLogStream() : null);
lifecycleManager.stopAndRemove(handle.getContainerId(), logStream);
}
/**
@@ -213,8 +213,10 @@ public class ElastiCacheMemcachedContainerManager {
if (handle == null) {
return;
}
activeContainers.remove(handle.getGroupId());
lifecycleManager.stopAndRemove(handle.getContainerId(), handle.getLogStream());
ElastiCacheContainerHandle existing = activeContainers.remove(handle.getGroupId());
Closeable logStream = handle.getLogStream() != null ? handle.getLogStream()
: (existing != null ? existing.getLogStream() : null);
lifecycleManager.stopAndRemove(handle.getContainerId(), logStream);
}
public void stopAll() {
@@ -35,6 +35,9 @@ public class CacheCluster {
private boolean atRestEncryptionEnabled;
private List<String> securityGroupIds = new ArrayList<>();
private Map<String, String> tags = new LinkedHashMap<>();
private String serverlessCacheName;
private String ownerAccountId;
private String userGroupId;
// Transient: not persisted, restored on container restart
private transient String containerId;
@@ -123,6 +126,15 @@ public class CacheCluster {
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags == null ? new LinkedHashMap<>() : tags; }
public String getServerlessCacheName() { return serverlessCacheName; }
public void setServerlessCacheName(String serverlessCacheName) { this.serverlessCacheName = serverlessCacheName; }
public String getOwnerAccountId() { return ownerAccountId; }
public void setOwnerAccountId(String ownerAccountId) { this.ownerAccountId = ownerAccountId; }
public String getUserGroupId() { return userGroupId; }
public void setUserGroupId(String userGroupId) { this.userGroupId = userGroupId; }
public String getContainerId() { return containerId; }
public void setContainerId(String containerId) { this.containerId = containerId; }
@@ -3,7 +3,9 @@ package io.github.hectorvent.floci.services.elasticache.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
@RegisterForReflection
@@ -16,6 +18,8 @@ public class ElastiCacheUserGroup {
private Set<String> userIds = new LinkedHashSet<>();
private Instant createdAt;
private String arn;
// Serverless caches attached to this group, by cache name, with the engine each runs.
private Map<String, String> serverlessCacheEngines = new LinkedHashMap<>();
public ElastiCacheUserGroup() {}
@@ -47,4 +51,9 @@ public class ElastiCacheUserGroup {
public String getArn() { return arn; }
public void setArn(String arn) { this.arn = arn; }
public Map<String, String> getServerlessCacheEngines() { return serverlessCacheEngines; }
public void setServerlessCacheEngines(Map<String, String> serverlessCacheEngines) {
this.serverlessCacheEngines = serverlessCacheEngines != null ? serverlessCacheEngines : new LinkedHashMap<>();
}
}
@@ -0,0 +1,109 @@
package io.github.hectorvent.floci.services.elasticache.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@RegisterForReflection
public class ServerlessCache {
private String serverlessCacheName;
private String engine;
private String majorEngineVersion;
private String fullEngineVersion;
private String description;
private String status;
private String arn;
private Instant createTime;
private Endpoint endpoint;
private Endpoint readerEndpoint;
private String region;
private String accountId;
private String backingCacheClusterId;
private String userGroupId;
private String kmsKeyId;
private Integer snapshotRetentionLimit;
private String dailySnapshotTime;
private CacheUsageLimits cacheUsageLimits;
private List<String> subnetIds = new ArrayList<>();
private List<String> securityGroupIds = new ArrayList<>();
private Map<String, String> tags = new LinkedHashMap<>();
public ServerlessCache() {}
public String getServerlessCacheName() { return serverlessCacheName; }
public void setServerlessCacheName(String serverlessCacheName) { this.serverlessCacheName = serverlessCacheName; }
public String getEngine() { return engine; }
public void setEngine(String engine) { this.engine = engine; }
public String getMajorEngineVersion() { return majorEngineVersion; }
public void setMajorEngineVersion(String majorEngineVersion) { this.majorEngineVersion = majorEngineVersion; }
public String getFullEngineVersion() { return fullEngineVersion; }
public void setFullEngineVersion(String fullEngineVersion) { this.fullEngineVersion = fullEngineVersion; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public String getArn() { return arn; }
public void setArn(String arn) { this.arn = arn; }
public Instant getCreateTime() { return createTime; }
public void setCreateTime(Instant createTime) { this.createTime = createTime; }
public Endpoint getEndpoint() { return endpoint; }
public void setEndpoint(Endpoint endpoint) { this.endpoint = endpoint; }
public Endpoint getReaderEndpoint() { return readerEndpoint; }
public void setReaderEndpoint(Endpoint readerEndpoint) { this.readerEndpoint = readerEndpoint; }
public String getRegion() { return region; }
public void setRegion(String region) { this.region = region; }
public String getAccountId() { return accountId; }
public void setAccountId(String accountId) { this.accountId = accountId; }
public String getBackingCacheClusterId() { return backingCacheClusterId; }
public void setBackingCacheClusterId(String backingCacheClusterId) { this.backingCacheClusterId = backingCacheClusterId; }
public String getUserGroupId() { return userGroupId; }
public void setUserGroupId(String userGroupId) { this.userGroupId = userGroupId; }
public String getKmsKeyId() { return kmsKeyId; }
public void setKmsKeyId(String kmsKeyId) { this.kmsKeyId = kmsKeyId; }
public Integer getSnapshotRetentionLimit() { return snapshotRetentionLimit; }
public void setSnapshotRetentionLimit(Integer snapshotRetentionLimit) { this.snapshotRetentionLimit = snapshotRetentionLimit; }
public String getDailySnapshotTime() { return dailySnapshotTime; }
public void setDailySnapshotTime(String dailySnapshotTime) { this.dailySnapshotTime = dailySnapshotTime; }
public CacheUsageLimits getCacheUsageLimits() { return cacheUsageLimits; }
public void setCacheUsageLimits(CacheUsageLimits cacheUsageLimits) { this.cacheUsageLimits = cacheUsageLimits; }
public List<String> getSubnetIds() { return new ArrayList<>(subnetIds); }
public void setSubnetIds(List<String> subnetIds) { this.subnetIds = subnetIds == null ? new ArrayList<>() : new ArrayList<>(subnetIds); }
public List<String> getSecurityGroupIds() { return new ArrayList<>(securityGroupIds); }
public void setSecurityGroupIds(List<String> securityGroupIds) { this.securityGroupIds = securityGroupIds == null ? new ArrayList<>() : new ArrayList<>(securityGroupIds); }
public Map<String, String> getTags() { return new LinkedHashMap<>(tags); }
public void setTags(Map<String, String> tags) { this.tags = tags == null ? new LinkedHashMap<>() : new LinkedHashMap<>(tags); }
@RegisterForReflection
public record CacheUsageLimits(DataStorage dataStorage, EcpuPerSecond ecpuPerSecond) {}
@RegisterForReflection
public record DataStorage(Integer minimum, Integer maximum, String unit) {}
@RegisterForReflection
public record EcpuPerSecond(Integer minimum, Integer maximum) {}
}
@@ -28,8 +28,14 @@ public class ElastiCacheProxyManager {
public void startProxy(String groupId, AuthMode authMode, int proxyPort,
String backendHost, int backendPort,
ElastiCacheAuthProxy.PasswordValidator passwordValidator) {
startProxy(groupId, authMode, proxyPort, backendHost, backendPort, passwordValidator, groupId);
}
public void startProxy(String groupId, AuthMode authMode, int proxyPort,
String backendHost, int backendPort,
ElastiCacheAuthProxy.PasswordValidator passwordValidator, String authIdentity) {
ElastiCacheAuthProxy proxy = new ElastiCacheAuthProxy(
groupId, authMode, backendHost, backendPort,
authIdentity, authMode, backendHost, backendPort,
passwordValidator, sigV4Validator);
try {
proxy.start(proxyPort);