fix(cloudformation): start one deletion per stack and refuse change sets on a stack being deleted (#5835)

This commit is contained in:
Niels Kootstra authored and GitHub committed 2026-10-16 18:11:40 -04:00
1 parent eb84539a67
commit 1f6261fc1c
3 files changed
+154 -49

No files matched your search

@@ -244,6 +244,10 @@ public class CloudFormationService implements ResourceProvider {
return stack != null ? stack.getStatus() : null;
}
private static boolean isBeingDeleted(String status) {
return "DELETE_IN_PROGRESS".equals(status) || "DELETE_COMPLETE".equals(status);
}
/**
* Whether a stack in this status refuses an update, on the two grounds AWS refuses one.
*
@@ -975,6 +979,10 @@ public class CloudFormationService implements ResourceProvider {
"Stack with id " + stackNameOrArn + " does not exist", 400);
}
ChangeSet cs = getChangeSetOrThrow(existing, changeSetName, region, accountId);
if (isBeingDeleted(existing.getStatus())) {
throw new AwsException("InvalidChangeSetStatus", "ChangeSet [" + cs.getChangeSetId()
+ "] cannot be executed while its stack is in status [" + existing.getStatus() + "]", 400);
}
String executionStatus = cs.getExecutionStatus();
boolean eligible = requireAvailable
? "AVAILABLE".equals(executionStatus)
@@ -1083,29 +1091,37 @@ public class CloudFormationService implements ResourceProvider {
}
return CompletableFuture.completedFuture(null); // Already gone — no-op
}
if (stack.isEnableTerminationProtection()) {
// Real AWS rejects deletion of a protected stack and leaves it unchanged.
throw new AwsException("ValidationError",
"Stack [" + stack.getStackId()
+ "] cannot be deleted while TerminationProtection is enabled", 400);
}
StackMutationSnapshot snapshot = snapshot(stack);
stack.setStatus("DELETE_IN_PROGRESS");
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", "DELETE_IN_PROGRESS", null);
try {
return submitOperation(() -> RequestScopes.runAs(accountId, region,
() -> deleteStackResources(stack, region, accountId)));
} catch (AwsException e) {
if ("LimitExceededException".equals(e.getErrorCode())) {
Stack restored = restoreStack(accountId, stack.getStackName(), region, snapshot);
if (restored != null) {
persistStack(restored);
}
// The check, the move to DELETE_IN_PROGRESS and the submission are one step under the
// stack's lock. A retried or racing delete therefore finds either the stack as it was or a
// deletion already running, and starts no second one; a stack that took this name since it
// was resolved is a different stack, and is left alone.
String stackId = stack.getStackId();
Future<?>[] submitted = new Future<?>[1];
stacks.compute(stackKey(accountId, stack.getStackName(), region), (k, existing) -> {
if (existing == null || !existing.getStackId().equals(stackId)
|| isBeingDeleted(existing.getStatus())) {
return existing;
}
throw e;
}
if (existing.isEnableTerminationProtection()) {
// Real AWS rejects deletion of a protected stack and leaves it unchanged.
throw new AwsException("ValidationError",
"Stack [" + existing.getStackId()
+ "] cannot be deleted while TerminationProtection is enabled", 400);
}
StackMutationSnapshot snapshot = snapshot(existing);
existing.setStatus("DELETE_IN_PROGRESS");
addEvent(existing, existing.getStackName(), existing.getStackId(),
"AWS::CloudFormation::Stack", "DELETE_IN_PROGRESS", null);
try {
submitted[0] = submitOperation(() -> RequestScopes.runAs(accountId, region,
() -> deleteStackResources(existing, region, accountId)));
} catch (AwsException e) {
restore(existing, snapshot);
throw e;
}
return existing;
});
return submitted[0] != null ? submitted[0] : CompletableFuture.completedFuture(null);
}
// ── ContinueUpdateRollback ────────────────────────────────────────────────
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.cloudformation.model.ChangeSet;
import io.github.hectorvent.floci.services.cloudformation.model.Stack;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
@@ -33,8 +34,8 @@ import static org.mockito.Mockito.withSettings;
/**
* Fills the bounded operation executor with change set executions that block inside resource
* provisioning, then checks that the execution it rejects leaves its stack and change set as
* they were.
* provisioning, then checks that the execution or stack delete it rejects leaves the stack (and
* change set) as they were, and can be retried once there is room.
*
* <p>The dispatcher bean is swapped for a mock whose default answer blocks {@code provision}
* for this test's stacks and forwards everything else to the real dispatcher. The answer
@@ -59,6 +60,9 @@ class CloudFormationServiceRestoreIntegrationTest {
@Inject
CfnResourceDispatcher provisioner;
@Inject
RegionResolver regionResolver;
private final CountDownLatch activeOperations = new CountDownLatch(ACTIVE_OPERATIONS);
private final CountDownLatch releaseOperations = new CountDownLatch(1);
private CfnResourceDispatcher blockingProvisioner;
@@ -76,28 +80,10 @@ class CloudFormationServiceRestoreIntegrationTest {
@Test
void rejectedExecutionRestoresStackAndChangeSetState() throws Exception {
String targetStack = uniqueStackName("target");
List<String> fillerStacks = new ArrayList<>();
for (int i = 0; i < ACTIVE_OPERATIONS + QUEUED_OPERATIONS; i++) {
fillerStacks.add(uniqueStackName("filler"));
}
for (String fillerStack : fillerStacks) {
createChangeSet(fillerStack);
}
createChangeSet(targetStack);
List<Future<?>> runningOperations = new ArrayList<>();
List<Future<?>> runningOperations = fillExecutor();
try {
for (String fillerStack : fillerStacks.subList(0, ACTIVE_OPERATIONS)) {
runningOperations.add(service.executeChangeSet(fillerStack, "initial", REGION));
}
assertTrue(activeOperations.await(TIMEOUT_SECONDS, TimeUnit.SECONDS),
this::describeProvisionerActivity);
for (String fillerStack : fillerStacks.subList(ACTIVE_OPERATIONS, fillerStacks.size())) {
runningOperations.add(service.executeChangeSet(fillerStack, "initial", REGION));
}
AwsException rejected = assertThrows(AwsException.class,
() -> service.executeChangeSet(targetStack, "initial", REGION));
assertEquals("LimitExceededException", rejected.getErrorCode());
@@ -108,10 +94,7 @@ class CloudFormationServiceRestoreIntegrationTest {
assertEquals("CREATE_COMPLETE", restoredChangeSet.getStatus());
assertEquals("AVAILABLE", restoredChangeSet.getExecutionStatus());
} finally {
releaseOperations.countDown();
for (Future<?> operation : runningOperations) {
operation.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
}
release(runningOperations);
}
Future<?> retry = service.executeChangeSet(targetStack, "initial", REGION);
@@ -121,6 +104,58 @@ class CloudFormationServiceRestoreIntegrationTest {
service.describeChangeSet(targetStack, "initial", REGION).getExecutionStatus());
}
@Test
void rejectedDeleteLeavesTheStackAsItWasAndCanBeRetried() throws Exception {
// Outside STACK_PREFIX, so its own create is not held by the blocking provisioner.
String targetStack = "restore-delete-target-" + System.nanoTime();
createChangeSet(targetStack);
service.executeChangeSet(targetStack, "initial", REGION).get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
Stack stack = service.describeStacks(targetStack, REGION).getFirst();
assertEquals("CREATE_COMPLETE", stack.getStatus());
List<Future<?>> runningOperations = fillExecutor();
try {
AwsException rejected = assertThrows(AwsException.class,
() -> service.deleteStack(targetStack, REGION));
assertEquals("LimitExceededException", rejected.getErrorCode());
assertEquals("CREATE_COMPLETE", service.describeStacks(targetStack, REGION).getFirst().getStatus());
} finally {
release(runningOperations);
}
service.deleteStack(targetStack, REGION, regionResolver.getAccountId()).get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
assertEquals("DELETE_COMPLETE", stack.getStatus());
}
/** Starts change set executions that block in provisioning until every thread and queue slot is taken. */
private List<Future<?>> fillExecutor() throws InterruptedException {
List<String> fillerStacks = new ArrayList<>();
for (int i = 0; i < ACTIVE_OPERATIONS + QUEUED_OPERATIONS; i++) {
fillerStacks.add(uniqueStackName("filler"));
}
for (String fillerStack : fillerStacks) {
createChangeSet(fillerStack);
}
List<Future<?>> runningOperations = new ArrayList<>();
for (String fillerStack : fillerStacks.subList(0, ACTIVE_OPERATIONS)) {
runningOperations.add(service.executeChangeSet(fillerStack, "initial", REGION));
}
assertTrue(activeOperations.await(TIMEOUT_SECONDS, TimeUnit.SECONDS),
this::describeProvisionerActivity);
for (String fillerStack : fillerStacks.subList(ACTIVE_OPERATIONS, fillerStacks.size())) {
runningOperations.add(service.executeChangeSet(fillerStack, "initial", REGION));
}
return runningOperations;
}
private void release(List<Future<?>> runningOperations) throws Exception {
releaseOperations.countDown();
for (Future<?> operation : runningOperations) {
operation.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
}
}
private void createChangeSet(String stackName) {
service.createChangeSet(stackName, "initial", "CREATE", TEMPLATE, null,
Map.of(), List.of(), Map.of(), REGION);
@@ -31,6 +31,8 @@ import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
@@ -57,8 +59,9 @@ import static org.mockito.Mockito.when;
/**
* Covers rollback cleanup when another actor removes a resource after its create succeeded, which
* resources a stack delete walks after a failed operation left them in a failed status, what a
* failed update rollback keeps so ContinueUpdateRollback can retry it, and that a stack which
* finished deleting is no longer updatable.
* failed update rollback keeps so ContinueUpdateRollback can retry it, that a stack which
* finished deleting is no longer updatable, and that a stack being deleted is neither deleted a
* second time nor updated by a change set.
*/
class CloudFormationServiceRollbackTest {
@@ -218,6 +221,46 @@ class CloudFormationServiceRollbackTest {
assertEquals(Set.of("create"), stack.getChangeSets().keySet());
}
@Test
void deleteStack_retriedWhileDeleting_deletesEachResourceOnce() throws Exception {
Stack stack = liveStack("retried-delete");
StackResource queue = resource("Queue", "queue-url", "AWS::SQS::Queue", "CREATE_COMPLETE");
stack.getResources().put(queue.getLogicalId(), queue);
when(provisioner.completeDeleteCleanup(any())).thenReturn(UpdateCleanupResult.notApplicable());
CountDownLatch deleting = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
doAnswer(invocation -> {
deleting.countDown();
release.await(30, TimeUnit.SECONDS);
return null;
}).when(provisioner).delete(eq(queue), eq(REGION));
Future<?> first = service.deleteStack("retried-delete", REGION, ACCOUNT);
assertTrue(deleting.await(10, TimeUnit.SECONDS));
// The retry starts no deletion of its own, so it never waits on the held resource delete.
service.deleteStack("retried-delete", REGION, ACCOUNT).get(5, TimeUnit.SECONDS);
release.countDown();
first.get(10, TimeUnit.SECONDS);
verify(provisioner, times(1)).delete(queue, REGION);
assertEquals("DELETE_COMPLETE", stack.getStatus());
}
@Test
void executeChangeSet_onStackBeingDeleted_isRefused() {
Stack stack = liveStack("executed-while-deleting");
service.createChangeSet("executed-while-deleting", "update", "UPDATE",
"{\"Resources\":{\"Topic\":{\"Type\":\"AWS::SNS::Topic\"}}}", null,
Map.of(), List.of(), Map.of(), REGION, ACCOUNT);
stack.setStatus("DELETE_IN_PROGRESS");
AwsException error = assertThrows(AwsException.class,
() -> service.executeChangeSet("executed-while-deleting", "update", REGION, ACCOUNT));
assertEquals("InvalidChangeSetStatus", error.getErrorCode());
assertEquals("DELETE_IN_PROGRESS", stack.getStatus());
}
@Test
void deleteStack_savedWithCircularTemplate_stillDeletesDependentsFirst() {
// A stack saved before circular templates were rejected: the queues depend on each other,
@@ -726,6 +769,17 @@ class CloudFormationServiceRollbackTest {
assertNull(stack.getUpdateRollbackResourceIds());
}
/** A stack whose create finished, created through the service so it is in the live map. */
private Stack liveStack(String stackName) {
service.createChangeSet(stackName, "create", "CREATE",
"{\"Resources\":{\"Queue\":{\"Type\":\"AWS::SQS::Queue\"}}}", null,
Map.of(), List.of(), Map.of(), REGION, ACCOUNT);
Stack stack = service.describeStacks(stackName, REGION, ACCOUNT).getFirst();
stack.getChangeSets().clear();
stack.setStatus("CREATE_COMPLETE");
return stack;
}
private static StackResource resource(String logicalId, String physicalId, String resourceType, String status) {
StackResource resource = new StackResource();
resource.setLogicalId(logicalId);