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

@@ -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);