mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(cloudformation): provision AWS::IoT::Authorizer (#4830)
* test(cloudformation): cover AWS::IoT::Authorizer against AWS * feat(cloudformation): provision AWS::IoT::Authorizer CloudFormation stubbed AWS::IoT::Authorizer with a fake ARN and created nothing. IotAuthorizerCfnProvisioner now creates a real authorizer through IotAuthorizerService. Ref is the authorizer name and Fn::GetAtt Arn the ARN. A missing AuthorizerFunctionArn fails with the registry's model validation error before any call. Status, EnableCachingForHttp, AuthorizerFunctionArn and the token settings update in place, sending only the declared properties, tags are reconciled, and a failed stack update restores them from a snapshot. Changing AuthorizerName or SigningDisabled replaces the authorizer and deletes the old one once the update commits; a replacement that keeps an explicit name is refused. Delete deactivates the authorizer first and tolerates one already gone. Closes #4822 * chore(cloudformation): move the IoT authorizer snapshot constant It sat at the same insertion point as other pull requests' snapshot constants, so they could not be merged together. * fix(cloudformation): treat only an empty intrinsic result as AWS::NoValue for IoT authorizers * fix(cloudformation): undo an IoT authorizer update whose tag reconcile fails * fix(cloudformation): report a SigningDisabled change on an IoT authorizer as a replacement * fix(cloudformation): create an IoT authorizer over a dispatcher stub and refuse declaring its generated name * fix(cloudformation): refuse an IoT authorizer boolean that is neither true nor false * fix(cloudformation): never delete a dispatcher stub's id in replacement cleanup * fix(cloudformation): tell a stub from a migrated resource and roll back a stub migration that kept its id * fix(cloudformation): name an unnamed IoT authorizer <LogicalId>_<12 chars> as CloudFormation does
This commit is contained in:
1 parent
4fb52e0b07
commit
4be8309e8d
16 files changed
+1995
-13
No files matched your search
+34
-1
@@ -16,6 +16,7 @@ import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Routes each CloudFormation resource to the per-service provisioner that owns its type, through
|
||||
@@ -32,6 +33,9 @@ public class CfnResourceDispatcher {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CfnResourceDispatcher.class);
|
||||
|
||||
/** The prefix of a stub's {@code Arn} attribute: the mark of a resource nothing was created for. */
|
||||
static final String STUB_ARN_PREFIX = "arn:aws:stub:::"; // partition-literal: stub marker for an unowned type, asserted by tests
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final CloudFormationResourceRegistry registry;
|
||||
private final CfnDynamicReferences dynamicReferences;
|
||||
@@ -86,6 +90,12 @@ public class CfnResourceDispatcher {
|
||||
if (owner != null) {
|
||||
owner.provision(resource, properties,
|
||||
new ProvisionContext(engine, region, accountId, stackName, existingPhysicalId, progress));
|
||||
// A provisioner that migrated a stub without writing its own Arn would leave the
|
||||
// stub's, and the real resource would read as a stub on its next update.
|
||||
String arn = resource.getAttributes().get("Arn");
|
||||
if (arn != null && arn.startsWith(STUB_ARN_PREFIX)) {
|
||||
resource.getAttributes().remove("Arn");
|
||||
}
|
||||
} else if (!stubUnsupportedResourceTypesAllowed()) {
|
||||
// Before the physical id below is assigned, so the Cloud Control path sees a
|
||||
// resource with none and reports this message rather than a success. On the stack
|
||||
@@ -106,7 +116,7 @@ public class CfnResourceDispatcher {
|
||||
resource.setStatusReason(unsupportedResourceTypeMessage(resourceType)
|
||||
+ " It was stubbed and nothing was created for it.");
|
||||
resource.setPhysicalId(logicalId + "-" + UUID.randomUUID().toString().substring(0, 8));
|
||||
resource.getAttributes().put("Arn", "arn:aws:stub:::" + logicalId); // partition-literal: stub marker for an unowned type, asserted by tests
|
||||
resource.getAttributes().put("Arn", STUB_ARN_PREFIX + logicalId);
|
||||
}
|
||||
resource.setStatus("CREATE_COMPLETE");
|
||||
} catch (Exception e) {
|
||||
@@ -117,6 +127,29 @@ public class CfnResourceDispatcher {
|
||||
return resource;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this resource is a dispatcher stub, which names nothing that exists: a stub {@code Arn},
|
||||
* the stub's own {@code <LogicalId>-<8 hex>} id and internal {@code __Floci} attributes only.
|
||||
* A real resource an older Floci migrated without dropping the stub's {@code Arn} fails the id
|
||||
* or attribute check, so it does not read as one.
|
||||
*/
|
||||
static boolean isStub(String physicalId, Map<String, String> attributes) {
|
||||
String arn = attributes.get("Arn");
|
||||
if (arn == null || !arn.startsWith(STUB_ARN_PREFIX)) {
|
||||
return false;
|
||||
}
|
||||
String logicalId = arn.substring(STUB_ARN_PREFIX.length());
|
||||
if (physicalId == null || !physicalId.matches(Pattern.quote(logicalId) + "-[0-9a-f]{8}")) {
|
||||
return false;
|
||||
}
|
||||
for (String key : attributes.keySet()) {
|
||||
if (!"Arn".equals(key) && !key.startsWith("__Floci")) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a resource type with no provisioner may be stubbed. The dispatchers hand-built in
|
||||
* unit tests carry no config; absent configuration means the documented default, which here is
|
||||
|
||||
+8
@@ -102,6 +102,14 @@ public final class CfnRollback {
|
||||
*/
|
||||
public static final String REST_API_UPDATE_SNAPSHOT_ATTR = "__FlociRestApiUpdateSnapshot";
|
||||
|
||||
/**
|
||||
* Holds the function ARN, status, caching flag, token settings and tags an IoT authorizer
|
||||
* carried before an in-place update changed them, so a failed stack update can put them back.
|
||||
* Written by {@code IotAuthorizerCfnProvisioner} before its update call and spent by its
|
||||
* {@code rollbackUpdate}.
|
||||
*/
|
||||
public static final String AUTHORIZER_UPDATE_SNAPSHOT_ATTR = "__FlociAuthorizerUpdateSnapshot";
|
||||
|
||||
/**
|
||||
* Holds the customer id, description, enabled flag and tags an API key carried before an
|
||||
* in-place update changed them, or the key an update created because the one the stack held
|
||||
|
||||
+316
@@ -0,0 +1,316 @@
|
||||
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.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.iot.IotAuthorizerService;
|
||||
import io.github.hectorvent.floci.services.iot.model.IotAuthorizer;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Provisions {@code AWS::IoT::Authorizer}. Things, policies and topic rules belong to
|
||||
* {@link IotCfnProvisioner}; this class takes only the authorizer service so the test fixture can
|
||||
* wire it from that service.
|
||||
*
|
||||
* <p>The authorizer name is the physical id and {@code Ref}, generated when the template gives none
|
||||
* and kept across updates; {@code Fn::GetAtt Arn} is the authorizer ARN. The name and
|
||||
* {@code SigningDisabled} are create-only. An update that keeps both changes the authorizer in
|
||||
* place through UpdateAuthorizer, sending only the properties the template declares, so a property
|
||||
* dropped from the template keeps its stored value, reconciles the tags, and keeps what it replaces
|
||||
* on the resource so a failed stack update can put it back. An in-place update whose tag reconcile
|
||||
* fails puts the authorizer back itself before reporting the failure, because the resource the
|
||||
* stack restores never carried that snapshot. An update that changes either, or drops
|
||||
* an explicit name, creates the new authorizer and leaves the displaced one to the
|
||||
* {@link ReplacementCleanup} record; a replacement that would keep an explicit name is refused, as
|
||||
* CloudFormation refuses it for any custom-named resource. Declaring the generated name as an
|
||||
* explicit name is refused the same way, because adding the create-only name is a replacement that
|
||||
* would keep it. A stack created before this provisioner existed holds the dispatcher's stub, which
|
||||
* names no authorizer, so its first update creates the authorizer as a first deploy would. A delete
|
||||
* deactivates the authorizer first, because the API refuses to delete an ACTIVE one.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class IotAuthorizerCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
private static final String TYPE = "AWS::IoT::Authorizer";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final int NAME_MAX_LENGTH = 128;
|
||||
/**
|
||||
* Records whether the name came from the template or was generated, so a later update can tell
|
||||
* an explicit name being dropped, which replaces the authorizer on AWS, from an unnamed
|
||||
* authorizer keeping the name it was given. Read back off the stored attributes.
|
||||
*/
|
||||
private static final String NAME_MODE_ATTR = "FlociAuthorizerNameMode";
|
||||
private static final String NAME_MODE_EXPLICIT = "explicit";
|
||||
private static final String NAME_MODE_GENERATED = "generated";
|
||||
|
||||
private final IotAuthorizerService authorizerService;
|
||||
|
||||
public IotAuthorizerCfnProvisioner(IotAuthorizerService authorizerService) {
|
||||
this.authorizerService = authorizerService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> resourceTypes() {
|
||||
return Set.of(TYPE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void provision(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.AUTHORIZER_UPDATE_SNAPSHOT_ATTR);
|
||||
Map<String, String> attributesBefore = Map.copyOf(r.getAttributes());
|
||||
String functionArn = resolvePresent(props, "AuthorizerFunctionArn", ctx);
|
||||
if (functionArn == null) {
|
||||
// The registry schema's required key, checked before the handler makes any call.
|
||||
throw new AwsException("InvalidRequest",
|
||||
"Model validation failed (#: required key [AuthorizerFunctionArn] not found)", 400);
|
||||
}
|
||||
String explicitName = resolvePresent(props, "AuthorizerName", ctx);
|
||||
boolean hasExplicitName = explicitName != null;
|
||||
String signingDisabled = resolveBoolean(props, "SigningDisabled", ctx);
|
||||
ObjectNode declared = MAPPER.createObjectNode().put("authorizerFunctionArn", functionArn);
|
||||
putIfPresent(declared, "status", resolvePresent(props, "Status", ctx));
|
||||
putIfPresent(declared, "tokenKeyName", resolvePresent(props, "TokenKeyName", ctx));
|
||||
String caching = resolveBoolean(props, "EnableCachingForHttp", ctx);
|
||||
if (caching != null) {
|
||||
declared.put("enableCachingForHttp", Boolean.parseBoolean(caching));
|
||||
}
|
||||
JsonNode keys = props == null ? null : ctx.engine().resolveNode(props.get("TokenSigningPublicKeys"));
|
||||
if (keys != null && keys.isObject()) {
|
||||
ObjectNode present = declared.putObject("tokenSigningPublicKeys");
|
||||
// ponytail: an intrinsic resolving to "" counts as AWS::NoValue and is dropped,
|
||||
// so an empty PEM chosen by Fn::If is not refused; a literal "" still is.
|
||||
for (Map.Entry<String, JsonNode> key : keys.properties()) {
|
||||
boolean literal = props.path("TokenSigningPublicKeys").path(key.getKey()).isTextual();
|
||||
if (literal || !"".equals(key.getValue().textValue())) {
|
||||
present.set(key.getKey(), key.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
Map<String, String> tags = ctx.resolveTags(props, "Tags");
|
||||
|
||||
// A stack from before this type had a provisioner holds the dispatcher's stub here, which
|
||||
// names no authorizer and never recorded a name mode, so the authorizer is created as on a first deploy.
|
||||
boolean updatesAuthorizer = ctx.isUpdate() && attributesBefore.containsKey(NAME_MODE_ATTR);
|
||||
IotAuthorizer prior = updatesAuthorizer
|
||||
? authorizerService.describeAuthorizer(ctx.priorPhysicalId(), ctx.region())
|
||||
: null;
|
||||
// ponytail: compared with the stored flag, so an absent SigningDisabled reads as its API default false.
|
||||
boolean signingChanged = prior != null && prior.isSigningDisabled() != Boolean.parseBoolean(signingDisabled);
|
||||
boolean nameWasGenerated = NAME_MODE_GENERATED.equals(attributesBefore.get(NAME_MODE_ATTR));
|
||||
if ((signingChanged || nameWasGenerated) && hasExplicitName && explicitName.equals(ctx.priorPhysicalId())) {
|
||||
throw new AwsException("ValidationError",
|
||||
"CloudFormation cannot update a stack when a custom-named resource requires "
|
||||
+ "replacing. Rename " + explicitName + " and update the stack again.", 400);
|
||||
}
|
||||
String name = physicalName(r, ctx, explicitName, updatesAuthorizer, signingChanged);
|
||||
|
||||
IotAuthorizer authorizer;
|
||||
if (updatesAuthorizer && ctx.reusesPriorEntity(name)) {
|
||||
snapshotBeforeUpdate(r, prior, ctx.region());
|
||||
authorizer = authorizerService.updateAuthorizer(name, declared, ctx.region());
|
||||
try {
|
||||
reconcileTags(prior, tags);
|
||||
} catch (RuntimeException failure) {
|
||||
unwind(r, name, failure);
|
||||
throw failure;
|
||||
}
|
||||
} else {
|
||||
if (signingDisabled != null) {
|
||||
declared.put("signingDisabled", Boolean.parseBoolean(signingDisabled));
|
||||
}
|
||||
if (!tags.isEmpty()) {
|
||||
ArrayNode tagList = declared.putArray("tags");
|
||||
tags.forEach((key, value) -> tagList.addObject().put("Key", key).put("Value", value));
|
||||
}
|
||||
authorizer = authorizerService.createAuthorizer(name, declared, ctx.region());
|
||||
}
|
||||
r.setPhysicalId(name);
|
||||
r.getAttributes().put("Arn", authorizer.getAuthorizerArn());
|
||||
r.getAttributes().put(NAME_MODE_ATTR, hasExplicitName ? NAME_MODE_EXPLICIT : NAME_MODE_GENERATED);
|
||||
ReplacementCleanup.record(r, ctx, attributesBefore);
|
||||
}
|
||||
|
||||
/**
|
||||
* An in-place update that changed the authorizer and then failed on its tags undoes itself.
|
||||
* CloudFormationService puts the resource the stack held before the attempt back in its place,
|
||||
* and that object never carried the snapshot taken here, so it marks the resource restored and
|
||||
* the rollback walker skips {@link #rollbackUpdate}: without this the stack reports a completed
|
||||
* rollback while the changed authorizer is still live. The stack must report the original
|
||||
* failure, so an unwind that cannot restore is attached to it and recorded as a rollback
|
||||
* failure, which ends the stack in UPDATE_ROLLBACK_FAILED. The unwind repeats the tag calls the
|
||||
* update just made, so it can come back carrying the very exception that interrupted the
|
||||
* update; a throwable cannot be suppressed under itself.
|
||||
*/
|
||||
private void unwind(StackResource r, String name, RuntimeException failure) {
|
||||
try {
|
||||
rollbackUpdate(r);
|
||||
r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR, "true");
|
||||
} catch (RuntimeException unwindFailure) {
|
||||
r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR,
|
||||
"Could not roll back the update of authorizer " + name + ": " + unwindFailure.getMessage());
|
||||
if (unwindFailure != failure) {
|
||||
failure.addSuppressed(unwindFailure);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The resolved property, or null when it is absent or an intrinsic resolved to AWS::NoValue,
|
||||
* which the engine yields as an empty string. A literal string, and an intrinsic result that is
|
||||
* only whitespace, is kept as written.
|
||||
*/
|
||||
private static String resolvePresent(JsonNode props, String name, ProvisionContext ctx) {
|
||||
String value = ctx.resolveOptional(props, name);
|
||||
boolean literal = props != null && props.path(name).isTextual();
|
||||
return literal || (value != null && !value.isEmpty()) ? value : null;
|
||||
}
|
||||
|
||||
/** A present boolean property, refused unless it is true or false rather than read as false. */
|
||||
private static String resolveBoolean(JsonNode props, String name, ProvisionContext ctx) {
|
||||
String value = resolvePresent(props, name, ctx);
|
||||
if (value != null && !"true".equalsIgnoreCase(value) && !"false".equalsIgnoreCase(value)) {
|
||||
throw new AwsException("ValidationError", TYPE + " " + name + " must be true or false, got " + value, 400);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private static void putIfPresent(ObjectNode body, String field, String value) {
|
||||
if (value != null) {
|
||||
body.put(field, value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The template's name when it gives one; otherwise the generated name the authorizer already
|
||||
* has, unless the previous name was explicit or signing changed, since either replaces the
|
||||
* authorizer on AWS, or the prior resource names no authorizer; and a fresh generated name
|
||||
* otherwise. Logical ids only hold characters the IoT name rule allows, and the generator
|
||||
* truncates to its limit.
|
||||
*/
|
||||
private static String physicalName(StackResource r, ProvisionContext ctx, String explicitName,
|
||||
boolean updatesAuthorizer, boolean signingChanged) {
|
||||
if (explicitName != null) {
|
||||
return explicitName;
|
||||
}
|
||||
boolean explicitNameRemoved = ctx.isUpdate()
|
||||
&& NAME_MODE_EXPLICIT.equals(r.getAttributes().get(NAME_MODE_ATTR));
|
||||
if (updatesAuthorizer && !explicitNameRemoved && !signingChanged) {
|
||||
return ctx.priorPhysicalId();
|
||||
}
|
||||
return generatedName(r.getLogicalId());
|
||||
}
|
||||
|
||||
/** CloudFormation names an unnamed authorizer {@code <LogicalId>_<12 chars>}, with no stack prefix. */
|
||||
private static String generatedName(String logicalId) {
|
||||
String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 12);
|
||||
int prefixMax = NAME_MAX_LENGTH - 1 - suffix.length();
|
||||
String prefix = logicalId.length() > prefixMax ? logicalId.substring(0, prefixMax) : logicalId;
|
||||
return prefix + "_" + suffix;
|
||||
}
|
||||
|
||||
private void reconcileTags(IotAuthorizer authorizer, Map<String, String> desired) {
|
||||
List<String> stale = ProvisionContext.staleTagKeys(authorizer.getTags(), desired);
|
||||
if (!stale.isEmpty()) {
|
||||
authorizerService.untagResource(authorizer.getAuthorizerArn(), stale);
|
||||
}
|
||||
if (!desired.isEmpty()) {
|
||||
authorizerService.tagResource(authorizer.getAuthorizerArn(), desired);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps what an in-place update can change, as the UpdateAuthorizer body that puts it back,
|
||||
* with the tags beside it, so {@link #rollbackUpdate} can restore them.
|
||||
*/
|
||||
private static void snapshotBeforeUpdate(StackResource r, IotAuthorizer current, String region) {
|
||||
ObjectNode snapshot = MAPPER.createObjectNode();
|
||||
snapshot.put("region", region);
|
||||
snapshot.put("name", current.getAuthorizerName());
|
||||
ObjectNode restore = snapshot.putObject("body")
|
||||
.put("authorizerFunctionArn", current.getAuthorizerFunctionArn())
|
||||
.put("status", current.getStatus())
|
||||
.put("enableCachingForHttp", current.isEnableCachingForHttp());
|
||||
putIfPresent(restore, "tokenKeyName", current.getTokenKeyName());
|
||||
// ponytail: UpdateAuthorizer merges keys by name, so a key the update added survives a rollback.
|
||||
if (current.getTokenSigningPublicKeys() != null) {
|
||||
restore.set("tokenSigningPublicKeys", MAPPER.valueToTree(current.getTokenSigningPublicKeys()));
|
||||
}
|
||||
snapshot.set("tags", MAPPER.valueToTree(current.getTags()));
|
||||
r.getAttributes().put(CfnRollback.AUTHORIZER_UPDATE_SNAPSHOT_ATTR, snapshot.toString());
|
||||
}
|
||||
|
||||
/** Deactivates, then deletes, as the AWS handler does; an authorizer already gone counts as deleted. */
|
||||
@Override
|
||||
public void delete(String resourceType, String physicalId, String region) {
|
||||
CfnDeletes.safeDelete("IoT authorizer", physicalId, () -> {
|
||||
authorizerService.updateAuthorizer(physicalId,
|
||||
MAPPER.createObjectNode().put("status", "INACTIVE"), region);
|
||||
authorizerService.deleteAuthorizer(physicalId, region);
|
||||
}, "ResourceNotFoundException");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasReplacementUpdate(StackResource resource) {
|
||||
return ReplacementCleanup.hasReplacement(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String updateCleanupPhysicalId(StackResource resource) {
|
||||
return ReplacementCleanup.cleanupPhysicalId(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UpdateCleanupResult completeUpdate(StackResource resource) {
|
||||
return ReplacementCleanup.complete(resource, this::delete);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearUpdate(StackResource resource) {
|
||||
resource.getAttributes().remove(CfnRollback.AUTHORIZER_UPDATE_SNAPSHOT_ATTR);
|
||||
ReplacementCleanup.clear(resource);
|
||||
}
|
||||
|
||||
/**
|
||||
* A replacement is undone through the cleanup record and an in-place update from the snapshot
|
||||
* taken before it. With neither on the resource the provision failed before it changed
|
||||
* anything, so there is nothing to undo.
|
||||
*/
|
||||
@Override
|
||||
public boolean rollbackUpdate(StackResource resource) {
|
||||
if (ReplacementCleanup.rollback(resource, this::delete)) {
|
||||
return true;
|
||||
}
|
||||
// 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.AUTHORIZER_UPDATE_SNAPSHOT_ATTR);
|
||||
if (raw == null) {
|
||||
return true;
|
||||
}
|
||||
JsonNode snapshot;
|
||||
try {
|
||||
snapshot = MAPPER.readTree(raw);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalStateException("Could not read the authorizer update snapshot for "
|
||||
+ resource.getLogicalId(), e);
|
||||
}
|
||||
String region = snapshot.path("region").asText();
|
||||
IotAuthorizer restored = authorizerService.updateAuthorizer(snapshot.path("name").asText(),
|
||||
snapshot.path("body"), region);
|
||||
Map<String, String> tags = new LinkedHashMap<>();
|
||||
snapshot.path("tags").properties().forEach(tag -> tags.put(tag.getKey(), tag.getValue().asText()));
|
||||
reconcileTags(restored, tags);
|
||||
resource.getAttributes().remove(CfnRollback.AUTHORIZER_UPDATE_SNAPSHOT_ATTR);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+21
-10
@@ -52,7 +52,9 @@ public final class ReplacementCleanup {
|
||||
* physical id. Call after the new entity exists, with the attributes the resource carried
|
||||
* before {@code provision} overwrote them: they are what {@link #rollback} puts back. A
|
||||
* provision that replaced nothing drops the rollback fields but keeps any entity an earlier
|
||||
* failed rollback left owed a delete.
|
||||
* failed rollback left owed a delete. A dispatcher stub's id is never listed, because a stub
|
||||
* created nothing, but a stub migration that kept the stub's id still keeps the rollback fields,
|
||||
* because the entity under that id is the one this update created.
|
||||
*/
|
||||
static void record(StackResource r, ProvisionContext ctx, Map<String, String> attributesBeforeProvision) {
|
||||
ObjectNode cleanup = readOrEmpty(r);
|
||||
@@ -60,7 +62,8 @@ public final class ReplacementCleanup {
|
||||
cleanup.remove("priorAttributes");
|
||||
cleanup.put("region", ctx.region());
|
||||
String prior = ctx.priorPhysicalId();
|
||||
if (ctx.isUpdate() && !prior.equals(r.getPhysicalId())) {
|
||||
boolean priorIsStub = CfnResourceDispatcher.isStub(prior, attributesBeforeProvision);
|
||||
if (ctx.isUpdate() && (!prior.equals(r.getPhysicalId()) || priorIsStub)) {
|
||||
cleanup.put("priorPhysicalId", prior);
|
||||
ObjectNode priorAttributes = cleanup.putObject("priorAttributes");
|
||||
attributesBeforeProvision.forEach((key, value) -> {
|
||||
@@ -68,7 +71,9 @@ public final class ReplacementCleanup {
|
||||
priorAttributes.put(key, value);
|
||||
}
|
||||
});
|
||||
addDisplaced(cleanup, prior, r.getResourceType(), ctx.region(), true);
|
||||
if (!priorIsStub) {
|
||||
addDisplaced(cleanup, prior, r.getResourceType(), ctx.region(), true);
|
||||
}
|
||||
}
|
||||
write(r, cleanup);
|
||||
}
|
||||
@@ -76,7 +81,8 @@ public final class ReplacementCleanup {
|
||||
/**
|
||||
* Undoes this update's replacement when a later resource failed the stack update: the resource
|
||||
* names the prior entity again, with the attributes it had, and the replacement is deleted. The
|
||||
* prior entity was displaced, never changed, so nothing is written to it.
|
||||
* prior entity was displaced, never changed, so nothing is written to it. A stub migration that
|
||||
* kept the stub's id still has its entity deleted, because the restored stub created nothing.
|
||||
*
|
||||
* <p>The prior leaves the delete list before the replacement's delete is attempted: it is
|
||||
* standing again, and a resource still owing its delete would put it on the next cleanup's list.
|
||||
@@ -105,7 +111,7 @@ public final class ReplacementCleanup {
|
||||
cleanup.remove("priorAttributes");
|
||||
removeDisplaced(cleanup, prior);
|
||||
write(r, cleanup);
|
||||
if (prior.equals(replacement)) {
|
||||
if (prior.equals(replacement) && !CfnResourceDispatcher.isStub(prior, r.getAttributes())) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
@@ -150,14 +156,14 @@ public final class ReplacementCleanup {
|
||||
if (cleanup == null) {
|
||||
return null;
|
||||
}
|
||||
JsonNode next = nextOwed(cleanup.path("displaced"), r.getPhysicalId(), "Retain".equals(r.getUpdateReplacePolicy()));
|
||||
JsonNode next = nextOwed(cleanup.path("displaced"), liveEntityId(r), "Retain".equals(r.getUpdateReplacePolicy()));
|
||||
return next == null ? null : next.path("physicalId").asText(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* The owed entry with the fewest attempts, ties by list order: the one the engine's retries are
|
||||
* still for. Skips the resource's own entity and, under Retain, the entities a committed
|
||||
* replacement displaced.
|
||||
* still for. Skips the resource's live entity, which a stub has none of, and, under Retain, the
|
||||
* entities a committed replacement displaced.
|
||||
*/
|
||||
private static JsonNode nextOwed(JsonNode displaced, String currentPhysicalId, boolean retain) {
|
||||
JsonNode next = null;
|
||||
@@ -218,12 +224,13 @@ public final class ReplacementCleanup {
|
||||
return UpdateCleanupResult.notApplicable();
|
||||
}
|
||||
boolean retain = "Retain".equals(r.getUpdateReplacePolicy());
|
||||
String liveEntityId = liveEntityId(r);
|
||||
ArrayNode displaced = cleanup.withArray("displaced");
|
||||
ArrayNode remaining = MAPPER.createArrayNode();
|
||||
for (JsonNode node : displaced) {
|
||||
ObjectNode entry = (ObjectNode) node;
|
||||
String physicalId = entry.path("physicalId").asText(null);
|
||||
if (physicalId == null || physicalId.equals(r.getPhysicalId())
|
||||
if (physicalId == null || physicalId.equals(liveEntityId)
|
||||
|| (retain && entry.path("retainable").asBoolean(false))) {
|
||||
continue;
|
||||
}
|
||||
@@ -248,11 +255,15 @@ public final class ReplacementCleanup {
|
||||
}
|
||||
// The result names the entity with the fewest attempts, the one the engine's retries are
|
||||
// still for and the one cleanupPhysicalId announced, so both events point at the same thing.
|
||||
JsonNode next = nextOwed(remaining, r.getPhysicalId(), retain);
|
||||
JsonNode next = nextOwed(remaining, liveEntityId, retain);
|
||||
return new UpdateCleanupResult(true, false, next.path("physicalId").asText(null),
|
||||
next.path("cleanupAttempts").asInt(0), next.path("cleanupFailureReason").asText(null));
|
||||
}
|
||||
|
||||
private static String liveEntityId(StackResource r) {
|
||||
return CfnResourceDispatcher.isStub(r.getPhysicalId(), r.getAttributes()) ? null : r.getPhysicalId();
|
||||
}
|
||||
|
||||
private static String firstDisplaced(ArrayNode displaced) {
|
||||
return displaced.isEmpty() ? null : displaced.get(0).path("physicalId").asText(null);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user