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

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

Three more arms leave the legacy switch, together with the ECS-only parsers
(container definitions, port mappings, environment, secrets, load balancers,
network configuration) and the three idempotent delete helpers. The monolith
no longer depends on EcsService at all; its constructor loses that parameter
and CfnProvisionerFixture passes one argument less.

Behaviour is unchanged except where the move fixes it: an unnamed cluster
keeps the name its first execution generated (ctx.stablePhysicalName), where
the switch generated a fresh name and created a second cluster on every
UpdateStack. Create-vs-update for a service branches on ctx.isUpdate() and
the stored Name attribute, since the physical id is the ARN; a renamed
service is created as a replacement, with the prior one left behind as every
replacement in the switch does today. A non-integer DesiredCount is a
ValidationError instead of an uncaught NumberFormatException. Deletes go
through CfnDeletes.safeDelete tolerating only the service's own not-found
codes, so a ClusterContainsTasksException still fails the stack delete
(#1634).

Fn::GetAtt keys are unchanged (Cluster Arn, TaskDefinition TaskDefinitionArn,
Service Name and ServiceArn), matching the registry schemas' readOnly
properties, and CloudFormationIntegrationTest keeps asserting them end to
end. EcsCfnProvisionerTest covers the three types against a mocked
EcsService. The whole CloudFormation test package passes on this tree apart
from the pre-existing ACM schema-gap row.

* refactor(cloudformation): treat an ECS service's cluster as create-only and clean up replacements

Review found that a service moved to another cluster while keeping its name
took the in-place update path: updateService was called against the new
cluster, which either fails with ServiceNotFoundException or mutates a
same-named service the new cluster already has. Cluster is create-only on
AWS::ECS::Service, so the update now compares the requested cluster (a name,
an ARN's last segment, or the default) with the one embedded in the prior
service ARN and creates a replacement when they differ.

A replacement, here and for a renamed service or a task definition's new
revision, now enters the replacement-cleanup lifecycle the engine already
runs (UPDATE_COMPLETE_CLEANUP_IN_PROGRESS, DELETE_IN_PROGRESS on the prior id,
three attempts, UpdateReplacePolicy Retain honoured) instead of leaving the
displaced entity behind. ReplacementCleanup is the plain bookkeeping for
provisioners without a rollback snapshot, beside the richer record
PipesCfnProvisioner keeps; the provisioner delegates the four interface hooks
to it and deletes through its own idempotent delete arm. Deregistering the
displaced task-definition revision after commit is what CloudFormation does
on AWS and stops revisions accumulating on every update.

* refactor(cloudformation): roll an ECS replacement back when a later resource fails

Review found that a replacement this provisioner produces (a service moved or
renamed, a task definition's new revision) could not be rolled back: when a
later resource failed the stack update, rollbackUpdate had no implementation,
so the engine reported "Rollback is not implemented", left the replacement
running and the stack in UPDATE_ROLLBACK_FAILED.

ReplacementCleanup now keeps the attributes the resource carried before the
provision alongside the prior physical id, and rollback() puts both back and
deletes the replacement through the provisioner's own delete arm; the record
is spent before the delete so a failing delete cannot put the restored prior
on the next cleanup's list, as PipesCfnProvisioner reasons for its rename.
The provisioner records once, in provision(), after the type switch, and
delegates rollbackUpdate. In-place updates owe no record and keep the
engine's existing handling.

The committed-update cleanup in CloudFormationService now walks resources in
reverse creation order, as every other teardown walk does: a displaced
service has to go before the displaced cluster it runs in, and a displaced
listener before the target group it forwards to, or that delete fails three
times and leaves the entity behind.

* refactor(cloudformation): order replacement cleanup by the template and keep an orphaned replacement owed

Two gaps in the replacement lifecycle, both found in review. The committed
cleanup walked the resource map reversed, but the map is insertion order and
a resource a later update added sits after the resources that depend on it,
so a cluster added after its service would still be deleted first. The
cleanup now walks resourcesInCreationOrder reversed, the template's
dependency order, exactly as DeleteStack does; a resource the template no
longer names sorts last.

And a rollback whose delete of the replacement failed forgot the replacement:
the record was cleared before the delete, so nothing could remove that
entity later even though UPDATE_ROLLBACK_FAILED is updatable here and both
the next committed update and DeleteStack run the cleanup first. The record
is now a list of every entity owed a delete: a replacement whose rollback
delete fails is listed in the prior's place, never retained (a failed update
created it), and the prior's own id and attributes are kept beside the list
only while this update's replacement can still be rolled back. Every listed
entity gets its attempt on every cleanup call, so one that keeps failing does
not leave the others untried.

* refactor(cloudformation): keep a displaced entity owed until its own attempts are used up

Review found that once any listed entity reached three failed deletes, the engine's give-up cleared the whole record, forgetting entities that still had attempts left. clearUpdate now drops only the entries that used up their attempts (and the rollback fields), and the cleanup result reports the lowest attempt count among what remains, naming that entity, so the engine keeps retrying until every remaining entity has had its own three attempts.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-09-06 13:47:45 -05:00
1 parent fa265a4a33
commit 9df197f3af
8 files changed
+1305 -309

No files matched your search

@@ -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,
@@ -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) {
@@ -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() {
}
@@ -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;
}
}
@@ -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;
}
}
}