fix(cloudformation): order leftover deletes by what their attributes reference (#5998)

* fix(cloudformation): infer no leftover order from custom resource data

Leftover ordering read every attribute of a resource the template no
longer names as a reference to what it uses. A custom resource's
attributes are its handler's response Data, which can name a resource
that depends on it, so a custom resource whose Data named a bucket that
DependsOn it was deleted before the bucket. Before leftovers were
ordered, reverse creation order got this right.

A custom resource is now one the dispatcher routes to the generic
handler, and of its attributes only Floci's own __Floci keys, such as
its ServiceToken, count. Custom::DynamoDBReplica has its own provisioner
and keeps the edge its TableName gives. A nested stack's Outputs.* and
an SSM parameter's Value are values passed through, not references, and
no longer order leftovers either.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(cloudformation): order leftovers without recursion

The leftover walk recursed once per link, so a long chain of leftovers,
each naming the next, could overflow the stack. A StackOverflowError is
not an Exception, so it got past the fall back to insertion order and
stopped the delete, cleanup or rollback. The walk now runs on an explicit
stack, with the same memo and the same cut where a cycle closes. Its
test walks 10,000 links on a small thread stack, which the recursive
walk overflows, and waits for it a bounded time.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(cloudformation): keep a leftover's own id from ordering it after a dependent

Some dependents take their parent's id as their own physical id: a
bucket policy is named by its bucket, a secret target attachment by its
secret's ARN. The parent's attribute naming that id then matched the
dependent, so a leftover bucket or secret was deleted before the policy
or attachment that depends on it.

An attribute naming the leftover's own id is no longer a reference, nor
is a resource whose id extends it. A leftover whose id extends another's
past a separator, as parent-1/child-1 does parent-1, goes before that
resource. A bucket policy or secret target attachment goes before
whatever else holds its id, including a bucket or secret the template
still names, whichever of the two was recorded first.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(cloudformation): order a custom resource or nested stack by what it was given

Leftover ordering read no edges from a custom resource's Data or a
nested stack's outputs, which left both with nothing they use. A custom
resource whose properties name a bucket it empties went after that
bucket, and a nested stack whose child created subnets in a VPC the
parent passed it went after the VPC, which then could not be deleted.
A Lambda ServiceToken, an ARN, never matched its function either, whose
physical id is its name.

A custom resource now orders by its resolved properties, with the
function name any Lambda ARN in them gives. A nested stack records the
parameters it passes its child under hidden __FlociUses keys and orders
by those. An SSM parameter's Value is what the parameter was given, as
with Value: !Ref Bucket, so it counts again. The registry now says which
types the generic custom-resource handler serves.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(cloudformation): let a leftover's own id still name another resource

A value equal to a leftover's own id was skipped outright, so a leftover
rule named like the event bus it is on lost its EventBusName edge and
went after the bus, which cannot be deleted while it has rules. Such a
value now skips only the leftover itself and the dependents that take
the same id. A function URL and a cluster's capacity provider
associations also take their parent's id, so they go before it. A
leftover recorded without a type no longer throws on the type check,
which had sent the whole stack back to insertion order.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(cloudformation): order a custom resource or nested stack by the resources it names

Ordering a leftover custom resource by the text of its properties, and a
nested stack by the values of its parameters, also matched literals. A
certificate resource given a domain's name went before the custom domain
that uses the certificate, which then cannot be deleted.

A custom resource or nested stack now keeps, as it is provisioned, the
physical id of each resource its definition names through Ref,
Fn::GetAtt, Fn::Sub or DependsOn, under hidden __FlociUses keys, and is
ordered by those. An update replaces them, and a rolled-back update puts
back the ones from before. Its properties and parameters are no longer
read for this.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(cloudformation): find what a leftover depended on by its logical id too

A custom resource or nested stack keeps the physical id of each resource
its definition names, but an update replaces a resource it only
DependsOn without touching it, so the id it kept goes stale and the
leftover lost that edge. A kept resource now also counts as whatever the
stack holds under its logical id.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(cloudformation): let what a definition named outweigh a shared id

CDK's S3AutoDeleteObjects resource takes its bucket's name as its id and
depends on the bucket and its policy. Left over with both, the bucket's
own name named the custom resource, the own-id rule dropped the policy
the definition named, and the policy counted the custom resource as the
holder of its id it uses, so the bucket went first and its delete failed
on the objects the custom resource would have removed.

What a definition named is now found by logical id and taken as given,
and a resource whose definition named a leftover is its dependent, not
something it uses. A nested stack saved before definitions were kept
orders by its outputs again, as it did then.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* docs(cloudformation): say which leftovers order by their kept uses

A nested stack keeps no uses when its definition names no resource, as
well as when it was saved before uses were kept, and orders by its
outputs either way. A kept use is found by its logical id, its physical
id being a record. A resource whose own definition named a leftover is
skipped by all three inferred rules, not only the value match.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(cloudformation): read no parent from a WAF or custom action type id

A WAFv2 web ACL or IP set has the physical id name|id|scope, and a
CodePipeline custom action type category|Custom|provider|version. Their
first part is their own identity, not a parent's id, yet the leftover
walk read it as the id of a resource they belong to, so a leftover web
ACL sharing a bucket's name was ordered after the bucket. These types no
longer get an edge from a prefix of their own id.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(cloudformation): keep a DependsOn-only change for a later leftover delete

An update that changes only a custom resource's or nested stack's
DependsOn does not re-provision it, so the resources it was kept as
using stayed as they were, and as a leftover it could later be deleted
after a resource it had come to depend on. As an update commits, what
each custom resource and nested stack the template names now names is
kept again. An update that rolls back keeps what was kept before.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(cloudformation): refresh kept uses only for active resources, safely

The refresh as an update commits re-read the definition of a custom
resource or nested stack whose condition had turned false, choosing its
Fn::If branches by conditions it was never provisioned under; if its
cleanup delete then failed, it stayed held with uses it never had. It
also ran where a failure would skip the committed update's cleanup. Such
a resource now keeps what it was provisioned with, and a failure in the
refresh is logged and costs only those keys.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* refactor(cloudformation): let provisioners say how their ids name a parent

The leftover walk listed in CloudFormationService which types take their
parent's physical id (bucket policy, secret target attachment, function
URL, capacity provider associations) and which types' ids name no parent
(WAFv2 web ACL and IP set, CodePipeline custom action type). That is
knowledge of how those types are provisioned. Two default hooks on
CfnResourceProvisioner, asked through the dispatcher as for replacement
updates, now let the S3, Secrets Manager, Lambda, ECS, WAFv2 and
CodePipeline provisioners say it for their own types. No behaviour
changes.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(cloudformation): answer the provisioner hooks as production does

The rollback test's stand-in provisioners were plain mocks, so they
answered no to a prefix of a custom resource's id naming its parent,
where a provisioner that overrides nothing answers yes. They now call
the interface's own defaults, the dispatcher test checks a custom type
keeps them, and a static import is back in order.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

---------

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
This commit is contained in:
Jackson Price authored and GitHub committed 2026-10-19 15:23:10 -04:00
1 parent d8064fae14
commit b955aa09ff
15 files changed
+1458 -23

No files matched your search

@@ -59,6 +59,7 @@ import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.UnaryOperator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -1997,6 +1998,8 @@ public class CloudFormationService implements ResourceProvider {
StackResource failedResource = null;
if (resources.isObject()) {
List<String> sortedLogicalIds = topologicalSort(resources, conditions);
Set<String> templateIds = new LinkedHashSet<>();
resources.fieldNames().forEachRemaining(templateIds::add);
if (!isCreate) {
for (String logicalId : sortedLogicalIds) {
@@ -2085,6 +2088,10 @@ public class CloudFormationService implements ResourceProvider {
// Both branches return a fresh StackResource, so the policy is carried over here
// rather than on the instance the loop started with.
resource.setDeletionPolicy(deletionPolicy);
if ("AWS::CloudFormation::Stack".equals(type) || dispatcher.isCustomResourceType(type)) {
recordTemplateUses(resource, collectResourceDependencies(resDef, templateIds, conditions),
physicalIds);
}
stack.getResources().put(logicalId, resource);
physicalIds.put(logicalId, resource.getPhysicalId());
@@ -2094,13 +2101,11 @@ public class CloudFormationService implements ResourceProvider {
boolean replaced = dispatcher.hasReplacementUpdate(resource)
|| (priorId != null && !priorId.equals(resource.getPhysicalId()));
if (replaced) {
Set<String> allResourceIds = new LinkedHashSet<>();
resources.fieldNames().forEachRemaining(allResourceIds::add);
for (String candidateId : sortedLogicalIds) {
if (!changedResourceIds.contains(candidateId)) {
Set<String> deps = new LinkedHashSet<>();
collectDependencies(resources.path(candidateId).path("Properties"),
allResourceIds, deps, conditions);
templateIds, deps, conditions);
if (deps.contains(logicalId)) {
changedResourceIds.add(candidateId);
}
@@ -2257,6 +2262,7 @@ public class CloudFormationService implements ResourceProvider {
if (!isCreate) {
updateCommitted = true;
refreshTemplateUses(stack, resources, conditions, physicalIds);
if (tags != null) {
stack.replaceTags(tags);
}
@@ -2838,6 +2844,7 @@ public class CloudFormationService implements ResourceProvider {
boolean recoveredPendingUpdate = dispatcher.requiresUpdateRecovery(previous);
resource.setStatus(recoveredPendingUpdate ? "UPDATE_COMPLETE" : previous.getStatus());
resource.setStatusReason(recoveredPendingUpdate ? null : previous.getStatusReason());
restoreTemplateUses(resource, previous);
addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(),
resource.getResourceType(), "UPDATE_COMPLETE",
"Resource update rolled back");
@@ -3120,9 +3127,11 @@ public class CloudFormationService implements ResourceProvider {
* reversing the map would delete it first: a certificate still used by a user pool domain, for
* one. Resources the template no longer names, left behind by a failed cleanup or skipped by
* ContinueUpdateRollback, are deleted as late as possible, after anything that might still use
* them, but before any held resource whose physical id one of their attributes names, such as a
* subnet's {@code VpcId}: with their template entry gone, that is the only record of what they
* depend on, so a leftover whose attributes name nothing it uses is still deleted last.
* them, but before any held resource they use: one whose physical id their record names, such
* as a subnet's {@code VpcId}, one whose id theirs extends, or for a type that takes its
* parent's id, the parent (see {@link #leftoverPosition}). With their template entry gone, that
* is the only record of what they depend on, so a leftover that uses nothing held is still
* deleted last.
* Conditions are ignored, both on resources and in {@code Fn::If}: a resource depends on what
* every branch names. The conditions read now need not be the ones a held resource was
* provisioned under, since a failed rollback restores the parameters but can leave a resource
@@ -3168,6 +3177,7 @@ public class CloudFormationService implements ResourceProvider {
rank.put(creationOrder.get(i), i);
}
Map<String, List<StackResource>> holdersByPhysicalId = new HashMap<>();
Map<String, StackResource> held = new HashMap<>();
int leftovers = 0;
for (StackResource resource : ordered) {
if (!rank.containsKey(resource.getLogicalId())) {
@@ -3177,12 +3187,17 @@ public class CloudFormationService implements ResourceProvider {
holdersByPhysicalId.computeIfAbsent(resource.getPhysicalId(), id -> new ArrayList<>())
.add(resource);
}
held.put(resource.getLogicalId(), resource);
}
double step = 1.0 / (leftovers + 1);
Map<String, Double> position = new HashMap<>();
Map<String, LeftoverReferences> read = new HashMap<>();
Function<StackResource, LeftoverReferences> references = resource -> read.computeIfAbsent(
resource.getLogicalId(), id -> leftoverReferences(resource, held));
for (StackResource resource : ordered) {
position.put(resource.getLogicalId(),
leftoverPosition(resource, rank, holdersByPhysicalId, step, position, new HashSet<>()));
leftoverPosition(resource, rank, holdersByPhysicalId, step, position, new HashSet<>(),
references));
}
ordered.sort(Comparator.comparingDouble(r -> position.get(r.getLogicalId())));
} catch (Exception e) {
@@ -3294,13 +3309,23 @@ public class CloudFormationService implements ResourceProvider {
/**
* A resource's place in {@link #resourcesInCreationOrder}: its template rank, or for a leftover
* one step after the latest held resource its attributes name, leftovers included, or else -1.
* A chain of leftovers stays below the next template rank, and a cycle among them is cut where
* it closes.
* one step after the latest held resource it uses, leftovers included, or else -1. A chain of
* leftovers stays below the next template rank, and a cycle among them is cut where it closes.
* A leftover uses what its definition named, and a held resource whose physical id one of its
* values names (both per {@link #leftoverReferences}), unless that resource's id extends the
* leftover's. A value equal to the leftover's own id names the leftover itself, so it does not
* make the leftover use a dependent that takes the same id, such as its bucket policy. It still
* names any other resource that shares the id, such as the event bus of a rule with the bus's
* name. A leftover also uses the resource whose id its own extends, {@code parent-1} for
* {@code parent-1/child-1}, unless its provisioner says its id names no parent, and a type whose
* provisioner says it takes its parent's id, such as a bucket policy, uses whatever else holds
* that id. None of these three counts a resource whose own definition named the leftover: that
* one depends on it.
*/
private static double leftoverPosition(StackResource resource, Map<String, Integer> rank,
Map<String, List<StackResource>> holdersByPhysicalId,
double step, Map<String, Double> position, Set<String> visiting) {
double step, Map<String, Double> position, Set<String> visiting,
Function<StackResource, LeftoverReferences> references) {
Integer resourceRank = rank.get(resource.getLogicalId());
if (resourceRank != null) {
return resourceRank;
@@ -3309,19 +3334,193 @@ public class CloudFormationService implements ResourceProvider {
if (known != null) {
return known;
}
// A depth-first walk on an explicit stack rather than recursion, so a long chain of
// leftovers, each naming the next, cannot overflow the thread's stack.
Deque<LeftoverVisit> path = new ArrayDeque<>();
path.push(new LeftoverVisit(resource, leftoverUses(resource, holdersByPhysicalId, references)));
visiting.add(resource.getLogicalId());
double placed = -1;
for (String value : resource.getAttributes().values()) {
while (true) {
LeftoverVisit current = path.peek();
if (current.next < current.uses.size()) {
StackResource holder = current.uses.get(current.next++);
Integer holderRank = rank.get(holder.getLogicalId());
Double holderPosition = holderRank != null
? Double.valueOf(holderRank) : position.get(holder.getLogicalId());
if (holderPosition != null) {
current.placed = Math.max(current.placed, holderPosition + step);
} else if (!visiting.contains(holder.getLogicalId())) {
// A holder already on the path closes a cycle, which is cut here.
visiting.add(holder.getLogicalId());
path.push(new LeftoverVisit(holder, leftoverUses(holder, holdersByPhysicalId, references)));
}
continue;
}
path.pop();
visiting.remove(current.resource.getLogicalId());
position.put(current.resource.getLogicalId(), current.placed);
LeftoverVisit parent = path.peek();
if (parent == null) {
return current.placed;
}
parent.placed = Math.max(parent.placed, current.placed + step);
}
}
/** One leftover on the walk's path: the held resources it uses, how many are done, its place so far. */
private static final class LeftoverVisit {
private final StackResource resource;
private final List<StackResource> uses;
private int next;
private double placed = -1;
private LeftoverVisit(StackResource resource, List<StackResource> uses) {
this.resource = resource;
this.uses = uses;
}
}
/** The held resources a leftover uses, per {@link #leftoverPosition}. */
private static List<StackResource> leftoverUses(StackResource resource,
Map<String, List<StackResource>> holdersByPhysicalId,
Function<StackResource, LeftoverReferences> references) {
LeftoverReferences named = references.apply(resource);
String own = resource.getPhysicalId();
List<StackResource> uses = new ArrayList<>(named.declared());
for (String value : named.values()) {
if (value == null) {
continue;
}
boolean ownId = value.equals(own);
for (StackResource holder : holdersByPhysicalId.getOrDefault(value, List.of())) {
if (!visiting.contains(holder.getLogicalId())) {
placed = Math.max(placed,
leftoverPosition(holder, rank, holdersByPhysicalId, step, position, visiting) + step);
// Its own id names the leftover, not a dependent that takes the same id.
if (holder != resource && !extendsId(holder.getPhysicalId(), own)
&& !(ownId && takesParentId(holder, references))
&& !declares(holder, resource, references)) {
uses.add(holder);
}
}
}
visiting.remove(resource.getLogicalId());
position.put(resource.getLogicalId(), placed);
return placed;
for (String prefix : named.idPrefixNamesParent() ? idPrefixes(own) : List.<String>of()) {
for (StackResource holder : holdersByPhysicalId.getOrDefault(prefix, List.of())) {
if (!declares(holder, resource, references)) {
uses.add(holder);
}
}
}
if (named.takesParentId()) {
// A type that takes its parent's id as its own uses whatever else holds that id.
for (StackResource holder : holdersByPhysicalId.getOrDefault(own, List.of())) {
if (holder != resource && !takesParentId(holder, references)
&& !declares(holder, resource, references)) {
uses.add(holder);
}
}
}
return uses;
}
/** Whether {@code holder}'s definition named {@code resource}: then it depends on it, not the reverse. */
private static boolean declares(StackResource holder, StackResource resource,
Function<StackResource, LeftoverReferences> references) {
return references.apply(holder).declared().contains(resource);
}
/**
* What a resource's record says it uses; see {@link #leftoverReferences}. {@code takesParentId}
* and {@code idPrefixNamesParent} are what its type's provisioner says of its physical id, per
* {@link CfnResourceDispatcher#takesParentPhysicalId} and
* {@link CfnResourceDispatcher#idPrefixCanNameParent}.
*/
private record LeftoverReferences(List<String> values, List<StackResource> declared,
boolean takesParentId, boolean idPrefixNamesParent) {
}
/** Whether a resource's type takes the physical id of the resource it depends on as its own. */
private static boolean takesParentId(StackResource resource,
Function<StackResource, LeftoverReferences> references) {
return references.apply(resource).takesParentId();
}
/** The characters after which a physical id may continue as a child's: {@code /}, {@code :} and {@code |}. */
private static final String ID_SEPARATORS = "/:|";
/**
* Whether {@code id} extends {@code parent} past a separator, as {@code parent-1/child-1} does
* {@code parent-1}: a resource named under another's id belongs to it.
*/
private static boolean extendsId(String id, String parent) {
return id != null && parent != null && id.length() > parent.length() && id.startsWith(parent)
&& ID_SEPARATORS.indexOf(id.charAt(parent.length())) >= 0;
}
/** Every proper prefix of {@code id} that ends just before a separator, which {@code id} extends. */
private static List<String> idPrefixes(String id) {
List<String> prefixes = new ArrayList<>();
if (id != null) {
for (int i = 1; i < id.length(); i++) {
if (ID_SEPARATORS.indexOf(id.charAt(i)) >= 0) {
prefixes.add(id.substring(0, i));
}
}
}
return prefixes;
}
/**
* What a resource's record says it uses, for leftover ordering. Its {@code values} may name a
* held resource by physical id: for most resources that is every attribute value, as some, such
* as a subnet's {@code VpcId}, say what the resource was given and the rest describe the
* resource itself. Two kinds of resource hold attributes that can as easily name a resource
* depending on them: a custom resource's are its handler's response Data, and a nested stack's
* {@code Outputs.*} are its child's outputs. Those do not count. A custom resource gives only
* Floci's own {@code __Floci} values, such as its ServiceToken, with the name of any Lambda
* function one gives by ARN, a function's physical id being its name. What the definition of
* either kind named, kept by {@link #recordTemplateUses}, is {@code declared}: the resources
* {@code held} under those logical ids now, as a later update may have replaced one without
* touching a resource that only {@code DependsOn} it. A nested stack that kept none, because it
* was saved before they were kept or its definition names no resource, counts its outputs, as
* Floci did before.
*/
private LeftoverReferences leftoverReferences(StackResource resource, Map<String, StackResource> held) {
List<String> values = new ArrayList<>();
List<StackResource> declared = new ArrayList<>();
boolean recorded = false;
for (String key : resource.getAttributes().keySet()) {
if (key.startsWith(TEMPLATE_USES_PREFIX)) {
recorded = true;
StackResource named = held.get(key.substring(TEMPLATE_USES_PREFIX.length()));
if (named != null && named != resource) {
declared.add(named);
}
}
}
boolean custom = dispatcher.isCustomResourceType(resource.getResourceType());
boolean skipOutputs = recorded && "AWS::CloudFormation::Stack".equals(resource.getResourceType());
for (Map.Entry<String, String> attribute : resource.getAttributes().entrySet()) {
String key = attribute.getKey();
if (key.startsWith(TEMPLATE_USES_PREFIX)
|| (custom ? !key.startsWith("__Floci") : skipOutputs && key.startsWith("Outputs."))) {
continue;
}
values.add(attribute.getValue());
if (custom) {
String function = lambdaFunctionName(attribute.getValue());
if (function != null) {
values.add(function);
}
}
}
String type = resource.getResourceType();
return new LeftoverReferences(values, declared, dispatcher.takesParentPhysicalId(type),
dispatcher.idPrefixCanNameParent(type));
}
/** The name of the Lambda function {@code value} gives by ARN, qualified or not, or else null. */
private static String lambdaFunctionName(String value) {
return AwsArnUtils.resourceIfArnFor(value, "lambda")
.filter(resource -> resource.startsWith("function:"))
.map(resource -> resource.substring("function:".length()).split(":", 2)[0])
.orElse(null);
}
void deleteStackResources(Stack stack, String region, String accountId) {
@@ -3974,6 +4173,73 @@ public class CloudFormationService implements ResourceProvider {
return resource;
}
/** Prefixes the keys {@link #recordTemplateUses} keeps, one per resource a definition names. */
private static final String TEMPLATE_USES_PREFIX = CfnRollback.USES_ATTR_PREFIX + "Resource.";
/**
* Keeps, under {@link CfnRollback#USES_ATTR_PREFIX} keys, one key per resource a definition
* names through {@code Ref}, {@code Fn::GetAtt}, {@code Fn::Sub} or {@code DependsOn}, in place of
* what an earlier operation kept. A custom resource's or nested stack's attributes are outputs, so
* these are what orders it before the resources it uses once the template no longer names it; a
* literal value it was given names nothing, even if another resource has that name. The key's
* logical id decides, and its value, that resource's physical id then, is kept as a record. One
* provisioned before these keys were kept has none until it changes or an update of its stack
* commits ({@link #refreshTemplateUses}), so as a leftover before then a custom resource orders
* by its ServiceToken alone, and a nested stack by its outputs.
*/
private static void recordTemplateUses(StackResource resource, Set<String> dependencies,
Map<String, String> physicalIds) {
resource.getAttributes().keySet().removeIf(key -> key.startsWith(TEMPLATE_USES_PREFIX));
for (String dependency : dependencies) {
String physicalId = physicalIds.get(dependency);
if (physicalId != null && !dependency.equals(resource.getLogicalId())) {
resource.getAttributes().put(TEMPLATE_USES_PREFIX + dependency, physicalId);
}
}
}
/**
* Keeps again, as an update commits, what each custom resource and nested stack the template
* names now names: one whose only change is its {@code DependsOn} is not re-provisioned, so
* {@link #recordTemplateUses} did not run for it. An update that rolls back never gets here,
* so the keys from before stay. One whose condition is now false keeps what it was provisioned
* with: the cleanup about to delete it may fail and leave it held. The update has committed, so
* a failure here is logged and costs only these keys, not the cleanup that follows.
*/
private void refreshTemplateUses(Stack stack, JsonNode resources, Map<String, Boolean> conditions,
Map<String, String> physicalIds) {
if (!resources.isObject()) {
return;
}
try {
Set<String> templateIds = new LinkedHashSet<>();
resources.fieldNames().forEachRemaining(templateIds::add);
for (String logicalId : templateIds) {
JsonNode definition = resources.get(logicalId);
String type = definition.path("Type").asText();
String condition = definition.path("Condition").asText(null);
StackResource resource = stack.getResources().get(logicalId);
if (resource != null && (condition == null || conditions.getOrDefault(condition, false))
&& ("AWS::CloudFormation::Stack".equals(type) || dispatcher.isCustomResourceType(type))) {
recordTemplateUses(resource, collectResourceDependencies(definition, templateIds, conditions),
physicalIds);
}
}
} catch (RuntimeException e) {
LOG.warnv("Stack {0} keeps the uses its resources recorded before this update: {1}",
stack.getStackName(), e.getMessage());
}
}
/** Puts back the {@link #recordTemplateUses} keys a resource held before an update now rolled back. */
private static void restoreTemplateUses(StackResource resource, StackResource previous) {
resource.getAttributes().keySet().removeIf(key -> key.startsWith(TEMPLATE_USES_PREFIX));
previous.getAttributes().forEach((key, value) -> {
if (key.startsWith(TEMPLATE_USES_PREFIX)) {
resource.getAttributes().put(key, value);
}
});
}
private static String newStackId(String stackName, String region, String accountId) {
return AwsArnUtils.Arn.of("cloudformation", region, accountId, "stack/" + stackName + "/" + UUID.randomUUID()).toString();
@@ -50,6 +50,14 @@ public class CfnResourceDispatcher {
this.config = config;
}
/**
* Whether the generic custom-resource handler serves a type, as the registry routes it; see
* {@link CloudFormationResourceRegistry#isCustomResourceType}.
*/
public boolean isCustomResourceType(String resourceType) {
return registry.isCustomResourceType(resourceType);
}
/**
* Provisions a single resource and returns the populated StackResource (physical id and
* attributes set).
@@ -290,6 +298,20 @@ public class CfnResourceDispatcher {
.orElse(false);
}
/** Whether the owner of a type says it takes its parent's physical id; see the provisioner hook. */
public boolean takesParentPhysicalId(String resourceType) {
return registry.forType(resourceType)
.map(owner -> owner.takesParentPhysicalId(resourceType))
.orElse(false);
}
/** Whether the owner of a type says a prefix of its id can name its parent; see the provisioner hook. */
public boolean idPrefixCanNameParent(String resourceType) {
return registry.forType(resourceType)
.map(owner -> owner.idPrefixCanNameParent(resourceType))
.orElse(true);
}
/** Drops the cleanup bookkeeping this update left on the resource. */
public void clearUpdate(StackResource resource) {
registry.forType(resource.getResourceType())
@@ -100,6 +100,25 @@ public interface CfnResourceProvisioner {
return false;
}
/**
* Whether a resource of {@code resourceType} takes the physical id of the resource it depends
* on as its own, as a bucket policy takes its bucket's name. The stack then deletes one left
* behind before whatever else holds that id. The default is no.
*/
default boolean takesParentPhysicalId(String resourceType) {
return false;
}
/**
* Whether a prefix of a {@code resourceType} physical id, up to a {@code /}, {@code :} or
* {@code |}, can be the physical id of the resource it belongs to, as {@code function|sid} is
* a Lambda permission's. The stack then deletes one left behind before that resource. The
* default is yes; a type whose id only joins parts of its own identity says no.
*/
default boolean idPrefixCanNameParent(String resourceType) {
return true;
}
/**
* Drops the bookkeeping the replacement cleanup kept on the resource, once the displaced entity
* is gone or its deletion is given up on. The default has none to drop.
@@ -215,9 +215,11 @@ public final class CfnRollback {
/**
* Prefixes attributes that name, by physical id, a resource this one uses where none of its
* public attributes does, such as a NAT gateway's subnet and Elastic IP. {@code
* CloudFormationService} reads every attribute value of a resource the template no longer
* names to delete it before what it uses; these keep {@code Fn::GetAtt} to what AWS resolves.
* public attributes does, such as a NAT gateway's subnet and Elastic IP, or the resources a
* custom resource's or nested stack's definition named. {@code CloudFormationService} reads the
* attribute values of a resource the template no longer names to delete it before what it uses;
* these keep {@code Fn::GetAtt} to what AWS resolves, and count even for a custom resource or
* nested stack, whose other attributes are outputs.
*/
public static final String USES_ATTR_PREFIX = "__FlociUses";
@@ -18,6 +18,8 @@ import java.util.Set;
@ApplicationScoped
public class CloudFormationResourceRegistry {
private static final String CUSTOM_RESOURCE_TYPE = "AWS::CloudFormation::CustomResource";
private final Map<String, CfnResourceProvisioner> byType = new HashMap<>();
@Inject
@@ -47,11 +49,22 @@ public class CloudFormationResourceRegistry {
// Custom::* is a dynamic, unenumerable prefix, so it cannot be a registered key. An
// exact entry still wins (Custom::DynamoDBReplica is registered to DynamoDbCfnProvisioner
// above); only otherwise-unmatched Custom:: types fall through to the generic handler.
provisioner = byType.get("AWS::CloudFormation::CustomResource");
provisioner = byType.get(CUSTOM_RESOURCE_TYPE);
}
return Optional.ofNullable(provisioner);
}
/**
* Whether {@code resourceType} is served by the generic custom-resource handler, whose
* attributes are the handler's response Data: {@code AWS::CloudFormation::CustomResource} and
* every {@code Custom::} type without an exact entry. {@code Custom::DynamoDBReplica} has its
* own provisioner and is not.
*/
public boolean isCustomResourceType(String resourceType) {
CfnResourceProvisioner generic = byType.get(CUSTOM_RESOURCE_TYPE);
return generic != null && forType(resourceType).orElse(null) == generic;
}
/**
* Every resource type served by an extracted provisioner, as resolved by CDI. Read by the
* inventory test: a provisioner missing {@code @ApplicationScoped} compiles and unit-tests
@@ -47,6 +47,12 @@ public class CodePipelineCfnProvisioner implements CfnResourceProvisioner {
"AWS::CodePipeline::Webhook");
}
/** A custom action type's id is its own {@code category|Custom|provider|version}, which names no parent. */
@Override
public boolean idPrefixCanNameParent(String resourceType) {
return !"AWS::CodePipeline::CustomActionType".equals(resourceType);
}
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
switch (r.getResourceType()) {
@@ -49,6 +49,12 @@ public class EcsCapacityCfnProvisioner implements CfnResourceProvisioner {
return Set.of(CAPACITY_PROVIDER, ASSOCIATIONS);
}
/** A cluster's associations are named by the {@code Cluster} they are given, its name when given by name. */
@Override
public boolean takesParentPhysicalId(String resourceType) {
return ASSOCIATIONS.equals(resourceType);
}
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
switch (r.getResourceType()) {
@@ -59,6 +59,15 @@ public class LambdaAddressingCfnProvisioner implements CfnResourceProvisioner {
return Set.of(PERMISSION, URL);
}
/**
* A function URL is named by the ARN of what it serves: an alias's ARN, which is the alias's
* own id, or its function's, which matches nothing since a function's id is its name.
*/
@Override
public boolean takesParentPhysicalId(String resourceType) {
return URL.equals(resourceType);
}
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
switch (r.getResourceType()) {
@@ -72,6 +72,12 @@ public class S3CfnProvisioner implements CfnResourceProvisioner {
return Set.of(BUCKET, BUCKET_POLICY);
}
/** A bucket policy is named by its bucket. */
@Override
public boolean takesParentPhysicalId(String resourceType) {
return BUCKET_POLICY.equals(resourceType);
}
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
switch (r.getResourceType()) {
@@ -73,6 +73,12 @@ public class SecretTargetAttachmentCfnProvisioner implements CfnResourceProvisio
return Set.of(TYPE);
}
/** An attachment is named by its secret's ARN. */
@Override
public boolean takesParentPhysicalId(String resourceType) {
return TYPE.equals(resourceType);
}
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
requireSupported(r.getResourceType());
@@ -37,6 +37,15 @@ public class WafV2CfnProvisioner implements CfnResourceProvisioner {
return Set.of(WEB_ACL, WEB_ACL_ASSOCIATION, IP_SET);
}
/**
* A web ACL or IP set id is its own {@code name|id|scope}, which names no parent. An
* association's, {@code resourceArn|webAclArn}, starts with the resource it is attached to.
*/
@Override
public boolean idPrefixCanNameParent(String resourceType) {
return WEB_ACL_ASSOCIATION.equals(resourceType);
}
@Override
public void provision(StackResource resource, JsonNode props, ProvisionContext ctx) {
if (WEB_ACL_ASSOCIATION.equals(resource.getResourceType())) {