mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cloudformation): reject resources that depend on each other in a cycle (#5208)
* fix(cloudformation): reject resources that depend on each other in a cycle A template whose resources form a dependency cycle was created anyway: the topological sort appended the resources it could not order and created them in template order. CloudFormation rejects such a template with a ValidationError naming the resources, before any of them is created. The sort now throws that error when resources remain unsorted, and the synchronous pre-check that runs before CreateStack, UpdateStack and CreateChangeSet calls the sort instead of repeating its dependency checks, so the request fails before any stack state is created. * fix(cloudformation): keep dependency order when deleting a stack saved with a cyclic template A stack saved before circular templates were rejected can still carry one. Deleting it hit the new circular-dependency error while ordering its resources, so the delete fell back to insertion order for every resource and could remove a resource before one still using it. The delete now orders what it can and places the circular resources after it, as before. * fix(cloudformation): order resources that depend on a cycle when deleting a saved stack A resource that depends on a dependency cycle cannot be ordered either, so the delete of a stack saved with a cyclic template ranked such resources in template order and could remove a target group before the listener using it. When the sort stalls it now releases a resource on the cycle itself and goes on, so everything that depends on the cycle keeps its dependency order. * fix(cloudformation): delete linked dependency cycles in dependency order When a saved stack's template has a cycle that depends on another cycle, the sort could release a resource of the dependent cycle before the cycle it uses was placed, so the delete removed that cycle's resources first. When the sort stalls it now releases a resource from the first strongly connected component Tarjan's algorithm completes over the resources left, which depends on no other cycle. * fix(cloudformation): order a saved cyclic stack in one pass and name only the cycle Breaking one cycle at a time searched again at every stall and recursed, so a long dependency chain could exhaust the thread's stack and stop the delete of a stack saved with a cyclic template. The resources left at a stall are now ordered in one pass by their strongly connected components, dependencies first, with an iterative Tarjan search. The circular-dependency error names only the components that are cycles, not resources that merely depend on one. * test(cloudformation): cover circular dependency rejection with the AWS SDK * test(cloudformation): assert only the cycle's resources in the SDK test's message
This commit is contained in:
1 parent
0f94d6213c
commit
13738f89de
6 files changed
+466
-32
No files matched your search
+1
-1
@@ -598,7 +598,7 @@ class AwsIncludeIntegrationTest {
|
||||
|
||||
@Test
|
||||
void conditionsFromTheIncludedSnippetReachProvisioningInsteadOfBeingRejected() {
|
||||
// validateConditionDependencies used to preflight the RAW, unmerged body: a Conditions
|
||||
// validateResourceDependencies used to preflight the RAW, unmerged body: a Conditions
|
||||
// section spliced in from a snippet was invisible there, so a resource conditioned on it
|
||||
// defaulted to excluded and a dependent resource failed CreateStack synchronously with a
|
||||
// spurious "Unresolved resource dependencies" error, even though the merge that runs later
|
||||
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
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.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
|
||||
@QuarkusTest
|
||||
class CloudFormationCircularDependencyIntegrationTest {
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStack_rejectsResourcesThatDependOnEachOther() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stackName = "cfn-cycle-" + suffix;
|
||||
String firstQueueName = "cycle-first-" + suffix;
|
||||
String secondQueueName = "cycle-second-" + suffix;
|
||||
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"FirstQueue": {
|
||||
"Type": "AWS::SQS::Queue",
|
||||
"DependsOn": "SecondQueue",
|
||||
"Properties": { "QueueName": "%s" }
|
||||
},
|
||||
"SecondQueue": {
|
||||
"Type": "AWS::SQS::Queue",
|
||||
"DependsOn": "FirstQueue",
|
||||
"Properties": { "QueueName": "%s" }
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(firstQueueName, secondQueueName);
|
||||
|
||||
try {
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("ErrorResponse.Error.Code", equalTo("ValidationError"))
|
||||
.body("ErrorResponse.Error.Message", containsString("Circular dependency between resources"))
|
||||
.body("ErrorResponse.Error.Message", containsString("FirstQueue"))
|
||||
.body("ErrorResponse.Error.Message", containsString("SecondQueue"));
|
||||
|
||||
assertQueueAbsent(firstQueueName);
|
||||
assertQueueAbsent(secondQueueName);
|
||||
} finally {
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DeleteStack")
|
||||
.formParam("StackName", stackName)
|
||||
.post("/");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStack_namesOnlyTheResourcesInTheCycle() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stackName = "cfn-cycle-names-" + suffix;
|
||||
|
||||
// Downstream depends on the cycle but is not part of it.
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"Downstream": { "Type": "AWS::SQS::Queue", "DependsOn": "FirstQueue" },
|
||||
"FirstQueue": { "Type": "AWS::SQS::Queue", "DependsOn": "SecondQueue" },
|
||||
"SecondQueue": { "Type": "AWS::SQS::Queue", "DependsOn": "FirstQueue" }
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
try {
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("ErrorResponse.Error.Code", equalTo("ValidationError"))
|
||||
.body("ErrorResponse.Error.Message", containsString("FirstQueue"))
|
||||
.body("ErrorResponse.Error.Message", containsString("SecondQueue"))
|
||||
.body("ErrorResponse.Error.Message", not(containsString("Downstream")));
|
||||
} finally {
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DeleteStack")
|
||||
.formParam("StackName", stackName)
|
||||
.post("/");
|
||||
}
|
||||
}
|
||||
|
||||
private static void assertQueueAbsent(String queueName) {
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "GetQueueUrl")
|
||||
.formParam("QueueName", queueName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("ErrorResponse.Error.Code", equalTo("AWS.SimpleQueueService.NonExistentQueue"));
|
||||
}
|
||||
}
|
||||
+158
@@ -17,11 +17,13 @@ import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.ssm.SsmService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.InOrder;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
@@ -31,6 +33,7 @@ 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.inOrder;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
@@ -194,6 +197,161 @@ class CloudFormationServiceRollbackTest {
|
||||
assertEquals(Set.of("create"), stack.getChangeSets().keySet());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteStack_savedWithCircularTemplate_stillDeletesDependentsFirst() {
|
||||
// A stack saved before circular templates were rejected: the queues depend on each other,
|
||||
// and the target group was added by a later update, so it sits after the listener using it.
|
||||
Stack stack = new Stack();
|
||||
stack.setStackName("delete-saved-circular-stack");
|
||||
stack.setStackId("stack-id");
|
||||
stack.setRegion(REGION);
|
||||
stack.setStatus("UPDATE_COMPLETE");
|
||||
stack.setTemplateBody("""
|
||||
{"Resources": {
|
||||
"FirstQueue": {"Type": "AWS::SQS::Queue", "DependsOn": "SecondQueue"},
|
||||
"SecondQueue": {"Type": "AWS::SQS::Queue", "DependsOn": "FirstQueue"},
|
||||
"TargetGroup": {"Type": "AWS::ElasticLoadBalancingV2::TargetGroup"},
|
||||
"Listener": {"Type": "AWS::ElasticLoadBalancingV2::Listener",
|
||||
"Properties": {"DefaultActions": [{"Type": "forward",
|
||||
"TargetGroupArn": {"Ref": "TargetGroup"}}]}}
|
||||
}}""");
|
||||
StackResource listener = resource("Listener", "listener-arn", "AWS::ElasticLoadBalancingV2::Listener",
|
||||
"CREATE_COMPLETE");
|
||||
StackResource firstQueue = resource("FirstQueue", "first-url", "AWS::SQS::Queue", "CREATE_COMPLETE");
|
||||
StackResource secondQueue = resource("SecondQueue", "second-url", "AWS::SQS::Queue", "CREATE_COMPLETE");
|
||||
StackResource targetGroup = resource("TargetGroup", "target-group-arn",
|
||||
"AWS::ElasticLoadBalancingV2::TargetGroup", "CREATE_COMPLETE");
|
||||
for (StackResource resource : new StackResource[] {listener, firstQueue, secondQueue, targetGroup}) {
|
||||
stack.getResources().put(resource.getLogicalId(), resource);
|
||||
}
|
||||
when(provisioner.completeUpdate(any())).thenReturn(UpdateCleanupResult.notApplicable());
|
||||
|
||||
service.deleteStackResources(stack, REGION, ACCOUNT);
|
||||
|
||||
InOrder deletes = inOrder(provisioner);
|
||||
deletes.verify(provisioner).delete(listener, REGION);
|
||||
deletes.verify(provisioner).delete(targetGroup, REGION);
|
||||
assertEquals("DELETE_COMPLETE", stack.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteStack_savedWithCircularTemplate_deletesResourcesDependingOnTheCycleInDependencyOrder() {
|
||||
// The target group depends on a queue in the cycle, so it cannot be ordered either; the
|
||||
// listener using it comes first in the template, yet must still be deleted first.
|
||||
Stack stack = new Stack();
|
||||
stack.setStackName("delete-saved-circular-chain");
|
||||
stack.setStackId("stack-id");
|
||||
stack.setRegion(REGION);
|
||||
stack.setStatus("UPDATE_COMPLETE");
|
||||
stack.setTemplateBody("""
|
||||
{"Resources": {
|
||||
"Listener": {"Type": "AWS::ElasticLoadBalancingV2::Listener",
|
||||
"Properties": {"DefaultActions": [{"Type": "forward",
|
||||
"TargetGroupArn": {"Ref": "TargetGroup"}}]}},
|
||||
"FirstQueue": {"Type": "AWS::SQS::Queue", "DependsOn": "SecondQueue"},
|
||||
"SecondQueue": {"Type": "AWS::SQS::Queue", "DependsOn": "FirstQueue"},
|
||||
"TargetGroup": {"Type": "AWS::ElasticLoadBalancingV2::TargetGroup", "DependsOn": "FirstQueue"}
|
||||
}}""");
|
||||
StackResource listener = resource("Listener", "listener-arn", "AWS::ElasticLoadBalancingV2::Listener",
|
||||
"CREATE_COMPLETE");
|
||||
StackResource firstQueue = resource("FirstQueue", "first-url", "AWS::SQS::Queue", "CREATE_COMPLETE");
|
||||
StackResource secondQueue = resource("SecondQueue", "second-url", "AWS::SQS::Queue", "CREATE_COMPLETE");
|
||||
StackResource targetGroup = resource("TargetGroup", "target-group-arn",
|
||||
"AWS::ElasticLoadBalancingV2::TargetGroup", "CREATE_COMPLETE");
|
||||
for (StackResource resource : new StackResource[] {listener, firstQueue, secondQueue, targetGroup}) {
|
||||
stack.getResources().put(resource.getLogicalId(), resource);
|
||||
}
|
||||
when(provisioner.completeUpdate(any())).thenReturn(UpdateCleanupResult.notApplicable());
|
||||
|
||||
service.deleteStackResources(stack, REGION, ACCOUNT);
|
||||
|
||||
InOrder deletes = inOrder(provisioner);
|
||||
deletes.verify(provisioner).delete(listener, REGION);
|
||||
deletes.verify(provisioner).delete(targetGroup, REGION);
|
||||
deletes.verify(provisioner).delete(firstQueue, REGION);
|
||||
assertEquals("DELETE_COMPLETE", stack.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteStack_savedWithLinkedCircularTemplates_deletesTheDependentCycleFirst() {
|
||||
// Two cycles, the consumer's cycle also depending on the queues' cycle: the consumer must
|
||||
// be deleted while the queues it uses still exist.
|
||||
Stack stack = new Stack();
|
||||
stack.setStackName("delete-saved-linked-cycles");
|
||||
stack.setStackId("stack-id");
|
||||
stack.setRegion(REGION);
|
||||
stack.setStatus("UPDATE_COMPLETE");
|
||||
stack.setTemplateBody("""
|
||||
{"Resources": {
|
||||
"Consumer": {"Type": "AWS::SQS::Queue", "DependsOn": ["Partner", "FirstQueue"]},
|
||||
"Partner": {"Type": "AWS::SQS::Queue", "DependsOn": "Consumer"},
|
||||
"FirstQueue": {"Type": "AWS::SQS::Queue", "DependsOn": "SecondQueue"},
|
||||
"SecondQueue": {"Type": "AWS::SQS::Queue", "DependsOn": "FirstQueue"}
|
||||
}}""");
|
||||
StackResource consumer = resource("Consumer", "consumer-url", "AWS::SQS::Queue", "CREATE_COMPLETE");
|
||||
StackResource partner = resource("Partner", "partner-url", "AWS::SQS::Queue", "CREATE_COMPLETE");
|
||||
StackResource firstQueue = resource("FirstQueue", "first-url", "AWS::SQS::Queue", "CREATE_COMPLETE");
|
||||
StackResource secondQueue = resource("SecondQueue", "second-url", "AWS::SQS::Queue", "CREATE_COMPLETE");
|
||||
for (StackResource resource : new StackResource[] {consumer, partner, firstQueue, secondQueue}) {
|
||||
stack.getResources().put(resource.getLogicalId(), resource);
|
||||
}
|
||||
when(provisioner.completeUpdate(any())).thenReturn(UpdateCleanupResult.notApplicable());
|
||||
|
||||
service.deleteStackResources(stack, REGION, ACCOUNT);
|
||||
|
||||
InOrder deletes = inOrder(provisioner);
|
||||
deletes.verify(provisioner).delete(consumer, REGION);
|
||||
deletes.verify(provisioner).delete(firstQueue, REGION);
|
||||
assertEquals("DELETE_COMPLETE", stack.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteStack_savedWithLongChainIntoCycle_deletesWithoutExhaustingTheThreadStack() throws InterruptedException {
|
||||
// Each resource depends on the next and the last one on a cycle, so finding the cycle has
|
||||
// to follow the whole chain; a small thread stack makes a recursive search overflow.
|
||||
int chainLength = 5_000;
|
||||
StringBuilder resources = new StringBuilder();
|
||||
Stack stack = new Stack();
|
||||
stack.setStackName("delete-saved-long-chain");
|
||||
stack.setStackId("stack-id");
|
||||
stack.setRegion(REGION);
|
||||
stack.setStatus("UPDATE_COMPLETE");
|
||||
StackResource[] chain = new StackResource[chainLength];
|
||||
for (int i = 0; i < chainLength; i++) {
|
||||
String next = i + 1 < chainLength ? "Link" + (i + 1) : "FirstQueue";
|
||||
resources.append("\"Link").append(i).append("\": {\"Type\": \"AWS::SQS::Queue\", \"DependsOn\": \"")
|
||||
.append(next).append("\"},");
|
||||
chain[i] = resource("Link" + i, "link-" + i, "AWS::SQS::Queue", "CREATE_COMPLETE");
|
||||
stack.getResources().put(chain[i].getLogicalId(), chain[i]);
|
||||
}
|
||||
stack.setTemplateBody("{\"Resources\": {" + resources
|
||||
+ "\"FirstQueue\": {\"Type\": \"AWS::SQS::Queue\", \"DependsOn\": \"SecondQueue\"},"
|
||||
+ "\"SecondQueue\": {\"Type\": \"AWS::SQS::Queue\", \"DependsOn\": \"FirstQueue\"}}}");
|
||||
StackResource firstQueue = resource("FirstQueue", "first-url", "AWS::SQS::Queue", "CREATE_COMPLETE");
|
||||
StackResource secondQueue = resource("SecondQueue", "second-url", "AWS::SQS::Queue", "CREATE_COMPLETE");
|
||||
stack.getResources().put(firstQueue.getLogicalId(), firstQueue);
|
||||
stack.getResources().put(secondQueue.getLogicalId(), secondQueue);
|
||||
when(provisioner.completeUpdate(any())).thenReturn(UpdateCleanupResult.notApplicable());
|
||||
|
||||
AtomicReference<Throwable> failure = new AtomicReference<>();
|
||||
Thread deleter = new Thread(null, () -> {
|
||||
try {
|
||||
service.deleteStackResources(stack, REGION, ACCOUNT);
|
||||
} catch (Throwable t) {
|
||||
failure.set(t);
|
||||
}
|
||||
}, "small-stack-delete", 256 * 1024);
|
||||
deleter.start();
|
||||
deleter.join();
|
||||
|
||||
assertNull(failure.get());
|
||||
assertEquals("DELETE_COMPLETE", stack.getStatus());
|
||||
InOrder deletes = inOrder(provisioner);
|
||||
deletes.verify(provisioner).delete(chain[0], REGION);
|
||||
deletes.verify(provisioner).delete(chain[chainLength - 1], REGION);
|
||||
deletes.verify(provisioner).delete(firstQueue, REGION);
|
||||
}
|
||||
|
||||
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