From d7c42e206530243e4917fcd6bff01ec90a056e58 Mon Sep 17 00:00:00 2001 From: Oleksandr Nikolaichuk <57410473+Sekator778@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:20:42 +0300 Subject: [PATCH] fix(cloudformation): replace a log group through the engine and delete the old one only after the update commits (#8463) * fix(cloudformation): replace a log group through the engine and delete the old one only after the update commits * refactor: use the derived record form * test(cloudformation): pin a renamed log group surviving a rolled-back update * test(cloudformation): bring the log group unit tests to engine-decided replacement * fix: drop the retired name-mode attribute on update --- .../provisioners/LogsCfnProvisioner.java | 133 +++++++----------- ...CloudFormationLogGroupProvisionerTest.java | 20 --- .../CloudFormationLogsIntegrationTest.java | 67 +++++++++ .../provisioners/LogsCfnProvisionerTest.java | 55 ++++---- 4 files changed, 146 insertions(+), 129 deletions(-) diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/LogsCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/LogsCfnProvisioner.java index 820e6b5e18..0931a1e0bf 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/LogsCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/LogsCfnProvisioner.java @@ -15,15 +15,7 @@ import java.util.Set; @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; @@ -36,32 +28,57 @@ public class LogsCfnProvisioner implements CfnResourceProvisioner { return Set.of("AWS::Logs::LogGroup"); } + @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 provision(StackResource r, JsonNode props, ProvisionContext ctx) { + if (ctx.isUpdate()) { + // Rolling this update back undoes it alone; only ContinueUpdateRollback retries the + // delete the last rollback could not make. + ReplacementCleanup.endRollbackRetry(r); + } + Map attributesBefore = new HashMap<>(r.getAttributes()); 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; + // LogGroupName is create-only, so the engine's change decides whether this update replaces + // the group. A named group cannot be replaced under the same name. + boolean replaces = ctx.isUpdate() && priorPhysicalId != null + && ctx.changes("AWS::Logs::LogGroup", props).requiresReplacement(); + if (replaces && hasExplicitName && explicitName.equals(priorPhysicalId)) { + throw CfnExceptions.customNamedReplacement(explicitName); } - // 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. + } else if (priorPhysicalId != null && !replaces) { + // No explicit name and no replacement: keep the prior name across updates instead of + // generating a fresh random one each time, so the log group is reconciled in place. name = priorPhysicalId; } else { name = ctx.generatePhysicalName(r.getLogicalId(), LOG_GROUP_NAME_MAX_LENGTH, false); @@ -87,38 +104,25 @@ public class LogsCfnProvisioner implements CfnResourceProvisioner { } } - // 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. + // Reconcile in place when the name is unchanged and the group is still there; otherwise this is + // either a first create or a replacement, both of which need a fresh createLogGroup call. A + // replacement leaves the old group alone: ReplacementCleanup deletes it once the stack update + // commits, or the new one when the update rolls back. 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()); - } + logsService.createLogGroup(name, retentionInDays, tags, ctx.region()); } // Ref returns the log group name; GetAtt Arn is arn:aws:logs:::log-group::* r.setPhysicalId(name); + // Written by earlier versions to tell a rename from a no-op; the engine decides that now. + r.getAttributes().remove("FlociLogGroupNameMode"); 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); + // createLogGroup fails on an existing name, so a replacing update always created its group. + ReplacementCleanup.record(r, ctx, attributesBefore); } private void reconcileLogGroup(String name, Integer retentionInDays, Map tags, @@ -140,44 +144,9 @@ public class LogsCfnProvisioner implements CfnResourceProvisioner { } } - /** - * 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); + CfnDeletes.safeDelete("log group", physicalId, + () -> logsService.deleteLogGroup(physicalId, region), "ResourceNotFoundException"); } } diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationLogGroupProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationLogGroupProvisionerTest.java index 69da140502..82e09e6357 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationLogGroupProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationLogGroupProvisionerTest.java @@ -12,8 +12,6 @@ import java.util.Map; import java.util.function.Function; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; @@ -49,24 +47,6 @@ class CloudFormationLogGroupProvisionerTest { .build(); } - @Test - void legacyExplicitNameWithNoRecordedMode_replacesWhenNameIsRemoved() { - // Simulates a log group created before FlociLogGroupNameMode was tracked: no attributes at - // all, and a physical id that does not match generatePhysicalName's shape, so it must have - // been an explicit LogGroupName the caller chose. - String legacyExplicitName = "my-hand-chosen-log-group"; - when(logsService.logGroupExists(legacyExplicitName, REGION)).thenReturn(true); - - StackResource result = provision("{}", legacyExplicitName, Map.of()); - - assertEquals("CREATE_COMPLETE", result.getStatus()); - assertNotEquals(legacyExplicitName, result.getPhysicalId()); - assertTrue(result.getPhysicalId().startsWith(STACK_NAME + "-LogGroup-"), - "expected a freshly generated name, got: " + result.getPhysicalId()); - verify(logsService).createLogGroup(eq(result.getPhysicalId()), isNull(), anyMap(), eq(REGION)); - verify(logsService).deleteLogGroup(legacyExplicitName, REGION); - } - @Test void legacyGeneratedNameWithNoRecordedMode_reconcilesInPlace() { // A physical id matching the exact --<12 hex chars> shape must have diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationLogsIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationLogsIntegrationTest.java index e375414e55..d067f23fc3 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationLogsIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationLogsIntegrationTest.java @@ -368,6 +368,73 @@ class CloudFormationLogsIntegrationTest { .body(containsString(oldName)); } + @Test + void renamedLogGroupSurvivesARolledBackUpdateAndTheReplacementIsRemoved() { + // LogGroupName is "Update requires: Replacement": AWS creates the new group first and removes + // the old one only in the cleanup phase after the whole update succeeds. When a later + // resource fails, the rollback keeps the old group and deletes the new one. + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-logs-rename-rollback-stack-" + suffix; + String oldName = "/cfn/test/rb-old-" + suffix; + String newName = "/cfn/test/rb-new-" + suffix; + String failingTemplate = """ + {"Resources":{ + "LogGroup":{"Type":"AWS::Logs::LogGroup","Properties":{"LogGroupName":"%s"}}, + "ZFail":{"Type":"AWS::CloudFormation::Stack","DependsOn":"LogGroup","Properties":{}} + }} + """.formatted(newName); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "CreateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", logGroupTemplate(oldName, 7)) + .when() + .post("/") + .then() + .statusCode(200); + CfnStackWaits.awaitStatus(stackName, "CREATE_COMPLETE", CFN_AUTH); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "UpdateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", failingTemplate) + .when() + .post("/") + .then() + .statusCode(200); + CfnStackWaits.awaitStatus(stackName, "UPDATE_ROLLBACK_COMPLETE", CFN_AUTH); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DescribeStackResources") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("" + oldName + "")) + .body(not(containsString(newName))); + + given() + .config(RestAssured.config().encoderConfig(EncoderConfig.encoderConfig() + .encodeContentTypeAs("application/x-amz-json-1.1", ContentType.TEXT))) + .header("Authorization", LOGS_AUTH) + .header("X-Amz-Target", "Logs_20140328.DescribeLogGroups") + .contentType("application/x-amz-json-1.1") + .body("{\"logGroupNamePrefix\":\"/cfn/test/rb-\"}") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("\"logGroupName\":\"" + oldName + "\"")) + .body(not(containsString(newName))); + } + @Test void updateStackRemovingExplicitName_generatesFreshNameInsteadOfKeepingOld() { // Going from an explicit LogGroupName to none is a naming-mode change, which is itself a diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/LogsCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/LogsCfnProvisionerTest.java index a74913ea2e..23b9f5fdbe 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/LogsCfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/LogsCfnProvisionerTest.java @@ -66,13 +66,19 @@ class LogsCfnProvisionerTest { /** Provisions as a create (no prior physical id) or an update (prior id and attributes). */ private StackResource provision(String json, String priorPhysicalId, Map attrs) { + return provision(json, priorPhysicalId, attrs, null); + } + + private StackResource provision(String json, String priorPhysicalId, Map attrs, + String priorJson) { 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)); + new ProvisionContext(engine, REGION, ACCOUNT_ID, STACK, priorPhysicalId, + event -> { }, priorJson == null ? null : props(priorJson))); return r; } @@ -86,15 +92,13 @@ class LogsCfnProvisionerTest { 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() { + void anUnnamedGroupGetsAGeneratedName() { StackResource r = provision("{}", null, Map.of()); assertTrue(r.getPhysicalId().startsWith("my-stack-LogGroup-"), r.getPhysicalId()); - assertEquals("generated", r.getAttributes().get("FlociLogGroupNameMode")); } @Test @@ -147,55 +151,52 @@ class LogsCfnProvisionerTest { verify(logs, never()).putRetentionPolicy(anyString(), anyInt(), anyString()); } + /** The old group is not deleted inline: the engine deletes it on commit, via the recorded cleanup. */ @Test - void arenameCreatesTheNewGroupBeforeDeletingTheOld() { + void aRenameCreatesTheNewGroupAndLeavesTheOldForTheEngineToDelete() { when(logs.logGroupExists("old", REGION)).thenReturn(true); StackResource r = provision(""" {"LogGroupName": "new"} - """, "old", Map.of("FlociLogGroupNameMode", "explicit")); + """, "old", Map.of(), """ + {"LogGroupName": "old"} + """); assertEquals("new", r.getPhysicalId()); verify(logs).createLogGroup(eq("new"), isNull(), anyMap(), eq(REGION)); - verify(logs).deleteLogGroup("old", REGION); + verify(logs, never()).deleteLogGroup("old", REGION); + assertTrue(provisioner.hasReplacementUpdate(r)); + assertEquals("old", provisioner.updateCleanupPhysicalId(r)); } - /** - * 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. - */ + /** If creating the replacement fails, the original is untouched and the failure propagates. */ @Test - void aFailedRenameLeavesTheOriginalAndFlagsTheRollback() { + void aFailedRenameLeavesTheOriginalAndThrows() { 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(""" + assertThrows(RuntimeException.class, () -> provision(""" {"LogGroupName": "new"} - """), new ProvisionContext(engine, REGION, ACCOUNT_ID, STACK, "old"))); + """, "old", Map.of(), """ + {"LogGroupName": "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. - */ + /** Dropping an explicit LogGroupName is a replacement on real AWS. */ @Test void removingAnExplicitNameReplacesTheGroup() { when(logs.logGroupExists("chosen", REGION)).thenReturn(true); - StackResource r = provision("{}", "chosen", Map.of("FlociLogGroupNameMode", "explicit")); + StackResource r = provision("{}", "chosen", Map.of(), """ + {"LogGroupName": "chosen"} + """); assertTrue(r.getPhysicalId().startsWith("my-stack-LogGroup-"), r.getPhysicalId()); - verify(logs).deleteLogGroup("chosen", REGION); + verify(logs, never()).deleteLogGroup("chosen", REGION); + assertEquals("chosen", provisioner.updateCleanupPhysicalId(r)); } /** A generated name is kept across updates so a no-op update does not churn the group. */