mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cloudformation): send a stack's status changes to the default bus, with their request token (#7053)
Floci sent no event as a stack's status changed, so a rule on `CloudFormation Stack Status Change` never fired, and whatever starts on one, a deploy waiting for its stack to finish among them, never started. It also dropped `ClientRequestToken`, which is how a consumer ties an event to the operation that caused it. - CloudFormation User Guide, "Using Amazon EventBridge with CloudFormation": events go to the default bus, "guaranteed to be delivered, and they might be delivered out of order". https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/eventbridge-integration.html - CloudFormation User Guide, "CloudFormation stack status change event detail": the envelope, `stack-id`, `status-details`, and "All events that are initiated by a given stack operation are assigned the same client request token". https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/event-detail-stack-status-change.html The pages say nothing of nested stacks, and their sample shows an empty token. Rules read on a real account on 2026-10-30, for a root nesting one stack, showed one event per status. Through a create change set, an update change set and DeleteStack, each with its own token, the root's events carried their operation's token but for REVIEW_IN_PROGRESS, which had no key, and the nested stack's had no key at all. Through a create and an update that failed in the nested stack, the root's rollback statuses carried the create's or the update's token, the nested stack's again had no key, neither the root's CREATE_FAILED nor any UPDATE_FAILED reached the bus, and the nested stack's failed create was CREATE_FAILED and then DELETE_IN_PROGRESS and DELETE_COMPLETE, with no ROLLBACK_* status. Floci now records and sends that: a nested stack records CREATE_IN_PROGRESS or UPDATE_IN_PROGRESS as its operation starts, its failed create ends in CREATE_FAILED for its parent's rollback to delete, without the "Rollback requested by user." CloudFormation's reason did not carry, and an update's first rollback passes through UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS. An operation given no token leaves the key out too. Two cases were not read and no test asserts them: a failure in the root's own resource with the nested stack healthy, and a delete that fails. They send CloudFormation's documented statuses from the same code. UPDATE_COMPLETE_CLEANUP_IN_PROGRESS stays where Floci has cleanup to do, though CloudFormation sent it on every update. A template Floci cannot execute at all still ends a root in CREATE_FAILED and sends it, so that stack's end is not silent; the reading has no such path. CloudFormationService.addEvent is the one place a status is recorded, so it queues an event for a stack's own record, and CloudFormationEventPublisher delivers them in order on one daemon thread. A status can be recorded under the stack's lock in stacks.compute and delivery calls a rule's targets before it returns, so delivering in place would hold that lock and the operation for as long as the targets take. A failed path records its event before it writes the status, so delivery waits a moment for that write. The queue is in memory: an event still in it when Floci stops is dropped and counted in the log, and is not sent on the next start. The query handler hands each operation's token to the service, which sets it on the stack before the operation's first record and clears it where the operation has none. It is not persisted. test(cloudformation): an update failing outside a resource sends no UPDATE_FAILED An update that fails before any resource, on an SSM parameter or a template that fails at execute, goes straight to its rollback, and CloudFormation sends no UPDATE_FAILED, as for a failure in a resource. On 2.4.0 the failed-execute path already sends none, so this commit carries the test alone that keeps it so: the bus hears UPDATE_IN_PROGRESS, the rollback's statuses and nothing else, each with the operation's request token. (test cherry picked from commit 9314dad130116c5d4c809072800c787a4d640446, whose code change 2.4.0 makes moot) fix(cloudformation): roll back a failed nested create's RetainExceptOnCreate, and send a start only once it runs A nested stack's failed create is deleted by its parent's rollback through the ordinary delete path, which kept what RetainExceptOnCreate marks. The delete of a child in CREATE_FAILED now carries the create-rollback flag, so those resources go as they did when the child rolled itself back, and a nested case in CloudFormationDeletionPolicyIntegrationTest keeps it so. The status an operation starts with is recorded under the stack's lock but sent by the operation as its first act, so an operation the executor refuses sends nothing. A successful create or update records its completion before the terminal status is exposed, as the failed paths do, so the event carries the operation's own token and not a later request's. The publisher test waits for the worker to be sleeping or stopped instead of a fixed 200 ms, and the status events test has one wait loop for the root's and the nested stack's events. fix(cloudformation): a delete deferred behind a running create sends its own token A DeleteStack accepted while an execution runs waits for it, and until now only its retain list waited: when the execution ended and the delete began, the stack still held the execution's token, so DELETE_IN_PROGRESS and DELETE_COMPLETE went out with it. The deferred delete now keeps its token beside what it retains, and the stack takes it as the delete starts. aDeleteLandingMidCreateCarriesItsOwnToken holds a custom resource's Create open, lands the delete, and reads the tokens on the bus; it was red before. The stale Javadoc above awaitEvents goes. The mid-create test stubbed the ServiceToken Lambda and PUT the response itself, which CustomResourceProbe already does. The probe takes a hold: the requests a predicate matches wait before they are answered until the test releases them, and the test reads when one has arrived. The status events test holds the Create that way.
This commit is contained in:
1 parent
6710ce4d46
commit
2a3dbb1aa4
10 files changed
+1173
-43
No files matched your search
+64
-1
@@ -837,6 +837,69 @@ class CloudFormationDeletionPolicyIntegrationTest {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A nested stack whose create fails ends in CREATE_FAILED and is deleted by its parent's rollback.
|
||||
* That delete rolls the child's create back, so a resource marked RetainExceptOnCreate goes, as
|
||||
* it does when a root rolls back, while Retain keeps its resource.
|
||||
*/
|
||||
@Test
|
||||
void rollingBackAFailedNestedCreateDeletesRetainExceptOnCreateButKeepsRetain() throws InterruptedException {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String keptBucket = "cfn-nested-rollback-retain-" + suffix;
|
||||
String rolledBackBucket = "cfn-nested-rollback-reoc-" + suffix;
|
||||
given().when().put("/nested-stack-templates").then().statusCode(200);
|
||||
String childTemplate = """
|
||||
{
|
||||
"Resources": {
|
||||
"KeptBucket": {
|
||||
"Type": "AWS::S3::Bucket",
|
||||
"DeletionPolicy": "Retain",
|
||||
"Properties": { "BucketName": "%s" }
|
||||
},
|
||||
"RolledBackBucket": {
|
||||
"Type": "AWS::S3::Bucket",
|
||||
"DeletionPolicy": "RetainExceptOnCreate",
|
||||
"DependsOn": "KeptBucket",
|
||||
"Properties": { "BucketName": "%s" }
|
||||
},
|
||||
"BadSecret": {
|
||||
"Type": "AWS::SecretsManager::Secret",
|
||||
"DependsOn": "RolledBackBucket",
|
||||
"Properties": {
|
||||
"Name": "bad-secret-nested-policy-%s",
|
||||
"SecretString": "explicit",
|
||||
"GenerateSecretString": { "PasswordLength": 32 }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(keptBucket, rolledBackBucket, suffix);
|
||||
given().contentType("application/json").body(childTemplate).when()
|
||||
.put("/nested-stack-templates/child-policy-" + suffix + ".json");
|
||||
|
||||
String stackName = "parent-policy-" + suffix;
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"ChildStack": {
|
||||
"Type": "AWS::CloudFormation::Stack",
|
||||
"Properties": { "TemplateURL": "http://localhost/nested-stack-templates/child-policy-%s.json" }
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(suffix);
|
||||
|
||||
String parentStackId = createStack(stackName, template);
|
||||
try {
|
||||
awaitStackStatus(parentStackId, "ROLLBACK_COMPLETE");
|
||||
cfnQuery("DescribeStacks", stackName + "-ChildStack").then().statusCode(400);
|
||||
assertBucketExists(keptBucket);
|
||||
assertBucketDeleted(rolledBackBucket);
|
||||
} finally {
|
||||
deleteStack(stackName);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void createChangeSet_nestedStackPreExistingLogGroup_rollsBackParentStack() throws Exception {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
@@ -919,7 +982,7 @@ class CloudFormationDeletionPolicyIntegrationTest {
|
||||
assertThat(events, containsString("<ResourceStatus>CREATE_FAILED</ResourceStatus>"));
|
||||
assertThat(events, containsString("<ResourceStatusReason>Nested stack " + stackName
|
||||
+ "-ChildStack failed: The following resource(s) failed to create: [MyLogGroup]."
|
||||
+ " Rollback requested by user.</ResourceStatusReason>"));
|
||||
+ "</ResourceStatusReason>"));
|
||||
} finally {
|
||||
deleteStack(stackName);
|
||||
}
|
||||
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
package io.floci.aws.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.services.cloudformation.model.Stack;
|
||||
import io.floci.aws.services.eventbridge.EventBridgeService;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.InOrder;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.contains;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
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.timeout;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
class CloudFormationEventPublisherTest {
|
||||
|
||||
private static final String STACK_ID = "arn:aws:cloudformation:us-east-1:000000000000:stack/s/1";
|
||||
private static final long DELIVERY_TIMEOUT_MILLIS = 5_000;
|
||||
|
||||
private final EventBridgeService eventBridge = mock(EventBridgeService.class);
|
||||
private final CloudFormationEventPublisher publisher =
|
||||
new CloudFormationEventPublisher(eventBridge, new ObjectMapper());
|
||||
|
||||
@BeforeEach
|
||||
void start() {
|
||||
publisher.start();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void stop() {
|
||||
publisher.stop();
|
||||
}
|
||||
|
||||
private static Stack stackInStatus(String status) {
|
||||
Stack stack = new Stack();
|
||||
stack.setStackId(STACK_ID);
|
||||
stack.setRegion("us-east-1");
|
||||
stack.setStatus(status);
|
||||
return stack;
|
||||
}
|
||||
|
||||
private static String detailWith(String status) {
|
||||
return contains("\"status\":\"" + status + "\"");
|
||||
}
|
||||
|
||||
private void awaitWorker(Thread.State state) {
|
||||
await().atMost(DELIVERY_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS).until(() -> publisher.workerState() == state);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEventRecordedBeforeItsStatusWriteWaitsForThatWrite() {
|
||||
Stack stack = stackInStatus("UPDATE_IN_PROGRESS");
|
||||
|
||||
publisher.stackStatusChanged(stack, "000000000000", "UPDATE_COMPLETE", null);
|
||||
|
||||
awaitWorker(Thread.State.TIMED_WAITING); // sleeping in awaitStatusWrite
|
||||
verify(eventBridge, never()).publishServiceEvent(anyString(), anyString(), anyString(),
|
||||
anyString(), anyString());
|
||||
stack.setStatus("UPDATE_COMPLETE");
|
||||
verify(eventBridge, timeout(DELIVERY_TIMEOUT_MILLIS)).publishServiceEvent(
|
||||
eq(CloudFormationEventPublisher.SOURCE), eq(CloudFormationEventPublisher.DETAIL_TYPE),
|
||||
detailWith("UPDATE_COMPLETE"), eq(STACK_ID), eq("us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEventStillQueuedWhenFlociStopsIsDropped() {
|
||||
Stack stack = stackInStatus("UPDATE_IN_PROGRESS");
|
||||
publisher.stackStatusChanged(stack, "000000000000", "UPDATE_COMPLETE", null);
|
||||
|
||||
publisher.stop();
|
||||
stack.setStatus("UPDATE_COMPLETE");
|
||||
|
||||
awaitWorker(Thread.State.TERMINATED);
|
||||
verify(eventBridge, never()).publishServiceEvent(anyString(), anyString(), anyString(),
|
||||
anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStatusLeftUnwrittenDoesNotHoldUpTheEventsBehindIt() {
|
||||
Stack stack = stackInStatus("UPDATE_IN_PROGRESS");
|
||||
|
||||
publisher.stackStatusChanged(stack, "000000000000", "UPDATE_COMPLETE", null);
|
||||
|
||||
verify(eventBridge, timeout(DELIVERY_TIMEOUT_MILLIS)).publishServiceEvent(anyString(), anyString(),
|
||||
detailWith("UPDATE_COMPLETE"), anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void eventsAreDeliveredInTheOrderRecordedAndAFailureStopsNothing() {
|
||||
doThrow(new IllegalStateException("bus is down")).when(eventBridge).publishServiceEvent(
|
||||
anyString(), anyString(), detailWith("CREATE_IN_PROGRESS"), anyString(), anyString());
|
||||
Stack stack = stackInStatus("CREATE_IN_PROGRESS");
|
||||
|
||||
publisher.stackStatusChanged(stack, "000000000000", "CREATE_IN_PROGRESS", null);
|
||||
stack.setStatus("CREATE_COMPLETE");
|
||||
publisher.stackStatusChanged(stack, "000000000000", "CREATE_COMPLETE", null);
|
||||
|
||||
verify(eventBridge, timeout(DELIVERY_TIMEOUT_MILLIS)).publishServiceEvent(anyString(), anyString(),
|
||||
detailWith("CREATE_COMPLETE"), anyString(), anyString());
|
||||
InOrder order = inOrder(eventBridge);
|
||||
order.verify(eventBridge).publishServiceEvent(anyString(), anyString(), detailWith("CREATE_IN_PROGRESS"),
|
||||
anyString(), anyString());
|
||||
order.verify(eventBridge).publishServiceEvent(anyString(), anyString(), detailWith("CREATE_COMPLETE"),
|
||||
anyString(), anyString());
|
||||
}
|
||||
}
|
||||
+4
-2
@@ -452,8 +452,10 @@ class CloudFormationServiceRollbackTest {
|
||||
service.rollbackFailedExecution(stack, REGION, false, added, previousState,
|
||||
new LinkedHashSet<>(List.of("Dup")));
|
||||
|
||||
assertEquals(List.of("UPDATE_ROLLBACK_IN_PROGRESS", "UPDATE_ROLLBACK_COMPLETE"), stack.statuses());
|
||||
assertEquals(List.of("UPDATE_ROLLBACK_IN_PROGRESS", "UPDATE_ROLLBACK_COMPLETE"), stackEventStatuses(stack));
|
||||
assertEquals(List.of("UPDATE_ROLLBACK_IN_PROGRESS", "UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS",
|
||||
"UPDATE_ROLLBACK_COMPLETE"), stack.statuses());
|
||||
assertEquals(List.of("UPDATE_ROLLBACK_IN_PROGRESS", "UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS",
|
||||
"UPDATE_ROLLBACK_COMPLETE"), stackEventStatuses(stack));
|
||||
stack.assertEachStatusFollowsItsEvent();
|
||||
assertEquals("The following resource(s) failed to create: [Dup].", stack.writes().getFirst().reason());
|
||||
}
|
||||
|
||||
+596
@@ -0,0 +1,596 @@
|
||||
package io.floci.aws.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.services.lambda.LambdaService;
|
||||
import io.floci.aws.testing.CfnRequests;
|
||||
import io.floci.aws.testing.CfnStackWaits;
|
||||
import io.floci.aws.testing.EventRuleQueue;
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.floci.aws.testing.StepFunctionsExecutions;
|
||||
import io.floci.aws.testing.StepFunctionsRequests;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.path.xml.XmlPath;
|
||||
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.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.containsInAnyOrder;
|
||||
import static org.hamcrest.Matchers.hasItems;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
/**
|
||||
* What a rule on the default bus receives as a stack's status changes, against what CloudFormation
|
||||
* sent a rule on 2026-10-30 for a root nesting one stack, through change sets and DeleteStack, each
|
||||
* with a token of its own, and through a create and an update that failed in the nested stack: the
|
||||
* root's events carry their operation's token, its rollback statuses included, but for
|
||||
* {@code REVIEW_IN_PROGRESS}, which has no key; a nested stack's events have no key at all; and the
|
||||
* root's {@code CREATE_FAILED} and any {@code UPDATE_FAILED} never reach the bus. A nested stack's
|
||||
* failed create is {@code CREATE_FAILED} and then a delete. Each status arrives once.
|
||||
*
|
||||
* <p>A failure in the root's own resource with the nested stack healthy, and a delete that fails, were
|
||||
* not read, and no test here asserts them.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CloudFormationStackStatusEventsIntegrationTest {
|
||||
|
||||
private static final String DETAIL_TYPE = "CloudFormation Stack Status Change";
|
||||
private static final String ALL_STATUS_CHANGES = """
|
||||
{"source": ["aws.cloudformation"], "detail-type": ["%s"]}
|
||||
""".formatted(DETAIL_TYPE);
|
||||
private static final String BUCKET = "stack-status-events-templates";
|
||||
private static final String CHILD_KEY = "child.json";
|
||||
private static final String CHILD_TEMPLATE = """
|
||||
{
|
||||
"Parameters": {"Value": {"Type": "String"}},
|
||||
"Resources": {
|
||||
"ChildTopic": {
|
||||
"Type": "AWS::SNS::Topic",
|
||||
"Properties": {"DisplayName": {"Ref": "Value"}}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
private static final String FAILING_CHILD_KEY = "failing-child.json";
|
||||
private static final String FAILING_CHILD_TEMPLATE = """
|
||||
{
|
||||
"Parameters": {"Value": {"Type": "String"}},
|
||||
"Resources": {
|
||||
"Broken": {"Type": "AWS::CloudFormation::Stack", "Properties": {}}
|
||||
}
|
||||
}
|
||||
""";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String HELD_SERVICE_TOKEN =
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:status-events-held-create";
|
||||
|
||||
@InjectMock
|
||||
LambdaService lambdaService;
|
||||
|
||||
/** The Create of {@link #heldTemplate()}'s custom resource, held until the test releases it. */
|
||||
private CustomResourceProbe.Hold heldCreate;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void holdTheCustomResourcesCreate() {
|
||||
heldCreate = CustomResourceProbe.stub(lambdaService, HELD_SERVICE_TOKEN, "status-events-held-probe")
|
||||
.hold(event -> "Create".equals(event.path("RequestType").asText()));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void releaseHeldCreate() {
|
||||
heldCreate.release();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void uploadChildTemplate() {
|
||||
given().when().put("/" + BUCKET).then().statusCode(200);
|
||||
given().body(CHILD_TEMPLATE).when().put("/" + BUCKET + "/" + CHILD_KEY).then().statusCode(200);
|
||||
given().body(FAILING_CHILD_TEMPLATE).when().put("/" + BUCKET + "/" + FAILING_CHILD_KEY).then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void changeSetsAndDeleteCarryEachOperationsTokenOnTheRootAndNoneOnTheNestedStack() throws Exception {
|
||||
String root = uniqueName("root");
|
||||
String rootId;
|
||||
try (EventRuleQueue queue = EventRuleQueue.route("us-east-1", root, ALL_STATUS_CHANGES)) {
|
||||
rootId = createChangeSet(root, "CREATE", "create", rootTemplate("first"));
|
||||
executeChangeSet(root, "create", "a");
|
||||
CfnStackWaits.awaitStatus(root, "CREATE_COMPLETE");
|
||||
|
||||
createChangeSet(root, "UPDATE", "update", rootTemplate("second"));
|
||||
executeChangeSet(root, "update", "b");
|
||||
CfnStackWaits.awaitStatus(root, "UPDATE_COMPLETE");
|
||||
|
||||
CfnRequests.cfn("DeleteStack", root).formParam("ClientRequestToken", "c")
|
||||
.when().post("/").then().statusCode(200);
|
||||
CfnStackWaits.awaitStatus(rootId, "DELETE_COMPLETE");
|
||||
|
||||
List<JsonNode> events = awaitEvents(queue, rootId, "DELETE_COMPLETE");
|
||||
List<JsonNode> rootEvents = naming(events, rootId);
|
||||
Map<String, Set<String>> tokens = tokensByStatus(rootEvents);
|
||||
|
||||
assertEquals(Set.of(NO_TOKEN), tokens.get("REVIEW_IN_PROGRESS"));
|
||||
assertEquals(Set.of("a"), tokens.get("CREATE_IN_PROGRESS"));
|
||||
assertEquals(Set.of("a"), tokens.get("CREATE_COMPLETE"));
|
||||
assertEquals(Set.of("b"), tokens.get("UPDATE_IN_PROGRESS"));
|
||||
assertEquals(Set.of("b"), tokens.get("UPDATE_COMPLETE"));
|
||||
assertEquals(Set.of("c"), tokens.get("DELETE_IN_PROGRESS"));
|
||||
assertEquals(Set.of("c"), tokens.get("DELETE_COMPLETE"));
|
||||
assertEachStatusOnce(rootEvents);
|
||||
|
||||
List<JsonNode> nested = awaitNested(queue, events, root, "DELETE_COMPLETE");
|
||||
assertThat(tokensByStatus(nested).keySet(), hasItems("CREATE_IN_PROGRESS", "CREATE_COMPLETE",
|
||||
"UPDATE_IN_PROGRESS", "UPDATE_COMPLETE", "DELETE_IN_PROGRESS", "DELETE_COMPLETE"));
|
||||
assertNoTokenOn(nested);
|
||||
assertEachStatusOnce(nested);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A DeleteStack that lands while the create still runs waits for it, and its statuses carry the
|
||||
* delete's token, not the create's, which the stack still held when the delete began.
|
||||
*/
|
||||
@Test
|
||||
void aDeleteLandingMidCreateCarriesItsOwnToken() throws Exception {
|
||||
String stack = uniqueName("mid-create");
|
||||
try (EventRuleQueue queue = EventRuleQueue.route("us-east-1", stack, ALL_STATUS_CHANGES)) {
|
||||
String stackId = createChangeSet(stack, "CREATE", "create", heldTemplate());
|
||||
executeChangeSet(stack, "create", "create-token");
|
||||
assertTrue(heldCreate.awaitRequest(10, TimeUnit.SECONDS), "the custom resource was never created");
|
||||
|
||||
CfnRequests.cfn("DeleteStack", stack).formParam("ClientRequestToken", "delete-token")
|
||||
.when().post("/").then().statusCode(200);
|
||||
heldCreate.release();
|
||||
CfnStackWaits.awaitStatus(stackId, "DELETE_COMPLETE");
|
||||
|
||||
List<JsonNode> events = naming(awaitEvents(queue, stackId, "DELETE_COMPLETE"), stackId);
|
||||
Map<String, Set<String>> tokens = tokensByStatus(events);
|
||||
assertEquals(Set.of("create-token"), tokens.get("CREATE_IN_PROGRESS"));
|
||||
assertEquals(Set.of("delete-token"), tokens.get("DELETE_IN_PROGRESS"));
|
||||
assertEquals(Set.of("delete-token"), tokens.get("DELETE_COMPLETE"));
|
||||
assertEachStatusOnce(events);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEventIsInTheShapeRead() throws Exception {
|
||||
String stack = uniqueName("shape");
|
||||
try (EventRuleQueue queue = EventRuleQueue.route("us-east-1", stack, ALL_STATUS_CHANGES)) {
|
||||
String stackId = createStack(stack, "shape-token", "first");
|
||||
|
||||
JsonNode complete = withStatus(naming(awaitEvents(queue, stackId, "CREATE_COMPLETE"), stackId),
|
||||
"CREATE_COMPLETE").get(0);
|
||||
|
||||
assertEquals("aws.cloudformation", complete.path("source").asText());
|
||||
assertEquals(DETAIL_TYPE, complete.path("detail-type").asText());
|
||||
assertEquals("000000000000", complete.path("account").asText());
|
||||
assertEquals("us-east-1", complete.path("region").asText());
|
||||
assertEquals(1, complete.path("resources").size());
|
||||
assertEquals(stackId, complete.path("resources").get(0).asText());
|
||||
JsonNode detail = complete.path("detail");
|
||||
assertEquals(stackId, detail.path("stack-id").asText());
|
||||
assertEquals("shape-token", detail.path("client-request-token").asText());
|
||||
assertEquals("CREATE_COMPLETE", detail.path("status-details").path("status").asText());
|
||||
assertEquals("", detail.path("status-details").path("detailed-status").asText("absent"));
|
||||
assertEquals("", detail.path("status-details").path("status-reason").asText("absent"));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The root's topic and its record of the nested stack both reach CREATE_COMPLETE on the root, so a
|
||||
* resource's record sent to the bus would show as that status more than once.
|
||||
*/
|
||||
@Test
|
||||
void aResourcesProgressSendsNothing() throws Exception {
|
||||
String root = uniqueName("resources");
|
||||
try (EventRuleQueue queue = EventRuleQueue.route("us-east-1", root, ALL_STATUS_CHANGES)) {
|
||||
String rootId = createStack(root, "resources-token", "first");
|
||||
|
||||
List<JsonNode> events = awaitEvents(queue, rootId, "CREATE_COMPLETE");
|
||||
|
||||
assertEquals(1, withStatus(naming(events, rootId), "CREATE_COMPLETE").size(), () -> "events: " + events);
|
||||
assertEquals(1, withStatus(naming(events, rootId), "CREATE_IN_PROGRESS").size(), () -> "events: " + events);
|
||||
List<String> stackNames = new ArrayList<>();
|
||||
for (JsonNode event : withStatus(events, "CREATE_COMPLETE")) {
|
||||
assertEquals(event.path("detail").path("stack-id").asText(), event.path("resources").get(0).asText());
|
||||
stackNames.add(event.path("detail").path("stack-id").asText().split("/")[1]);
|
||||
}
|
||||
assertThat(stackNames, containsInAnyOrder(root + "-Nested", root));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void createUpdateAndDeleteStackCarryTheirTokens() throws Exception {
|
||||
String stack = uniqueName("direct");
|
||||
try (EventRuleQueue queue = EventRuleQueue.route("us-east-1", stack, ALL_STATUS_CHANGES)) {
|
||||
String stackId = createStack(stack, "direct-create", "first");
|
||||
CfnRequests.cfn("UpdateStack", stack)
|
||||
.formParam("TemplateBody", rootTemplate("second"))
|
||||
.formParam("ClientRequestToken", "direct-update")
|
||||
.when().post("/").then().statusCode(200);
|
||||
CfnStackWaits.awaitStatus(stack, "UPDATE_COMPLETE");
|
||||
CfnRequests.cfn("DeleteStack", stack).formParam("ClientRequestToken", "direct-delete")
|
||||
.when().post("/").then().statusCode(200);
|
||||
|
||||
Map<String, Set<String>> tokens =
|
||||
tokensByStatus(naming(awaitEvents(queue, stackId, "DELETE_COMPLETE"), stackId));
|
||||
|
||||
assertEquals(Set.of("direct-create"), tokens.get("CREATE_IN_PROGRESS"));
|
||||
assertEquals(Set.of("direct-create"), tokens.get("CREATE_COMPLETE"));
|
||||
assertEquals(Set.of("direct-update"), tokens.get("UPDATE_IN_PROGRESS"));
|
||||
assertEquals(Set.of("direct-update"), tokens.get("UPDATE_COMPLETE"));
|
||||
assertEquals(Set.of("direct-delete"), tokens.get("DELETE_IN_PROGRESS"));
|
||||
assertEquals(Set.of("direct-delete"), tokens.get("DELETE_COMPLETE"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anOperationGivenNoTokenDoesNotCarryTheLastOnes() throws Exception {
|
||||
String stack = uniqueName("no-token");
|
||||
try (EventRuleQueue queue = EventRuleQueue.route("us-east-1", stack, ALL_STATUS_CHANGES)) {
|
||||
String stackId = createStack(stack, "had-a-token", "first");
|
||||
CfnRequests.cfn("UpdateStack", stack)
|
||||
.formParam("TemplateBody", rootTemplate("second"))
|
||||
.when().post("/").then().statusCode(200);
|
||||
CfnStackWaits.awaitStatus(stack, "UPDATE_COMPLETE");
|
||||
|
||||
Map<String, Set<String>> tokens =
|
||||
tokensByStatus(naming(awaitEvents(queue, stackId, "UPDATE_COMPLETE"), stackId));
|
||||
|
||||
assertEquals(Set.of("had-a-token"), tokens.get("CREATE_COMPLETE"));
|
||||
assertEquals(Set.of(NO_TOKEN), tokens.get("UPDATE_IN_PROGRESS"));
|
||||
assertEquals(Set.of(NO_TOKEN), tokens.get("UPDATE_COMPLETE"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPatternOnTheStatusSeesOnlyThatStatus() throws Exception {
|
||||
String stack = uniqueName("pattern");
|
||||
String pattern = """
|
||||
{"source": ["aws.cloudformation"], "detail-type": ["%s"],
|
||||
"detail": {"status-details": {"status": ["UPDATE_COMPLETE"]}}}
|
||||
""".formatted(DETAIL_TYPE);
|
||||
try (EventRuleQueue queue = EventRuleQueue.route("us-east-1", stack, pattern)) {
|
||||
String stackId = createStack(stack, "pattern-create", "first");
|
||||
CfnRequests.cfn("UpdateStack", stack)
|
||||
.formParam("TemplateBody", rootTemplate("second"))
|
||||
.formParam("ClientRequestToken", "pattern-update")
|
||||
.when().post("/").then().statusCode(200);
|
||||
CfnStackWaits.awaitStatus(stack, "UPDATE_COMPLETE");
|
||||
|
||||
List<JsonNode> events = awaitEvents(queue, stackId, "UPDATE_COMPLETE");
|
||||
|
||||
assertEquals(Set.of("UPDATE_COMPLETE"), tokensByStatus(naming(events, stackId)).keySet());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStateMachinesTaskNamesTheDeploy() throws Exception {
|
||||
String stack = uniqueName("task");
|
||||
try (EventRuleQueue queue = EventRuleQueue.route("us-east-1", stack, ALL_STATUS_CHANGES)) {
|
||||
String stackId = createStack(stack, "task-create", "first");
|
||||
createChangeSet(stack, "UPDATE", "by-task", rootTemplate("second"));
|
||||
ObjectNode parameters = MAPPER.createObjectNode().put("StackName", stack)
|
||||
.put("ChangeSetName", "by-task").put("ClientRequestToken", "swb-d1");
|
||||
ObjectNode task = MAPPER.createObjectNode().put("Type", "Task")
|
||||
.put("Resource", "arn:aws:states:::aws-sdk:cloudformation:executeChangeSet")
|
||||
.put("End", true);
|
||||
task.set("Parameters", parameters);
|
||||
ObjectNode definition = MAPPER.createObjectNode().put("StartAt", "Execute");
|
||||
definition.putObject("States").set("Execute", task);
|
||||
String stateMachineArn = StepFunctionsRequests.sfn("CreateStateMachine", Map.of(
|
||||
"name", stack, "definition", definition.toString(),
|
||||
"roleArn", "arn:aws:iam::000000000000:role/test-role"))
|
||||
.then().statusCode(200).extract().path("stateMachineArn");
|
||||
String executionArn = StepFunctionsRequests.sfn("StartExecution",
|
||||
Map.of("stateMachineArn", stateMachineArn, "input", "{}"))
|
||||
.then().statusCode(200).extract().path("executionArn");
|
||||
assertEquals("SUCCEEDED",
|
||||
StepFunctionsExecutions.waitForTerminalState(executionArn).jsonPath().getString("status"));
|
||||
CfnStackWaits.awaitStatus(stack, "UPDATE_COMPLETE");
|
||||
|
||||
Map<String, Set<String>> tokens =
|
||||
tokensByStatus(naming(awaitEvents(queue, stackId, "UPDATE_COMPLETE"), stackId));
|
||||
|
||||
assertEquals(Set.of("swb-d1"), tokens.get("UPDATE_COMPLETE"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedCreateCarriesItsTokenThroughItsRollback() throws Exception {
|
||||
String root = uniqueName("failed-create");
|
||||
try (EventRuleQueue queue = EventRuleQueue.route("us-east-1", root, ALL_STATUS_CHANGES)) {
|
||||
String rootId = createChangeSet(root, "CREATE", "create", rootTemplate("first", FAILING_CHILD_KEY));
|
||||
executeChangeSet(root, "create", "fc-create");
|
||||
CfnStackWaits.awaitStatus(root, "ROLLBACK_COMPLETE");
|
||||
|
||||
List<JsonNode> events = awaitEvents(queue, rootId, "ROLLBACK_COMPLETE");
|
||||
List<JsonNode> rootEvents = naming(events, rootId);
|
||||
Map<String, Set<String>> tokens = tokensByStatus(rootEvents);
|
||||
|
||||
assertEquals(Set.of(NO_TOKEN), tokens.get("REVIEW_IN_PROGRESS"));
|
||||
assertEquals(Set.of("fc-create"), tokens.get("CREATE_IN_PROGRESS"));
|
||||
assertEquals(Set.of("fc-create"), tokens.get("ROLLBACK_IN_PROGRESS"));
|
||||
assertEquals(Set.of("fc-create"), tokens.get("ROLLBACK_COMPLETE"));
|
||||
assertEquals(Set.of("REVIEW_IN_PROGRESS", "CREATE_IN_PROGRESS", "ROLLBACK_IN_PROGRESS", "ROLLBACK_COMPLETE"),
|
||||
tokens.keySet());
|
||||
assertEachStatusOnce(rootEvents);
|
||||
assertFalse(withStatus(rootEvents, "ROLLBACK_IN_PROGRESS").get(0).path("detail").path("status-details")
|
||||
.path("status-reason").asText().isEmpty());
|
||||
List<JsonNode> nested = nestedEvents(events, root);
|
||||
assertNoTokenOn(nested);
|
||||
assertEquals(Set.of("CREATE_IN_PROGRESS", "CREATE_FAILED", "DELETE_IN_PROGRESS", "DELETE_COMPLETE"),
|
||||
tokensByStatus(nested).keySet());
|
||||
assertEachStatusOnce(nested);
|
||||
|
||||
CfnRequests.cfn("DeleteStack", root).formParam("ClientRequestToken", "fc-delete")
|
||||
.when().post("/").then().statusCode(200);
|
||||
assertEquals(Set.of("fc-delete"), tokensByStatus(naming(awaitEvents(queue, rootId, "DELETE_COMPLETE"), rootId))
|
||||
.get("DELETE_COMPLETE"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedUpdateCarriesItsTokenThroughItsRollback() throws Exception {
|
||||
String root = uniqueName("failed-update");
|
||||
try (EventRuleQueue queue = EventRuleQueue.route("us-east-1", root, ALL_STATUS_CHANGES)) {
|
||||
String rootId = createStack(root, "fu-create", "first");
|
||||
createChangeSet(root, "UPDATE", "update", rootTemplate("second", FAILING_CHILD_KEY));
|
||||
executeChangeSet(root, "update", "fu-update");
|
||||
CfnStackWaits.awaitStatus(root, "UPDATE_ROLLBACK_COMPLETE");
|
||||
|
||||
List<JsonNode> events = awaitEvents(queue, rootId, "UPDATE_ROLLBACK_COMPLETE");
|
||||
Map<String, Set<String>> tokens = tokensByStatus(naming(events, rootId));
|
||||
|
||||
assertEquals(Set.of("fu-create"), tokens.get("CREATE_COMPLETE"));
|
||||
assertEquals(Set.of("fu-update"), tokens.get("UPDATE_IN_PROGRESS"));
|
||||
assertEquals(Set.of("fu-update"), tokens.get("UPDATE_ROLLBACK_IN_PROGRESS"));
|
||||
assertEquals(Set.of("fu-update"), tokens.get("UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS"));
|
||||
assertEquals(Set.of("fu-update"), tokens.get("UPDATE_ROLLBACK_COMPLETE"));
|
||||
assertEquals(List.of(), withStatus(events, "UPDATE_FAILED"));
|
||||
assertEachStatusOnce(naming(events, rootId));
|
||||
List<JsonNode> nested = nestedEvents(events, root);
|
||||
assertNoTokenOn(nested);
|
||||
assertThat(tokensByStatus(nested).keySet(), hasItems("UPDATE_IN_PROGRESS", "UPDATE_ROLLBACK_IN_PROGRESS",
|
||||
"UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS", "UPDATE_ROLLBACK_COMPLETE"));
|
||||
assertEachStatusOnce(nested);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A parameter that cannot be fetched fails the update at execute, before any resource: the same
|
||||
* rollback as a failure in a resource, so the same statuses on the bus. Delivery is in order, so
|
||||
* an UPDATE_FAILED sent would be on the queue ahead of the rollback's last status.
|
||||
*/
|
||||
@Test
|
||||
void anUpdateFailingOutsideAResourceSendsNoUpdateFailed() throws Exception {
|
||||
String stack = uniqueName("failed-execute");
|
||||
String template = rootTemplate("first").replaceFirst("\\{", """
|
||||
{
|
||||
"Parameters": {
|
||||
"Missing": {
|
||||
"Type": "AWS::SSM::Parameter::Value<String>",
|
||||
"Default": "/stack-status-events/no-such-parameter"
|
||||
}
|
||||
},
|
||||
""");
|
||||
try (EventRuleQueue queue = EventRuleQueue.route("us-east-1", stack, ALL_STATUS_CHANGES)) {
|
||||
String stackId = createStack(stack, "fe-create", "first");
|
||||
createChangeSet(stack, "UPDATE", "update", template);
|
||||
executeChangeSet(stack, "update", "fe-update");
|
||||
CfnStackWaits.awaitStatus(stack, "UPDATE_ROLLBACK_COMPLETE");
|
||||
|
||||
List<JsonNode> rootEvents = naming(awaitEvents(queue, stackId, "UPDATE_ROLLBACK_COMPLETE"), stackId);
|
||||
Map<String, Set<String>> tokens = tokensByStatus(rootEvents);
|
||||
|
||||
assertEquals(List.of(), withStatus(rootEvents, "UPDATE_FAILED"));
|
||||
assertEquals(Set.of("fe-update"), tokens.get("UPDATE_IN_PROGRESS"));
|
||||
assertEquals(Set.of("fe-update"), tokens.get("UPDATE_ROLLBACK_IN_PROGRESS"));
|
||||
assertEquals(Set.of("fe-update"), tokens.get("UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS"));
|
||||
assertEquals(Set.of("fe-update"), tokens.get("UPDATE_ROLLBACK_COMPLETE"));
|
||||
assertEachStatusOnce(rootEvents);
|
||||
}
|
||||
}
|
||||
|
||||
/** Green with or without the events: it keeps delivery from ever failing the stack. */
|
||||
@Test
|
||||
void aTargetThatCannotBeDeliveredToLeavesTheStackAlone() {
|
||||
String stack = uniqueName("undeliverable");
|
||||
String events = "application/x-amz-json-1.1";
|
||||
given().header("X-Amz-Target", "AWSEvents.PutRule").contentType(events)
|
||||
.body(MAPPER.createObjectNode().put("Name", stack).put("EventPattern", ALL_STATUS_CHANGES).toString())
|
||||
.when().post("/").then().statusCode(200);
|
||||
ObjectNode targets = MAPPER.createObjectNode().put("Rule", stack);
|
||||
targets.putArray("Targets").addObject().put("Id", "1")
|
||||
.put("Arn", "arn:aws:sqs:us-east-1:000000000000:no-such-queue-" + stack);
|
||||
given().header("X-Amz-Target", "AWSEvents.PutTargets").contentType(events).body(targets.toString())
|
||||
.when().post("/").then().statusCode(200);
|
||||
try {
|
||||
createStack(stack, "undeliverable-token", "first");
|
||||
} finally {
|
||||
ObjectNode remove = MAPPER.createObjectNode().put("Rule", stack);
|
||||
remove.putArray("Ids").add("1");
|
||||
given().header("X-Amz-Target", "AWSEvents.RemoveTargets").contentType(events).body(remove.toString())
|
||||
.when().post("/").then().statusCode(200);
|
||||
given().header("X-Amz-Target", "AWSEvents.DeleteRule").contentType(events)
|
||||
.body(MAPPER.createObjectNode().put("Name", stack).toString())
|
||||
.when().post("/").then().statusCode(200);
|
||||
}
|
||||
}
|
||||
|
||||
private static final String NO_TOKEN = "(no key)";
|
||||
|
||||
private static String uniqueName(String prefix) {
|
||||
return "status-" + prefix + "-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
}
|
||||
|
||||
private static String rootTemplate(String childValue) {
|
||||
return rootTemplate(childValue, CHILD_KEY);
|
||||
}
|
||||
|
||||
private static String rootTemplate(String childValue, String childKey) {
|
||||
return """
|
||||
{
|
||||
"Resources": {
|
||||
"RootTopic": {
|
||||
"Type": "AWS::SNS::Topic",
|
||||
"Properties": {"DisplayName": "root"}
|
||||
},
|
||||
"Nested": {
|
||||
"Type": "AWS::CloudFormation::Stack",
|
||||
"Properties": {
|
||||
"TemplateURL": "https://s3.amazonaws.com/%2$s/%3$s",
|
||||
"Parameters": {"Value": "%1$s"}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(childValue, BUCKET, childKey);
|
||||
}
|
||||
|
||||
private static String createStack(String name, String token, String childValue) {
|
||||
String xml = CfnRequests.cfn("CreateStack", name)
|
||||
.formParam("TemplateBody", rootTemplate(childValue))
|
||||
.formParam("ClientRequestToken", token)
|
||||
.when().post("/").then().statusCode(200).extract().asString();
|
||||
CfnStackWaits.awaitStatus(name, "CREATE_COMPLETE");
|
||||
return XmlPath.from(xml).getString("**.find { it.name() == 'StackId' }");
|
||||
}
|
||||
|
||||
/** A stack whose create holds at its custom resource until {@link #heldCreate} is released. */
|
||||
private static String heldTemplate() {
|
||||
return """
|
||||
{
|
||||
"Resources": {
|
||||
"Probe": {"Type": "Custom::HeldCreate", "Properties": {"ServiceToken": "%s"}}
|
||||
}
|
||||
}
|
||||
""".formatted(HELD_SERVICE_TOKEN);
|
||||
}
|
||||
|
||||
private static String createChangeSet(String stack, String type, String changeSet, String template) {
|
||||
String xml = CfnRequests.cfn("CreateChangeSet", stack)
|
||||
.formParam("ChangeSetName", changeSet)
|
||||
.formParam("ChangeSetType", type)
|
||||
.formParam("TemplateBody", template)
|
||||
.when().post("/").then().statusCode(200).extract().asString();
|
||||
return XmlPath.from(xml).getString("**.find { it.name() == 'StackId' }");
|
||||
}
|
||||
|
||||
private static void executeChangeSet(String stack, String changeSet, String token) {
|
||||
CfnRequests.cfn("ExecuteChangeSet", stack)
|
||||
.formParam("ChangeSetName", changeSet)
|
||||
.formParam("ClientRequestToken", token)
|
||||
.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* The events on the queue once {@code stackId} has sent {@code lastStatus}; the bus delivers apart
|
||||
* from the stack operation, so the status DescribeStacks answers can be ahead of the queue. Every
|
||||
* event the queue has held by then is returned, whichever stack it names.
|
||||
*/
|
||||
private static List<JsonNode> awaitEvents(EventRuleQueue queue, String stackId, String lastStatus)
|
||||
throws Exception {
|
||||
List<JsonNode> events = new ArrayList<>();
|
||||
awaitEvents(queue, events, event -> stackId.equals(stackId(event)), stackId, lastStatus);
|
||||
return events;
|
||||
}
|
||||
|
||||
/** The nested stack's events, waiting for {@code lastStatus} since delivery runs in order behind the root's. */
|
||||
private static List<JsonNode> awaitNested(EventRuleQueue queue, List<JsonNode> events, String root,
|
||||
String lastStatus) throws Exception {
|
||||
return awaitEvents(queue, events, event -> isNested(event, root), "the nested stack of " + root, lastStatus);
|
||||
}
|
||||
|
||||
/**
|
||||
* Drains the queue into {@code events} until one of {@code those} carries {@code lastStatus}, and
|
||||
* returns the events that are {@code those}.
|
||||
*/
|
||||
private static List<JsonNode> awaitEvents(EventRuleQueue queue, List<JsonNode> events, Predicate<JsonNode> those,
|
||||
String whose, String lastStatus) throws Exception {
|
||||
long deadline = System.currentTimeMillis() + 10_000;
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
events.addAll(queue.drain());
|
||||
List<JsonNode> matching = events.stream().filter(those).toList();
|
||||
if (matching.stream().anyMatch(event -> lastStatus.equals(status(event)))) {
|
||||
return matching;
|
||||
}
|
||||
Thread.sleep(50);
|
||||
}
|
||||
fail("No " + DETAIL_TYPE + " event with status " + lastStatus + " for " + whose + " within ten seconds; "
|
||||
+ "the queue held: " + events);
|
||||
return List.of();
|
||||
}
|
||||
|
||||
private static List<JsonNode> nestedEvents(List<JsonNode> events, String root) {
|
||||
return events.stream().filter(event -> isNested(event, root)).toList();
|
||||
}
|
||||
|
||||
private static boolean isNested(JsonNode event, String root) {
|
||||
return stackId(event).contains("/" + root + "-Nested/");
|
||||
}
|
||||
|
||||
private static String stackId(JsonNode event) {
|
||||
return event.path("detail").path("stack-id").asText();
|
||||
}
|
||||
|
||||
private static void assertNoTokenOn(List<JsonNode> nested) {
|
||||
assertFalse(nested.isEmpty(), "no event named the nested stack");
|
||||
for (JsonNode event : nested) {
|
||||
assertFalse(event.path("detail").has("client-request-token"), () -> "nested event: " + event);
|
||||
}
|
||||
}
|
||||
|
||||
private static List<JsonNode> naming(List<JsonNode> events, String stackId) {
|
||||
return events.stream()
|
||||
.filter(event -> stackId.equals(event.path("detail").path("stack-id").asText()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static void assertEachStatusOnce(List<JsonNode> events) {
|
||||
List<String> statuses = events.stream().map(CloudFormationStackStatusEventsIntegrationTest::status).toList();
|
||||
assertEquals(new LinkedHashSet<>(statuses).size(), statuses.size(), () -> "statuses: " + statuses);
|
||||
}
|
||||
|
||||
private static List<JsonNode> withStatus(List<JsonNode> events, String status) {
|
||||
return events.stream().filter(event -> status.equals(status(event))).toList();
|
||||
}
|
||||
|
||||
private static String status(JsonNode event) {
|
||||
return event.path("detail").path("status-details").path("status").asText();
|
||||
}
|
||||
|
||||
/** Each status seen, with the tokens its events carried, an event with no key counting as {@link #NO_TOKEN}. */
|
||||
private static Map<String, Set<String>> tokensByStatus(List<JsonNode> events) {
|
||||
Map<String, Set<String>> tokens = new LinkedHashMap<>();
|
||||
for (JsonNode event : events) {
|
||||
JsonNode detail = event.path("detail");
|
||||
tokens.computeIfAbsent(status(event), key -> new LinkedHashSet<>())
|
||||
.add(detail.has("client-request-token") ? detail.path("client-request-token").asText() : NO_TOKEN);
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,8 @@ 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.TimeUnit;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
@@ -24,10 +26,33 @@ import static org.mockito.Mockito.when;
|
||||
* The handler of a custom resource in a stack test. It stands in for the ServiceToken Lambda on a
|
||||
* mocked {@link LambdaService}, keeps every request it is sent, and answers each the way a handler
|
||||
* does: a PUT of its result to the event's {@code ResponseURL}, SUCCESS unless {@link #failOn} names
|
||||
* the request.
|
||||
* the request, and only once {@link #hold} lets it, where one is set.
|
||||
*/
|
||||
final class CustomResourceProbe {
|
||||
|
||||
/** A request {@link #hold} keeps from its answer until the test releases it. */
|
||||
static final class Hold {
|
||||
private final CountDownLatch received = new CountDownLatch(1);
|
||||
private final CountDownLatch released = new CountDownLatch(1);
|
||||
|
||||
/** Whether a held request has arrived within {@code timeout}. */
|
||||
boolean awaitRequest(long timeout, TimeUnit unit) throws InterruptedException {
|
||||
return received.await(timeout, unit);
|
||||
}
|
||||
|
||||
/** Lets the held request answer. Idempotent, so an {@code @AfterEach} can call it. */
|
||||
void release() {
|
||||
released.countDown();
|
||||
}
|
||||
|
||||
private void keep() throws InterruptedException {
|
||||
received.countDown();
|
||||
if (!released.await(10, TimeUnit.SECONDS)) {
|
||||
throw new AssertionError("the test never released the held custom resource request");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private final List<JsonNode> events = new CopyOnWriteArrayList<>();
|
||||
@@ -35,6 +60,8 @@ final class CustomResourceProbe {
|
||||
private volatile Function<JsonNode, Map<String, String>> data;
|
||||
private volatile Predicate<JsonNode> failing = event -> false;
|
||||
private volatile String failureReason;
|
||||
private volatile Predicate<JsonNode> holding = event -> false;
|
||||
private volatile Hold hold;
|
||||
|
||||
private CustomResourceProbe(String physicalId) {
|
||||
this.physicalId = physicalId;
|
||||
@@ -64,6 +91,16 @@ final class CustomResourceProbe {
|
||||
failing = request;
|
||||
}
|
||||
|
||||
/**
|
||||
* Holds the requests {@code request} matches before they are answered, until the returned hold is
|
||||
* released, so a test can act while a stack operation waits on its custom resource.
|
||||
*/
|
||||
Hold hold(Predicate<JsonNode> request) {
|
||||
hold = new Hold();
|
||||
holding = request;
|
||||
return hold;
|
||||
}
|
||||
|
||||
/** Every request so far, in the order it was sent. */
|
||||
List<JsonNode> events() {
|
||||
return events;
|
||||
@@ -75,7 +112,10 @@ final class CustomResourceProbe {
|
||||
.findFirst().orElseThrow(() -> new AssertionError("No " + requestType + " request in " + events));
|
||||
}
|
||||
|
||||
private void answer(JsonNode event) {
|
||||
private void answer(JsonNode event) throws InterruptedException {
|
||||
if (holding.test(event)) {
|
||||
hold.keep();
|
||||
}
|
||||
ObjectNode response = MAPPER.createObjectNode();
|
||||
if (failing.test(event)) {
|
||||
response.put("Status", "FAILED").put("Reason", failureReason);
|
||||
|
||||
Reference in new issue
Block a user