mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cloudformation): roll back a changed custom resource (#4941)
When a stack update sent a custom resource's handler an Update and the update then failed, Floci never told the handler. If a later resource failed, the rollback recorded "Rollback is not implemented for Custom::..." and the stack ended UPDATE_ROLLBACK_FAILED with the handler's change still applied. If the handler failed its own Update, Floci put the previous resource back in silence. In both cases CloudFormation sends the handler a second Update with the previous properties so it can undo the change. CustomResourceCfnProvisioner now snapshots the resource before an Update reaches its handler: the prior physical id, the old and the attempted properties, the region and the Data attributes, under the new CUSTOM_RESOURCE_UPDATE_SNAPSHOT_ATTR. A stale snapshot from an earlier update is dropped first, so an update that sends nothing needs no rollback. The ServiceToken is checked as Lambda's Invoke checks it before the snapshot is written, so an Update rejected before it reaches any handler is restored as before and sends no rollback request. While the snapshot is held, retainsFailedUpdateState answers true, so an Update the handler failed keeps its copy for the rollback walker instead of being restored over. Its rollbackUpdate spends the snapshot: - the physical id was kept: report UPDATE_IN_PROGRESS and send Update with the old properties as ResourceProperties and the attempted ones as OldResourceProperties, under the same physical id and stack id. On SUCCESS the Data attributes are replaced by the response's. A response naming another id is taken, and the id that was sent gets a best effort Delete with the attempted properties at once, since Floci has no rollback cleanup phase. - the handler replaced the resource: send a best effort Delete for the new id with the attempted properties and point the resource back at the old id and attributes, with no Update. CloudFormation sends this Delete in its cleanup phase; Floci sends it during the rollback. The old properties become the resource's own before the handler is called, as on AWS, which treats the rollback target as the resource's properties even when the handler fails it: a later DeleteStack sends them in its Delete and the next update sends them as OldResourceProperties. A FAILED answer throws with the handler's Reason, so the resource is UPDATE_FAILED and the stack UPDATE_ROLLBACK_FAILED, as on AWS, and the snapshot stays so a retry sends the same Update again.
This commit is contained in:
1 parent
85e0061a6f
commit
e8a300f4d5
5 files changed
+715
-24
No files matched your search
+284
@@ -0,0 +1,284 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.XmlParser;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
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;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* A stack update that changes a custom resource and then fails on a later resource rolls the custom
|
||||
* resource back the way CloudFormation does: the handler is sent a second {@code Update} carrying
|
||||
* the old properties, so it can undo what the first one applied.
|
||||
*
|
||||
* <p>The ServiceToken Lambda is mocked, as in {@code CloudFormationCustomResourceStackIdIntegrationTest},
|
||||
* so no Docker is needed. The mock answers like a real handler, by a PUT of its result to the
|
||||
* event's {@code ResponseURL}.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CloudFormationCustomResourceRollbackIntegrationTest {
|
||||
|
||||
private static final String SERVICE_TOKEN =
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:rollback-probe";
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final List<JsonNode> events = new CopyOnWriteArrayList<>();
|
||||
private volatile String failingRequest;
|
||||
private volatile String failureReason;
|
||||
|
||||
@InjectMock
|
||||
LambdaService lambdaService;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void stubHandler() {
|
||||
when(lambdaService.invoke(any(), eq(SERVICE_TOKEN), any(), eq(InvocationType.RequestResponse)))
|
||||
.thenAnswer(inv -> {
|
||||
JsonNode event = mapper.readTree((byte[]) inv.getArgument(2));
|
||||
events.add(event);
|
||||
putResponse(event);
|
||||
return new InvokeResult(200, null, "null".getBytes(StandardCharsets.UTF_8), null, "req-1");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void laterFailureSendsTheCustomResourceItsOldPropertiesBack() throws InterruptedException {
|
||||
String stackName = "cr-rollback-" + Long.toString(System.nanoTime(), 36);
|
||||
String stackId = createStack(stackName, template("1", false));
|
||||
awaitStackStatus(stackId, "CREATE_COMPLETE");
|
||||
String physicalId = probePhysicalId(stackName);
|
||||
|
||||
updateStack(stackName, template("2", true));
|
||||
awaitStackStatus(stackId, "UPDATE_ROLLBACK_COMPLETE");
|
||||
|
||||
assertEquals(List.of("Create:1", "Update:2", "Update:1"), requests());
|
||||
assertProperties(events.get(0), "1", null);
|
||||
assertProperties(events.get(1), "2", "1");
|
||||
assertProperties(events.get(2), "1", "2");
|
||||
assertEquals(physicalId, events.get(2).get("PhysicalResourceId").asText());
|
||||
assertEquals(physicalId, probePhysicalId(stackName));
|
||||
assertFalse(describeStackEvents(stackId).contains("Rollback is not implemented"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void handlerThatFailsTheRollbackLeavesTheStackUpdateRollbackFailed() throws InterruptedException {
|
||||
failOn("Update:1", "cannot restore revision 1");
|
||||
String stackName = "cr-rollback-failed-" + Long.toString(System.nanoTime(), 36);
|
||||
String stackId = createStack(stackName, template("1", false));
|
||||
awaitStackStatus(stackId, "CREATE_COMPLETE");
|
||||
|
||||
updateStack(stackName, template("2", true));
|
||||
awaitStackStatus(stackId, "UPDATE_ROLLBACK_FAILED");
|
||||
|
||||
assertEquals(List.of("Create:1", "Update:2", "Update:1"), requests());
|
||||
List<Map<String, String>> probeFailures = XmlParser.extractGroups(describeStackEvents(stackId), "member")
|
||||
.stream()
|
||||
.filter(e -> "Probe".equals(e.get("LogicalResourceId")))
|
||||
.filter(e -> "UPDATE_FAILED".equals(e.get("ResourceStatus")))
|
||||
.toList();
|
||||
assertEquals(1, probeFailures.size(), probeFailures.toString());
|
||||
String reason = probeFailures.get(0).get("ResourceStatusReason");
|
||||
assertTrue(reason.contains("cannot restore revision 1"), reason);
|
||||
}
|
||||
|
||||
@Test
|
||||
void customResourceWhoseOwnUpdateFailsIsSentItsOldPropertiesBack() throws InterruptedException {
|
||||
failOn("Update:3", "forced failure for Update v3");
|
||||
String stackName = "cr-own-update-failed-" + Long.toString(System.nanoTime(), 36);
|
||||
String stackId = createStack(stackName, template("1", false));
|
||||
awaitStackStatus(stackId, "CREATE_COMPLETE");
|
||||
String physicalId = probePhysicalId(stackName);
|
||||
|
||||
updateStack(stackName, template("3", false));
|
||||
awaitStackStatus(stackId, "UPDATE_ROLLBACK_COMPLETE");
|
||||
|
||||
assertEquals(List.of("Create:1", "Update:3", "Update:1"), requests());
|
||||
assertProperties(events.get(0), "1", null);
|
||||
assertProperties(events.get(1), "3", "1");
|
||||
assertProperties(events.get(2), "1", "3");
|
||||
assertEquals(physicalId, events.get(2).get("PhysicalResourceId").asText());
|
||||
assertEquals(physicalId, probePhysicalId(stackName));
|
||||
List<String> probeStatuses = XmlParser.extractGroups(describeStackEvents(stackId), "member")
|
||||
.reversed()
|
||||
.stream()
|
||||
.filter(e -> "Probe".equals(e.get("LogicalResourceId")))
|
||||
.map(e -> e.get("ResourceStatus"))
|
||||
.toList();
|
||||
assertEquals(List.of("UPDATE_FAILED", "UPDATE_IN_PROGRESS", "UPDATE_COMPLETE"),
|
||||
probeStatuses.subList(probeStatuses.size() - 3, probeStatuses.size()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteAfterAFailedRollbackSendsTheOldProperties() throws InterruptedException {
|
||||
failOn("Update:1", "cannot restore revision 1");
|
||||
String stackName = "cr-delete-after-failed-" + Long.toString(System.nanoTime(), 36);
|
||||
String stackId = createStack(stackName, template("1", false));
|
||||
awaitStackStatus(stackId, "CREATE_COMPLETE");
|
||||
String physicalId = probePhysicalId(stackName);
|
||||
updateStack(stackName, template("2", true));
|
||||
awaitStackStatus(stackId, "UPDATE_ROLLBACK_FAILED");
|
||||
|
||||
deleteStack(stackName);
|
||||
awaitStackStatus(stackId, "DELETE_COMPLETE");
|
||||
|
||||
assertEquals(List.of("Create:1", "Update:2", "Update:1", "Delete:1"), requests());
|
||||
assertProperties(events.get(3), "1", null);
|
||||
assertEquals(physicalId, events.get(3).get("PhysicalResourceId").asText());
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts the request's complete ResourceProperties, and its OldResourceProperties or, when
|
||||
* {@code oldRevision} is null, that it carries none.
|
||||
*/
|
||||
private void assertProperties(JsonNode event, String revision, String oldRevision) {
|
||||
assertEquals(properties(revision), event.get("ResourceProperties"), event.toString());
|
||||
if (oldRevision == null) {
|
||||
assertFalse(event.has("OldResourceProperties"), event.toString());
|
||||
} else {
|
||||
assertEquals(properties(oldRevision), event.get("OldResourceProperties"), event.toString());
|
||||
}
|
||||
}
|
||||
|
||||
private ObjectNode properties(String revision) {
|
||||
ObjectNode properties = mapper.createObjectNode();
|
||||
properties.put("ServiceToken", SERVICE_TOKEN);
|
||||
properties.put("Revision", revision);
|
||||
return properties;
|
||||
}
|
||||
|
||||
private void failOn(String request, String reason) {
|
||||
failingRequest = request;
|
||||
failureReason = reason;
|
||||
}
|
||||
|
||||
private static String template(String revision, boolean withFailingBucket) {
|
||||
String failingBucket = withFailingBucket
|
||||
? """
|
||||
,
|
||||
"Bad": {
|
||||
"Type": "AWS::S3::Bucket",
|
||||
"DependsOn": "Probe",
|
||||
"Properties": {"BucketName": "bad/name"}
|
||||
}
|
||||
"""
|
||||
: "";
|
||||
return """
|
||||
{
|
||||
"Resources": {
|
||||
"Probe": {
|
||||
"Type": "Custom::RollbackProbe",
|
||||
"Properties": {
|
||||
"ServiceToken": "%s",
|
||||
"Revision": "%s"
|
||||
}
|
||||
}%s
|
||||
}
|
||||
}
|
||||
""".formatted(SERVICE_TOKEN, revision, failingBucket);
|
||||
}
|
||||
|
||||
/** Each request the handler saw, as its RequestType and the Revision it was asked to apply. */
|
||||
private List<String> requests() {
|
||||
return events.stream().map(CloudFormationCustomResourceRollbackIntegrationTest::request).toList();
|
||||
}
|
||||
|
||||
private static String request(JsonNode event) {
|
||||
return event.get("RequestType").asText() + ":" + event.get("ResourceProperties").get("Revision").asText();
|
||||
}
|
||||
|
||||
/**
|
||||
* Answers the request the way a handler does: a PUT of its result document to ResponseURL. The
|
||||
* request the test named with {@link #failOn} is answered FAILED.
|
||||
*/
|
||||
private void putResponse(JsonNode event) {
|
||||
ObjectNode response = mapper.createObjectNode();
|
||||
if (request(event).equals(failingRequest)) {
|
||||
response.put("Status", "FAILED");
|
||||
response.put("Reason", failureReason);
|
||||
} else {
|
||||
response.put("Status", "SUCCESS");
|
||||
}
|
||||
response.put("RequestId", event.get("RequestId").asText());
|
||||
response.put("StackId", event.get("StackId").asText());
|
||||
response.put("LogicalResourceId", event.get("LogicalResourceId").asText());
|
||||
response.put("PhysicalResourceId", "rollback-probe");
|
||||
String path = URI.create(event.get("ResponseURL").asText()).getPath();
|
||||
given().body(response.toString()).when().put(path).then().statusCode(200);
|
||||
}
|
||||
|
||||
private static String createStack(String stackName, String template) {
|
||||
String xml = cfn(Map.of("Action", "CreateStack", "StackName", stackName, "TemplateBody", template));
|
||||
return XmlParser.extractFirst(xml, "StackId", null);
|
||||
}
|
||||
|
||||
private static void updateStack(String stackName, String template) {
|
||||
cfn(Map.of("Action", "UpdateStack", "StackName", stackName, "TemplateBody", template));
|
||||
}
|
||||
|
||||
private static void deleteStack(String stackName) {
|
||||
cfn(Map.of("Action", "DeleteStack", "StackName", stackName));
|
||||
}
|
||||
|
||||
private static String probePhysicalId(String stackName) {
|
||||
String xml = cfn(Map.of("Action", "DescribeStackResource", "StackName", stackName,
|
||||
"LogicalResourceId", "Probe"));
|
||||
return XmlParser.extractFirst(xml, "PhysicalResourceId", null);
|
||||
}
|
||||
|
||||
private static String describeStackEvents(String stackId) {
|
||||
return cfn(Map.of("Action", "DescribeStackEvents", "StackName", stackId));
|
||||
}
|
||||
|
||||
/** Polls DescribeStacks by stack id and returns its XML once the stack reaches {@code status}. */
|
||||
private static String awaitStackStatus(String stackId, String status) throws InterruptedException {
|
||||
String xml = "";
|
||||
long deadline = System.currentTimeMillis() + 10_000;
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
xml = cfn(Map.of("Action", "DescribeStacks", "StackName", stackId));
|
||||
if (xml.contains("<StackStatus>" + status + "</StackStatus>")) {
|
||||
return xml;
|
||||
}
|
||||
Thread.sleep(50);
|
||||
}
|
||||
fail("stack " + stackId + " never reached " + status + ": " + xml);
|
||||
return xml;
|
||||
}
|
||||
|
||||
private static String cfn(Map<String, String> params) {
|
||||
return given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParams(params)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().asString();
|
||||
}
|
||||
}
|
||||
+266
-8
@@ -4,9 +4,11 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerReachableEndpoint;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnRollback;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
@@ -20,6 +22,8 @@ import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
@@ -77,23 +81,54 @@ class CustomResourceProvisionerTest {
|
||||
|
||||
/** Stubs the Lambda to behave like a handler that PUTs a SUCCESS response to the ResponseURL. */
|
||||
private void stubHandler(String physicalId, Map<String, String> data) {
|
||||
respond(event -> success(physicalId, data));
|
||||
}
|
||||
|
||||
/** Stubs the Lambda to PUT, for each event it is sent, the response {@code answer} builds. */
|
||||
private void respond(Function<JsonNode, ObjectNode> answer) {
|
||||
when(lambdaService.invoke(any(), eq(SERVICE_TOKEN), any(), eq(InvocationType.RequestResponse)))
|
||||
.thenAnswer(inv -> {
|
||||
JsonNode event = mapper.readTree((byte[]) inv.getArgument(2));
|
||||
String responseUrl = event.get("ResponseURL").asText();
|
||||
String token = responseUrl.substring(responseUrl.lastIndexOf('/') + 1);
|
||||
|
||||
ObjectNode response = mapper.createObjectNode();
|
||||
response.put("Status", "SUCCESS");
|
||||
response.put("PhysicalResourceId", physicalId);
|
||||
ObjectNode dataNode = response.putObject("Data");
|
||||
data.forEach(dataNode::put);
|
||||
store.complete(token, response);
|
||||
|
||||
store.complete(token, answer.apply(event));
|
||||
return new InvokeResult(200, null, "null".getBytes(), null, "req-1");
|
||||
});
|
||||
}
|
||||
|
||||
private ObjectNode success(String physicalId, Map<String, String> data) {
|
||||
ObjectNode response = mapper.createObjectNode();
|
||||
response.put("Status", "SUCCESS");
|
||||
response.put("PhysicalResourceId", physicalId);
|
||||
ObjectNode dataNode = response.putObject("Data");
|
||||
data.forEach(dataNode::put);
|
||||
return response;
|
||||
}
|
||||
|
||||
private ObjectNode failed(String reason) {
|
||||
ObjectNode response = mapper.createObjectNode();
|
||||
response.put("Status", "FAILED");
|
||||
response.put("Reason", reason);
|
||||
return response;
|
||||
}
|
||||
|
||||
private StackResource create() {
|
||||
return provisioner.provision("MyCr", "Custom::Test", props(),
|
||||
engine(), "us-east-1", "000000000000", "my-stack");
|
||||
}
|
||||
|
||||
private StackResource update(StackResource current, String message) {
|
||||
ObjectNode changed = props();
|
||||
changed.put("Message", message);
|
||||
return provisioner.provision("MyCr", "Custom::Test", changed,
|
||||
engine(), "us-east-1", "000000000000", "my-stack",
|
||||
current.getPhysicalId(), current.getAttributes());
|
||||
}
|
||||
|
||||
private static String message(JsonNode event, String properties) {
|
||||
return event.path(properties).path("Message").asText(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createInvokesHandlerAndCapturesPhysicalIdAndData() {
|
||||
stubHandler("phys-123", Map.of("Greeting", "hello"));
|
||||
@@ -266,6 +301,229 @@ class CustomResourceProvisionerTest {
|
||||
assertTrue(AwsArnUtils.isArnFor(stackId, "cloudformation"), stackId);
|
||||
}
|
||||
|
||||
@Test
|
||||
void changedUpdateRecordsTheRollbackSnapshotBeforeTheHandlerRuns() {
|
||||
respond(event -> "Update".equals(event.get("RequestType").asText())
|
||||
? failed("boom") : success("phys-123", Map.of()));
|
||||
|
||||
StackResource updated = update(create(), "bye");
|
||||
|
||||
assertEquals("CREATE_FAILED", updated.getStatus());
|
||||
assertTrue(updated.getAttributes().containsKey(CfnRollback.CUSTOM_RESOURCE_UPDATE_SNAPSHOT_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rollbackUpdateSendsTheOldPropertiesBackToTheSamePhysicalId() {
|
||||
respond(event -> {
|
||||
String message = message(event, "ResourceProperties");
|
||||
return success("phys-123", "bye".equals(message)
|
||||
? Map.of("Greeting", message, "Farewell", "yes")
|
||||
: Map.of("Greeting", message));
|
||||
});
|
||||
StackResource created = create();
|
||||
String createdStash = created.getAttributes().get("__FlociResourceProperties");
|
||||
StackResource updated = update(created, "bye");
|
||||
List<String> progress = new ArrayList<>();
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(updated, event -> progress.add(event.getResourceStatus())));
|
||||
|
||||
JsonNode rollback = capturedEvents(3).get(2);
|
||||
assertEquals("Update", rollback.get("RequestType").asText());
|
||||
assertEquals("phys-123", rollback.get("PhysicalResourceId").asText());
|
||||
assertEquals("hi", message(rollback, "ResourceProperties"));
|
||||
assertEquals("bye", message(rollback, "OldResourceProperties"));
|
||||
assertEquals(STACK_ID, rollback.get("StackId").asText());
|
||||
assertEquals(List.of("UPDATE_IN_PROGRESS"), progress);
|
||||
assertEquals("phys-123", updated.getPhysicalId());
|
||||
assertEquals(createdStash, updated.getAttributes().get("__FlociResourceProperties"));
|
||||
assertEquals("hi", updated.getAttributes().get("Greeting"));
|
||||
assertFalse(updated.getAttributes().containsKey("Farewell"));
|
||||
assertFalse(updated.getAttributes().containsKey(CfnRollback.CUSTOM_RESOURCE_UPDATE_SNAPSHOT_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rollbackUpdateThatTheHandlerFailsThrowsItsReasonAndKeepsTheSnapshot() {
|
||||
respond(event -> "bye".equals(message(event, "OldResourceProperties"))
|
||||
? failed("cannot undo") : success("phys-123", Map.of()));
|
||||
StackResource updated = update(create(), "bye");
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> provisioner.rollbackUpdate(updated, event -> { }));
|
||||
|
||||
assertTrue(failure.getMessage().contains("cannot undo"), failure.getMessage());
|
||||
assertTrue(updated.getAttributes().containsKey(CfnRollback.CUSTOM_RESOURCE_UPDATE_SNAPSHOT_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void retryOfAFailedRollbackSendsTheSameUpdateAgain() {
|
||||
respond(event -> "bye".equals(message(event, "OldResourceProperties"))
|
||||
? failed("cannot undo") : success("phys-123", Map.of()));
|
||||
StackResource updated = update(create(), "bye");
|
||||
assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(updated, event -> { }));
|
||||
|
||||
assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(updated, event -> { }));
|
||||
|
||||
JsonNode retry = capturedEvents(4).get(3);
|
||||
assertEquals("Update", retry.get("RequestType").asText());
|
||||
assertEquals("hi", message(retry, "ResourceProperties"));
|
||||
assertEquals("bye", message(retry, "OldResourceProperties"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteAfterAFailedRollbackCarriesTheOldProperties() {
|
||||
// AWS treats the rollback target as the resource's properties even though the handler failed it.
|
||||
respond(event -> "bye".equals(message(event, "OldResourceProperties"))
|
||||
? failed("cannot undo") : success("phys-123", Map.of()));
|
||||
StackResource updated = update(create(), "bye");
|
||||
assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(updated, event -> { }));
|
||||
|
||||
provisioner.delete(updated, "us-east-1");
|
||||
|
||||
JsonNode delete = capturedEvents(4).get(3);
|
||||
assertEquals("Delete", delete.get("RequestType").asText());
|
||||
assertEquals("phys-123", delete.get("PhysicalResourceId").asText());
|
||||
assertEquals("hi", message(delete, "ResourceProperties"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedUpdateIsRetainedForRollbackOnlyWhenItReachedTheHandler() {
|
||||
respond(event -> "bye".equals(message(event, "ResourceProperties"))
|
||||
? failed("forced failure") : success("phys-123", Map.of()));
|
||||
StackResource created = create();
|
||||
|
||||
StackResource failed = update(created, "bye");
|
||||
|
||||
assertEquals("CREATE_FAILED", failed.getStatus());
|
||||
assertTrue(provisioner.retainsFailedUpdateState(failed));
|
||||
assertFalse(provisioner.retainsFailedUpdateState(created));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateThatChangesTheServiceTokenFailsBeforeAnyHandlerIsSent() {
|
||||
stubHandler("phys-123", Map.of());
|
||||
StackResource created = create();
|
||||
ObjectNode otherToken = props();
|
||||
otherToken.put("ServiceToken", "arn:aws:lambda:us-east-1:000000000000:function:OtherHandler");
|
||||
|
||||
StackResource failed = provisioner.provision("MyCr", "Custom::Test", otherToken,
|
||||
engine(), "us-east-1", "000000000000", "my-stack",
|
||||
created.getPhysicalId(), created.getAttributes());
|
||||
|
||||
assertEquals("CREATE_FAILED", failed.getStatus());
|
||||
assertEquals("Modifying service token is not allowed.", failed.getStatusReason());
|
||||
assertFalse(provisioner.retainsFailedUpdateState(failed));
|
||||
verify(lambdaService, times(1)).invoke(any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateOfAResourceWithNoStashedPropertiesHasNothingToRollBack() {
|
||||
stubHandler("phys-123", Map.of());
|
||||
StackResource created = create();
|
||||
created.getAttributes().remove("__FlociResourceProperties");
|
||||
|
||||
StackResource updated = update(created, "bye");
|
||||
|
||||
assertFalse(updated.getAttributes().containsKey(CfnRollback.CUSTOM_RESOURCE_UPDATE_SNAPSHOT_ATTR));
|
||||
assertTrue(provisioner.rollbackUpdate(updated, event -> { }));
|
||||
capturedEvents(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rollbackOfAnUpdateTheHandlerFailedSendsTheAttemptedPropertiesAsOld() {
|
||||
respond(event -> "bye".equals(message(event, "ResourceProperties"))
|
||||
? failed("forced failure") : success("phys-123", Map.of()));
|
||||
StackResource created = create();
|
||||
String createdStash = created.getAttributes().get("__FlociResourceProperties");
|
||||
StackResource failed = update(created, "bye");
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(failed, event -> { }));
|
||||
|
||||
JsonNode rollback = capturedEvents(3).get(2);
|
||||
assertEquals("Update", rollback.get("RequestType").asText());
|
||||
assertEquals("phys-123", rollback.get("PhysicalResourceId").asText());
|
||||
assertEquals("hi", message(rollback, "ResourceProperties"));
|
||||
assertEquals("bye", message(rollback, "OldResourceProperties"));
|
||||
assertEquals("phys-123", failed.getPhysicalId());
|
||||
assertEquals(createdStash, failed.getAttributes().get("__FlociResourceProperties"));
|
||||
assertFalse(failed.getAttributes().containsKey(CfnRollback.CUSTOM_RESOURCE_UPDATE_SNAPSHOT_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rollbackSendsTheStackIdTheFailedUpdateWasSent() {
|
||||
respond(event -> "bye".equals(message(event, "ResourceProperties"))
|
||||
? failed("forced failure") : success("phys-123", Map.of()));
|
||||
StackResource created = create();
|
||||
created.getAttributes().remove("__FlociStackId");
|
||||
StackResource failed = update(created, "bye");
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(failed, event -> { }));
|
||||
|
||||
List<JsonNode> events = capturedEvents(3);
|
||||
assertEquals(STACK_ID, events.get(1).get("StackId").asText());
|
||||
assertEquals(STACK_ID, events.get(2).get("StackId").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void dataUnderTheReservedPrefixIsNotKept() {
|
||||
stubHandler("phys-123", Map.of("__FlociStackId", "forged", "Greeting", "hi"));
|
||||
|
||||
StackResource created = create();
|
||||
|
||||
assertEquals(STACK_ID, created.getAttributes().get("__FlociStackId"));
|
||||
assertEquals("hi", created.getAttributes().get("Greeting"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rollbackOfAReplacingUpdateDeletesTheReplacementAndSendsNoUpdate() {
|
||||
respond(event -> {
|
||||
String message = message(event, "ResourceProperties");
|
||||
return success("bye".equals(message) ? "phys-456" : "phys-123", Map.of("Greeting", message));
|
||||
});
|
||||
StackResource created = create();
|
||||
String createdStash = created.getAttributes().get("__FlociResourceProperties");
|
||||
StackResource updated = update(created, "bye");
|
||||
assertEquals("phys-456", updated.getPhysicalId());
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(updated, event -> { }));
|
||||
|
||||
JsonNode delete = capturedEvents(3).get(2);
|
||||
assertEquals("Delete", delete.get("RequestType").asText());
|
||||
assertEquals("phys-456", delete.get("PhysicalResourceId").asText());
|
||||
assertEquals("bye", message(delete, "ResourceProperties"));
|
||||
assertEquals("phys-123", updated.getPhysicalId());
|
||||
assertEquals(createdStash, updated.getAttributes().get("__FlociResourceProperties"));
|
||||
assertEquals("hi", updated.getAttributes().get("Greeting"));
|
||||
assertFalse(updated.getAttributes().containsKey(CfnRollback.CUSTOM_RESOURCE_UPDATE_SNAPSHOT_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rollbackResponseNamingAnotherPhysicalIdIsTakenAndTheIdSentIsDeleted() {
|
||||
respond(event -> success("bye".equals(message(event, "OldResourceProperties"))
|
||||
? "phys-789" : "phys-123", Map.of()));
|
||||
StackResource updated = update(create(), "bye");
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(updated, event -> { }));
|
||||
|
||||
List<JsonNode> events = capturedEvents(4);
|
||||
assertEquals("Update", events.get(2).get("RequestType").asText());
|
||||
JsonNode delete = events.get(3);
|
||||
assertEquals("Delete", delete.get("RequestType").asText());
|
||||
assertEquals("phys-123", delete.get("PhysicalResourceId").asText());
|
||||
assertEquals("bye", message(delete, "ResourceProperties"));
|
||||
assertEquals("phys-789", updated.getPhysicalId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rollbackAfterAnUpdateThatSentNothingSendsNothing() {
|
||||
stubHandler("phys-123", Map.of());
|
||||
StackResource changed = update(create(), "bye");
|
||||
StackResource unchanged = update(changed, "bye");
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(unchanged, event -> { }));
|
||||
|
||||
capturedEvents(2);
|
||||
}
|
||||
|
||||
private List<JsonNode> capturedEvents(int count) {
|
||||
ArgumentCaptor<byte[]> payloads = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(lambdaService, times(count)).invoke(any(), eq(SERVICE_TOKEN), payloads.capture(),
|
||||
|
||||
Reference in new issue
Block a user