mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cloudformation): honor retained resources on stack deletion (#6723)
* fix(cloudformation): honor retained resources on stack deletion * test(cloudformation): assert the unretained sibling bucket is removed * fix(cloudformation): skip every retained resource, whatever its status A DELETE_FAILED stack can hold a CREATE_FAILED resource that the delete never touches, because floci only deletes a failed resource it owns for rollback. Naming it in RetainResources was accepted but left it CREATE_FAILED with no DELETE_SKIPPED event. AWS reports every retained resource DELETE_SKIPPED, so the retain check now runs before the deletability guard. * test(cloudformation): build the retain integration test on the shared CFN helpers Use CfnStackWaits.awaitStatus, which also fails at once on another terminal status, instead of a private poll, and CfnRequests.cfn for the Query requests.
This commit is contained in:
1 parent
4c52e12834
commit
7cf516a14d
8 files changed
+508
-10
No files matched your search
+194
@@ -0,0 +1,194 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.XmlParser;
|
||||
import io.github.hectorvent.floci.testing.CfnStackWaits;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static io.github.hectorvent.floci.testing.CfnRequests.cfn;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
/**
|
||||
* Verifies {@code DeleteStack}'s {@code RetainResources}: a stack whose delete failed can be deleted
|
||||
* again while keeping the resources it names, and a request naming them anywhere else is refused
|
||||
* with the texts AWS answers.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CloudFormationDeleteStackRetainResourcesIntegrationTest {
|
||||
|
||||
private static final String INVALID_STATE = "The specified resources to retain must be in a valid state."
|
||||
+ " Do not specify resources that are in the DELETE_COMPLETE state.";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void retainedBucketKeepsItsDataWhileTheRestOfTheStackIsDeleted() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String data = "cfn-retain-data-" + suffix;
|
||||
String spare = "cfn-retain-spare-" + suffix;
|
||||
String stackName = "cfn-retain-" + suffix;
|
||||
String stackId = deleteFailedStack(stackName, data, spare, "cfn-retain-other-" + suffix);
|
||||
given().when().delete("/" + spare + "/object.txt").then().statusCode(204);
|
||||
|
||||
deleteStack(stackName, "DataBucket").then().statusCode(200);
|
||||
|
||||
CfnStackWaits.awaitStatus(stackId, "DELETE_COMPLETE");
|
||||
given().when().get("/" + data + "/object.txt").then().statusCode(200).body(containsString("kept"));
|
||||
bucketRequest(spare).then().statusCode(404);
|
||||
String events = cfn("DescribeStackEvents", stackId)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().asString();
|
||||
Map<String, String> newest = XmlParser.extractGroups(events, "member").stream()
|
||||
.filter(member -> "DataBucket".equals(member.get("LogicalResourceId")))
|
||||
.findFirst().orElseThrow();
|
||||
assertEquals("DELETE_SKIPPED", newest.get("ResourceStatus"));
|
||||
assertNull(newest.get("ResourceStatusReason"));
|
||||
given().when().delete("/" + data + "/object.txt");
|
||||
given().header("Host", data + ".localhost").when().delete("/");
|
||||
}
|
||||
|
||||
@Test
|
||||
void retainingAResourceTheStackNoLongerHasIsRefused() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String data = "cfn-retain-gone-data-" + suffix;
|
||||
String spare = "cfn-retain-gone-spare-" + suffix;
|
||||
String stackName = "cfn-retain-gone-" + suffix;
|
||||
String stackId = deleteFailedStack(stackName, data, spare, "cfn-retain-gone-other-" + suffix);
|
||||
|
||||
// OtherBucket was deleted by the failed delete, Nope was never a resource of the stack.
|
||||
for (String retained : new String[] {"OtherBucket", "Nope"}) {
|
||||
assertValidationError(deleteStack(stackName, retained), INVALID_STATE);
|
||||
}
|
||||
|
||||
assertThat(describeStacks(stackId), containsString("<StackStatus>DELETE_FAILED</StackStatus>"));
|
||||
given().when().delete("/" + data + "/object.txt");
|
||||
given().when().delete("/" + spare + "/object.txt");
|
||||
deleteStack(stackName).then().statusCode(200);
|
||||
CfnStackWaits.awaitStatus(stackId, "DELETE_COMPLETE");
|
||||
}
|
||||
|
||||
@Test
|
||||
void retainingIsRefusedUnlessTheStackIsDeleteFailed() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String bucket = "cfn-retain-live-" + suffix;
|
||||
String stackName = "cfn-retain-live-" + suffix;
|
||||
String stackId = createStack(stackName, """
|
||||
{"Resources": {"Bucket": {"Type": "AWS::S3::Bucket", "Properties": {"BucketName": "%s"}}}}
|
||||
""".formatted(bucket));
|
||||
CfnStackWaits.awaitStatus(stackId, "CREATE_COMPLETE");
|
||||
|
||||
assertValidationError(deleteStack(stackName, "Bucket"), "Invalid operation on stack [" + stackId
|
||||
+ "]. When you delete a stack, specify which resources to retain only when the stack is in the"
|
||||
+ " DELETE_FAILED state.");
|
||||
assertThat(describeStacks(stackId), containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
|
||||
|
||||
// An empty list is the one the AWS CLI sends for --retain-resources with no ids: no list at all.
|
||||
cfn("DeleteStack", stackName)
|
||||
.formParam("RetainResources", "")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
CfnStackWaits.awaitStatus(stackId, "DELETE_COMPLETE");
|
||||
bucketRequest(bucket).then().statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedRetainListIsRefusedBeforeTheStackIsLookedUp() {
|
||||
String missing = "cfn-retain-missing-" + Long.toString(System.nanoTime(), 36);
|
||||
String tooLong = "a".repeat(256);
|
||||
String lengths = "' at 'resourcesToRetain' failed to satisfy constraint: Member must satisfy constraint:"
|
||||
+ " [Member must have length less than or equal to 255, Member must have length greater than"
|
||||
+ " or equal to 1]";
|
||||
|
||||
assertValidationError(deleteStack(missing, ""), "1 validation error detected: Value '[]" + lengths);
|
||||
assertValidationError(deleteStack(missing, "x", tooLong),
|
||||
"1 validation error detected: Value '[x, " + tooLong + "]" + lengths);
|
||||
assertValidationError(deleteStack(missing, "x", "x"), "The logical IDs specified for the resources to"
|
||||
+ " retain are not all unique. Specify unique logical IDs for all of the resources that you want"
|
||||
+ " to retain.");
|
||||
deleteStack(missing, "x", "a".repeat(255)).then().statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* A stack of three buckets whose delete failed on the two holding an object: DataBucket and
|
||||
* SpareBucket are DELETE_FAILED, the empty OtherBucket is DELETE_COMPLETE.
|
||||
*/
|
||||
private static String deleteFailedStack(String stackName, String data, String spare, String other) {
|
||||
String stackId = createStack(stackName, """
|
||||
{
|
||||
"Resources": {
|
||||
"DataBucket": {"Type": "AWS::S3::Bucket", "Properties": {"BucketName": "%s"}},
|
||||
"SpareBucket": {"Type": "AWS::S3::Bucket", "Properties": {"BucketName": "%s"}},
|
||||
"OtherBucket": {"Type": "AWS::S3::Bucket", "Properties": {"BucketName": "%s"}}
|
||||
}
|
||||
}
|
||||
""".formatted(data, spare, other));
|
||||
CfnStackWaits.awaitStatus(stackId, "CREATE_COMPLETE");
|
||||
for (String bucket : new String[] {data, spare}) {
|
||||
given().contentType("text/plain").body("kept").when().put("/" + bucket + "/object.txt")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
deleteStack(stackName).then().statusCode(200);
|
||||
CfnStackWaits.awaitStatus(stackId, "DELETE_FAILED");
|
||||
bucketRequest(other).then().statusCode(404);
|
||||
return stackId;
|
||||
}
|
||||
|
||||
private static void assertValidationError(Response response, String message) {
|
||||
response.then()
|
||||
.statusCode(400)
|
||||
.body("ErrorResponse.Error.Code", equalTo("ValidationError"))
|
||||
.body("ErrorResponse.Error.Message", equalTo(message));
|
||||
}
|
||||
|
||||
private static String createStack(String stackName, String template) {
|
||||
String xml = cfn("CreateStack", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().asString();
|
||||
int start = xml.indexOf("<StackId>") + "<StackId>".length();
|
||||
return xml.substring(start, xml.indexOf("</StackId>", start));
|
||||
}
|
||||
|
||||
private static Response deleteStack(String stackName, String... retainResources) {
|
||||
RequestSpecification request = cfn("DeleteStack", stackName);
|
||||
for (int i = 0; i < retainResources.length; i++) {
|
||||
request.formParam("RetainResources.member." + (i + 1), retainResources[i]);
|
||||
}
|
||||
return request.when().post("/");
|
||||
}
|
||||
|
||||
private static String describeStacks(String stackId) {
|
||||
return cfn("DescribeStacks", stackId)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().asString();
|
||||
}
|
||||
|
||||
private static Response bucketRequest(String bucket) {
|
||||
return given().header("Host", bucket + ".localhost").when().get("/");
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -116,7 +116,7 @@ class CloudFormationServiceRestoreIntegrationTest {
|
||||
List<Future<?>> runningOperations = fillExecutor();
|
||||
try {
|
||||
AwsException rejected = assertThrows(AwsException.class,
|
||||
() -> service.deleteStack(targetStack, REGION));
|
||||
() -> service.deleteStack(targetStack, List.of(), REGION));
|
||||
assertEquals("LimitExceededException", rejected.getErrorCode());
|
||||
assertEquals("CREATE_COMPLETE", service.describeStacks(targetStack, REGION).getFirst().getStatus());
|
||||
} finally {
|
||||
|
||||
+111
@@ -420,6 +420,102 @@ class CloudFormationServiceRollbackTest {
|
||||
assertEquals("DELETE_COMPLETE", stack.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteStack_retainingResourcesOfADeleteFailedStack_skipsOnlyThose() throws Exception {
|
||||
Stack stack = deleteFailedStack("retained-delete");
|
||||
StackResource data = stack.getResources().get("Data");
|
||||
StackResource spare = stack.getResources().get("Spare");
|
||||
|
||||
service.deleteStack("retained-delete", List.of("Data"), REGION, ACCOUNT).get(10, TimeUnit.SECONDS);
|
||||
|
||||
assertEquals("DELETE_COMPLETE", stack.getStatus());
|
||||
verify(provisioner, never()).delete(eq(data), anyString());
|
||||
verify(provisioner).delete(spare, REGION);
|
||||
assertEquals("DELETE_SKIPPED", data.getStatus());
|
||||
assertNull(data.getStatusReason());
|
||||
assertTrue(stack.getEvents().stream().anyMatch(event -> "Data".equals(event.getLogicalResourceId())
|
||||
&& "DELETE_SKIPPED".equals(event.getResourceStatus())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteStack_retainingResourcesTheDeleteWouldNotTouch_skipsThemToo() throws Exception {
|
||||
Stack stack = deleteFailedStack("retained-failed-create");
|
||||
StackResource borrowed = resource("Borrowed", "existing-param", "AWS::SSM::Parameter", "CREATE_FAILED");
|
||||
StackResource unnamed = resource("Unnamed", null, "AWS::SSM::Parameter", "CREATE_FAILED");
|
||||
for (StackResource failed : List.of(borrowed, unnamed)) {
|
||||
failed.setStatusReason("Error occurred during operation 'PutParameter'.");
|
||||
stack.getResources().put(failed.getLogicalId(), failed);
|
||||
}
|
||||
|
||||
service.deleteStack("retained-failed-create", List.of("Data", "Borrowed", "Unnamed"), REGION, ACCOUNT)
|
||||
.get(10, TimeUnit.SECONDS);
|
||||
|
||||
assertEquals("DELETE_COMPLETE", stack.getStatus());
|
||||
for (StackResource failed : List.of(borrowed, unnamed)) {
|
||||
verify(provisioner, never()).delete(eq(failed), anyString());
|
||||
assertEquals("DELETE_SKIPPED", failed.getStatus());
|
||||
assertNull(failed.getStatusReason());
|
||||
assertTrue(stack.getEvents().stream().anyMatch(event -> failed.getLogicalId()
|
||||
.equals(event.getLogicalResourceId()) && "DELETE_SKIPPED".equals(event.getResourceStatus())));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteStack_retriedWhileDeleting_refusesADifferentRetainList() throws Exception {
|
||||
Stack stack = deleteFailedStack("retain-retried");
|
||||
StackResource spare = stack.getResources().get("Spare");
|
||||
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(spare), eq(REGION));
|
||||
|
||||
Future<?> first = service.deleteStack("retain-retried", List.of("Data"), REGION, ACCOUNT);
|
||||
assertTrue(deleting.await(10, TimeUnit.SECONDS));
|
||||
service.deleteStack("retain-retried", List.of("Data"), REGION, ACCOUNT).get(5, TimeUnit.SECONDS);
|
||||
for (List<String> other : List.of(List.<String>of(), List.of("Data", "Spare"))) {
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> service.deleteStack("retain-retried", other, REGION, ACCOUNT));
|
||||
assertEquals("ValidationError", error.getErrorCode());
|
||||
assertEquals("A delete stack operation is already in progress for stack [" + stack.getStackId()
|
||||
+ "]. Do not submit another delete stack request specifying different resources to retain"
|
||||
+ " or resources to retain in a different order.", error.getMessage());
|
||||
}
|
||||
release.countDown();
|
||||
first.get(10, TimeUnit.SECONDS);
|
||||
|
||||
verify(provisioner, times(1)).delete(spare, REGION);
|
||||
assertEquals("DELETE_COMPLETE", stack.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteStack_retriedOnAChildItsParentIsDeleting_isANoOp() throws Exception {
|
||||
Stack child = deleteFailedStack("retain-child");
|
||||
child.setRetainResources(List.of("Data"));
|
||||
Stack parent = liveStack("retain-parent");
|
||||
parent.getResources().clear();
|
||||
parent.getResources().put("Child",
|
||||
resource("Child", child.getStackId(), "AWS::CloudFormation::Stack", "CREATE_COMPLETE"));
|
||||
StackResource spare = child.getResources().get("Spare");
|
||||
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(spare), eq(REGION));
|
||||
|
||||
Future<?> parentDelete = service.deleteStack("retain-parent", REGION, ACCOUNT);
|
||||
assertTrue(deleting.await(10, TimeUnit.SECONDS));
|
||||
service.deleteStack("retain-child", List.of(), REGION, ACCOUNT).get(5, TimeUnit.SECONDS);
|
||||
release.countDown();
|
||||
parentDelete.get(10, TimeUnit.SECONDS);
|
||||
|
||||
assertEquals("DELETE_COMPLETE", child.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void executeChangeSet_onStackBeingDeleted_isRefused() {
|
||||
Stack stack = liveStack("executed-while-deleting");
|
||||
@@ -1774,6 +1870,21 @@ class CloudFormationServiceRollbackTest {
|
||||
return stack;
|
||||
}
|
||||
|
||||
/** A live stack whose delete failed on both of its buckets, Data and Spare. */
|
||||
private Stack deleteFailedStack(String stackName) {
|
||||
Stack stack = liveStack(stackName);
|
||||
stack.setStatus("DELETE_FAILED");
|
||||
stack.getResources().clear();
|
||||
for (String logicalId : List.of("Data", "Spare")) {
|
||||
StackResource bucket = resource(logicalId, logicalId.toLowerCase() + "-bucket", "AWS::S3::Bucket",
|
||||
"DELETE_FAILED");
|
||||
bucket.setStatusReason("The bucket you tried to delete is not empty");
|
||||
stack.getResources().put(logicalId, bucket);
|
||||
}
|
||||
when(provisioner.completeDeleteCleanup(any())).thenReturn(UpdateCleanupResult.notApplicable());
|
||||
return stack;
|
||||
}
|
||||
|
||||
private static List<String> stackEventStatuses(Stack stack) {
|
||||
return stack.getEvents().stream()
|
||||
.filter(event -> "AWS::CloudFormation::Stack".equals(event.getResourceType()))
|
||||
|
||||
Reference in new issue
Block a user