Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

refactor(cloudformation): move AWS::ECS::Cluster, TaskDefinition and Service into EcsCfnProvisioner (#3114)

Hector Ventura9df197f3af3c
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
index e824424983..b1da5d2020 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
@@ -46,7 +46,6 @@ import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.kinesis.KinesisService;
import io.github.hectorvent.floci.services.kinesis.model.KinesisStream;
import io.github.hectorvent.floci.services.ec2.model.Tag;
-import io.github.hectorvent.floci.services.ecs.EcsService;
import io.github.hectorvent.floci.services.firehose.FirehoseService;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription;
import io.github.hectorvent.floci.services.rds.RdsService;
@@ -59,18 +58,6 @@ import io.github.hectorvent.floci.services.rds.model.DbSubnetGroup;
import io.github.hectorvent.floci.services.eks.EksService;
import io.github.hectorvent.floci.services.eks.model.CreateClusterRequest;
import io.github.hectorvent.floci.services.eks.model.Nodegroup;
-import io.github.hectorvent.floci.services.ecs.model.AwsVpcConfiguration;
-import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
-import io.github.hectorvent.floci.services.ecs.model.EcsCluster;
-import io.github.hectorvent.floci.services.ecs.model.EcsLoadBalancer;
-import io.github.hectorvent.floci.services.ecs.model.EcsServiceModel;
-import io.github.hectorvent.floci.services.ecs.model.KeyValuePair;
-import io.github.hectorvent.floci.services.ecs.model.LaunchType;
-import io.github.hectorvent.floci.services.ecs.model.NetworkConfiguration;
-import io.github.hectorvent.floci.services.ecs.model.NetworkMode;
-import io.github.hectorvent.floci.services.ecs.model.PortMapping;
-import io.github.hectorvent.floci.services.ecs.model.Secret;
-import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import io.github.hectorvent.floci.services.elbv2.ElbV2Service;
import io.github.hectorvent.floci.services.elbv2.model.Action;
import io.github.hectorvent.floci.services.elbv2.model.Listener;
@@ -239,9 +226,6 @@ public class CloudFormationResourceProvisioner {
"AWS::EC2::SecurityGroup",
"AWS::EC2::Subnet",
"AWS::EC2::SubnetRouteTableAssociation",
- "AWS::ECS::Cluster",
- "AWS::ECS::Service",
- "AWS::ECS::TaskDefinition",
"AWS::EKS::Cluster",
"AWS::EKS::Nodegroup",
"AWS::ElasticLoadBalancingV2::Listener",
@@ -294,7 +278,6 @@ public class CloudFormationResourceProvisioner {
private final ObjectMapper objectMapper;
private final CustomResourceResponseStore customResourceResponseStore;
private final ContainerReachableEndpoint reachableEndpoint;
- private final EcsService ecsService;
private final ElbV2Service elbV2Service;
private final StepFunctionsService stepFunctionsService;
private final BatchService batchService;
@@ -327,7 +310,6 @@ public class CloudFormationResourceProvisioner {
ObjectMapper objectMapper,
CustomResourceResponseStore customResourceResponseStore,
ContainerReachableEndpoint reachableEndpoint,
- EcsService ecsService,
ElbV2Service elbV2Service,
StepFunctionsService stepFunctionsService,
BatchService batchService,
@@ -358,7 +340,6 @@ public class CloudFormationResourceProvisioner {
this.objectMapper = objectMapper;
this.customResourceResponseStore = customResourceResponseStore;
this.reachableEndpoint = reachableEndpoint;
- this.ecsService = ecsService;
this.elbV2Service = elbV2Service;
this.stepFunctionsService = stepFunctionsService;
this.batchService = batchService;
@@ -458,9 +439,6 @@ public class CloudFormationResourceProvisioner {
case "AWS::CloudFormation::CustomResource" ->
provisionCustomResource(resource, properties, engine, region, accountId, stackName);
case "Custom::DynamoDBReplica" -> provisionDynamoDbReplica(resource, properties, engine, region);
- case "AWS::ECS::Cluster" -> provisionEcsCluster(resource, properties, engine, region, stackName);
- case "AWS::ECS::TaskDefinition" -> provisionEcsTaskDefinition(resource, properties, engine, region, stackName);
- case "AWS::ECS::Service" -> provisionEcsService(resource, properties, engine, region, stackName);
case "AWS::ElasticLoadBalancingV2::LoadBalancer" ->
provisionLoadBalancer(resource, properties, engine, region, stackName);
case "AWS::ElasticLoadBalancingV2::TargetGroup" ->
@@ -744,9 +722,6 @@ public class CloudFormationResourceProvisioner {
case "AWS::Lambda::LayerVersion" -> deleteLambdaLayerVersion(physicalId, region);
case "AWS::Cognito::UserPool" -> cognitoService.deleteUserPool(physicalId);
case "AWS::Cognito::UserPoolClient" -> cognitoService.deleteUserPoolClient(physicalId);
- case "AWS::ECS::Cluster" -> deleteEcsClusterSafe(physicalId, region);
- case "AWS::ECS::TaskDefinition" -> deleteEcsTaskDefinitionSafe(physicalId, region);
- case "AWS::ECS::Service" -> deleteEcsServiceSafe(physicalId, region);
case "AWS::ElasticLoadBalancingV2::LoadBalancer" -> elbV2Service.deleteLoadBalancer(region, physicalId);
case "AWS::ElasticLoadBalancingV2::TargetGroup" -> elbV2Service.deleteTargetGroup(region, physicalId);
case "AWS::ElasticLoadBalancingV2::Listener" -> elbV2Service.deleteListener(region, physicalId);
@@ -6249,260 +6224,6 @@ public class CloudFormationResourceProvisioner {
return account.matches("\\d{12}") ? account : "000000000000";
}
- // ── ECS ──────────────────────────────────────────────────────────────────
-
- private void provisionEcsCluster(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
- String region, String stackName) {
- String clusterName = resolveOptional(props, "ClusterName", engine);
- if (clusterName == null || clusterName.isBlank()) {
- clusterName = generatePhysicalName(stackName, r.getLogicalId(), 255, false);
- }
- // createCluster is idempotent, so re-running it on a stack update reuses the existing cluster.
- EcsCluster cluster = ecsService.createCluster(clusterName, region);
- r.setPhysicalId(cluster.getClusterName());
- r.getAttributes().put("Arn", cluster.getClusterArn());
- }
-
- private void provisionEcsTaskDefinition(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
- String region, String stackName) {
- String family = resolveOptional(props, "Family", engine);
- if (family == null || family.isBlank()) {
- family = generatePhysicalName(stackName, r.getLogicalId(), 255, false);
- }
- List<ContainerDefinition> containerDefs =
- parseContainerDefinitions(props != null ? props.get("ContainerDefinitions") : null, engine);
- NetworkMode networkMode = parseNetworkMode(resolveOptional(props, "NetworkMode", engine));
- String cpu = resolveOptional(props, "Cpu", engine);
- String memory = resolveOptional(props, "Memory", engine);
- String taskRoleArn = resolveOptional(props, "TaskRoleArn", engine);
- String executionRoleArn = resolveOptional(props, "ExecutionRoleArn", engine);
- List<String> requiresCompatibilities = resolveStringListOrEmpty(props, "RequiresCompatibilities", engine);
-
- // Task definitions are immutable; each CFN update registers a fresh revision.
- TaskDefinition td = ecsService.registerTaskDefinition(family, containerDefs, networkMode, cpu, memory,
- taskRoleArn, executionRoleArn, requiresCompatibilities, region);
-
- r.setPhysicalId(td.getTaskDefinitionArn());
- r.getAttributes().put("TaskDefinitionArn", td.getTaskDefinitionArn());
- }
-
- private void provisionEcsService(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
- String region, String stackName) {
- String clusterRef = resolveOptional(props, "Cluster", engine);
- String taskDefinition = resolveOptional(props, "TaskDefinition", engine);
- int desiredCount = intOrDefault(resolveOptional(props, "DesiredCount", engine), 1);
- LaunchType launchType = parseLaunchType(resolveOptional(props, "LaunchType", engine));
- List<EcsLoadBalancer> loadBalancers =
- parseEcsLoadBalancers(props != null ? props.get("LoadBalancers") : null, engine);
- NetworkConfiguration networkConfiguration =
- parseEcsNetworkConfiguration(props != null ? props.get("NetworkConfiguration") : null, engine);
-
- String serviceName = resolveOptional(props, "ServiceName", engine);
- if (serviceName == null || serviceName.isBlank()) {
- serviceName = r.getAttributes().get("Name");
- }
- if (serviceName == null || serviceName.isBlank()) {
- serviceName = generatePhysicalName(stackName, r.getLogicalId(), 255, false);
- }
-
- EcsServiceModel svc;
- if (r.getPhysicalId() == null) {
- svc = ecsService.createService(clusterRef, serviceName, taskDefinition,
- desiredCount, launchType, loadBalancers, networkConfiguration, region);
- } else {
- svc = ecsService.updateService(clusterRef, serviceName, taskDefinition,
- desiredCount, networkConfiguration, region);
- }
-
- r.setPhysicalId(svc.getServiceArn());
- r.getAttributes().put("Name", svc.getServiceName());
- r.getAttributes().put("ServiceArn", svc.getServiceArn());
- }
-
- private void deleteEcsServiceSafe(String serviceArn, String region) {
- // Floci service ARNs embed the cluster: arn:aws:ecs:<region>:<acct>:service/<cluster>/<service>.
- // Parse both so the right cluster's tasks get stopped during teardown.
- String clusterRef = null;
- String serviceName = serviceArn;
- try {
- String[] segments = AwsArnUtils.parse(serviceArn).resource().split("/");
- if (segments.length == 3) {
- clusterRef = segments[1];
- serviceName = segments[2];
- } else if (segments.length == 2) {
- // Legacy ARN format without an embedded cluster: service/<service>.
- serviceName = segments[1];
- }
- } catch (IllegalArgumentException e) {
- // Not an ARN; treat the value as a bare service name.
- }
- try {
- ecsService.deleteService(clusterRef, serviceName, true, region);
- } catch (AwsException e) {
- // Idempotent delete: only an already-gone service (e.g. after a persistent restore that
- // dropped ECS state) is treated as delete-complete. Any other error must still fail the
- // stack delete rather than being silently swallowed. See issue #1634.
- if (!"ServiceNotFoundException".equals(e.getErrorCode())) {
- throw e;
- }
- LOG.debugv("ECS service {0} already gone, treating delete as complete: {1}",
- serviceArn, e.getMessage());
- }
- }
-
- private void deleteEcsTaskDefinitionSafe(String physicalId, String region) {
- try {
- ecsService.deregisterTaskDefinition(physicalId, region);
- } catch (AwsException e) {
- // Idempotent delete: only an already-missing task definition (ClientException "Unable to
- // describe task definition", e.g. after a persistent restore) is delete-complete. Other
- // errors must still fail the stack delete. See #1634.
- if (!"ClientException".equals(e.getErrorCode())) {
- throw e;
- }
- LOG.debugv("ECS task definition {0} already gone, treating delete as complete: {1}",
- physicalId, e.getMessage());
- }
- }
-
- private void deleteEcsClusterSafe(String physicalId, String region) {
- try {
- ecsService.deleteCluster(physicalId, region);
- } catch (AwsException e) {
- // Idempotent delete: only an already-missing cluster is delete-complete. A genuine
- // failure such as ClusterContainsTasksException must still fail the stack delete. See #1634.
- if (!"ClusterNotFoundException".equals(e.getErrorCode())) {
- throw e;
- }
- LOG.debugv("ECS cluster {0} already gone, treating delete as complete: {1}",
- physicalId, e.getMessage());
- }
- }
-
- private List<ContainerDefinition> parseContainerDefinitions(JsonNode node, CloudFormationTemplateEngine engine) {
- List<ContainerDefinition> result = new ArrayList<>();
- if (node == null || node.isNull()) {
- return result;
- }
- JsonNode resolved = engine.resolveNode(node);
- if (resolved == null || !resolved.isArray()) {
- return result;
- }
- for (JsonNode item : resolved) {
- ContainerDefinition def = new ContainerDefinition();
- def.setName(item.path("Name").asText(null));
- def.setImage(item.path("Image").asText(null));
- def.setEssential(item.path("Essential").asBoolean(true));
- if (item.hasNonNull("Cpu")) {
- def.setCpu(item.path("Cpu").asInt());
- }
- if (item.hasNonNull("Memory")) {
- def.setMemory(item.path("Memory").asInt());
- }
- if (item.hasNonNull("MemoryReservation")) {
- def.setMemoryReservation(item.path("MemoryReservation").asInt());
- }
- def.setPortMappings(parseCfnPortMappings(item.path("PortMappings")));
- def.setEnvironment(parseCfnEnvironment(item.path("Environment")));
- def.setSecrets(parseCfnSecrets(item.path("Secrets")));
- if (item.path("Command").isArray()) {
- List<String> cmd = new ArrayList<>();
- item.path("Command").forEach(c -> cmd.add(c.asText()));
- def.setCommand(cmd);
- }
- if (item.path("EntryPoint").isArray()) {
- List<String> ep = new ArrayList<>();
- item.path("EntryPoint").forEach(e -> ep.add(e.asText()));
- def.setEntryPoint(ep);
- }
- result.add(def);
- }
- return result;
- }
-
- private List<PortMapping> parseCfnPortMappings(JsonNode node) {
- List<PortMapping> result = new ArrayList<>();
- if (node == null || !node.isArray()) {
- return result;
- }
- for (JsonNode item : node) {
- int containerPort = item.path("ContainerPort").asInt(0);
- int hostPort = item.path("HostPort").asInt(0);
- String protocol = item.path("Protocol").asText("tcp");
- result.add(new PortMapping(containerPort, hostPort, protocol));
- }
- return result;
- }
-
- private List<KeyValuePair> parseCfnEnvironment(JsonNode node) {
- List<KeyValuePair> result = new ArrayList<>();
- if (node == null || !node.isArray()) {
- return result;
- }
- for (JsonNode item : node) {
- result.add(new KeyValuePair(item.path("Name").asText(), item.path("Value").asText()));
- }
- return result;
- }
-
- private List<Secret> parseCfnSecrets(JsonNode node) {
- List<Secret> result = new ArrayList<>();
- if (node == null || !node.isArray()) {
- return result;
- }
- for (JsonNode item : node) {
- result.add(new Secret(item.path("Name").asText(), item.path("ValueFrom").asText()));
- }
- return result;
- }
-
- private List<EcsLoadBalancer> parseEcsLoadBalancers(JsonNode node, CloudFormationTemplateEngine engine) {
- List<EcsLoadBalancer> result = new ArrayList<>();
- if (node == null || node.isNull()) {
- return result;
- }
- JsonNode resolved = engine.resolveNode(node);
- if (resolved == null || !resolved.isArray()) {
- return result;
- }
- for (JsonNode item : resolved) {
- EcsLoadBalancer lb = new EcsLoadBalancer();
- if (item.hasNonNull("TargetGroupArn")) {
- lb.setTargetGroupArn(item.path("TargetGroupArn").asText());
- }
- if (item.hasNonNull("LoadBalancerName")) {
- lb.setLoadBalancerName(item.path("LoadBalancerName").asText());
- }
- if (item.hasNonNull("ContainerName")) {
- lb.setContainerName(item.path("ContainerName").asText());
- }
- if (item.hasNonNull("ContainerPort")) {
- lb.setContainerPort(item.path("ContainerPort").asInt());
- }
- result.add(lb);
- }
- return result;
- }
-
- private NetworkConfiguration parseEcsNetworkConfiguration(JsonNode node, CloudFormationTemplateEngine engine) {
- if (node == null || node.isNull()) {
- return null;
- }
- JsonNode resolved = engine.resolveNode(node);
- if (resolved == null || !resolved.isObject() || !resolved.hasNonNull("AwsvpcConfiguration")) {
- return null;
- }
- JsonNode awsvpc = resolved.path("AwsvpcConfiguration");
- AwsVpcConfiguration awsvpcConfig = new AwsVpcConfiguration();
- awsvpcConfig.setSubnets(jsonArrayToStringList(awsvpc.path("Subnets")));
- awsvpcConfig.setSecurityGroups(jsonArrayToStringList(awsvpc.path("SecurityGroups")));
- if (awsvpc.hasNonNull("AssignPublicIp")) {
- awsvpcConfig.setAssignPublicIp(awsvpc.path("AssignPublicIp").asText());
- }
- NetworkConfiguration networkConfiguration = new NetworkConfiguration();
- networkConfiguration.setAwsvpcConfiguration(awsvpcConfig);
- return networkConfiguration;
- }
private static List<String> jsonArrayToStringList(JsonNode node) {
List<String> result = new ArrayList<>();
@@ -6512,28 +6233,6 @@ public class CloudFormationResourceProvisioner {
return result;
}
- private static NetworkMode parseNetworkMode(String value) {
- if (value == null || value.isBlank()) {
- return null;
- }
- try {
- return NetworkMode.valueOf(value);
- } catch (IllegalArgumentException e) {
- return null;
- }
- }
-
- private static LaunchType parseLaunchType(String value) {
- if (value == null || value.isBlank()) {
- return null;
- }
- try {
- return LaunchType.valueOf(value);
- } catch (IllegalArgumentException e) {
- return null;
- }
- }
-
// ── ELBv2 ────────────────────────────────────────────────────────────────
private void provisionLoadBalancer(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java
index 7b18376e44..b456c22826 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java
@@ -1243,7 +1243,7 @@ public class CloudFormationService implements ResourceProvider {
List<UpdateCleanupFailure> cleanupFailures =
new ArrayList<>(deleteRemovedOrConditionFalseResources(
stack, resources, conditions, region));
- cleanupFailures.addAll(finishCommittedResourceCleanup(stack));
+ cleanupFailures.addAll(finishCommittedResourceCleanup(stack, region));
finishCommittedStackUpdate(stack, cleanupFailures);
return;
}
@@ -1334,9 +1334,16 @@ public class CloudFormationService implements ResourceProvider {
persistStack(stack);
}
- private List<UpdateCleanupFailure> finishCommittedResourceCleanup(Stack stack) {
+ private List<UpdateCleanupFailure> finishCommittedResourceCleanup(Stack stack, String region) {
List<UpdateCleanupFailure> failures = new ArrayList<>();
- for (StackResource resource : stack.getResources().values()) {
+ // Dependents go before what they depend on, as when the stack is deleted: a displaced
+ // listener has to go before the displaced target group it still forwards to, or that
+ // delete fails ResourceInUse three times and leaves the group behind. The template's
+ // order, not the map's: a resource a later update added sits after the resources that
+ // depend on it, so reversing the map would delete it first.
+ List<StackResource> resources = resourcesInCreationOrder(stack, region);
+ Collections.reverse(resources);
+ for (StackResource resource : resources) {
String cleanupPhysicalId = provisioner.updateCleanupPhysicalId(resource);
if (cleanupPhysicalId != null) {
addEvent(
@@ -1822,7 +1829,7 @@ public class CloudFormationService implements ResourceProvider {
// last update left in place. An entity displaced by a replacement whose cleanup phase
// never ended is named only by the cleanup the resource still carries, so the stack
// deletes that one too: nothing else ever will.
- for (UpdateCleanupFailure displacedFailure : finishCommittedResourceCleanup(stack)) {
+ for (UpdateCleanupFailure displacedFailure : finishCommittedResourceCleanup(stack, region)) {
failedResources.add(displacedFailure.logicalId());
}
for (StackResource resource : resources) {
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 c250e58d6a..8f00ddc534 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
@@ -54,6 +54,15 @@ public final class CfnRollback {
*/
public static final String PIPE_RENAME_CLEANUP_ATTR = "__FlociPipeRenameCleanup";
+ /**
+ * Holds the entity a replacing update displaced, for provisioners whose replacement needs no
+ * rollback snapshot: the prior physical id, its resource type and region, and how many times
+ * deleting it has been attempted. Written by {@link ReplacementCleanup#record} when a
+ * provision leaves the resource with a new physical id, and spent by {@code completeUpdate}
+ * once the update has committed.
+ */
+ public static final String REPLACEMENT_CLEANUP_ATTR = "__FlociReplacementCleanup";
+
private CfnRollback() {
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcsCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcsCfnProvisioner.java
new file mode 100644
index 0000000000..b655f33c28
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcsCfnProvisioner.java
@@ -0,0 +1,398 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import io.github.hectorvent.floci.core.common.AwsArnUtils;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import io.github.hectorvent.floci.services.ecs.EcsService;
+import io.github.hectorvent.floci.services.ecs.model.AwsVpcConfiguration;
+import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
+import io.github.hectorvent.floci.services.ecs.model.EcsCluster;
+import io.github.hectorvent.floci.services.ecs.model.EcsLoadBalancer;
+import io.github.hectorvent.floci.services.ecs.model.EcsServiceModel;
+import io.github.hectorvent.floci.services.ecs.model.KeyValuePair;
+import io.github.hectorvent.floci.services.ecs.model.LaunchType;
+import io.github.hectorvent.floci.services.ecs.model.NetworkConfiguration;
+import io.github.hectorvent.floci.services.ecs.model.NetworkMode;
+import io.github.hectorvent.floci.services.ecs.model.PortMapping;
+import io.github.hectorvent.floci.services.ecs.model.Secret;
+import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * CloudFormation provisioning for the ECS core types, {@code AWS::ECS::Cluster},
+ * {@code AWS::ECS::TaskDefinition} and {@code AWS::ECS::Service}, moved out of the
+ * {@code CloudFormationResourceProvisioner} switch. Capacity providers live in
+ * {@link EcsCapacityCfnProvisioner}.
+ */
+@ApplicationScoped
+public class EcsCfnProvisioner implements CfnResourceProvisioner {
+
+ private static final Logger LOG = Logger.getLogger(EcsCfnProvisioner.class);
+
+ private static final String CLUSTER = "AWS::ECS::Cluster";
+ private static final String TASK_DEFINITION = "AWS::ECS::TaskDefinition";
+ private static final String SERVICE = "AWS::ECS::Service";
+
+ private final EcsService ecsService;
+
+ @Inject
+ public EcsCfnProvisioner(EcsService ecsService) {
+ this.ecsService = ecsService;
+ }
+
+ @Override
+ public Set<String> resourceTypes() {
+ return Set.of(CLUSTER, TASK_DEFINITION, SERVICE);
+ }
+
+ @Override
+ public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
+ Map<String, String> attributesBefore = Map.copyOf(r.getAttributes());
+ switch (r.getResourceType()) {
+ case CLUSTER -> provisionCluster(r, props, ctx);
+ case TASK_DEFINITION -> provisionTaskDefinition(r, props, ctx);
+ case SERVICE -> provisionService(r, props, ctx);
+ default -> throw new IllegalStateException("EcsCfnProvisioner cannot handle " + r.getResourceType());
+ }
+ // A provision that left the resource with a new physical id replaced the entity: the
+ // displaced one is deleted once the update commits, or restored if the update rolls back.
+ ReplacementCleanup.record(r, ctx, attributesBefore);
+ }
+
+ @Override
+ public void delete(String resourceType, String physicalId, String region) {
+ if (physicalId == null || physicalId.isBlank()) {
+ return;
+ }
+ switch (resourceType) {
+ // Only the service's own not-found code is tolerated: a real failure such as
+ // ClusterContainsTasksException must still fail the stack delete (#1634).
+ case CLUSTER -> CfnDeletes.safeDelete("ECS cluster", physicalId,
+ () -> ecsService.deleteCluster(physicalId, region), "ClusterNotFoundException");
+ // An already-missing task definition, for example after a persistent restore that
+ // dropped ECS state, surfaces as ClientException "Unable to describe task definition".
+ case TASK_DEFINITION -> CfnDeletes.safeDelete("ECS task definition", physicalId,
+ () -> ecsService.deregisterTaskDefinition(physicalId, region), "ClientException");
+ case SERVICE -> deleteService(physicalId, region);
+ default -> { }
+ }
+ }
+
+ @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) {
+ ReplacementCleanup.clear(resource);
+ }
+
+ /**
+ * A replacement is undone through the cleanup record. Without one, a cluster has nothing to put
+ * back: its only property is the create-only name, so an update that kept it re-issued the
+ * idempotent create and changed nothing. A service without a record was updated in place, and
+ * putting that back needs a snapshot this provisioner does not keep, so the engine reports it as
+ * not rolled back, as it did for the switch.
+ */
+ @Override
+ public boolean rollbackUpdate(StackResource resource) {
+ if (ReplacementCleanup.rollback(resource, this::delete)) {
+ return true;
+ }
+ return CLUSTER.equals(resource.getResourceType());
+ }
+
+ /**
+ * The cluster name is create-only and the physical id, so an unnamed cluster keeps the name its
+ * first execution generated. createCluster is idempotent, which is what makes an unchanged
+ * update a no-op here.
+ */
+ private void provisionCluster(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String clusterName = ctx.stablePhysicalName(ctx.resolveOptional(props, "ClusterName"),
+ r.getLogicalId(), 255, false);
+ EcsCluster cluster = ecsService.createCluster(clusterName, ctx.region());
+ r.setPhysicalId(cluster.getClusterName());
+ r.getAttributes().put("Arn", cluster.getClusterArn());
+ }
+
+ /**
+ * Every property of a task definition is create-only, so an update registers a fresh revision
+ * under the same family, as CloudFormation does on AWS; the physical id is the new revision's
+ * ARN, and the displaced revision is deregistered once the stack update commits.
+ */
+ private void provisionTaskDefinition(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String family = ctx.resolveOptional(props, "Family");
+ if (family == null || family.isBlank()) {
+ family = ctx.generatePhysicalName(r.getLogicalId(), 255, false);
+ }
+ List<ContainerDefinition> containerDefs =
+ parseContainerDefinitions(props != null ? props.get("ContainerDefinitions") : null, ctx);
+ NetworkMode networkMode = parseEnum(NetworkMode.class, ctx.resolveOptional(props, "NetworkMode"));
+ String cpu = ctx.resolveOptional(props, "Cpu");
+ String memory = ctx.resolveOptional(props, "Memory");
+ String taskRoleArn = ctx.resolveOptional(props, "TaskRoleArn");
+ String executionRoleArn = ctx.resolveOptional(props, "ExecutionRoleArn");
+ List<String> requiresCompatibilities = ctx.resolveStringList(props, "RequiresCompatibilities");
+
+ TaskDefinition td = ecsService.registerTaskDefinition(family, containerDefs, networkMode, cpu, memory,
+ taskRoleArn, executionRoleArn, requiresCompatibilities, ctx.region());
+
+ r.setPhysicalId(td.getTaskDefinitionArn());
+ r.getAttributes().put("TaskDefinitionArn", td.getTaskDefinitionArn());
+ }
+
+ /**
+ * The physical id is the service ARN, not the name, so the name an unnamed service got at
+ * create time is read back from the {@code Name} attribute rather than the prior id. An update
+ * that keeps the name and the cluster updates the service in place; a changed name or a
+ * changed cluster (both create-only) is a replacement: the new service is created and the
+ * displaced one deleted once the stack update commits, through the replacement cleanup.
+ */
+ private void provisionService(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String clusterRef = ctx.resolveOptional(props, "Cluster");
+ String taskDefinition = ctx.resolveOptional(props, "TaskDefinition");
+ int desiredCount = parseDesiredCount(ctx.resolveOptional(props, "DesiredCount"));
+ LaunchType launchType = parseEnum(LaunchType.class, ctx.resolveOptional(props, "LaunchType"));
+ List<EcsLoadBalancer> loadBalancers =
+ parseLoadBalancers(props != null ? props.get("LoadBalancers") : null, ctx);
+ NetworkConfiguration networkConfiguration =
+ parseNetworkConfiguration(props != null ? props.get("NetworkConfiguration") : null, ctx);
+
+ String priorName = r.getAttributes().get("Name");
+ String serviceName = ctx.resolveOptional(props, "ServiceName");
+ if (serviceName == null || serviceName.isBlank()) {
+ serviceName = priorName;
+ }
+ if (serviceName == null || serviceName.isBlank()) {
+ serviceName = ctx.generatePhysicalName(r.getLogicalId(), 255, false);
+ }
+
+ EcsServiceModel svc;
+ if (ctx.isUpdate() && serviceName.equals(priorName)
+ && clusterName(clusterRef).equals(clusterOfServiceArn(ctx.priorPhysicalId()))) {
+ svc = ecsService.updateService(clusterRef, serviceName, taskDefinition,
+ desiredCount, networkConfiguration, ctx.region());
+ } else {
+ svc = ecsService.createService(clusterRef, serviceName, taskDefinition,
+ desiredCount, launchType, loadBalancers, networkConfiguration, ctx.region());
+ }
+
+ r.setPhysicalId(svc.getServiceArn());
+ r.getAttributes().put("Name", svc.getServiceName());
+ r.getAttributes().put("ServiceArn", svc.getServiceArn());
+ }
+
+ /** The cluster name a template value addresses: a name, an ARN's last segment, or the default. */
+ private static String clusterName(String clusterRef) {
+ if (clusterRef == null || clusterRef.isBlank()) {
+ return "default";
+ }
+ int slash = clusterRef.lastIndexOf('/');
+ return clusterRef.startsWith("arn:") && slash >= 0 ? clusterRef.substring(slash + 1) : clusterRef;
+ }
+
+ /** The cluster segment of {@code service/<cluster>/<name>}; the legacy {@code service/<name>} form is the default. */
+ private static String clusterOfServiceArn(String serviceArn) {
+ try {
+ String[] segments = AwsArnUtils.parse(serviceArn).resource().split("/");
+ return segments.length == 3 ? segments[1] : "default";
+ } catch (IllegalArgumentException e) {
+ return "default";
+ }
+ }
+
+ /**
+ * Floci service ARNs embed the cluster, {@code arn:aws:ecs:<region>:<acct>:service/<cluster>/<service>},
+ * so both are parsed out and the right cluster's tasks get stopped during teardown.
+ */
+ private void deleteService(String serviceArn, String region) {
+ String clusterRef = null;
+ String serviceName = serviceArn;
+ try {
+ String[] segments = AwsArnUtils.parse(serviceArn).resource().split("/");
+ if (segments.length == 3) {
+ clusterRef = segments[1];
+ serviceName = segments[2];
+ } else if (segments.length == 2) {
+ serviceName = segments[1];
+ }
+ } catch (IllegalArgumentException e) {
+ LOG.debugv("ECS service id {0} is not an ARN, deleting it as a bare service name", serviceArn);
+ }
+ final String cluster = clusterRef;
+ final String name = serviceName;
+ CfnDeletes.safeDelete("ECS service", serviceArn,
+ () -> ecsService.deleteService(cluster, name, true, region), "ServiceNotFoundException");
+ }
+
+ private static List<ContainerDefinition> parseContainerDefinitions(JsonNode node, ProvisionContext ctx) {
+ List<ContainerDefinition> result = new ArrayList<>();
+ if (node == null || node.isNull()) {
+ return result;
+ }
+ JsonNode resolved = ctx.engine().resolveNode(node);
+ if (resolved == null || !resolved.isArray()) {
+ return result;
+ }
+ for (JsonNode item : resolved) {
+ ContainerDefinition def = new ContainerDefinition();
+ def.setName(item.path("Name").asText(null));
+ def.setImage(item.path("Image").asText(null));
+ def.setEssential(item.path("Essential").asBoolean(true));
+ if (item.hasNonNull("Cpu")) {
+ def.setCpu(item.path("Cpu").asInt());
+ }
+ if (item.hasNonNull("Memory")) {
+ def.setMemory(item.path("Memory").asInt());
+ }
+ if (item.hasNonNull("MemoryReservation")) {
+ def.setMemoryReservation(item.path("MemoryReservation").asInt());
+ }
+ def.setPortMappings(parsePortMappings(item.path("PortMappings")));
+ def.setEnvironment(parseEnvironment(item.path("Environment")));
+ def.setSecrets(parseSecrets(item.path("Secrets")));
+ if (item.path("Command").isArray()) {
+ def.setCommand(toStringList(item.path("Command")));
+ }
+ if (item.path("EntryPoint").isArray()) {
+ def.setEntryPoint(toStringList(item.path("EntryPoint")));
+ }
+ result.add(def);
+ }
+ return result;
+ }
+
+ private static List<PortMapping> parsePortMappings(JsonNode node) {
+ List<PortMapping> result = new ArrayList<>();
+ if (node == null || !node.isArray()) {
+ return result;
+ }
+ for (JsonNode item : node) {
+ result.add(new PortMapping(item.path("ContainerPort").asInt(0), item.path("HostPort").asInt(0),
+ item.path("Protocol").asText("tcp")));
+ }
+ return result;
+ }
+
+ private static List<KeyValuePair> parseEnvironment(JsonNode node) {
+ List<KeyValuePair> result = new ArrayList<>();
+ if (node == null || !node.isArray()) {
+ return result;
+ }
+ for (JsonNode item : node) {
+ result.add(new KeyValuePair(item.path("Name").asText(), item.path("Value").asText()));
+ }
+ return result;
+ }
+
+ private static List<Secret> parseSecrets(JsonNode node) {
+ List<Secret> result = new ArrayList<>();
+ if (node == null || !node.isArray()) {
+ return result;
+ }
+ for (JsonNode item : node) {
+ result.add(new Secret(item.path("Name").asText(), item.path("ValueFrom").asText()));
+ }
+ return result;
+ }
+
+ private static List<EcsLoadBalancer> parseLoadBalancers(JsonNode node, ProvisionContext ctx) {
+ List<EcsLoadBalancer> result = new ArrayList<>();
+ if (node == null || node.isNull()) {
+ return result;
+ }
+ JsonNode resolved = ctx.engine().resolveNode(node);
+ if (resolved == null || !resolved.isArray()) {
+ return result;
+ }
+ for (JsonNode item : resolved) {
+ EcsLoadBalancer lb = new EcsLoadBalancer();
+ if (item.hasNonNull("TargetGroupArn")) {
+ lb.setTargetGroupArn(item.path("TargetGroupArn").asText());
+ }
+ if (item.hasNonNull("LoadBalancerName")) {
+ lb.setLoadBalancerName(item.path("LoadBalancerName").asText());
+ }
+ if (item.hasNonNull("ContainerName")) {
+ lb.setContainerName(item.path("ContainerName").asText());
+ }
+ if (item.hasNonNull("ContainerPort")) {
+ lb.setContainerPort(item.path("ContainerPort").asInt());
+ }
+ result.add(lb);
+ }
+ return result;
+ }
+
+ private static NetworkConfiguration parseNetworkConfiguration(JsonNode node, ProvisionContext ctx) {
+ if (node == null || node.isNull()) {
+ return null;
+ }
+ JsonNode resolved = ctx.engine().resolveNode(node);
+ if (resolved == null || !resolved.isObject() || !resolved.hasNonNull("AwsvpcConfiguration")) {
+ return null;
+ }
+ JsonNode awsvpc = resolved.path("AwsvpcConfiguration");
+ AwsVpcConfiguration awsvpcConfig = new AwsVpcConfiguration();
+ awsvpcConfig.setSubnets(toStringList(awsvpc.path("Subnets")));
+ awsvpcConfig.setSecurityGroups(toStringList(awsvpc.path("SecurityGroups")));
+ if (awsvpc.hasNonNull("AssignPublicIp")) {
+ awsvpcConfig.setAssignPublicIp(awsvpc.path("AssignPublicIp").asText());
+ }
+ NetworkConfiguration networkConfiguration = new NetworkConfiguration();
+ networkConfiguration.setAwsvpcConfiguration(awsvpcConfig);
+ return networkConfiguration;
+ }
+
+ /** An absent or unknown enum value means "not set", as the switch arms treated it. */
+ private static <E extends Enum<E>> E parseEnum(Class<E> type, String value) {
+ if (value == null || value.isBlank()) {
+ return null;
+ }
+ try {
+ return Enum.valueOf(type, value);
+ } catch (IllegalArgumentException e) {
+ LOG.debugv("Ignoring unknown {0} value {1}", type.getSimpleName(), value);
+ return null;
+ }
+ }
+
+ /** DesiredCount defaults to 1 when absent; anything present has to be an integer. */
+ private static int parseDesiredCount(String value) {
+ if (value == null || value.isBlank()) {
+ return 1;
+ }
+ try {
+ return Integer.parseInt(value.trim());
+ } catch (NumberFormatException e) {
+ throw new AwsException("ValidationError", "Value of property DesiredCount must be an integer.", 400);
+ }
+ }
+
+ private static List<String> toStringList(JsonNode node) {
+ List<String> result = new ArrayList<>();
+ if (node != null && node.isArray()) {
+ node.forEach(v -> result.add(v.asText()));
+ }
+ return result;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ReplacementCleanup.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ReplacementCleanup.java
new file mode 100644
index 0000000000..21f24df487
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ReplacementCleanup.java
@@ -0,0 +1,291 @@
+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.services.cloudformation.model.StackResource;
+import org.jboss.logging.Logger;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * The replacement lifecycle for provisioners whose replacing update simply creates the new entity
+ * and leaves the displaced one to be dealt with later: deleted once the stack update commits, the
+ * shape CloudFormation gives every replacement (DELETE_IN_PROGRESS on the old physical id after
+ * UPDATE_COMPLETE_CLEANUP_IN_PROGRESS, three attempts, {@code UpdateReplacePolicy: Retain} keeps it),
+ * or put back when a later resource fails the update and it rolls back.
+ *
+ * <p>The record on the resource lists every entity owed a delete, not only the one this update
+ * displaced: a replacement whose rollback could not delete it stays listed, so the next committed
+ * update or the stack delete removes it instead of it being forgotten. The prior entity's id and
+ * attributes are kept beside the list only while this update's replacement can still be rolled back.
+ *
+ * <p>{@code PipesCfnProvisioner} carries its own richer record because it also snapshots the
+ * entity's configuration for in-place rollback; this is the plain version for types without one.
+ * A provisioner calls {@link #record} at the end of a successful {@code provision} and delegates
+ * the cleanup hooks and {@link #rollback} here.
+ */
+final class ReplacementCleanup {
+
+ private static final Logger LOG = Logger.getLogger(ReplacementCleanup.class);
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private static final int MAX_ATTEMPTS = 3;
+
+ /** Deletes a displaced entity; the caller's own idempotent delete arm. */
+ @FunctionalInterface
+ interface Deleter {
+ void delete(String resourceType, String physicalId, String region);
+ }
+
+ private ReplacementCleanup() {
+ }
+
+ /**
+ * Records the entity this update displaced when the provision left the resource with a new
+ * physical id. Call after the new entity exists, with the attributes the resource carried
+ * before {@code provision} overwrote them: they are what {@link #rollback} puts back. A
+ * provision that replaced nothing drops the rollback fields but keeps any entity an earlier
+ * failed rollback left owed a delete.
+ */
+ static void record(StackResource r, ProvisionContext ctx, Map<String, String> attributesBeforeProvision) {
+ ObjectNode cleanup = readOrEmpty(r);
+ cleanup.remove("priorPhysicalId");
+ cleanup.remove("priorAttributes");
+ cleanup.put("region", ctx.region());
+ String prior = ctx.priorPhysicalId();
+ if (ctx.isUpdate() && !prior.equals(r.getPhysicalId())) {
+ cleanup.put("priorPhysicalId", prior);
+ ObjectNode priorAttributes = cleanup.putObject("priorAttributes");
+ attributesBeforeProvision.forEach((key, value) -> {
+ if (!key.startsWith("__Floci") && value != null) {
+ priorAttributes.put(key, value);
+ }
+ });
+ addDisplaced(cleanup, prior, r.getResourceType(), ctx.region(), true);
+ }
+ write(r, cleanup);
+ }
+
+ /**
+ * Undoes this update's replacement when a later resource failed the stack update: the resource
+ * names the prior entity again, with the attributes it had, and the replacement is deleted. The
+ * prior entity was displaced, never changed, so nothing is written to it.
+ *
+ * <p>The prior leaves the delete list before the replacement's delete is attempted: it is
+ * standing again, and a resource still owing its delete would put it on the next cleanup's list.
+ * A replacement whose delete fails is listed in its place, never retained (a failed update
+ * created it), so the next committed update or the stack delete removes it, and the failure
+ * propagates so the stack reports it. Returns false when this update replaced nothing, which
+ * leaves the engine's handling of in-place updates unchanged.
+ */
+ static boolean rollback(StackResource r, Deleter deleter) {
+ ObjectNode cleanup = read(r);
+ if (cleanup == null || cleanup.path("priorPhysicalId").asText(null) == null) {
+ return false;
+ }
+ String prior = cleanup.path("priorPhysicalId").asText();
+ String replacement = r.getPhysicalId();
+ r.setPhysicalId(prior);
+ Iterator<String> keys = r.getAttributes().keySet().iterator();
+ while (keys.hasNext()) {
+ if (!keys.next().startsWith("__Floci")) {
+ keys.remove();
+ }
+ }
+ cleanup.path("priorAttributes").fields()
+ .forEachRemaining(e -> r.getAttributes().put(e.getKey(), e.getValue().asText()));
+ cleanup.remove("priorPhysicalId");
+ cleanup.remove("priorAttributes");
+ removeDisplaced(cleanup, prior);
+ write(r, cleanup);
+ if (prior.equals(replacement)) {
+ return true;
+ }
+ try {
+ deleter.delete(r.getResourceType(), replacement, region(cleanup, r));
+ } catch (RuntimeException deleteFailure) {
+ addDisplaced(cleanup, replacement, r.getResourceType(), region(cleanup, r), false);
+ write(r, cleanup);
+ throw deleteFailure;
+ }
+ return true;
+ }
+
+ static boolean hasReplacement(StackResource r) {
+ ObjectNode cleanup = read(r);
+ return cleanup != null && cleanup.path("displaced").size() > 0;
+ }
+
+ /**
+ * The first entity still owed a delete, or null when none is or {@code UpdateReplacePolicy:
+ * Retain} keeps it. The engine announces one physical id per resource, so a resource owing
+ * more than one names the first; the rest are deleted in the same cleanup.
+ */
+ static String cleanupPhysicalId(StackResource r) {
+ ObjectNode cleanup = read(r);
+ if (cleanup == null) {
+ return null;
+ }
+ boolean retain = "Retain".equals(r.getUpdateReplacePolicy());
+ for (JsonNode entry : cleanup.path("displaced")) {
+ if (!(retain && entry.path("retainable").asBoolean(false))) {
+ return entry.path("physicalId").asText(null);
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Drops what the cleanup is done with: the record when nothing is owed any more, and otherwise
+ * only the entries that used up their attempts. The engine calls this once the resource's
+ * cleanup either completed or gave up, and giving up on one entity must not forget another
+ * that still has attempts left; that one stays owed for the next committed update or the
+ * stack delete.
+ */
+ static void clear(StackResource r) {
+ ObjectNode cleanup = read(r);
+ if (cleanup == null) {
+ return;
+ }
+ ArrayNode displaced = cleanup.withArray("displaced");
+ ArrayNode kept = MAPPER.createArrayNode();
+ for (JsonNode entry : displaced) {
+ if (entry.path("cleanupAttempts").asInt(0) < MAX_ATTEMPTS) {
+ kept.add(entry);
+ }
+ }
+ cleanup.set("displaced", kept);
+ cleanup.remove("priorPhysicalId");
+ cleanup.remove("priorAttributes");
+ write(r, cleanup);
+ }
+
+ private static void drop(StackResource r) {
+ r.getAttributes().remove(CfnRollback.REPLACEMENT_CLEANUP_ATTR);
+ }
+
+ /**
+ * One delete attempt for every entity still owed one. An entity whose delete succeeds leaves
+ * the list; one whose delete throws keeps its attempt count and last failure, so the caller's
+ * retries continue where this one stopped and no entity is left untried because another kept
+ * failing. The result reports the lowest attempt count among what remains: the engine retries
+ * while that is below three, so it stops only once every remaining entity has used up its own
+ * attempts. {@code UpdateReplacePolicy: Retain} keeps the entity a committed replacement
+ * displaced, not a replacement a failed update created.
+ */
+ static UpdateCleanupResult complete(StackResource r, Deleter deleter) {
+ ObjectNode cleanup = read(r);
+ if (cleanup == null) {
+ return UpdateCleanupResult.notApplicable();
+ }
+ boolean retain = "Retain".equals(r.getUpdateReplacePolicy());
+ ArrayNode displaced = cleanup.withArray("displaced");
+ ArrayNode remaining = MAPPER.createArrayNode();
+ int attempts = Integer.MAX_VALUE;
+ String failureReason = null;
+ String firstRemaining = null;
+ for (JsonNode node : displaced) {
+ ObjectNode entry = (ObjectNode) node;
+ String physicalId = entry.path("physicalId").asText(null);
+ if (physicalId == null || physicalId.equals(r.getPhysicalId())
+ || (retain && entry.path("retainable").asBoolean(false))) {
+ continue;
+ }
+ int entryAttempts = entry.path("cleanupAttempts").asInt(0);
+ if (entryAttempts < MAX_ATTEMPTS) {
+ try {
+ deleter.delete(entry.path("resourceType").asText(r.getResourceType()), physicalId,
+ entry.path("region").asText(null));
+ continue;
+ } catch (RuntimeException deleteFailure) {
+ entryAttempts++;
+ entry.put("cleanupAttempts", entryAttempts);
+ entry.put("cleanupFailureReason", deleteFailure.getMessage());
+ }
+ }
+ remaining.add(entry);
+ // The result names the entity with the fewest attempts, the one the engine's retries
+ // are still for, so its DELETE_FAILED event points at what is actually still owed.
+ if (entryAttempts < attempts) {
+ attempts = entryAttempts;
+ failureReason = entry.path("cleanupFailureReason").asText(null);
+ firstRemaining = physicalId;
+ }
+ }
+ cleanup.set("displaced", remaining);
+ write(r, cleanup);
+ if (remaining.isEmpty()) {
+ return new UpdateCleanupResult(true, true, firstDisplaced(displaced), 0, null);
+ }
+ return new UpdateCleanupResult(true, false, firstRemaining, attempts, failureReason);
+ }
+
+ private static String firstDisplaced(ArrayNode displaced) {
+ return displaced.isEmpty() ? null : displaced.get(0).path("physicalId").asText(null);
+ }
+
+ private static void addDisplaced(ObjectNode cleanup, String physicalId, String resourceType, String region,
+ boolean retainable) {
+ ArrayNode displaced = cleanup.withArray("displaced");
+ for (JsonNode entry : displaced) {
+ if (physicalId.equals(entry.path("physicalId").asText(null))) {
+ return;
+ }
+ }
+ ObjectNode entry = displaced.addObject();
+ entry.put("physicalId", physicalId);
+ entry.put("resourceType", resourceType);
+ entry.put("region", region);
+ entry.put("retainable", retainable);
+ entry.put("cleanupAttempts", 0);
+ }
+
+ private static void removeDisplaced(ObjectNode cleanup, String physicalId) {
+ ArrayNode displaced = cleanup.withArray("displaced");
+ List<JsonNode> kept = new ArrayList<>();
+ for (JsonNode entry : displaced) {
+ if (!physicalId.equals(entry.path("physicalId").asText(null))) {
+ kept.add(entry);
+ }
+ }
+ displaced.removeAll();
+ kept.forEach(displaced::add);
+ }
+
+ private static String region(ObjectNode cleanup, StackResource r) {
+ return cleanup.path("region").asText(null);
+ }
+
+ private static void write(StackResource r, ObjectNode cleanup) {
+ if (cleanup.path("displaced").size() == 0 && cleanup.path("priorPhysicalId").asText(null) == null) {
+ drop(r);
+ return;
+ }
+ r.getAttributes().put(CfnRollback.REPLACEMENT_CLEANUP_ATTR, cleanup.toString());
+ }
+
+ private static ObjectNode readOrEmpty(StackResource r) {
+ ObjectNode cleanup = read(r);
+ return cleanup == null ? MAPPER.createObjectNode() : cleanup;
+ }
+
+ private static ObjectNode read(StackResource r) {
+ String raw = r.getAttributes().get(CfnRollback.REPLACEMENT_CLEANUP_ATTR);
+ if (raw == null || raw.isBlank()) {
+ return null;
+ }
+ try {
+ JsonNode node = MAPPER.readTree(raw);
+ return node.isObject() ? (ObjectNode) node : null;
+ } catch (JsonProcessingException e) {
+ LOG.warnv("Unreadable replacement cleanup record on {0}, dropping it: {1}", r.getLogicalId(), e.getMessage());
+ drop(r);
+ return null;
+ }
+ }
+}
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 3f0fd369dc..64c583470b 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
@@ -36,6 +36,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2VpcEnd
import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2VpcGatewayAttachmentCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.EcrCfnProvisioner;
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.FirehoseCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.IamRoleCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.IotCfnProvisioner;
@@ -235,6 +236,7 @@ final class CfnProvisionerFixture {
}
if (ecsService != null) {
discovered.add(new EcsCapacityCfnProvisioner(ecsService));
+ discovered.add(new EcsCfnProvisioner(ecsService));
}
if (apiGatewayService != null) {
discovered.add(new ApiGatewayAccountCfnProvisioner(apiGatewayService));
@@ -560,7 +562,6 @@ final class CfnProvisionerFixture {
objectMapper,
customResourceResponseStore,
reachableEndpoint,
- ecsService,
elbV2Service,
stepFunctionsService,
batchService,
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcsCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcsCfnProvisionerTest.java
new file mode 100644
index 0000000000..055ca7493b
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcsCfnProvisionerTest.java
@@ -0,0 +1,591 @@
+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.ArrayNode;
+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.ecs.EcsService;
+import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
+import io.github.hectorvent.floci.services.ecs.model.EcsCluster;
+import io.github.hectorvent.floci.services.ecs.model.EcsLoadBalancer;
+import io.github.hectorvent.floci.services.ecs.model.EcsServiceModel;
+import io.github.hectorvent.floci.services.ecs.model.LaunchType;
+import io.github.hectorvent.floci.services.ecs.model.NetworkConfiguration;
+import io.github.hectorvent.floci.services.ecs.model.NetworkMode;
+import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.InOrder;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Set;
+
+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.anyInt;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.isNull;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.inOrder;
+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;
+
+/**
+ * The ECS core-type provisioner in isolation: one mocked service, no Quarkus boot. The
+ * integration test in {@code CloudFormationIntegrationTest} covers the same three types end to
+ * end, including the exact {@code Fn::GetAtt} keys.
+ */
+class EcsCfnProvisionerTest {
+
+ private static final String REGION = "us-east-1";
+ private static final String CLUSTER_ARN = "arn:aws:ecs:us-east-1:000000000000:cluster/web";
+ private static final String TASK_DEF_ARN = "arn:aws:ecs:us-east-1:000000000000:task-definition/web:3";
+ private static final String SERVICE_ARN = "arn:aws:ecs:us-east-1:000000000000:service/web/front";
+
+ private final EcsService ecs = mock(EcsService.class);
+ private final EcsCfnProvisioner provisioner = new EcsCfnProvisioner(ecs);
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ private ProvisionContext ctx() {
+ return ctx(null);
+ }
+
+ private ProvisionContext ctx(String priorPhysicalId) {
+ CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
+ when(engine.resolve(any())).thenAnswer(inv -> {
+ JsonNode node = inv.getArgument(0);
+ return node == null || node.isMissingNode() || node.isNull() ? null : node.asText();
+ });
+ when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
+ // resolveStringList delegates to the real engine method; for the literal arrays these
+ // tests use it just walks the array and calls resolve(...) per element, stubbed above.
+ when(engine.resolveStringList(any())).thenCallRealMethod();
+ return new ProvisionContext(engine, REGION, "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 EcsCluster cluster(String name) {
+ EcsCluster c = new EcsCluster();
+ c.setClusterName(name);
+ c.setClusterArn("arn:aws:ecs:us-east-1:000000000000:cluster/" + name);
+ return c;
+ }
+
+ private EcsServiceModel service(String name) {
+ EcsServiceModel s = new EcsServiceModel();
+ s.setServiceName(name);
+ s.setServiceArn("arn:aws:ecs:us-east-1:000000000000:service/web/" + name);
+ return s;
+ }
+
+ @Test
+ void declaresTheThreeCoreTypes() {
+ assertEquals(Set.of("AWS::ECS::Cluster", "AWS::ECS::TaskDefinition", "AWS::ECS::Service"),
+ provisioner.resourceTypes());
+ }
+
+ @Test
+ void clusterUsesTheDeclaredNameAndExposesArn() {
+ when(ecs.createCluster("web", REGION)).thenReturn(cluster("web"));
+ StackResource r = resource("AWS::ECS::Cluster", "Cluster");
+
+ provisioner.provision(r, mapper.createObjectNode().put("ClusterName", "web"), ctx());
+
+ assertEquals("web", r.getPhysicalId());
+ assertEquals(CLUSTER_ARN, r.getAttributes().get("Arn"));
+ assertEquals(Set.of("Arn"), r.getAttributes().keySet());
+ }
+
+ @Test
+ void anUnnamedClusterGeneratesANameOnCreateAndKeepsItOnUpdate() {
+ when(ecs.createCluster(anyString(), eq(REGION))).thenAnswer(inv -> cluster(inv.getArgument(0)));
+ StackResource created = resource("AWS::ECS::Cluster", "Cluster");
+ provisioner.provision(created, mapper.createObjectNode(), ctx());
+ String generated = created.getPhysicalId();
+ assertTrue(generated.startsWith("my-stack-Cluster-"), generated);
+
+ StackResource updated = resource("AWS::ECS::Cluster", "Cluster");
+ provisioner.provision(updated, mapper.createObjectNode(), ctx(generated));
+
+ // createCluster is idempotent, so the update re-issues it under the same name instead of
+ // minting a second cluster.
+ assertEquals(generated, updated.getPhysicalId());
+ verify(ecs, times(2)).createCluster(generated, REGION);
+ }
+
+ @Test
+ void taskDefinitionRegistersTheParsedContainersAndExposesTheArn() {
+ TaskDefinition td = new TaskDefinition();
+ td.setTaskDefinitionArn(TASK_DEF_ARN);
+ when(ecs.registerTaskDefinition(eq("web"), anyList(), eq(NetworkMode.awsvpc), eq("256"), eq("512"),
+ eq("arn:aws:iam::000000000000:role/task"), eq("arn:aws:iam::000000000000:role/exec"),
+ eq(List.of("FARGATE")), eq(REGION))).thenReturn(td);
+
+ ObjectNode props = mapper.createObjectNode()
+ .put("Family", "web").put("NetworkMode", "awsvpc").put("Cpu", "256").put("Memory", "512")
+ .put("TaskRoleArn", "arn:aws:iam::000000000000:role/task")
+ .put("ExecutionRoleArn", "arn:aws:iam::000000000000:role/exec");
+ props.putArray("RequiresCompatibilities").add("FARGATE");
+ ObjectNode container = props.putArray("ContainerDefinitions").addObject()
+ .put("Name", "app").put("Image", "nginx:1").put("Cpu", 128).put("Memory", 256);
+ container.putArray("PortMappings").addObject().put("ContainerPort", 80).put("HostPort", 8080);
+ container.putArray("Environment").addObject().put("Name", "MODE").put("Value", "prod");
+ container.putArray("Secrets").addObject().put("Name", "DB").put("ValueFrom", "arn:aws:secretsmanager:x");
+ container.putArray("Command").add("run").add("--fast");
+
+ StackResource r = resource("AWS::ECS::TaskDefinition", "TaskDef");
+ provisioner.provision(r, props, ctx());
+
+ assertEquals(TASK_DEF_ARN, r.getPhysicalId());
+ assertEquals(TASK_DEF_ARN, r.getAttributes().get("TaskDefinitionArn"));
+ @SuppressWarnings("unchecked")
+ ArgumentCaptor<List<ContainerDefinition>> defs = ArgumentCaptor.forClass(List.class);
+ verify(ecs).registerTaskDefinition(eq("web"), defs.capture(), eq(NetworkMode.awsvpc), eq("256"),
+ eq("512"), anyString(), anyString(), anyList(), eq(REGION));
+ ContainerDefinition def = defs.getValue().get(0);
+ assertEquals("app", def.getName());
+ assertEquals("nginx:1", def.getImage());
+ assertEquals(128, def.getCpu());
+ assertEquals(256, def.getMemory());
+ assertEquals(80, def.getPortMappings().get(0).containerPort());
+ assertEquals(8080, def.getPortMappings().get(0).hostPort());
+ assertEquals("tcp", def.getPortMappings().get(0).protocol());
+ assertEquals("prod", def.getEnvironment().get(0).value());
+ assertEquals("arn:aws:secretsmanager:x", def.getSecrets().get(0).valueFrom());
+ assertEquals(List.of("run", "--fast"), def.getCommand());
+ }
+
+ @Test
+ void taskDefinitionWithoutFamilyGeneratesOneAndIgnoresAnUnknownNetworkMode() {
+ TaskDefinition td = new TaskDefinition();
+ td.setTaskDefinitionArn(TASK_DEF_ARN);
+ when(ecs.registerTaskDefinition(anyString(), anyList(), isNull(), isNull(), isNull(), isNull(), isNull(),
+ anyList(), eq(REGION))).thenReturn(td);
+
+ StackResource r = resource("AWS::ECS::TaskDefinition", "TaskDef");
+ provisioner.provision(r, mapper.createObjectNode().put("NetworkMode", "not-a-mode"), ctx());
+
+ ArgumentCaptor<String> family = ArgumentCaptor.forClass(String.class);
+ verify(ecs).registerTaskDefinition(family.capture(), anyList(), isNull(), isNull(), isNull(), isNull(),
+ isNull(), anyList(), eq(REGION));
+ assertTrue(family.getValue().startsWith("my-stack-TaskDef-"), family.getValue());
+ }
+
+ @Test
+ void serviceIsCreatedWithTheParsedLoadBalancersAndNetwork() {
+ when(ecs.createService(eq("web"), eq("front"), eq(TASK_DEF_ARN), eq(2), eq(LaunchType.FARGATE),
+ anyList(), any(), eq(REGION))).thenReturn(service("front"));
+ ObjectNode props = mapper.createObjectNode()
+ .put("Cluster", "web").put("ServiceName", "front").put("TaskDefinition", TASK_DEF_ARN)
+ .put("DesiredCount", "2").put("LaunchType", "FARGATE");
+ props.putArray("LoadBalancers").addObject()
+ .put("TargetGroupArn", "arn:aws:elasticloadbalancing:tg").put("ContainerName", "app").put("ContainerPort", 80);
+ ObjectNode awsvpc = props.putObject("NetworkConfiguration").putObject("AwsvpcConfiguration");
+ awsvpc.putArray("Subnets").add("subnet-1").add("subnet-2");
+ awsvpc.putArray("SecurityGroups").add("sg-1");
+ awsvpc.put("AssignPublicIp", "ENABLED");
+
+ StackResource r = resource("AWS::ECS::Service", "Service");
+ provisioner.provision(r, props, ctx());
+
+ assertEquals(SERVICE_ARN, r.getPhysicalId());
+ assertEquals("front", r.getAttributes().get("Name"));
+ assertEquals(SERVICE_ARN, r.getAttributes().get("ServiceArn"));
+ assertEquals(Set.of("Name", "ServiceArn"), r.getAttributes().keySet());
+ @SuppressWarnings("unchecked")
+ ArgumentCaptor<List<EcsLoadBalancer>> lbs = ArgumentCaptor.forClass(List.class);
+ ArgumentCaptor<NetworkConfiguration> net = ArgumentCaptor.forClass(NetworkConfiguration.class);
+ verify(ecs).createService(eq("web"), eq("front"), eq(TASK_DEF_ARN), eq(2), eq(LaunchType.FARGATE),
+ lbs.capture(), net.capture(), eq(REGION));
+ assertEquals("app", lbs.getValue().get(0).getContainerName());
+ assertEquals(80, lbs.getValue().get(0).getContainerPort());
+ assertEquals(List.of("subnet-1", "subnet-2"), net.getValue().getAwsvpcConfiguration().getSubnets());
+ assertEquals("ENABLED", net.getValue().getAwsvpcConfiguration().getAssignPublicIp());
+ }
+
+ @Test
+ void anUnchangedServiceIsUpdatedInPlaceOnTheSecondPass() {
+ when(ecs.updateService(eq("web"), eq("front"), eq(TASK_DEF_ARN), eq(3), isNull(), eq(REGION)))
+ .thenReturn(service("front"));
+ StackResource r = resource("AWS::ECS::Service", "Service");
+ r.getAttributes().put("Name", "front");
+ ObjectNode props = mapper.createObjectNode()
+ .put("Cluster", "web").put("ServiceName", "front").put("TaskDefinition", TASK_DEF_ARN)
+ .put("DesiredCount", "3");
+
+ provisioner.provision(r, props, ctx(SERVICE_ARN));
+
+ assertEquals(SERVICE_ARN, r.getPhysicalId());
+ verify(ecs).updateService("web", "front", TASK_DEF_ARN, 3, null, REGION);
+ verify(ecs, never()).createService(anyString(), anyString(), anyString(), anyInt(), any(), anyList(),
+ any(), anyString());
+ }
+
+ @Test
+ void anUnnamedServiceKeepsTheNameItGotAtCreateTime() {
+ when(ecs.updateService(eq("web"), eq("my-stack-Service-abc"), eq(TASK_DEF_ARN), eq(1), isNull(), eq(REGION)))
+ .thenReturn(service("my-stack-Service-abc"));
+ StackResource r = resource("AWS::ECS::Service", "Service");
+ r.getAttributes().put("Name", "my-stack-Service-abc");
+
+ provisioner.provision(r, mapper.createObjectNode().put("Cluster", "web").put("TaskDefinition", TASK_DEF_ARN),
+ ctx("arn:aws:ecs:us-east-1:000000000000:service/web/my-stack-Service-abc"));
+
+ verify(ecs).updateService("web", "my-stack-Service-abc", TASK_DEF_ARN, 1, null, REGION);
+ }
+
+ @Test
+ void aRenamedServiceIsCreatedAsAReplacement() {
+ when(ecs.createService(eq("web"), eq("front-v2"), eq(TASK_DEF_ARN), eq(1), isNull(), anyList(), isNull(),
+ eq(REGION))).thenReturn(service("front-v2"));
+ StackResource r = resource("AWS::ECS::Service", "Service");
+ r.getAttributes().put("Name", "front");
+
+ provisioner.provision(r, mapper.createObjectNode()
+ .put("Cluster", "web").put("ServiceName", "front-v2").put("TaskDefinition", TASK_DEF_ARN),
+ ctx(SERVICE_ARN));
+
+ assertNotEquals(SERVICE_ARN, r.getPhysicalId());
+ assertEquals("front-v2", r.getAttributes().get("Name"));
+ verify(ecs, never()).updateService(anyString(), anyString(), anyString(), anyInt(), any(), anyString());
+ }
+
+ @Test
+ void aServiceMovedToAnotherClusterIsCreatedAsAReplacementAndTheOldOneCleanedUpAfterCommit() {
+ EcsServiceModel moved = service("front");
+ moved.setServiceArn("arn:aws:ecs:us-east-1:000000000000:service/batch/front");
+ when(ecs.createService(eq("batch"), eq("front"), eq(TASK_DEF_ARN), eq(1), isNull(), anyList(), isNull(),
+ eq(REGION))).thenReturn(moved);
+ StackResource r = resource("AWS::ECS::Service", "Service");
+ r.getAttributes().put("Name", "front");
+
+ provisioner.provision(r, mapper.createObjectNode()
+ .put("Cluster", "batch").put("ServiceName", "front").put("TaskDefinition", TASK_DEF_ARN), ctx(SERVICE_ARN));
+
+ // Cluster is create-only: same name, other cluster is a replacement, never an in-place update
+ // against a service the new cluster may not have (or may have under another owner).
+ verify(ecs, never()).updateService(anyString(), anyString(), anyString(), anyInt(), any(), anyString());
+ assertEquals(moved.getServiceArn(), r.getPhysicalId());
+ assertTrue(provisioner.hasReplacementUpdate(r));
+ assertEquals(SERVICE_ARN, provisioner.updateCleanupPhysicalId(r));
+
+ UpdateCleanupResult cleanup = provisioner.completeUpdate(r);
+
+ InOrder order = inOrder(ecs);
+ order.verify(ecs).createService(eq("batch"), eq("front"), eq(TASK_DEF_ARN), eq(1), isNull(), anyList(), isNull(),
+ eq(REGION));
+ order.verify(ecs).deleteService("web", "front", true, REGION);
+ assertEquals(new UpdateCleanupResult(true, true, SERVICE_ARN, 0, null), cleanup);
+ provisioner.clearUpdate(r);
+ assertFalse(provisioner.hasReplacementUpdate(r));
+ }
+
+ @Test
+ void theClusterGivenAsAnArnStillCountsAsTheSameCluster() {
+ when(ecs.updateService(eq(CLUSTER_ARN), eq("front"), eq(TASK_DEF_ARN), eq(1), isNull(), eq(REGION)))
+ .thenReturn(service("front"));
+ StackResource r = resource("AWS::ECS::Service", "Service");
+ r.getAttributes().put("Name", "front");
+
+ provisioner.provision(r, mapper.createObjectNode()
+ .put("Cluster", CLUSTER_ARN).put("ServiceName", "front").put("TaskDefinition", TASK_DEF_ARN), ctx(SERVICE_ARN));
+
+ verify(ecs).updateService(CLUSTER_ARN, "front", TASK_DEF_ARN, 1, null, REGION);
+ assertFalse(provisioner.hasReplacementUpdate(r), "an in-place update owes no cleanup");
+ }
+
+ @Test
+ void aTaskDefinitionUpdateDeregistersTheDisplacedRevisionAfterCommit() {
+ TaskDefinition next = new TaskDefinition();
+ next.setTaskDefinitionArn(TASK_DEF_ARN.replace(":3", ":4"));
+ when(ecs.registerTaskDefinition(eq("web"), anyList(), isNull(), isNull(), isNull(), isNull(), isNull(), anyList(),
+ eq(REGION))).thenReturn(next);
+ StackResource r = resource("AWS::ECS::TaskDefinition", "TaskDef");
+
+ provisioner.provision(r, mapper.createObjectNode().put("Family", "web"), ctx(TASK_DEF_ARN));
+
+ assertEquals(next.getTaskDefinitionArn(), r.getPhysicalId());
+ assertEquals(TASK_DEF_ARN, provisioner.updateCleanupPhysicalId(r));
+ assertEquals(new UpdateCleanupResult(true, true, TASK_DEF_ARN, 0, null), provisioner.completeUpdate(r));
+ verify(ecs).deregisterTaskDefinition(TASK_DEF_ARN, REGION);
+ }
+
+ @Test
+ void aRetainedDisplacedEntityIsNotDeletedAndAFailingDeleteIsRetriedThreeTimes() {
+ TaskDefinition next = new TaskDefinition();
+ next.setTaskDefinitionArn(TASK_DEF_ARN.replace(":3", ":4"));
+ when(ecs.registerTaskDefinition(eq("web"), anyList(), isNull(), isNull(), isNull(), isNull(), isNull(), anyList(),
+ eq(REGION))).thenReturn(next);
+
+ StackResource retained = resource("AWS::ECS::TaskDefinition", "TaskDef");
+ retained.setUpdateReplacePolicy("Retain");
+ provisioner.provision(retained, mapper.createObjectNode().put("Family", "web"), ctx(TASK_DEF_ARN));
+ assertNull(provisioner.updateCleanupPhysicalId(retained));
+ assertEquals(new UpdateCleanupResult(true, true, TASK_DEF_ARN, 0, null), provisioner.completeUpdate(retained));
+ verify(ecs, never()).deregisterTaskDefinition(anyString(), anyString());
+
+ StackResource failing = resource("AWS::ECS::TaskDefinition", "TaskDef");
+ provisioner.provision(failing, mapper.createObjectNode().put("Family", "web"), ctx(TASK_DEF_ARN));
+ doThrow(new AwsException("ServerException", "busy", 500)).when(ecs).deregisterTaskDefinition(TASK_DEF_ARN, REGION);
+ UpdateCleanupResult first = provisioner.completeUpdate(failing);
+ assertFalse(first.complete());
+ assertEquals(1, first.attempts());
+ provisioner.completeUpdate(failing);
+ UpdateCleanupResult third = provisioner.completeUpdate(failing);
+ assertEquals(3, third.attempts());
+ assertEquals("busy", third.failureReason());
+ UpdateCleanupResult givenUp = provisioner.completeUpdate(failing);
+ assertEquals(3, givenUp.attempts(), "no fourth attempt");
+ verify(ecs, org.mockito.Mockito.times(3)).deregisterTaskDefinition(TASK_DEF_ARN, REGION);
+ }
+
+ @Test
+ void aFailedStackUpdateRollsAReplacementBackToThePriorServiceAndDeletesTheReplacement() {
+ EcsServiceModel moved = service("front");
+ moved.setServiceArn("arn:aws:ecs:us-east-1:000000000000:service/batch/front");
+ when(ecs.createService(eq("batch"), eq("front"), eq(TASK_DEF_ARN), eq(1), isNull(), anyList(), isNull(),
+ eq(REGION))).thenReturn(moved);
+ StackResource r = resource("AWS::ECS::Service", "Service");
+ r.getAttributes().put("Name", "front");
+ r.getAttributes().put("ServiceArn", SERVICE_ARN);
+ provisioner.provision(r, mapper.createObjectNode()
+ .put("Cluster", "batch").put("ServiceName", "front").put("TaskDefinition", TASK_DEF_ARN), ctx(SERVICE_ARN));
+ assertEquals(moved.getServiceArn(), r.getAttributes().get("ServiceArn"));
+
+ assertTrue(provisioner.rollbackUpdate(r));
+
+ // The resource names the prior service again, with the attributes it had, the replacement
+ // is deleted in its cluster, the prior is never touched, and the cleanup record is spent.
+ assertEquals(SERVICE_ARN, r.getPhysicalId());
+ assertEquals(SERVICE_ARN, r.getAttributes().get("ServiceArn"));
+ assertEquals("front", r.getAttributes().get("Name"));
+ verify(ecs).deleteService("batch", "front", true, REGION);
+ verify(ecs, never()).deleteService("web", "front", true, REGION);
+ assertFalse(provisioner.hasReplacementUpdate(r));
+ assertEquals(UpdateCleanupResult.notApplicable(), provisioner.completeUpdate(r));
+ }
+
+ @Test
+ void anUnchangedClusterHasNothingToRollBack() {
+ when(ecs.createCluster("web", REGION)).thenReturn(cluster("web"));
+ StackResource r = resource("AWS::ECS::Cluster", "Cluster");
+ provisioner.provision(r, mapper.createObjectNode().put("ClusterName", "web"), ctx("web"));
+
+ // The idempotent create changed nothing, so the rollback is complete with nothing to do.
+ assertTrue(provisioner.rollbackUpdate(r));
+ assertEquals("web", r.getPhysicalId());
+ verify(ecs, never()).deleteCluster(anyString(), anyString());
+ }
+
+ @Test
+ void anInPlaceUpdateIsNotRolledBackHere() {
+ when(ecs.updateService(eq("web"), eq("front"), eq(TASK_DEF_ARN), eq(3), isNull(), eq(REGION)))
+ .thenReturn(service("front"));
+ StackResource r = resource("AWS::ECS::Service", "Service");
+ r.getAttributes().put("Name", "front");
+ provisioner.provision(r, mapper.createObjectNode()
+ .put("Cluster", "web").put("ServiceName", "front").put("TaskDefinition", TASK_DEF_ARN)
+ .put("DesiredCount", "3"), ctx(SERVICE_ARN));
+
+ assertFalse(provisioner.rollbackUpdate(r), "no replacement means nothing this helper can undo");
+ assertEquals(SERVICE_ARN, r.getPhysicalId());
+ verify(ecs, never()).deleteService(anyString(), anyString(), eq(true), anyString());
+ }
+
+ @Test
+ void aRollbackWhoseDeleteFailsStillPointsTheResourceAtThePriorAndPropagates() {
+ TaskDefinition next = new TaskDefinition();
+ next.setTaskDefinitionArn(TASK_DEF_ARN.replace(":3", ":4"));
+ when(ecs.registerTaskDefinition(eq("web"), anyList(), isNull(), isNull(), isNull(), isNull(), isNull(), anyList(),
+ eq(REGION))).thenReturn(next);
+ doThrow(new AwsException("ServerException", "busy", 500)).when(ecs).deregisterTaskDefinition(next.getTaskDefinitionArn(), REGION);
+ StackResource r = resource("AWS::ECS::TaskDefinition", "TaskDef");
+ r.getAttributes().put("TaskDefinitionArn", TASK_DEF_ARN);
+ provisioner.provision(r, mapper.createObjectNode().put("Family", "web"), ctx(TASK_DEF_ARN));
+
+ AwsException e = assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
+ assertEquals("busy", e.getMessage());
+ assertEquals(TASK_DEF_ARN, r.getPhysicalId());
+ assertEquals(TASK_DEF_ARN, r.getAttributes().get("TaskDefinitionArn"));
+
+ // The replacement the failed update created stays owed a delete; the restored prior does not.
+ assertTrue(provisioner.hasReplacementUpdate(r));
+ assertEquals(next.getTaskDefinitionArn(), provisioner.updateCleanupPhysicalId(r));
+ org.mockito.Mockito.reset(ecs);
+ assertEquals(new UpdateCleanupResult(true, true, next.getTaskDefinitionArn(), 0, null), provisioner.completeUpdate(r));
+ verify(ecs).deregisterTaskDefinition(next.getTaskDefinitionArn(), REGION);
+ verify(ecs, never()).deregisterTaskDefinition(TASK_DEF_ARN, REGION);
+ assertFalse(provisioner.hasReplacementUpdate(r));
+ }
+
+ @Test
+ void anOrphanFromAFailedRollbackSurvivesAnInPlaceUpdateAndIsDeletedWithTheNextReplacement() {
+ String orphan = TASK_DEF_ARN.replace(":3", ":4");
+ TaskDefinition next = new TaskDefinition();
+ next.setTaskDefinitionArn(orphan);
+ when(ecs.registerTaskDefinition(eq("web"), anyList(), isNull(), isNull(), isNull(), isNull(), isNull(), anyList(),
+ eq(REGION))).thenReturn(next);
+ doThrow(new AwsException("ServerException", "busy", 500)).when(ecs).deregisterTaskDefinition(orphan, REGION);
+ StackResource r = resource("AWS::ECS::TaskDefinition", "TaskDef");
+ r.getAttributes().put("TaskDefinitionArn", TASK_DEF_ARN);
+ provisioner.provision(r, mapper.createObjectNode().put("Family", "web"), ctx(TASK_DEF_ARN));
+ assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
+ assertEquals(TASK_DEF_ARN, r.getPhysicalId());
+
+ // A rollback with no replacement of its own deletes nothing and keeps the orphan owed.
+ assertFalse(provisioner.rollbackUpdate(r));
+ assertTrue(provisioner.hasReplacementUpdate(r));
+
+ // The next update registers revision 5: revision 3 (the prior) joins the orphan on the list
+ // and the committed cleanup deletes both, never the live revision.
+ TaskDefinition fifth = new TaskDefinition();
+ fifth.setTaskDefinitionArn(TASK_DEF_ARN.replace(":3", ":5"));
+ when(ecs.registerTaskDefinition(eq("web"), anyList(), isNull(), isNull(), isNull(), isNull(), isNull(), anyList(),
+ eq(REGION))).thenReturn(fifth);
+ provisioner.provision(r, mapper.createObjectNode().put("Family", "web"), ctx(TASK_DEF_ARN));
+ org.mockito.Mockito.reset(ecs);
+ UpdateCleanupResult cleanup = provisioner.completeUpdate(r);
+ assertTrue(cleanup.complete(), cleanup.toString());
+ verify(ecs).deregisterTaskDefinition(orphan, REGION);
+ verify(ecs).deregisterTaskDefinition(TASK_DEF_ARN, REGION);
+ verify(ecs, never()).deregisterTaskDefinition(fifth.getTaskDefinitionArn(), REGION);
+ assertFalse(provisioner.hasReplacementUpdate(r));
+ }
+
+ @Test
+ void givingUpOnOneEntityDoesNotForgetAnotherThatStillHasAttemptsLeft() {
+ String orphan = TASK_DEF_ARN.replace(":3", ":4");
+ TaskDefinition next = new TaskDefinition();
+ next.setTaskDefinitionArn(orphan);
+ when(ecs.registerTaskDefinition(eq("web"), anyList(), isNull(), isNull(), isNull(), isNull(), isNull(), anyList(),
+ eq(REGION))).thenReturn(next);
+ doThrow(new AwsException("ServerException", "busy", 500)).when(ecs).deregisterTaskDefinition(orphan, REGION);
+ StackResource r = resource("AWS::ECS::TaskDefinition", "TaskDef");
+ r.getAttributes().put("TaskDefinitionArn", TASK_DEF_ARN);
+ provisioner.provision(r, mapper.createObjectNode().put("Family", "web"), ctx(TASK_DEF_ARN));
+ assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
+ // The orphan uses up its three attempts in a cleanup where it is the only entry.
+ for (int i = 0; i < 3; i++) {
+ provisioner.completeUpdate(r);
+ }
+ assertEquals(3, provisioner.completeUpdate(r).attempts());
+
+ // A later replacement adds revision 3 to the list; its delete also fails at first.
+ TaskDefinition fifth = new TaskDefinition();
+ fifth.setTaskDefinitionArn(TASK_DEF_ARN.replace(":3", ":5"));
+ when(ecs.registerTaskDefinition(eq("web"), anyList(), isNull(), isNull(), isNull(), isNull(), isNull(), anyList(),
+ eq(REGION))).thenReturn(fifth);
+ provisioner.provision(r, mapper.createObjectNode().put("Family", "web"), ctx(TASK_DEF_ARN));
+ doThrow(new AwsException("ServerException", "busy", 500)).when(ecs).deregisterTaskDefinition(TASK_DEF_ARN, REGION);
+
+ // The result reports the entry with attempts left, so the engine keeps retrying it rather
+ // than giving up on the strength of the exhausted orphan.
+ UpdateCleanupResult first = provisioner.completeUpdate(r);
+ assertFalse(first.complete());
+ assertEquals(1, first.attempts());
+ assertEquals(TASK_DEF_ARN, first.previousPhysicalId());
+
+ // The engine gives up once the lowest count reaches three and clears; only the exhausted
+ // entries go, and an entry that succeeded meanwhile is gone already.
+ org.mockito.Mockito.doReturn(new TaskDefinition()).when(ecs).deregisterTaskDefinition(TASK_DEF_ARN, REGION);
+ UpdateCleanupResult second = provisioner.completeUpdate(r);
+ assertFalse(second.complete(), "the exhausted orphan is still listed");
+ assertEquals(3, second.attempts());
+ assertEquals(orphan, second.previousPhysicalId());
+ provisioner.clearUpdate(r);
+ assertFalse(provisioner.hasReplacementUpdate(r), "nothing with attempts left remains");
+ // One delete during the failed rollback, then the three cleanup attempts, never a fifth.
+ verify(ecs, org.mockito.Mockito.times(4)).deregisterTaskDefinition(orphan, REGION);
+ }
+
+ @Test
+ void clearingAfterAGiveUpKeepsAnEntryThatStillHasAttemptsLeft() {
+ String orphan = TASK_DEF_ARN.replace(":3", ":4");
+ TaskDefinition next = new TaskDefinition();
+ next.setTaskDefinitionArn(orphan);
+ when(ecs.registerTaskDefinition(eq("web"), anyList(), isNull(), isNull(), isNull(), isNull(), isNull(), anyList(),
+ eq(REGION))).thenReturn(next);
+ doThrow(new AwsException("ServerException", "busy", 500)).when(ecs).deregisterTaskDefinition(orphan, REGION);
+ StackResource r = resource("AWS::ECS::TaskDefinition", "TaskDef");
+ r.getAttributes().put("TaskDefinitionArn", TASK_DEF_ARN);
+ provisioner.provision(r, mapper.createObjectNode().put("Family", "web"), ctx(TASK_DEF_ARN));
+ assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
+ provisioner.completeUpdate(r);
+
+ // Cleared with one attempt used: the orphan is not forgotten.
+ provisioner.clearUpdate(r);
+ assertTrue(provisioner.hasReplacementUpdate(r));
+ assertEquals(orphan, provisioner.updateCleanupPhysicalId(r));
+ }
+
+ @Test
+ void aNonIntegerDesiredCountIsAValidationError() {
+ StackResource r = resource("AWS::ECS::Service", "Service");
+ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r,
+ mapper.createObjectNode().put("Cluster", "web").put("DesiredCount", "two"), ctx()));
+ assertEquals("ValidationError", e.getErrorCode());
+ assertNull(r.getPhysicalId());
+ }
+
+ @Test
+ void deleteToleratesOnlyTheServicesOwnNotFoundCodes() {
+ doThrow(new AwsException("ClusterNotFoundException", "gone", 400)).when(ecs).deleteCluster("web", REGION);
+ provisioner.delete("AWS::ECS::Cluster", "web", REGION);
+
+ doThrow(new AwsException("ClientException", "Unable to describe task definition", 400))
+ .when(ecs).deregisterTaskDefinition(TASK_DEF_ARN, REGION);
+ provisioner.delete("AWS::ECS::TaskDefinition", TASK_DEF_ARN, REGION);
+
+ doThrow(new AwsException("ServiceNotFoundException", "gone", 400))
+ .when(ecs).deleteService("web", "front", true, REGION);
+ provisioner.delete("AWS::ECS::Service", SERVICE_ARN, REGION);
+
+ doThrow(new AwsException("ClusterContainsTasksException", "busy", 400)).when(ecs).deleteCluster("busy", REGION);
+ AwsException e = assertThrows(AwsException.class, () -> provisioner.delete("AWS::ECS::Cluster", "busy", REGION));
+ assertEquals("ClusterContainsTasksException", e.getErrorCode());
+ }
+
+ @Test
+ void deleteServiceParsesTheClusterOutOfTheArn() {
+ provisioner.delete("AWS::ECS::Service", SERVICE_ARN, REGION);
+ verify(ecs).deleteService("web", "front", true, REGION);
+
+ provisioner.delete("AWS::ECS::Service", "bare-name", REGION);
+ verify(ecs).deleteService(null, "bare-name", true, REGION);
+ }
+
+ @Test
+ void deleteWithoutAPhysicalIdIsANoOp() {
+ provisioner.delete("AWS::ECS::Cluster", null, REGION);
+ provisioner.delete("AWS::ECS::Service", "", REGION);
+ verify(ecs, never()).deleteCluster(any(), any());
+ verify(ecs, never()).deleteService(any(), any(), eq(true), any());
+ }
+
+ @Test
+ void rejectsAResourceTypeItDoesNotOwn() {
+ StackResource r = resource("AWS::ECS::CapacityProvider", "Cp");
+ assertThrows(IllegalStateException.class, () -> provisioner.provision(r, mapper.createObjectNode(), ctx()));
+ }
+}
diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv
index 1de7988326..d2054a9986 100644
--- a/src/test/resources/cloudformation/supported-resource-types.tsv
+++ b/src/test/resources/cloudformation/supported-resource-types.tsv
@@ -55,10 +55,10 @@ AWS::EC2::VPCEndpoint Ec2VpcEndpointCfnProvisioner
AWS::EC2::VPCGatewayAttachment Ec2VpcGatewayAttachmentCfnProvisioner
AWS::ECR::Repository EcrCfnProvisioner
AWS::ECS::CapacityProvider EcsCapacityCfnProvisioner
-AWS::ECS::Cluster LEGACY_SWITCH
+AWS::ECS::Cluster EcsCfnProvisioner
AWS::ECS::ClusterCapacityProviderAssociations EcsCapacityCfnProvisioner
-AWS::ECS::Service LEGACY_SWITCH
-AWS::ECS::TaskDefinition LEGACY_SWITCH
+AWS::ECS::Service EcsCfnProvisioner
+AWS::ECS::TaskDefinition EcsCfnProvisioner
AWS::EKS::Cluster LEGACY_SWITCH
AWS::EKS::Nodegroup LEGACY_SWITCH
AWS::ElasticLoadBalancingV2::Listener LEGACY_SWITCH