diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/EcrCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/EcrCfnProvisioner.java index e72e288491..17162788da 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/EcrCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/EcrCfnProvisioner.java @@ -2,6 +2,7 @@ package io.floci.aws.services.cloudformation.provisioners; import com.fasterxml.jackson.databind.JsonNode; import io.floci.aws.services.cloudformation.model.StackResource; +import io.floci.aws.services.cloudformation.provisioners.ProvisionContext.NamedChange; import io.floci.aws.services.ecr.EcrService; import io.floci.aws.services.ecr.model.Repository; import jakarta.enterprise.context.ApplicationScoped; @@ -88,19 +89,11 @@ public class EcrCfnProvisioner implements CfnResourceProvisioner { Map attributesBefore = new HashMap<>(r.getAttributes()); // The engine's change decides whether the update replaces the repository: RepositoryName and // EncryptionConfiguration are create-only in the registry. A named repository cannot be - // replaced under the same name. - boolean replaces = ctx.isUpdate() && ctx.changes(REPOSITORY, props).requiresReplacement(); - String explicitName = ctx.resolveOptional(props, "RepositoryName"); - // CDK bootstrap requires lower-case repository names; CFN-generated suffixes can include - // upper-case characters. Normalize to satisfy the AWS ECR repository name pattern. A - // replacing update that names nothing gets a fresh generated name, not the prior one. - String repoName = (replaces && (explicitName == null || explicitName.isBlank()) - ? ctx.generatePhysicalName(r.getLogicalId(), REPOSITORY_NAME_MAX_LENGTH, true) - : ctx.stablePhysicalName(explicitName, r.getLogicalId(), REPOSITORY_NAME_MAX_LENGTH, true)) - .toLowerCase(); - if (replaces && ctx.reusesPriorEntity(repoName)) { - throw CfnExceptions.customNamedReplacement(repoName); - } + // replaced under the same name. CDK bootstrap requires lower-case repository names, and + // CFN-generated suffixes can include upper-case characters, so the name is lower-cased. + NamedChange change = ctx.changes(REPOSITORY, props, ctx.resolveOptional(props, "RepositoryName"), + r.getLogicalId(), REPOSITORY_NAME_MAX_LENGTH, true, String::toLowerCase); + String repoName = change.name(); String mutability = ctx.resolveOptional(props, "ImageTagMutability"); Boolean scanOnPush = scanOnPush(props, ctx); @@ -156,7 +149,7 @@ public class EcrCfnProvisioner implements CfnResourceProvisioner { // when it is empty: EmptyOnDelete is not read, and an empty-only delete is what AWS does // by default. A create under an existing name fails, so a replacement here is always one // this update created. - ReplacementCleanup.record(r, ctx, attributesBefore, replaces && !reusing); + ReplacementCleanup.record(r, ctx, attributesBefore, change.replaces()); } @Override diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/IotCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/IotCfnProvisioner.java index 4619aaaf38..9e9d23d173 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/IotCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/IotCfnProvisioner.java @@ -3,6 +3,7 @@ package io.floci.aws.services.cloudformation.provisioners; import com.fasterxml.jackson.databind.JsonNode; import io.floci.aws.core.common.AwsException; import io.floci.aws.services.cloudformation.model.StackResource; +import io.floci.aws.services.cloudformation.provisioners.ProvisionContext.NamedChange; import io.floci.aws.services.iot.IotService; import io.floci.aws.services.iot.model.IotPolicy; import io.floci.aws.services.iot.model.IotTopicRule; @@ -10,22 +11,26 @@ import io.floci.aws.services.iot.model.Thing; import jakarta.enterprise.context.ApplicationScoped; import org.jboss.logging.Logger; +import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.function.UnaryOperator; /** - * Provisions the IoT Core registry and rules engine types: {@code AWS::IoT::Thing}, - * {@code AWS::IoT::Policy} and {@code AWS::IoT::TopicRule}. The physical id is the resource name, - * as it is on AWS, so a rename is a replacement: the new entity is created first and the prior - * one removed afterwards, since there is no generic replacement flow. + * Provisions IoT Core things, policies, and topic rules. The resource name is the physical id. + * A replacement leaves the prior entity in place until the stack update commits. If the update + * rolls back, the prior entity is restored as the stack resource and any newly created replacement is deleted. */ @ApplicationScoped public class IotCfnProvisioner implements CfnResourceProvisioner { private static final Logger LOG = Logger.getLogger(IotCfnProvisioner.class); private static final String NOT_FOUND = "ResourceNotFoundException"; + private static final String THING = "AWS::IoT::Thing"; + private static final String POLICY = "AWS::IoT::Policy"; + private static final String TOPIC_RULE = "AWS::IoT::TopicRule"; private static final int NAME_MAX_LENGTH = 128; private final IotService iotService; @@ -36,27 +41,59 @@ public class IotCfnProvisioner implements CfnResourceProvisioner { @Override public Set resourceTypes() { - return Set.of("AWS::IoT::Thing", "AWS::IoT::Policy", "AWS::IoT::TopicRule"); + return Set.of(THING, POLICY, TOPIC_RULE); } @Override public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { - switch (r.getResourceType()) { - case "AWS::IoT::Thing" -> provisionThing(r, props, ctx); - case "AWS::IoT::Policy" -> provisionPolicy(r, props, ctx); - case "AWS::IoT::TopicRule" -> provisionTopicRule(r, props, ctx); - default -> throw new IllegalStateException("IotCfnProvisioner cannot handle " + r.getResourceType()); + if (ctx.isUpdate()) { + ReplacementCleanup.endRollbackRetry(r); } + Map attributesBefore = new HashMap<>(r.getAttributes()); + ProvisionResult result = switch (r.getResourceType()) { + case THING -> provisionThing(r, props, ctx); + case POLICY -> provisionPolicy(r, props, ctx); + case TOPIC_RULE -> provisionTopicRule(r, props, ctx); + default -> throw new IllegalStateException("IotCfnProvisioner cannot handle " + r.getResourceType()); + }; + ReplacementCleanup.record(r, ctx, attributesBefore, result.replaces(), result.replacementCreated()); + } + + private record ProvisionResult(boolean replaces, boolean replacementCreated) { } + + @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) { + ReplacementCleanup.clear(resource); + } + + @Override + public boolean rollbackUpdate(StackResource resource) { + return ReplacementCleanup.rollback(resource, this::delete); } @Override public void delete(String resourceType, String physicalId, String region) { switch (resourceType) { - case "AWS::IoT::Thing" -> CfnDeletes.safeDelete("thing", physicalId, + case THING -> CfnDeletes.safeDelete("thing", physicalId, () -> iotService.deleteThing(physicalId, region), NOT_FOUND); - case "AWS::IoT::Policy" -> CfnDeletes.safeDelete("policy", physicalId, + case POLICY -> CfnDeletes.safeDelete("policy", physicalId, () -> detachAndDeletePolicy(physicalId, region), NOT_FOUND); - case "AWS::IoT::TopicRule" -> CfnDeletes.safeDelete("topic rule", physicalId, + case TOPIC_RULE -> CfnDeletes.safeDelete("topic rule", physicalId, () -> iotService.deleteTopicRule(physicalId, region), NOT_FOUND); default -> throw new IllegalStateException("IotCfnProvisioner cannot handle " + resourceType); } @@ -66,20 +103,35 @@ public class IotCfnProvisioner implements CfnResourceProvisioner { * {@code AttributePayload.Attributes} is the whole desired attribute set: an update replaces the * stored attributes rather than merging into them, as the CloudFormation handler does. */ - private void provisionThing(StackResource r, JsonNode props, ProvisionContext ctx) { - String name = ctx.stablePhysicalName(ctx.resolveOptional(props, "ThingName"), - r.getLogicalId(), NAME_MAX_LENGTH, false); + private ProvisionResult provisionThing(StackResource r, JsonNode props, ProvisionContext ctx) { + NamedChange change = ctx.changes(THING, props, ctx.resolveOptional(props, "ThingName"), + r.getLogicalId(), NAME_MAX_LENGTH, false, UnaryOperator.identity()); + String name = change.name(); Map attributes = thingAttributes(props, ctx); String region = ctx.region(); - boolean sameThing = ctx.reusesPriorEntity(name); - Thing thing = sameThing - ? iotService.updateThing(name, attributes, null, region) - : iotService.createThing(name, attributes, region); + boolean sameThing = ctx.isUpdate() && !change.replaces(); + Thing thing; + boolean replacementCreated = false; + if (sameThing) { + thing = iotService.updateThing(name, attributes, null, region); + } else { + replacementCreated = !thingExists(name, region); + thing = iotService.createThing(name, attributes, region); + } r.setPhysicalId(name); r.getAttributes().put("Arn", thing.getThingArn()); r.getAttributes().put("Id", thing.getThingId()); - if (!sameThing) { - deletePrior(r, ctx); + return new ProvisionResult(change.replaces(), replacementCreated); + } + + private boolean thingExists(String name, String region) { + try { + return iotService.describeThing(name, region) != null; + } catch (AwsException e) { + if (NOT_FOUND.equals(e.getErrorCode())) { + return false; + } + throw e; } } @@ -88,28 +140,29 @@ public class IotCfnProvisioner implements CfnResourceProvisioner { * document is compared as the string the policy stores, which is what this provisioner wrote * on the previous execution. {@code Id} is the policy name, as on AWS. */ - private void provisionPolicy(StackResource r, JsonNode props, ProvisionContext ctx) { - String name = ctx.stablePhysicalName(ctx.resolveOptional(props, "PolicyName"), - r.getLogicalId(), NAME_MAX_LENGTH, false); + private ProvisionResult provisionPolicy(StackResource r, JsonNode props, ProvisionContext ctx) { + NamedChange change = ctx.changes(POLICY, props, ctx.resolveOptional(props, "PolicyName"), + r.getLogicalId(), NAME_MAX_LENGTH, false, UnaryOperator.identity()); + String name = change.name(); String document = props == null ? null : ctx.engine().resolveJsonAttribute(props.path("PolicyDocument")); if (document == null || document.isBlank()) { - throw new IllegalArgumentException("AWS::IoT::Policy requires PolicyDocument"); + throw new IllegalArgumentException(POLICY + " requires PolicyDocument"); } Map tags = ctx.resolveTags(props, "Tags"); String region = ctx.region(); - if (ctx.reusesPriorEntity(name)) { + if (ctx.isUpdate() && !change.replaces()) { IotPolicy policy = iotService.getPolicy(name, region); if (!document.equals(policy.getPolicyDocument())) { createDefaultVersion(name, document, region); } reconcileTags(policy.getPolicyArn(), tags); recordPolicy(r, name, policy.getPolicyArn()); - return; + return new ProvisionResult(false, false); } IotPolicy policy = iotService.createPolicy(name, document, region); recordPolicy(r, name, policy.getPolicyArn()); finishCreate(r, ctx, () -> applyTags(policy.getPolicyArn(), tags)); - deletePrior(r, ctx); + return new ProvisionResult(change.replaces(), true); } /** @@ -142,29 +195,30 @@ public class IotCfnProvisioner implements CfnResourceProvisioner { * the characters a rule name allows, since AWS rejects the hyphens * {@link ProvisionContext#generatePhysicalName} emits. */ - private void provisionTopicRule(StackResource r, JsonNode props, ProvisionContext ctx) { - String name = ctx.resolveOptional(props, "RuleName"); - if (name == null || name.isBlank()) { - name = ctx.stablePhysicalName(null, r.getLogicalId(), NAME_MAX_LENGTH, false) - .replaceAll("[^A-Za-z0-9_]", ""); - } + private ProvisionResult provisionTopicRule(StackResource r, JsonNode props, ProvisionContext ctx) { + String explicitName = ctx.resolveOptional(props, "RuleName"); + UnaryOperator normalizeName = explicitName == null || explicitName.isBlank() + ? name -> name.replaceAll("[^A-Za-z0-9_]", "") : UnaryOperator.identity(); + NamedChange change = ctx.changes(TOPIC_RULE, props, explicitName, r.getLogicalId(), NAME_MAX_LENGTH, + false, normalizeName); + String name = change.name(); if (props == null || !props.hasNonNull("TopicRulePayload")) { - throw new IllegalArgumentException("AWS::IoT::TopicRule requires TopicRulePayload"); + throw new IllegalArgumentException(TOPIC_RULE + " requires TopicRulePayload"); } JsonNode payload = CfnApiShapeConverter.convert(ctx.engine().resolveNode(props.get("TopicRulePayload")), CfnApiShapeConverter.OMIT_NULL_PROPERTIES); Map tags = ctx.resolveTags(props, "Tags"); String region = ctx.region(); - if (ctx.reusesPriorEntity(name)) { + if (ctx.isUpdate() && !change.replaces()) { IotTopicRule rule = iotService.replaceTopicRule(name, payload, region); reconcileTags(rule.getRuleArn(), tags); recordTopicRule(r, name, rule.getRuleArn()); - return; + return new ProvisionResult(false, false); } IotTopicRule rule = iotService.createTopicRule(name, payload, region); recordTopicRule(r, name, rule.getRuleArn()); finishCreate(r, ctx, () -> applyTags(rule.getRuleArn(), tags)); - deletePrior(r, ctx); + return new ProvisionResult(change.replaces(), true); } /** @@ -237,23 +291,6 @@ public class IotCfnProvisioner implements CfnResourceProvisioner { } } - /** - * Removes the entity a replacement supersedes. As in CloudFormation's update cleanup, a failure - * does not fail the update: the stack already points at the new entity, so the prior one is - * left behind with a warning in the log. - */ - private void deletePrior(StackResource r, ProvisionContext ctx) { - if (!ctx.isUpdate()) { - return; - } - try { - delete(r.getResourceType(), ctx.priorPhysicalId(), ctx.region()); - } catch (AwsException e) { - LOG.warnv("Could not delete {0} {1} replaced by {2}: {3}", - r.getResourceType(), ctx.priorPhysicalId(), r.getPhysicalId(), e.getMessage()); - } - } - private void applyTags(String arn, Map tags) { if (!tags.isEmpty()) { iotService.tagResource(arn, tags); diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContext.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContext.java index a07f63ffb0..08039b6b99 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContext.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContext.java @@ -14,6 +14,7 @@ import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.function.Consumer; +import java.util.function.UnaryOperator; /** * The per-provision context every resource handler drew from: the template engine (for resolving @@ -166,6 +167,29 @@ public record ProvisionContext(CloudFormationTemplateEngine engine, String regio return PropertyChanges.between(resourceType, isUpdate(), priorProperties, props); } + /** + * The physical name and whether the update replaces, from the engine's change: a replacing + * update that names nothing gets a fresh generated name rather than the prior one, and a + * replacing update whose name, after {@code normalizeName}, is still the prior id is refused, + * since AWS cannot replace a custom-named resource under the same name. An overload of + * {@link #changes(String, JsonNode)}, so the ratchet in {@code CfnSchemaCoverageTest} sees the call. + */ + NamedChange changes(String resourceType, JsonNode props, String explicitName, String logicalId, + int maxLength, boolean lowercase, UnaryOperator normalizeName) { + boolean decided = isUpdate() && changes(resourceType, props).requiresReplacement(); + String name = normalizeName.apply(decided && (explicitName == null || explicitName.isBlank()) + ? generatePhysicalName(logicalId, maxLength, lowercase) + : stablePhysicalName(explicitName, logicalId, maxLength, lowercase)); + if (decided && reusesPriorEntity(name)) { + throw CfnExceptions.customNamedReplacement(name); + } + // A name that resolves away from the prior id is a new entity even where the change could not + // see it (a moved dynamic reference whose digest is gone), so the prior one is still cleaned up. + return new NamedChange(name, decided || (isUpdate() && !reusesPriorEntity(name))); + } + + record NamedChange(String name, boolean replaces) { } + /** * Resolves a CloudFormation tag property to a map, preserving template order. Both registry * shapes are read: the {@code [{Key, Value}]} list most types declare, and the diff --git a/src/test/java/io/floci/aws/services/cloudformation/CfnReplacementIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CfnReplacementIntegrationTest.java index 8017d2d577..b78157a197 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CfnReplacementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CfnReplacementIntegrationTest.java @@ -137,6 +137,11 @@ class CfnReplacementIntegrationTest { static Stream rows() { String app = appConfigApplication("replacement-orders"); + String iotName = json("'Name': {'Type': 'String', 'Default': 'repl-iot-@V@'}"); + String iotThingName = json("'ThingName': {'Ref': 'Name'}"); + String iotPolicy = json("'PolicyName': {'Ref': 'Name'}," + + " 'PolicyDocument': {'Version': '2012-10-17'," + + " 'Statement': [{'Effect': 'Allow', 'Action': 'iot:Connect', 'Resource': '*'}]}"); return Stream.of( createOnlyRow("AppConfig profile Type", app, "", PROFILE_TYPE, PROFILE + "\"LocationUri\": \"hosted\", \"Type\": \"AWS.Freeform\"", @@ -185,6 +190,12 @@ class CfnReplacementIntegrationTest { "Subject", "True", true, null), createOnlyRow("ECR repository RepositoryName removed", "", "", "AWS::ECR::Repository", "\"RepositoryName\": \"repl-ecr-named\"", "", "True", false, null), + createOnlyRow("IoT thing ThingName", "", iotName, "AWS::IoT::Thing", + iotThingName, iotThingName, "True", false, null), + createOnlyRow("IoT policy PolicyName", "", iotName, "AWS::IoT::Policy", + iotPolicy, iotPolicy, "True", false, null), + createOnlyRow("IoT thing ThingName removed", "", "", "AWS::IoT::Thing", + "\"ThingName\": \"repl-iot-named\"", "", "True", false, null), createOnlyRow("DynamoDB table explicit TableName removed", "", "", "AWS::DynamoDB::Table", DDB_KEYS + ", \"TableName\": \"repl-ddb-removed\"", DDB_KEYS, "True", false, null), new Row("log group given a Properties block that sets its name", diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/IotCfnProvisionerTestSupport.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/IotCfnProvisionerTestSupport.java index 6fd567f854..abdf089657 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/IotCfnProvisionerTestSupport.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/IotCfnProvisionerTestSupport.java @@ -33,11 +33,15 @@ final class IotCfnProvisionerTestSupport { return ctx(null); } + static ProvisionContext ctx(String priorPhysicalId) { + return ctx(priorPhysicalId, null); + } + /** * Scalars resolve to their text, an intrinsic collapses to a {@code resolved:} marker and * everything else is walked in place, so a nested payload keeps its shape and scalar types. */ - static ProvisionContext ctx(String priorPhysicalId) { + static ProvisionContext ctx(String priorPhysicalId, JsonNode priorProperties) { CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); when(engine.resolve(any())).thenAnswer(inv -> { JsonNode node = inv.getArgument(0); @@ -51,7 +55,7 @@ final class IotCfnProvisionerTestSupport { } return node.isTextual() ? node.asText() : node.toString(); }); - return new ProvisionContext(engine, REGION, ACCOUNT, "my-stack", priorPhysicalId); + return new ProvisionContext(engine, REGION, ACCOUNT, "my-stack", priorPhysicalId, event -> {}, priorProperties); } static JsonNode resolveIntrinsics(JsonNode node) { diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/IotPolicyCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/IotPolicyCfnProvisionerTest.java index 0ec7eb8885..6f38d48df7 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/IotPolicyCfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/IotPolicyCfnProvisionerTest.java @@ -207,8 +207,11 @@ class IotPolicyCfnProvisionerTest { when(iot.createPolicy("renamed", DOCUMENT, REGION)).thenReturn(policy("renamed", DOCUMENT)); when(iot.listTargetsForPolicy("device-policy", REGION)).thenReturn(Set.of("arn:aws:iot:us-east-1:000000000000:cert/abc")); StackResource r = resource(TYPE, "Policy"); + r.setPhysicalId("device-policy"); - provisioner.provision(r, props("renamed", document(), null), ctx("device-policy")); + provisioner.provision(r, props("renamed", document(), null), + ctx("device-policy", props("device-policy", document(), null))); + provisioner.completeUpdate(r); InOrder inOrder = inOrder(iot); inOrder.verify(iot).createPolicy("renamed", DOCUMENT, REGION); @@ -227,10 +230,14 @@ class IotPolicyCfnProvisionerTest { when(iot.createPolicy("renamed", DOCUMENT, REGION)).thenReturn(policy("renamed", DOCUMENT)); doThrow(new AwsException("InternalFailureException", "storage", 500)).when(iot).deletePolicy("device-policy", REGION); StackResource r = resource(TYPE, "Policy"); + r.setPhysicalId("device-policy"); - assertDoesNotThrow(() -> provisioner.provision(r, props("renamed", document(), null), ctx("device-policy"))); + assertDoesNotThrow(() -> provisioner.provision(r, props("renamed", document(), null), + ctx("device-policy", props("device-policy", document(), null)))); + assertDoesNotThrow(() -> provisioner.completeUpdate(r)); assertEquals("renamed", r.getPhysicalId()); + verify(iot).deletePolicy("device-policy", REGION); verify(iot, never()).deletePolicy("renamed", REGION); } @@ -241,7 +248,8 @@ class IotPolicyCfnProvisionerTest { StackResource r = resource(TYPE, "Policy"); ObjectNode props = props("renamed", document(), Map.of("env", "test")); - AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx("device-policy"))); + AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, + ctx("device-policy", props("device-policy", document(), null)))); assertEquals("InternalFailureException", e.getErrorCode()); verify(iot).deletePolicy("renamed", REGION); @@ -256,7 +264,8 @@ class IotPolicyCfnProvisionerTest { StackResource r = resource(TYPE, "Policy"); ObjectNode props = props("renamed", document(), Map.of("env", "test")); - AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx("device-policy"))); + AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, + ctx("device-policy", props("device-policy", document(), null)))); assertEquals("InternalFailureException", e.getErrorCode()); assertEquals(1, e.getSuppressed().length); diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/IotThingCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/IotThingCfnProvisionerTest.java index 553ce52cd7..e25fddd64e 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/IotThingCfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/IotThingCfnProvisionerTest.java @@ -8,6 +8,7 @@ import io.floci.aws.services.iot.IotService; import io.floci.aws.services.iot.model.Thing; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; import java.util.Map; import java.util.Set; @@ -16,6 +17,7 @@ import static io.floci.aws.services.cloudformation.provisioners.IotCfnProvisione import static io.floci.aws.services.cloudformation.provisioners.IotCfnProvisionerTestSupport.ctx; import static io.floci.aws.services.cloudformation.provisioners.IotCfnProvisionerTestSupport.notFound; import static io.floci.aws.services.cloudformation.provisioners.IotCfnProvisionerTestSupport.resource; +import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -25,6 +27,7 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -143,16 +146,80 @@ class IotThingCfnProvisionerTest { } @Test - void thingRenameCreatesTheReplacementThenDeletesThePriorThing() { + void thingRenameKeepsThePriorThingUntilUpdateCleanup() { when(iot.createThing(eq("sensor-2"), any(), eq(REGION))).thenReturn(thing("sensor-2", Map.of())); StackResource r = resource(TYPE, "Sensor"); + r.setPhysicalId("sensor-1"); + r.getAttributes().putAll(Map.of("Arn", ARN, "Id", THING_ID)); - provisioner.provision(r, props("sensor-2", null), ctx("sensor-1")); + provisioner.provision(r, props("sensor-2", null), ctx("sensor-1", props("sensor-1", null))); - verify(iot).deleteThing("sensor-1", REGION); + verify(iot, never()).deleteThing("sensor-1", REGION); verify(iot, never()).updateThing(anyString(), any(), any(), anyString()); assertEquals("sensor-2", r.getPhysicalId()); assertEquals("arn:aws:iot:us-east-1:000000000000:thing/sensor-2", r.getAttributes().get("Arn")); + + assertTrue(provisioner.completeUpdate(r).complete()); + + verify(iot).deleteThing("sensor-1", REGION); + verify(iot, never()).deleteThing("sensor-2", REGION); + } + + @Test + void thingRenameRollbackDeletesTheReplacementAndKeepsThePriorThing() { + when(iot.createThing(eq("sensor-2"), any(), eq(REGION))).thenReturn(thing("sensor-2", Map.of())); + StackResource r = resource(TYPE, "Sensor"); + r.setPhysicalId("sensor-1"); + r.getAttributes().putAll(Map.of("Arn", ARN, "Id", THING_ID)); + + provisioner.provision(r, props("sensor-2", null), ctx("sensor-1", props("sensor-1", null))); + boolean rolledBack = provisioner.rollbackUpdate(r); + + assertAll( + () -> verify(iot).deleteThing("sensor-2", REGION), + () -> verify(iot, never()).deleteThing("sensor-1", REGION)); + assertTrue(rolledBack); + assertEquals("sensor-1", r.getPhysicalId()); + } + + @Test + void thingRenameRollbackPreservesAnExistingTargetThing() { + Map attributes = Map.of("Model", "M2"); + Thing existing = thing("sensor-2", attributes); + when(iot.describeThing("sensor-2", REGION)).thenReturn(existing); + when(iot.createThing("sensor-2", attributes, REGION)).thenReturn(existing); + StackResource r = resource(TYPE, "Sensor"); + r.setPhysicalId("sensor-1"); + r.getAttributes().putAll(Map.of("Arn", ARN, "Id", THING_ID)); + + provisioner.provision(r, props("sensor-2", attributes), ctx("sensor-1", props("sensor-1", null))); + assertEquals("sensor-2", r.getPhysicalId()); + boolean rolledBack = provisioner.rollbackUpdate(r); + + assertAll( + () -> verify(iot, never()).deleteThing("sensor-2", REGION), + () -> assertTrue(rolledBack), + () -> assertEquals("sensor-1", r.getPhysicalId()), + () -> assertEquals(Map.of("Arn", ARN, "Id", THING_ID), r.getAttributes())); + } + + @Test + void thingUpdateReplacesThePriorThingWhenUnchangedPropertiesResolveToADifferentName() { + when(iot.createThing("sensor-b", Map.of(), REGION)).thenReturn(thing("sensor-b", Map.of())); + StackResource r = resource(TYPE, "Sensor"); + r.setPhysicalId("sensor-a"); + ObjectNode properties = props("sensor-b", null); + + provisioner.provision(r, properties, ctx("sensor-a", properties.deepCopy())); + provisioner.completeUpdate(r); + + InOrder calls = inOrder(iot); + calls.verify(iot).createThing("sensor-b", Map.of(), REGION); + calls.verify(iot).deleteThing("sensor-a", REGION); + verify(iot, never()).updateThing(anyString(), any(), any(), anyString()); + assertEquals("sensor-b", r.getPhysicalId()); + assertEquals("arn:aws:iot:us-east-1:000000000000:thing/sensor-b", r.getAttributes().get("Arn")); + assertEquals(THING_ID, r.getAttributes().get("Id")); } @Test @@ -160,9 +227,13 @@ class IotThingCfnProvisionerTest { when(iot.createThing(eq("sensor-2"), any(), eq(REGION))).thenReturn(thing("sensor-2", Map.of())); doThrow(notFound("Thing")).when(iot).deleteThing("sensor-1", REGION); StackResource r = resource(TYPE, "Sensor"); + r.setPhysicalId("sensor-1"); - assertDoesNotThrow(() -> provisioner.provision(r, props("sensor-2", null), ctx("sensor-1"))); + assertDoesNotThrow(() -> provisioner.provision(r, props("sensor-2", null), + ctx("sensor-1", props("sensor-1", null)))); + assertDoesNotThrow(() -> provisioner.completeUpdate(r)); + verify(iot).deleteThing("sensor-1", REGION); assertEquals("sensor-2", r.getPhysicalId()); } @@ -173,9 +244,13 @@ class IotThingCfnProvisionerTest { when(iot.createThing(eq("sensor-2"), any(), eq(REGION))).thenReturn(thing("sensor-2", Map.of())); doThrow(new AwsException("InvalidRequestException", "Cannot delete", 400)).when(iot).deleteThing("sensor-1", REGION); StackResource r = resource(TYPE, "Sensor"); + r.setPhysicalId("sensor-1"); - assertDoesNotThrow(() -> provisioner.provision(r, props("sensor-2", null), ctx("sensor-1"))); + assertDoesNotThrow(() -> provisioner.provision(r, props("sensor-2", null), + ctx("sensor-1", props("sensor-1", null)))); + assertDoesNotThrow(() -> provisioner.completeUpdate(r)); + verify(iot).deleteThing("sensor-1", REGION); assertEquals("sensor-2", r.getPhysicalId()); } diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/IotTopicRuleCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/IotTopicRuleCfnProvisionerTest.java index 1dcdce5dd3..8abe51c1e8 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/IotTopicRuleCfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/IotTopicRuleCfnProvisionerTest.java @@ -219,8 +219,11 @@ class IotTopicRuleCfnProvisionerTest { void topicRuleRenameCreatesTheReplacementThenDeletesThePriorRule() { when(iot.createTopicRule(eq("renamedRule"), any(), eq(REGION))).thenReturn(rule("renamedRule")); StackResource r = resource(TYPE, "Rule"); + r.setPhysicalId("telemetryRule"); - provisioner.provision(r, props("renamedRule", templatePayload(), null), ctx("telemetryRule")); + provisioner.provision(r, props("renamedRule", templatePayload(), null), + ctx("telemetryRule", props("telemetryRule", templatePayload(), null))); + provisioner.completeUpdate(r); verify(iot).deleteTopicRule("telemetryRule", REGION); verify(iot, never()).replaceTopicRule(anyString(), any(), anyString()); @@ -235,7 +238,8 @@ class IotTopicRuleCfnProvisionerTest { StackResource r = resource(TYPE, "Rule"); ObjectNode props = props("renamedRule", templatePayload(), Map.of("env", "test")); - assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx("telemetryRule"))); + assertThrows(AwsException.class, () -> provisioner.provision(r, props, + ctx("telemetryRule", props("telemetryRule", templatePayload(), null)))); verify(iot).deleteTopicRule("renamedRule", REGION); verify(iot, never()).deleteTopicRule("telemetryRule", REGION); diff --git a/src/test/resources/cloudformation/change-exempt.tsv b/src/test/resources/cloudformation/change-exempt.tsv index 211e295998..b13f7814ce 100644 --- a/src/test/resources/cloudformation/change-exempt.tsv +++ b/src/test/resources/cloudformation/change-exempt.tsv @@ -127,9 +127,6 @@ AWS::IAM::Role update not yet on the engine's changes (#6606) AWS::IAM::User prior entity found by reusesPriorEntity; moves to the engine's decision with the create-only work AWS::IoT::Authorizer prior entity found by reusesPriorEntity; moves to the engine's decision with the create-only work AWS::IoT::DomainConfiguration wholesale request builder: the whole property node goes to the service -AWS::IoT::Policy prior entity found by reusesPriorEntity; moves to the engine's decision with the create-only work -AWS::IoT::Thing prior entity found by reusesPriorEntity; moves to the engine's decision with the create-only work -AWS::IoT::TopicRule prior entity found by reusesPriorEntity; moves to the engine's decision with the create-only work AWS::KMS::Alias update not yet on the engine's changes (#6606) AWS::Kinesis::Stream update not yet on the engine's changes (#6606) AWS::KinesisFirehose::DeliveryStream prior entity found by reusesPriorEntity; moves to the engine's decision with the create-only work