fix(cloudformation): send a stack's status changes to the default bus, with their request token (#7053)

Floci sent no event as a stack's status changed, so a rule on `CloudFormation Stack Status Change`
never fired, and whatever starts on one, a deploy waiting for its stack to finish among them, never
started. It also dropped `ClientRequestToken`, which is how a consumer ties an event to the
operation that caused it.

- CloudFormation User Guide, "Using Amazon EventBridge with CloudFormation": events go to the
  default bus, "guaranteed to be delivered, and they might be delivered out of order".
  https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/eventbridge-integration.html
- CloudFormation User Guide, "CloudFormation stack status change event detail": the envelope,
  `stack-id`, `status-details`, and "All events that are initiated by a given stack operation are
  assigned the same client request token".
  https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/event-detail-stack-status-change.html

The pages say nothing of nested stacks, and their sample shows an empty token. Rules read on a real
account on 2026-10-30, for a root nesting one stack, showed one event per status. Through a create
change set, an update change set and DeleteStack, each with its own token, the root's events carried
their operation's token but for REVIEW_IN_PROGRESS, which had no key, and the nested stack's had no
key at all. Through a create and an update that failed in the nested stack, the root's rollback
statuses carried the create's or the update's token, the nested stack's again had no key, neither the
root's CREATE_FAILED nor any UPDATE_FAILED reached the bus, and the nested stack's failed create was
CREATE_FAILED and then DELETE_IN_PROGRESS and DELETE_COMPLETE, with no ROLLBACK_* status. Floci now
records and sends that: a nested stack records CREATE_IN_PROGRESS or UPDATE_IN_PROGRESS as its
operation starts, its failed create ends in CREATE_FAILED for its parent's rollback to delete, without
the "Rollback requested by user." CloudFormation's reason did not carry, and an update's first rollback
passes through UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS. An operation given no token leaves the key
out too.

Two cases were not read and no test asserts them: a failure in the root's own resource with the
nested stack healthy, and a delete that fails. They send CloudFormation's documented statuses from the
same code. UPDATE_COMPLETE_CLEANUP_IN_PROGRESS stays where Floci has cleanup to do, though
CloudFormation sent it on every update. A template Floci cannot execute at all still ends a root in
CREATE_FAILED and sends it, so that stack's end is not silent; the reading has no such path.

CloudFormationService.addEvent is the one place a status is recorded, so it queues an event for a
stack's own record, and CloudFormationEventPublisher delivers them in order on one daemon thread. A
status can be recorded under the stack's lock in stacks.compute and delivery calls a rule's targets
before it returns, so delivering in place would hold that lock and the operation for as long as the
targets take. A failed path records its event before it writes the status, so delivery waits a
moment for that write. The queue is in memory: an event still in it when Floci stops is dropped and
counted in the log, and is not sent on the next start.

The query handler hands each operation's token to the service, which sets it on the stack before the
operation's first record and clears it where the operation has none. It is not persisted.

test(cloudformation): an update failing outside a resource sends no UPDATE_FAILED

An update that fails before any resource, on an SSM parameter or a template that fails at execute,
goes straight to its rollback, and CloudFormation sends no UPDATE_FAILED, as for a failure in a
resource. On 2.4.0 the failed-execute path already sends none, so this commit carries the test alone
that keeps it so: the bus hears UPDATE_IN_PROGRESS, the rollback's statuses and nothing else, each
with the operation's request token.

(test cherry picked from commit 9314dad130116c5d4c809072800c787a4d640446, whose code change 2.4.0
makes moot)

fix(cloudformation): roll back a failed nested create's RetainExceptOnCreate, and send a start only once it runs

A nested stack's failed create is deleted by its parent's rollback through the
ordinary delete path, which kept what RetainExceptOnCreate marks. The delete of
a child in CREATE_FAILED now carries the create-rollback flag, so those
resources go as they did when the child rolled itself back, and a nested case
in CloudFormationDeletionPolicyIntegrationTest keeps it so.

The status an operation starts with is recorded under the stack's lock but
sent by the operation as its first act, so an operation the executor refuses
sends nothing. A successful create or update records its completion before
the terminal status is exposed, as the failed paths do, so the event carries
the operation's own token and not a later request's.

The publisher test waits for the worker to be sleeping or stopped instead of a
fixed 200 ms, and the status events test has one wait loop for the root's and
the nested stack's events.

fix(cloudformation): a delete deferred behind a running create sends its own token

A DeleteStack accepted while an execution runs waits for it, and until now
only its retain list waited: when the execution ended and the delete began,
the stack still held the execution's token, so DELETE_IN_PROGRESS and
DELETE_COMPLETE went out with it. The deferred delete now keeps its token
beside what it retains, and the stack takes it as the delete starts.
aDeleteLandingMidCreateCarriesItsOwnToken holds a custom resource's Create
open, lands the delete, and reads the tokens on the bus; it was red before.

The stale Javadoc above awaitEvents goes.

The mid-create test stubbed the ServiceToken Lambda and PUT the response itself,
which CustomResourceProbe already does. The probe takes a hold: the requests a
predicate matches wait before they are answered until the test releases them,
and the test reads when one has arrived. The status events test holds the
Create that way.
This commit is contained in:
Charles Swanberg authored and GitHub committed 2026-11-09 20:58:07 -04:00
1 parent 6710ce4d46
commit 2a3dbb1aa4
10 files changed
+1173 -43

No files matched your search

@@ -0,0 +1,144 @@
package io.floci.aws.services.cloudformation;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.services.cloudformation.model.Stack;
import io.floci.aws.services.eventbridge.EventBridgeService;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.Objects;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
/**
* Publishes AWS-shaped {@code aws.cloudformation} "CloudFormation Stack Status Change" events to the
* default EventBridge bus of the stack's account and Region, one per status recorded for a stack.
*
* <p>Unlike the other publishers this one only queues, and one daemon worker delivers in order. A
* status can be recorded while the service holds the stack's lock in {@code stacks.compute}, and
* delivery calls a rule's targets before it returns, so delivering in place would hold that lock and
* the operation for as long as the targets take.
*
* <p>The queue is in memory. An event still in it when Floci stops is dropped, and counted in the log:
* it is not sent on the next start, even where the stack itself is persisted.
*/
@ApplicationScoped
public class CloudFormationEventPublisher {
private static final Logger LOG = Logger.getLogger(CloudFormationEventPublisher.class);
static final String SOURCE = "aws.cloudformation";
static final String DETAIL_TYPE = "CloudFormation Stack Status Change";
private static final long STATUS_WRITE_WAIT_NANOS = TimeUnit.SECONDS.toNanos(1);
private record StatusChange(Stack stack, String accountId, String statusWhenRecorded, String status,
String reason, String token) {
}
private final BlockingQueue<StatusChange> pending = new LinkedBlockingQueue<>();
private final EventBridgeService eventBridgeService;
private final ObjectMapper objectMapper;
private Thread worker;
@Inject
public CloudFormationEventPublisher(EventBridgeService eventBridgeService, ObjectMapper objectMapper) {
this.eventBridgeService = eventBridgeService;
this.objectMapper = objectMapper;
}
@PostConstruct
void start() {
worker = new Thread(this::deliverInOrder, "cloudformation-event-publisher");
worker.setDaemon(true);
worker.start();
}
@PreDestroy
void stop() {
worker.interrupt();
}
/** The worker's state: sleeping in {@link #awaitStatusWrite} is TIMED_WAITING, stopped is TERMINATED. */
Thread.State workerState() {
return worker.getState();
}
/**
* Queues one event for {@code status} and returns at once, so it is safe under the stack's lock.
* The token is the one on the stack now, the operation that caused this status.
*/
public void stackStatusChanged(Stack stack, String accountId, String status, String reason) {
pending.add(new StatusChange(stack, accountId, stack.getStatus(), status, reason,
stack.getClientRequestToken()));
}
private void deliverInOrder() {
StatusChange held = null;
try {
while (true) {
held = pending.take();
awaitStatusWrite(held);
if (Thread.interrupted()) {
throw new InterruptedException();
}
deliver(held);
held = null;
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
int dropped = pending.size() + (held != null ? 1 : 0);
if (dropped > 0) {
LOG.warnv("Dropping {0} queued CloudFormation Stack Status Change event(s): Floci is stopping", dropped);
}
}
}
/**
* A failed path records its event before it writes the status, the volatile publishing write, so
* that a reader who sees the status also sees the event in DescribeStackEvents. A reader the bus
* event wakes must see the status too, so delivery waits out the few statements between the two.
* Bounded, since a status left unwritten must not hold up every later event.
*/
private static void awaitStatusWrite(StatusChange change) throws InterruptedException {
if (Objects.equals(change.statusWhenRecorded(), change.status())) {
return;
}
long deadline = System.nanoTime() + STATUS_WRITE_WAIT_NANOS;
while (Objects.equals(change.statusWhenRecorded(), change.stack().getStatus())
&& System.nanoTime() < deadline) {
Thread.sleep(1);
}
}
private void deliver(StatusChange change) {
String stackId = change.stack().getStackId();
String region = change.stack().getRegion();
try {
String detail = objectMapper.writeValueAsString(buildDetail(change));
RequestScopes.runAs(change.accountId(), region,
() -> eventBridgeService.publishServiceEvent(SOURCE, DETAIL_TYPE, detail, stackId, region));
} catch (Exception e) {
LOG.warnv("Failed to emit CloudFormation Stack Status Change for {0}: {1}", stackId, e.getMessage());
}
}
// As CloudFormation sent them on 2026-10-30: the key is absent, not empty, where there is no token,
// and detailed-status and status-reason are present and empty where there is nothing to say.
private ObjectNode buildDetail(StatusChange change) {
ObjectNode detail = objectMapper.createObjectNode();
detail.put("stack-id", change.stack().getStackId());
if (change.token() != null && !change.token().isEmpty()) {
detail.put("client-request-token", change.token());
}
ObjectNode statusDetails = detail.putObject("status-details");
statusDetails.put("status", change.status());
statusDetails.put("detailed-status", "");
statusDetails.put("status-reason", change.reason() != null ? change.reason() : "");
return detail;
}
}
@@ -125,7 +125,8 @@ public class CloudFormationQueryHandler {
templateBody, templateUrl, parameters, capabilities, tags, region,
terminationProtection, stackPolicy);
try {
cfnService.executeChangeSet(initial.getStackId(), initial.getChangeSetId(), region);
cfnService.executeChangeSetWithToken(initial.getStackId(), initial.getChangeSetId(), region,
params.getFirst("ClientRequestToken"));
} catch (AwsException e) {
if (terminationProtection) {
cfnService.clearProtectionAfterRejectedCreate(stackName, initial, region);
@@ -171,7 +172,8 @@ public class CloudFormationQueryHandler {
cfnService.deleteChangeSet(stackName, cs.getChangeSetName(), region);
return xmlError("ValidationError", "No updates are to be performed.", 400);
}
cfnService.executeChangeSet(cs.getStackId(), cs.getChangeSetId(), region);
cfnService.executeChangeSetWithToken(cs.getStackId(), cs.getChangeSetId(), region,
params.getFirst("ClientRequestToken"));
String xml = new XmlBuilder()
.start("UpdateStackResponse", CF_NS)
@@ -190,7 +192,7 @@ public class CloudFormationQueryHandler {
String stackName = params.getFirst("StackName");
List<String> retainResources = extractList(params, "RetainResources.member.");
try {
cfnService.deleteStack(stackName, retainResources, region);
cfnService.deleteStackForRequest(stackName, retainResources, region, params.getFirst("ClientRequestToken"));
String xml = new XmlBuilder()
.start("DeleteStackResponse", CF_NS)
.raw(AwsQueryResponse.responseMetadata())
@@ -208,10 +210,12 @@ public class CloudFormationQueryHandler {
String stackName = params.getFirst("StackName");
List<String> resourcesToSkip = extractList(params, "ResourcesToSkip.member.");
boolean forceRollback = Boolean.parseBoolean(params.getFirst("ForceRollback"));
// RoleARN and ClientRequestToken are accepted and have no effect: Floci assumes no role
// for stack operations and does not deduplicate retried requests.
// RoleARN is accepted and has no effect: Floci assumes no role for stack operations.
// ClientRequestToken goes on the status events the operation sends; a repeated one is not
// refused, as Floci does not deduplicate retried requests.
try {
cfnService.continueUpdateRollback(stackName, resourcesToSkip, forceRollback, region);
cfnService.continueUpdateRollback(stackName, resourcesToSkip, forceRollback, region,
params.getFirst("ClientRequestToken"));
} catch (AwsException e) {
return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
}
@@ -362,7 +366,8 @@ public class CloudFormationQueryHandler {
String stackName = params.getFirst("StackName");
String changeSetName = params.getFirst("ChangeSetName");
try {
cfnService.executeChangeSetForRequest(stackName, changeSetName, region);
cfnService.executeChangeSetForRequest(stackName, changeSetName, region,
params.getFirst("ClientRequestToken"));
} catch (AwsException e) {
return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
}
@@ -128,7 +128,10 @@ public class CloudFormationService implements ResourceProvider {
// The execution running on a stack, by stack id, completed once it and any delete it deferred end.
private final ConcurrentHashMap<String, CompletableFuture<Void>> runningExecutions = new ConcurrentHashMap<>();
// A delete requested while its stack's execution runs, by stack id, with the resources it retains.
private final ConcurrentHashMap<String, List<String>> deferredDeletes = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, DeferredDelete> deferredDeletes = new ConcurrentHashMap<>();
/** A DeleteStack accepted while an execution runs: what it retains, and the token its statuses carry. */
private record DeferredDelete(List<String> retain, String clientRequestToken) {}
private final ExecutorService executor = newOperationExecutor();
static ThreadPoolExecutor newOperationExecutor() {
@@ -149,6 +152,8 @@ public class CloudFormationService implements ResourceProvider {
private final SamTransformProcessor samTransformProcessor;
private final AwsIncludeProcessor awsIncludeProcessor;
private final Clock clock;
// Null on a service built by hand, as a unit test builds one, which then sends no events.
private final CloudFormationEventPublisher eventPublisher;
// Persisted state so stacks survive a restart (criteria #10, #11). The in-memory maps above are
// the live working copy; these backends are write-through + loaded on startup. Legacy records
@@ -157,13 +162,24 @@ public class CloudFormationService implements ResourceProvider {
private final AccountAwareStorageBackend<String> exportBackend;
@Inject
public CloudFormationService(CfnResourceDispatcher dispatcher, S3Service s3Service,
SsmService ssmService, GetStackOutputRoleAuthorizer stackOutputRoles,
CfnDynamicReferences dynamicReferences,
ObjectMapper objectMapper, EmulatorConfig config,
RegionResolver regionResolver, Clock clock,
StorageFactory storageFactory) {
this(dispatcher, s3Service, ssmService, stackOutputRoles, dynamicReferences, objectMapper, config,
regionResolver, clock, storageFactory, null);
}
@Inject
public CloudFormationService(CfnResourceDispatcher dispatcher, S3Service s3Service,
SsmService ssmService, GetStackOutputRoleAuthorizer stackOutputRoles,
CfnDynamicReferences dynamicReferences,
ObjectMapper objectMapper, EmulatorConfig config,
RegionResolver regionResolver, Clock clock,
StorageFactory storageFactory,
CloudFormationEventPublisher eventPublisher) {
this.dispatcher = dispatcher;
this.s3Service = s3Service;
this.ssmService = ssmService;
@@ -175,6 +191,7 @@ public class CloudFormationService implements ResourceProvider {
this.samTransformProcessor = new SamTransformProcessor(objectMapper);
this.awsIncludeProcessor = new AwsIncludeProcessor(objectMapper, s3Service);
this.clock = clock;
this.eventPublisher = eventPublisher;
this.stackBackend = storageFactory.create(
"cloudformation", "cloudformation-stacks.json", new TypeReference<Map<String, Stack>>() {});
this.exportBackend = storageFactory.create(
@@ -736,6 +753,9 @@ public class CloudFormationService implements ResourceProvider {
cs.setStatus("CREATE_COMPLETE");
cs.setExecutionStatus("AVAILABLE");
}
// No operation runs on a stack that takes a change set, and what this one records carries
// no token: CreateChangeSet's ClientToken is not a ClientRequestToken.
target.setClientRequestToken(null);
target.getChangeSets().put(changeSetName, cs);
created[0] = cs;
return target;
@@ -1332,8 +1352,20 @@ public class CloudFormationService implements ResourceProvider {
* update equivalent) when their own change set failed - executing it unconditionally is how
* that failure surfaces on those paths, and floci must still expose it there.
*/
public Future<?> executeChangeSetForRequest(String stackName, String changeSetName, String region) {
return claimAndSubmitExecution(stackName, changeSetName, region, regionResolver.getAccountId(), true);
public Future<?> executeChangeSetForRequest(String stackName, String changeSetName, String region,
String clientRequestToken) {
return claimAndSubmitExecution(stackName, changeSetName, region, regionResolver.getAccountId(), true,
clientRequestToken);
}
/**
* The execute {@code CreateStack} and {@code UpdateStack} run, as
* {@link #executeChangeSet(String, String, String)}, for a request that carries a token.
*/
public Future<?> executeChangeSetWithToken(String stackName, String changeSetName, String region,
String clientRequestToken) {
return claimAndSubmitExecution(stackName, changeSetName, region, regionResolver.getAccountId(), false,
clientRequestToken);
}
/**
@@ -1351,7 +1383,7 @@ public class CloudFormationService implements ResourceProvider {
* refuses one that is already executing or has already executed.
*/
public Future<?> executeChangeSet(String stackName, String changeSetName, String region, String accountId) {
return claimAndSubmitExecution(stackName, changeSetName, region, accountId, false);
return claimAndSubmitExecution(stackName, changeSetName, region, accountId, false, null);
}
private record ClaimedExecution(ChangeSet changeSet, boolean isCreate, CompletableFuture<Void> done) {}
@@ -1366,7 +1398,8 @@ public class CloudFormationService implements ResourceProvider {
// compute() holds the stack's per-key lock for the whole claim, so only one racing execution can win.
private Future<?> claimAndSubmitExecution(String stackNameOrArn, String changeSetName, String region,
String accountId, boolean requireAvailable) {
String accountId, boolean requireAvailable,
String clientRequestToken) {
String canonicalStackName = getStackForChangeSet(stackNameOrArn, changeSetName, region,
accountId).getStackName();
@@ -1412,9 +1445,10 @@ public class CloudFormationService implements ResourceProvider {
if (isCreate && cs.getStackPolicyBody() != null) {
existing.setStackPolicyBody(cs.getStackPolicyBody());
}
existing.setClientRequestToken(clientRequestToken);
existing.setStatus(isCreate ? "CREATE_IN_PROGRESS" : "UPDATE_IN_PROGRESS");
existing.setLastUpdatedTime(now());
addEvent(existing, existing.getStackName(), existing.getStackId(),
recordEvent(existing, existing.getStackName(), existing.getStackId(),
"AWS::CloudFormation::Stack", isCreate ? "CREATE_IN_PROGRESS" : "UPDATE_IN_PROGRESS", null);
CompletableFuture<Void> done = new CompletableFuture<>();
runningExecutions.put(existing.getStackId(), done);
@@ -1453,6 +1487,7 @@ public class CloudFormationService implements ResourceProvider {
Map<String, String> params = cs.getParameters() != null ? cs.getParameters() : Map.of();
return submitOperation(() -> RequestScopes.runAs(accountId, region, () -> {
publishStackStatus(stack, claimed.isCreate() ? "CREATE_IN_PROGRESS" : "UPDATE_IN_PROGRESS", null);
try {
executeTemplate(stack, templateBody, params, cs.getTags(), claimed.isCreate(), region, accountId,
cs.getStackPolicyBody());
@@ -1484,14 +1519,17 @@ public class CloudFormationService implements ResourceProvider {
if (!runningExecutions.remove(stackId, done)) {
return existing;
}
List<String> retain = deferredDeletes.remove(stackId);
if (retain != null && existing != null && stackId.equals(existing.getStackId())) {
startDelete(existing, retain);
deferred.add(retain);
DeferredDelete delete = deferredDeletes.remove(stackId);
if (delete != null && existing != null && stackId.equals(existing.getStackId())) {
// The delete's own token, not the execution's, from its first status on.
existing.setClientRequestToken(delete.clientRequestToken());
startDelete(existing, delete.retain());
deferred.add(delete.retain());
}
return existing;
});
if (!deferred.isEmpty()) {
publishStackStatus(stack, "DELETE_IN_PROGRESS", null);
deleteStackResources(stack, deferred.getFirst(), region, accountId);
}
done.complete(null);
@@ -1501,10 +1539,11 @@ public class CloudFormationService implements ResourceProvider {
}
}
/** Moves the stack to DELETE_IN_PROGRESS; the delete sends that status as it begins. */
private void startDelete(Stack stack, List<String> retain) {
stack.setRetainResources(retain);
stack.setStatus("DELETE_IN_PROGRESS");
addEvent(stack, stack.getStackName(), stack.getStackId(),
recordEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", "DELETE_IN_PROGRESS", null);
}
@@ -1552,6 +1591,17 @@ public class CloudFormationService implements ResourceProvider {
* removal) can await it.
*/
public Future<?> deleteStack(String stackName, List<String> retainResources, String region, String accountId) {
return deleteStack(stackName, retainResources, region, accountId, null);
}
/** The {@code DeleteStack} operation, in the caller's account, for a request that may carry a token. */
public Future<?> deleteStackForRequest(String stackName, List<String> retainResources, String region,
String clientRequestToken) {
return deleteStack(stackName, retainResources, region, regionResolver.getAccountId(), clientRequestToken);
}
private Future<?> deleteStack(String stackName, List<String> retainResources, String region, String accountId,
String clientRequestToken) {
validateRetainResources(retainResources);
purgeExpiredDeletedStacks();
Stack stack = resolveStack(stackName, region, accountId);
@@ -1611,15 +1661,18 @@ public class CloudFormationService implements ResourceProvider {
if (running != null) {
// The execution deletes the stack once it ends: a create stops before its next
// resource, an update finishes, and the delete then removes all that was built.
deferredDeletes.putIfAbsent(existing.getStackId(), retain);
deferredDeletes.putIfAbsent(existing.getStackId(), new DeferredDelete(retain, clientRequestToken));
submitted[0] = running;
return existing;
}
StackMutationSnapshot snapshot = snapshot(existing);
existing.setClientRequestToken(clientRequestToken);
startDelete(existing, retain);
try {
submitted[0] = submitOperation(() -> RequestScopes.runAs(accountId, region,
() -> deleteStackResources(existing, retain, region, accountId)));
submitted[0] = submitOperation(() -> RequestScopes.runAs(accountId, region, () -> {
publishStackStatus(existing, "DELETE_IN_PROGRESS", null);
deleteStackResources(existing, retain, region, accountId);
}));
} catch (AwsException e) {
restore(existing, snapshot);
throw e;
@@ -1657,6 +1710,12 @@ public class CloudFormationService implements ResourceProvider {
*/
public Future<?> continueUpdateRollback(
String stackNameOrArn, List<String> resourcesToSkip, boolean forceRollback, String region) {
return continueUpdateRollback(stackNameOrArn, resourcesToSkip, forceRollback, region, null);
}
public Future<?> continueUpdateRollback(
String stackNameOrArn, List<String> resourcesToSkip, boolean forceRollback, String region,
String clientRequestToken) {
validateContinueUpdateRollback(stackNameOrArn, resourcesToSkip);
if (forceRollback && !resourcesToSkip.isEmpty()) {
throw new AwsException("ValidationError", FORCE_WITH_SKIPS, 400);
@@ -1677,15 +1736,18 @@ public class CloudFormationService implements ResourceProvider {
throw new AwsException("ValidationError", CONTINUE_ROLLBACK_REFUSED, 400);
}
snapshot[0] = snapshot(existing);
existing.setClientRequestToken(clientRequestToken);
existing.setStatus("UPDATE_ROLLBACK_IN_PROGRESS");
addEvent(existing, existing.getStackName(), existing.getStackId(),
recordEvent(existing, existing.getStackName(), existing.getStackId(),
"AWS::CloudFormation::Stack", "UPDATE_ROLLBACK_IN_PROGRESS", "User Initiated");
return existing;
});
try {
persistStack(stack);
return submitOperation(() -> RequestScopes.runAs(accountId, region,
() -> resumeUpdateRollback(stack, skips, forceRollback, region)));
return submitOperation(() -> RequestScopes.runAs(accountId, region, () -> {
publishStackStatus(stack, "UPDATE_ROLLBACK_IN_PROGRESS", "User Initiated");
resumeUpdateRollback(stack, skips, forceRollback, region);
}));
} catch (AwsException e) {
if ("LimitExceededException".equals(e.getErrorCode())) {
Stack restored = restoreStack(accountId, stackName, region, snapshot[0]);
@@ -2622,10 +2684,12 @@ public class CloudFormationService implements ResourceProvider {
return;
}
stack.setStatus("CREATE_COMPLETE");
stack.setLastUpdatedTime(now());
// Recorded before the status, as the failed paths do: once the status is terminal another
// operation may take the stack and its token, and this event carries this operation's.
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", "CREATE_COMPLETE", null);
stack.setLastUpdatedTime(now());
stack.setStatus("CREATE_COMPLETE");
persistStack(stack);
LOG.infov("Stack {0} execution complete: CREATE_COMPLETE", stack.getStackName());
@@ -2693,7 +2757,8 @@ public class CloudFormationService implements ResourceProvider {
Set<String> attemptedResourceIds) {
LOG.warnv("Stack {0} resource {1} failed: {2}", stack.getStackName(),
failedResource.getLogicalId(), failedResource.getStatusReason());
rollbackFailedExecution(stack, region, isCreate, rollbackReason(isCreate, failedResource), previousState,
rollbackFailedExecution(stack, region, isCreate,
rollbackReason(isCreate && stack.getParentId() == null, failedResource), previousState,
attemptedResourceIds);
}
@@ -2707,7 +2772,14 @@ public class CloudFormationService implements ResourceProvider {
Set<String> attemptedResourceIds) {
stack.setStatusReason(reason);
if (isCreate) {
if (isCreate && stack.getParentId() != null) {
// CloudFormation reports a nested stack's failed create as CREATE_FAILED and its rollback
// as the delete its parent's rollback gives it; the nested stack has no ROLLBACK_* status.
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", "CREATE_FAILED", reason);
stack.setLastUpdatedTime(now());
stack.setStatus("CREATE_FAILED");
} else if (isCreate) {
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", "ROLLBACK_IN_PROGRESS", reason);
stack.setStatus("ROLLBACK_IN_PROGRESS");
@@ -2875,11 +2947,11 @@ public class CloudFormationService implements ResourceProvider {
.collect(java.util.stream.Collectors.joining(", "))
+ "].";
}
stack.setStatus("UPDATE_COMPLETE");
stack.setStatusReason(statusReason);
stack.setLastUpdatedTime(now());
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", "UPDATE_COMPLETE", statusReason);
stack.setStatusReason(statusReason);
stack.setLastUpdatedTime(now());
stack.setStatus("UPDATE_COMPLETE");
persistStack(stack);
LOG.infov("Stack {0} execution complete: UPDATE_COMPLETE", stack.getStackName());
}
@@ -2918,11 +2990,14 @@ public class CloudFormationService implements ResourceProvider {
"Stack [" + child.getStackId()
+ "] cannot be deleted while TerminationProtection is enabled", 400);
}
// A child in CREATE_FAILED is deleted as the rollback of its create, so what
// RetainExceptOnCreate marks goes with it, as it does when a root rolls back.
boolean createRollback = "CREATE_FAILED".equals(child.getStatus());
child.setRetainResources(List.of());
child.setStatus("DELETE_IN_PROGRESS");
addEvent(child, child.getStackName(), child.getStackId(),
"AWS::CloudFormation::Stack", "DELETE_IN_PROGRESS", null);
deleteStackResources(child, region, accountId);
deleteStackResources(child, List.of(), region, accountId, createRollback);
} else {
dispatcher.delete(resource, region);
}
@@ -2986,7 +3061,7 @@ public class CloudFormationService implements ResourceProvider {
stack, previousState.resources(), owed, region);
stack.setUpdateRollbackResourceIds(List.copyOf(rollbackFailures));
finishUpdateRollback(stack, region, previousState, rollbackFailures,
forceRollback && !skips.isEmpty() ? FORCED_ROLLBACK_COMPLETE_REASON : null);
forceRollback && !skips.isEmpty() ? FORCED_ROLLBACK_COMPLETE_REASON : null, false);
} catch (Exception e) {
// Nobody reads this worker's future: a stack left UPDATE_ROLLBACK_IN_PROGRESS here could
// never be continued. The snapshot and the resources still owed a rollback are kept.
@@ -3044,14 +3119,15 @@ public class CloudFormationService implements ResourceProvider {
List<String> rollbackFailures = rollbackUpdatedResources(
stack, previousState.resources(), attemptedResourceIds, region);
finishUpdateRollback(stack, region, previousState, rollbackFailures, null);
finishUpdateRollback(stack, region, previousState, rollbackFailures, null, true);
}
/**
* Ends an update rollback, the first one and every ContinueUpdateRollback retry alike: restores
* the parameters, outputs and exports, and the template once every resource rolled back, then
* settles the stack in UPDATE_ROLLBACK_COMPLETE, with {@code completionReason} as its reason, or
* UPDATE_ROLLBACK_FAILED. A rollback that fails keeps the snapshot and the resources still owed
* UPDATE_ROLLBACK_FAILED. The first rollback reports UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS on
* the way, as CloudFormation was read to; a retry was not read. A rollback that fails keeps the snapshot and the resources still owed
* a rollback on the stack for a retry.
*/
private void finishUpdateRollback(
@@ -3059,7 +3135,8 @@ public class CloudFormationService implements ResourceProvider {
String region,
StackUpdateSnapshot previousState,
List<String> rollbackFailures,
String completionReason) {
String completionReason,
boolean reportsCleanup) {
List<String> owedResourceIds = List.copyOf(rollbackFailures);
// Parameters are independent of resource-rollback outcome - always restore them to the last
// successfully deployed values, even when resource rollback itself fails and the stack lands
@@ -3091,6 +3168,11 @@ public class CloudFormationService implements ResourceProvider {
if (rollbackFailures.isEmpty()) {
stack.setUpdateRollbackSnapshot(null);
stack.setUpdateRollbackResourceIds(null);
if (reportsCleanup) {
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", "UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS", null);
stack.setStatus("UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS");
}
// Reason and event before the status, which is the volatile publishing write.
stack.setStatusReason(completionReason);
addEvent(stack, stack.getStackName(), stack.getStackId(),
@@ -3958,6 +4040,15 @@ public class CloudFormationService implements ResourceProvider {
/** Deletes the stack's resources, except those {@code retainResources} names or a policy retains. */
void deleteStackResources(Stack stack, List<String> retainResources, String region, String accountId) {
deleteStackResources(stack, retainResources, region, accountId, false);
}
/**
* As {@link #deleteStackResources(Stack, List, String, String)}; {@code createRollback} says the
* delete rolls back the stack's create, which {@code RetainExceptOnCreate} does not survive.
*/
private void deleteStackResources(Stack stack, List<String> retainResources, String region, String accountId,
boolean createRollback) {
try {
List<StackResource> resources = resourcesInCreationOrder(stack, region);
Collections.reverse(resources); // Dependents go before what they depend on
@@ -3981,7 +4072,7 @@ public class CloudFormationService implements ResourceProvider {
if (resource.getPhysicalId() == null || !isDeletableOnStackDelete(resource)) {
continue;
}
if (skipRetainedResource(stack, resource, false)) {
if (skipRetainedResource(stack, resource, createRollback)) {
continue;
}
addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(),
@@ -4622,9 +4713,14 @@ public class CloudFormationService implements ResourceProvider {
if (childCreate) {
childStack = newStack(childStackName, newStackId(childStackName, region, accountId), region, accountId);
childStack.setParentId(parentStack.getStackId());
childStack.setStatus("CREATE_IN_PROGRESS");
stacks.put(stackKey(accountId, childStackName, region), childStack);
} else {
childStack.setStatus("UPDATE_IN_PROGRESS");
}
addEvent(childStack, childStack.getStackName(), childStack.getStackId(),
"AWS::CloudFormation::Stack", childCreate ? "CREATE_IN_PROGRESS" : "UPDATE_IN_PROGRESS", null);
if (!childCreate) {
resource.getAttributes().put(CfnRollback.NESTED_STACK_UPDATE_SNAPSHOT_ATTR,
@@ -4786,6 +4882,21 @@ public class CloudFormationService implements ResourceProvider {
private void addEvent(Stack stack, String logicalId, String physicalId,
String resourceType, String status, String reason) {
recordEvent(stack, logicalId, physicalId, resourceType, status, reason);
// A stack's own record: a parent's record of a nested stack has the resource's logical id.
if (stack.getStackName().equals(logicalId) && stack.getStackId().equals(physicalId)) {
publishStackStatus(stack, status, reason);
}
}
/**
* Records the event without sending it to the bus. The status an operation starts with is
* recorded under the stack's lock before the operation is submitted, and the executor may refuse
* it; the operation then sends that status as its first act, so a rule never sees a start that
* does not run.
*/
private void recordEvent(Stack stack, String logicalId, String physicalId,
String resourceType, String status, String reason) {
StackEvent event = new StackEvent();
event.setStackId(stack.getStackId());
event.setStackName(stack.getStackName());
@@ -4797,6 +4908,12 @@ public class CloudFormationService implements ResourceProvider {
stack.getEvents().add(event);
}
private void publishStackStatus(Stack stack, String status, String reason) {
if (eventPublisher != null) {
eventPublisher.stackStatusChanged(stack, ownerAccount(stack), status, reason);
}
}
private Stack getStackOrThrow(String stackNameOrArn, String region) {
return getStackOrThrow(stackNameOrArn, region, currentAccount());
}
@@ -44,6 +44,13 @@ public class Stack {
*/
private volatile String status = "CREATE_IN_PROGRESS";
private String statusReason;
/** The stack that nests this one; null for a root stack. */
private String parentId;
/**
* The ClientRequestToken of this stack's current operation, null when it was given none. A nested
* stack never has one. Set before the operation's first record and read on its worker thread.
*/
private volatile String clientRequestToken;
private Instant creationTime = Instant.now();
private Instant lastUpdatedTime;
/** Set once the stack reaches DELETE_COMPLETE; null for every stack that is still there. */
@@ -99,6 +106,12 @@ public class Stack {
public void setStatus(String status) { this.status = status; }
public String getStatusReason() { return statusReason; }
public void setStatusReason(String statusReason) { this.statusReason = statusReason; }
public String getParentId() { return parentId; }
public void setParentId(String parentId) { this.parentId = parentId; }
@JsonIgnore
public String getClientRequestToken() { return clientRequestToken; }
@JsonIgnore
public void setClientRequestToken(String clientRequestToken) { this.clientRequestToken = clientRequestToken; }
public Instant getCreationTime() { return creationTime; }
public void setCreationTime(Instant creationTime) { this.creationTime = creationTime; }
public Instant getLastUpdatedTime() { return lastUpdatedTime; }