diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 22e5712682..0e0178e9f6 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -159,7 +159,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`, `User` (Tags are ignored), `UserGroup` (Tags are ignored) | +| ElastiCache | `CacheCluster` (starts a real container; modifying an existing cluster in place is not supported), `SubnetGroup`, `User` (Tags are ignored), `UserGroup` (Tags are ignored), `ServerlessCache` (GetAtt uses the dotted Endpoint.* and ReaderEndpoint.* form) | | 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` | diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnExceptions.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnExceptions.java new file mode 100644 index 0000000000..3dfe3c4421 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnExceptions.java @@ -0,0 +1,21 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import io.github.hectorvent.floci.core.common.AwsException; + +/** + * Exceptions shared by extracted CloudFormation resource provisioners. + */ +public final class CfnExceptions { + + private CfnExceptions() { + } + + /** + * Thrown when an update requires replacing a custom-named resource that kept its name. + */ + public static AwsException customNamedReplacement(String name) { + return new AwsException("ValidationError", + "CloudFormation cannot update a stack when a custom-named resource requires replacing. " + + "Rename " + name + " and update the stack again.", 400); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java index 1d747ad8c3..8c0d85c87c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java @@ -200,6 +200,13 @@ public final class CfnRollback { */ public static final String COGNITO_UPDATE_SNAPSHOT_ATTR = "__FlociCognitoUpdateSnapshot"; + /** + * Holds the settings and tags a serverless cache had before an in-place update changed them, + * so a failed stack update can put them back. Written by {@code ElastiCacheServerlessCfnProvisioner} + * before its modify call and spent by its {@code rollbackUpdate}. + */ + public static final String SERVERLESS_CACHE_UPDATE_SNAPSHOT_ATTR = "__FlociServerlessCacheUpdateSnapshot"; + /** * Holds the configuration an Auto Scaling group carried before an in-place update changed it, * so a failed stack update can restore it. diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoUserPoolUserToGroupAttachmentCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoUserPoolUserToGroupAttachmentCfnProvisioner.java index 49cd3487a2..66f6c76755 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoUserPoolUserToGroupAttachmentCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoUserPoolUserToGroupAttachmentCfnProvisioner.java @@ -62,9 +62,7 @@ public class CognitoUserPoolUserToGroupAttachmentCfnProvisioner implements CfnRe if (ctx.reusesPriorEntity(physicalId)) { JsonNode prior = memberships(attributesBefore).get(physicalId); if (prior != null && !prior.equals(membership)) { - throw new AwsException("ValidationError", - "CloudFormation cannot update a stack when a custom-named resource requires replacing. Rename " - + physicalId + " and update the stack again.", 400); + throw CfnExceptions.customNamedReplacement(physicalId); } } else { String member = cognitoService.adminGetUser(userPoolId, username).getUsername(); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElastiCacheCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElastiCacheCfnProvisioner.java index e312e2d5a2..c53c1a07aa 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElastiCacheCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElastiCacheCfnProvisioner.java @@ -433,7 +433,14 @@ public class ElastiCacheCfnProvisioner implements CfnResourceProvisioner { if (passwords.isEmpty()) { passwords = ctx.resolveStringList(props, "Passwords"); } - boolean noPasswordRequired = Boolean.parseBoolean(ctx.resolveOptional(props, "NoPasswordRequired")); + String noPasswordFlag = ctx.resolveOptional(props, "NoPasswordRequired"); + // parseBoolean reads every unrecognised value as false, which would hide a malformed template. + if (noPasswordFlag != null && !noPasswordFlag.isBlank() + && !"true".equalsIgnoreCase(noPasswordFlag) && !"false".equalsIgnoreCase(noPasswordFlag)) { + throw new AwsException("ValidationException", + "NoPasswordRequired must be true or false, got: " + noPasswordFlag, 400); + } + boolean noPasswordRequired = Boolean.parseBoolean(noPasswordFlag); return UserAuthentication.resolve(type, passwords, noPasswordRequired); } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElastiCacheServerlessCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElastiCacheServerlessCfnProvisioner.java new file mode 100644 index 0000000000..8bb9f6997a --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElastiCacheServerlessCfnProvisioner.java @@ -0,0 +1,309 @@ +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 com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.elasticache.ElastiCacheServerlessService; +import io.github.hectorvent.floci.services.elasticache.model.Endpoint; +import io.github.hectorvent.floci.services.elasticache.model.ServerlessCache; +import io.github.hectorvent.floci.services.elasticache.model.ServerlessCache.CacheUsageLimits; +import io.github.hectorvent.floci.services.elasticache.model.ServerlessCache.DataStorage; +import io.github.hectorvent.floci.services.elasticache.model.ServerlessCache.EcpuPerSecond; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +/** Provisions AWS::ElastiCache::ServerlessCache. Injects only ElastiCacheServerlessService. */ +@ApplicationScoped +public class ElastiCacheServerlessCfnProvisioner implements CfnResourceProvisioner { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String SERVERLESS_CACHE = "AWS::ElastiCache::ServerlessCache"; + private static final String CREATE_ONLY_ATTR = "__FlociCreateOnly"; + + private final ElastiCacheServerlessService serverlessService; + + @Inject + public ElastiCacheServerlessCfnProvisioner(ElastiCacheServerlessService serverlessService) { + this.serverlessService = serverlessService; + } + + @Override + public Set resourceTypes() { + return Set.of(SERVERLESS_CACHE); + } + + @Override + public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { + Map attributesBefore = Map.copyOf(r.getAttributes()); + String name = ctx.resolveOptional(props, "ServerlessCacheName"); + String engine = ctx.resolveOptional(props, "Engine"); + if (name == null || name.isBlank() || engine == null || engine.isBlank()) { + throw new AwsException("ValidationException", "ServerlessCacheName and Engine are required", 400); + } + // The service stores the name in lowercase, so the prior physical id only matches in that form. + name = name.toLowerCase(Locale.ROOT); + ServerlessCache cache; + if (ctx.reusesPriorEntity(name)) { + cache = modify(r, name, props, ctx); + } else { + cache = create(name, engine, props, ctx); + } + + r.setPhysicalId(cache.getServerlessCacheName()); + r.getAttributes().put("ARN", cache.getArn()); + r.getAttributes().put("Status", cache.getStatus()); + if (cache.getFullEngineVersion() != null) { + r.getAttributes().put("FullEngineVersion", cache.getFullEngineVersion()); + } + if (cache.getCreateTime() != null) { + r.getAttributes().put("CreateTime", cache.getCreateTime().toString()); + } + putEndpoint(r, "Endpoint", cache.getEndpoint()); + putEndpoint(r, "ReaderEndpoint", cache.getReaderEndpoint()); + r.getAttributes().put(CREATE_ONLY_ATTR, createOnlyRecord(props, ctx).toString()); + ReplacementCleanup.record(r, ctx, attributesBefore); + } + + private ServerlessCache create(String name, String engine, JsonNode props, ProvisionContext ctx) { + List subnetIds = ctx.resolveStringList(props, "SubnetIds"); + List securityGroupIds = ctx.resolveStringList(props, "SecurityGroupIds"); + List snapshotArns = ctx.resolveStringList(props, "SnapshotArnsToRestore"); + return serverlessService.createServerlessCache(new ElastiCacheServerlessService.CreateServerlessCacheRequest( + name, + engine, + ctx.resolveOptional(props, "MajorEngineVersion"), + ctx.resolveOptional(props, "Description"), + subnetIds.isEmpty() ? null : subnetIds, + securityGroupIds.isEmpty() ? null : securityGroupIds, + ctx.resolveOptional(props, "UserGroupId"), + ctx.resolveOptional(props, "KmsKeyId"), + usageLimits(props, ctx), + optionalInt(ctx.resolveOptional(props, "SnapshotRetentionLimit")), + ctx.resolveOptional(props, "DailySnapshotTime"), + snapshotArns.isEmpty() ? null : snapshotArns, + ctx.resolveTags(props, "Tags"))); + } + + private ServerlessCache modify(StackResource r, String name, JsonNode props, ProvisionContext ctx) { + ServerlessCache existing = serverlessService.getServerlessCache(name); + if (createOnlyPropertiesChanged(r, props, ctx)) { + throw CfnExceptions.customNamedReplacement(name); + } + snapshotBeforeUpdate(r, existing); + List securityGroupIds = ctx.resolveStringList(props, "SecurityGroupIds"); + boolean hadSecurityGroups = existing.getSecurityGroupIds() != null && !existing.getSecurityGroupIds().isEmpty(); + // A null list means leave unchanged, so clearing the groups needs an explicit empty one. + List desiredSecurityGroups = !securityGroupIds.isEmpty() ? securityGroupIds + : hadSecurityGroups ? List.of() : null; + String description = ctx.resolveOptional(props, "Description"); + String userGroupId = ctx.resolveOptional(props, "UserGroupId"); + boolean removeUserGroup = userGroupId == null && existing.getUserGroupId() != null; + try { + serverlessService.modifyServerlessCache(new ElastiCacheServerlessService.ModifyServerlessCacheRequest( + name, + // A removed Description goes back to the empty one a new cache gets. + description == null ? "" : description, + ctx.resolveOptional(props, "Engine"), + ctx.resolveOptional(props, "MajorEngineVersion"), + desiredSecurityGroups, + userGroupId, + removeUserGroup ? Boolean.TRUE : null, + usageLimits(props, ctx), + optionalInt(ctx.resolveOptional(props, "SnapshotRetentionLimit")), + ctx.resolveOptional(props, "DailySnapshotTime"), + true)); + return serverlessService.replaceTags(name, ctx.resolveTags(props, "Tags")); + } catch (RuntimeException failure) { + // The stack skips rollbackUpdate for the resource whose own update failed, and the tag step + // runs after the settings were saved, so the settings are put back here. + try { + restoreSnapshot(r); + } catch (RuntimeException restoreFailure) { + failure.addSuppressed(restoreFailure); + } + throw failure; + } + } + + /** Keeps what an in-place update changes, so a failed stack update can put it back. */ + private static void snapshotBeforeUpdate(StackResource r, ServerlessCache existing) { + ObjectNode snapshot = MAPPER.createObjectNode(); + snapshot.put("name", existing.getServerlessCacheName()); + snapshot.put("description", existing.getDescription() == null ? "" : existing.getDescription()); + snapshot.set("securityGroupIds", MAPPER.valueToTree( + existing.getSecurityGroupIds() == null ? List.of() : existing.getSecurityGroupIds())); + if (existing.getUserGroupId() != null) { + snapshot.put("userGroupId", existing.getUserGroupId()); + } + if (existing.getCacheUsageLimits() != null) { + snapshot.set("cacheUsageLimits", MAPPER.valueToTree(existing.getCacheUsageLimits())); + } + snapshot.put("snapshotRetentionLimit", + existing.getSnapshotRetentionLimit() == null ? 0 : existing.getSnapshotRetentionLimit()); + if (existing.getDailySnapshotTime() != null) { + snapshot.put("dailySnapshotTime", existing.getDailySnapshotTime()); + } + ObjectNode tags = snapshot.putObject("tags"); + if (existing.getTags() != null) { + existing.getTags().forEach(tags::put); + } + r.getAttributes().put(CfnRollback.SERVERLESS_CACHE_UPDATE_SNAPSHOT_ATTR, snapshot.toString()); + } + + private void restoreSnapshot(StackResource r) { + String raw = r.getAttributes().get(CfnRollback.SERVERLESS_CACHE_UPDATE_SNAPSHOT_ATTR); + if (raw == null) { + return; + } + JsonNode snapshot; + try { + snapshot = MAPPER.readTree(raw); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Could not read the serverless cache update snapshot for " + + r.getLogicalId(), e); + } + String name = snapshot.path("name").asText(); + List securityGroupIds = new ArrayList<>(); + snapshot.path("securityGroupIds").forEach(id -> securityGroupIds.add(id.asText())); + String userGroupId = snapshot.hasNonNull("userGroupId") ? snapshot.get("userGroupId").asText() : null; + CacheUsageLimits limits = snapshot.hasNonNull("cacheUsageLimits") + ? MAPPER.convertValue(snapshot.get("cacheUsageLimits"), CacheUsageLimits.class) : null; + Map tags = new HashMap<>(); + snapshot.path("tags").fields().forEachRemaining(e -> tags.put(e.getKey(), e.getValue().asText())); + serverlessService.modifyServerlessCache(new ElastiCacheServerlessService.ModifyServerlessCacheRequest( + name, + snapshot.path("description").asText(""), + null, + null, + securityGroupIds, + userGroupId, + userGroupId == null ? Boolean.TRUE : null, + limits, + snapshot.path("snapshotRetentionLimit").asInt(0), + snapshot.hasNonNull("dailySnapshotTime") ? snapshot.get("dailySnapshotTime").asText() : null, + true)); + serverlessService.replaceTags(name, tags); + r.getAttributes().remove(CfnRollback.SERVERLESS_CACHE_UPDATE_SNAPSHOT_ATTR); + } + + private CacheUsageLimits usageLimits(JsonNode props, ProvisionContext ctx) { + if (!props.hasNonNull("CacheUsageLimits")) { + return null; + } + JsonNode limits = ctx.engine().resolveNode(props.get("CacheUsageLimits")); + JsonNode storage = limits.path("DataStorage"); + JsonNode ecpu = limits.path("ECPUPerSecond"); + DataStorage dataStorage = storage.isObject() + ? new DataStorage(intOrNull(storage, "Minimum"), intOrNull(storage, "Maximum"), + storage.hasNonNull("Unit") ? storage.get("Unit").asText() : null) + : null; + EcpuPerSecond ecpuPerSecond = ecpu.isObject() + ? new EcpuPerSecond(intOrNull(ecpu, "Minimum"), intOrNull(ecpu, "Maximum")) + : null; + return new CacheUsageLimits(dataStorage, ecpuPerSecond); + } + + private static Integer intOrNull(JsonNode node, String field) { + return node.hasNonNull(field) ? Integer.valueOf(node.get(field).asInt()) : null; + } + + private static Integer optionalInt(String raw) { + return raw == null || raw.isBlank() ? null : Integer.valueOf(raw); + } + + private void putEndpoint(StackResource r, String prefix, Endpoint endpoint) { + if (endpoint == null) { + return; + } + r.getAttributes().put(prefix + ".Address", endpoint.address()); + r.getAttributes().put(prefix + ".Port", String.valueOf(endpoint.port())); + } + + private static ObjectNode createOnlyRecord(JsonNode props, ProvisionContext ctx) { + ObjectNode record = MAPPER.createObjectNode(); + if (props == null) { + return record; + } + String kms = ctx.resolveOptional(props, "KmsKeyId"); + if (kms != null && !kms.isBlank()) { + record.put("KmsKeyId", kms.trim()); + } + String connectionType = ctx.resolveOptional(props, "ConnectionType"); + if (connectionType != null && !connectionType.isBlank()) { + record.put("ConnectionType", connectionType.trim()); + } + String networkType = ctx.resolveOptional(props, "NetworkType"); + if (networkType != null && !networkType.isBlank()) { + record.put("NetworkType", networkType.trim()); + } + List subnets = ctx.resolveStringList(props, "SubnetIds"); + if (!subnets.isEmpty()) { + ArrayNode arr = record.putArray("SubnetIds"); + subnets.stream().sorted().forEach(arr::add); + } + List snapshots = ctx.resolveStringList(props, "SnapshotArnsToRestore"); + if (!snapshots.isEmpty()) { + ArrayNode arr = record.putArray("SnapshotArnsToRestore"); + snapshots.forEach(arr::add); + } + return record; + } + + private static boolean createOnlyPropertiesChanged(StackResource r, JsonNode props, ProvisionContext ctx) { + String recorded = r.getAttributes().getOrDefault(CREATE_ONLY_ATTR, "{}"); + return !recorded.equals(createOnlyRecord(props, ctx).toString()); + } + + @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) { + return ReplacementCleanup.complete(resource, this::delete); + } + + @Override + public void clearUpdate(StackResource resource) { + resource.getAttributes().remove(CfnRollback.SERVERLESS_CACHE_UPDATE_SNAPSHOT_ATTR); + ReplacementCleanup.clear(resource); + } + + @Override + public boolean rollbackUpdate(StackResource resource) { + if (ReplacementCleanup.rollback(resource, this::delete)) { + return true; + } + if (resource.getAttributes().get(CfnRollback.SERVERLESS_CACHE_UPDATE_SNAPSHOT_ATTR) == null) { + return false; + } + restoreSnapshot(resource); + return true; + } + + @Override + public void delete(String resourceType, String physicalId, String region) { + if (physicalId == null) { + return; + } + CfnDeletes.safeDelete("ElastiCache serverless cache", physicalId, + () -> serverlessService.deleteServerlessCache(physicalId), "ServerlessCacheNotFoundFault"); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServerlessService.java b/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServerlessService.java index 995c22848a..f6320a92cd 100644 --- a/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServerlessService.java +++ b/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServerlessService.java @@ -32,18 +32,16 @@ public class ElastiCacheServerlessService implements Resettable { private final RegionResolver resolver; private final ElastiCacheService runtime; private final ElastiCacheMemcachedService memcached; - private final ElastiCacheService groups; private final ConcurrentHashMap locks = new ConcurrentHashMap<>(); @Inject public ElastiCacheServerlessService(StorageFactory factory, RegionResolver resolver, ElastiCacheService runtime, - ElastiCacheMemcachedService memcached, ElastiCacheService groups) { + ElastiCacheMemcachedService memcached) { this.caches = factory.create("elasticache", "elasticache-serverless-caches.json", new TypeReference>() {}); this.resolver = resolver; this.runtime = runtime; this.memcached = memcached; - this.groups = groups; } public record CreateServerlessCacheRequest(String serverlessCacheName, String engine, String majorEngineVersion, @@ -55,7 +53,19 @@ public class ElastiCacheServerlessService implements Resettable { public record ModifyServerlessCacheRequest(String serverlessCacheName, String description, String engine, String majorEngineVersion, List securityGroupIds, String userGroupId, Boolean removeUserGroup, CacheUsageLimits cacheUsageLimits, - Integer snapshotRetentionLimit, String dailySnapshotTime) {} + Integer snapshotRetentionLimit, String dailySnapshotTime, + boolean resetUnset) { + + /** The API form: an omitted field leaves the stored value unchanged. */ + public ModifyServerlessCacheRequest(String serverlessCacheName, String description, String engine, + String majorEngineVersion, List securityGroupIds, + String userGroupId, Boolean removeUserGroup, + CacheUsageLimits cacheUsageLimits, Integer snapshotRetentionLimit, + String dailySnapshotTime) { + this(serverlessCacheName, description, engine, majorEngineVersion, securityGroupIds, userGroupId, + removeUserGroup, cacheUsageLimits, snapshotRetentionLimit, dailySnapshotTime, false); + } + } public ServerlessCache createServerlessCache(CreateServerlessCacheRequest request) { String name = normalizedName(request.serverlessCacheName()); @@ -69,9 +79,7 @@ public class ElastiCacheServerlessService implements Resettable { if (request.snapshotArnsToRestore() != null && !request.snapshotArnsToRestore().isEmpty()) { throw invalid("Snapshot restore is not supported locally."); } - if (request.tags() != null && request.tags().size() > 50) { - throw new AwsException("TagQuotaPerResourceExceeded", "At most 50 tags are supported.", 400); - } + validateTagCount(request.tags()); String rawGroup = request.userGroupId(); String group = normalizedUserGroupId(rawGroup); String region = resolver.getRegion(); @@ -85,7 +93,7 @@ public class ElastiCacheServerlessService implements Resettable { CacheCluster backing = null; try { if (group != null) { - groups.attachServerlessCache(group, key(name), engine); + runtime.attachServerlessCache(group, key(name), engine); attached = true; } String runtimeId = "serverless-" + UUID.randomUUID(); @@ -131,7 +139,7 @@ public class ElastiCacheServerlessService implements Resettable { } if (attached) { try { - groups.detachServerlessCache(group, key(name)); + runtime.detachServerlessCache(group, key(name)); } catch (RuntimeException cleanupFailure) { exception.addSuppressed(cleanupFailure); } @@ -178,7 +186,7 @@ public class ElastiCacheServerlessService implements Resettable { validateGroup(group, previous.getEngine(), previous.getRegion()); boolean changedGroup = !Objects.equals(group, previous.getUserGroupId()); if (changedGroup && group != null) { - groups.attachServerlessCache(group, key(name), previous.getEngine()); + runtime.attachServerlessCache(group, key(name), previous.getEngine()); } try { if (changedGroup && !"memcached".equals(previous.getEngine())) { @@ -191,13 +199,15 @@ public class ElastiCacheServerlessService implements Resettable { if (request.securityGroupIds() != null) { updated.setSecurityGroupIds(request.securityGroupIds()); } - if (request.cacheUsageLimits() != null) { + // CloudFormation sends the whole desired state, so an omitted field goes back to its create default. + if (request.cacheUsageLimits() != null || request.resetUnset()) { updated.setCacheUsageLimits(request.cacheUsageLimits()); } - if (request.snapshotRetentionLimit() != null) { - updated.setSnapshotRetentionLimit(request.snapshotRetentionLimit()); + if (request.snapshotRetentionLimit() != null || request.resetUnset()) { + updated.setSnapshotRetentionLimit( + request.snapshotRetentionLimit() == null ? 0 : request.snapshotRetentionLimit()); } - if (request.dailySnapshotTime() != null) { + if (request.dailySnapshotTime() != null || request.resetUnset()) { updated.setDailySnapshotTime(request.dailySnapshotTime()); } caches.put(key(name), updated); @@ -206,7 +216,7 @@ public class ElastiCacheServerlessService implements Resettable { try { runtime.updateServerlessUserGroup(previous.getBackingCacheClusterId(), previous.getAccountId(), previous.getUserGroupId()); if (group != null) { - groups.detachServerlessCache(group, key(name)); + runtime.detachServerlessCache(group, key(name)); } } catch (RuntimeException rollbackFailure) { exception.addSuppressed(rollbackFailure); @@ -215,12 +225,30 @@ public class ElastiCacheServerlessService implements Resettable { throw exception; } if (changedGroup && previous.getUserGroupId() != null) { - groups.detachServerlessCache(previous.getUserGroupId(), key(name)); + runtime.detachServerlessCache(previous.getUserGroupId(), key(name)); } return current(updated); } } + /** Drives the tags to exactly the given set, the way CloudFormation reconciles a resource on update. */ + public ServerlessCache replaceTags(String name, Map tags) { + validateTagCount(tags); + String normalized = normalizedName(name); + synchronized (lockFor(normalized)) { + ServerlessCache updated = copy(requireCache(normalized)); + updated.setTags(tags); + caches.put(key(normalized), updated); + return current(updated); + } + } + + private static void validateTagCount(Map tags) { + if (tags != null && tags.size() > 50) { + throw new AwsException("TagQuotaPerResourceExceeded", "At most 50 tags are supported.", 400); + } + } + public ServerlessCache deleteServerlessCache(String name) { return deleteServerlessCache(name, null); } @@ -242,7 +270,7 @@ public class ElastiCacheServerlessService implements Resettable { cache.getBackingCacheClusterId(), normalized); } if (cache.getUserGroupId() != null) { - groups.detachServerlessCache(cache.getUserGroupId(), key(normalized)); + runtime.detachServerlessCache(cache.getUserGroupId(), key(normalized)); } caches.delete(key(normalized)); ServerlessCache deleted = copy(cache); @@ -300,7 +328,7 @@ public class ElastiCacheServerlessService implements Resettable { if ("memcached".equals(engine)) { throw new AwsException("InvalidParameterCombination", "Memcached does not support user groups.", 400); } - groups.validateServerlessAssociation(group, engine); + runtime.validateServerlessAssociation(group, engine); } private static String normalizedName(String name) { @@ -375,7 +403,7 @@ public class ElastiCacheServerlessService implements Resettable { cache.getBackingCacheClusterId(), cache.getServerlessCacheName()); } if (cache.getUserGroupId() != null) { - groups.detachServerlessCache(cache.getUserGroupId(), + runtime.detachServerlessCache(cache.getUserGroupId(), cache.getRegion() + "/" + cache.getServerlessCacheName()); } } diff --git a/src/main/resources/cloudformation/create-only-properties.json b/src/main/resources/cloudformation/create-only-properties.json index e212a16862..e537dc8718 100644 --- a/src/main/resources/cloudformation/create-only-properties.json +++ b/src/main/resources/cloudformation/create-only-properties.json @@ -419,6 +419,14 @@ "AmiType", "Subnets" ], + "AWS::ElastiCache::ServerlessCache": [ + "ServerlessCacheName", + "KmsKeyId", + "SnapshotArnsToRestore", + "SubnetIds", + "ConnectionType", + "NetworkType" + ], "AWS::ElasticLoadBalancingV2::Listener": [ "LoadBalancerArn" ], diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnCreateOnlyPropertiesTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnCreateOnlyPropertiesTest.java index 3d9f9f5f70..f133739ce0 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnCreateOnlyPropertiesTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnCreateOnlyPropertiesTest.java @@ -37,6 +37,20 @@ class CfnCreateOnlyPropertiesTest { assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::ApiGatewayV2::VpcLink", "Tags")); } + @Test + void isCreateOnly_serverlessCacheReplacesOnItsSchemaProperties() { + String type = "AWS::ElastiCache::ServerlessCache"; + assertTrue(CfnCreateOnlyProperties.isCreateOnly(type, "ServerlessCacheName")); + assertTrue(CfnCreateOnlyProperties.isCreateOnly(type, "SubnetIds")); + assertTrue(CfnCreateOnlyProperties.isCreateOnly(type, "KmsKeyId")); + assertTrue(CfnCreateOnlyProperties.isCreateOnly(type, "SnapshotArnsToRestore")); + assertTrue(CfnCreateOnlyProperties.isCreateOnly(type, "ConnectionType")); + assertTrue(CfnCreateOnlyProperties.isCreateOnly(type, "NetworkType")); + assertFalse(CfnCreateOnlyProperties.isCreateOnly(type, "SecurityGroupIds")); + assertFalse(CfnCreateOnlyProperties.isCreateOnly(type, "Description")); + assertFalse(CfnCreateOnlyProperties.isCreateOnly(type, "Tags")); + } + @Test void isCreateOnly_treatsEmptySchemaListAsAuthoritative() { assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::ApiGateway::RestApi", "Name")); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java index ebc256147d..59cdf76365 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java @@ -64,6 +64,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.EcsCapaci 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.ElastiCacheServerlessCfnProvisioner; 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; @@ -123,6 +124,7 @@ 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.ElastiCacheServerlessService; import io.github.hectorvent.floci.services.elasticache.ElastiCacheService; import io.github.hectorvent.floci.services.elbv2.ElbV2Service; import io.github.hectorvent.floci.services.eventbridge.EventBridgeService; @@ -236,6 +238,7 @@ final class CfnProvisionerFixture { private BackupService backupService; private ElastiCacheService elastiCacheService; private ElastiCacheMemcachedService elastiCacheMemcachedService; + private ElastiCacheServerlessService elastiCacheServerlessService; private RedshiftService redshiftService; private RedshiftServerlessService redshiftServerlessService; private CloudMapService cloudMapService; @@ -464,6 +467,9 @@ final class CfnProvisionerFixture { if (elastiCacheService != null && elastiCacheMemcachedService != null) { discovered.add(new ElastiCacheCfnProvisioner(elastiCacheService, elastiCacheMemcachedService)); } + if (elastiCacheServerlessService != null) { + discovered.add(new ElastiCacheServerlessCfnProvisioner(elastiCacheServerlessService)); + } if (redshiftService != null) { discovered.add(new RedshiftClusterCfnProvisioner(redshiftService)); } @@ -746,6 +752,11 @@ final class CfnProvisionerFixture { return this; } + public Builder elastiCacheServerless(ElastiCacheServerlessService s) { + this.elastiCacheServerlessService = s; + return this; + } + public Builder redshiftService(RedshiftService s) { this.redshiftService = s; return this; diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/ElastiCacheCfnIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ElastiCacheCfnIntegrationTest.java index d82acba0e8..acec325a69 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/ElastiCacheCfnIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ElastiCacheCfnIntegrationTest.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.cloudformation; import io.github.hectorvent.floci.core.common.XmlParser; +import io.github.hectorvent.floci.testing.DockerAvailability; import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; import io.quarkus.test.common.http.TestHTTPResource; import io.quarkus.test.junit.QuarkusTest; @@ -17,9 +18,7 @@ import software.amazon.awssdk.services.elasticache.model.CacheSubnetGroupNotFoun import software.amazon.awssdk.services.elasticache.model.ElastiCacheException; import software.amazon.awssdk.services.elasticache.model.UserGroupNotFoundException; -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; @@ -191,7 +190,7 @@ class ElastiCacheCfnIntegrationTest { @Test void cacheClusterExposesEndpoints() throws Exception { - Assumptions.assumeTrue(dockerAvailable(), "Docker is required for the cache data plane"); + Assumptions.assumeTrue(DockerAvailability.isAvailable(), "Docker is required for the cache data plane"); cloudFormation(DATA_STACK, "CreateStack", DATA_TEMPLATE); String stacks = describeStacks(DATA_STACK, "CREATE_COMPLETE"); @@ -210,21 +209,6 @@ class ElastiCacheCfnIntegrationTest { 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() diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/ElastiCacheServerlessCfnIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ElastiCacheServerlessCfnIntegrationTest.java new file mode 100644 index 0000000000..603e8a655c --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ElastiCacheServerlessCfnIntegrationTest.java @@ -0,0 +1,142 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import io.github.hectorvent.floci.core.common.XmlParser; +import io.github.hectorvent.floci.services.elasticache.ServerlessTestProfile; +import io.github.hectorvent.floci.testing.DockerAvailability; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +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.ServerlessCache; +import software.amazon.awssdk.services.elasticache.model.ServerlessCacheNotFoundException; +import software.amazon.awssdk.services.elasticache.model.UserGroupNotFoundException; + +import java.net.URI; + +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.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Provisions AWS::ElastiCache::ServerlessCache through CloudFormation. 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 +@TestProfile(ServerlessTestProfile.class) +class ElastiCacheServerlessCfnIntegrationTest { + + private static final String CFN_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260903/us-east-1/cloudformation/aws4_request"; + private static final String STACK = "elasticache-cfn-serverless-it"; + + private static final String TEMPLATE = """ + { + "Resources": { + "Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.74.0.0/16"}}, + "Subnet": {"Type": "AWS::EC2::Subnet", + "Properties": {"VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.74.0.0/24"}}, + "DefaultUser": {"Type": "AWS::ElastiCache::User", + "Properties": {"UserId": "cfn-it-sl-default", "UserName": "default", + "Engine": "redis", "AccessString": "off -@all", + "NoPasswordRequired": true}}, + "UserGroup": {"Type": "AWS::ElastiCache::UserGroup", + "Properties": {"UserGroupId": "cfn-it-sl-users", "Engine": "redis", + "UserIds": [{"Ref": "DefaultUser"}]}}, + "Serverless": {"Type": "AWS::ElastiCache::ServerlessCache", + "Properties": {"ServerlessCacheName": "cfn-it-serverless", "Engine": "valkey", + "SubnetIds": [{"Ref": "Subnet"}], + "UserGroupId": {"Ref": "UserGroup"}}} + }, + "Outputs": { + "ServerlessRef": {"Value": {"Ref": "Serverless"}}, + "ServerlessArn": {"Value": {"Fn::GetAtt": ["Serverless", "ARN"]}}, + "ServerlessAddress": {"Value": {"Fn::GetAtt": ["Serverless", "Endpoint.Address"]}}, + "ServerlessPort": {"Value": {"Fn::GetAtt": ["Serverless", "Endpoint.Port"]}} + } + } + """; + + @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 serverlessCacheExposesEndpointsAndIsRemovedWithTheStack() throws Exception { + Assumptions.assumeTrue(DockerAvailability.isAvailable(), "Docker is required for the cache data plane"); + cloudFormation(STACK, "CreateStack", TEMPLATE); + String stacks = describeStacks(STACK, "CREATE_COMPLETE"); + + assertEquals("cfn-it-serverless", outputValue(stacks, "ServerlessRef")); + assertFalse(outputValue(stacks, "ServerlessAddress").contains("Serverless.Endpoint"), + "an unset attribute resolves to the literal LogicalId.Attr"); + assertTrue(outputValue(stacks, "ServerlessArn").endsWith(":serverlesscache:cfn-it-serverless")); + + try (ElastiCacheClient client = client()) { + ServerlessCache serverless = client.describeServerlessCaches(r -> r.serverlessCacheName("cfn-it-serverless")) + .serverlessCaches().getFirst(); + assertNotNull(serverless.endpoint()); + assertEquals(outputValue(stacks, "ServerlessPort"), String.valueOf(serverless.endpoint().port())); + assertEquals("cfn-it-sl-users", serverless.userGroupId()); + } + + cloudFormation(STACK, "DeleteStack", null); + CfnStackWaits.awaitStackDeleted(STACK); + try (ElastiCacheClient client = client()) { + assertThrows(ServerlessCacheNotFoundException.class, + () -> client.describeServerlessCaches(r -> r.serverlessCacheName("cfn-it-serverless"))); + assertThrows(UserGroupNotFoundException.class, + () -> client.describeUserGroups(r -> r.userGroupId("cfn-it-sl-users"))); + } + } + + + 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("" + expectedStatus + "")) + .extract().asString(); + } + + private static String outputValue(String xml, String key) { + return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get(key); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElastiCacheCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElastiCacheCfnProvisionerTest.java index e3ff0bc0c9..a0a36e2b97 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElastiCacheCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElastiCacheCfnProvisionerTest.java @@ -333,6 +333,16 @@ class ElastiCacheCfnProvisionerTest { verify(cache, never()).createUser(any(), any(), any(), any(), any(), any()); } + @Test + void userRejectsMalformedNoPasswordRequiredFlag() { + StackResource r = resource("AWS::ElastiCache::User", "Bad"); + AwsException ex = assertThrows(AwsException.class, () -> provisioner.provision(r, props(""" + {"UserId":"u","UserName":"u","Engine":"redis","NoPasswordRequired":"yes"} + """), ctx(null))); + assertEquals("ValidationException", ex.getErrorCode()); + verify(cache, never()).createUser(any(), any(), any(), any(), any(), any()); + } + @Test void userRejectsConflictingNoPasswordRequiredAndPasswords() { StackResource r = resource("AWS::ElastiCache::User", "Bad"); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElastiCacheServerlessCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElastiCacheServerlessCfnProvisionerTest.java new file mode 100644 index 0000000000..0749e1f5ae --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElastiCacheServerlessCfnProvisionerTest.java @@ -0,0 +1,399 @@ +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.ElastiCacheServerlessService; +import io.github.hectorvent.floci.services.elasticache.model.Endpoint; +import io.github.hectorvent.floci.services.elasticache.model.ServerlessCache; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +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.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.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class ElastiCacheServerlessCfnProvisionerTest { + + private final ObjectMapper mapper = new ObjectMapper(); + private final ElastiCacheServerlessService serverless = mock(ElastiCacheServerlessService.class); + private final ElastiCacheServerlessCfnProvisioner serverlessProvisioner = + new ElastiCacheServerlessCfnProvisioner(serverless); + + 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 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 serverlessCacheExposesEndpointAndArnAttributes() throws Exception { + ServerlessCache created = new ServerlessCache(); + created.setServerlessCacheName("sl"); + created.setArn("arn:aws:elasticache:us-east-1:000000000000:serverlesscache:sl"); + created.setStatus("available"); + created.setFullEngineVersion("8.0"); + created.setEndpoint(new Endpoint("localhost", 6420)); + created.setReaderEndpoint(new Endpoint("localhost", 6421)); + when(serverless.createServerlessCache(any())).thenReturn(created); + StackResource r = resource("AWS::ElastiCache::ServerlessCache", "Sl"); + + serverlessProvisioner.provision(r, props(""" + {"ServerlessCacheName":"sl","Engine":"valkey","SubnetIds":["subnet-1"],"UserGroupId":"team", + "CacheUsageLimits":{"DataStorage":{"Maximum":10,"Unit":"GB"},"ECPUPerSecond":{"Maximum":5000}}} + """), ctx(null)); + + assertEquals("sl", r.getPhysicalId()); + assertEquals("arn:aws:elasticache:us-east-1:000000000000:serverlesscache:sl", r.getAttributes().get("ARN")); + assertEquals("6420", r.getAttributes().get("Endpoint.Port")); + assertEquals("localhost", r.getAttributes().get("ReaderEndpoint.Address")); + ArgumentCaptor request = + ArgumentCaptor.forClass(ElastiCacheServerlessService.CreateServerlessCacheRequest.class); + verify(serverless).createServerlessCache(request.capture()); + assertEquals("team", request.getValue().userGroupId()); + assertEquals(10, request.getValue().cacheUsageLimits().dataStorage().maximum()); + assertEquals(5000, request.getValue().cacheUsageLimits().ecpuPerSecond().maximum()); + } + + @Test + void mixedCaseServerlessNameIsReusedOnUpdateThroughItsLowercaseForm() throws Exception { + ServerlessCache existing = new ServerlessCache(); + existing.setServerlessCacheName("mycache"); + existing.setArn("arn"); + existing.setStatus("available"); + when(serverless.getServerlessCache("mycache")).thenReturn(existing); + when(serverless.modifyServerlessCache(any())).thenReturn(existing); + when(serverless.replaceTags(eq("mycache"), any())).thenReturn(existing); + StackResource r = resource("AWS::ElastiCache::ServerlessCache", "Sl"); + + serverlessProvisioner.provision(r, props("{\"ServerlessCacheName\":\"MyCache\",\"Engine\":\"valkey\"}"), + ctx("mycache")); + + verify(serverless, never()).createServerlessCache(any()); + assertEquals("mycache", r.getPhysicalId()); + } + + @Test + void serverlessSubnetChangeIsRejectedInsteadOfIgnored() throws Exception { + ServerlessCache existing = new ServerlessCache(); + existing.setServerlessCacheName("sl"); + existing.setSubnetIds(List.of("subnet-1")); + when(serverless.getServerlessCache("sl")).thenReturn(existing); + StackResource r = resource("AWS::ElastiCache::ServerlessCache", "Sl"); + r.getAttributes().put("__FlociCreateOnly", "{\"SubnetIds\":[\"subnet-1\"]}"); + + AwsException error = assertThrows(AwsException.class, () -> serverlessProvisioner.provision(r, + props("{\"ServerlessCacheName\":\"sl\",\"Engine\":\"valkey\",\"SubnetIds\":[\"subnet-2\"]}"), ctx("sl"))); + assertEquals("ValidationError", error.getErrorCode()); + assertEquals("CloudFormation cannot update a stack when a custom-named resource requires replacing. " + + "Rename sl and update the stack again.", error.getMessage()); + verify(serverless, never()).modifyServerlessCache(any()); + } + + @Test + void serverlessKmsKeyChangeIsRejectedInsteadOfIgnored() throws Exception { + ServerlessCache existing = new ServerlessCache(); + existing.setServerlessCacheName("sl"); + existing.setKmsKeyId("key-1"); + when(serverless.getServerlessCache("sl")).thenReturn(existing); + StackResource r = resource("AWS::ElastiCache::ServerlessCache", "Sl"); + r.getAttributes().put("__FlociCreateOnly", "{\"KmsKeyId\":\"key-1\"}"); + + AwsException error = assertThrows(AwsException.class, () -> serverlessProvisioner.provision(r, + props("{\"ServerlessCacheName\":\"sl\",\"Engine\":\"valkey\"}"), ctx("sl"))); + assertEquals("ValidationError", error.getErrorCode()); + assertEquals("CloudFormation cannot update a stack when a custom-named resource requires replacing. " + + "Rename sl and update the stack again.", error.getMessage()); + verify(serverless, never()).modifyServerlessCache(any()); + } + + @Test + void serverlessSnapshotArnsToRestoreChangeIsRejectedInsteadOfIgnored() throws Exception { + ServerlessCache existing = new ServerlessCache(); + existing.setServerlessCacheName("sl"); + when(serverless.getServerlessCache("sl")).thenReturn(existing); + StackResource r = resource("AWS::ElastiCache::ServerlessCache", "Sl"); + r.getAttributes().put("__FlociCreateOnly", "{}"); + + AwsException error = assertThrows(AwsException.class, () -> serverlessProvisioner.provision(r, + props("{\"ServerlessCacheName\":\"sl\",\"Engine\":\"valkey\",\"SnapshotArnsToRestore\":[\"arn:aws:snapshot:1\"]}"), + ctx("sl"))); + assertEquals("ValidationError", error.getErrorCode()); + assertEquals("CloudFormation cannot update a stack when a custom-named resource requires replacing. " + + "Rename sl and update the stack again.", error.getMessage()); + verify(serverless, never()).modifyServerlessCache(any()); + } + + @Test + void serverlessConnectionTypeChangeIsRejectedInsteadOfIgnored() throws Exception { + ServerlessCache existing = new ServerlessCache(); + existing.setServerlessCacheName("sl"); + when(serverless.getServerlessCache("sl")).thenReturn(existing); + StackResource r = resource("AWS::ElastiCache::ServerlessCache", "Sl"); + r.getAttributes().put("__FlociCreateOnly", "{\"ConnectionType\":\"vpc\"}"); + + AwsException error = assertThrows(AwsException.class, () -> serverlessProvisioner.provision(r, + props("{\"ServerlessCacheName\":\"sl\",\"Engine\":\"valkey\",\"ConnectionType\":\"public\"}"), + ctx("sl"))); + assertEquals("ValidationError", error.getErrorCode()); + assertEquals("CloudFormation cannot update a stack when a custom-named resource requires replacing. " + + "Rename sl and update the stack again.", error.getMessage()); + verify(serverless, never()).modifyServerlessCache(any()); + } + + @Test + void serverlessNetworkTypeChangeIsRejectedInsteadOfIgnored() throws Exception { + ServerlessCache existing = new ServerlessCache(); + existing.setServerlessCacheName("sl"); + when(serverless.getServerlessCache("sl")).thenReturn(existing); + StackResource r = resource("AWS::ElastiCache::ServerlessCache", "Sl"); + r.getAttributes().put("__FlociCreateOnly", "{\"NetworkType\":\"ipv4\"}"); + + AwsException error = assertThrows(AwsException.class, () -> serverlessProvisioner.provision(r, + props("{\"ServerlessCacheName\":\"sl\",\"Engine\":\"valkey\",\"NetworkType\":\"ipv6\"}"), + ctx("sl"))); + assertEquals("ValidationError", error.getErrorCode()); + assertEquals("CloudFormation cannot update a stack when a custom-named resource requires replacing. " + + "Rename sl and update the stack again.", error.getMessage()); + verify(serverless, never()).modifyServerlessCache(any()); + } + + @Test + void serverlessUpdatePreservingCreateOnlySucceedsWhileChangingCreateOnlyIsRejected() throws Exception { + ServerlessCache cache = new ServerlessCache(); + cache.setServerlessCacheName("sl"); + cache.setArn("arn:aws:elasticache:us-east-1:000000000000:serverlesscache:sl"); + cache.setStatus("available"); + cache.setDescription("initial"); + when(serverless.createServerlessCache(any())).thenReturn(cache); + when(serverless.getServerlessCache("sl")).thenReturn(cache); + when(serverless.modifyServerlessCache(any())).thenReturn(cache); + when(serverless.replaceTags(eq("sl"), any())).thenReturn(cache); + StackResource r = resource("AWS::ElastiCache::ServerlessCache", "Sl"); + + serverlessProvisioner.provision(r, props(""" + {"ServerlessCacheName":"sl","Engine":"valkey","ConnectionType":"vpc","Description":"initial"} + """), ctx(null)); + assertEquals("sl", r.getPhysicalId()); + assertEquals("{\"ConnectionType\":\"vpc\"}", r.getAttributes().get("__FlociCreateOnly")); + + serverlessProvisioner.provision(r, props(""" + {"ServerlessCacheName":"sl","Engine":"valkey","ConnectionType":"vpc","Description":"updated"} + """), ctx("sl")); + verify(serverless).modifyServerlessCache(any()); + + AwsException error = assertThrows(AwsException.class, () -> serverlessProvisioner.provision(r, props(""" + {"ServerlessCacheName":"sl","Engine":"valkey","ConnectionType":"public","Description":"updated"} + """), ctx("sl"))); + assertEquals("ValidationError", error.getErrorCode()); + assertEquals("CloudFormation cannot update a stack when a custom-named resource requires replacing. " + + "Rename sl and update the stack again.", error.getMessage()); + } + + @Test + void serverlessRecordedCreateOnlyPropertyChangeIsRejected() throws Exception { + ServerlessCache existing = new ServerlessCache(); + existing.setServerlessCacheName("sl"); + when(serverless.getServerlessCache("sl")).thenReturn(existing); + StackResource r = resource("AWS::ElastiCache::ServerlessCache", "Sl"); + r.getAttributes().put("__FlociCreateOnly", + "{\"ConnectionType\":\"vpc\",\"NetworkType\":\"ipv4\",\"SnapshotArnsToRestore\":[\"arn:aws:snap-1\"]}"); + + AwsException error = assertThrows(AwsException.class, () -> serverlessProvisioner.provision(r, + props("{\"ServerlessCacheName\":\"sl\",\"Engine\":\"valkey\",\"ConnectionType\":\"vpc\",\"NetworkType\":\"ipv4\"}"), + ctx("sl"))); + assertEquals("ValidationError", error.getErrorCode()); + assertEquals("CloudFormation cannot update a stack when a custom-named resource requires replacing. " + + "Rename sl and update the stack again.", error.getMessage()); + verify(serverless, never()).modifyServerlessCache(any()); + } + + @Test + void serverlessUpdateClearsSecurityGroupsAndDescriptionRemovedFromTheTemplate() throws Exception { + ServerlessCache existing = new ServerlessCache(); + existing.setServerlessCacheName("sl"); + existing.setSecurityGroupIds(List.of("sg-1")); + existing.setDescription("old"); + existing.setArn("arn"); + existing.setStatus("available"); + when(serverless.getServerlessCache("sl")).thenReturn(existing); + when(serverless.modifyServerlessCache(any())).thenReturn(existing); + when(serverless.replaceTags(eq("sl"), any())).thenReturn(existing); + StackResource r = resource("AWS::ElastiCache::ServerlessCache", "Sl"); + + serverlessProvisioner.provision(r, props("{\"ServerlessCacheName\":\"sl\",\"Engine\":\"valkey\"}"), ctx("sl")); + + ArgumentCaptor request = + ArgumentCaptor.forClass(ElastiCacheServerlessService.ModifyServerlessCacheRequest.class); + verify(serverless).modifyServerlessCache(request.capture()); + assertEquals(List.of(), request.getValue().securityGroupIds()); + assertEquals("", request.getValue().description()); + } + + @Test + void renamedServerlessCacheReplacesAndDeletesTheOldOne() throws Exception { + ServerlessCache created = new ServerlessCache(); + created.setServerlessCacheName("new-sl"); + created.setArn("arn"); + created.setStatus("available"); + when(serverless.createServerlessCache(any())).thenReturn(created); + StackResource r = resource("AWS::ElastiCache::ServerlessCache", "Sl"); + + serverlessProvisioner.provision(r, props("{\"ServerlessCacheName\":\"new-sl\",\"Engine\":\"valkey\"}"), ctx("old-sl")); + + assertTrue(serverlessProvisioner.hasReplacementUpdate(r)); + serverlessProvisioner.completeUpdate(r); + verify(serverless).deleteServerlessCache("old-sl"); + } + + @Test + void serverlessUpdateModifiesInPlaceDropsUserGroupAndReplacesTags() throws Exception { + ServerlessCache existing = new ServerlessCache(); + existing.setServerlessCacheName("sl"); + existing.setUserGroupId("team"); + existing.setArn("arn"); + existing.setStatus("available"); + when(serverless.getServerlessCache("sl")).thenReturn(existing); + when(serverless.modifyServerlessCache(any())).thenReturn(existing); + when(serverless.replaceTags(eq("sl"), any())).thenReturn(existing); + StackResource r = resource("AWS::ElastiCache::ServerlessCache", "Sl"); + + serverlessProvisioner.provision(r, props(""" + {"ServerlessCacheName":"sl","Engine":"valkey","Description":"updated", + "CacheUsageLimits":{"ECPUPerSecond":{"Maximum":4000}}, + "Tags":[{"Key":"team","Value":"x"}]} + """), ctx("sl")); + + ArgumentCaptor request = + ArgumentCaptor.forClass(ElastiCacheServerlessService.ModifyServerlessCacheRequest.class); + verify(serverless).modifyServerlessCache(request.capture()); + assertEquals(Boolean.TRUE, request.getValue().removeUserGroup()); + assertEquals("updated", request.getValue().description()); + assertEquals(4000, request.getValue().cacheUsageLimits().ecpuPerSecond().maximum()); + verify(serverless).replaceTags(eq("sl"), any()); + verify(serverless, never()).createServerlessCache(any()); + } + + private ServerlessCache existingWithSettings() { + ServerlessCache existing = new ServerlessCache(); + existing.setServerlessCacheName("sl"); + existing.setArn("arn"); + existing.setStatus("available"); + existing.setDescription("old"); + existing.setSecurityGroupIds(List.of("sg-1")); + existing.setUserGroupId("team"); + existing.setSnapshotRetentionLimit(7); + existing.setDailySnapshotTime("05:00"); + existing.setCacheUsageLimits(new ServerlessCache.CacheUsageLimits(null, + new ServerlessCache.EcpuPerSecond(null, 4000))); + existing.setTags(new HashMap<>(Map.of("env", "dev"))); + return existing; + } + + @Test + void serverlessUpdateResetsLimitsAndSnapshotSettingsRemovedFromTheTemplate() throws Exception { + ServerlessCache existing = existingWithSettings(); + when(serverless.getServerlessCache("sl")).thenReturn(existing); + when(serverless.modifyServerlessCache(any())).thenReturn(existing); + when(serverless.replaceTags(eq("sl"), any())).thenReturn(existing); + StackResource r = resource("AWS::ElastiCache::ServerlessCache", "Sl"); + + serverlessProvisioner.provision(r, props("{\"ServerlessCacheName\":\"sl\",\"Engine\":\"valkey\"}"), ctx("sl")); + + ArgumentCaptor request = + ArgumentCaptor.forClass(ElastiCacheServerlessService.ModifyServerlessCacheRequest.class); + verify(serverless).modifyServerlessCache(request.capture()); + assertTrue(request.getValue().resetUnset()); + assertEquals(null, request.getValue().cacheUsageLimits()); + assertEquals(null, request.getValue().snapshotRetentionLimit()); + assertEquals(null, request.getValue().dailySnapshotTime()); + } + + @Test + void failedTagUpdatePutsTheSettingsBack() throws Exception { + ServerlessCache existing = existingWithSettings(); + when(serverless.getServerlessCache("sl")).thenReturn(existing); + when(serverless.modifyServerlessCache(any())).thenReturn(existing); + when(serverless.replaceTags(eq("sl"), any())) + .thenThrow(new AwsException("TagQuotaPerResourceExceeded", "too many", 400)) + .thenReturn(existing); + StackResource r = resource("AWS::ElastiCache::ServerlessCache", "Sl"); + + assertThrows(AwsException.class, () -> serverlessProvisioner.provision(r, props(""" + {"ServerlessCacheName":"sl","Engine":"valkey","Description":"new"} + """), ctx("sl"))); + + ArgumentCaptor request = + ArgumentCaptor.forClass(ElastiCacheServerlessService.ModifyServerlessCacheRequest.class); + verify(serverless, times(2)).modifyServerlessCache(request.capture()); + ElastiCacheServerlessService.ModifyServerlessCacheRequest restore = request.getAllValues().get(1); + assertEquals("old", restore.description()); + assertEquals(List.of("sg-1"), restore.securityGroupIds()); + assertEquals("team", restore.userGroupId()); + assertEquals(7, restore.snapshotRetentionLimit()); + assertEquals("05:00", restore.dailySnapshotTime()); + assertEquals(4000, restore.cacheUsageLimits().ecpuPerSecond().maximum()); + verify(serverless).replaceTags("sl", Map.of("env", "dev")); + } + + @Test + void rollbackOfAnInPlaceServerlessUpdateRestoresThePriorSettings() throws Exception { + ServerlessCache existing = existingWithSettings(); + when(serverless.getServerlessCache("sl")).thenReturn(existing); + when(serverless.modifyServerlessCache(any())).thenReturn(existing); + when(serverless.replaceTags(eq("sl"), any())).thenReturn(existing); + StackResource r = resource("AWS::ElastiCache::ServerlessCache", "Sl"); + serverlessProvisioner.provision(r, props(""" + {"ServerlessCacheName":"sl","Engine":"valkey","Description":"new"} + """), ctx("sl")); + + assertTrue(serverlessProvisioner.rollbackUpdate(r)); + + ArgumentCaptor request = + ArgumentCaptor.forClass(ElastiCacheServerlessService.ModifyServerlessCacheRequest.class); + verify(serverless, times(2)).modifyServerlessCache(request.capture()); + assertEquals("old", request.getAllValues().get(1).description()); + serverlessProvisioner.clearUpdate(r); + assertTrue(r.getAttributes().keySet().stream().noneMatch(k -> k.contains("ServerlessCacheUpdateSnapshot"))); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheClusterIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheClusterIntegrationTest.java index 9a844431e5..0a87041c47 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheClusterIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheClusterIntegrationTest.java @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.elasticache; +import io.github.hectorvent.floci.testing.DockerAvailability; import io.quarkus.test.junit.QuarkusTest; import io.restassured.path.xml.XmlPath; import org.junit.jupiter.api.AfterAll; @@ -44,8 +45,8 @@ class ElastiCacheClusterIntegrationTest { private static int secondShardPort; @BeforeAll - static void requireDocker() { - Assumptions.assumeTrue(isDockerAvailable(), "Docker daemon must be available for ElastiCache integration tests"); + static void requireDocker() throws InterruptedException { + Assumptions.assumeTrue(DockerAvailability.isAvailable(), "Docker daemon must be available for ElastiCache integration tests"); } @AfterAll @@ -214,15 +215,6 @@ class ElastiCacheClusterIntegrationTest { .statusCode(404); } - private static boolean isDockerAvailable() { - try { - Process process = new ProcessBuilder("docker", "info").start(); - return process.waitFor() == 0; - } catch (Exception e) { - return false; - } - } - private static Socket openSocket(int port) throws IOException { Socket socket = new Socket("localhost", port); socket.setTcpNoDelay(true); diff --git a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheRedisClusterIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheRedisClusterIntegrationTest.java index 07ada5a24b..480c755db0 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheRedisClusterIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheRedisClusterIntegrationTest.java @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.elasticache; +import io.github.hectorvent.floci.testing.DockerAvailability; import io.quarkus.test.junit.QuarkusTest; import io.restassured.path.xml.XmlPath; import org.junit.jupiter.api.AfterAll; @@ -40,8 +41,8 @@ class ElastiCacheRedisClusterIntegrationTest { private static int nodePort; @BeforeAll - static void requireDocker() { - Assumptions.assumeTrue(isDockerAvailable(), "Docker daemon must be available for ElastiCache integration tests"); + static void requireDocker() throws InterruptedException { + Assumptions.assumeTrue(DockerAvailability.isAvailable(), "Docker daemon must be available for ElastiCache integration tests"); } @AfterAll @@ -175,15 +176,6 @@ class ElastiCacheRedisClusterIntegrationTest { .statusCode(404); } - private static boolean isDockerAvailable() { - try { - Process process = new ProcessBuilder("docker", "info").start(); - return process.waitFor() == 0; - } catch (Exception e) { - return false; - } - } - private static Socket openSocket(String host, int port) throws IOException { Socket socket = new Socket(host, port); socket.setTcpNoDelay(true); diff --git a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServerlessIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServerlessIntegrationTest.java index cb5ebe0cb2..a3f2fa6c28 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServerlessIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServerlessIntegrationTest.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.elasticache; import io.github.hectorvent.floci.services.ec2.Ec2Service; +import io.github.hectorvent.floci.testing.DockerAvailability; import io.quarkus.test.common.http.TestHTTPResource; import io.quarkus.test.junit.QuarkusTest; import io.quarkus.test.junit.TestProfile; @@ -20,7 +21,6 @@ import java.net.Socket; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.List; -import java.util.concurrent.TimeUnit; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsString; @@ -100,7 +100,7 @@ class ElastiCacheServerlessIntegrationTest { @Test void dockerValkeyPreservesDataAndAuthenticatesCurrentGroupMembers() throws Exception { - Assumptions.assumeTrue(dockerAvailable(), "Docker is required for the serverless data plane"); + Assumptions.assumeTrue(DockerAvailability.isAvailable(), "Docker is required for the serverless data plane"); try (ElastiCacheClient client = client()) { client.createUser(request -> request.userId("serverless-alice").userName("alice").engine("valkey") .accessString("on ~* +@all").passwords("alice-password-123")); @@ -164,7 +164,7 @@ class ElastiCacheServerlessIntegrationTest { @Test void dockerMemcachedPreservesValuesAcrossMetadataChanges() throws Exception { - Assumptions.assumeTrue(dockerAvailable(), "Docker is required for the serverless Memcached data plane"); + Assumptions.assumeTrue(DockerAvailability.isAvailable(), "Docker is required for the serverless Memcached data plane"); try (ElastiCacheClient client = client()) { try { ServerlessCache cache = client.createServerlessCache(request -> request.serverlessCacheName("serverless-memcached") @@ -196,22 +196,6 @@ class ElastiCacheServerlessIntegrationTest { } } - private static boolean dockerAvailable() throws IOException, InterruptedException { - 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 Socket socket(ServerlessCache cache) throws IOException { Socket socket = new Socket(cache.endpoint().address(), cache.endpoint().port()); socket.setSoTimeout(10_000); diff --git a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServerlessServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServerlessServiceTest.java index 77396e71b1..2922e00b63 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServerlessServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServerlessServiceTest.java @@ -28,6 +28,7 @@ import org.junit.jupiter.api.io.TempDir; import org.mockito.ArgumentCaptor; import java.nio.file.Path; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -108,7 +109,7 @@ class ElastiCacheServerlessServiceTest { config, ec2, resolver, kms, new ElastiCacheProvisioningIds()); memcached = new ElastiCacheMemcachedService(mock(ElastiCacheMemcachedContainerManager.class), factory, config, new ElastiCacheProvisioningIds(), resolver); - service = new ElastiCacheServerlessService(factory, resolver, runtime, memcached, runtime); + service = new ElastiCacheServerlessService(factory, resolver, runtime, memcached); runtime.createUser("alice", "alice", AuthMode.PASSWORD, List.of("password-a"), "on ~* +@all", "valkey"); runtime.createUser("bob", "bob", AuthMode.PASSWORD, List.of("password-b"), "on ~* +@all", "valkey"); runtime.createUserGroup("team", "valkey", List.of("alice"), "us-east-1"); @@ -242,7 +243,7 @@ class ElastiCacheServerlessServiceTest { @Test void rehydratedServiceRetainsRuntimeIdentityAndAssociation() { ServerlessCache original = service.createServerlessCache(create("cache", "valkey", "team")); - ElastiCacheServerlessService reloaded = new ElastiCacheServerlessService(factory, resolver, runtime, memcached, runtime); + ElastiCacheServerlessService reloaded = new ElastiCacheServerlessService(factory, resolver, runtime, memcached); assertEquals(original.getBackingCacheClusterId(), reloaded.getServerlessCache("cache").getBackingCacheClusterId()); error("InvalidUserGroupState", () -> runtime.deleteUserGroup("team")); reloaded.deleteServerlessCache("cache"); @@ -306,14 +307,14 @@ class ElastiCacheServerlessServiceTest { void persistentRestartRestoresHiddenRuntimeCredentialsAndPortOwnership() { StorageFactory persistent = persistentFactory(); ElastiCacheService persistedRuntime = newRuntime(persistent); - ElastiCacheServerlessService persisted = new ElastiCacheServerlessService(persistent, resolver, persistedRuntime, memcached, persistedRuntime); + ElastiCacheServerlessService persisted = new ElastiCacheServerlessService(persistent, resolver, persistedRuntime, memcached); persistedRuntime.createUser("member", "member", AuthMode.PASSWORD, List.of("secret"), "on ~* +@all", "valkey"); persistedRuntime.createUserGroup("persisted-team", "valkey", List.of("member"), "us-east-1"); ServerlessCache original = persisted.createServerlessCache(create("persistent", "valkey", "persisted-team")); persistent.shutdownAll(); StorageFactory reloadedFactory = persistentFactory(); ElastiCacheService reloadedRuntime = newRuntime(reloadedFactory); - ElastiCacheServerlessService reloaded = new ElastiCacheServerlessService(reloadedFactory, resolver, reloadedRuntime, memcached, reloadedRuntime); + ElastiCacheServerlessService reloaded = new ElastiCacheServerlessService(reloadedFactory, resolver, reloadedRuntime, memcached); reloadedFactory.loadAll(); clearInvocations(proxies); reloadedRuntime.restorePersistedRuntime().join(); @@ -361,7 +362,7 @@ class ElastiCacheServerlessServiceTest { assertTrue(backing.getForAccount("111111111111", original.getBackingCacheClusterId()).isPresent()); context.setAccountId("111111111111"); context.setRegion("cn-north-1"); - ElastiCacheServerlessService reloaded = new ElastiCacheServerlessService(factory, resolver, reloadedRuntime, memcached, reloadedRuntime); + ElastiCacheServerlessService reloaded = new ElastiCacheServerlessService(factory, resolver, reloadedRuntime, memcached); assertEquals(original.getEndpoint(), reloaded.getServerlessCache("account-cache").getEndpoint()); reloaded.deleteServerlessCache("account-cache"); runtime.deleteUserGroup("team"); @@ -431,4 +432,39 @@ class ElastiCacheServerlessServiceTest { assertNotNull(runtime.deleteUserGroup("team")); } + + @Test + void modifyWithResetUnsetClearsLimitsAndSnapshotSettingsButOmittedFieldsStayOtherwise() { + service.createServerlessCache(new ElastiCacheServerlessService.CreateServerlessCacheRequest("reset-cache", + "valkey", null, "description", List.of("subnet-local"), List.of("sg-local"), null, null, + new ServerlessCache.CacheUsageLimits(null, new ServerlessCache.EcpuPerSecond(null, 4000)), 7, "05:00", + List.of(), Map.of())); + + ServerlessCache kept = service.modifyServerlessCache(new ElastiCacheServerlessService.ModifyServerlessCacheRequest( + "reset-cache", "d", null, null, null, null, null, null, null, null)); + assertEquals(7, kept.getSnapshotRetentionLimit()); + assertEquals("05:00", kept.getDailySnapshotTime()); + assertNotNull(kept.getCacheUsageLimits()); + + ServerlessCache reset = service.modifyServerlessCache(new ElastiCacheServerlessService.ModifyServerlessCacheRequest( + "reset-cache", "d", null, null, null, null, null, null, null, null, true)); + assertEquals(0, reset.getSnapshotRetentionLimit()); + assertNull(reset.getDailySnapshotTime()); + assertNull(reset.getCacheUsageLimits()); + } + + @Test + void replaceTagsDrivesTheTagsToTheGivenSetAndRejectsMoreThanFifty() { + service.createServerlessCache(create("tag-cache", "valkey", null)); + + assertEquals(Map.of("env", "dev"), service.replaceTags("tag-cache", Map.of("env", "dev")).getTags()); + assertEquals(Map.of("env", "dev"), service.getServerlessCache("tag-cache").getTags()); + + Map tooMany = new HashMap<>(); + for (int i = 0; i < 51; i++) { + tooMany.put("k" + i, "v"); + } + error("TagQuotaPerResourceExceeded", () -> service.replaceTags("tag-cache", tooMany)); + assertEquals(Map.of("env", "dev"), service.getServerlessCache("tag-cache").getTags()); + } } diff --git a/src/test/java/io/github/hectorvent/floci/testing/DockerAvailability.java b/src/test/java/io/github/hectorvent/floci/testing/DockerAvailability.java new file mode 100644 index 0000000000..0f378bc34c --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/testing/DockerAvailability.java @@ -0,0 +1,32 @@ +package io.github.hectorvent.floci.testing; + +import java.io.IOException; +import java.util.concurrent.TimeUnit; + +/** Probe that lets Docker-backed integration tests skip themselves when no daemon answers. */ +public final class DockerAvailability { + + private static final long PROBE_TIMEOUT_SECONDS = 10; + + private DockerAvailability() { + } + + /** True when {@code docker info} succeeds within the probe timeout. */ + public static boolean isAvailable() throws InterruptedException { + Process process; + try { + process = new ProcessBuilder("docker", "info") + .redirectOutput(ProcessBuilder.Redirect.DISCARD) + .redirectError(ProcessBuilder.Redirect.DISCARD) + .start(); + } catch (IOException expected) { + // The Docker CLI is optional on development machines. + return false; + } + if (!process.waitFor(PROBE_TIMEOUT_SECONDS, TimeUnit.SECONDS)) { + process.destroyForcibly(); + return false; + } + return process.exitValue() == 0; + } +} diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index f7030ba587..6ec22b887c 100644 --- a/src/test/resources/cloudformation/supported-resource-types.tsv +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -95,6 +95,7 @@ AWS::ECS::TaskDefinition EcsCfnProvisioner AWS::EKS::Cluster EksCfnProvisioner AWS::EKS::Nodegroup EksCfnProvisioner AWS::ElastiCache::CacheCluster ElastiCacheCfnProvisioner +AWS::ElastiCache::ServerlessCache ElastiCacheServerlessCfnProvisioner AWS::ElastiCache::SubnetGroup ElastiCacheCfnProvisioner AWS::ElastiCache::User ElastiCacheCfnProvisioner AWS::ElastiCache::UserGroup ElastiCacheCfnProvisioner diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml index e009864285..0f32406c87 100644 --- a/tools/docs/cfn_resource_types.yaml +++ b/tools/docs/cfn_resource_types.yaml @@ -88,7 +88,7 @@ type_order: AWS::RDS: [DBInstance, DBCluster, DBSubnetGroup, DBParameterGroup, DBClusterParameterGroup] AWS::ElastiCache: - [CacheCluster, SubnetGroup, User, UserGroup] + [CacheCluster, SubnetGroup, User, UserGroup, ServerlessCache] AWS::Redshift: [Cluster, ClusterParameterGroup, ClusterSubnetGroup, ClusterSecurityGroup] AWS::RedshiftServerless: @@ -180,6 +180,7 @@ notes: AWS::ElastiCache::CacheCluster: 'starts a real container; modifying an existing cluster in place is not supported' AWS::ElastiCache::User: Tags are ignored AWS::ElastiCache::UserGroup: Tags are ignored + AWS::ElastiCache::ServerlessCache: 'GetAtt uses the dotted Endpoint.* and ReaderEndpoint.* form' 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'