Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(cloudformation): idempotent ECS resource deletion on stack delete (#1645)

Hector Ventura04e0f2dddb09
diff --git a/src/main/java/io/github/hectorvent/floci/core/storage/PersistentStorage.java b/src/main/java/io/github/hectorvent/floci/core/storage/PersistentStorage.java
index 93db67465d..015751639a 100644
--- a/src/main/java/io/github/hectorvent/floci/core/storage/PersistentStorage.java
+++ b/src/main/java/io/github/hectorvent/floci/core/storage/PersistentStorage.java
@@ -91,7 +91,25 @@ public class PersistentStorage<K, V> implements StorageBackend<K, V> {
store.putAll(data);
LOG.infov("Loaded {0} entries from {1}", store.size(), filePath);
} catch (IOException e) {
- LOG.errorv(e, "Failed to load data from {0}", filePath);
+ // Starting empty here silently drops all persisted state for this store, which can leave
+ // other services (e.g. CloudFormation) referencing resources that now appear missing
+ // (see issue #1634). Quarantine the unreadable file and log loudly so the data loss is
+ // detectable rather than masquerading as an empty store.
+ quarantineUnreadableFile(e);
+ }
+ }
+
+ private void quarantineUnreadableFile(IOException cause) {
+ Path quarantine = filePath.resolveSibling(filePath.getFileName() + ".corrupt");
+ try {
+ Files.move(filePath, quarantine, StandardCopyOption.REPLACE_EXISTING);
+ LOG.errorv(cause, "Failed to load persisted data from {0}; moved the unreadable file to "
+ + "{1} and started with an empty store. This store's state was lost.",
+ filePath, quarantine);
+ } catch (IOException moveError) {
+ LOG.errorv(cause, "Failed to load persisted data from {0}; could not quarantine it ({1}). "
+ + "Starting with an empty store. This store's state was lost.",
+ filePath, moveError.getMessage());
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
index edfb888357..80c499bb09 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
@@ -425,8 +425,8 @@ public class CloudFormationResourceProvisioner {
case "AWS::Lambda::LayerVersion" -> deleteLambdaLayerVersion(physicalId, region);
case "AWS::Cognito::UserPool" -> cognitoService.deleteUserPool(physicalId);
case "AWS::Cognito::UserPoolClient" -> cognitoService.deleteUserPoolClient(physicalId);
- case "AWS::ECS::Cluster" -> ecsService.deleteCluster(physicalId, region);
- case "AWS::ECS::TaskDefinition" -> ecsService.deregisterTaskDefinition(physicalId, region);
+ case "AWS::ECS::Cluster" -> deleteEcsClusterSafe(physicalId, region);
+ case "AWS::ECS::TaskDefinition" -> deleteEcsTaskDefinitionSafe(physicalId, region);
case "AWS::ECS::Service" -> deleteEcsServiceSafe(physicalId, region);
case "AWS::ElasticLoadBalancingV2::LoadBalancer" -> elbV2Service.deleteLoadBalancer(region, physicalId);
case "AWS::ElasticLoadBalancingV2::TargetGroup" -> elbV2Service.deleteTargetGroup(region, physicalId);
@@ -3233,7 +3233,47 @@ public class CloudFormationResourceProvisioner {
} catch (IllegalArgumentException e) {
// Not an ARN; treat the value as a bare service name.
}
- ecsService.deleteService(clusterRef, serviceName, true, region);
+ try {
+ ecsService.deleteService(clusterRef, serviceName, true, region);
+ } catch (AwsException e) {
+ // Idempotent delete: only an already-gone service (e.g. after a persistent restore that
+ // dropped ECS state) is treated as delete-complete. Any other error must still fail the
+ // stack delete rather than being silently swallowed. See issue #1634.
+ if (!"ServiceNotFoundException".equals(e.getErrorCode())) {
+ throw e;
+ }
+ LOG.debugv("ECS service {0} already gone, treating delete as complete: {1}",
+ serviceArn, e.getMessage());
+ }
+ }
+
+ private void deleteEcsTaskDefinitionSafe(String physicalId, String region) {
+ try {
+ ecsService.deregisterTaskDefinition(physicalId, region);
+ } catch (AwsException e) {
+ // Idempotent delete: only an already-missing task definition (ClientException "Unable to
+ // describe task definition", e.g. after a persistent restore) is delete-complete. Other
+ // errors must still fail the stack delete. See #1634.
+ if (!"ClientException".equals(e.getErrorCode())) {
+ throw e;
+ }
+ LOG.debugv("ECS task definition {0} already gone, treating delete as complete: {1}",
+ physicalId, e.getMessage());
+ }
+ }
+
+ private void deleteEcsClusterSafe(String physicalId, String region) {
+ try {
+ ecsService.deleteCluster(physicalId, region);
+ } catch (AwsException e) {
+ // Idempotent delete: only an already-missing cluster is delete-complete. A genuine
+ // failure such as ClusterContainsTasksException must still fail the stack delete. See #1634.
+ if (!"ClusterNotFoundException".equals(e.getErrorCode())) {
+ throw e;
+ }
+ LOG.debugv("ECS cluster {0} already gone, treating delete as complete: {1}",
+ physicalId, e.getMessage());
+ }
}
private List<ContainerDefinition> parseContainerDefinitions(JsonNode node, CloudFormationTemplateEngine engine) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/LaunchType.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/LaunchType.java
index 162ae547ab..f6a78b80fb 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/LaunchType.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/LaunchType.java
@@ -1,5 +1,8 @@
package io.github.hectorvent.floci.services.ecs.model;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+@RegisterForReflection
public enum LaunchType {
EC2, FARGATE, EXTERNAL
}
\ No newline at end of file
diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/NetworkMode.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/NetworkMode.java
index a29493b715..d83e2d28e7 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/NetworkMode.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/NetworkMode.java
@@ -1,5 +1,8 @@
package io.github.hectorvent.floci.services.ecs.model;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+@RegisterForReflection
public enum NetworkMode {
bridge, host, awsvpc, none
}
\ No newline at end of file
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEcsDeleteAfterRestoreIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEcsDeleteAfterRestoreIntegrationTest.java
new file mode 100644
index 0000000000..5f56a8a193
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEcsDeleteAfterRestoreIntegrationTest.java
@@ -0,0 +1,160 @@
+package io.github.hectorvent.floci.services.cloudformation;
+
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.not;
+
+/**
+ * Regression tests for #1634. Deleting a CloudFormation stack that tracks ECS resources must reach
+ * {@code DELETE_COMPLETE} when ECS no longer has those resources (e.g. after a persistent restore
+ * dropped the records while the stack still referenced their ARNs). The idempotent delete only
+ * swallows the specific "already gone" error, so a genuine failure such as
+ * {@code ClusterContainsTasksException} must still settle the stack into {@code DELETE_FAILED}.
+ */
+@QuarkusTest
+class CloudFormationEcsDeleteAfterRestoreIntegrationTest {
+
+ private static final String ECS_TARGET = "AmazonEC2ContainerServiceV20141113.";
+ private static final String ECS_CONTENT_TYPE = "application/x-amz-json-1.1";
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @Test
+ void deleteStack_withMissingEcsTaskDefinition_reachesDeleteComplete() throws Exception {
+ String stack = "cfn-1634-missing-td";
+ String cluster = "cfn-1634-missing-td-cluster";
+ String family = "cfn-1634-missing-td-family";
+
+ String stackArn = createStack(stack, ecsTemplate(cluster, family));
+ awaitStackStatus(stackArn, "CREATE_COMPLETE");
+
+ // Simulate a persistent restore that dropped the ECS task definition: deregister then delete
+ // it through the ECS API so ECS no longer has the record the stack still references. These
+ // run unauthenticated, like CreateStack/DeleteStack, so they share the same account namespace.
+ ecs("DeregisterTaskDefinition", "{\"taskDefinition\":\"" + family + "\"}");
+ ecs("DeleteTaskDefinitions", "{\"taskDefinitions\":[\"" + family + "\"]}");
+
+ deleteStack(stack);
+
+ String statusXml = awaitStackSettled(stackArn);
+ assertThat(statusXml, containsString("<StackStatus>DELETE_COMPLETE</StackStatus>"));
+ assertThat(statusXml, not(containsString("<StackStatus>DELETE_FAILED</StackStatus>")));
+ }
+
+ @Test
+ void deleteStack_withClusterStillRunningTasks_failsAndDoesNotSwallow() throws Exception {
+ String stack = "cfn-1634-running-tasks";
+ String cluster = "cfn-1634-running-tasks-cluster";
+ String family = "cfn-1634-running-tasks-family";
+
+ String stackArn = createStack(stack, ecsTemplate(cluster, family));
+ awaitStackStatus(stackArn, "CREATE_COMPLETE");
+
+ // The cluster still has a running task at delete time (a genuine ClusterContainsTasksException),
+ // which must NOT be treated as already-gone. ECS runs in mock mode under test, so the task is
+ // in-memory RUNNING with no container behind it.
+ ecs("RunTask", "{\"cluster\":\"" + cluster + "\",\"taskDefinition\":\"" + family + "\",\"count\":1}");
+
+ deleteStack(stack);
+
+ String statusXml = awaitStackSettled(stackArn);
+ assertThat(statusXml, containsString("<StackStatus>DELETE_FAILED</StackStatus>"));
+ assertThat(statusXml, not(containsString("<StackStatus>DELETE_COMPLETE</StackStatus>")));
+ }
+
+ private static String ecsTemplate(String clusterName, String family) {
+ return """
+ {
+ "Resources": {
+ "EcsCluster": {
+ "Type": "AWS::ECS::Cluster",
+ "Properties": { "ClusterName": "%s" }
+ },
+ "TaskDef": {
+ "Type": "AWS::ECS::TaskDefinition",
+ "Properties": {
+ "Family": "%s",
+ "NetworkMode": "awsvpc",
+ "ContainerDefinitions": [
+ { "Name": "web", "Image": "nginx:latest", "Essential": true }
+ ]
+ }
+ }
+ }
+ }
+ """.formatted(clusterName, family);
+ }
+
+ private String createStack(String stackName, String template) {
+ String xml = given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", template)
+ .when().post("/")
+ .then().statusCode(200).body(containsString("<StackId>"))
+ .extract().asString();
+ return xml.substring(xml.indexOf("<StackId>") + "<StackId>".length(), xml.indexOf("</StackId>"));
+ }
+
+ private void deleteStack(String stackName) {
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DeleteStack")
+ .formParam("StackName", stackName)
+ .when().post("/")
+ .then().statusCode(200);
+ }
+
+ private void ecs(String action, String body) {
+ given()
+ .contentType(ECS_CONTENT_TYPE)
+ .header("X-Amz-Target", ECS_TARGET + action)
+ .body(body)
+ .when().post("/")
+ .then().statusCode(200);
+ }
+
+ private void awaitStackStatus(String stackArn, String status) throws Exception {
+ long deadline = System.currentTimeMillis() + 10_000;
+ while (System.currentTimeMillis() < deadline) {
+ if (describeStacks(stackArn).contains("<StackStatus>" + status + "</StackStatus>")) {
+ return;
+ }
+ Thread.sleep(200);
+ }
+ throw new AssertionError("Stack did not reach " + status + ": " + describeStacks(stackArn));
+ }
+
+ private String awaitStackSettled(String stackArn) throws Exception {
+ long deadline = System.currentTimeMillis() + 10_000;
+ while (System.currentTimeMillis() < deadline) {
+ String xml = describeStacks(stackArn);
+ if (xml.contains("<StackStatus>DELETE_COMPLETE</StackStatus>")
+ || xml.contains("<StackStatus>DELETE_FAILED</StackStatus>")) {
+ return xml;
+ }
+ Thread.sleep(200);
+ }
+ throw new AssertionError("Stack did not settle into DELETE_COMPLETE/DELETE_FAILED: "
+ + describeStacks(stackArn));
+ }
+
+ private String describeStacks(String stackArn) {
+ return given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStacks")
+ .formParam("StackName", stackArn)
+ .when().post("/")
+ .then().statusCode(200).extract().asString();
+ }
+}