fix(cloudformation): delete a custom resource a committed update replaced (#8223)

This commit is contained in:
Mario Toffia authored and GitHub committed 2026-11-13 16:05:42 -04:00
1 parent 2dc93aa087
commit 6341708315
5 files changed
+223 -9

No files matched your search

+6
View File
@@ -1026,6 +1026,12 @@ Lambda. floci supports two shapes:
The handler's `Data` keys resolve through `Fn::GetAtt`, except keys that begin with `__Floci`. Floci
reserves that prefix for its own resource state and ignores such keys.
An update whose handler returned a new `PhysicalResourceId` replaced the resource. Once the update
commits, the stack enters `UPDATE_COMPLETE_CLEANUP_IN_PROGRESS` and the id it replaced gets a
`Delete` carrying the properties it had, with no `OldResourceProperties`, as on AWS. A `Delete` the
handler fails is tried three times, then reported as `DELETE_FAILED`, and the update still completes.
Under `UpdateReplacePolicy: Retain` the replaced id gets no `Delete`.
A failed stack update rolls back a custom resource whose handler was sent an `Update`, as
CloudFormation does. This holds whether the handler applied the update and a later resource failed,
or the handler answered `FAILED` itself. The handler is sent a second `Update` under the same
@@ -170,12 +170,8 @@ public class CustomResourceCfnProvisioner implements CfnResourceProvisioner {
LOG.debugv("Custom resource {0} has no stored ServiceToken; skipping Delete", r.getLogicalId());
return;
}
// A resource stashed before the stack id was recorded has none, and delete() has no stack.
String stackId = stackIdOrMinted(r.getAttributes().get(CR_STACK_ID_ATTR), region,
accountFromArn(serviceToken), "");
try {
JsonNode response = invokeCustomResourceHandler(serviceToken, "Delete", r.getLogicalId(),
r.getResourceType(), r.getPhysicalId(), resourceProperties, null, region, stackId);
JsonNode response = invokeDelete(r, r.getPhysicalId(), resourceProperties, region);
if (!"SUCCESS".equals(response.path("Status").asText("FAILED"))) {
LOG.warnv("Custom resource {0} Delete reported FAILED: {1}",
r.getLogicalId(), response.path("Reason").asText("(no reason given)"));
@@ -186,6 +182,65 @@ public class CustomResourceCfnProvisioner implements CfnResourceProvisioner {
}
}
private JsonNode invokeDelete(StackResource r, String physicalId, ObjectNode resourceProperties, String region) {
String serviceToken = r.getAttributes().get(CR_SERVICE_TOKEN_ATTR);
// A resource stashed before the stack id was recorded has none, and delete() has no stack.
String stackId = stackIdOrMinted(r.getAttributes().get(CR_STACK_ID_ATTR), region,
accountFromArn(serviceToken), "");
return invokeCustomResourceHandler(serviceToken, "Delete", r.getLogicalId(), r.getResourceType(),
physicalId, resourceProperties, null, region, stackId);
}
/** An update whose handler answered a new PhysicalResourceId replaced the resource. */
@Override
public boolean hasReplacementUpdate(StackResource resource) {
return replacedPhysicalId(resource) != null;
}
@Override
public String updateCleanupPhysicalId(StackResource resource) {
return "Retain".equals(resource.getUpdateReplacePolicy()) ? null : replacedPhysicalId(resource);
}
/**
* Sends the id a committed update replaced a Delete with the properties it had, as CloudFormation
* does in UPDATE_COMPLETE_CLEANUP_IN_PROGRESS. One attempt per call: the count lives on the
* snapshot, and a handler that keeps failing leaves the update committed.
*/
@Override
public UpdateCleanupResult completeUpdate(StackResource resource) {
JsonNode snapshot = CfnRollback.updateSnapshot(resource, CfnRollback.CUSTOM_RESOURCE_UPDATE_SNAPSHOT_ATTR);
if (snapshot == null) {
return UpdateCleanupResult.notApplicable();
}
String replacedId = updateCleanupPhysicalId(resource);
if (replacedId == null) {
return new UpdateCleanupResult(true, true, null, 0, null);
}
try {
requireSuccess(invokeDelete(resource, replacedId, (ObjectNode) snapshot.get("properties"),
snapshot.path("region").asText()));
return new UpdateCleanupResult(true, true, replacedId, 0, null);
} catch (AwsException e) {
int attempts = snapshot.path("cleanupAttempts").asInt() + 1;
((ObjectNode) snapshot).put("cleanupAttempts", attempts);
resource.getAttributes().put(CfnRollback.CUSTOM_RESOURCE_UPDATE_SNAPSHOT_ATTR, snapshot.toString());
return new UpdateCleanupResult(true, false, replacedId, attempts, e.getMessage());
}
}
@Override
public void clearUpdate(StackResource resource) {
resource.getAttributes().remove(CfnRollback.CUSTOM_RESOURCE_UPDATE_SNAPSHOT_ATTR);
}
/** The physical id the update replaced, or null when there is no update or it kept its id. */
private static String replacedPhysicalId(StackResource resource) {
JsonNode snapshot = CfnRollback.updateSnapshot(resource, CfnRollback.CUSTOM_RESOURCE_UPDATE_SNAPSHOT_ATTR);
String priorPhysicalId = snapshot == null ? null : CfnRollback.snapshotText(snapshot, "physicalId");
return priorPhysicalId == null || priorPhysicalId.equals(resource.getPhysicalId()) ? null : priorPhysicalId;
}
@Override
public boolean rollbackUpdate(StackResource resource) {
return rollbackUpdate(resource, event -> { });
@@ -25,7 +25,9 @@ import static org.junit.jupiter.api.Assertions.fail;
/**
* 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.
* the old properties, so it can undo what the first one applied. A committed update whose handler
* answered a new PhysicalResourceId replaced the resource, and its cleanup phase sends the old id a
* {@code Delete}.
*
* <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
@@ -138,6 +140,63 @@ class CloudFormationCustomResourceRollbackIntegrationTest {
assertEquals(physicalId, probe.events().get(3).get("PhysicalResourceId").asText());
}
@Test
void committedReplacementSendsTheReplacedIdADeleteInTheCleanupPhase() throws InterruptedException {
probe.physicalId(event -> "probe-" + event.get("ResourceProperties").get("Revision").asText());
String stackName = "cr-replaced-" + Long.toString(System.nanoTime(), 36);
String stackId = createStack(stackName, template("1", false));
awaitStackStatus(stackId, "CREATE_COMPLETE");
updateStack(stackName, template("2", false));
awaitStackStatus(stackId, "UPDATE_COMPLETE");
assertEquals(List.of("Create:1", "Update:2", "Delete:1"), requests());
JsonNode delete = probe.events().get(2);
assertProperties(delete, "1", null);
assertEquals("probe-1", delete.get("PhysicalResourceId").asText());
assertEquals(stackId, delete.get("StackId").asText());
assertEquals("probe-2", physicalIdUnauthenticated(stackName, "Probe"));
String events = describeStackEvents(stackId);
assertTrue(events.contains("UPDATE_COMPLETE_CLEANUP_IN_PROGRESS"), events);
List<String> probeEvents = probeEvents(stackId);
assertEquals(List.of("UPDATE_IN_PROGRESS:probe-1", "UPDATE_COMPLETE:probe-2",
"DELETE_IN_PROGRESS:probe-1", "DELETE_COMPLETE:probe-1"),
probeEvents.subList(probeEvents.size() - 4, probeEvents.size()));
}
@Test
void replacedIdWhoseDeleteFailsDoesNotFailTheUpdate() throws InterruptedException {
probe.physicalId(event -> "probe-" + event.get("ResourceProperties").get("Revision").asText());
failOn("Delete:1", "still in use");
String stackName = "cr-replaced-failed-" + Long.toString(System.nanoTime(), 36);
String stackId = createStack(stackName, template("1", false));
awaitStackStatus(stackId, "CREATE_COMPLETE");
updateStack(stackName, template("2", false));
awaitStackStatus(stackId, "UPDATE_COMPLETE");
assertEquals(List.of("Create:1", "Update:2", "Delete:1", "Delete:1", "Delete:1"), requests());
List<Map<String, String>> failures = XmlParser.extractGroups(describeStackEvents(stackId), "member")
.stream()
.filter(e -> "Probe".equals(e.get("LogicalResourceId")))
.filter(e -> "DELETE_FAILED".equals(e.get("ResourceStatus")))
.toList();
assertEquals(1, failures.size(), failures.toString());
assertEquals("probe-1", failures.get(0).get("PhysicalResourceId"));
assertTrue(failures.get(0).get("ResourceStatusReason").contains("still in use"), failures.toString());
assertEquals("probe-2", physicalIdUnauthenticated(stackName, "Probe"));
}
/** The Probe's stack events, oldest first, as their ResourceStatus and PhysicalResourceId. */
private static List<String> probeEvents(String stackId) {
return XmlParser.extractGroups(describeStackEvents(stackId), "member")
.reversed()
.stream()
.filter(e -> "Probe".equals(e.get("LogicalResourceId")))
.map(e -> e.get("ResourceStatus") + ":" + e.get("PhysicalResourceId"))
.toList();
}
/**
* Asserts the request's complete ResourceProperties, and its OldResourceProperties or, when
* {@code oldRevision} is null, that it carries none.
@@ -56,7 +56,7 @@ final class CustomResourceProbe {
private static final ObjectMapper MAPPER = new ObjectMapper();
private final List<JsonNode> events = new CopyOnWriteArrayList<>();
private final String physicalId;
private volatile Function<JsonNode, String> physicalId;
private volatile Function<JsonNode, Map<String, String>> data;
private volatile Predicate<JsonNode> failing = event -> false;
private volatile String failureReason;
@@ -64,7 +64,7 @@ final class CustomResourceProbe {
private volatile Hold hold;
private CustomResourceProbe(String physicalId) {
this.physicalId = physicalId;
this.physicalId = event -> physicalId;
}
static CustomResourceProbe stub(LambdaService lambdaService, String serviceToken, String physicalId) {
@@ -79,6 +79,12 @@ final class CustomResourceProbe {
return probe;
}
/** Answers each request with the PhysicalResourceId {@code physicalId} builds from it. */
CustomResourceProbe physicalId(Function<JsonNode, String> physicalId) {
this.physicalId = physicalId;
return this;
}
/** Answers each request with the Data {@code data} builds from it. */
CustomResourceProbe data(Function<JsonNode, Map<String, String>> data) {
this.data = data;
@@ -125,7 +131,7 @@ final class CustomResourceProbe {
response.put("RequestId", event.get("RequestId").asText())
.put("StackId", event.get("StackId").asText())
.put("LogicalResourceId", event.get("LogicalResourceId").asText())
.put("PhysicalResourceId", physicalId);
.put("PhysicalResourceId", physicalId.apply(event));
if (data != null) {
response.set("Data", MAPPER.valueToTree(data.apply(event)));
}
@@ -9,6 +9,7 @@ import io.floci.aws.core.common.docker.ContainerReachableEndpoint;
import io.floci.aws.services.cloudformation.model.StackResource;
import io.floci.aws.services.cloudformation.provisioners.CfnResourceDispatcher;
import io.floci.aws.services.cloudformation.provisioners.CfnRollback;
import io.floci.aws.services.cloudformation.provisioners.UpdateCleanupResult;
import io.floci.aws.services.lambda.LambdaService;
import io.floci.aws.services.lambda.model.InvocationType;
import io.floci.aws.services.lambda.model.InvokeResult;
@@ -24,6 +25,7 @@ import java.util.function.Supplier;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -526,6 +528,92 @@ class CustomResourceProvisionerTest {
capturedEvents(2);
}
@Test
void committedReplacementSendsTheReplacedIdADeleteWithItsOldProperties() {
respond(event -> success(replacingId(event), Map.of()));
StackResource updated = update(create(), "bye");
assertTrue(provisioner.hasReplacementUpdate(updated));
assertEquals("phys-123", provisioner.updateCleanupPhysicalId(updated));
UpdateCleanupResult result = provisioner.completeUpdate(updated);
assertTrue(result.applicable());
assertTrue(result.complete());
assertEquals("phys-123", result.previousPhysicalId());
JsonNode delete = capturedEvents(3).get(2);
assertEquals("Delete", delete.get("RequestType").asText());
assertEquals("phys-123", delete.get("PhysicalResourceId").asText());
assertEquals("hi", message(delete, "ResourceProperties"));
assertEquals(SERVICE_TOKEN, delete.path("ResourceProperties").path("ServiceToken").asText());
assertFalse(delete.has("OldResourceProperties"));
assertEquals(STACK_ID, delete.get("StackId").asText());
assertEquals("phys-456", updated.getPhysicalId());
}
@Test
void cleanupDeleteTheHandlerFailsCountsEachAttemptWithItsReason() {
respond(event -> "Delete".equals(event.get("RequestType").asText())
? failed("still in use") : success(replacingId(event), Map.of()));
StackResource updated = update(create(), "bye");
UpdateCleanupResult first = provisioner.completeUpdate(updated);
UpdateCleanupResult second = provisioner.completeUpdate(updated);
assertTrue(first.applicable());
assertFalse(first.complete());
assertEquals("phys-123", first.previousPhysicalId());
assertEquals(1, first.attempts());
assertTrue(first.failureReason().contains("still in use"), first.failureReason());
assertEquals(2, second.attempts());
capturedEvents(4);
}
@Test
void clearedReplacementOwesNoCleanup() {
respond(event -> success(replacingId(event), Map.of()));
StackResource updated = update(create(), "bye");
provisioner.clearUpdate(updated);
assertFalse(provisioner.hasReplacementUpdate(updated));
assertFalse(updated.getAttributes().containsKey(CfnRollback.CUSTOM_RESOURCE_UPDATE_SNAPSHOT_ATTR));
}
@Test
void replacementUnderUpdateReplacePolicyRetainSendsNoDelete() {
respond(event -> success(replacingId(event), Map.of()));
StackResource updated = update(create(), "bye");
updated.setUpdateReplacePolicy("Retain");
assertTrue(provisioner.hasReplacementUpdate(updated));
assertNull(provisioner.updateCleanupPhysicalId(updated));
UpdateCleanupResult result = provisioner.completeUpdate(updated);
assertTrue(result.applicable());
assertTrue(result.complete());
capturedEvents(2);
}
@Test
void committedInPlaceUpdateOwesNoCleanup() {
stubHandler("phys-123", Map.of());
StackResource updated = update(create(), "bye");
assertFalse(provisioner.hasReplacementUpdate(updated));
assertNull(provisioner.updateCleanupPhysicalId(updated));
UpdateCleanupResult result = provisioner.completeUpdate(updated);
assertTrue(result.applicable());
assertTrue(result.complete());
assertNull(result.previousPhysicalId());
capturedEvents(2);
}
/** The id a handler that replaces its resource on the "bye" update answers. */
private static String replacingId(JsonNode event) {
return "bye".equals(message(event, "ResourceProperties")) ? "phys-456" : "phys-123";
}
private List<JsonNode> capturedEvents(int count) {
ArgumentCaptor<byte[]> payloads = ArgumentCaptor.forClass(byte[].class);
verify(lambdaService, times(count)).invoke(any(), eq(SERVICE_TOKEN), payloads.capture(),