fix(cloudformation): provision a usage plan's throttle, quota and stage throttles (#6419)

* fix(cloudformation): provision a usage plan's throttle, quota and stage throttles

* fix(cloudformation): roll back a usage plan when its stack update fails

* fix(cloudformation): keep a failed usage plan update for its rollback retry

* fix(cloudformation): snapshot a usage plan under its patch lock

* fix(cloudformation): restore a usage plan without a lock-free comparison

* refactor(cloudformation): share the API key and usage plan update rollback through CfnRollback
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-10-26 06:55:14 -04:00
1 parent 0634184f5e
commit e09c0b648f
11 files changed
+1141 -175

No files matched your search

@@ -80,6 +80,7 @@ import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.regex.Pattern;
@@ -133,9 +134,10 @@ public class ApiGatewayService implements ResourceProvider {
private final Object domainNameLock = new Object();
private final Object vpcLinkTagLock = new Object();
/**
* Guards a usage plan patch and delete. A patch writes back the stages, throttle and quota it
* read, so two at once would restore one another's stale values, and a delete between its read
* and its write would be undone.
* Guards a usage plan patch, its delete, the CloudFormation limits replacement, the rollback
* restore and the {@code readUsagePlan} read. A patch writes back what it read, so two at once
* would restore one another's stale values, and a delete between its read and its write would
* be undone.
*/
private final Object usagePlanLock = new Object();
private final TlsCertificateManager certificateManager;
@@ -1546,6 +1548,13 @@ public class ApiGatewayService implements ResourceProvider {
.orElseThrow(() -> new AwsException("NotFoundException", "Invalid Usage Plan ID specified", 404));
}
/** Reads the stored plan under the lock patches hold, so the reader sees one revision of it. */
public <T> T readUsagePlan(String region, String usagePlanId, Function<UsagePlan, T> reader) {
synchronized (usagePlanLock) {
return reader.apply(getUsagePlan(region, usagePlanId));
}
}
public UsagePlan updateUsagePlan(String region, String usagePlanId, List<Map<String, String>> patchOperations) {
synchronized (usagePlanLock) {
UsagePlan plan = getUsagePlan(region, usagePlanId);
@@ -1626,6 +1635,37 @@ public class ApiGatewayService implements ResourceProvider {
return plan;
}
/**
* Replaces a usage plan's stages, throttle and quota wholesale. CloudFormation drives them to the
* template's desired state on update, as it does tags, so a stage the template dropped has to go.
*/
public UsagePlan replaceUsagePlanLimits(String region, String usagePlanId, UsagePlan.Limits limits) {
synchronized (usagePlanLock) {
UsagePlan plan = getUsagePlan(region, usagePlanId);
plan.applyLimits(limits);
usagePlanStore.put(usagePlanKey(region, usagePlanId), plan);
return plan;
}
}
/**
* Sets a usage plan's name, description, stages, throttle, quota and tags to exactly the given
* values, a null description included, which no patch can set. It is for putting back the plan
* as it was before a failed CloudFormation update changed it.
*/
public UsagePlan restoreUsagePlan(String region, String usagePlanId, String name, String description,
UsagePlan.Limits limits, Map<String, String> tags) {
synchronized (usagePlanLock) {
UsagePlan plan = getUsagePlan(region, usagePlanId);
plan.setName(name);
plan.setDescription(description);
plan.applyLimits(limits);
plan.setTags(new HashMap<>(tags));
usagePlanStore.put(usagePlanKey(region, usagePlanId), plan);
return plan;
}
}
public void tagUsagePlan(String region, String usagePlanId, Map<String, String> tags) {
ReservedTags.rejectApiGatewayReservedTagsOnUpdate(tags);
Map<String, String> merged = new HashMap<>(getUsagePlan(region, usagePlanId).getTags());
@@ -66,8 +66,9 @@ public final class UsagePlanLimits {
/**
* The stages, throttle and quota of a {@code CreateUsagePlan} request whose JSON types
* {@link ApiGatewayRequestShapes} has checked. A JSON number is read as API Gateway reads it, and
* text, which only CloudFormation's template values send, is parsed as written.
* {@link ApiGatewayRequestShapes} has checked, or of the same shape as CloudFormation's provisioner
* builds it. A JSON number is read as API Gateway reads it, and text, which only CloudFormation's
* template values send, is parsed as written.
*/
public static Limits fromRequest(Map<String, Object> request) {
Map<?, ?> quotaSettings = request.get("quota") instanceof Map<?, ?> settings ? settings : null;
@@ -72,7 +72,7 @@ public class UsagePlan {
@RegisterForReflection
public record Quota(int limit, int offset, String period) {}
/** A plan's stages, throttle and quota as one value. */
/** A plan's stages, throttle and quota, which CloudFormation replaces as one. */
@RegisterForReflection
public record Limits(List<ApiStage> apiStages, Throttle throttle, Quota quota) {}
}
@@ -1,6 +1,5 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
@@ -67,22 +66,10 @@ public class ApiGatewayApiKeyCfnProvisioner implements CfnResourceProvisioner {
}
create(r, props, ctx);
if (ctx.isUpdate()) {
recordCreatedByUpdate(r, ctx);
CfnRollback.recordCreatedByUpdate(r, ctx, CfnRollback.API_KEY_UPDATE_SNAPSHOT_ATTR);
}
}
/**
* Records that this update created the key because the one at the prior physical id was gone,
* so {@link #rollbackUpdate} can delete it and name the prior id again.
*/
private static void recordCreatedByUpdate(StackResource r, ProvisionContext ctx) {
ObjectNode snapshot = MAPPER.createObjectNode();
snapshot.put("region", ctx.region());
snapshot.put("createdId", r.getPhysicalId());
snapshot.put("priorId", ctx.priorPhysicalId());
r.getAttributes().put(CfnRollback.API_KEY_UPDATE_SNAPSHOT_ATTR, snapshot.toString());
}
private void create(StackResource r, JsonNode props, ProvisionContext ctx) {
String name = ctx.resolveOptional(props, "Name");
if (name == null || name.isBlank()) {
@@ -143,29 +130,15 @@ public class ApiGatewayApiKeyCfnProvisioner implements CfnResourceProvisioner {
// Tags go first: the service refuses a tag change that adds a reserved tag key, and refusing
// it before the patch leaves the key exactly as the stack last committed it.
ApiKey key = existing;
try {
CfnRollback.guarded(r, ctx, false, () -> { }, () -> rollbackUpdate(r), () -> {
if (tagsChanged) {
key = apiGatewayService.replaceApiKeyTags(ctx.region(), existing.getId(), desiredTags);
apiGatewayService.replaceApiKeyTags(ctx.region(), existing.getId(), desiredTags);
}
if (!patches.isEmpty()) {
key = apiGatewayService.updateApiKey(ctx.region(), existing.getId(), patches);
apiGatewayService.updateApiKey(ctx.region(), existing.getId(), patches);
}
} catch (RuntimeException failure) {
// The stack skips rollbackUpdate for a resource whose own update failed, so undo it here.
try {
rollbackUpdate(r);
} catch (RuntimeException restoreFailure) {
r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR,
"Could not roll back the update of API key " + existing.getId() + ": "
+ restoreFailure.getMessage());
if (restoreFailure != failure) {
failure.addSuppressed(restoreFailure);
}
}
throw failure;
}
record(r, key);
});
record(r, existing);
}
/**
@@ -249,14 +222,13 @@ public class ApiGatewayApiKeyCfnProvisioner implements CfnResourceProvisioner {
}
/**
* Undoes the update from the snapshot on the resource, and is also called by {@code update} when
* one of its own mutating calls fails. When the update created the key because
* the one at the prior physical id was gone, the created key is deleted and the resource names
* the prior id again. Otherwise the customer id, description, enabled flag and tags are put
* back, writing only the values where the live key differs from the snapshot, so an update that
* failed before it changed anything writes nothing. With no snapshot on the resource the update
* changed nothing, since every mutating call is preceded by the snapshot or followed by the
* creation record, so there is nothing to undo.
* Undoes the update from the snapshot on the resource, and is also the in-place undo
* {@code update} hands to {@link CfnRollback#guarded}. A key the update created is removed by
* {@link CfnRollback#undoCreatedByUpdate}. Otherwise the customer id, description, enabled flag
* and tags are put back, writing only the values where the live key differs from the snapshot,
* so an update that failed before it changed anything writes nothing. With no snapshot on the
* resource the update changed nothing, since every mutating call is preceded by the snapshot or
* followed by the creation record, so there is nothing to undo.
* A key deleted since the update fails the rollback with NotFoundException, and the stack
* reports the rollback as failed.
*/
@@ -264,29 +236,15 @@ public class ApiGatewayApiKeyCfnProvisioner implements CfnResourceProvisioner {
public boolean rollbackUpdate(StackResource resource) {
// The snapshot is spent only once the restore succeeded: a restore that throws leaves it in
// place for the next attempt instead of reporting a rollback that never happened.
String raw = resource.getAttributes().get(CfnRollback.API_KEY_UPDATE_SNAPSHOT_ATTR);
if (raw == null) {
JsonNode snapshot = CfnRollback.updateSnapshot(resource, CfnRollback.API_KEY_UPDATE_SNAPSHOT_ATTR);
if (snapshot == null) {
return true;
}
JsonNode snapshot;
try {
snapshot = MAPPER.readTree(raw);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Could not read the API key update snapshot for "
+ resource.getLogicalId(), e);
if (CfnRollback.undoCreatedByUpdate(resource, snapshot, CfnRollback.API_KEY_UPDATE_SNAPSHOT_ATTR,
"APIKeyId", (createdId, region) -> delete(TYPE, createdId, region))) {
return true;
}
String region = snapshot.path("region").asText();
String createdId = snapshotText(snapshot, "createdId");
if (createdId != null) {
// Deleted before the resource names the prior id again, so a failed delete leaves the
// resource naming the created key and deleting the stack still removes it.
delete(TYPE, createdId, region);
String priorId = snapshot.path("priorId").asText();
resource.setPhysicalId(priorId);
resource.getAttributes().put("APIKeyId", priorId);
resource.getAttributes().remove(CfnRollback.API_KEY_UPDATE_SNAPSHOT_ATTR);
return true;
}
String id = snapshot.path("id").asText();
ApiKey live = apiGatewayService.getApiKey(region, id);
Map<String, String> tags = new HashMap<>();
@@ -294,18 +252,12 @@ public class ApiGatewayApiKeyCfnProvisioner implements CfnResourceProvisioner {
if (!tags.equals(live.getTags())) {
apiGatewayService.restoreApiKeyTags(region, id, tags);
}
List<Map<String, String>> patches = patchesTo(live, snapshotText(snapshot, "customerId"),
snapshotText(snapshot, "description"), snapshot.path("enabled").asBoolean());
List<Map<String, String>> patches = patchesTo(live, CfnRollback.snapshotText(snapshot, "customerId"),
CfnRollback.snapshotText(snapshot, "description"), snapshot.path("enabled").asBoolean());
if (!patches.isEmpty()) {
apiGatewayService.updateApiKey(region, id, patches);
}
resource.getAttributes().remove(CfnRollback.API_KEY_UPDATE_SNAPSHOT_ATTR);
return true;
}
/** A snapshotted string, or null when the key carried none. */
private static String snapshotText(JsonNode snapshot, String field) {
JsonNode value = snapshot.get(field);
return value == null || value.isNull() ? null : value.asText();
}
}
@@ -1,9 +1,13 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeType;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.ReservedTags;
import io.github.hectorvent.floci.services.apigateway.ApiGatewayService;
import io.github.hectorvent.floci.services.apigateway.UsagePlanLimits;
import io.github.hectorvent.floci.services.apigateway.model.UsagePlan;
import io.github.hectorvent.floci.services.apigateway.model.UsagePlanKey;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
@@ -13,6 +17,7 @@ import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@@ -23,9 +28,10 @@ import java.util.Set;
* {@code AWS::ApiGateway::UsagePlanKey}, backed by {@link ApiGatewayService}.
*
* <p>A usage plan's {@code Ref} and {@code Fn::GetAtt Id} are the plan id. Every plan property is
* mutable, so an update patches the plan in place, adding and removing API stages as the template
* moves them. Throttle and Quota, on the plan and per stage, have no counterpart in
* {@link UsagePlan} and are accepted without effect.
* mutable, so an update patches the name and description in place and replaces the API stages,
* throttle and quota together when any of them changes. The values the plan had are kept on the
* resource so a failed stack update can put them all back. Throttle and quota are stored and
* reported, not enforced.
*
* <p>A usage plan key's {@code Ref} and {@code Fn::GetAtt Id} are {@code <keyId>:<usagePlanId>},
* as on AWS. All three of its properties are createOnly, so a change to any of them is refused as a
@@ -39,6 +45,7 @@ public class ApiGatewayUsagePlanCfnProvisioner implements CfnResourceProvisioner
private static final String USAGE_PLAN = "AWS::ApiGateway::UsagePlan";
private static final String USAGE_PLAN_KEY = "AWS::ApiGateway::UsagePlanKey";
private static final String NOT_FOUND = "NotFoundException";
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String KEY_ID_SEPARATOR = ":";
/** The registry schema's only allowed KeyType. */
private static final String API_KEY_TYPE = "API_KEY";
@@ -70,6 +77,8 @@ public class ApiGatewayUsagePlanCfnProvisioner implements CfnResourceProvisioner
// ──────────────────────────── UsagePlan ────────────────────────────
private void provisionUsagePlan(StackResource r, JsonNode props, ProvisionContext ctx) {
// A snapshot describes the update in flight; one an earlier update left behind is stale.
r.getAttributes().remove(CfnRollback.USAGE_PLAN_UPDATE_SNAPSHOT_ATTR);
if (ctx.isUpdate()) {
// An update re-invokes provision with the prior physical id. Creating unconditionally
// would mint a second plan on every update and orphan the first, which then outlives
@@ -84,23 +93,20 @@ public class ApiGatewayUsagePlanCfnProvisioner implements CfnResourceProvisioner
if (name == null || name.isBlank()) {
name = ctx.generatePhysicalName(r.getLogicalId(), GENERATED_NAME_MAX, false);
}
Map<String, Object> request = new HashMap<>();
Map<String, Object> request = limitsRequest(props, ctx);
request.put("name", name);
request.put("description", ctx.resolveOptional(props, "Description"));
List<Map<String, Object>> apiStages = new ArrayList<>();
for (UsagePlan.ApiStage stage : apiStages(props, ctx)) {
Map<String, Object> entry = new HashMap<>();
entry.put("apiId", stage.apiId());
entry.put("stage", stage.stage());
apiStages.add(entry);
}
request.put("apiStages", apiStages);
request.put("tags", ctx.resolveTags(props, "Tags"));
recordPlan(r, apiGatewayService.createUsagePlan(ctx.region(), request));
if (ctx.isUpdate()) {
CfnRollback.recordCreatedByUpdate(r, ctx, CfnRollback.USAGE_PLAN_UPDATE_SNAPSHOT_ATTR);
}
}
private void updateUsagePlan(StackResource r, UsagePlan existing, JsonNode props, ProvisionContext ctx) {
// Validated before anything changes, so a template the service would refuse leaves the plan as it was.
UsagePlan.Limits desiredLimits = UsagePlanLimits.fromRequest(limitsRequest(props, ctx));
List<Map<String, String>> patches = new ArrayList<>();
// A template that omits UsagePlanName keeps whatever name the plan was created with.
String name = ctx.resolveOptional(props, "UsagePlanName");
@@ -112,70 +118,140 @@ public class ApiGatewayUsagePlanCfnProvisioner implements CfnResourceProvisioner
// The service rejects a null patch value, so a dropped Description clears to "".
patches.add(patch("replace", "/description", description == null ? "" : description));
}
// ApiStages is a set the template owns outright: stages it no longer lists come off the
// plan, stages it adds go on. The service models that as add/remove of "apiId:stage".
List<UsagePlan.ApiStage> desired = apiStages(props, ctx);
List<UsagePlan.ApiStage> current = List.copyOf(existing.getApiStages());
for (UsagePlan.ApiStage stage : current) {
if (!listsStage(desired, stage)) {
patches.add(patch("remove", "/apiStages", stage.apiId() + KEY_ID_SEPARATOR + stage.stage()));
}
}
for (UsagePlan.ApiStage stage : desired) {
if (!listsStage(current, stage)) {
patches.add(patch("add", "/apiStages", stage.apiId() + KEY_ID_SEPARATOR + stage.stage()));
}
}
UsagePlan plan = patches.isEmpty()
? existing
: apiGatewayService.updateUsagePlan(ctx.region(), existing.getId(), patches);
// ApiStages, Throttle and Quota belong to the template outright, so what it no longer lists comes
// off the plan. They are replaced together, and only when one of them changed.
boolean limitsChanged = !desiredLimits.equals(existing.limits());
// The stored tags never include the reserved id-override keys (createUsagePlan strips them),
// so the comparison ignores them too; the service strips them again on the way in.
Map<String, String> desiredTags = ctx.resolveTags(props, "Tags");
if (!ReservedTags.stripApiGatewayReservedTags(desiredTags).equals(plan.getTags())) {
plan = apiGatewayService.replaceUsagePlanTags(ctx.region(), plan.getId(), desiredTags);
boolean tagsChanged = !ReservedTags.stripApiGatewayReservedTags(desiredTags).equals(existing.getTags());
if (!patches.isEmpty() || limitsChanged || tagsChanged) {
r.getAttributes().put(CfnRollback.USAGE_PLAN_UPDATE_SNAPSHOT_ATTR, apiGatewayService.readUsagePlan(
ctx.region(), existing.getId(), plan -> snapshot(plan, ctx.region())));
}
recordPlan(r, plan);
CfnRollback.guarded(r, ctx, false, () -> { }, () -> rollbackUpdate(r), () -> {
if (!patches.isEmpty()) {
apiGatewayService.updateUsagePlan(ctx.region(), existing.getId(), patches);
}
if (limitsChanged) {
apiGatewayService.replaceUsagePlanLimits(ctx.region(), existing.getId(), desiredLimits);
}
if (tagsChanged) {
apiGatewayService.replaceUsagePlanTags(ctx.region(), existing.getId(), desiredTags);
}
});
recordPlan(r, existing);
}
/**
* Whether {@code stages} lists {@code stage}'s API and stage. A stage's method throttle is not part of
* its identity, so a stage throttled through UpdateUsagePlan still matches the template's.
* The name, description, stages with their method throttles, throttle, quota and tags the plan
* has before an in-place update changes them, so {@link #rollbackUpdate} can put them back.
* Written as text before the first mutating call, because the service updates the stored plan in
* place, and built inside {@link ApiGatewayService#readUsagePlan} so a concurrent patch cannot
* land halfway through it.
*/
private static boolean listsStage(List<UsagePlan.ApiStage> stages, UsagePlan.ApiStage stage) {
return stages.stream().anyMatch(listed -> Objects.equals(listed.apiId(), stage.apiId())
&& Objects.equals(listed.stage(), stage.stage()));
private static String snapshot(UsagePlan plan, String region) {
ObjectNode snapshot = MAPPER.createObjectNode();
snapshot.put("region", region);
snapshot.put("id", plan.getId());
snapshot.put("name", plan.getName());
snapshot.put("description", plan.getDescription());
snapshot.set("limits", MAPPER.valueToTree(plan.limits()));
ObjectNode tags = snapshot.putObject("tags");
plan.getTags().forEach(tags::put);
return snapshot.toString();
}
/** The template's ApiStages as (apiId, stage) pairs, in template order. */
private static List<UsagePlan.ApiStage> apiStages(JsonNode props, ProvisionContext ctx) {
List<UsagePlan.ApiStage> stages = new ArrayList<>();
if (props == null || !props.has("ApiStages")) {
/**
* The template's ApiStages, Throttle and Quota in CreateUsagePlan's request shape, which
* {@link UsagePlanLimits#fromRequest} validates for create and update alike.
*/
private static Map<String, Object> limitsRequest(JsonNode props, ProvisionContext ctx) {
Map<String, Object> request = new HashMap<>();
request.put("apiStages", apiStages(props, ctx));
JsonNode throttle = resolved(props, "Throttle", ctx);
if (throttle != null) {
CfnPropertyTypes.requireType("Throttle", throttle, JsonNodeType.OBJECT);
request.put("throttle", throttle(throttle, ctx));
}
JsonNode quota = resolved(props, "Quota", ctx);
if (quota != null) {
CfnPropertyTypes.requireType("Quota", quota, JsonNodeType.OBJECT);
Map<String, Object> settings = new HashMap<>();
putResolved(settings, "limit", quota.path("Limit"), ctx);
putResolved(settings, "offset", quota.path("Offset"), ctx);
putResolved(settings, "period", quota.path("Period"), ctx);
request.put("quota", settings);
}
return request;
}
/** The template's ApiStages in template order, each with its per-method Throttle. */
private static List<Map<String, Object>> apiStages(JsonNode props, ProvisionContext ctx) {
List<Map<String, Object>> stages = new ArrayList<>();
JsonNode resolved = resolved(props, "ApiStages", ctx);
if (resolved == null) {
return stages;
}
JsonNode resolved = ctx.engine().resolveNode(props.get("ApiStages"));
if (resolved == null || resolved.isNull()) {
return stages;
}
if (!resolved.isArray()) {
throw new AwsException("ValidationError", "ApiStages of a usage plan must be a list.", 400);
}
for (JsonNode entry : resolved) {
CfnPropertyTypes.requireType("ApiStages", resolved, JsonNodeType.ARRAY);
for (int i = 0; i < resolved.size(); i++) {
JsonNode entry = resolved.get(i);
// Template validation names a list entry by its index.
CfnPropertyTypes.requireType(String.valueOf(i), entry, JsonNodeType.OBJECT);
String apiId = blankToNull(ctx.engine().resolve(entry.path("ApiId")));
String stage = blankToNull(ctx.engine().resolve(entry.path("Stage")));
if (apiId == null || stage == null) {
throw new AwsException("ValidationError",
"Every ApiStages entry of a usage plan needs both ApiId and Stage.", 400);
}
UsagePlan.ApiStage apiStage = new UsagePlan.ApiStage(apiId, stage);
if (!stages.contains(apiStage)) {
stages.add(apiStage);
Map<String, Object> apiStage = new HashMap<>();
apiStage.put("apiId", apiId);
apiStage.put("stage", stage);
JsonNode methods = entry.path("Throttle");
if (!methods.isMissingNode() && !methods.isNull()) {
CfnPropertyTypes.requireType("Throttle", methods, JsonNodeType.OBJECT);
Map<String, Object> throttles = new LinkedHashMap<>();
for (Map.Entry<String, JsonNode> method : methods.properties()) {
CfnPropertyTypes.requireType(method.getKey(), method.getValue(), JsonNodeType.OBJECT);
throttles.put(method.getKey(), throttle(method.getValue(), ctx));
}
apiStage.put("throttle", throttles);
}
stages.add(apiStage);
}
return stages;
}
private static Map<String, Object> throttle(JsonNode settings, ProvisionContext ctx) {
Map<String, Object> throttle = new HashMap<>();
putResolved(throttle, "burstLimit", settings.path("BurstLimit"), ctx);
putResolved(throttle, "rateLimit", settings.path("RateLimit"), ctx);
return throttle;
}
/**
* {@code props[name]} with its intrinsics resolved, or null when the template leaves it out,
* including through {@code AWS::NoValue}.
*/
private static JsonNode resolved(JsonNode props, String name, ProvisionContext ctx) {
if (props == null || !props.has(name)) {
return null;
}
JsonNode node = ctx.engine().resolveNodeOmittingNoValue(props.get(name));
return node == null || node.isNull() || node.isMissingNode() ? null : node;
}
/**
* A member the template gives is passed on as it resolves, blank included, so the service refuses an
* invalid one instead of reading it as absent; only a missing or null member is left out.
*/
private static void putResolved(Map<String, Object> target, String key, JsonNode value, ProvisionContext ctx) {
if (!value.isMissingNode() && !value.isNull()) {
target.put(key, ctx.engine().resolve(value));
}
}
private UsagePlan findUsagePlan(String region, String usagePlanId) {
try {
return apiGatewayService.getUsagePlan(region, usagePlanId);
@@ -285,6 +361,67 @@ public class ApiGatewayUsagePlanCfnProvisioner implements CfnResourceProvisioner
return patch;
}
/**
* An update that failed after its snapshot may already have changed the plan, and its own undo
* may have failed too, so the engine keeps this attempt for {@link #rollbackUpdate} instead of
* putting the previous resource back over it and losing the snapshot. A failure before the
* snapshot changed nothing and is left to the engine.
*/
@Override
public boolean retainsFailedUpdateState(StackResource resource) {
return resource.getAttributes().containsKey(CfnRollback.USAGE_PLAN_UPDATE_SNAPSHOT_ATTR);
}
/**
* The engine calls this for every resource once a stack update commits, so the snapshot is
* dropped here: the update committed and nothing will roll it back, and a snapshot left behind
* would make a later failure keep its attempt and restore stale values.
*/
@Override
public UpdateCleanupResult completeUpdate(StackResource resource) {
resource.getAttributes().remove(CfnRollback.USAGE_PLAN_UPDATE_SNAPSHOT_ATTR);
return UpdateCleanupResult.notApplicable();
}
/**
* Undoes a usage plan update from the snapshot on the resource, and is also the in-place undo
* {@code updateUsagePlan} hands to {@link CfnRollback#guarded}. A plan the update created is
* removed by {@link CfnRollback#undoCreatedByUpdate}. Otherwise the name, description, stages,
* throttle, quota and tags are put back with one restore, which runs under the service's patch
* lock and is written whether or not the plan already matches the snapshot: a comparison read
* outside that lock could mix two revisions of the plan. With no snapshot on the resource the
* update changed nothing, since every mutating call is preceded by the snapshot or followed by
* the creation record, so there is nothing to undo. A plan deleted since the update fails the
* rollback with NotFoundException, and the stack reports the rollback as failed. A usage plan
* key keeps the default, which answers false.
*/
@Override
public boolean rollbackUpdate(StackResource resource) {
if (!USAGE_PLAN.equals(resource.getResourceType())) {
return false;
}
// The snapshot is spent only once the restore succeeded: a restore that throws leaves it in
// place for the next attempt instead of reporting a rollback that never happened.
JsonNode snapshot = CfnRollback.updateSnapshot(resource, CfnRollback.USAGE_PLAN_UPDATE_SNAPSHOT_ATTR);
if (snapshot == null) {
return true;
}
if (CfnRollback.undoCreatedByUpdate(resource, snapshot, CfnRollback.USAGE_PLAN_UPDATE_SNAPSHOT_ATTR, "Id",
(createdId, region) -> delete(USAGE_PLAN, createdId, region))) {
return true;
}
String region = snapshot.path("region").asText();
String id = snapshot.path("id").asText();
String name = CfnRollback.snapshotText(snapshot, "name");
String description = CfnRollback.snapshotText(snapshot, "description");
UsagePlan.Limits limits = MAPPER.convertValue(snapshot.path("limits"), UsagePlan.Limits.class);
Map<String, String> tags = new HashMap<>();
snapshot.path("tags").properties().forEach(tag -> tags.put(tag.getKey(), tag.getValue().asText()));
apiGatewayService.restoreUsagePlan(region, id, name, description, limits, tags);
resource.getAttributes().remove(CfnRollback.USAGE_PLAN_UPDATE_SNAPSHOT_ATTR);
return true;
}
/** Without this the plan, or the key's membership in it, outlives the stack. */
@Override
public void delete(String resourceType, String physicalId, String region) {
@@ -1,8 +1,14 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import org.jboss.logging.Logger;
import java.util.function.BiConsumer;
/**
* Rollback bookkeeping shared by every {@link CfnResourceProvisioner} and read by
* {@code CloudFormationService}. It lives here so the ownership marker and the cleanup logging
@@ -11,6 +17,7 @@ import org.jboss.logging.Logger;
public final class CfnRollback {
private static final Logger LOG = Logger.getLogger(CfnRollback.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
/**
* Marks a resource whose backing entity this stack created. {@code CloudFormationService} reads
@@ -165,6 +172,15 @@ public final class CfnRollback {
*/
public static final String API_KEY_UPDATE_SNAPSHOT_ATTR = "__FlociApiKeyUpdateSnapshot";
/**
* Holds the name, description, stages with their method throttles, throttle, quota and tags a
* usage plan carried before an in-place update changed them, or the plan an update created because
* the one the stack held was gone, so a failed stack update can put the plan back or delete the
* created one. Written by {@code ApiGatewayUsagePlanCfnProvisioner} before its first in-place
* mutating call or right after that creation, and spent by its {@code rollbackUpdate}.
*/
public static final String USAGE_PLAN_UPDATE_SNAPSHOT_ATTR = "__FlociUsagePlanUpdateSnapshot";
/**
* Holds the role, object prefixes, tagging action and tags a GuardDuty Malware Protection plan
* carried before an in-place update changed them, or the plan an update created because the one
@@ -334,7 +350,8 @@ public final class CfnRollback {
* provisioner whose snapshot a ContinueUpdateRollback still needs after an undo that failed
* carries it in {@link CfnResourceProvisioner#mergeFailedUpdateResourceTracking}.
*
* <p>A compensation that fails is reported, never hidden. A created entity carries
* <p>A compensation that fails is reported, never hidden, and is attached to the failure as
* suppressed unless it rethrows that same exception. A created entity carries
* {@link #ROLLBACK_OWNED_ATTR} while the steps run, so the engine's create rollback deletes it
* (and reports that failing) if the undo here could not, and during an update the entity is
* also listed in the cleanup record, which the engine carries onto the restored resource and
@@ -357,7 +374,9 @@ public final class CfnRollback {
undoCreate.run();
r.getAttributes().remove(ROLLBACK_OWNED_ATTR);
} catch (RuntimeException undo) {
e.addSuppressed(undo);
if (undo != e) {
e.addSuppressed(undo);
}
String reason = "Could not remove " + r.getPhysicalId() + ", created for " + r.getLogicalId()
+ " by a failed update: " + undo.getMessage();
LOG.warn(reason);
@@ -372,7 +391,9 @@ public final class CfnRollback {
try {
undoInPlace.run();
} catch (RuntimeException undo) {
e.addSuppressed(undo);
if (undo != e) {
e.addSuppressed(undo);
}
String reason = "Could not restore " + r.getPhysicalId() + " for " + r.getLogicalId()
+ " after a failed update: " + undo.getMessage();
LOG.warn(reason);
@@ -382,4 +403,58 @@ public final class CfnRollback {
throw e;
}
}
/**
* Records that an update created the entity because the one at the prior physical id was gone,
* so {@link #undoCreatedByUpdate} can delete it and name the prior id again.
*/
public static void recordCreatedByUpdate(StackResource r, ProvisionContext ctx, String snapshotAttr) {
ObjectNode snapshot = MAPPER.createObjectNode();
snapshot.put("region", ctx.region());
snapshot.put("createdId", r.getPhysicalId());
snapshot.put("priorId", ctx.priorPhysicalId());
r.getAttributes().put(snapshotAttr, snapshot.toString());
}
/** The update snapshot held in {@code snapshotAttr}, or null when the resource carries none. */
public static JsonNode updateSnapshot(StackResource resource, String snapshotAttr) {
String raw = resource.getAttributes().get(snapshotAttr);
if (raw == null) {
return null;
}
try {
return MAPPER.readTree(raw);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Could not read the update snapshot " + snapshotAttr + " for "
+ resource.getLogicalId(), e);
}
}
/** A snapshotted string, or null when the field is absent or JSON null. */
public static String snapshotText(JsonNode snapshot, String field) {
JsonNode value = snapshot.get(field);
return value == null || value.isNull() ? null : value.asText();
}
/**
* Undoes an update {@link #recordCreatedByUpdate} recorded: deletes the created entity with
* {@code deleteInRegion}, which takes its id and region, names the prior id again as the physical
* id and in {@code idAttribute}, and spends the snapshot. Returns false, changing nothing, when
* the update did not create the entity.
*/
public static boolean undoCreatedByUpdate(StackResource resource, JsonNode snapshot, String snapshotAttr,
String idAttribute, BiConsumer<String, String> deleteInRegion) {
String createdId = snapshotText(snapshot, "createdId");
if (createdId == null) {
return false;
}
// Deleted before the resource names the prior id again, so a failed delete leaves the
// resource naming the created entity and deleting the stack still removes it.
deleteInRegion.accept(createdId, snapshot.path("region").asText());
String priorId = snapshot.path("priorId").asText();
resource.setPhysicalId(priorId);
resource.getAttributes().put(idAttribute, priorId);
resource.getAttributes().remove(snapshotAttr);
return true;
}
}