mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(cloudformation): delete UPDATE_FAILED resources on DeleteStack (#4470)
* fix(cloudformation): delete UPDATE_FAILED resources on DeleteStack A failed update whose rollback cannot restore a resource leaves it UPDATE_FAILED with its physical id and the stack in UPDATE_ROLLBACK_FAILED. DeleteStack only walked CREATE_COMPLETE, UPDATE_COMPLETE and DELETE_FAILED resources, plus UPDATE_FAILED ones whose provisioner opted in, so every other failed resource was skipped without an event and the stack still reached DELETE_COMPLETE, leaving the role, log group or bucket behind. Delete every UPDATE_FAILED resource that has a physical id. Delete a CREATE_FAILED resource only when the provisioner marked its entity as created by the stack, as the create rollback does, since a failed create can name an entity that existed before. Closes #4467 * test(cloudformation): clean up the outside log group when the test fails * docs(cloudformation): list the resource statuses DeleteStack deletes * fix(cloudformation): mark a failed nested stack the operation created as stack-owned A nested stack whose child fails during creation came back CREATE_FAILED with the child's stack id but no ownership marker, so neither the create rollback nor DeleteStack deleted the child stack. * test(cloudformation): clean up the stack, role and log group when the test fails * docs(cloudformation): update the hasPendingRollbackCleanup javadoc now that DeleteStack no longer calls it
This commit is contained in:
1 parent
64375691ac
commit
60d112542d
10 files changed
+490
-23
No files matched your search
+197
@@ -0,0 +1,197 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
|
||||
import software.amazon.awssdk.services.cloudformation.model.Capability;
|
||||
import software.amazon.awssdk.services.cloudformation.model.CloudFormationException;
|
||||
import software.amazon.awssdk.services.cloudformation.model.Stack;
|
||||
import software.amazon.awssdk.services.cloudformation.model.StackEvent;
|
||||
import software.amazon.awssdk.services.cloudformation.model.StackResource;
|
||||
import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient;
|
||||
import software.amazon.awssdk.services.cloudwatchlogs.model.LogGroup;
|
||||
import software.amazon.awssdk.services.cloudwatchlogs.model.ResourceNotFoundException;
|
||||
import software.amazon.awssdk.services.iam.IamClient;
|
||||
import software.amazon.awssdk.services.iam.model.NoSuchEntityException;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
@DisplayName("CloudFormation DeleteStack after UPDATE_ROLLBACK_FAILED")
|
||||
class CloudFormationDeleteAfterFailedRollbackTest {
|
||||
|
||||
private static CloudFormationClient cfn;
|
||||
private static IamClient iam;
|
||||
private static CloudWatchLogsClient logs;
|
||||
private String stackName;
|
||||
private String roleName;
|
||||
private String logGroup;
|
||||
private String outsideGroup;
|
||||
|
||||
@BeforeAll
|
||||
static void clients() {
|
||||
cfn = TestFixtures.cloudFormationClient();
|
||||
iam = TestFixtures.iamClient();
|
||||
logs = TestFixtures.cloudWatchLogsClient();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
stackName = TestFixtures.uniqueName("compat-cfn-delete-rollback-failed");
|
||||
roleName = stackName + "-role";
|
||||
logGroup = "/test/" + stackName + "/lg";
|
||||
outsideGroup = "/test/" + stackName + "/outside";
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanup() {
|
||||
try {
|
||||
cfn.deleteStack(r -> r.stackName(stackName));
|
||||
} catch (CloudFormationException ignored) {
|
||||
// The test deletes the stack itself; this only covers an assertion failing first.
|
||||
}
|
||||
try {
|
||||
iam.deleteRole(r -> r.roleName(roleName));
|
||||
} catch (NoSuchEntityException ignored) {
|
||||
// Deleted by DeleteStack, which is what the test asserts.
|
||||
}
|
||||
for (String group : List.of(logGroup, outsideGroup)) {
|
||||
try {
|
||||
logs.deleteLogGroup(r -> r.logGroupName(group));
|
||||
} catch (ResourceNotFoundException ignored) {
|
||||
// Deleted by DeleteStack, which is what the test asserts.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void closeClients() {
|
||||
cfn.close();
|
||||
iam.close();
|
||||
logs.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("deletes resources a failed update rollback left UPDATE_FAILED")
|
||||
void deletesUpdateFailedResources() throws InterruptedException {
|
||||
logs.createLogGroup(r -> r.logGroupName(outsideGroup));
|
||||
|
||||
String stackId = cfn.createStack(r -> r.stackName(stackName)
|
||||
.templateBody(template(false))
|
||||
.capabilities(Capability.CAPABILITY_NAMED_IAM)).stackId();
|
||||
assertThat(awaitStable()).isEqualTo("CREATE_COMPLETE");
|
||||
|
||||
cfn.updateStack(r -> r.stackName(stackName)
|
||||
.templateBody(template(true))
|
||||
.capabilities(Capability.CAPABILITY_NAMED_IAM));
|
||||
assertThat(awaitStable()).isEqualTo("UPDATE_ROLLBACK_FAILED");
|
||||
assertThat(cfn.describeStackResources(r -> r.stackName(stackName)).stackResources())
|
||||
.filteredOn(resource -> List.of("Role", "LogGroup").contains(resource.logicalResourceId()))
|
||||
.extracting(StackResource::resourceStatusAsString)
|
||||
.as("precondition: the rollback could not restore the role or the log group")
|
||||
.containsExactlyInAnyOrder("UPDATE_FAILED", "UPDATE_FAILED");
|
||||
|
||||
cfn.deleteStack(r -> r.stackName(stackName));
|
||||
awaitDeleted();
|
||||
|
||||
assertThatThrownBy(() -> iam.getRole(r -> r.roleName(roleName)))
|
||||
.isInstanceOf(NoSuchEntityException.class);
|
||||
assertThat(logGroupNames(logGroup)).isEmpty();
|
||||
assertThat(logGroupNames(outsideGroup))
|
||||
.as("the group the update collided with was never the stack's")
|
||||
.containsExactly(outsideGroup);
|
||||
|
||||
List<StackEvent> events = cfn.describeStackEventsPaginator(r -> r.stackName(stackId))
|
||||
.stackEvents().stream().toList();
|
||||
assertThat(events)
|
||||
.filteredOn(event -> "DELETE_COMPLETE".equals(event.resourceStatusAsString()))
|
||||
.extracting(StackEvent::logicalResourceId)
|
||||
.contains("Role", "LogGroup");
|
||||
}
|
||||
|
||||
private List<String> logGroupNames(String prefix) {
|
||||
return logs.describeLogGroupsPaginator(r -> r.logGroupNamePrefix(prefix)).logGroups().stream()
|
||||
.map(LogGroup::logGroupName).toList();
|
||||
}
|
||||
|
||||
/** The role and log group; the update changes both and adds a group that collides with outsideGroup. */
|
||||
private String template(boolean failingUpdate) {
|
||||
String roleExtra = failingUpdate ? ", \"Description\": \"updated\"" : "";
|
||||
String groupExtra = failingUpdate ? ", \"RetentionInDays\": 7" : "";
|
||||
String dup = failingUpdate ? """
|
||||
,
|
||||
"Dup": {
|
||||
"Type": "AWS::Logs::LogGroup",
|
||||
"DependsOn": ["Role", "LogGroup"],
|
||||
"Properties": {"LogGroupName": "%s"}
|
||||
}""".formatted(outsideGroup) : "";
|
||||
return """
|
||||
{
|
||||
"Resources": {
|
||||
"Role": {
|
||||
"Type": "AWS::IAM::Role",
|
||||
"Properties": {
|
||||
"RoleName": "%s",
|
||||
"AssumeRolePolicyDocument": {
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [{
|
||||
"Effect": "Allow",
|
||||
"Principal": {"Service": "lambda.amazonaws.com"},
|
||||
"Action": "sts:AssumeRole"
|
||||
}]
|
||||
}%s
|
||||
}
|
||||
},
|
||||
"LogGroup": {
|
||||
"Type": "AWS::Logs::LogGroup",
|
||||
"Properties": {"LogGroupName": "%s"%s}
|
||||
}%s
|
||||
}
|
||||
}
|
||||
""".formatted(roleName, roleExtra, logGroup, groupExtra, dup);
|
||||
}
|
||||
|
||||
private String awaitStable() throws InterruptedException {
|
||||
return await(() -> {
|
||||
Stack stack = cfn.describeStacks(r -> r.stackName(stackName)).stacks().get(0);
|
||||
String status = stack.stackStatusAsString();
|
||||
return status.endsWith("_IN_PROGRESS") ? null : status;
|
||||
}, "a stable status");
|
||||
}
|
||||
|
||||
private void awaitDeleted() throws InterruptedException {
|
||||
String status = await(() -> {
|
||||
try {
|
||||
List<Stack> stacks = cfn.describeStacks(r -> r.stackName(stackName)).stacks();
|
||||
String current = stacks.isEmpty() ? "DELETE_COMPLETE" : stacks.get(0).stackStatusAsString();
|
||||
return current.endsWith("_IN_PROGRESS") ? null : current;
|
||||
} catch (CloudFormationException e) {
|
||||
if ("ValidationError".equals(e.awsErrorDetails().errorCode())
|
||||
&& e.getMessage().contains("does not exist")) {
|
||||
return "DELETE_COMPLETE";
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}, "stack deletion");
|
||||
assertThat(status).isEqualTo("DELETE_COMPLETE");
|
||||
}
|
||||
|
||||
private String await(Supplier<String> status, String expected) throws InterruptedException {
|
||||
long deadline = System.nanoTime() + 60_000_000_000L;
|
||||
while (System.nanoTime() < deadline) {
|
||||
String current = status.get();
|
||||
if (current != null) {
|
||||
return current;
|
||||
}
|
||||
Thread.sleep(100);
|
||||
}
|
||||
throw new AssertionError(stackName + " timed out waiting for " + expected);
|
||||
}
|
||||
}
|
||||
@@ -417,6 +417,20 @@ A kept resource is reported as `DELETE_SKIPPED` in `DescribeStackEvents` and doe
|
||||
deletion — the stack still reaches `DELETE_COMPLETE` while the resource keeps existing. This also
|
||||
lets a stack owning a non-empty S3 bucket be deleted, since the bucket is never touched.
|
||||
|
||||
Otherwise `DeleteStack` deletes each resource that has a physical id and is in one of these
|
||||
statuses:
|
||||
|
||||
- `CREATE_COMPLETE`, `UPDATE_COMPLETE`
|
||||
- `UPDATE_FAILED`, which a failed update rollback leaves on the resources it could not restore, so
|
||||
deleting a stack in `UPDATE_ROLLBACK_FAILED` removes them
|
||||
- `DELETE_FAILED`, which a retried `DeleteStack` attempts again
|
||||
- `CREATE_FAILED`, only when the stack created the backing entity, since a failed create can name
|
||||
an entity that existed before and belongs to someone else
|
||||
|
||||
Resources in any other status (`DELETE_COMPLETE`, `DELETE_SKIPPED`, an in-progress status) and
|
||||
resources without a physical id are skipped. A resource that cannot be deleted leaves the stack in
|
||||
`DELETE_FAILED`, named in the status reason.
|
||||
|
||||
Deviations from AWS to be aware of:
|
||||
|
||||
- `Snapshot` deletes the resource without taking a snapshot; floci has no snapshot support for the
|
||||
|
||||
+26
-11
@@ -2033,7 +2033,7 @@ public class CloudFormationService implements ResourceProvider {
|
||||
return ordered;
|
||||
}
|
||||
|
||||
private void deleteStackResources(Stack stack, String region, String accountId) {
|
||||
void deleteStackResources(Stack stack, String region, String accountId) {
|
||||
try {
|
||||
List<StackResource> resources = resourcesInCreationOrder(stack, region);
|
||||
Collections.reverse(resources); // Dependents go before what they depend on
|
||||
@@ -2047,16 +2047,7 @@ public class CloudFormationService implements ResourceProvider {
|
||||
failedResources.add(displacedFailure.logicalId());
|
||||
}
|
||||
for (StackResource resource : resources) {
|
||||
// CREATE_COMPLETE/UPDATE_COMPLETE: first delete attempt. DELETE_FAILED: a previous
|
||||
// delete left the resource behind (e.g. the bucket was non-empty); AWS re-attempts
|
||||
// it on retry. Failed updates are included only when their provisioner still
|
||||
// tracks an ownership-aware cleanup obligation.
|
||||
boolean deletable = "CREATE_COMPLETE".equals(resource.getStatus())
|
||||
|| "UPDATE_COMPLETE".equals(resource.getStatus())
|
||||
|| "DELETE_FAILED".equals(resource.getStatus())
|
||||
|| ("UPDATE_FAILED".equals(resource.getStatus())
|
||||
&& dispatcher.hasPendingRollbackCleanup(resource));
|
||||
if (resource.getPhysicalId() == null || !deletable) {
|
||||
if (resource.getPhysicalId() == null || !isDeletableOnStackDelete(resource)) {
|
||||
continue;
|
||||
}
|
||||
if (skipRetainedResource(stack, resource, false)) {
|
||||
@@ -2130,6 +2121,25 @@ public class CloudFormationService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether {@code DeleteStack} owes a delete to a resource that has a physical id. AWS deletes
|
||||
* everything the stack manages, whatever status the last operation left it in.
|
||||
*
|
||||
* <p>{@code UPDATE_FAILED} is what a failed update rollback leaves on a resource it could not
|
||||
* restore; its physical id names the committed entity, or an entity a cancelled create made
|
||||
* and the rollback already tried to delete. {@code DELETE_FAILED} is a delete to retry.
|
||||
* {@code CREATE_FAILED} is deleted only when the provisioner marked the entity as created by
|
||||
* this stack, as the create rollback does: a failed create can carry the physical id of an
|
||||
* entity that already existed, which the stack must not delete.
|
||||
*/
|
||||
private static boolean isDeletableOnStackDelete(StackResource resource) {
|
||||
return switch (resource.getStatus() == null ? "" : resource.getStatus()) {
|
||||
case "CREATE_COMPLETE", "UPDATE_COMPLETE", "UPDATE_FAILED", "DELETE_FAILED" -> true;
|
||||
case "CREATE_FAILED" -> "true".equals(resource.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR));
|
||||
default -> false;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a resource's {@code DeletionPolicy}. {@code Retain} keeps the resource on every stack
|
||||
* operation; {@code RetainExceptOnCreate} keeps it too, except when the create that made it is
|
||||
@@ -2525,6 +2535,11 @@ public class CloudFormationService implements ResourceProvider {
|
||||
resource.setStatus("CREATE_COMPLETE");
|
||||
} else {
|
||||
resource.setStatus("CREATE_FAILED");
|
||||
if (childCreate) {
|
||||
// This operation created the child, so rolling back or deleting the parent owes it
|
||||
// a delete; a child an update only re-applied stays tracked by the prior resource.
|
||||
resource.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true");
|
||||
}
|
||||
String reason = childStack.getStatusReason();
|
||||
if (reason == null || reason.isBlank()) {
|
||||
reason = "Nested stack " + childStackName + " rolled back or failed with status " + childStack.getStatus();
|
||||
|
||||
+1
-1
@@ -218,7 +218,7 @@ public class CfnResourceDispatcher {
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/** Only an opted-in provisioner may identify cleanup owed by an UPDATE_FAILED resource. */
|
||||
/** Whether an opted-in provisioner still tracks cleanup owed by an UPDATE_FAILED resource. */
|
||||
public boolean hasPendingRollbackCleanup(StackResource resource) {
|
||||
return registry.forType(resource.getResourceType())
|
||||
.map(owner -> owner.hasPendingRollbackCleanup(resource))
|
||||
|
||||
+3
-2
@@ -52,8 +52,9 @@ public interface CfnResourceProvisioner {
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a failed update still needs this provisioner's ownership-aware delete. Opt-in:
|
||||
* a failed resource is not otherwise assumed to own a backing entity.
|
||||
* Whether a failed update still tracks cleanup that this provisioner's ownership-aware delete
|
||||
* owes. The engine no longer consults it: {@code DeleteStack} deletes every
|
||||
* {@code UPDATE_FAILED} resource that has a physical id.
|
||||
*/
|
||||
default boolean hasPendingRollbackCleanup(StackResource resource) {
|
||||
return false;
|
||||
|
||||
+2
-4
@@ -11,7 +11,6 @@ import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
@@ -306,9 +305,8 @@ class CloudFormationCloudWatchDashboardIntegrationTest {
|
||||
|
||||
cloudFormation(stack, "DeleteStack", null, Map.of());
|
||||
CfnStackWaits.awaitStackDeleted(stack);
|
||||
// A resource left UPDATE_FAILED by a failed rollback is not one DeleteStack removes, so the
|
||||
// dashboard outlives the stack and this test removes it itself.
|
||||
dashboardsService.deleteDashboards(List.of(name), "us-east-1");
|
||||
// A resource left UPDATE_FAILED by a failed rollback still belongs to the stack.
|
||||
getDashboard(name).then().statusCode(404);
|
||||
}
|
||||
|
||||
/** Dropping an explicit name is a replacement on AWS: the dashboard comes back under a generated name. */
|
||||
|
||||
+178
@@ -0,0 +1,178 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.XmlParser;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.RestAssured;
|
||||
import io.restassured.config.EncoderConfig;
|
||||
import io.restassured.http.ContentType;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* DeleteStack deletes every resource the stack manages, whatever status the last operation left it
|
||||
* in. A failed update whose rollback cannot restore a resource leaves it {@code UPDATE_FAILED} with
|
||||
* its physical id, and the stack in {@code UPDATE_ROLLBACK_FAILED}; deleting that stack must still
|
||||
* delete the resource rather than report {@code DELETE_COMPLETE} and leave it behind
|
||||
* (floci-io/floci#4467).
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CloudFormationDeleteAfterFailedRollbackIntegrationTest {
|
||||
|
||||
private static final String CFN_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260926/us-east-1/cloudformation/aws4_request";
|
||||
private static final String IAM_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260926/us-east-1/iam/aws4_request";
|
||||
private static final String LOGS_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260926/us-east-1/logs/aws4_request";
|
||||
|
||||
@Test
|
||||
void deleteStackAfterUpdateRollbackFailedDeletesUpdateFailedResources() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stackName = "delete-after-rollback-failed-" + suffix;
|
||||
String roleName = "delete-after-rollback-failed-role-" + suffix;
|
||||
String logGroup = "/delete-after-rollback-failed/" + suffix + "/lg";
|
||||
String outsideGroup = "/delete-after-rollback-failed/" + suffix + "/outside";
|
||||
|
||||
logs("CreateLogGroup", "{\"logGroupName\":\"" + outsideGroup + "\"}").then().statusCode(200);
|
||||
try {
|
||||
String stackId = XmlParser.extractFirst(
|
||||
cfn("CreateStack", stackName, template(roleName, logGroup, null)).then().statusCode(200)
|
||||
.extract().asString(),
|
||||
"StackId", null);
|
||||
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
|
||||
|
||||
// Role and LogGroup both change, then Dup collides with the group created outside the stack.
|
||||
// Neither type rolls an update back, so both are left UPDATE_FAILED with their physical ids.
|
||||
cfn("UpdateStack", stackName, template(roleName, logGroup, outsideGroup)).then().statusCode(200);
|
||||
assertEquals("UPDATE_ROLLBACK_FAILED", CfnStackWaits.awaitTerminal(stackName).status());
|
||||
Map<String, String> statuses = resourceStatuses(stackName);
|
||||
assertEquals("UPDATE_FAILED", statuses.get("Role"), statuses.toString());
|
||||
assertEquals("UPDATE_FAILED", statuses.get("LogGroup"), statuses.toString());
|
||||
|
||||
cfn("DeleteStack", stackName, null).then().statusCode(200);
|
||||
CfnStackWaits.awaitStackDeleted(stackName);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", "GetRole")
|
||||
.formParam("RoleName", roleName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body(containsString("<Code>NoSuchEntity</Code>"));
|
||||
logs("DescribeLogGroups", "{\"logGroupNamePrefix\":\"" + logGroup + "\"}").then()
|
||||
.statusCode(200)
|
||||
.body(not(containsString(logGroup)));
|
||||
// The group Dup collided with was never the stack's, so it survives.
|
||||
logs("DescribeLogGroups", "{\"logGroupNamePrefix\":\"" + outsideGroup + "\"}").then()
|
||||
.statusCode(200)
|
||||
.body(containsString(outsideGroup));
|
||||
|
||||
List<Map<String, String>> events = XmlParser.extractGroups(
|
||||
cfn("DescribeStackEvents", stackId, null).then().statusCode(200).extract().asString(),
|
||||
"member");
|
||||
assertDeleteComplete(events, "Role", roleName);
|
||||
assertDeleteComplete(events, "LogGroup", logGroup);
|
||||
} finally {
|
||||
// Best effort and unchecked, so a failed assertion above is not masked. The role and log
|
||||
// group are deleted directly because a regression would leave them behind DeleteStack.
|
||||
cfn("DeleteStack", stackName, null);
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", "DeleteRole")
|
||||
.formParam("RoleName", roleName)
|
||||
.when()
|
||||
.post("/");
|
||||
logs("DeleteLogGroup", "{\"logGroupName\":\"" + logGroup + "\"}");
|
||||
logs("DeleteLogGroup", "{\"logGroupName\":\"" + outsideGroup + "\"}");
|
||||
}
|
||||
}
|
||||
|
||||
private static void assertDeleteComplete(List<Map<String, String>> events, String logicalId,
|
||||
String physicalId) {
|
||||
boolean found = events.stream().anyMatch(event -> logicalId.equals(event.get("LogicalResourceId"))
|
||||
&& physicalId.equals(event.get("PhysicalResourceId"))
|
||||
&& "DELETE_COMPLETE".equals(event.get("ResourceStatus")));
|
||||
assertTrue(found, "no DELETE_COMPLETE event for " + logicalId + " (" + physicalId + ") in " + events);
|
||||
}
|
||||
|
||||
private static Map<String, String> resourceStatuses(String stackName) {
|
||||
String body = cfn("DescribeStackResources", stackName, null).then().statusCode(200).extract().asString();
|
||||
return XmlParser.extractPairs(body, "StackResources", "LogicalResourceId", "ResourceStatus");
|
||||
}
|
||||
|
||||
/** The role and log group, changed and joined by a colliding log group when outsideGroup is set. */
|
||||
private static String template(String roleName, String logGroup, String outsideGroup) {
|
||||
String roleExtra = outsideGroup == null ? "" : ", \"Description\": \"updated\"";
|
||||
String groupExtra = outsideGroup == null ? "" : ", \"RetentionInDays\": 7";
|
||||
String dup = outsideGroup == null ? "" : """
|
||||
,
|
||||
"Dup": {
|
||||
"Type": "AWS::Logs::LogGroup",
|
||||
"DependsOn": ["Role", "LogGroup"],
|
||||
"Properties": {"LogGroupName": "%s"}
|
||||
}""".formatted(outsideGroup);
|
||||
return """
|
||||
{
|
||||
"Resources": {
|
||||
"Role": {
|
||||
"Type": "AWS::IAM::Role",
|
||||
"Properties": {
|
||||
"RoleName": "%s",
|
||||
"AssumeRolePolicyDocument": {
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [{
|
||||
"Effect": "Allow",
|
||||
"Principal": {"Service": "lambda.amazonaws.com"},
|
||||
"Action": "sts:AssumeRole"
|
||||
}]
|
||||
}%s
|
||||
}
|
||||
},
|
||||
"LogGroup": {
|
||||
"Type": "AWS::Logs::LogGroup",
|
||||
"Properties": {"LogGroupName": "%s"%s}
|
||||
}%s
|
||||
}
|
||||
}
|
||||
""".formatted(roleName, roleExtra, logGroup, groupExtra, dup);
|
||||
}
|
||||
|
||||
private static Response cfn(String action, String stackName, String templateBody) {
|
||||
RequestSpecification request = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", action)
|
||||
.formParam("StackName", stackName);
|
||||
if (templateBody != null) {
|
||||
request.formParam("TemplateBody", templateBody)
|
||||
.formParam("Capabilities.member.1", "CAPABILITY_NAMED_IAM");
|
||||
}
|
||||
return request.when().post("/");
|
||||
}
|
||||
|
||||
private static Response logs(String target, String body) {
|
||||
return given()
|
||||
.config(RestAssured.config().encoderConfig(EncoderConfig.encoderConfig()
|
||||
.encodeContentTypeAs("application/x-amz-json-1.1", ContentType.TEXT)))
|
||||
.header("Authorization", LOGS_AUTH)
|
||||
.header("X-Amz-Target", "Logs_20140328." + target)
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.body(body)
|
||||
.when()
|
||||
.post("/");
|
||||
}
|
||||
}
|
||||
+2
@@ -745,6 +745,8 @@ class CloudFormationDeletionPolicyIntegrationTest {
|
||||
try {
|
||||
awaitStackStatus(parentStackId, "ROLLBACK_COMPLETE");
|
||||
assertBucketDeleted(bucketName);
|
||||
// The child this create made goes with the parent's rollback instead of outliving it.
|
||||
cfnQuery("DescribeStacks", stackName + "-ChildStack").then().statusCode(400);
|
||||
|
||||
// The parent must have stopped at the failed ChildStack resource and never reached
|
||||
// ConsumerParam: proof the child's failure was detected before its (never-computed)
|
||||
|
||||
+2
-3
@@ -507,9 +507,8 @@ class CloudFormationPipesCleanupIntegrationTest {
|
||||
|
||||
Mockito.doCallRealMethod().when(pipesService).tagResource(anyString(), anyString(), anyMap());
|
||||
deleteStack(stackName);
|
||||
// A resource left UPDATE_FAILED by a failed rollback is not one DeleteStack removes, so the
|
||||
// pipe outlives the stack and this test deletes it itself.
|
||||
pipesService.deletePipe(pipeName, "us-east-1");
|
||||
// A resource left UPDATE_FAILED by a failed rollback still belongs to the stack.
|
||||
assertPipeMissing(pipeName);
|
||||
}
|
||||
|
||||
/** The pipe alone, under a fixed name, so every update reconciles it in place. */
|
||||
|
||||
+65
-2
@@ -11,6 +11,8 @@ import io.github.hectorvent.floci.services.cloudformation.model.Stack;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnDynamicReferences;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnRollback;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.UpdateCleanupResult;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.ssm.SsmService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -22,14 +24,20 @@ import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Covers rollback cleanup when another actor removes a resource after its create succeeded.
|
||||
* Covers rollback cleanup when another actor removes a resource after its create succeeded, and
|
||||
* which resources a stack delete walks after a failed operation left them in a failed status.
|
||||
*/
|
||||
class CloudFormationServiceRollbackTest {
|
||||
|
||||
@@ -42,7 +50,7 @@ class CloudFormationServiceRollbackTest {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
provisioner = mock(CfnResourceDispatcher.class);
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.defaultAccountId()).thenReturn(ACCOUNT);
|
||||
|
||||
service = new CloudFormationService(
|
||||
@@ -108,6 +116,61 @@ class CloudFormationServiceRollbackTest {
|
||||
verify(provisioner).delete(created, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteStack_afterFailedUpdateRollback_deletesUpdateFailedResources() {
|
||||
Stack stack = new Stack();
|
||||
stack.setStackName("delete-after-update-rollback-failed");
|
||||
stack.setStackId("stack-id");
|
||||
stack.setRegion(REGION);
|
||||
stack.setStatus("UPDATE_ROLLBACK_FAILED");
|
||||
|
||||
StackResource role = resource("Role", "leak-probe-role", "AWS::IAM::Role", "UPDATE_FAILED");
|
||||
role.setStatusReason("Rollback is not implemented for AWS::IAM::Role");
|
||||
StackResource logGroup = resource("LogGroup", "/leak-probe/lg", "AWS::Logs::LogGroup", "UPDATE_FAILED");
|
||||
StackResource alreadyDeleted = resource("Gone", "gone-id", "AWS::SQS::Queue", "DELETE_COMPLETE");
|
||||
StackResource adopted = resource("Adopted", "/outside/existing", "AWS::Logs::LogGroup", "CREATE_FAILED");
|
||||
StackResource owned = resource("Owned", "owned-id", "AWS::IAM::User", "CREATE_FAILED");
|
||||
owned.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true");
|
||||
for (StackResource resource : new StackResource[] {role, logGroup, alreadyDeleted, adopted, owned}) {
|
||||
stack.getResources().put(resource.getLogicalId(), resource);
|
||||
}
|
||||
when(provisioner.completeUpdate(any())).thenReturn(UpdateCleanupResult.notApplicable());
|
||||
|
||||
service.deleteStackResources(stack, REGION, ACCOUNT);
|
||||
|
||||
assertEquals("DELETE_COMPLETE", stack.getStatus());
|
||||
verify(provisioner).delete(role, REGION);
|
||||
verify(provisioner).delete(logGroup, REGION);
|
||||
verify(provisioner).delete(owned, REGION);
|
||||
verify(provisioner, never()).delete(eq(alreadyDeleted), anyString());
|
||||
verify(provisioner, never()).delete(eq(adopted), anyString());
|
||||
assertEquals("DELETE_COMPLETE", role.getStatus());
|
||||
assertNull(role.getStatusReason());
|
||||
assertEquals("DELETE_COMPLETE", logGroup.getStatus());
|
||||
assertEquals("CREATE_FAILED", adopted.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteStack_withUndeletableUpdateFailedResource_reachesDeleteFailed() {
|
||||
Stack stack = new Stack();
|
||||
stack.setStackName("delete-update-failed-bucket");
|
||||
stack.setStackId("stack-id");
|
||||
stack.setRegion(REGION);
|
||||
stack.setStatus("UPDATE_ROLLBACK_FAILED");
|
||||
|
||||
StackResource bucket = resource("Bucket", "leak-probe-bucket", "AWS::S3::Bucket", "UPDATE_FAILED");
|
||||
stack.getResources().put(bucket.getLogicalId(), bucket);
|
||||
when(provisioner.completeUpdate(any())).thenReturn(UpdateCleanupResult.notApplicable());
|
||||
doThrow(new AwsException("BucketNotEmpty", "The bucket you tried to delete is not empty", 409))
|
||||
.when(provisioner).delete(eq(bucket), eq(REGION));
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> service.deleteStackResources(stack, REGION, ACCOUNT));
|
||||
|
||||
assertEquals("DELETE_FAILED", stack.getStatus());
|
||||
assertEquals("The following resource(s) failed to delete: [Bucket].", stack.getStatusReason());
|
||||
assertEquals("DELETE_FAILED", bucket.getStatus());
|
||||
}
|
||||
|
||||
private static StackResource resource(String logicalId, String physicalId, String resourceType, String status) {
|
||||
StackResource resource = new StackResource();
|
||||
resource.setLogicalId(logicalId);
|
||||
|
||||
Reference in new issue
Block a user