From 70a185a3aa682a102c70c1865f5f3f04992de9c1 Mon Sep 17 00:00:00 2001 From: Niels Kootstra <545768+nkootstra@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:06:48 +0100 Subject: [PATCH] fix(cloudformation): delete a stack whose create is still running only once the create stops (#7358) * fix(cloudformation): delete a stack whose create is still running only once the create stops * fix(cloudformation): leave a deferred delete to the execution it waits on and report its failure * fix(cloudformation): refuse a new execution once a delete has been deferred * test(cloudformation): wait for stack statuses with the shared CfnStackWaits helper --- docs/services/cloudformation.md | 8 + .../cloudformation/CloudFormationService.java | 107 ++++++-- ...tionDeleteDuringCreateIntegrationTest.java | 229 ++++++++++++++++++ 3 files changed, 324 insertions(+), 20 deletions(-) create mode 100644 src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDeleteDuringCreateIntegrationTest.java diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 4004dc3390..80a02141cf 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -1054,8 +1054,16 @@ parameter is refused when the stack is in any other status, when it names a reso not have or has already deleted, or when it names one twice. A retry while that delete is still running must repeat the same list in the same order. +A `DeleteStack` that arrives while the stack is still being created or updated waits for that +operation: a create stops before its next resource, an update runs to its end, and the delete then +removes everything the stack holds, its exports included. Until the delete starts, the stack keeps +its in-progress status. + Deviations from AWS to be aware of: +- A delete that arrives during a create does not interrupt the resource being created; that + resource finishes, and is then deleted with the rest. + - `Snapshot` deletes the resource without taking a snapshot; floci has no snapshot support for the types AWS allows it on. - Every resource defaults to `Delete`. AWS instead defaults `AWS::RDS::DBCluster`, and diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java index 8e8e295fd4..1d30b35267 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java @@ -121,6 +121,10 @@ public class CloudFormationService implements ResourceProvider { private final ConcurrentHashMap deletedStacks = new ConcurrentHashMap<>(); // Account-scoped exports registry: account:region:exportName -> exportValue private final ConcurrentHashMap exports = new ConcurrentHashMap<>(); + // The execution running on a stack, by stack id, completed once it and any delete it deferred end. + private final ConcurrentHashMap> runningExecutions = new ConcurrentHashMap<>(); + // A delete requested while its stack's execution runs, by stack id, with the resources it retains. + private final ConcurrentHashMap> deferredDeletes = new ConcurrentHashMap<>(); private final ExecutorService executor = newOperationExecutor(); static ThreadPoolExecutor newOperationExecutor() { @@ -1182,7 +1186,7 @@ public class CloudFormationService implements ResourceProvider { return claimAndSubmitExecution(stackName, changeSetName, region, accountId, false); } - private record ClaimedExecution(ChangeSet changeSet, boolean isCreate) {} + private record ClaimedExecution(ChangeSet changeSet, boolean isCreate, CompletableFuture done) {} private record ChangeSetState(String status, String executionStatus) {} @@ -1205,9 +1209,13 @@ public class CloudFormationService implements ResourceProvider { "Stack with id " + stackNameOrArn + " does not exist", 400); } ChangeSet cs = getChangeSetOrThrow(existing, changeSetName, region, accountId); - if (isBeingDeleted(existing.getStatus())) { + // A delete deferred to the running execution has been accepted, so the stack is being + // deleted even before that execution ends and the delete reports DELETE_IN_PROGRESS. + String deletingStatus = deferredDeletes.containsKey(existing.getStackId()) + ? "DELETE_IN_PROGRESS" : existing.getStatus(); + if (isBeingDeleted(deletingStatus)) { throw new AwsException("InvalidChangeSetStatus", "ChangeSet [" + cs.getChangeSetId() - + "] cannot be executed while its stack is in status [" + existing.getStatus() + "]", 400); + + "] cannot be executed while its stack is in status [" + deletingStatus + "]", 400); } String executionStatus = cs.getExecutionStatus(); boolean eligible = requireAvailable @@ -1236,18 +1244,24 @@ public class CloudFormationService implements ResourceProvider { existing.setLastUpdatedTime(now()); addEvent(existing, existing.getStackName(), existing.getStackId(), "AWS::CloudFormation::Stack", isCreate ? "CREATE_IN_PROGRESS" : "UPDATE_IN_PROGRESS", null); - claimed[0] = new ClaimedExecution(cs, isCreate); + CompletableFuture done = new CompletableFuture<>(); + runningExecutions.put(existing.getStackId(), done); + claimed[0] = new ClaimedExecution(cs, isCreate, done); return existing; }); try { persistStack(stack); - return submitExecution(stack, claimed[0].changeSet(), claimed[0].isCreate(), region, accountId); - } catch (AwsException e) { - if ("LimitExceededException".equals(e.getErrorCode())) { - Stack restored = restoreStack(accountId, canonicalStackName, region, snapshot[0]); - if (restored != null) { - persistStack(restored); + return submitExecution(stack, claimed[0], region, accountId); + } catch (RuntimeException e) { + try { + if (e instanceof AwsException aws && "LimitExceededException".equals(aws.getErrorCode())) { + Stack restored = restoreStack(accountId, canonicalStackName, region, snapshot[0]); + if (restored != null) { + persistStack(restored); + } } + } finally { + endExecution(stack, claimed[0].done(), region, accountId); } throw e; } @@ -1261,19 +1275,62 @@ public class CloudFormationService implements ResourceProvider { "ChangeSet [" + cs.getChangeSetId() + "] cannot be executed in its current " + detail, 400); } - private Future submitExecution(Stack stack, ChangeSet cs, boolean isCreate, String region, String accountId) { + private Future submitExecution(Stack stack, ClaimedExecution claimed, String region, String accountId) { + ChangeSet cs = claimed.changeSet(); String templateBody = cs.getTemplateBody(); Map params = cs.getParameters() != null ? cs.getParameters() : Map.of(); return submitOperation(() -> RequestScopes.runAs(accountId, region, () -> { - executeTemplate(stack, templateBody, params, cs.getTags(), isCreate, region, accountId); - String status = stack.getStatus(); - cs.setExecutionStatus(status != null && (status.contains("ROLLBACK") || status.endsWith("_FAILED")) - ? "EXECUTE_FAILED" : "EXECUTE_COMPLETE"); - persistStack(stack); + try { + executeTemplate(stack, templateBody, params, cs.getTags(), claimed.isCreate(), region, accountId); + String status = stack.getStatus(); + cs.setExecutionStatus(status != null && (status.contains("ROLLBACK") || status.endsWith("_FAILED")) + ? "EXECUTE_FAILED" : "EXECUTE_COMPLETE"); + persistStack(stack); + } finally { + endExecution(stack, claimed.done(), region, accountId); + } })); } + /** + * Ends an execution and runs the delete requested while it ran, if any. Both happen under the + * stack's lock, so a DeleteStack either defers to the execution or finds it ended and deletes the + * stack itself; it never deletes alongside a running execution. An execution that a newer one + * has replaced leaves the deferred delete to the newer one, which the delete is waiting on. + * {@code done} fails when the deferred delete does, as the future of a delete started directly. + */ + private void endExecution(Stack stack, CompletableFuture done, String region, String accountId) { + String stackId = stack.getStackId(); + List> deferred = new ArrayList<>(1); + try { + stacks.compute(stackKey(accountId, stack.getStackName(), region), (k, existing) -> { + if (!runningExecutions.remove(stackId, done)) { + return existing; + } + List retain = deferredDeletes.remove(stackId); + if (retain != null && existing != null && stackId.equals(existing.getStackId())) { + startDelete(existing, retain); + deferred.add(retain); + } + return existing; + }); + if (!deferred.isEmpty()) { + deleteStackResources(stack, deferred.getFirst(), region, accountId); + } + done.complete(null); + } catch (RuntimeException e) { + done.completeExceptionally(e); + } + } + + private void startDelete(Stack stack, List retain) { + stack.setRetainResources(retain); + stack.setStatus("DELETE_IN_PROGRESS"); + addEvent(stack, stack.getStackName(), stack.getStackId(), + "AWS::CloudFormation::Stack", "DELETE_IN_PROGRESS", null); + } + // ── DeleteChangeSet ─────────────────────────────────────────────────────── public void deleteChangeSet(String stackName, String changeSetName, String region) { @@ -1373,11 +1430,16 @@ public class CloudFormationService implements ResourceProvider { } } } + CompletableFuture running = runningExecutions.get(existing.getStackId()); + 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); + submitted[0] = running; + return existing; + } StackMutationSnapshot snapshot = snapshot(existing); - existing.setRetainResources(retain); - existing.setStatus("DELETE_IN_PROGRESS"); - addEvent(existing, existing.getStackName(), existing.getStackId(), - "AWS::CloudFormation::Stack", "DELETE_IN_PROGRESS", null); + startDelete(existing, retain); try { submitted[0] = submitOperation(() -> RequestScopes.runAs(accountId, region, () -> deleteStackResources(existing, retain, region, accountId))); @@ -2058,6 +2120,11 @@ public class CloudFormationService implements ResourceProvider { } for (String logicalId : sortedLogicalIds) { + if (isCreate && deferredDeletes.containsKey(stack.getStackId())) { + LOG.infov("Stack {0} is being deleted, so its create stops before {1}", + stack.getStackName(), logicalId); + return; + } if (!isCreate && !changedResourceIds.contains(logicalId)) { continue; } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDeleteDuringCreateIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDeleteDuringCreateIntegrationTest.java new file mode 100644 index 0000000000..09a3ac318e --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDeleteDuringCreateIntegrationTest.java @@ -0,0 +1,229 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.XmlParser; +import io.github.hectorvent.floci.services.lambda.LambdaService; +import io.github.hectorvent.floci.services.lambda.model.InvocationType; +import io.github.hectorvent.floci.services.lambda.model.InvokeResult; +import io.github.hectorvent.floci.testing.CfnStackWaits; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.InjectMock; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +/** + * DeleteStack on a stack whose create is still provisioning deletes the stack once the create has + * stopped: no resource is created after the delete, and nothing the create built survives it. + * + *

The custom resource's ServiceToken Lambda is mocked and holds its Create request until the + * test releases it, so the delete arrives while that resource is being created. + */ +@QuarkusTest +class CloudFormationDeleteDuringCreateIntegrationTest { + + private static final String SERVICE_TOKEN = + "arn:aws:lambda:us-east-1:000000000000:function:delete-during-create"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private final List requests = new CopyOnWriteArrayList<>(); + private final CountDownLatch createReceived = new CountDownLatch(1); + private final CountDownLatch releaseCreate = new CountDownLatch(1); + private final CountDownLatch deleteReceived = new CountDownLatch(1); + + @InjectMock + LambdaService lambdaService; + + @Inject + CloudFormationService cloudFormationService; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @BeforeEach + void stubHandler() { + when(lambdaService.invoke(any(), eq(SERVICE_TOKEN), any(), eq(InvocationType.RequestResponse))) + .thenAnswer(invocation -> { + JsonNode event = MAPPER.readTree((byte[]) invocation.getArgument(2)); + String requestType = event.get("RequestType").asText(); + requests.add(requestType); + if ("Create".equals(requestType)) { + createReceived.countDown(); + assertTrue(releaseCreate.await(10, TimeUnit.SECONDS), "the test never released the Create"); + } else if ("Delete".equals(requestType)) { + deleteReceived.countDown(); + } + respond(event); + return new InvokeResult(200, null, "null".getBytes(StandardCharsets.UTF_8), null, "req-1"); + }); + } + + @AfterEach + void releaseHeldCreate() { + releaseCreate.countDown(); + } + + @Test + void deleteDuringCreateRemovesWhatTheCreateBuiltAndCreatesNothingAfterIt() throws Exception { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "delete-during-create-" + suffix; + String topicName = "after-probe-" + suffix; + String exportName = "delete-during-create-export-" + suffix; + cfn(Map.of("Action", "CreateChangeSet", "StackName", stackName, "ChangeSetName", "create", + "ChangeSetType", "CREATE", "TemplateBody", template(topicName, exportName))); + String stackId = stackId(stackName); + cfn(Map.of("Action", "ExecuteChangeSet", "StackName", stackName, "ChangeSetName", "create")); + assertTrue(createReceived.await(10, TimeUnit.SECONDS), "the custom resource was never created"); + + cfn(Map.of("Action", "DeleteStack", "StackName", stackName)); + releaseCreate.countDown(); + + assertTrue(deleteReceived.await(10, TimeUnit.SECONDS), + "the custom resource the create built was never deleted: " + requests); + CfnStackWaits.awaitStatus(stackId, "DELETE_COMPLETE"); + assertEquals(List.of("Create", "Delete"), requests); + assertFalse(topicExists(topicName), "the resource after the custom resource was created"); + assertFalse(cfn(Map.of("Action", "ListExports")).contains(exportName), "the export was registered"); + + String otherStack = "delete-during-create-other-" + suffix; + cfn(Map.of("Action", "CreateStack", "StackName", otherStack, + "TemplateBody", exportingTemplate(exportName))); + try { + CfnStackWaits.awaitStatus(stackId(otherStack), "CREATE_COMPLETE"); + } finally { + cfn(Map.of("Action", "DeleteStack", "StackName", otherStack)); + } + assertTrue(cfn(Map.of("Action", "DescribeStacks", "StackName", stackId)) + .contains("DELETE_COMPLETE")); + } + + @Test + void deleteDuringCreateThatFailsFailsTheDeleteItsCallerAwaits() throws Exception { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "delete-during-create-failing-" + suffix; + String bucketName = "delete-during-create-" + suffix; + cfn(Map.of("Action", "CreateChangeSet", "StackName", stackName, "ChangeSetName", "create", + "ChangeSetType", "CREATE", "TemplateBody", bucketTemplate(bucketName))); + String stackId = stackId(stackName); + cfn(Map.of("Action", "ExecuteChangeSet", "StackName", stackName, "ChangeSetName", "create")); + assertTrue(createReceived.await(10, TimeUnit.SECONDS), "the custom resource was never created"); + given().body("keeps the bucket").when().put("/" + bucketName + "/object.txt").then().statusCode(200); + + Future delete = cloudFormationService.deleteStack(stackName, "us-east-1", "000000000000"); + releaseCreate.countDown(); + + try { + assertThrows(ExecutionException.class, () -> delete.get(10, TimeUnit.SECONDS)); + CfnStackWaits.awaitStatus(stackId, "DELETE_FAILED"); + } finally { + given().when().delete("/" + bucketName + "/object.txt"); + cfn(Map.of("Action", "DeleteStack", "StackName", stackName)); + } + } + + private static String bucketTemplate(String bucketName) { + return """ + { + "Resources": { + "Bucket": { + "Type": "AWS::S3::Bucket", + "Properties": {"BucketName": "%s"} + }, + "Probe": { + "Type": "Custom::DeleteDuringCreate", + "DependsOn": "Bucket", + "Properties": {"ServiceToken": "%s"} + } + } + } + """.formatted(bucketName, SERVICE_TOKEN); + } + + private static String template(String topicName, String exportName) { + return """ + { + "Resources": { + "Probe": { + "Type": "Custom::DeleteDuringCreate", + "Properties": {"ServiceToken": "%s"} + }, + "Topic": { + "Type": "AWS::SNS::Topic", + "DependsOn": "Probe", + "Properties": {"TopicName": "%s"} + } + }, + "Outputs": { + "TopicArn": {"Value": {"Ref": "Topic"}, "Export": {"Name": "%s"}} + } + } + """.formatted(SERVICE_TOKEN, topicName, exportName); + } + + private static String exportingTemplate(String exportName) { + return """ + { + "Resources": {"Topic": {"Type": "AWS::SNS::Topic"}}, + "Outputs": { + "TopicArn": {"Value": {"Ref": "Topic"}, "Export": {"Name": "%s"}} + } + } + """.formatted(exportName); + } + + private static void respond(JsonNode event) { + ObjectNode response = MAPPER.createObjectNode() + .put("Status", "SUCCESS") + .put("RequestId", event.get("RequestId").asText()) + .put("StackId", event.get("StackId").asText()) + .put("LogicalResourceId", event.get("LogicalResourceId").asText()) + .put("PhysicalResourceId", "delete-during-create-probe"); + given().body(response.toString()).when().put(URI.create(event.get("ResponseURL").asText()).getPath()) + .then().statusCode(200); + } + + private static boolean topicExists(String topicName) { + return cfn(Map.of("Action", "ListTopics")).contains(":" + topicName + ""); + } + + private static String stackId(String stackName) { + return XmlParser.extractFirst(cfn(Map.of("Action", "DescribeStacks", "StackName", stackName)), "StackId", null); + } + + private static String cfn(Map params) { + return given() + .contentType("application/x-www-form-urlencoded") + .formParams(params) + .when() + .post("/") + .then() + .statusCode(200) + .extract().asString(); + } +}