feat(cloudformation): provision ElastiCache cache clusters and subnet groups (#5307)

* feat(cloudformation): provision ElastiCache cache clusters and subnet groups

Add AWS::ElastiCache::CacheCluster and AWS::ElastiCache::SubnetGroup provisioners with Ref, Fn::GetAtt endpoint attributes, create-only replacement and update handling. Subnet group updates now carry tags through modifyCacheSubnetGroup, and Memcached clusters record their network type.

* fix(elasticache): validate cluster name, rollback subnet groups and preserve memcached tags

* fix(elasticache): align in-use error wire code and enforce schema required properties
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-10 11:11:00 -04:00
1 parent 141fd747ee
commit 475d230ebc
14 files changed
+1098 -8

No files matched your search

+1
View File
@@ -138,6 +138,7 @@ cross-resource references.
| ECS | `Cluster`, `TaskDefinition`, `Service`, `CapacityProvider`, `ClusterCapacityProviderAssociations` |
| EKS | `Cluster`, `Nodegroup` |
| RDS | `DBInstance` (starts a real container), `DBCluster` (starts a real container), `DBSubnetGroup`, `DBParameterGroup`, `DBClusterParameterGroup`, `DBProxy`, `DBProxyTargetGroup` |
| ElastiCache | `CacheCluster` (starts a real container; modifying an existing cluster in place is not supported), `SubnetGroup` |
| Redshift | `Cluster` (single-node container; Port and non-dev DBName ignored; ManageMasterPassword unsupported), `ClusterParameterGroup`, `ClusterSubnetGroup`, `ClusterSecurityGroup` (accepted; no EC2-Classic security group model) |
| Redshift Serverless | `Namespace` (ManageAdminPassword is accepted and not applied; GetAtt uses the dotted Namespace.* form), `Workgroup` (starts a real container; one workgroup per namespace; capacity, VPC and price-performance settings are stored only; snapshot restore properties are ignored; GetAtt uses the dotted Workgroup.* form) |
| EC2 | `VPC`, `Subnet`, `SecurityGroup` (inline `SecurityGroupIngress`/`SecurityGroupEgress` supported), `SecurityGroupIngress`, `SecurityGroupEgress`, `InternetGateway`, `RouteTable`, `SubnetRouteTableAssociation`, `Route`, `NatGateway`, `EIP`, `Instance`, `LaunchTemplate`, `VPCGatewayAttachment`, `VPCEndpoint`, `NetworkAcl`, `NetworkAclEntry`, `SubnetNetworkAclAssociation`, `FlowLog` |
+6
View File
@@ -325,6 +325,12 @@
</dependency>
<!-- Testing -->
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>elasticache</artifactId>
<version>2.55.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-junit</artifactId>
@@ -0,0 +1,326 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.elasticache.ElastiCacheMemcachedService;
import io.github.hectorvent.floci.services.elasticache.ElastiCacheService;
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.CacheSubnetGroup;
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.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* Provisions AWS::ElastiCache::CacheCluster and SubnetGroup. A cache cluster needs the Memcached
* service as well as the Redis one, because the two engines keep their clusters in separate stores.
*/
@ApplicationScoped
public class ElastiCacheCfnProvisioner implements CfnResourceProvisioner {
private static final Logger LOG = Logger.getLogger(ElastiCacheCfnProvisioner.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String CACHE_CLUSTER = "AWS::ElastiCache::CacheCluster";
private static final String SUBNET_GROUP = "AWS::ElastiCache::SubnetGroup";
private static final String SUBNET_GROUP_UPDATE_SNAPSHOT_ATTR = "__FlociCacheSubnetGroupUpdateSnapshot";
private static final List<String> UNSUPPORTED_CLUSTER_PROPERTIES = List.of("CacheSecurityGroupNames",
"NotificationTopicArn", "AZMode", "PreferredAvailabilityZones", "LogDeliveryConfigurations",
"SnapshotArns", "SnapshotName");
private static final String DEFAULT_NETWORK_TYPE = "ipv4";
private static final int CLUSTER_ID_MAX_LENGTH = 50;
private static final int SUBNET_GROUP_NAME_MAX_LENGTH = 255;
private final ElastiCacheService elastiCacheService;
private final ElastiCacheMemcachedService memcachedService;
@Inject
public ElastiCacheCfnProvisioner(ElastiCacheService elastiCacheService,
ElastiCacheMemcachedService memcachedService) {
this.elastiCacheService = elastiCacheService;
this.memcachedService = memcachedService;
}
@Override
public Set<String> resourceTypes() {
return Set.of(CACHE_CLUSTER, SUBNET_GROUP);
}
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
r.getAttributes().remove(SUBNET_GROUP_UPDATE_SNAPSHOT_ATTR);
Map<String, String> attributesBefore = Map.copyOf(r.getAttributes());
switch (r.getResourceType()) {
case CACHE_CLUSTER -> provisionCacheCluster(r, props, ctx);
case SUBNET_GROUP -> provisionSubnetGroup(r, props, ctx);
default -> throw new IllegalStateException(
"ElastiCacheCfnProvisioner cannot provision " + r.getResourceType());
}
ReplacementCleanup.record(r, ctx, attributesBefore);
}
@Override
public boolean hasReplacementUpdate(StackResource resource) {
return ReplacementCleanup.hasReplacement(resource);
}
@Override
public String updateCleanupPhysicalId(StackResource resource) {
return ReplacementCleanup.cleanupPhysicalId(resource);
}
@Override
public UpdateCleanupResult completeUpdate(StackResource resource) {
if ("UPDATE_COMPLETE".equals(resource.getStatus())) {
resource.getAttributes().remove(SUBNET_GROUP_UPDATE_SNAPSHOT_ATTR);
}
return ReplacementCleanup.complete(resource, this::delete);
}
@Override
public void clearUpdate(StackResource resource) {
resource.getAttributes().remove(SUBNET_GROUP_UPDATE_SNAPSHOT_ATTR);
ReplacementCleanup.clear(resource);
}
@Override
public boolean rollbackUpdate(StackResource resource) {
if (SUBNET_GROUP.equals(resource.getResourceType())) {
String rawSnapshot = resource.getAttributes().remove(SUBNET_GROUP_UPDATE_SNAPSHOT_ATTR);
if (rawSnapshot != null) {
try {
SubnetGroupSnapshot snapshot = MAPPER.readValue(rawSnapshot, SubnetGroupSnapshot.class);
elastiCacheService.modifyCacheSubnetGroup(snapshot.name(), snapshot.description(),
snapshot.subnetIds(), snapshot.tags());
return true;
} catch (Exception e) {
LOG.errorv("Could not restore subnet group {0} after failed update: {1}",
resource.getPhysicalId(), e.getMessage());
}
}
}
return ReplacementCleanup.rollback(resource, this::delete);
}
private void provisionCacheCluster(StackResource r, JsonNode props, ProvisionContext ctx) {
String engine = ctx.resolveOptional(props, "Engine");
if (engine == null || engine.isBlank()) {
throw new AwsException("ValidationException", "Engine is required", 400);
}
String nodeType = ctx.resolveOptional(props, "CacheNodeType");
if (nodeType == null || nodeType.isBlank()) {
throw new AwsException("ValidationException", "CacheNodeType is required", 400);
}
String explicitNodes = ctx.resolveOptional(props, "NumCacheNodes");
if (explicitNodes == null || explicitNodes.isBlank()) {
throw new AwsException("ValidationException", "NumCacheNodes is required", 400);
}
String explicitName = ctx.resolveOptional(props, "ClusterName");
if (explicitName != null && explicitName.length() > CLUSTER_ID_MAX_LENGTH) {
throw new AwsException("ValidationException",
"ClusterName exceeds maximum length of " + CLUSTER_ID_MAX_LENGTH, 400);
}
String subnetGroup = ctx.resolveOptional(props, "CacheSubnetGroupName");
Integer port = optionalInt(ctx.resolveOptional(props, "Port"));
CacheCluster prior = ctx.isUpdate() ? findCluster(ctx.priorPhysicalId()) : null;
// Engine, CacheSubnetGroupName and NetworkType are create-only in AWS: a change replaces the
// cluster, so an unnamed one gets a fresh generated id. Port is not compared, because the
// emulator reports its own host proxy port rather than the requested one.
String networkType = ctx.resolveOptional(props, "NetworkType");
String desiredNetworkType = networkType == null || networkType.isBlank() ? DEFAULT_NETWORK_TYPE : networkType;
// A cluster stored before the type was recorded reads as the default, which is what it was created with.
String storedNetworkType = prior == null || prior.getNetworkType() == null
? DEFAULT_NETWORK_TYPE : prior.getNetworkType();
boolean createOnlyChanged = prior != null
&& (!engine.equalsIgnoreCase(prior.getEngine())
|| !Objects.equals(subnetGroup, prior.getCacheSubnetGroupName())
|| !desiredNetworkType.equals(storedNetworkType));
if (createOnlyChanged && explicitName != null && explicitName.equals(ctx.priorPhysicalId())) {
throw new AwsException("InvalidParameterValue", "Updating a create-only property of cache cluster "
+ explicitName + " requires a new ClusterName", 400);
}
String id;
if (createOnlyChanged && explicitName == null) {
id = ctx.generatePhysicalName(r.getLogicalId(), CLUSTER_ID_MAX_LENGTH, true);
} else {
id = ctx.stablePhysicalName(explicitName, r.getLogicalId(), CLUSTER_ID_MAX_LENGTH, true);
}
CacheCluster cluster;
if (ctx.reusesPriorEntity(id)) {
cluster = prior != null ? prior : findCluster(id);
if (cluster == null) {
LOG.warnv("ElastiCache cache cluster {0} was deleted outside the stack, recreating it", id);
cluster = createCluster(id, engine, port, props, ctx);
} else {
warnIgnoredClusterChanges(id, cluster, props, ctx);
}
} else {
cluster = createCluster(id, engine, port, props, ctx);
}
r.setPhysicalId(id);
putEndpointAttributes(r, cluster);
}
private void warnUnsupportedClusterProperties(String id, JsonNode props) {
for (String name : UNSUPPORTED_CLUSTER_PROPERTIES) {
if (props.hasNonNull(name)) {
LOG.warnv("ElastiCache cache cluster {0}: {1} is accepted and ignored", id, name);
}
}
}
private void warnIgnoredClusterChanges(String id, CacheCluster cluster, JsonNode props, ProvisionContext ctx) {
String nodeType = ctx.resolveOptional(props, "CacheNodeType");
String nodes = ctx.resolveOptional(props, "NumCacheNodes");
String version = ctx.resolveOptional(props, "EngineVersion");
boolean changed = (nodeType != null && !nodeType.equals(cluster.getCacheNodeType()))
|| (nodes != null && Integer.parseInt(nodes) != cluster.getNumCacheNodes())
|| (version != null && !version.equals(cluster.getEngineVersion()));
if (changed) {
LOG.warnv("ElastiCache cache cluster {0}: in-place modification is not supported, changes to CacheNodeType, NumCacheNodes and EngineVersion are ignored", id);
}
}
private CacheCluster createCluster(String id, String engine, Integer port, JsonNode props,
ProvisionContext ctx) {
warnUnsupportedClusterProperties(id, props);
List<String> securityGroupIds = ctx.resolveStringList(props, "VpcSecurityGroupIds");
ElastiCacheService.CreateCacheClusterRequest request = new ElastiCacheService.CreateCacheClusterRequest(
id,
engine,
ctx.resolveOptional(props, "EngineVersion"),
ctx.resolveOptional(props, "CacheNodeType"),
optionalInt(ctx.resolveOptional(props, "NumCacheNodes")),
port,
AuthMode.NO_AUTH,
null,
ctx.resolveOptional(props, "CacheParameterGroupName"),
ctx.resolveOptional(props, "CacheSubnetGroupName"),
optionalInt(ctx.resolveOptional(props, "SnapshotRetentionLimit")),
ctx.resolveOptional(props, "SnapshotWindow"),
ctx.resolveOptional(props, "PreferredMaintenanceWindow"),
ctx.resolveOptional(props, "PreferredAvailabilityZone"),
securityGroupIds.isEmpty() ? null : securityGroupIds,
ctx.resolveOptional(props, "NetworkType"),
ctx.resolveOptional(props, "IpDiscovery"),
null,
ctx.region(),
ctx.resolveTags(props, "Tags"));
return "memcached".equalsIgnoreCase(engine)
? memcachedService.createCacheCluster(request)
: elastiCacheService.createCacheCluster(request);
}
private void putEndpointAttributes(StackResource r, CacheCluster cluster) {
r.getAttributes().remove("RedisEndpoint.Address");
r.getAttributes().remove("RedisEndpoint.Port");
r.getAttributes().remove("ConfigurationEndpoint.Address");
r.getAttributes().remove("ConfigurationEndpoint.Port");
Endpoint endpoint = cluster.getConfigurationEndpoint();
if (endpoint == null) {
return;
}
// CloudFormation exposes a memcached cluster through ConfigurationEndpoint and a
// redis or valkey one through RedisEndpoint.
String prefix = "memcached".equalsIgnoreCase(cluster.getEngine())
? "ConfigurationEndpoint" : "RedisEndpoint";
r.getAttributes().put(prefix + ".Address", endpoint.address());
r.getAttributes().put(prefix + ".Port", String.valueOf(endpoint.port()));
}
private CacheCluster findCluster(String clusterId) {
if (clusterId == null || clusterId.isBlank()) {
return null;
}
List<CacheCluster> found = elastiCacheService.findCacheClusters(clusterId);
if (!found.isEmpty()) {
return found.getFirst();
}
try {
return memcachedService.getCacheCluster(clusterId);
} catch (AwsException e) {
if ("CacheClusterNotFound".equals(e.getErrorCode())) {
return null;
}
throw e;
}
}
private void provisionSubnetGroup(StackResource r, JsonNode props, ProvisionContext ctx) {
String description = ctx.resolveOptional(props, "Description");
if (description == null || description.isBlank()) {
throw new AwsException("ValidationException", "Description is required", 400);
}
String explicitName = ctx.resolveOptional(props, "CacheSubnetGroupName");
if (explicitName != null && explicitName.length() > SUBNET_GROUP_NAME_MAX_LENGTH) {
throw new AwsException("ValidationException",
"CacheSubnetGroupName exceeds maximum length of " + SUBNET_GROUP_NAME_MAX_LENGTH, 400);
}
String id = ctx.stablePhysicalName(explicitName, r.getLogicalId(), SUBNET_GROUP_NAME_MAX_LENGTH, true);
List<String> subnetIds = ctx.resolveStringList(props, "SubnetIds");
CacheSubnetGroup group;
if (ctx.reusesPriorEntity(id)) {
List<CacheSubnetGroup> existing = elastiCacheService.describeCacheSubnetGroups(id);
if (!existing.isEmpty()) {
CacheSubnetGroup prior = existing.getFirst();
SubnetGroupSnapshot snapshot = new SubnetGroupSnapshot(
prior.getName(),
prior.getDescription(),
new ArrayList<>(prior.getSubnetAvailabilityZones().keySet()),
prior.getTags());
try {
r.getAttributes().put(SUBNET_GROUP_UPDATE_SNAPSHOT_ATTR, MAPPER.writeValueAsString(snapshot));
} catch (JsonProcessingException e) {
LOG.errorv("Could not snapshot subnet group {0} before update: {1}", id, e.getMessage());
}
}
group = elastiCacheService.modifyCacheSubnetGroup(id, description, subnetIds,
ctx.resolveTags(props, "Tags"));
} else {
group = elastiCacheService.createCacheSubnetGroup(id, description, subnetIds,
ctx.resolveTags(props, "Tags"));
}
r.setPhysicalId(group.getName());
}
@Override
public void delete(String resourceType, String physicalId, String region) {
if (resourceType == null || physicalId == null) {
return;
}
switch (resourceType) {
case CACHE_CLUSTER -> CfnDeletes.safeDelete("ElastiCache cache cluster", physicalId, () -> {
if (elastiCacheService.findCacheClusters(physicalId).isEmpty()) {
memcachedService.deleteCacheCluster(physicalId);
} else {
elastiCacheService.deleteCacheCluster(physicalId);
}
}, "CacheClusterNotFound");
case SUBNET_GROUP -> CfnDeletes.safeDelete("ElastiCache subnet group", physicalId,
() -> elastiCacheService.deleteCacheSubnetGroup(physicalId), "CacheSubnetGroupNotFoundFault");
default -> {
}
}
}
private static Integer optionalInt(String raw) {
return raw == null || raw.isBlank() ? null : Integer.valueOf(raw);
}
private record SubnetGroupSnapshot(String name, String description, List<String> subnetIds,
Map<String, String> tags) {}
}
@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheCont
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.CacheSubnetGroup;
import io.github.hectorvent.floci.services.elasticache.model.Endpoint;
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroup;
import jakarta.enterprise.context.ApplicationScoped;
@@ -45,6 +46,7 @@ public class ElastiCacheMemcachedService {
*/
private final StorageBackend<String, CacheCluster> redisClusters;
private final StorageBackend<String, ReplicationGroup> groups;
private final StorageBackend<String, CacheSubnetGroup> subnetGroups;
private final ElastiCacheMemcachedContainerManager containerManager;
private final EmulatorConfig config;
/** Shared with {@link ElastiCacheService}: one namespace, one set of in-flight claims. */
@@ -68,6 +70,8 @@ public class ElastiCacheMemcachedService {
new TypeReference<Map<String, CacheCluster>>() {});
this.groups = storageFactory.create("elasticache", "elasticache-groups.json",
new TypeReference<Map<String, ReplicationGroup>>() {});
this.subnetGroups = storageFactory.create("elasticache", "elasticache-subnet-groups.json",
new TypeReference<Map<String, CacheSubnetGroup>>() {});
}
/**
@@ -87,6 +91,7 @@ public class ElastiCacheMemcachedService {
"The request cannot be processed because it would exceed the allowed number "
+ "of cache nodes in a single cluster.", 400);
}
ElastiCacheService.requireCacheSubnetGroup(subnetGroups, request.cacheSubnetGroupName());
// Claimed before the store checks rather than after, because no create here or in
// ElastiCacheService persists its record until its container has started: a store check
// that passes is no promise the id is still free by the time this one writes. The claim
@@ -136,12 +141,15 @@ public class ElastiCacheMemcachedService {
? 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());
@@ -782,9 +782,12 @@ private Response handleCreateCacheParameterGroup(MultivaluedMap<String, String>
}
tags = cluster.getTags();
} else if (service.listMemberCacheClusters(arn[6]).isEmpty()) {
// Memcached clusters and replication group members carry no tags, but they do
// exist. Only an id no source knows is a not-found.
memcachedService.getCacheCluster(arn[6]);
CacheCluster mcCluster = memcachedService.getCacheCluster(arn[6]);
if (mcCluster.getArn() != null && !mcCluster.getArn().equalsIgnoreCase(resourceName)) {
throw new AwsException("CacheClusterNotFound",
"Cache cluster " + arn[6] + " not found.", 404);
}
tags = mcCluster.getTags();
}
}
if ("subnetgroup".equals(arn[5])) {
@@ -1246,7 +1246,7 @@ public class ElastiCacheService implements ResourceProvider {
if (request.preferredMaintenanceWindow() != null && !request.preferredMaintenanceWindow().isBlank()) {
BackupWindows.parseMaintenanceWindow(request.preferredMaintenanceWindow());
}
requireCacheSubnetGroup(request.cacheSubnetGroupName());
requireCacheSubnetGroup(subnetGroups, request.cacheSubnetGroupName());
String parameterGroupReservation = reserveParameterGroup(request.cacheParameterGroupName());
try {
if (cacheClusterIdTaken(clusterId)) {
@@ -1285,7 +1285,7 @@ public class ElastiCacheService implements ResourceProvider {
* <p>{@code CreateReplicationGroup} does not make this check, so a replication group can
* still be created against a subnet group that is not there.
*/
private void requireCacheSubnetGroup(String name) {
static void requireCacheSubnetGroup(StorageBackend<String, CacheSubnetGroup> subnetGroups, String name) {
if (name == null || name.isBlank()) {
return;
}
@@ -2185,6 +2185,12 @@ public class ElastiCacheService implements ResourceProvider {
/** Replaces the description and, when subnets are given, the whole subnet set. */
public CacheSubnetGroup modifyCacheSubnetGroup(String name, String description, List<String> subnetIds) {
return modifyCacheSubnetGroup(name, description, subnetIds, null);
}
/** As above; a non-null {@code tags} replaces the stored tag map, an empty one clears it. */
public CacheSubnetGroup modifyCacheSubnetGroup(String name, String description, List<String> subnetIds,
Map<String, String> tags) {
validateSubnetGroupName(name);
synchronized (lockFor("sng:" + name)) {
CacheSubnetGroup existing = subnetGroups.get(name)
@@ -2201,7 +2207,7 @@ public class ElastiCacheService implements ResourceProvider {
} else {
updated = buildSubnetGroup(name, effectiveDescription, subnetIds);
}
updated.setTags(existing.getTags());
updated.setTags(tags != null ? tags : existing.getTags());
subnetGroups.put(name, updated);
return updated;
}
@@ -2214,6 +2220,16 @@ public class ElastiCacheService implements ResourceProvider {
throw new AwsException("CacheSubnetGroupNotFoundFault",
"Cache Subnet Group " + name + " does not exist.", 400);
}
boolean inUse = cacheClusters.scan(k -> true).stream()
.anyMatch(c -> name.equals(c.getCacheSubnetGroupName()))
|| memcachedClusters.scan(k -> true).stream()
.anyMatch(c -> name.equals(c.getCacheSubnetGroupName()))
|| groups.scan(k -> true).stream()
.anyMatch(g -> name.equals(g.getCacheSubnetGroupName()));
if (inUse) {
throw new AwsException("CacheSubnetGroupInUse",
"The requested cache subnet group is currently in use.", 400);
}
subnetGroups.delete(name);
}
LOG.infov("Deleted cache subnet group {0}", name);
@@ -56,6 +56,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.EcrCfnPro
import io.github.hectorvent.floci.services.cloudformation.provisioners.EcsCapacityCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.EcsCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.EksCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ElastiCacheCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ElbV2CfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.EventsArchiveCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.EventsCfnProvisioner;
@@ -114,6 +115,8 @@ import io.github.hectorvent.floci.services.ec2.FlowLogService;
import io.github.hectorvent.floci.services.ecr.EcrService;
import io.github.hectorvent.floci.services.ecs.EcsService;
import io.github.hectorvent.floci.services.eks.EksService;
import io.github.hectorvent.floci.services.elasticache.ElastiCacheMemcachedService;
import io.github.hectorvent.floci.services.elasticache.ElastiCacheService;
import io.github.hectorvent.floci.services.elbv2.ElbV2Service;
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
import io.github.hectorvent.floci.services.firehose.FirehoseService;
@@ -223,6 +226,8 @@ final class CfnProvisionerFixture {
private SqsService sqsService;
private WafV2Service wafV2Service;
private BackupService backupService;
private ElastiCacheService elastiCacheService;
private ElastiCacheMemcachedService elastiCacheMemcachedService;
private RedshiftService redshiftService;
private RedshiftServerlessService redshiftServerlessService;
private CloudMapService cloudMapService;
@@ -441,6 +446,9 @@ final class CfnProvisionerFixture {
if (transferService != null) {
discovered.add(new TransferCfnProvisioner(transferService));
}
if (elastiCacheService != null && elastiCacheMemcachedService != null) {
discovered.add(new ElastiCacheCfnProvisioner(elastiCacheService, elastiCacheMemcachedService));
}
if (redshiftService != null) {
discovered.add(new RedshiftClusterCfnProvisioner(redshiftService));
}
@@ -703,6 +711,17 @@ final class CfnProvisionerFixture {
return this;
}
/** The cache cluster provisioner needs both engines' services; name this and elastiCacheMemcached. */
public Builder elastiCache(ElastiCacheService s) {
this.elastiCacheService = s;
return this;
}
public Builder elastiCacheMemcached(ElastiCacheMemcachedService s) {
this.elastiCacheMemcachedService = s;
return this;
}
public Builder redshiftService(RedshiftService s) {
this.redshiftService = s;
return this;
@@ -0,0 +1,211 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.elasticache.ElastiCacheClient;
import software.amazon.awssdk.services.elasticache.model.CacheCluster;
import software.amazon.awssdk.services.elasticache.model.CacheSubnetGroupNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.util.concurrent.TimeUnit;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* Provisions the ElastiCache resource types through CloudFormation and checks them against the
* ElastiCache API. Output values are asserted, not only the stack status: an unmapped type is
* stubbed as CREATE_COMPLETE, and its Fn::GetAtt resolves to the literal "LogicalId.Attr".
*/
@QuarkusTest
class ElastiCacheCfnIntegrationTest {
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260903/us-east-1/cloudformation/aws4_request";
private static final String METADATA_STACK = "elasticache-cfn-metadata-it";
private static final String DATA_STACK = "elasticache-cfn-data-it";
private static final String METADATA_TEMPLATE = """
{
"Resources": {
"Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.71.0.0/16"}},
"Subnet": {"Type": "AWS::EC2::Subnet",
"Properties": {"VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.71.0.0/24"}},
"SubnetGroup": {"Type": "AWS::ElastiCache::SubnetGroup",
"Properties": {"CacheSubnetGroupName": "cfn-it-sng", "Description": "example",
"SubnetIds": [{"Ref": "Subnet"}]}}
},
"Outputs": {
"SubnetGroupRef": {"Value": {"Ref": "SubnetGroup"}}
}
}
""";
private static final String DATA_TEMPLATE = """
{
"Resources": {
"Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.72.0.0/16"}},
"Subnet": {"Type": "AWS::EC2::Subnet",
"Properties": {"VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.72.0.0/24"}},
"SubnetGroup": {"Type": "AWS::ElastiCache::SubnetGroup",
"Properties": {"Description": "example", "SubnetIds": [{"Ref": "Subnet"}]}},
"Cluster": {"Type": "AWS::ElastiCache::CacheCluster",
"Properties": {"ClusterName": "cfn-it-cluster", "Engine": "redis",
"CacheNodeType": "cache.t3.micro", "NumCacheNodes": 1,
"CacheSubnetGroupName": {"Ref": "SubnetGroup"}}}
},
"Outputs": {
"ClusterRef": {"Value": {"Ref": "Cluster"}},
"ClusterAddress": {"Value": {"Fn::GetAtt": ["Cluster", "RedisEndpoint.Address"]}},
"ClusterPort": {"Value": {"Fn::GetAtt": ["Cluster", "RedisEndpoint.Port"]}}
}
}
""";
private static final String UPDATE_TEMPLATE = """
{
"Resources": {
"Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.73.0.0/16"}},
"Subnet": {"Type": "AWS::EC2::Subnet",
"Properties": {"VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.73.0.0/24"}},
"SubnetGroup": {"Type": "AWS::ElastiCache::SubnetGroup",
"Properties": {"CacheSubnetGroupName": "@@SNG@@", "Description": "example",
"SubnetIds": [{"Ref": "Subnet"}]}}
},
"Outputs": {
"SubnetGroupRef": {"Value": {"Ref": "SubnetGroup"}}
}
}
""";
@TestHTTPResource
URI endpoint;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
private ElastiCacheClient client() {
return ElastiCacheClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test")))
.build();
}
@Test
void subnetGroupIsCreatedAndRemovedWithTheStack() {
cloudFormation(METADATA_STACK, "CreateStack", METADATA_TEMPLATE);
String stacks = describeStacks(METADATA_STACK, "CREATE_COMPLETE");
assertEquals("cfn-it-sng", outputValue(stacks, "SubnetGroupRef"));
try (ElastiCacheClient client = client()) {
assertEquals(1, client.describeCacheSubnetGroups(r -> r.cacheSubnetGroupName("cfn-it-sng"))
.cacheSubnetGroups().size());
cloudFormation(METADATA_STACK, "DeleteStack", null);
CfnStackWaits.awaitStackDeleted(METADATA_STACK);
assertThrows(CacheSubnetGroupNotFoundException.class,
() -> client.describeCacheSubnetGroups(r -> r.cacheSubnetGroupName("cfn-it-sng")));
}
}
@Test
void renamedSubnetGroupIsReplaced() {
String stack = "elasticache-cfn-update-it";
cloudFormation(stack, "CreateStack", UPDATE_TEMPLATE.replace("@@SNG@@", "cfn-it-upd-sng-a"));
describeStacks(stack, "CREATE_COMPLETE");
cloudFormation(stack, "UpdateStack", UPDATE_TEMPLATE.replace("@@SNG@@", "cfn-it-upd-sng-b"));
String stacks = describeStacks(stack, "UPDATE_COMPLETE");
assertEquals("cfn-it-upd-sng-b", outputValue(stacks, "SubnetGroupRef"));
try (ElastiCacheClient client = client()) {
assertThrows(CacheSubnetGroupNotFoundException.class,
() -> client.describeCacheSubnetGroups(r -> r.cacheSubnetGroupName("cfn-it-upd-sng-a")));
assertEquals(1, client.describeCacheSubnetGroups(r -> r.cacheSubnetGroupName("cfn-it-upd-sng-b"))
.cacheSubnetGroups().size());
}
cloudFormation(stack, "DeleteStack", null);
CfnStackWaits.awaitStackDeleted(stack);
}
@Test
void cacheClusterExposesEndpoints() throws Exception {
Assumptions.assumeTrue(dockerAvailable(), "Docker is required for the cache data plane");
cloudFormation(DATA_STACK, "CreateStack", DATA_TEMPLATE);
String stacks = describeStacks(DATA_STACK, "CREATE_COMPLETE");
assertEquals("cfn-it-cluster", outputValue(stacks, "ClusterRef"));
assertFalse(outputValue(stacks, "ClusterAddress").contains("Cluster.RedisEndpoint"),
"an unset attribute resolves to the literal LogicalId.Attr");
try (ElastiCacheClient client = client()) {
CacheCluster cluster = client.describeCacheClusters(r -> r.cacheClusterId("cfn-it-cluster").showCacheNodeInfo(true))
.cacheClusters().getFirst();
assertEquals(outputValue(stacks, "ClusterPort"),
String.valueOf(cluster.cacheNodes().getFirst().endpoint().port()));
}
cloudFormation(DATA_STACK, "DeleteStack", null);
CfnStackWaits.awaitStackDeleted(DATA_STACK);
}
private static boolean dockerAvailable() throws Exception {
Process process;
try {
process = new ProcessBuilder("docker", "info").redirectOutput(ProcessBuilder.Redirect.DISCARD)
.redirectError(ProcessBuilder.Redirect.DISCARD).start();
} catch (IOException expected) {
// Docker CLI is optional on development machines.
return false;
}
if (!process.waitFor(10, TimeUnit.SECONDS)) {
process.destroyForcibly();
return false;
}
return process.exitValue() == 0;
}
private static void cloudFormation(String stack, String action, String templateBody) {
RequestSpecification request = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", action)
.formParam("StackName", stack);
if (templateBody != null) {
request.formParam("TemplateBody", templateBody);
}
request.when().post("/").then().statusCode(200);
}
private static String describeStacks(String stack, String expectedStatus) {
return given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", stack)
.when().post("/").then().statusCode(200)
.body(containsString("<StackStatus>" + expectedStatus + "</StackStatus>"))
.extract().asString();
}
private static String outputValue(String xml, String key) {
return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get(key);
}
}
@@ -0,0 +1,403 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.elasticache.ElastiCacheMemcachedService;
import io.github.hectorvent.floci.services.elasticache.ElastiCacheService;
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.CacheClusterStatus;
import io.github.hectorvent.floci.services.elasticache.model.CacheSubnetGroup;
import io.github.hectorvent.floci.services.elasticache.model.Endpoint;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class ElastiCacheCfnProvisionerTest {
private final ObjectMapper mapper = new ObjectMapper();
private final ElastiCacheService cache = mock(ElastiCacheService.class);
private final ElastiCacheMemcachedService memcached = mock(ElastiCacheMemcachedService.class);
private final ElastiCacheCfnProvisioner provisioner = new ElastiCacheCfnProvisioner(cache, memcached);
private ProvisionContext ctx(String priorPhysicalId) {
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(inv -> {
JsonNode node = inv.getArgument(0);
return node == null ? null : node.asText();
});
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
when(engine.resolveStringList(any())).thenAnswer(inv -> {
JsonNode node = inv.getArgument(0);
List<String> values = new ArrayList<>();
if (node != null && node.isArray()) {
node.forEach(item -> values.add(item.asText()));
}
return values;
});
return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", priorPhysicalId);
}
private StackResource resource(String type, String logicalId) {
StackResource r = new StackResource();
r.setLogicalId(logicalId);
r.setResourceType(type);
r.setAttributes(new HashMap<>());
return r;
}
private ObjectNode props(String json) throws Exception {
return (ObjectNode) mapper.readTree(json);
}
@Test
void redisCacheClusterExposesRedisEndpointAttributes() throws Exception {
CacheCluster created = new CacheCluster("app-cache", CacheClusterStatus.AVAILABLE, "redis", "7.1",
new Endpoint("localhost", 6400), Instant.now());
when(cache.createCacheCluster(any())).thenReturn(created);
StackResource r = resource("AWS::ElastiCache::CacheCluster", "Cluster");
provisioner.provision(r, props("""
{"ClusterName":"app-cache","Engine":"redis","CacheNodeType":"cache.t3.micro","NumCacheNodes":1}
"""), ctx(null));
assertEquals("app-cache", r.getPhysicalId());
assertEquals("localhost", r.getAttributes().get("RedisEndpoint.Address"));
assertEquals("6400", r.getAttributes().get("RedisEndpoint.Port"));
ArgumentCaptor<ElastiCacheService.CreateCacheClusterRequest> request =
ArgumentCaptor.forClass(ElastiCacheService.CreateCacheClusterRequest.class);
verify(cache).createCacheCluster(request.capture());
assertEquals("cache.t3.micro", request.getValue().cacheNodeType());
assertEquals(1, request.getValue().numCacheNodes());
verify(memcached, never()).createCacheCluster(any());
}
@Test
void memcachedCacheClusterGoesToMemcachedServiceWithConfigurationEndpoint() throws Exception {
CacheCluster created = new CacheCluster("mc", CacheClusterStatus.AVAILABLE, "memcached", "1.6",
new Endpoint("localhost", 6410), Instant.now());
when(memcached.createCacheCluster(any())).thenReturn(created);
StackResource r = resource("AWS::ElastiCache::CacheCluster", "Mc");
provisioner.provision(r, props("""
{"ClusterName":"mc","Engine":"memcached","CacheNodeType":"cache.t3.micro","NumCacheNodes":1}
"""), ctx(null));
assertEquals("6410", r.getAttributes().get("ConfigurationEndpoint.Port"));
verify(cache, never()).createCacheCluster(any());
}
@Test
void missingCacheNodeTypeIsRejected() throws Exception {
StackResource r = resource("AWS::ElastiCache::CacheCluster", "Cluster");
assertThrows(AwsException.class, () -> provisioner.provision(r,
props("{\"Engine\":\"redis\",\"NumCacheNodes\":1}"), ctx(null)));
verify(cache, never()).createCacheCluster(any());
verify(memcached, never()).createCacheCluster(any());
}
@Test
void missingNumCacheNodesIsRejected() throws Exception {
StackResource r = resource("AWS::ElastiCache::CacheCluster", "Cluster");
assertThrows(AwsException.class, () -> provisioner.provision(r,
props("{\"Engine\":\"redis\",\"CacheNodeType\":\"cache.t3.micro\"}"), ctx(null)));
verify(cache, never()).createCacheCluster(any());
verify(memcached, never()).createCacheCluster(any());
}
@Test
void missingSubnetGroupDescriptionIsRejected() throws Exception {
StackResource r = resource("AWS::ElastiCache::SubnetGroup", "Sng");
assertThrows(AwsException.class, () -> provisioner.provision(r,
props("{\"CacheSubnetGroupName\":\"my-sng\",\"SubnetIds\":[\"s-1\"]}"), ctx(null)));
verify(cache, never()).createCacheSubnetGroup(any(), any(), any(), any());
}
@Test
void oversizedClusterNameIsRejected() throws Exception {
String longName = "c".repeat(51);
StackResource r = resource("AWS::ElastiCache::CacheCluster", "Cluster");
assertThrows(AwsException.class, () -> provisioner.provision(r,
props("{\"ClusterName\":\"" + longName + "\",\"Engine\":\"redis\",\"CacheNodeType\":\"cache.t3.micro\",\"NumCacheNodes\":1}"),
ctx(null)));
verify(cache, never()).createCacheCluster(any());
}
@Test
void oversizedSubnetGroupNameIsRejected() throws Exception {
String longName = "s".repeat(256);
StackResource r = resource("AWS::ElastiCache::SubnetGroup", "Sng");
assertThrows(AwsException.class, () -> provisioner.provision(r,
props("{\"CacheSubnetGroupName\":\"" + longName + "\",\"Description\":\"d\",\"SubnetIds\":[\"s-1\"]}"),
ctx(null)));
verify(cache, never()).createCacheSubnetGroup(any(), any(), any(), any());
}
@Test
void cacheClusterWithoutNameGetsLowercaseGeneratedId() throws Exception {
when(cache.createCacheCluster(any())).thenAnswer(inv -> {
ElastiCacheService.CreateCacheClusterRequest req = inv.getArgument(0);
return new CacheCluster(req.cacheClusterId(), CacheClusterStatus.AVAILABLE, "redis", "7.1",
new Endpoint("localhost", 6400), Instant.now());
});
StackResource r = resource("AWS::ElastiCache::CacheCluster", "MyCluster");
provisioner.provision(r, props("{\"Engine\":\"redis\",\"CacheNodeType\":\"cache.t3.micro\",\"NumCacheNodes\":1}"), ctx(null));
assertEquals(r.getPhysicalId().toLowerCase(), r.getPhysicalId());
assertEquals(true, r.getPhysicalId().length() <= 50);
}
@Test
void cacheClusterUpdateWithSameNameDoesNotCreateAgain() throws Exception {
CacheCluster existing = new CacheCluster("app-cache", CacheClusterStatus.AVAILABLE, "redis", "7.1",
new Endpoint("localhost", 6400), Instant.now());
when(cache.findCacheClusters("app-cache")).thenReturn(List.of(existing));
StackResource r = resource("AWS::ElastiCache::CacheCluster", "Cluster");
provisioner.provision(r, props("{\"ClusterName\":\"app-cache\",\"Engine\":\"redis\",\"CacheNodeType\":\"cache.t3.micro\",\"NumCacheNodes\":1}"),
ctx("app-cache"));
verify(cache, never()).createCacheCluster(any());
assertEquals("6400", r.getAttributes().get("RedisEndpoint.Port"));
}
@Test
void explicitClusterNameWithChangedEngineIsRejectedOnUpdate() throws Exception {
CacheCluster existing = new CacheCluster("app-cache", CacheClusterStatus.AVAILABLE, "redis", "7.1",
new Endpoint("localhost", 6400), Instant.now());
when(cache.findCacheClusters("app-cache")).thenReturn(List.of(existing));
StackResource r = resource("AWS::ElastiCache::CacheCluster", "Cluster");
assertThrows(AwsException.class, () -> provisioner.provision(r,
props("{\"ClusterName\":\"app-cache\",\"Engine\":\"valkey\",\"CacheNodeType\":\"cache.t3.micro\",\"NumCacheNodes\":1}"), ctx("app-cache")));
}
@Test
void unnamedClusterWithChangedEngineIsReplacedUnderANewId() throws Exception {
CacheCluster existing = new CacheCluster("old-id", CacheClusterStatus.AVAILABLE, "redis", "7.1",
new Endpoint("localhost", 6400), Instant.now());
when(cache.findCacheClusters("old-id")).thenReturn(List.of(existing));
when(cache.createCacheCluster(any())).thenAnswer(inv -> {
ElastiCacheService.CreateCacheClusterRequest req = inv.getArgument(0);
return new CacheCluster(req.cacheClusterId(), CacheClusterStatus.AVAILABLE, "valkey", "8.0",
new Endpoint("localhost", 6401), Instant.now());
});
StackResource r = resource("AWS::ElastiCache::CacheCluster", "Cluster");
provisioner.provision(r, props("{\"Engine\":\"valkey\",\"CacheNodeType\":\"cache.t3.micro\",\"NumCacheNodes\":1}"), ctx("old-id"));
assertNotEquals("old-id", r.getPhysicalId());
assertEquals("6401", r.getAttributes().get("RedisEndpoint.Port"));
}
@Test
void engineSwitchCleansUpDisplacedEndpointAttributes() throws Exception {
CacheCluster existingRedis = new CacheCluster("cluster-1", CacheClusterStatus.AVAILABLE, "redis", "7.1",
new Endpoint("localhost", 6400), Instant.now());
when(cache.findCacheClusters("cluster-1")).thenReturn(List.of(existingRedis));
CacheCluster replacementMemcached = new CacheCluster("cluster-2", CacheClusterStatus.AVAILABLE,
"memcached", "1.6", new Endpoint("localhost", 6410), Instant.now());
when(memcached.createCacheCluster(any())).thenReturn(replacementMemcached);
StackResource r = resource("AWS::ElastiCache::CacheCluster", "Cluster");
r.getAttributes().put("RedisEndpoint.Address", "localhost");
r.getAttributes().put("RedisEndpoint.Port", "6400");
provisioner.provision(r, props("""
{"Engine":"memcached","CacheNodeType":"cache.t3.micro","NumCacheNodes":1}
"""), ctx("cluster-1"));
assertEquals("6410", r.getAttributes().get("ConfigurationEndpoint.Port"));
assertEquals("localhost", r.getAttributes().get("ConfigurationEndpoint.Address"));
assertNull(r.getAttributes().get("RedisEndpoint.Address"));
assertNull(r.getAttributes().get("RedisEndpoint.Port"));
}
@Test
void subnetGroupUsesNameAsPhysicalId() throws Exception {
CacheSubnetGroup group =
mock(CacheSubnetGroup.class);
when(group.getName()).thenReturn("my-sng");
when(cache.createCacheSubnetGroup(eq("my-sng"), eq("d"), eq(List.of("subnet-1")), any())).thenReturn(group);
StackResource r = resource("AWS::ElastiCache::SubnetGroup", "Sng");
provisioner.provision(r, props("""
{"CacheSubnetGroupName":"my-sng","Description":"d","SubnetIds":["subnet-1"]}
"""), ctx(null));
assertEquals("my-sng", r.getPhysicalId());
}
@Test
void transitEncryptionDoesNotTurnOnIamAuthentication() throws Exception {
when(cache.createCacheCluster(any())).thenReturn(new CacheCluster("tls", CacheClusterStatus.AVAILABLE,
"redis", "7.1", new Endpoint("localhost", 6400), Instant.now()));
StackResource r = resource("AWS::ElastiCache::CacheCluster", "Tls");
provisioner.provision(r, props("{\"ClusterName\":\"tls\",\"Engine\":\"redis\",\"CacheNodeType\":\"cache.t3.micro\",\"NumCacheNodes\":1,\"TransitEncryptionEnabled\":true}"),
ctx(null));
ArgumentCaptor<ElastiCacheService.CreateCacheClusterRequest> request =
ArgumentCaptor.forClass(ElastiCacheService.CreateCacheClusterRequest.class);
verify(cache).createCacheCluster(request.capture());
assertEquals(AuthMode.NO_AUTH, request.getValue().authMode());
}
@Test
void memcachedClusterWithUnchangedNetworkTypeIsNotReplaced() throws Exception {
CacheCluster existing = new CacheCluster("mc", CacheClusterStatus.AVAILABLE, "memcached", "1.6",
new Endpoint("localhost", 6410), Instant.now());
when(cache.findCacheClusters("mc")).thenReturn(List.of());
when(memcached.getCacheCluster("mc")).thenReturn(existing);
StackResource r = resource("AWS::ElastiCache::CacheCluster", "Mc");
provisioner.provision(r, props("{\"ClusterName\":\"mc\",\"Engine\":\"memcached\",\"CacheNodeType\":\"cache.t3.micro\",\"NumCacheNodes\":1,\"NetworkType\":\"ipv4\"}"),
ctx("mc"));
verify(memcached, never()).createCacheCluster(any());
assertEquals("mc", r.getPhysicalId());
}
@Test
void removingANonDefaultNetworkTypeReplacesAnUnnamedCluster() throws Exception {
CacheCluster existing = new CacheCluster("old-id", CacheClusterStatus.AVAILABLE, "redis", "7.1",
new Endpoint("localhost", 6400), Instant.now());
existing.setNetworkType("dual_stack");
when(cache.findCacheClusters("old-id")).thenReturn(List.of(existing));
when(cache.createCacheCluster(any())).thenAnswer(inv -> {
ElastiCacheService.CreateCacheClusterRequest req = inv.getArgument(0);
return new CacheCluster(req.cacheClusterId(), CacheClusterStatus.AVAILABLE, "redis", "7.1",
new Endpoint("localhost", 6401), Instant.now());
});
StackResource r = resource("AWS::ElastiCache::CacheCluster", "Cluster");
provisioner.provision(r, props("{\"Engine\":\"redis\",\"CacheNodeType\":\"cache.t3.micro\",\"NumCacheNodes\":1}"), ctx("old-id"));
assertNotEquals("old-id", r.getPhysicalId());
verify(cache).createCacheCluster(any());
}
@Test
void subnetGroupUpdatePassesTheDesiredTags() throws Exception {
CacheSubnetGroup group = mock(CacheSubnetGroup.class);
when(group.getName()).thenReturn("my-sng");
when(cache.modifyCacheSubnetGroup(eq("my-sng"), any(), any(), any())).thenReturn(group);
StackResource r = resource("AWS::ElastiCache::SubnetGroup", "Sng");
provisioner.provision(r, props("{\"CacheSubnetGroupName\":\"my-sng\",\"Description\":\"d\",\"SubnetIds\":[\"s-1\"]}"),
ctx("my-sng"));
verify(cache).modifyCacheSubnetGroup("my-sng", "d", List.of("s-1"), Map.of());
}
@Test
void rollbackHookRestoresPriorSubnetGroupConfigurationAfterLaterResourceFails() throws Exception {
CacheSubnetGroup existing = mock(CacheSubnetGroup.class);
when(existing.getName()).thenReturn("my-sng");
when(existing.getDescription()).thenReturn("old-desc");
when(existing.getSubnetAvailabilityZones()).thenReturn(Map.of("subnet-1", "us-east-1a"));
when(existing.getTags()).thenReturn(Map.of("env", "old"));
when(cache.describeCacheSubnetGroups("my-sng")).thenReturn(List.of(existing));
CacheSubnetGroup modified = mock(CacheSubnetGroup.class);
when(modified.getName()).thenReturn("my-sng");
when(cache.modifyCacheSubnetGroup(eq("my-sng"), eq("new-desc"), eq(List.of("subnet-2")), any()))
.thenReturn(modified);
StackResource r = resource("AWS::ElastiCache::SubnetGroup", "Sng");
provisioner.provision(r, props("""
{"CacheSubnetGroupName":"my-sng","Description":"new-desc","SubnetIds":["subnet-2"]}
"""), ctx("my-sng"));
assertTrue(provisioner.rollbackUpdate(r));
verify(cache).modifyCacheSubnetGroup("my-sng", "old-desc", List.of("subnet-1"), Map.of("env", "old"));
}
@Test
void committedSubnetGroupUpdateClearsRollbackSnapshot() {
StackResource r = resource("AWS::ElastiCache::SubnetGroup", "Sng");
r.getAttributes().put("__FlociCacheSubnetGroupUpdateSnapshot", "snapshot-data");
r.setStatus("UPDATE_COMPLETE");
UpdateCleanupResult result = provisioner.completeUpdate(r);
assertFalse(result.applicable());
assertNull(r.getAttributes().get("__FlociCacheSubnetGroupUpdateSnapshot"));
}
@Test
void clusterDeletedOutsideTheStackIsRecreatedOnUpdate() throws Exception {
when(cache.findCacheClusters("app-cache")).thenReturn(List.of());
when(memcached.getCacheCluster("app-cache")).thenThrow(new AwsException("CacheClusterNotFound", "gone", 404));
when(cache.createCacheCluster(any())).thenReturn(new CacheCluster("app-cache", CacheClusterStatus.AVAILABLE,
"redis", "7.1", new Endpoint("localhost", 6402), Instant.now()));
StackResource r = resource("AWS::ElastiCache::CacheCluster", "Cluster");
provisioner.provision(r, props("{\"ClusterName\":\"app-cache\",\"Engine\":\"redis\",\"CacheNodeType\":\"cache.t3.micro\",\"NumCacheNodes\":1}"), ctx("app-cache"));
verify(cache).createCacheCluster(any());
assertEquals("6402", r.getAttributes().get("RedisEndpoint.Port"));
}
@Test
void renamedSubnetGroupReplacesAndDeletesTheOldOneAfterTheUpdate() throws Exception {
CacheSubnetGroup created = mock(CacheSubnetGroup.class);
when(created.getName()).thenReturn("new-sng");
when(cache.createCacheSubnetGroup(eq("new-sng"), any(), any(), any())).thenReturn(created);
StackResource r = resource("AWS::ElastiCache::SubnetGroup", "Sng");
provisioner.provision(r, props("{\"CacheSubnetGroupName\":\"new-sng\",\"Description\":\"d\",\"SubnetIds\":[\"s-1\"]}"),
ctx("old-sng"));
assertTrue(provisioner.hasReplacementUpdate(r));
assertEquals("old-sng", provisioner.updateCleanupPhysicalId(r));
provisioner.completeUpdate(r);
verify(cache).deleteCacheSubnetGroup("old-sng");
}
@Test
void deleteToleratesAlreadyDeletedButPropagatesOtherFailures() {
doThrow(new AwsException("CacheSubnetGroupNotFoundFault", "gone", 400))
.when(cache).deleteCacheSubnetGroup("gone");
provisioner.delete("AWS::ElastiCache::SubnetGroup", "gone", "us-east-1");
doThrow(new AwsException("CacheSubnetGroupInUse", "busy", 400))
.when(cache).deleteCacheSubnetGroup("busy");
assertThrows(AwsException.class,
() -> provisioner.delete("AWS::ElastiCache::SubnetGroup", "busy", "us-east-1"));
}
@Test
void memcachedClusterRejectsNonexistentSubnetGroup() throws Exception {
when(memcached.createCacheCluster(any())).thenThrow(new AwsException("CacheSubnetGroupNotFoundFault", "not found", 400));
StackResource r = resource("AWS::ElastiCache::CacheCluster", "Mc");
assertThrows(AwsException.class, () -> provisioner.provision(r,
props("""
{"ClusterName":"mc","Engine":"memcached","CacheNodeType":"cache.t3.micro","NumCacheNodes":1,"CacheSubnetGroupName":"missing-sng"}
"""), ctx(null)));
}
}
@@ -4,11 +4,13 @@ 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;
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.CacheSubnetGroup;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -38,6 +40,7 @@ class ElastiCacheMemcachedServiceTest {
private ElastiCacheMemcachedService service;
private ElastiCacheMemcachedContainerManager containerManager;
private ElastiCacheProvisioningIds provisioningIds;
private AccountAwareStorageBackend<CacheSubnetGroup> subnetGroups;
@BeforeEach
void setUp() {
@@ -53,7 +56,9 @@ class ElastiCacheMemcachedServiceTest {
when(ecConfig.defaultMemcachedImage()).thenReturn("memcached:1.6");
when(config.hostname()).thenReturn(Optional.of("localhost"));
subnetGroups = AccountAwareStorageBackend.inMemory("000000000000");
when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000"));
when(storageFactory.create(eq("elasticache"), eq("elasticache-subnet-groups.json"), any())).thenAnswer(inv -> subnetGroups);
when(containerManager.tryStart(anyString(), anyString(), any()))
.thenReturn(new ElastiCacheContainerHandle("cid", "cluster", "localhost", 11211));
@@ -73,6 +78,10 @@ class ElastiCacheMemcachedServiceTest {
@Test
void createClusterStoresWhatTheRequestSetForTheDescribe() {
CacheSubnetGroup subnetGroup = new CacheSubnetGroup();
subnetGroup.setName("my-subnets");
subnetGroups.put("my-subnets", subnetGroup);
service.createCacheCluster(new ElastiCacheService.CreateCacheClusterRequest(
"sized", "memcached", null, "cache.m5.large", 3, null, null, null,
"default.memcached1.6", "my-subnets", null, null, null, "us-east-1c",
@@ -89,6 +98,33 @@ class ElastiCacheMemcachedServiceTest {
assertEquals("arn:aws:elasticache:us-east-1:000000000000:cluster:sized", stored.getArn());
}
@Test
void createClusterWithNonexistentSubnetGroupThrows() {
ElastiCacheService.CreateCacheClusterRequest req = new ElastiCacheService.CreateCacheClusterRequest(
"missing-subnets", "memcached", null, null, null, null, null, null,
null, "nonexistent-subnets", null, null, null, null, null, null, null, null,
"us-east-1", null);
AwsException ex = assertThrows(AwsException.class, () -> service.createCacheCluster(req));
assertEquals("CacheSubnetGroupNotFoundFault", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
}
@Test
void createClusterPreservesTags() {
Map<String, String> tags = Map.of("env", "prod", "team", "backend");
ElastiCacheService.CreateCacheClusterRequest req = new ElastiCacheService.CreateCacheClusterRequest(
"tagged-cluster", "memcached", null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null,
"us-east-1", tags);
CacheCluster created = service.createCacheCluster(req);
assertEquals(tags, created.getTags());
CacheCluster stored = service.getCacheCluster("tagged-cluster");
assertEquals(tags, stored.getTags());
}
@Test
void createClusterDefaultsToOneNodeOfADefaultType() {
service.createCacheCluster(request("plain"));
@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
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;
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheMemcachedContainerManager;
@@ -2105,8 +2106,7 @@ class ElastiCacheServiceTest {
@Test
void aKnownCacheSubnetGroupIsAcceptedAndReported() {
io.github.hectorvent.floci.services.ec2.model.Subnet subnet =
new io.github.hectorvent.floci.services.ec2.model.Subnet();
Subnet subnet = new Subnet();
subnet.setSubnetId("subnet-1");
subnet.setVpcId("vpc-1");
subnet.setAvailabilityZone("us-east-1a");
@@ -2121,6 +2121,58 @@ class ElastiCacheServiceTest {
assertEquals("real-group", cluster.getCacheSubnetGroupName());
}
@Test
void deleteCacheSubnetGroupInUseByClusterThrows() {
Subnet subnet = new Subnet();
subnet.setSubnetId("subnet-1");
subnet.setVpcId("vpc-1");
subnet.setAvailabilityZone("us-east-1a");
when(ec2Service.describeSubnets(anyString(), any(), any())).thenReturn(List.of(subnet));
service.createCacheSubnetGroup("used-group", "d", List.of("subnet-1"), Map.of());
service.createCacheCluster(new ElastiCacheService.CreateCacheClusterRequest(
"sng-cluster", "redis", null, null, 1, null, AuthMode.NO_AUTH, null, null,
"used-group", null, null, null, null, null, null, null, null,
"us-east-1", Map.of()));
AwsException ex = assertThrows(AwsException.class, () -> service.deleteCacheSubnetGroup("used-group"));
assertEquals("CacheSubnetGroupInUse", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
}
@Test
void deleteCacheSubnetGroupInUseByReplicationGroupThrows() {
Subnet subnet = new Subnet();
subnet.setSubnetId("subnet-1");
subnet.setVpcId("vpc-1");
subnet.setAvailabilityZone("us-east-1a");
when(ec2Service.describeSubnets(anyString(), any(), any())).thenReturn(List.of(subnet));
service.createCacheSubnetGroup("rg-used-group", "d", List.of("subnet-1"), Map.of());
service.createReplicationGroup(new ElastiCacheService.CreateReplicationGroupRequest(
"rg-cluster", "desc", AuthMode.NO_AUTH, null, "us-east-1", null, null, null,
null, "rg-used-group", null, null, null, null, null, null, null,
ReplicationGroupSettings.defaults(), Map.of(), null));
AwsException ex = assertThrows(AwsException.class, () -> service.deleteCacheSubnetGroup("rg-used-group"));
assertEquals("CacheSubnetGroupInUse", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
}
@Test
void deleteCacheSubnetGroupNotInUseSucceeds() {
Subnet subnet = new Subnet();
subnet.setSubnetId("subnet-1");
subnet.setVpcId("vpc-1");
subnet.setAvailabilityZone("us-east-1a");
when(ec2Service.describeSubnets(anyString(), any(), any())).thenReturn(List.of(subnet));
service.createCacheSubnetGroup("free-group", "d", List.of("subnet-1"), Map.of());
service.deleteCacheSubnetGroup("free-group");
assertThrows(AwsException.class, () -> service.describeCacheSubnetGroups("free-group"));
}
@Test
void aCacheClusterCreatedWithoutDockerStillReachesAvailable() {
when(containerManager.tryStart(anyString(), anyString(), any())).thenReturn(null);
@@ -53,6 +53,8 @@ AWS::SecretsManager::Secret Id Fn::GetAtt Id on a secret is its ARN, which the p
AWS::EKS::Cluster ClusterSecurityGroupId not modeled: Floci does not create a cluster security group, so there is no id to publish
AWS::EKS::Cluster EncryptionConfigKeyArn not modeled: Floci does not apply envelope encryption, so no KMS key arn is resolved
AWS::EKS::Cluster Id not modeled: Floci identifies a cluster by its Name (the primary identifier and Ref), not a separate Id
AWS::ElastiCache::CacheCluster ConfigurationEndpoint the whole object has no scalar GetAtt form; its members are set under the dotted ConfigurationEndpoint.* attributes, the form AWS GetAtt exposes (memcached only)
AWS::ElastiCache::CacheCluster RedisEndpoint the whole object has no scalar GetAtt form; its members are set under the dotted RedisEndpoint.* attributes, the form AWS GetAtt exposes (redis and valkey only)
AWS::IAM::Policy Id not published: Floci uses the policy name for Ref, AWS returns an opaque generated identifier that Floci does not model
AWS::IAM::ManagedPolicy AttachmentCount not published: the attachment count is dynamic and Floci does not expose it as a stable Fn::GetAtt value
AWS::IAM::ManagedPolicy CreateDate not published: Floci does not surface the policy create date as an Fn::GetAtt value
1 AWS::AppSync::GraphQLApi GraphQLEndpointArn the private-endpoint ARN of the GraphQL endpoint; Floci serves one public endpoint and has no private-endpoint model
53 AWS::EKS::Cluster ClusterSecurityGroupId not modeled: Floci does not create a cluster security group, so there is no id to publish
54 AWS::EKS::Cluster EncryptionConfigKeyArn not modeled: Floci does not apply envelope encryption, so no KMS key arn is resolved
55 AWS::EKS::Cluster Id not modeled: Floci identifies a cluster by its Name (the primary identifier and Ref), not a separate Id
56 AWS::ElastiCache::CacheCluster ConfigurationEndpoint the whole object has no scalar GetAtt form; its members are set under the dotted ConfigurationEndpoint.* attributes, the form AWS GetAtt exposes (memcached only)
57 AWS::ElastiCache::CacheCluster RedisEndpoint the whole object has no scalar GetAtt form; its members are set under the dotted RedisEndpoint.* attributes, the form AWS GetAtt exposes (redis and valkey only)
58 AWS::IAM::Policy Id not published: Floci uses the policy name for Ref, AWS returns an opaque generated identifier that Floci does not model
59 AWS::IAM::ManagedPolicy AttachmentCount not published: the attachment count is dynamic and Floci does not expose it as a stable Fn::GetAtt value
60 AWS::IAM::ManagedPolicy CreateDate not published: Floci does not surface the policy create date as an Fn::GetAtt value
@@ -83,6 +83,8 @@ AWS::ECS::Service EcsCfnProvisioner
AWS::ECS::TaskDefinition EcsCfnProvisioner
AWS::EKS::Cluster EksCfnProvisioner
AWS::EKS::Nodegroup EksCfnProvisioner
AWS::ElastiCache::CacheCluster ElastiCacheCfnProvisioner
AWS::ElastiCache::SubnetGroup ElastiCacheCfnProvisioner
AWS::ElasticLoadBalancingV2::Listener ElbV2CfnProvisioner
AWS::ElasticLoadBalancingV2::ListenerRule ElbV2CfnProvisioner
AWS::ElasticLoadBalancingV2::LoadBalancer ElbV2CfnProvisioner
1 AWS::ApiGateway::Account ApiGatewayAccountCfnProvisioner
83 AWS::ECS::TaskDefinition EcsCfnProvisioner
84 AWS::EKS::Cluster EksCfnProvisioner
85 AWS::EKS::Nodegroup EksCfnProvisioner
86 AWS::ElastiCache::CacheCluster ElastiCacheCfnProvisioner
87 AWS::ElastiCache::SubnetGroup ElastiCacheCfnProvisioner
88 AWS::ElasticLoadBalancingV2::Listener ElbV2CfnProvisioner
89 AWS::ElasticLoadBalancingV2::ListenerRule ElbV2CfnProvisioner
90 AWS::ElasticLoadBalancingV2::LoadBalancer ElbV2CfnProvisioner
+5
View File
@@ -24,6 +24,7 @@ order:
- AWS::ECS
- AWS::EKS
- AWS::RDS
- AWS::ElastiCache
- AWS::Redshift
- AWS::RedshiftServerless
- AWS::EC2
@@ -84,6 +85,8 @@ type_order:
AWS::EKS: [Cluster, Nodegroup]
AWS::RDS:
[DBInstance, DBCluster, DBSubnetGroup, DBParameterGroup, DBClusterParameterGroup]
AWS::ElastiCache:
[CacheCluster, SubnetGroup]
AWS::Redshift:
[Cluster, ClusterParameterGroup, ClusterSubnetGroup, ClusterSecurityGroup]
AWS::RedshiftServerless:
@@ -137,6 +140,7 @@ service_labels:
AWS::KinesisFirehose: Kinesis Data Firehose
AWS::Lambda: Lambda
AWS::Logs: CloudWatch Logs
AWS::ElastiCache: ElastiCache
AWS::Organizations: Organizations
AWS::Pipes: Pipes
AWS::RDS: RDS
@@ -165,6 +169,7 @@ notes:
AWS::EC2::SecurityGroup: inline `SecurityGroupIngress`/`SecurityGroupEgress` supported
AWS::RDS::DBInstance: starts a real container
AWS::RDS::DBCluster: starts a real container
AWS::ElastiCache::CacheCluster: 'starts a real container; modifying an existing cluster in place is not supported'
AWS::Redshift::ClusterSecurityGroup: accepted; no EC2-Classic security group model
AWS::Redshift::Cluster: single-node container; Port and non-dev DBName ignored; ManageMasterPassword unsupported
AWS::RedshiftServerless::Namespace: 'ManageAdminPassword is accepted and not applied; GetAtt uses the dotted Namespace.* form'