mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(rds): enhance DB cluster handling by recording createOnly properties and updating rollback logic (#3636)
Signed-off-by: Matheus André <matheusandr2@gmail.com>
This commit is contained in:
1 parent
a5ebda01fb
commit
b2b43dfb3c
2 files changed
+407
-25
No files matched your search
+167
-25
@@ -1,6 +1,8 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
@@ -17,6 +19,7 @@ import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
@@ -41,6 +44,45 @@ import java.util.Set;
|
||||
public class RdsCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(RdsCfnProvisioner.class);
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
/**
|
||||
* The createOnlyProperties of {@code AWS::RDS::DBCluster} that nothing on the cluster on file
|
||||
* records. {@code DBClusterIdentifier} is the physical id, {@code EngineMode},
|
||||
* {@code StorageEncrypted} and {@code DatabaseName} are fields of the cluster, but Floci does not
|
||||
* emulate a KMS key, public access, a subnet group placement chosen by the template or a
|
||||
* restore source on a cluster, so a change to one of these can only be seen against what the
|
||||
* template said last time. The values the last successful provision resolved are kept on the
|
||||
* resource under {@link #DB_CLUSTER_CREATE_ONLY_ATTR}, which is how CloudFormation decides too:
|
||||
* on the template's change, not on the live entity.
|
||||
*/
|
||||
static final List<String> DB_CLUSTER_RECORDED_CREATE_ONLY = List.of(
|
||||
"ClusterScalabilityType", "DBSubnetGroupName", "DBSystemId", "KmsKeyId",
|
||||
"PubliclyAccessible", "RestoreToTime", "RestoreType", "SnapshotIdentifier",
|
||||
"SourceDBClusterIdentifier", "SourceDbClusterResourceId", "SourceRegion",
|
||||
"UseLatestRestorableTime");
|
||||
/**
|
||||
* The booleans among {@link #DB_CLUSTER_RECORDED_CREATE_ONLY}, recorded as {@code true}/
|
||||
* {@code false} however the template spelled them. {@code UseLatestRestorableTime} defaults to
|
||||
* false, so an absent one is recorded as false. {@code PubliclyAccessible} has no fixed default
|
||||
* (AWS documents true without a subnet group or with the default one, false with a custom one),
|
||||
* so an absent one is recorded as absent and a template that later spells out either value is a
|
||||
* change: the cluster may have been created public.
|
||||
*/
|
||||
private static final Set<String> DB_CLUSTER_BOOLEAN_CREATE_ONLY =
|
||||
Set.of("PubliclyAccessible", "UseLatestRestorableTime");
|
||||
private static final Set<String> DB_CLUSTER_DEFAULT_FALSE_CREATE_ONLY = Set.of("UseLatestRestorableTime");
|
||||
/**
|
||||
* The recorded createOnly values of a DB cluster resource, a JSON object keyed by property.
|
||||
* Internal, like the other {@code __Floci} attributes. A resource provisioned before these were
|
||||
* recorded has none, and its first update records them without replacing anything.
|
||||
*/
|
||||
static final String DB_CLUSTER_CREATE_ONLY_ATTR = "__FlociDbClusterCreateOnly";
|
||||
/**
|
||||
* The record an update overwrote, kept until the update commits so a rollback puts it back
|
||||
* beside the prior cluster; an empty value means there was no record before.
|
||||
*/
|
||||
static final String DB_CLUSTER_CREATE_ONLY_PRIOR_ATTR = "__FlociDbClusterCreateOnlyPrior";
|
||||
|
||||
private final RdsService rdsService;
|
||||
private final CfnDynamicReferences dynamicReferences;
|
||||
@@ -113,23 +155,35 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
@Override
|
||||
public UpdateCleanupResult completeUpdate(StackResource resource) {
|
||||
resource.getAttributes().remove(DB_CLUSTER_CREATE_ONLY_PRIOR_ATTR);
|
||||
return ReplacementCleanup.complete(resource, this::delete);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearUpdate(StackResource resource) {
|
||||
resource.getAttributes().remove(DB_CLUSTER_CREATE_ONLY_PRIOR_ATTR);
|
||||
ReplacementCleanup.clear(resource);
|
||||
}
|
||||
|
||||
/**
|
||||
* A replacement is undone through the cleanup record: the resource names the displaced cluster
|
||||
* again and the replacement is deleted. Without a record the update was in place, and putting
|
||||
* that back needs a snapshot this provisioner does not keep, so the engine keeps reporting it
|
||||
* as not rolled back, as before.
|
||||
* again and the replacement is deleted. The createOnly record follows the cluster back, since
|
||||
* {@link ReplacementCleanup} leaves {@code __Floci} attributes alone. Without a record the
|
||||
* update was in place, and putting that back needs a snapshot this provisioner does not keep,
|
||||
* so the engine keeps reporting it as not rolled back, as before.
|
||||
*/
|
||||
@Override
|
||||
public boolean rollbackUpdate(StackResource resource) {
|
||||
return ReplacementCleanup.rollback(resource, this::delete);
|
||||
boolean replaced = ReplacementCleanup.rollback(resource, this::delete);
|
||||
String priorRecord = resource.getAttributes().remove(DB_CLUSTER_CREATE_ONLY_PRIOR_ATTR);
|
||||
if (priorRecord != null) {
|
||||
if (priorRecord.isEmpty()) {
|
||||
resource.getAttributes().remove(DB_CLUSTER_CREATE_ONLY_ATTR);
|
||||
} else {
|
||||
resource.getAttributes().put(DB_CLUSTER_CREATE_ONLY_ATTR, priorRecord);
|
||||
}
|
||||
}
|
||||
return replaced;
|
||||
}
|
||||
|
||||
private void provisionDbSubnetGroup(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
|
||||
@@ -292,14 +346,16 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
|
||||
}
|
||||
|
||||
/**
|
||||
* A DB cluster follows CloudFormation's replacement lifecycle. {@code DBClusterIdentifier},
|
||||
* {@code EngineMode} and {@code StorageEncrypted} are createOnlyProperties in the
|
||||
* {@code AWS::RDS::DBCluster} schema, so a change to any of them creates the replacement under
|
||||
* a distinct physical id first and leaves the displaced cluster standing: it is deleted once
|
||||
* the stack update commits ({@link #completeUpdate}), or the resource is pointed back at it and
|
||||
* the replacement is removed when a later resource fails the update ({@link #rollbackUpdate}).
|
||||
* A cluster the template names explicitly has no distinct id to move to, which is the update
|
||||
* CloudFormation refuses for a custom-named resource, so it is refused here the same way.
|
||||
* A DB cluster follows CloudFormation's replacement lifecycle. A change to any of the
|
||||
* createOnlyProperties in the {@code AWS::RDS::DBCluster} schema ({@code DBClusterIdentifier},
|
||||
* {@code EngineMode}, {@code StorageEncrypted} and {@code DatabaseName} against the cluster on
|
||||
* file, the rest against what the template said last time, see
|
||||
* {@link #DB_CLUSTER_RECORDED_CREATE_ONLY}) creates the replacement under a distinct physical
|
||||
* id first and leaves the displaced cluster standing: it is deleted once the stack update
|
||||
* commits ({@link #completeUpdate}), or the resource is pointed back at it and the replacement
|
||||
* is removed when a later resource fails the update ({@link #rollbackUpdate}). A cluster the
|
||||
* template names explicitly has no distinct id to move to, which is the update CloudFormation
|
||||
* refuses for a custom-named resource, so it is refused here the same way.
|
||||
*/
|
||||
private void provisionDbCluster(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
|
||||
ProvisionContext ctx, String region) {
|
||||
@@ -321,16 +377,19 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
|
||||
DbCluster cluster = sameNameExistingResource(priorPhysicalId, id, rdsService::getDbCluster);
|
||||
String engineMode = resolveOptional(props, "EngineMode", engine);
|
||||
boolean storageEncrypted = parseBoolProp(props, "StorageEncrypted", engine);
|
||||
if (cluster != null && requiresDbClusterReplacement(cluster, engineMode, storageEncrypted)) {
|
||||
String databaseName = resolveOptional(props, "DatabaseName", engine);
|
||||
Map<String, String> createOnly = dbClusterRecordedCreateOnly(props, engine);
|
||||
String replacementReason = cluster == null ? null : dbClusterReplacementReason(cluster,
|
||||
engineMode, storageEncrypted, databaseName,
|
||||
readDbClusterCreateOnly(attributesBefore.get(DB_CLUSTER_CREATE_ONLY_ATTR)), createOnly);
|
||||
if (replacementReason != null) {
|
||||
if (customNamed) {
|
||||
throw new AwsException("ValidationError",
|
||||
"CloudFormation cannot update a stack when a custom-named resource requires "
|
||||
+ "replacing. Rename " + id + " and update the stack again.", 400);
|
||||
}
|
||||
id = ctx.generatePhysicalName(r.getLogicalId(), 60, true);
|
||||
LOG.infov("Replacing DB cluster {0} with {1}: EngineMode/StorageEncrypted changed from "
|
||||
+ "{2}/{3} to {4}/{5}", priorPhysicalId, id, cluster.getEngineMode(),
|
||||
cluster.isStorageEncrypted(), engineMode, storageEncrypted);
|
||||
LOG.infov("Replacing DB cluster {0} with {1}: {2}", priorPhysicalId, id, replacementReason);
|
||||
cluster = null;
|
||||
}
|
||||
if (cluster != null) {
|
||||
@@ -352,7 +411,6 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
|
||||
resolveOptionalWithoutDynamicReferences(props, "MasterUsername", engine), region, false);
|
||||
String masterPassword = resolveDynamicReferences(
|
||||
resolveOptionalWithoutDynamicReferences(props, "MasterUserPassword", engine), region, true);
|
||||
String databaseName = resolveOptional(props, "DatabaseName", engine);
|
||||
boolean iamEnabled = parseBoolProp(props, "EnableIAMDatabaseAuthentication", engine);
|
||||
String parameterGroup = resolveOptional(props, "DBClusterParameterGroupName", engine);
|
||||
if (engineMode == null && !storageEncrypted) {
|
||||
@@ -387,23 +445,107 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
|
||||
if (cluster.getDbClusterResourceId() != null) {
|
||||
r.getAttributes().put("DBClusterResourceId", cluster.getDbClusterResourceId());
|
||||
}
|
||||
recordDbClusterCreateOnly(r, ctx, attributesBefore, createOnly);
|
||||
// A provision that left the resource with a new physical id replaced the cluster: the
|
||||
// displaced one is deleted once the update commits, or restored if the update rolls back.
|
||||
ReplacementCleanup.record(r, ctx, attributesBefore);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the template's {@code EngineMode}/{@code StorageEncrypted} differ from the cluster on
|
||||
* file. Both are createOnlyProperties, so a difference means replacement. A template without
|
||||
* {@code EngineMode} means the RDS default {@code provisioned}, and a cluster persisted before
|
||||
* the mode was tracked reports no mode at all, which is the same default.
|
||||
* Why the template's createOnly properties call for a replacement of the cluster on file, or
|
||||
* null when they describe it. {@code EngineMode}, {@code StorageEncrypted} and
|
||||
* {@code DatabaseName} are read from the cluster itself: a template without {@code EngineMode}
|
||||
* means the RDS default {@code provisioned}, and a cluster persisted before the mode was tracked
|
||||
* reports no mode at all, which is the same default. The rest are read from the record the last
|
||||
* provision left ({@link #DB_CLUSTER_RECORDED_CREATE_ONLY}); a resource without one predates
|
||||
* the record, and nothing on file can say what it was created with, so it is kept.
|
||||
*/
|
||||
private static boolean requiresDbClusterReplacement(DbCluster existing, String engineMode,
|
||||
boolean storageEncrypted) {
|
||||
private static String dbClusterReplacementReason(DbCluster existing, String engineMode,
|
||||
boolean storageEncrypted, String databaseName,
|
||||
Map<String, String> recorded,
|
||||
Map<String, String> desired) {
|
||||
List<String> changed = new ArrayList<>();
|
||||
String desiredMode = firstNonBlank(engineMode, "provisioned");
|
||||
String currentMode = firstNonBlank(existing.getEngineMode(), "provisioned");
|
||||
return !desiredMode.equalsIgnoreCase(currentMode)
|
||||
|| existing.isStorageEncrypted() != storageEncrypted;
|
||||
if (!desiredMode.equalsIgnoreCase(currentMode)) {
|
||||
changed.add("EngineMode " + currentMode + " -> " + desiredMode);
|
||||
}
|
||||
if (existing.isStorageEncrypted() != storageEncrypted) {
|
||||
changed.add("StorageEncrypted " + existing.isStorageEncrypted() + " -> " + storageEncrypted);
|
||||
}
|
||||
String currentDatabase = firstNonBlank(existing.getDatabaseName(), null);
|
||||
String desiredDatabase = firstNonBlank(databaseName, null);
|
||||
if (!Objects.equals(currentDatabase, desiredDatabase)) {
|
||||
changed.add("DatabaseName " + currentDatabase + " -> " + desiredDatabase);
|
||||
}
|
||||
if (recorded != null) {
|
||||
for (String property : DB_CLUSTER_RECORDED_CREATE_ONLY) {
|
||||
if (!Objects.equals(recorded.get(property), desired.get(property))) {
|
||||
changed.add(property + " " + recorded.get(property) + " -> " + desired.get(property));
|
||||
}
|
||||
}
|
||||
}
|
||||
return changed.isEmpty() ? null : String.join(", ", changed);
|
||||
}
|
||||
|
||||
/**
|
||||
* The template's values for {@link #DB_CLUSTER_RECORDED_CREATE_ONLY}: a value only when set,
|
||||
* booleans normalised to {@code true}/{@code false}, and the ones with a fixed default of false
|
||||
* recorded as false when absent (see {@link #DB_CLUSTER_BOOLEAN_CREATE_ONLY}).
|
||||
*/
|
||||
private Map<String, String> dbClusterRecordedCreateOnly(JsonNode props,
|
||||
CloudFormationTemplateEngine engine) {
|
||||
Map<String, String> values = new LinkedHashMap<>();
|
||||
for (String property : DB_CLUSTER_RECORDED_CREATE_ONLY) {
|
||||
String value = resolveOptional(props, property, engine);
|
||||
boolean set = value != null && !value.isBlank();
|
||||
if (DB_CLUSTER_BOOLEAN_CREATE_ONLY.contains(property)) {
|
||||
if (set) {
|
||||
values.put(property, String.valueOf(Boolean.parseBoolean(value.trim())));
|
||||
} else if (DB_CLUSTER_DEFAULT_FALSE_CREATE_ONLY.contains(property)) {
|
||||
values.put(property, "false");
|
||||
}
|
||||
} else if (set) {
|
||||
values.put(property, value);
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the createOnly record the next update compares against. On an update that changed it
|
||||
* (a replacement, or the first record of a resource that predates it) the previous record is
|
||||
* kept beside it until the update commits, so {@link #rollbackUpdate} can put it back.
|
||||
*/
|
||||
private static void recordDbClusterCreateOnly(StackResource r, ProvisionContext ctx,
|
||||
Map<String, String> attributesBefore,
|
||||
Map<String, String> createOnly) {
|
||||
String priorRecord = attributesBefore.get(DB_CLUSTER_CREATE_ONLY_ATTR);
|
||||
if (ctx.isUpdate() && !createOnly.equals(readDbClusterCreateOnly(priorRecord))) {
|
||||
r.getAttributes().put(DB_CLUSTER_CREATE_ONLY_PRIOR_ATTR, priorRecord == null ? "" : priorRecord);
|
||||
}
|
||||
ObjectNode record = MAPPER.createObjectNode();
|
||||
createOnly.forEach(record::put);
|
||||
r.getAttributes().put(DB_CLUSTER_CREATE_ONLY_ATTR, record.toString());
|
||||
}
|
||||
|
||||
/** The record as a map, or null when the resource carries none or it cannot be read. */
|
||||
private static Map<String, String> readDbClusterCreateOnly(String raw) {
|
||||
if (raw == null || raw.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
JsonNode node = MAPPER.readTree(raw);
|
||||
if (!node.isObject()) {
|
||||
return null;
|
||||
}
|
||||
Map<String, String> values = new LinkedHashMap<>();
|
||||
node.fields().forEachRemaining(e -> values.put(e.getKey(), e.getValue().asText()));
|
||||
return values;
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Ignoring unreadable DB cluster createOnly record: {0}", raw);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private Double parseServerlessV2Capacity(JsonNode props, String field,
|
||||
|
||||
+240
@@ -25,6 +25,7 @@ import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InOrder;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.util.List;
|
||||
@@ -1544,6 +1545,245 @@ class RdsCfnProvisionerTest {
|
||||
verify(rdsService).modifyDbCluster("mycluster", null, false, null, null, null, "us-east-1");
|
||||
}
|
||||
|
||||
// ── the remaining createOnlyProperties of AWS::RDS::DBCluster ──
|
||||
|
||||
private static final String CREATE_ONLY_ATTR = "__FlociDbClusterCreateOnly";
|
||||
private static final String CREATE_ONLY_PRIOR_ATTR = "__FlociDbClusterCreateOnlyPrior";
|
||||
|
||||
/**
|
||||
* A CreateStack of the template, leaving the cluster on file under a generated physical id
|
||||
* and the resource carrying the createOnly record the next update compares against.
|
||||
*/
|
||||
private StackResource createUnnamedCluster(String json) {
|
||||
createDbClusterEchoesRequestedId();
|
||||
StackResource created = provision("Cluster", "AWS::RDS::DBCluster", json);
|
||||
assertEquals("CREATE_COMPLETE", created.getStatus(), created.getStatusReason());
|
||||
DbCluster existing = mock(DbCluster.class);
|
||||
when(rdsService.getDbCluster(any())).thenReturn(existing);
|
||||
DbCluster reconciled = mock(DbCluster.class);
|
||||
when(reconciled.getDbClusterIdentifier()).thenReturn(created.getPhysicalId());
|
||||
when(rdsService.modifyDbCluster(eq(created.getPhysicalId()), any(), anyBoolean(),
|
||||
any(), any(), any(), eq("us-east-1"))).thenReturn(reconciled);
|
||||
return created;
|
||||
}
|
||||
|
||||
private StackResource updateCluster(StackResource committed, String json) {
|
||||
return provisionExisting("Cluster", "AWS::RDS::DBCluster", json, "us-east-1",
|
||||
committed.getPhysicalId(), committed.getAttributes());
|
||||
}
|
||||
|
||||
/** A template with {@code Engine} and one more property, quoted unless it is a boolean. */
|
||||
private static String clusterTemplate(String property, String value) {
|
||||
String literal = "true".equals(value) || "false".equals(value) ? value : "\"" + value + "\"";
|
||||
return "{\"Engine\":\"aurora-postgresql\",\"" + property + "\":" + literal + "}";
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateStackReplacesDbClusterWhenDatabaseNameChanges() {
|
||||
// DatabaseName is createOnly and the cluster on file records it, so the change is read
|
||||
// from the cluster like EngineMode and StorageEncrypted.
|
||||
DbCluster existing = priorUnnamedCluster("provisioned", false);
|
||||
when(existing.getDatabaseName()).thenReturn("appdb");
|
||||
createDbClusterEchoesRequestedId();
|
||||
|
||||
StackResource r = updateUnnamedCluster("""
|
||||
{"Engine":"aurora-postgresql","DatabaseName":"reports"}
|
||||
""");
|
||||
|
||||
assertEquals("CREATE_COMPLETE", r.getStatus());
|
||||
String replacement = r.getPhysicalId();
|
||||
assertNotEquals(PRIOR_CLUSTER, replacement);
|
||||
verify(rdsService).createDbCluster(replacement, "aurora-postgresql", null, null, null,
|
||||
"reports", false, null, null, null, false, "us-east-1");
|
||||
verify(rdsService, never()).modifyDbCluster(any(), any(), any(), any(), any(), any(), any());
|
||||
verify(rdsService, never()).deleteDbCluster(any(), any());
|
||||
assertEquals(PRIOR_CLUSTER, provisioner.updateCleanupPhysicalId(r));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"KmsKeyId, alias/aws/rds, arn:aws:kms:us-east-1:000000000000:key/11111111-2222-3333-4444-555555555555",
|
||||
"DBSubnetGroupName, private-subnets, public-subnets",
|
||||
"DBSystemId, rdsCustomOracle, rdsCustomOracle2",
|
||||
"PubliclyAccessible, false, true",
|
||||
"ClusterScalabilityType, standard, limitless",
|
||||
"SnapshotIdentifier, nightly-1, nightly-2",
|
||||
"SourceDBClusterIdentifier, source-a, source-b",
|
||||
"SourceDbClusterResourceId, cluster-AAAA, cluster-BBBB",
|
||||
"SourceRegion, us-west-2, eu-west-1",
|
||||
"RestoreType, full-copy, copy-on-write",
|
||||
"RestoreToTime, 2026-01-01T00:00:00Z, 2026-02-01T00:00:00Z",
|
||||
"UseLatestRestorableTime, false, true"
|
||||
})
|
||||
void updateStackReplacesDbClusterWhenARecordedCreateOnlyPropertyChanges(
|
||||
String property, String before, String after) {
|
||||
// Nothing on the cluster on file records these, so the change is read against what the
|
||||
// template said when the cluster was created: the same replacement lifecycle as EngineMode,
|
||||
// with the prior cluster owed a delete only after the update commits.
|
||||
StackResource created = createUnnamedCluster(clusterTemplate(property, before));
|
||||
String prior = created.getPhysicalId();
|
||||
assertTrue(created.getAttributes().get(CREATE_ONLY_ATTR).contains("\"" + property + "\""));
|
||||
assertFalse(created.getAttributes().containsKey(CREATE_ONLY_PRIOR_ATTR),
|
||||
"a create has no record to roll back to");
|
||||
|
||||
StackResource r = updateCluster(created, clusterTemplate(property, after));
|
||||
|
||||
assertEquals("CREATE_COMPLETE", r.getStatus(), r.getStatusReason());
|
||||
assertNotEquals(prior, r.getPhysicalId());
|
||||
verify(rdsService, never()).modifyDbCluster(any(), any(), any(), any(), any(), any(), any());
|
||||
verify(rdsService, never()).deleteDbCluster(any(), any());
|
||||
assertTrue(r.getAttributes().get(CREATE_ONLY_ATTR).contains(after));
|
||||
assertEquals(prior, provisioner.updateCleanupPhysicalId(r));
|
||||
UpdateCleanupResult cleanup = provisioner.completeUpdate(r);
|
||||
assertTrue(cleanup.complete());
|
||||
verify(rdsService).deleteDbCluster(prior, "us-east-1");
|
||||
assertFalse(r.getAttributes().containsKey(CREATE_ONLY_PRIOR_ATTR),
|
||||
"the committed update drops the record it replaced");
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateStackKeepsDbClusterWhenRecordedCreateOnlyPropertiesUnchanged() {
|
||||
// The same values, a boolean with a fixed default omitted instead of written as false, and
|
||||
// a changed mutable property describe the same cluster: it is modified in place and the
|
||||
// record stands.
|
||||
StackResource created = createUnnamedCluster("""
|
||||
{"Engine":"aurora-postgresql","KmsKeyId":"alias/aws/rds","UseLatestRestorableTime":false,
|
||||
"DBSubnetGroupName":"private-subnets","MasterUserPassword":"secret"}
|
||||
""");
|
||||
String record = created.getAttributes().get(CREATE_ONLY_ATTR);
|
||||
|
||||
StackResource r = updateCluster(created, """
|
||||
{"Engine":"aurora-postgresql","KmsKeyId":"alias/aws/rds",
|
||||
"DBSubnetGroupName":"private-subnets","MasterUserPassword":"rotated"}
|
||||
""");
|
||||
|
||||
assertEquals("CREATE_COMPLETE", r.getStatus(), r.getStatusReason());
|
||||
assertEquals(created.getPhysicalId(), r.getPhysicalId());
|
||||
verify(rdsService).modifyDbCluster(created.getPhysicalId(), "rotated", false,
|
||||
null, null, null, "us-east-1");
|
||||
verify(rdsService, times(1)).createDbCluster(any(), any(), any(), any(), any(), any(),
|
||||
anyBoolean(), any(), any(), any(), anyBoolean(), any());
|
||||
assertEquals(record, r.getAttributes().get(CREATE_ONLY_ATTR));
|
||||
assertFalse(r.getAttributes().containsKey(CREATE_ONLY_PRIOR_ATTR));
|
||||
assertFalse(provisioner.hasReplacementUpdate(r));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"false", "true"})
|
||||
void updateStackReplacesDbClusterWhenPubliclyAccessibleIsSpelledOutAfterBeingOmitted(String value) {
|
||||
// PubliclyAccessible has no fixed default: AWS makes an omitted one true or false depending
|
||||
// on the subnet group, so a cluster created without it may well be public, and a template
|
||||
// that later writes either value is a change CloudFormation replaces on. Absent stays
|
||||
// absent in the record rather than being read as false.
|
||||
StackResource created = createUnnamedCluster("""
|
||||
{"Engine":"aurora-postgresql","DBSubnetGroupName":"private-subnets"}
|
||||
""");
|
||||
String prior = created.getPhysicalId();
|
||||
assertFalse(created.getAttributes().get(CREATE_ONLY_ATTR).contains("PubliclyAccessible"));
|
||||
|
||||
StackResource r = updateCluster(created, """
|
||||
{"Engine":"aurora-postgresql","DBSubnetGroupName":"private-subnets",
|
||||
"PubliclyAccessible":%s}
|
||||
""".formatted(value));
|
||||
|
||||
assertEquals("CREATE_COMPLETE", r.getStatus(), r.getStatusReason());
|
||||
assertNotEquals(prior, r.getPhysicalId());
|
||||
verify(rdsService, never()).modifyDbCluster(any(), any(), any(), any(), any(), any(), any());
|
||||
assertEquals(prior, provisioner.updateCleanupPhysicalId(r));
|
||||
assertTrue(r.getAttributes().get(CREATE_ONLY_ATTR).contains("\"PubliclyAccessible\":\"" + value + "\""));
|
||||
|
||||
// And the other way round: dropping it again is a change too.
|
||||
provisioner.completeUpdate(r);
|
||||
StackResource dropped = updateCluster(r, """
|
||||
{"Engine":"aurora-postgresql","DBSubnetGroupName":"private-subnets"}
|
||||
""");
|
||||
assertEquals("CREATE_COMPLETE", dropped.getStatus(), dropped.getStatusReason());
|
||||
assertNotEquals(r.getPhysicalId(), dropped.getPhysicalId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateStackRecordsCreateOnlyPropertiesOfAClusterProvisionedBeforeTheyWereTracked() {
|
||||
// A resource from before the record existed says nothing about what its cluster was
|
||||
// created with, so the first update keeps the cluster and records the template; the update
|
||||
// after that is compared against the record.
|
||||
priorUnnamedCluster("provisioned", false);
|
||||
DbCluster reconciled = mock(DbCluster.class);
|
||||
when(reconciled.getDbClusterIdentifier()).thenReturn(PRIOR_CLUSTER);
|
||||
when(rdsService.modifyDbCluster(eq(PRIOR_CLUSTER), any(), anyBoolean(),
|
||||
any(), any(), any(), eq("us-east-1"))).thenReturn(reconciled);
|
||||
|
||||
StackResource first = updateUnnamedCluster("""
|
||||
{"Engine":"aurora-postgresql","KmsKeyId":"alias/aws/rds"}
|
||||
""");
|
||||
|
||||
assertEquals("CREATE_COMPLETE", first.getStatus(), first.getStatusReason());
|
||||
assertEquals(PRIOR_CLUSTER, first.getPhysicalId());
|
||||
verify(rdsService).modifyDbCluster(PRIOR_CLUSTER, null, false, null, null, null, "us-east-1");
|
||||
assertTrue(first.getAttributes().get(CREATE_ONLY_ATTR).contains("alias/aws/rds"));
|
||||
assertEquals("", first.getAttributes().get(CREATE_ONLY_PRIOR_ATTR),
|
||||
"a rollback of this update drops the record again");
|
||||
provisioner.clearUpdate(first);
|
||||
assertFalse(first.getAttributes().containsKey(CREATE_ONLY_PRIOR_ATTR));
|
||||
|
||||
createDbClusterEchoesRequestedId();
|
||||
StackResource second = updateCluster(first, """
|
||||
{"Engine":"aurora-postgresql","KmsKeyId":"alias/other"}
|
||||
""");
|
||||
|
||||
assertEquals("CREATE_COMPLETE", second.getStatus(), second.getStatusReason());
|
||||
assertNotEquals(PRIOR_CLUSTER, second.getPhysicalId());
|
||||
assertEquals(PRIOR_CLUSTER, provisioner.updateCleanupPhysicalId(second));
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedLaterUpdateRollsBackTheCreateOnlyRecordWithTheDbCluster() {
|
||||
// The record follows the cluster: rolled back to the prior cluster, the resource compares
|
||||
// the next template against what that cluster was created with, not the replacement.
|
||||
StackResource created = createUnnamedCluster(clusterTemplate("KmsKeyId", "alias/aws/rds"));
|
||||
String prior = created.getPhysicalId();
|
||||
String priorRecord = created.getAttributes().get(CREATE_ONLY_ATTR);
|
||||
StackResource r = updateCluster(created, clusterTemplate("KmsKeyId", "alias/other"));
|
||||
String replacement = r.getPhysicalId();
|
||||
assertNotEquals(prior, replacement);
|
||||
assertEquals(priorRecord, r.getAttributes().get(CREATE_ONLY_PRIOR_ATTR));
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
|
||||
assertEquals(prior, r.getPhysicalId());
|
||||
assertEquals(priorRecord, r.getAttributes().get(CREATE_ONLY_ATTR));
|
||||
assertFalse(r.getAttributes().containsKey(CREATE_ONLY_PRIOR_ATTR));
|
||||
verify(rdsService).deleteDbCluster(replacement, "us-east-1");
|
||||
verify(rdsService, never()).deleteDbCluster(prior, "us-east-1");
|
||||
|
||||
StackResource again = updateCluster(r, clusterTemplate("KmsKeyId", "alias/aws/rds"));
|
||||
|
||||
assertEquals("CREATE_COMPLETE", again.getStatus(), again.getStatusReason());
|
||||
assertEquals(prior, again.getPhysicalId(), "the rolled-back template describes the prior cluster");
|
||||
verify(rdsService).modifyDbCluster(prior, null, false, null, null, null, "us-east-1");
|
||||
verify(rdsService, times(2)).createDbCluster(any(), any(), any(), any(), any(), any(),
|
||||
anyBoolean(), any(), any(), any(), anyBoolean(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void customNamedDbClusterRefusesRecordedCreateOnlyPropertyChange() {
|
||||
createDbClusterEchoesRequestedId();
|
||||
StackResource created = provision("Cluster", "AWS::RDS::DBCluster", """
|
||||
{"DBClusterIdentifier":"mycluster","Engine":"aurora-postgresql","KmsKeyId":"alias/aws/rds"}
|
||||
""");
|
||||
when(rdsService.getDbCluster("mycluster")).thenReturn(mock(DbCluster.class));
|
||||
|
||||
StackResource r = updateCluster(created, """
|
||||
{"DBClusterIdentifier":"mycluster","Engine":"aurora-postgresql","KmsKeyId":"alias/other"}
|
||||
""");
|
||||
|
||||
assertEquals("CREATE_FAILED", r.getStatus());
|
||||
assertTrue(r.getStatusReason().contains(
|
||||
"custom-named resource requires replacing. Rename mycluster and update the stack again."));
|
||||
assertEquals("mycluster", r.getPhysicalId());
|
||||
verify(rdsService, never()).deleteDbCluster(any(), any());
|
||||
verify(rdsService, never()).modifyDbCluster(any(), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteDelegatesToRdsServiceForEachRdsType() {
|
||||
// Stack deletion tears down RDS resources via the physical id set at provision time.
|
||||
|
||||
Reference in new issue
Block a user