Light, fluffy, and always free - The AWS Local Emulator alternative
refactor(cloudformation): move AWS::Logs::LogGroup into its own provisioner (#2756)
Hector Ventura1d81cdd0d29f
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.javaindex 54a80422c0..817e53041f 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java@@ -139,7 +139,7 @@ public class CloudFormationResourceProvisioner {private static final String LAMBDA_CODE_IDENTITY_ATTR = "FlociLambdaCodeIdentity";private static final String LAMBDA_NAME_MODE_ATTR = "FlociLambdaFunctionNameMode";private static final String LAMBDA_PACKAGE_TYPE_ATTR = "FlociLambdaPackageType";- static final String UPDATE_ROLLBACK_RESTORED_ATTR = "__FlociUpdateRollbackRestored";+ static final String UPDATE_ROLLBACK_RESTORED_ATTR = CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR;static final String UPDATE_ROLLBACK_FAILURE_ATTR = "__FlociUpdateRollbackFailure";private static final String INLINE_CLEANUP_POLICY_NAME_ATTR = "__FlociInlineCleanupPolicyName";private static final String INLINE_CLEANUP_ROLE_TARGETS_ATTR = "__FlociInlineCleanupRoleTargets";@@ -158,7 +158,6 @@ public class CloudFormationResourceProvisioner {private static final String NAME_MODE_GENERATED = "generated";private static final int GENERATED_NAME_SUFFIX_LENGTH = 12;private static final int STEP_FUNCTIONS_NAME_MAX_LENGTH = 80;- private static final String LOG_GROUP_NAME_MODE_ATTR = "FlociLogGroupNameMode";private static final String SECRET_TARGET_MANAGED_KEYS_ATTR = "__FlociSecretTargetManagedKeys";private static final String SECRET_TARGET_OWNER_ATTR = "__FlociSecretTargetOwner";private static final String DDB_REPLICA_TABLE_NAME_ATTR = "TableName";@@ -261,7 +260,6 @@ public class CloudFormationResourceProvisioner {"AWS::Lambda::EventSourceMapping","AWS::Lambda::Function","AWS::Lambda::LayerVersion",- "AWS::Logs::LogGroup","AWS::RDS::DBCluster","AWS::RDS::DBClusterParameterGroup","AWS::RDS::DBInstance",@@ -309,7 +307,6 @@ public class CloudFormationResourceProvisioner {private final Ec2Service ec2Service;private final RdsService rdsService;private final EksService eksService;- private final CloudWatchLogsService logsService;private final KinesisService kinesisService;private final CloudWatchMetricsService cloudWatchMetricsService;private final AutoScalingService autoScalingService;@@ -377,7 +374,6 @@ public class CloudFormationResourceProvisioner {this.ec2Service = ec2Service;this.rdsService = rdsService;this.eksService = eksService;- this.logsService = logsService;this.kinesisService = kinesisService;this.cloudWatchMetricsService = cloudWatchMetricsService;this.autoScalingService = autoScalingService;@@ -517,7 +513,6 @@ public class CloudFormationResourceProvisioner {provisionDbProxyTargetGroup(resource, properties, engine, region);case "AWS::EKS::Cluster" -> provisionEksCluster(resource, properties, engine, stackName);case "AWS::EKS::Nodegroup" -> provisionEksNodegroup(resource, properties, engine, stackName);- case "AWS::Logs::LogGroup" -> provisionLogGroup(resource, properties, engine, region, accountId, stackName);case "AWS::Kinesis::Stream" ->provisionKinesisStream(resource, properties, engine, region, stackName);case "AWS::CloudWatch::Alarm" ->@@ -755,7 +750,6 @@ public class CloudFormationResourceProvisioner {case "AWS::RDS::DBClusterParameterGroup" ->rdsService.deleteDbClusterParameterGroup(physicalId, region);case "AWS::EKS::Cluster" -> eksService.deleteCluster(physicalId);- case "AWS::Logs::LogGroup" -> logsService.deleteLogGroup(physicalId, region);case "AWS::Kinesis::Stream" -> kinesisService.deleteStream(physicalId, region);case "AWS::CloudWatch::Alarm" ->cloudWatchMetricsService.deleteAlarms(List.of(physicalId), region);@@ -890,89 +884,6 @@ public class CloudFormationResourceProvisioner {// ── CloudWatch Logs ─────────────────────────────────────────────────────────- private void provisionLogGroup(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,- String region, String accountId, String stackName) {- String explicitName = resolveOptional(props, "LogGroupName", engine);- boolean hasExplicitName = explicitName != null && !explicitName.isBlank();- String previousNameMode = r.getAttributes().get(LOG_GROUP_NAME_MODE_ATTR);- if (previousNameMode == null && r.getPhysicalId() != null) {- // Stacks persisted before FlociLogGroupNameMode existed have no recorded mode, but an- // auto-generated name always has the deterministic shape generatePhysicalName produces,- // so anything else must have been explicit.- previousNameMode = isGeneratedName(r.getPhysicalId(), stackName, r.getLogicalId(), 512)- ? NAME_MODE_GENERATED- : NAME_MODE_EXPLICIT;- }- // Going from an explicit name to none is itself a replacement-worthy change on real AWS, not- // something to silently keep reconciling under the old explicit name (mirrors the same check- // for Lambda's FunctionName above).- boolean explicitNameRemoved = r.getPhysicalId() != null && !hasExplicitName- && NAME_MODE_EXPLICIT.equals(previousNameMode);-- String name;- if (hasExplicitName) {- name = explicitName;- } else if (r.getPhysicalId() != null && !explicitNameRemoved) {- // No explicit name and the prior name was itself auto-generated: keep it across updates- // instead of generating a fresh random one each time, so the log group is reconciled in- // place rather than replaced on every no-op update.- name = r.getPhysicalId();- } else {- name = generatePhysicalName(stackName, r.getLogicalId(), 512, false);- }- Integer retentionInDays = null;- String retention = resolveOptional(props, "RetentionInDays", engine);- if (retention != null && !retention.isBlank()) {- try {- retentionInDays = Integer.valueOf(retention.trim());- } catch (NumberFormatException ignored) {- // leave unset- }- }- Map<String, String> tags = new HashMap<>();- if (props != null && props.has("Tags") && props.get("Tags").isArray()) {- for (JsonNode tag : props.get("Tags")) {- String key = engine.resolve(tag.path("Key"));- if (!key.isEmpty()) {- tags.put(key, engine.resolve(tag.path("Value")));- }- }- }-- // LogGroupName isn't updatable in place on real AWS (a change replaces the resource), so only- // reconcile in place when the name is unchanged and the group is still there; otherwise this is- // either a first create or a rename, both of which need a fresh createLogGroup call. On a rename,- // create the new group before deleting the old one: if the new name collides with something else- // and createLogGroup throws, the update rolls back without touching the old group, since rollback- // does not restore a resource this method already deleted.- String priorPhysicalId = r.getPhysicalId();- if (priorPhysicalId != null && priorPhysicalId.equals(name) && logsService.logGroupExists(name, region)) {- reconcileLogGroup(name, retentionInDays, tags, region);- } else {- boolean preservedPriorGroup = priorPhysicalId != null- && !priorPhysicalId.equals(name)- && logsService.logGroupExists(priorPhysicalId, region);- try {- logsService.createLogGroup(name, retentionInDays, tags, region);- } catch (RuntimeException failure) {- if (preservedPriorGroup) {- r.getAttributes().put(UPDATE_ROLLBACK_RESTORED_ATTR, "true");- }- throw failure;- }- if (preservedPriorGroup) {- logsService.deleteLogGroup(priorPhysicalId, region);- }- }-- // Ref returns the log group name; GetAtt Arn is arn:aws:logs:<region>:<account>:log-group:<name>:*- r.setPhysicalId(name);- r.getAttributes().put("Arn",- AwsArnUtils.Arn.of("logs", region, accountId, "log-group:" + name + ":*").toString());- r.getAttributes().put(LOG_GROUP_NAME_MODE_ATTR,- hasExplicitName ? NAME_MODE_EXPLICIT : NAME_MODE_GENERATED);- }-/*** Whether {@code physicalId} matches the exact shape {@link #generatePhysicalName} produces for* this stack/logical id/maxLength: its base-and-truncation logic (minus the random suffix itself)@@ -1017,24 +928,6 @@ public class CloudFormationResourceProvisioner {return prefix;}- private void reconcileLogGroup(String name, Integer retentionInDays, Map<String, String> tags, String region) {- if (retentionInDays != null) {- logsService.putRetentionPolicy(name, retentionInDays, region);- } else {- logsService.deleteRetentionPolicy(name, region);- }- Map<String, String> existingTags = logsService.listTagsLogGroup(name, region);- List<String> tagsToRemove = existingTags.keySet().stream()- .filter(key -> !tags.containsKey(key))- .toList();- if (!tagsToRemove.isEmpty()) {- logsService.untagLogGroup(name, tagsToRemove, region);- }- if (!tags.isEmpty()) {- logsService.tagLogGroup(name, tags, region);- }- }-// ── Kinesis ─────────────────────────────────────────────────────────────────private void provisionKinesisStream(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.javaindex 01c5b19dae..715c1b14e7 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java@@ -19,6 +19,15 @@ public final class CfnRollback {*/public static final String ROLLBACK_OWNED_ATTR = "__FlociRollbackOwned";+ /**+ * Marks a resource whose prior physical entity is still intact after a failed update, so the+ * rollback must not try to restore it. Set by a provisioner that creates the replacement before+ * deleting the original; read by {@code CloudFormationService} when deciding what a rollback+ * owes. Lives here rather than on {@code CloudFormationResourceProvisioner} so extracted+ * provisioners in this package can set it.+ */+ public static final String UPDATE_ROLLBACK_RESTORED_ATTR = "__FlociUpdateRollbackRestored";+private CfnRollback() {}diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LogsCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LogsCfnProvisioner.javanew file mode 100644index 0000000000..42cca4a393--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LogsCfnProvisioner.java@@ -0,0 +1,182 @@+package io.github.hectorvent.floci.services.cloudformation.provisioners;++import com.fasterxml.jackson.databind.JsonNode;+import io.github.hectorvent.floci.core.common.AwsArnUtils;+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;+import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;+import jakarta.enterprise.context.ApplicationScoped;++import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.Set;++/** Provisions {@code AWS::Logs::LogGroup}. */+@ApplicationScoped+public class LogsCfnProvisioner implements CfnResourceProvisioner {++ /**+ * Records whether the log group's name came from the template or was generated, so a later+ * update can tell a rename from a no-op. Read back off the resource's stored attributes.+ */+ private static final String LOG_GROUP_NAME_MODE_ATTR = "FlociLogGroupNameMode";+ private static final String NAME_MODE_EXPLICIT = "explicit";+ private static final String NAME_MODE_GENERATED = "generated";+ private static final int LOG_GROUP_NAME_MAX_LENGTH = 512;+ private static final int GENERATED_NAME_SUFFIX_LENGTH = 12;++ private final CloudWatchLogsService logsService;++ public LogsCfnProvisioner(CloudWatchLogsService logsService) {+ this.logsService = logsService;+ }++ @Override+ public Set<String> resourceTypes() {+ return Set.of("AWS::Logs::LogGroup");+ }++ @Override+ public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {+ String explicitName = ctx.resolveOptional(props, "LogGroupName");+ boolean hasExplicitName = explicitName != null && !explicitName.isBlank();+ String priorPhysicalId = ctx.priorPhysicalId();++ String previousNameMode = r.getAttributes().get(LOG_GROUP_NAME_MODE_ATTR);+ if (previousNameMode == null && priorPhysicalId != null) {+ // Stacks persisted before FlociLogGroupNameMode existed have no recorded mode, but an+ // auto-generated name always has the deterministic shape generatePhysicalName produces,+ // so anything else must have been explicit.+ previousNameMode = isGeneratedName(priorPhysicalId, ctx.stackName(), r.getLogicalId(),+ LOG_GROUP_NAME_MAX_LENGTH) ? NAME_MODE_GENERATED : NAME_MODE_EXPLICIT;+ }+ // Going from an explicit name to none is itself a replacement-worthy change on real AWS, not+ // something to silently keep reconciling under the old explicit name.+ boolean explicitNameRemoved = priorPhysicalId != null && !hasExplicitName+ && NAME_MODE_EXPLICIT.equals(previousNameMode);++ String name;+ if (hasExplicitName) {+ name = explicitName;+ } else if (priorPhysicalId != null && !explicitNameRemoved) {+ // No explicit name and the prior name was itself auto-generated: keep it across updates+ // instead of generating a fresh random one each time, so the log group is reconciled in+ // place rather than replaced on every no-op update.+ name = priorPhysicalId;+ } else {+ name = ctx.generatePhysicalName(r.getLogicalId(), LOG_GROUP_NAME_MAX_LENGTH, false);+ }++ Integer retentionInDays = null;+ String retention = ctx.resolveOptional(props, "RetentionInDays");+ if (retention != null && !retention.isBlank()) {+ try {+ retentionInDays = Integer.valueOf(retention.trim());+ } catch (NumberFormatException ignored) {+ // leave unset+ }+ }+ Map<String, String> tags = new HashMap<>();+ if (props != null && props.has("Tags") && props.get("Tags").isArray()) {+ for (JsonNode tag : props.get("Tags")) {+ String key = ctx.engine().resolve(tag.path("Key"));+ if (!key.isEmpty()) {+ tags.put(key, ctx.engine().resolve(tag.path("Value")));+ }+ }+ }++ // LogGroupName isn't updatable in place on real AWS (a change replaces the resource), so only+ // reconcile in place when the name is unchanged and the group is still there; otherwise this is+ // either a first create or a rename, both of which need a fresh createLogGroup call. On a rename,+ // create the new group before deleting the old one: if the new name collides with something else+ // and createLogGroup throws, the update rolls back without touching the old group, since rollback+ // does not restore a resource this method already deleted.+ if (priorPhysicalId != null && priorPhysicalId.equals(name)+ && logsService.logGroupExists(name, ctx.region())) {+ reconcileLogGroup(name, retentionInDays, tags, ctx.region());+ } else {+ boolean preservedPriorGroup = priorPhysicalId != null+ && !priorPhysicalId.equals(name)+ && logsService.logGroupExists(priorPhysicalId, ctx.region());+ try {+ logsService.createLogGroup(name, retentionInDays, tags, ctx.region());+ } catch (RuntimeException failure) {+ if (preservedPriorGroup) {+ r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR, "true");+ }+ throw failure;+ }+ if (preservedPriorGroup) {+ logsService.deleteLogGroup(priorPhysicalId, ctx.region());+ }+ }++ // Ref returns the log group name; GetAtt Arn is arn:aws:logs:<region>:<account>:log-group:<name>:*+ r.setPhysicalId(name);+ r.getAttributes().put("Arn", AwsArnUtils.Arn+ .of("logs", ctx.region(), ctx.accountId(), "log-group:" + name + ":*").toString());+ r.getAttributes().put(LOG_GROUP_NAME_MODE_ATTR,+ hasExplicitName ? NAME_MODE_EXPLICIT : NAME_MODE_GENERATED);+ }++ private void reconcileLogGroup(String name, Integer retentionInDays, Map<String, String> tags,+ String region) {+ if (retentionInDays != null) {+ logsService.putRetentionPolicy(name, retentionInDays, region);+ } else {+ logsService.deleteRetentionPolicy(name, region);+ }+ Map<String, String> existingTags = logsService.listTagsLogGroup(name, region);+ List<String> tagsToRemove = existingTags.keySet().stream()+ .filter(key -> !tags.containsKey(key))+ .toList();+ if (!tagsToRemove.isEmpty()) {+ logsService.untagLogGroup(name, tagsToRemove, region);+ }+ if (!tags.isEmpty()) {+ logsService.tagLogGroup(name, tags, region);+ }+ }++ /**+ * Whether a physical id has the exact shape {@code generatePhysicalName} produces. Copied from+ * the monolith, which still needs it for a type that has not migrated yet.+ */+ private boolean isGeneratedName(String physicalId, String stackName, String logicalId, int maxLength) {+ if (physicalId == null || physicalId.length() < GENERATED_NAME_SUFFIX_LENGTH + 1) {+ return false;+ }+ String suffix = physicalId.substring(physicalId.length() - GENERATED_NAME_SUFFIX_LENGTH);+ for (int i = 0; i < suffix.length(); i++) {+ char c = suffix.charAt(i);+ boolean hex = (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f');+ if (!hex) {+ return false;+ }+ }+ if (physicalId.charAt(physicalId.length() - GENERATED_NAME_SUFFIX_LENGTH - 1) != '-') {+ return false;+ }+ String actualPrefix = physicalId.substring(0, physicalId.length() - GENERATED_NAME_SUFFIX_LENGTH - 1);+ return actualPrefix.equals(expectedGeneratedNamePrefix(stackName, logicalId, maxLength));+ }++ private String expectedGeneratedNamePrefix(String stackName, String logicalId, int maxLength) {+ String base = stackName + "-" + logicalId;+ if (maxLength <= 0 || base.length() + 1 + GENERATED_NAME_SUFFIX_LENGTH <= maxLength) {+ return base;+ }+ int keep = Math.max(0, maxLength - GENERATED_NAME_SUFFIX_LENGTH - 1);+ String prefix = base.length() > keep ? base.substring(0, keep) : base;+ while (prefix.endsWith("-")) {+ prefix = prefix.substring(0, prefix.length() - 1);+ }+ return prefix;+ }++ @Override+ public void delete(String resourceType, String physicalId, String region) {+ logsService.deleteLogGroup(physicalId, region);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLogGroupProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLogGroupProvisionerTest.javaindex 222c68ad5a..9e2c81cec8 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLogGroupProvisionerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLogGroupProvisionerTest.java@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudformation;import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;import io.github.hectorvent.floci.services.cloudformation.model.StackResource;+import io.github.hectorvent.floci.services.cloudformation.provisioners.LogsCfnProvisioner;import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;@@ -39,9 +40,14 @@ class CloudFormationLogGroupProvisionerTest {@BeforeEachvoid setUp() {logsService = mock(CloudWatchLogsService.class);+ // Registering the provisioner is load-bearing, not decoration: AWS::Logs::LogGroup now lives+ // in LogsCfnProvisioner, so with an empty registry these calls would fall through to the+ // dispatcher's stub arm and assert against a synthetic id instead of the real logic. Going+ // through the dispatcher rather than the provisioner directly also covers the plumbing this+ // migration changed, that existingPhysicalId and existingAttributes reach ProvisionContext.provisioner = CfnProvisionerFixture.builder().objectMapper(mapper)- .logs(logsService)+ .provisioners(new LogsCfnProvisioner(logsService)).build();}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LogsCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LogsCfnProvisionerTest.javanew file mode 100644index 0000000000..31daa3cd27--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LogsCfnProvisionerTest.java@@ -0,0 +1,218 @@+package io.github.hectorvent.floci.services.cloudformation.provisioners;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;+import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.mockito.ArgumentCaptor;++import java.util.HashMap;+import java.util.List;+import java.util.Map;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyInt;+import static org.mockito.ArgumentMatchers.anyMap;+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.mock;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++/**+ * {@code AWS::Logs::LogGroup}, whose provision body is also its update path: it decides between+ * reconciling in place and replacing, from the prior physical id and the recorded name mode.+ */+class LogsCfnProvisionerTest {++ private static final ObjectMapper MAPPER = new ObjectMapper();+ private static final String REGION = "us-east-1";+ private static final String ACCOUNT_ID = "000000000000";+ private static final String STACK = "my-stack";++ private CloudWatchLogsService logs;+ private LogsCfnProvisioner provisioner;+ private CloudFormationTemplateEngine engine;++ @BeforeEach+ void setUp() {+ logs = mock(CloudWatchLogsService.class);+ provisioner = new LogsCfnProvisioner(logs);+ engine = mock(CloudFormationTemplateEngine.class);+ when(engine.resolve(any())).thenAnswer(i -> {+ JsonNode node = i.getArgument(0);+ return node == null || node.isMissingNode() || node.isNull() ? null : node.asText();+ });+ when(engine.resolveNode(any())).thenAnswer(i -> i.getArgument(0));+ when(logs.listTagsLogGroup(anyString(), anyString())).thenReturn(Map.of());+ }++ private static JsonNode props(String json) {+ try {+ return MAPPER.readTree(json);+ } catch (Exception e) {+ throw new IllegalArgumentException(e);+ }+ }++ /** Provisions as a create (no prior physical id) or an update (prior id and attributes). */+ private StackResource provision(String json, String priorPhysicalId, Map<String, String> attrs) {+ StackResource r = new StackResource();+ r.setLogicalId("LogGroup");+ r.setResourceType("AWS::Logs::LogGroup");+ r.setPhysicalId(priorPhysicalId);+ r.setAttributes(new HashMap<>(attrs));+ provisioner.provision(r, props(json),+ new ProvisionContext(engine, REGION, ACCOUNT_ID, STACK, priorPhysicalId));+ return r;+ }++ @Test+ void createUsesTheExplicitNameAndSetsTheArn() {+ StackResource r = provision("""+ {"LogGroupName": "/aws/app"}+ """, null, Map.of());++ verify(logs).createLogGroup(eq("/aws/app"), isNull(), anyMap(), eq(REGION));+ assertEquals("/aws/app", r.getPhysicalId(), "Ref is the log group name");+ assertEquals("arn:aws:logs:us-east-1:000000000000:log-group:/aws/app:*",+ r.getAttributes().get("Arn"));+ assertEquals("explicit", r.getAttributes().get("FlociLogGroupNameMode"));+ }++ @Test+ void anUnnamedGroupGetsAGeneratedNameRecordedAsGenerated() {+ StackResource r = provision("{}", null, Map.of());++ assertTrue(r.getPhysicalId().startsWith("my-stack-LogGroup-"), r.getPhysicalId());+ assertEquals("generated", r.getAttributes().get("FlociLogGroupNameMode"));+ }++ @Test+ void retentionAndTagsReachTheService() {+ ArgumentCaptor<Map<String, String>> tags = ArgumentCaptor.forClass(Map.class);++ provision("""+ {"LogGroupName": "g", "RetentionInDays": "14",+ "Tags": [{"Key": "env", "Value": "dev"}]}+ """, null, Map.of());++ verify(logs).createLogGroup(eq("g"), eq(14), tags.capture(), eq(REGION));+ assertEquals(Map.of("env", "dev"), tags.getValue());+ }++ /** A non-numeric RetentionInDays leaves retention unset rather than failing the resource. */+ @Test+ void anUnparseableRetentionIsIgnored() {+ provision("""+ {"LogGroupName": "g", "RetentionInDays": "forever"}+ """, null, Map.of());++ verify(logs).createLogGroup(eq("g"), isNull(), anyMap(), eq(REGION));+ }++ @Test+ void anUnchangedNameReconcilesInPlaceInsteadOfRecreating() {+ when(logs.logGroupExists("g", REGION)).thenReturn(true);+ when(logs.listTagsLogGroup("g", REGION)).thenReturn(Map.of("stale", "1"));++ provision("""+ {"LogGroupName": "g", "RetentionInDays": "7"}+ """, "g", Map.of("FlociLogGroupNameMode", "explicit"));++ verify(logs, never()).createLogGroup(anyString(), any(), anyMap(), anyString());+ verify(logs).putRetentionPolicy("g", 7, REGION);+ // A tag dropped from the template is removed from the live group, not just left behind.+ verify(logs).untagLogGroup("g", List.of("stale"), REGION);+ }++ @Test+ void reconcileClearsRetentionWhenTheTemplateDropsIt() {+ when(logs.logGroupExists("g", REGION)).thenReturn(true);++ provision("""+ {"LogGroupName": "g"}+ """, "g", Map.of("FlociLogGroupNameMode", "explicit"));++ verify(logs).deleteRetentionPolicy("g", REGION);+ verify(logs, never()).putRetentionPolicy(anyString(), anyInt(), anyString());+ }++ @Test+ void arenameCreatesTheNewGroupBeforeDeletingTheOld() {+ when(logs.logGroupExists("old", REGION)).thenReturn(true);++ StackResource r = provision("""+ {"LogGroupName": "new"}+ """, "old", Map.of("FlociLogGroupNameMode", "explicit"));++ assertEquals("new", r.getPhysicalId());+ verify(logs).createLogGroup(eq("new"), isNull(), anyMap(), eq(REGION));+ verify(logs).deleteLogGroup("old", REGION);+ }++ /**+ * If creating the replacement fails, the original must survive and the resource must say so, or+ * rollback would try to restore a group that was never deleted.+ */+ @Test+ void aFailedRenameLeavesTheOriginalAndFlagsTheRollback() {+ when(logs.logGroupExists("old", REGION)).thenReturn(true);+ doThrow(new RuntimeException("name taken"))+ .when(logs).createLogGroup(eq("new"), any(), anyMap(), anyString());++ StackResource r = new StackResource();+ r.setLogicalId("LogGroup");+ r.setResourceType("AWS::Logs::LogGroup");+ r.setPhysicalId("old");+ r.setAttributes(new HashMap<>(Map.of("FlociLogGroupNameMode", "explicit")));++ assertThrows(RuntimeException.class, () -> provisioner.provision(r, props("""+ {"LogGroupName": "new"}+ """), new ProvisionContext(engine, REGION, ACCOUNT_ID, STACK, "old")));++ verify(logs, never()).deleteLogGroup("old", REGION);+ assertEquals("true", r.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR));+ }++ /**+ * Dropping an explicit LogGroupName is a replacement on real AWS, so it must not keep+ * reconciling under the old explicit name.+ */+ @Test+ void removingAnExplicitNameReplacesTheGroup() {+ when(logs.logGroupExists("chosen", REGION)).thenReturn(true);++ StackResource r = provision("{}", "chosen", Map.of("FlociLogGroupNameMode", "explicit"));++ assertTrue(r.getPhysicalId().startsWith("my-stack-LogGroup-"), r.getPhysicalId());+ verify(logs).deleteLogGroup("chosen", REGION);+ }++ /** A generated name is kept across updates so a no-op update does not churn the group. */+ @Test+ void aGeneratedNameIsKeptAcrossUpdates() {+ String generated = "my-stack-LogGroup-abc123def456";+ when(logs.logGroupExists(generated, REGION)).thenReturn(true);++ StackResource r = provision("{}", generated, Map.of("FlociLogGroupNameMode", "generated"));++ assertEquals(generated, r.getPhysicalId());+ verify(logs, never()).createLogGroup(anyString(), any(), anyMap(), anyString());+ }++ @Test+ void deleteReachesTheService() {+ provisioner.delete("AWS::Logs::LogGroup", "g", REGION);+ verify(logs).deleteLogGroup("g", REGION);+ }+}diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsvindex 6fb79a61af..e6d720ffe4 100644--- a/src/test/resources/cloudformation/supported-resource-types.tsv+++ b/src/test/resources/cloudformation/supported-resource-types.tsv@@ -82,7 +82,7 @@ AWS::Lambda::MicrovmImage LambdaMicrovmsCfnProvisionerAWS::Lambda::NetworkConnector LambdaMicrovmsCfnProvisionerAWS::Lambda::Permission LambdaAddressingCfnProvisionerAWS::Lambda::Version LambdaVersionAliasCfnProvisioner-AWS::Logs::LogGroup LEGACY_SWITCH+AWS::Logs::LogGroup LogsCfnProvisionerAWS::Organizations::Account OrganizationsCfnProvisionerAWS::Organizations::Organization OrganizationsCfnProvisionerAWS::Organizations::OrganizationalUnit OrganizationsCfnProvisioner