From df1d850d71306afb6fd042179e39ab9f4d9bbc65 Mon Sep 17 00:00:00 2001 From: jwoa95 <88512616+jwoa95@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:37:43 +0000 Subject: [PATCH] fix(rds): apply minor engine upgrades to backing databases (#8089) Closes floci-io/floci#8007 Persist whether a standalone instance has never initialized its database. Protect engine versions before backend startup so runtime loss and proxy failures cannot expose existing storage to a metadata-only version change. Update SDK compatibility assertions to reject unsupported upgrades and verify resizing separately. Apply supported minor upgrades using the version-specific image on the existing volume and endpoint. Keep major upgrades, downgrades, and pinned-image changes blocked before mutation. Preserve the never-started case, report failed restarts honestly, and restore successful minor-upgrade coverage in the Java SDK compatibility suite. --- .../com/floci/test/RdsControlPlaneTest.java | 20 +- docs/services/rds.md | 42 ++- .../io/floci/aws/services/rds/RdsService.java | 132 +++++++-- .../aws/services/rds/model/DbInstance.java | 7 + ...RdsEngineVersionDockerIntegrationTest.java | 112 ++++++++ .../aws/services/rds/RdsServiceTest.java | 260 ++++++++++++++++++ 6 files changed, 530 insertions(+), 43 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/rds/RdsEngineVersionDockerIntegrationTest.java diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsControlPlaneTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsControlPlaneTest.java index 3a354dce90..96662434e9 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsControlPlaneTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsControlPlaneTest.java @@ -542,8 +542,8 @@ class RdsControlPlaneTest { } @Test - @DisplayName("ModifyDBInstance resizes and upgrades an instance, and Describe reports it") - void sdkResizesAndUpgradesAStandaloneInstance() { + @DisplayName("ModifyDBInstance applies minor upgrades and refuses major upgrades atomically") + void sdkResizesAndAppliesMinorEngineUpgrades() { String instanceName = TestFixtures.uniqueName("rds-resize-db"); try { createDbInstance(rds, instanceName, "resize-secret"); @@ -557,6 +557,7 @@ class RdsControlPlaneTest { assertThat(modified.dbInstanceClass()).isEqualTo("db.t3.large"); assertThat(modified.allocatedStorage()).isEqualTo(100); assertThat(modified.engineVersion()).isEqualTo("16.4"); + assertThat(modified.dbInstanceStatus()).isEqualTo("available"); DBInstance described = rds.describeDBInstances(b -> b.dbInstanceIdentifier(instanceName)) .dbInstances().get(0); @@ -574,11 +575,20 @@ class RdsControlPlaneTest { .isInstanceOfSatisfying(RdsException.class, e -> assertThat( e.awsErrorDetails().errorCode()).isEqualTo("InvalidParameterCombination")); - DBInstance upgraded = rds.modifyDBInstance(b -> b + assertThatThrownBy(() -> rds.modifyDBInstance(b -> b .dbInstanceIdentifier(instanceName) + .dbInstanceClass("db.t3.xlarge") + .allocatedStorage(200) .engineVersion("17.2") - .allowMajorVersionUpgrade(true)).dbInstance(); - assertThat(upgraded.engineVersion()).isEqualTo("17.2"); + .allowMajorVersionUpgrade(true))) + .isInstanceOfSatisfying(RdsException.class, e -> assertThat( + e.awsErrorDetails().errorCode()).isEqualTo("InvalidParameterCombination")); + + DBInstance afterRejectedUpgrades = rds.describeDBInstances(b -> b.dbInstanceIdentifier(instanceName)) + .dbInstances().get(0); + assertThat(afterRejectedUpgrades.engineVersion()).isEqualTo("16.4"); + assertThat(afterRejectedUpgrades.dbInstanceClass()).isEqualTo("db.t3.large"); + assertThat(afterRejectedUpgrades.allocatedStorage()).isEqualTo(100); } finally { deleteDbInstance(rds, instanceName); } diff --git a/docs/services/rds.md b/docs/services/rds.md index c21351d872..9ae529b5a0 100644 --- a/docs/services/rds.md +++ b/docs/services/rds.md @@ -455,7 +455,7 @@ keep a cluster awake; and parameter group changes do not resume one. ## Modifying a DB instance -`ModifyDBInstance` applies `DBInstanceClass`, `AllocatedStorage` and `EngineVersion`, and +`ModifyDBInstance` applies `DBInstanceClass` and `AllocatedStorage`, and `DescribeDBInstances` reports the new values. Members the request leaves out keep their current value, so a partial modify does not reset anything. @@ -467,7 +467,29 @@ value, so a partial modify does not reset anything. rather than refused, which is what AWS does. SQL Server takes the size it is given. - The same size is not a change and is left alone. -`EngineVersion` accepts a minor upgrade on its own. A different major version needs +Standalone container-backed instances support minor `EngineVersion` upgrades when the default +image follows the requested version. Floci stops the proxy and database container, starts the new +engine image on the same storage volume, and rebinds the existing endpoint. It reports `available` +only after both the new backend and proxy have started. A failed restart reports `failed` and +retains the storage volume. + +Major upgrades and downgrades fail with `InvalidParameterCombination` before any settings change. +PostgreSQL 10 and later use the leading component as the major version; older PostgreSQL releases, +MySQL, and MariaDB use the first two components. Existing databases need a migration for a major +upgrade, which Floci does not perform. `AllowMajorVersionUpgrade` does not bypass this limitation. +Custom image overrides and SQL Server do not map `EngineVersion` to a new image, so their version +changes are also refused. Cluster members must use cluster-level engine management. Repeating the +current version is allowed alongside other changes without restarting the database. + +A standalone instance created while Docker is unavailable may change its version before its first +backend startup when its image follows the requested version. Its eventual container uses the +updated version. Floci persists this never-started +state, and protects the version before attempting to initialize the database, including when a later +proxy startup fails. Existing databases remain protected against major changes after a reboot, +storage reload, or lost container. Older records without this state are treated as existing databases. + +In mock mode (`FLOCI_SERVICES_RDS_MOCK=true`), `EngineVersion` updates the instance metadata. +A minor upgrade is accepted on its own. A different major version needs `AllowMajorVersionUpgrade`, without which the request fails with `InvalidParameterCombination`. Major versions are compared on the leading version component, so a MySQL 8.0 to 8.4 upgrade reads as a minor one here while AWS treats it as major. @@ -476,17 +498,11 @@ A refused member fails the whole request: a modify that carries a new `DBInstanc shrinking `AllocatedStorage` returns `InvalidParameterCombination` and leaves the class as it was, so a read-back never reports a value the request did not get. -Two deviations are worth knowing: - -- **Changes apply immediately.** AWS defers a class, storage or engine-version change to the - preferred maintenance window unless `ApplyImmediately` is set, and reports it under - `PendingModifiedValues` until then. Floci runs no maintenance window and does not model - `PendingModifiedValues`, so it applies the change as soon as the request lands whatever - `ApplyImmediately` says. Without this a deferred change would never be applied at all, and every - read-back would report the same drift. -- **The backing container is not re-imaged.** An engine-version change is recorded on the instance - and reported on read, but the container started at create time keeps running the image it was - started with. This is control-plane compatibility, like Aurora Serverless v2 scaling above. +Accepted changes apply immediately. AWS defers a class, storage or engine-version change to the +preferred maintenance window unless `ApplyImmediately` is set, and reports it under +`PendingModifiedValues` until then. Floci runs no maintenance window and does not model +`PendingModifiedValues`, so it applies accepted changes as soon as the request lands whatever +`ApplyImmediately` says. For standalone, non-Aurora instances with instance-owned storage, `CreateDBInstance` and `ModifyDBInstance` retain the `StorageType` values `gp2`, `gp3`, `io1` and `io2`. A modify diff --git a/src/main/java/io/floci/aws/services/rds/RdsService.java b/src/main/java/io/floci/aws/services/rds/RdsService.java index 355dedaeb8..e5760141b1 100644 --- a/src/main/java/io/floci/aws/services/rds/RdsService.java +++ b/src/main/java/io/floci/aws/services/rds/RdsService.java @@ -901,6 +901,7 @@ public class RdsService implements Resettable, ResourceProvider { instance.setContainerHost(handle.getHost()); instance.setContainerPort(handle.getPort()); } else if (!containerManager.refusedParameterGroup(dbInstanceArn)) { + instance.setBackendNeverStarted(containerManager.getActiveHandle(dbInstanceArn) == null); LOG.warnv("DB instance {0} created without a backing database container: no " + "Docker daemon is reachable. Metadata operations work; connections to " + "the database do not until a daemon appears.", id); @@ -3881,6 +3882,8 @@ public class RdsService implements Resettable, ResourceProvider { // Resolved before the first setter runs, since the checks it carries read the instance's // current size and engine version: a refusal here must leave the whole request unapplied. DbInstanceScalingChanges resolvedScaling = scaling.resolveFor(instance); + String previousEngineVersion = instance.getEngineVersion(); + boolean restartForUpgrade = requiresMinorEngineRestart(instance, resolvedScaling.engineVersion()); DbInstanceSettings effective = withEffectiveWindows(settings, instance); if (isBlank(instance.getDbClusterIdentifier()) && !isAuroraEngine(engineName(instance))) { effective.validateStorageType(); @@ -3943,6 +3946,9 @@ public class RdsService implements Resettable, ResourceProvider { instance.setAutoMinorVersionUpgrade(autoMinorVersionUpgrade); } effective.applyTo(instance); + if (restartForUpgrade) { + instance.setStatus(DbInstanceStatus.MODIFYING); + } resolvedScaling.applyTo(instance); if (publiclyAccessible != null) { instance.setPubliclyAccessible(publiclyAccessible); @@ -3964,10 +3970,82 @@ public class RdsService implements Resettable, ResourceProvider { rdsResourceRelayKey(instance.getDbInstanceArn(), id), iamEnabled); } + if (restartForUpgrade) { + restartForMinorEngineUpgrade(instance, previousEngineVersion, effectiveRegion); + } + LOG.infov("DB instance {0} modified", id); return instance; } + private boolean requiresMinorEngineRestart(DbInstance instance, String requestedVersion) { + if (config.services().rds().mock() + || isBlank(requestedVersion) || requestedVersion.equals(instance.getEngineVersion())) { + return false; + } + String currentVersion = instance.getEngineVersion(); + boolean imageChanges = !imageForEngine(instance.getEngine(), currentVersion) + .equals(imageForEngine(instance.getEngine(), requestedVersion)); + if (instance.isBackendNeverStarted() && imageChanges) { + return false; + } + boolean numericVersions = currentVersion != null + && currentVersion.matches("[0-9]{1,9}(\\.[0-9]{1,9})*") + && requestedVersion.matches("[0-9]{1,9}(\\.[0-9]{1,9})*"); + if (!isBlank(instance.getDbClusterIdentifier()) || isAuroraEngine(engineName(instance)) + || !numericVersions + || !engineVersionFamily(instance.getEngine(), currentVersion) + .equals(engineVersionFamily(instance.getEngine(), requestedVersion)) + || RdsEngineCatalog.compareVersions(requestedVersion, currentVersion) <= 0 + || !imageChanges) { + throw new AwsException("InvalidParameterCombination", + "Only minor engine upgrades with version-specific images are supported for " + + "standalone container-backed DB instances.", 400); + } + return true; + } + + private static String engineVersionFamily(DatabaseEngine engine, String version) { + String[] parts = version.split("\\."); + if (parts.length == 1 || engine == DatabaseEngine.POSTGRES && parts[0].length() > 1) { + return parts[0]; + } + return parts[0] + "." + parts[1]; + } + + private void restartForMinorEngineUpgrade(DbInstance instance, String previousVersion, String region) { + String id = instance.getDbInstanceIdentifier(); + String previousContainerId = instance.getContainerId(); + try { + proxyManager.stopProxy(rdsResourceRelayKey(instance.getDbInstanceArn(), id)); + if (previousContainerId != null) { + containerManager.stop(buildHandle(instance)); + } + instance.setContainerId(null); + instance.setContainerHost(null); + instance.setContainerPort(0); + startStandaloneInstanceBackend(instance, id, region); + if (!hasBackend(instance.getContainerHost(), instance.getContainerPort())) { + throw new AwsException("InvalidDBInstanceState", + "The database backend could not be started for the engine version upgrade.", 400); + } + instance.setStatus(DbInstanceStatus.AVAILABLE); + putInstanceForScope(currentAccountId(), region, id, instance); + } catch (RuntimeException | Error failure) { + if (!hasBackend(instance.getContainerHost(), instance.getContainerPort()) + || Objects.equals(previousContainerId, instance.getContainerId())) { + instance.setEngineVersion(previousVersion); + } + instance.setStatus(DbInstanceStatus.FAILED); + try { + putInstanceForScope(currentAccountId(), region, id, instance); + } catch (RuntimeException persistFailure) { + failure.addSuppressed(persistFailure); + } + throw failure; + } + } + /** * Gives a DB instance exactly the VPC security groups {@code groupIds}, as CloudFormation sets * them on an update and puts them back on a rollback. ModifyDBInstance keeps the groups when the @@ -4358,16 +4436,11 @@ public class RdsService implements Resettable, ResourceProvider { } return; } - String image = imageForEngine(instance.getEngine(), instance.getEngineVersion()); String storageResourceId = resolvedInstanceStorageResourceId(instance); String dockerVolumeName = resolvedInstanceDockerVolumeName(instance); RdsContainerHandle handle; try { - handle = containerManager.tryStart( - instance.getDbInstanceArn(), id, storageResourceId, - dockerVolumeName, instance.getEngine(), image, instance.getMasterUsername(), - instance.getMasterPassword(), instance.getDbName(), - instanceEngineParameters(instance)); + handle = startInstanceContainer(instance); } catch (RuntimeException | Error e) { instance.setStatus(DbInstanceStatus.FAILED); putInstanceForScope(currentAccountId(), effectiveRegion, id, instance); @@ -4644,14 +4717,9 @@ public class RdsService implements Resettable, ResourceProvider { } throw e; } - String image = imageForEngine(instance.getEngine(), instance.getEngineVersion()); String storageResourceId = resolvedInstanceStorageResourceId(instance); String dockerVolumeName = resolvedInstanceDockerVolumeName(instance); - RdsContainerHandle handle = containerManager.tryStart( - instance.getDbInstanceArn(), id, storageResourceId, - dockerVolumeName, instance.getEngine(), image, instance.getMasterUsername(), - instance.getMasterPassword(), instance.getDbName(), - instanceEngineParameters(instance)); + RdsContainerHandle handle = startInstanceContainer(instance); instance.setContainerStorageResourceId(storageResourceId); instance.setDockerVolumeName(dockerVolumeName); instance.setContainerId(handle != null ? handle.getContainerId() : null); @@ -4833,12 +4901,7 @@ public class RdsService implements Resettable, ResourceProvider { backendHost = cluster.getContainerHost(); backendPort = cluster.getContainerPort(); } else { - String image = imageForEngine(instance.getEngine(), instance.getEngineVersion()); - started = containerManager.tryStart( - instance.getDbInstanceArn(), id, resolvedInstanceStorageResourceId(instance), - resolvedInstanceDockerVolumeName(instance), instance.getEngine(), image, - instance.getMasterUsername(), instance.getMasterPassword(), instance.getDbName(), - instanceEngineParameters(instance)); + started = startInstanceContainer(instance); if (started == null) { return instance; } @@ -4896,6 +4959,31 @@ public class RdsService implements Resettable, ResourceProvider { return instance; } + /** Records a possible database initialization before startup, even if its proxy later fails. */ + private RdsContainerHandle startInstanceContainer(DbInstance instance) { + boolean neverStarted = instance.isBackendNeverStarted(); + String accountId = accountIdFromArn(instance.getDbInstanceArn()); + String region = regionFromArn(instance.getDbInstanceArn()); + String id = instance.getDbInstanceIdentifier(); + if (neverStarted) { + instance.setBackendNeverStarted(false); + putInstanceForScope(accountId, region, id, instance); + } + RdsContainerHandle started = containerManager.tryStart( + instance.getDbInstanceArn(), id, resolvedInstanceStorageResourceId(instance), + resolvedInstanceDockerVolumeName(instance), instance.getEngine(), + imageForEngine(instance.getEngine(), instance.getEngineVersion()), + instance.getMasterUsername(), instance.getMasterPassword(), instance.getDbName(), + instanceEngineParameters(instance)); + if (neverStarted && started == null + && !containerManager.refusedParameterGroup(instance.getDbInstanceArn()) + && containerManager.getActiveHandle(instance.getDbInstanceArn()) == null) { + instance.setBackendNeverStarted(true); + putInstanceForScope(accountId, region, id, instance); + } + return started; + } + /** * The {@link #ensureInstanceBackend} counterpart for DB clusters. * @@ -9699,13 +9787,7 @@ public class RdsService implements Resettable, ResourceProvider { instance.setContainerHost(cluster.getContainerHost()); instance.setContainerPort(cluster.getContainerPort()); } else { - String image = imageForEngine(instance.getEngine(), instance.getEngineVersion()); - restoredHandle = containerManager.tryStart( - instance.getDbInstanceArn(), instance.getDbInstanceIdentifier(), - instance.getContainerStorageResourceId(), - instance.getDockerVolumeName(), instance.getEngine(), image, - instance.getMasterUsername(), instance.getMasterPassword(), instance.getDbName(), - instanceEngineParameters(instance)); + restoredHandle = startInstanceContainer(instance); backendHost = restoredHandle != null ? restoredHandle.getHost() : null; backendPort = restoredHandle != null ? restoredHandle.getPort() : 0; instance.setContainerId(restoredHandle != null ? restoredHandle.getContainerId() : null); diff --git a/src/main/java/io/floci/aws/services/rds/model/DbInstance.java b/src/main/java/io/floci/aws/services/rds/model/DbInstance.java index 2e8432d926..a71b1df1f7 100644 --- a/src/main/java/io/floci/aws/services/rds/model/DbInstance.java +++ b/src/main/java/io/floci/aws/services/rds/model/DbInstance.java @@ -89,6 +89,8 @@ public class DbInstance { private String dockerVolumeName; private String volumeId; private String containerStorageResourceId; + // Legacy records default to protected: only a confirmed never-started backend may change versions. + private boolean backendNeverStarted; private boolean backendCleanupRequired; private boolean managedSecretCleanupRequired; @@ -297,6 +299,11 @@ public class DbInstance { this.containerStorageResourceId = containerStorageResourceId; } + public boolean isBackendNeverStarted() { return backendNeverStarted; } + public void setBackendNeverStarted(boolean backendNeverStarted) { + this.backendNeverStarted = backendNeverStarted; + } + public boolean isBackendCleanupRequired() { return backendCleanupRequired; } public void setBackendCleanupRequired(boolean backendCleanupRequired) { this.backendCleanupRequired = backendCleanupRequired; diff --git a/src/test/java/io/floci/aws/services/rds/RdsEngineVersionDockerIntegrationTest.java b/src/test/java/io/floci/aws/services/rds/RdsEngineVersionDockerIntegrationTest.java new file mode 100644 index 0000000000..e1f04140f1 --- /dev/null +++ b/src/test/java/io/floci/aws/services/rds/RdsEngineVersionDockerIntegrationTest.java @@ -0,0 +1,112 @@ +package io.floci.aws.services.rds; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.rds.RdsClient; +import software.amazon.awssdk.services.rds.model.DBInstance; +import software.amazon.awssdk.services.rds.model.RdsException; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Duration; + +import static io.floci.aws.testing.RdsRequests.assumeDocker; +import static io.floci.aws.testing.RdsRequests.rdsClient; +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +@Tag("docker") +class RdsEngineVersionDockerIntegrationTest { + + private static final String PASSWORD = "Passw0rd12345"; + + @BeforeEach + void checkDocker() throws InterruptedException { + assumeDocker(); + } + + @Test + void minorUpgradePreservesDataAndMajorUpgradeIsRefused() throws SQLException { + String id = "engine-version-" + Long.toString(System.nanoTime(), 36); + try (RdsClient client = rdsClient("us-east-1", "000000000000")) { + client.createDBInstance(b -> b.dbInstanceIdentifier(id).engine("postgres").engineVersion("16.4") + .dbInstanceClass("db.t3.micro").allocatedStorage(20).dbName("appdb") + .masterUsername("admin").masterUserPassword(PASSWORD)); + try { + DBInstance original = describe(client, id); + int port = original.endpoint().port(); + await().atMost(Duration.ofSeconds(60)).untilAsserted(() -> + assertTrue(query(port, "SHOW server_version").startsWith("16.4"))); + try (Connection connection = connect(port); Statement statement = connection.createStatement()) { + statement.execute("CREATE TABLE upgrade_probe (value TEXT)"); + statement.execute("INSERT INTO upgrade_probe VALUES ('preserved')"); + } + + for (String target : new String[] {"17.2"}) { + for (boolean immediately : new boolean[] {true, false}) { + RdsException error = assertThrows(RdsException.class, () -> + client.modifyDBInstance(b -> b.dbInstanceIdentifier(id).engineVersion(target) + .allowMajorVersionUpgrade(true).applyImmediately(immediately) + .dbInstanceClass("db.t3.large").allocatedStorage(100) + .masterUserPassword("ChangedPassw0rd12345"))); + + assertEquals(400, error.statusCode()); + assertEquals("InvalidParameterCombination", error.awsErrorDetails().errorCode()); + assertTrue(error.getMessage().contains("container-backed")); + DBInstance unchanged = describe(client, id); + assertEquals("16.4", unchanged.engineVersion()); + assertEquals("available", unchanged.dbInstanceStatus()); + assertEquals(original.endpoint(), unchanged.endpoint()); + assertEquals("db.t3.micro", unchanged.dbInstanceClass()); + assertEquals(20, unchanged.allocatedStorage()); + assertTrue(query(port, "SHOW server_version").startsWith("16.4")); + assertEquals("preserved", query(port, "SELECT value FROM upgrade_probe")); + } + } + + DBInstance sameVersion = client.modifyDBInstance(b -> b.dbInstanceIdentifier(id) + .engineVersion("16.4").dbInstanceClass("db.t3.large").applyImmediately(true)).dbInstance(); + assertEquals("16.4", sameVersion.engineVersion()); + assertEquals("db.t3.large", sameVersion.dbInstanceClass()); + assertEquals("preserved", query(port, "SELECT value FROM upgrade_probe")); + + DBInstance upgraded = client.modifyDBInstance(b -> b.dbInstanceIdentifier(id) + .engineVersion("16.5").allocatedStorage(100).applyImmediately(true)).dbInstance(); + assertEquals("16.5", upgraded.engineVersion()); + assertEquals("available", upgraded.dbInstanceStatus()); + assertEquals(original.endpoint(), upgraded.endpoint()); + assertEquals("16.5", describe(client, id).engineVersion()); + assertTrue(query(port, "SHOW server_version").startsWith("16.5")); + assertEquals("preserved", query(port, "SELECT value FROM upgrade_probe")); + } finally { + client.deleteDBInstance(b -> b.dbInstanceIdentifier(id).skipFinalSnapshot(true)); + } + } + } + + private static DBInstance describe(RdsClient client, String id) { + return client.describeDBInstances(b -> b.dbInstanceIdentifier(id)).dbInstances().getFirst(); + } + + private static Connection connect(int port) throws SQLException { + return DriverManager.getConnection("jdbc:postgresql://127.0.0.1:" + port + + "/appdb?sslmode=disable&connectTimeout=5&socketTimeout=5", "admin", PASSWORD); + } + + private static String query(int port, String sql) throws SQLException { + try (Connection connection = connect(port); + Statement statement = connection.createStatement(); + ResultSet rows = statement.executeQuery(sql)) { + assertTrue(rows.next()); + return rows.getString(1); + } + } +} diff --git a/src/test/java/io/floci/aws/services/rds/RdsServiceTest.java b/src/test/java/io/floci/aws/services/rds/RdsServiceTest.java index 831b227902..9e0e8f6409 100644 --- a/src/test/java/io/floci/aws/services/rds/RdsServiceTest.java +++ b/src/test/java/io/floci/aws/services/rds/RdsServiceTest.java @@ -2441,6 +2441,7 @@ class RdsServiceTest { @Test void modifyDbInstanceAppliesInstanceClassStorageAndEngineVersion() { + when(rdsConfig.mock()).thenReturn(true); createScalingInstance("scaled", "postgres", "13", 20); DbInstance modified = rdsService.modifyDbInstance("scaled", null, null, null, @@ -2519,6 +2520,7 @@ class RdsServiceTest { @Test void modifyDbInstanceRejectsMajorEngineVersionUpgradeWithoutTheFlag() { + when(rdsConfig.mock()).thenReturn(true); createScalingInstance("major", "postgres", "13", 20); AwsException error = assertThrows(AwsException.class, () -> @@ -2532,6 +2534,7 @@ class RdsServiceTest { @Test void modifyDbInstanceAppliesMajorEngineVersionUpgradeWithTheFlag() { + when(rdsConfig.mock()).thenReturn(true); createScalingInstance("major-allowed", "postgres", "13", 20); DbInstance modified = rdsService.modifyDbInstance("major-allowed", null, null, null, @@ -2585,6 +2588,263 @@ class RdsServiceTest { assertEquals(1, stored.getBackupRetentionPeriod()); } + @Test + void modifyDbInstanceRestartsAMinorUpgradeOnTheSameStorageAndEndpoint() { + createScalingInstance("minor-upgrade", "postgres", "16.4", 20); + DbInstance original = rdsService.getDbInstance("minor-upgrade"); + DbEndpoint endpoint = original.getEndpoint(); + String volume = original.getDockerVolumeName(); + String storageId = original.getContainerStorageResourceId(); + clearInvocations(containerManager, proxyManager); + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(new RdsContainerHandle("upgraded-container", "minor-upgrade", "localhost", 15432)); + + DbInstance modified = rdsService.modifyDbInstance("minor-upgrade", null, null, null, + null, null, null, null, DbInstanceSettings.unchanged(), null, + new DbInstanceScalingChanges("db.t3.large", 100, "16.5", null)); + + assertEquals("16.5", modified.getEngineVersion()); + assertEquals("upgraded-container", modified.getContainerId()); + assertEquals("db.t3.large", modified.getDbInstanceClass()); + assertEquals(100, modified.getAllocatedStorage()); + assertEquals(endpoint, modified.getEndpoint()); + assertEquals(volume, modified.getDockerVolumeName()); + assertEquals(storageId, modified.getContainerStorageResourceId()); + verify(containerManager).stop(any()); + verify(containerManager).tryStart(eq(original.getDbInstanceArn()), eq("minor-upgrade"), + eq(storageId), eq(volume), eq(DatabaseEngine.POSTGRES), eq("postgres:16.5-alpine"), + eq("admin"), eq("Password123!"), eq("dbname"), any()); + verify(proxyManager).stopProxy(any()); + } + + @ParameterizedTest + @CsvSource({"mysql,8.0.36,8.0.37,mysql:8.0.37", "mariadb,10.11.11,10.11.12,mariadb:10.11.12", + "postgres,9.5.1,9.5.2,postgres:9.5.2-alpine"}) + void minorUpgradeUsesTheEnginesVersionedImage(String engine, String current, String target, String image) { + createScalingInstance("minor-image", engine, current, 20); + clearInvocations(containerManager); + + DbInstance modified = rdsService.modifyDbInstance("minor-image", null, null, null, + null, null, null, null, DbInstanceSettings.unchanged(), null, + new DbInstanceScalingChanges(null, null, target, null)); + + assertEquals(target, modified.getEngineVersion()); + assertEquals(DbInstanceStatus.AVAILABLE, modified.getStatus()); + verify(containerManager).tryStart(any(), eq("minor-image"), any(), any(), eq(modified.getEngine()), + eq(image), any(), any(), any(), any()); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void minorUpgradeRefusesAPinnedImageWithoutChangingTheInstance(boolean offline) { + when(rdsConfig.defaultPostgresImage()).thenReturn(Optional.of("postgres:16.4-alpine")); + if (offline) { + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(null); + } + createScalingInstance("pinned-upgrade", "postgres", "16.4", 20); + clearInvocations(containerManager, proxyManager); + + AwsException error = assertThrows(AwsException.class, () -> + rdsService.modifyDbInstance("pinned-upgrade", null, null, null, + null, null, null, null, DbInstanceSettings.unchanged(), null, + new DbInstanceScalingChanges("db.t3.large", 100, "16.5", null))); + + assertEquals("InvalidParameterCombination", error.getErrorCode()); + assertEquals("16.4", rdsService.getDbInstance("pinned-upgrade").getEngineVersion()); + assertEquals("db.t3.micro", rdsService.getDbInstance("pinned-upgrade").getDbInstanceClass()); + assertEquals(20, rdsService.getDbInstance("pinned-upgrade").getAllocatedStorage()); + verifyNoInteractions(containerManager, proxyManager); + } + + @ParameterizedTest + @ValueSource(strings = {"stop", "start", "unavailable", "proxy"}) + void failedMinorUpgradeDoesNotReportAnAvailableDatabase(String failurePhase) { + createScalingInstance("failed-minor", "postgres", "16.4", 20); + if ("stop".equals(failurePhase)) { + doThrow(new IllegalStateException("stop failed")).when(containerManager).stop(any()); + } else if ("start".equals(failurePhase)) { + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenThrow(new IllegalStateException("start failed")); + } else if ("unavailable".equals(failurePhase)) { + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(null); + } else { + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(new RdsContainerHandle("new-container", "failed-minor", "localhost", 15432)); + doThrow(new IllegalStateException("proxy failed")).when(proxyManager).startProxy( + any(), any(), any(), anyBoolean(), anyInt(), any(), anyInt(), + any(), any(), any(), any(), any(), any()); + } + + assertThrows(RuntimeException.class, () -> + rdsService.modifyDbInstance("failed-minor", null, null, null, + null, null, null, null, DbInstanceSettings.unchanged(), null, + new DbInstanceScalingChanges(null, null, "16.5", null))); + + DbInstance failed = rdsService.getDbInstance("failed-minor"); + assertEquals(DbInstanceStatus.FAILED, failed.getStatus()); + assertEquals("proxy".equals(failurePhase) ? "16.5" : "16.4", failed.getEngineVersion()); + verify(containerManager, never()).removeVolume(any(), any(), any()); + } + + @Test + void modifyDbInstanceRejectsContainerBackedMajorEngineVersionChanges() { + createScalingInstance("real-engine", "postgres", "16.4", 20); + + AwsException error = assertThrows(AwsException.class, () -> + rdsService.modifyDbInstance("real-engine", null, null, null, + null, null, null, null, DbInstanceSettings.unchanged(), null, + new DbInstanceScalingChanges(null, null, "17.2", true))); + + assertEquals("InvalidParameterCombination", error.getErrorCode()); + assertEquals(400, error.getHttpStatus()); + assertEquals("16.4", rdsService.getDbInstance("real-engine").getEngineVersion()); + } + + @Test + void modifyDbInstanceUpdatesEngineVersionBeforeTheFirstBackendStart() { + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(null); + createScalingInstance("offline-upgrade", "postgres", "16.4", 20); + assertNull(rdsService.getDbInstance("offline-upgrade").getContainerId()); + assertNull(rdsService.ensureInstanceBackend("offline-upgrade", "us-east-1").getContainerId()); + + DbInstance modified = rdsService.modifyDbInstance("offline-upgrade", null, null, null, + null, null, null, null, DbInstanceSettings.unchanged(), null, + new DbInstanceScalingChanges(null, null, "17.2", true)); + + assertEquals("17.2", modified.getEngineVersion()); + assertTrue(modified.isBackendNeverStarted()); + clearInvocations(containerManager); + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(new RdsContainerHandle("new-container", "offline-upgrade", "localhost", 5432)); + DbInstance started = rdsService.ensureInstanceBackend("offline-upgrade", "us-east-1"); + + assertEquals("17.2", started.getEngineVersion()); + assertEquals("new-container", started.getContainerId()); + assertFalse(started.isBackendNeverStarted()); + verify(containerManager).tryStart(any(), eq("offline-upgrade"), any(), any(), eq(DatabaseEngine.POSTGRES), + eq("postgres:17.2-alpine"), any(), any(), any(), any()); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void engineVersionProtectionSurvivesMissingRuntimeAndStorageReload( + boolean started, @TempDir Path directory) { + Path file = directory.resolve("instances.json"); + TypeReference> type = new TypeReference<>() {}; + PersistentStorage instances = new PersistentStorage<>(file, type); + rdsService = newService(containerManager, proxyManager, instances, + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>()); + if (!started) { + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(null); + } + createScalingInstance("history-db", "postgres", "16.4", 20); + DbInstance created = rdsService.getDbInstance("history-db"); + created.setContainerId(null); + created.setContainerHost(null); + created.setContainerPort(0); + instances.put(instances.keys().iterator().next(), created); + + PersistentStorage reloaded = new PersistentStorage<>(file, type); + reloaded.load(); + rdsService = newService(containerManager, proxyManager, reloaded, + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>()); + Executable modify = () -> rdsService.modifyDbInstance("history-db", null, null, null, + null, null, null, null, DbInstanceSettings.unchanged(), null, + new DbInstanceScalingChanges(null, null, "17.2", true)); + + if (started) { + assertEquals("InvalidParameterCombination", assertThrows(AwsException.class, modify).getErrorCode()); + assertEquals("16.4", rdsService.getDbInstance("history-db").getEngineVersion()); + } else { + assertDoesNotThrow(modify); + assertEquals("17.2", rdsService.getDbInstance("history-db").getEngineVersion()); + } + } + + @Test + void engineVersionProtectionIsPersistedBeforeAProxyStartupFailure(@TempDir Path directory) { + Path file = directory.resolve("instances.json"); + TypeReference> type = new TypeReference<>() {}; + PersistentStorage instances = new PersistentStorage<>(file, type); + rdsService = newService(containerManager, proxyManager, instances, + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>()); + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(null); + createScalingInstance("failed-proxy", "postgres", "16.4", 20); + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(new RdsContainerHandle("late-container", "failed-proxy", "localhost", 5432)); + doThrow(new IllegalStateException("port in use")).when(proxyManager).startProxy( + any(), any(), any(), anyBoolean(), anyInt(), any(), anyInt(), any(), any(), any(), any(), any(), any()); + + assertThrows(IllegalStateException.class, () -> rdsService.ensureInstanceBackend("failed-proxy", "us-east-1")); + + PersistentStorage reloaded = new PersistentStorage<>(file, type); + reloaded.load(); + rdsService = newService(containerManager, proxyManager, reloaded, + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>()); + assertNull(rdsService.getDbInstance("failed-proxy").getContainerId()); + assertEquals("InvalidParameterCombination", assertThrows(AwsException.class, () -> + rdsService.modifyDbInstance("failed-proxy", null, null, null, + null, null, null, null, DbInstanceSettings.unchanged(), null, + new DbInstanceScalingChanges(null, null, "17.2", true))).getErrorCode()); + } + + @ParameterizedTest + @CsvSource({"mysql,8.0,8.4", "mariadb,10.11,11.4", "mariadb,10.11,10.12", "sqlserver-se,15.00,16.00", + "sqlserver-se,15.00,15.00.2000", "postgres,16.4,16.3", "postgres,9.5.1,9.6.1"}) + void modifyDbInstanceRejectsOtherContainerBackedVersionChanges( + String engine, String currentVersion, String targetVersion) { + createScalingInstance("other-engine", engine, currentVersion, 20); + + AwsException error = assertThrows(AwsException.class, () -> + rdsService.modifyDbInstance("other-engine", null, null, null, + null, null, null, null, DbInstanceSettings.unchanged(), null, + new DbInstanceScalingChanges(null, null, targetVersion, true))); + + assertEquals("InvalidParameterCombination", error.getErrorCode()); + assertEquals(currentVersion, rdsService.getDbInstance("other-engine").getEngineVersion()); + } + + @Test + void rejectedContainerEngineUpgradeLeavesOtherSettingsAndBackendsUntouched() { + createScalingInstance("atomic-upgrade", "postgres", "16.4", 20); + clearInvocations(containerManager, proxyManager); + + assertThrows(AwsException.class, () -> + rdsService.modifyDbInstance("atomic-upgrade", "ChangedPassword!", true, null, + null, null, null, false, + new DbInstanceSettings(null, null, 7, null, null, null), null, + new DbInstanceScalingChanges("db.t3.large", 100, "17.2", true))); + + DbInstance stored = rdsService.getDbInstance("atomic-upgrade"); + assertEquals("16.4", stored.getEngineVersion()); + assertEquals("db.t3.micro", stored.getDbInstanceClass()); + assertEquals(20, stored.getAllocatedStorage()); + assertEquals("Password123!", stored.getMasterPassword()); + assertFalse(stored.isIamDatabaseAuthenticationEnabled()); + assertTrue(stored.isAutoMinorVersionUpgrade()); + assertEquals(1, stored.getBackupRetentionPeriod()); + verifyNoInteractions(containerManager, proxyManager); + } + + @ParameterizedTest + @ValueSource(strings = {"16.4", "", " "}) + void modifyDbInstanceAcceptsUnchangedContainerBackedEngineVersion(String version) { + createScalingInstance("same-engine", "postgres", "16.4", 20); + + DbInstance modified = rdsService.modifyDbInstance("same-engine", null, null, null, + null, null, null, null, DbInstanceSettings.unchanged(), null, + new DbInstanceScalingChanges("db.t3.large", 100, version, null)); + + assertEquals("16.4", modified.getEngineVersion()); + assertEquals("db.t3.large", modified.getDbInstanceClass()); + assertEquals(100, modified.getAllocatedStorage()); + } + private void createScalingInstance(String id, String engine, String engineVersion, int storage) { String dbName = engine.startsWith("sqlserver") ? null : "dbname"; rdsService.createDbInstance(id, engine, engineVersion,