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 d00df757f1..c0dcfb8ebb 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 @@ -31,6 +31,7 @@ import software.amazon.awssdk.services.rds.model.ModifyOptionGroupResponse; import software.amazon.awssdk.services.rds.model.OptionConfiguration; import software.amazon.awssdk.services.rds.model.OptionGroupNotFoundException; import software.amazon.awssdk.services.rds.model.OptionSetting; +import software.amazon.awssdk.services.rds.model.RdsException; import software.amazon.awssdk.services.rds.model.Tag; import java.util.List; @@ -433,6 +434,49 @@ class RdsControlPlaneTest { } } + @Test + @DisplayName("ModifyDBInstance resizes and upgrades an instance, and Describe reports it") + void sdkResizesAndUpgradesAStandaloneInstance() { + String instanceName = TestFixtures.uniqueName("rds-resize-db"); + try { + createDbInstance(rds, instanceName, "resize-secret"); + + DBInstance modified = rds.modifyDBInstance(b -> b + .dbInstanceIdentifier(instanceName) + .dbInstanceClass("db.t3.large") + .allocatedStorage(100) + .engineVersion("16.4")).dbInstance(); + + assertThat(modified.dbInstanceClass()).isEqualTo("db.t3.large"); + assertThat(modified.allocatedStorage()).isEqualTo(100); + assertThat(modified.engineVersion()).isEqualTo("16.4"); + + DBInstance described = rds.describeDBInstances(b -> b.dbInstanceIdentifier(instanceName)) + .dbInstances().get(0); + assertThat(described.dbInstanceClass()).isEqualTo("db.t3.large"); + assertThat(described.allocatedStorage()).isEqualTo(100); + assertThat(described.engineVersion()).isEqualTo("16.4"); + + assertThatThrownBy(() -> rds.modifyDBInstance(b -> b + .dbInstanceIdentifier(instanceName).allocatedStorage(50))) + .isInstanceOfSatisfying(RdsException.class, e -> assertThat( + e.awsErrorDetails().errorCode()).isEqualTo("InvalidParameterCombination")); + + assertThatThrownBy(() -> rds.modifyDBInstance(b -> b + .dbInstanceIdentifier(instanceName).engineVersion("17.2"))) + .isInstanceOfSatisfying(RdsException.class, e -> assertThat( + e.awsErrorDetails().errorCode()).isEqualTo("InvalidParameterCombination")); + + DBInstance upgraded = rds.modifyDBInstance(b -> b + .dbInstanceIdentifier(instanceName) + .engineVersion("17.2") + .allowMajorVersionUpgrade(true)).dbInstance(); + assertThat(upgraded.engineVersion()).isEqualTo("17.2"); + } finally { + deleteDbInstance(rds, instanceName); + } + } + @Test void sdkCopiesModifiesAndDeletesManualSnapshots() { String instanceName = TestFixtures.uniqueName("rds-snap-db"); diff --git a/docs/services/rds.md b/docs/services/rds.md index 9d57193210..11f03c463e 100644 --- a/docs/services/rds.md +++ b/docs/services/rds.md @@ -261,6 +261,44 @@ new scaling configuration instead of assuming that the cluster is Aurora. This is control-plane compatibility: Floci persists and returns the scaling configuration, but it does not resize or automatically pause the backing Docker container. +## Modifying a DB instance + +`ModifyDBInstance` applies `DBInstanceClass`, `AllocatedStorage` and `EngineVersion`, and +`DescribeDBInstances` reports the new values. Members the request leaves out keep their current +value, so a partial modify does not reset anything. + +`AllocatedStorage` follows the AWS rules for the member: + +- A size smaller than the current one fails with `InvalidParameterCombination`. RDS storage never + shrinks. +- On PostgreSQL, MySQL and MariaDB, an increase of less than 10% is rounded up to 10% greater + 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 +`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. + +A refused member fails the whole request: a modify that carries a new `DBInstanceClass` alongside a +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. + +`StorageType`, `MultiAZ` and `Iops` are not read on a modify yet. Floci reports every instance as +`gp2`. + ## Examples ```bash diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/RdsCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/RdsCfnProvisioner.java index 04b28e5b64..ee2d37ffad 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/RdsCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/RdsCfnProvisioner.java @@ -309,10 +309,11 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner { // provision() is re-invoked on every UpdateStack for every resource, so a same-id instance // already on file must be reconciled rather than re-created (createDbInstance throws - // DBInstanceAlreadyExists). Only the properties RdsService.modifyDbInstance actually supports - // (password, IAM auth, subnet group) are reconciled here; other property changes (engine, - // instance class, allocated storage, ...) are a pre-existing gap in that method, not addressed - // by this fix. + // DBInstanceAlreadyExists). Only password, IAM auth and subnet group are reconciled here. + // modifyDbInstance also takes DBInstanceClass, AllocatedStorage and EngineVersion now, but + // threading them through an UpdateStack is a separate change: DBInstanceClass and + // AllocatedStorage are update-in-place on the AWS::RDS::DBInstance schema while Engine is + // create-only, so passing them needs the replacement handling the DB cluster arm has. DbInstance instance = sameNameExistingResource(priorPhysicalId, id, rdsService::getDbInstance); if (instance != null) { instance = rdsService.modifyDbInstance( diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java index c6931627a9..5b739a38fa 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java @@ -14,6 +14,7 @@ import io.github.hectorvent.floci.services.rds.model.DbEndpoint; import io.github.hectorvent.floci.services.docdb.DocDbQueryHandler; import io.github.hectorvent.floci.services.neptune.NeptuneQueryHandler; import io.github.hectorvent.floci.services.rds.model.DbInstance; +import io.github.hectorvent.floci.services.rds.model.DbInstanceScalingChanges; import io.github.hectorvent.floci.services.rds.model.DbInstanceSettings; import io.github.hectorvent.floci.services.rds.model.LogExportChanges; import io.github.hectorvent.floci.services.rds.model.DbInstanceStatus; @@ -409,11 +410,12 @@ public class RdsQueryHandler { } try { DbInstanceSettings settings = instanceSettings(params, false); + DbInstanceScalingChanges scaling = scalingChanges(params); List vpcSecurityGroupIds = vpcSecurityGroupIds(params); DbInstance instance = service.modifyDbInstance( id, newPassword, iamEnabled, dbSubnetGroupName, vpcSecurityGroupIds, optionGroupName, region, autoMinorVersionUpgrade, - settings, publiclyAccessible); + settings, publiclyAccessible, scaling); String result = dbInstanceXml(instance); return Response.ok(AwsQueryResponse.envelope("ModifyDBInstance", AwsNamespaces.RDS, result)).build(); } catch (AwsException e) { @@ -421,6 +423,18 @@ public class RdsQueryHandler { } } + /** + * The members a modify scales the instance by. Reading them here is why an SDK request to + * resize a live instance, or to upgrade its engine version, used to be accepted and dropped. + */ + private static DbInstanceScalingChanges scalingChanges(MultivaluedMap params) { + return new DbInstanceScalingChanges( + params.getFirst("DBInstanceClass"), + optionalInt(params.getFirst("AllocatedStorage")), + params.getFirst("EngineVersion"), + parseOptionalBoolean(params, "AllowMajorVersionUpgrade")); + } + private static DbInstanceSettings instanceSettings(MultivaluedMap params) { return instanceSettings(params, true); } @@ -2220,7 +2234,7 @@ public class RdsQueryHandler { xml.elem("IAMDatabaseAuthenticationEnabled", i.isIamDatabaseAuthenticationEnabled()) .elem("MultiAZ", i.isMultiAz()) .elem("AutoMinorVersionUpgrade", i.isAutoMinorVersionUpgrade()) - .elem("StorageType", "gp2") + .elem("StorageType", DbInstance.DEFAULT_STORAGE_TYPE) .elem("PubliclyAccessible", i.isPubliclyAccessible()) .elem("AvailabilityZone", i.getAvailabilityZone() != null ? i.getAvailabilityZone() : config.defaultAvailabilityZone()) .elem("PreferredMaintenanceWindow", i.getPreferredMaintenanceWindow() != null diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java index 2a43ee3fef..250b4ebd43 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java @@ -33,6 +33,7 @@ import io.github.hectorvent.floci.services.rds.model.DbEndpoint; import io.github.hectorvent.floci.services.rds.model.DbInstance; import io.github.hectorvent.floci.services.kms.KmsService; import io.github.hectorvent.floci.services.kms.model.KmsKey; +import io.github.hectorvent.floci.services.rds.model.DbInstanceScalingChanges; import io.github.hectorvent.floci.services.rds.model.DbInstanceSettings; import io.github.hectorvent.floci.services.rds.model.DbInstanceStatus; import io.github.hectorvent.floci.services.rds.model.DbParameterGroup; @@ -2400,13 +2401,24 @@ public class RdsService implements Resettable, ResourceProvider { settings, null); } + public DbInstance modifyDbInstance( + String id, String newPassword, Boolean iamEnabled, + String dbSubnetGroupName, List vpcSecurityGroupIds, + String optionGroupName, String region, Boolean autoMinorVersionUpgrade, + DbInstanceSettings settings, Boolean publiclyAccessible) { + return modifyDbInstance(id, newPassword, iamEnabled, dbSubnetGroupName, + vpcSecurityGroupIds, optionGroupName, region, autoMinorVersionUpgrade, + settings, publiclyAccessible, DbInstanceScalingChanges.unchanged()); + } + // synchronized like the tag and delete paths: an unguarded read-modify-write here could // write an instance back after deleteDbInstance removed it public synchronized DbInstance modifyDbInstance( String id, String newPassword, Boolean iamEnabled, String dbSubnetGroupName, List vpcSecurityGroupIds, String optionGroupName, String region, Boolean autoMinorVersionUpgrade, - DbInstanceSettings settings, Boolean publiclyAccessible) { + DbInstanceSettings settings, Boolean publiclyAccessible, + DbInstanceScalingChanges scaling) { validateInstanceSettings(settings); String effectiveRegion = effectiveRegion(region); DbInstance instance = getDbInstance(id, effectiveRegion); @@ -2416,6 +2428,9 @@ public class RdsService implements Resettable, ResourceProvider { "DB instance " + id + " is in state " + instance.getStatus().name().toLowerCase(Locale.ROOT) + " and cannot be modified.", 400); } + // 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); DbInstanceSettings effective = withEffectiveWindows(settings, instance); instance.setStatus(DbInstanceStatus.AVAILABLE); if (optionGroupName != null && !optionGroupName.isBlank()) { @@ -2457,6 +2472,7 @@ public class RdsService implements Resettable, ResourceProvider { instance.setAutoMinorVersionUpgrade(autoMinorVersionUpgrade); } effective.applyTo(instance); + resolvedScaling.applyTo(instance); if (publiclyAccessible != null) { instance.setPubliclyAccessible(publiclyAccessible); } diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstance.java b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstance.java index 78c8d50e19..bfb9b425cb 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstance.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstance.java @@ -11,6 +11,9 @@ import java.util.Map; @RegisterForReflection public class DbInstance { + /** The only storage type Floci models, and the one DescribeDBInstances reports. */ + public static final String DEFAULT_STORAGE_TYPE = "gp2"; + private String dbInstanceIdentifier; private DatabaseEngine engine; // the engine name the request gave (aurora-postgresql, postgres, ...): the enum collapses the diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstanceScalingChanges.java b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstanceScalingChanges.java new file mode 100644 index 0000000000..1b614a5bcb --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstanceScalingChanges.java @@ -0,0 +1,108 @@ +package io.github.hectorvent.floci.services.rds.model; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.Set; + +/** + * The compute, storage and engine-version members of ModifyDBInstance: the ones AWS applies with + * an outage rather than in the background. A null member is one the request left out, which leaves + * the instance's current value alone. + * + *

Floci applies them as soon as the request lands. AWS defers them to the preferred maintenance + * window unless ApplyImmediately is set, and reports them under PendingModifiedValues until then; + * Floci runs no maintenance window, so a deferred change would never be applied at all and every + * read-back would report drift. + */ +@RegisterForReflection +public record DbInstanceScalingChanges(String dbInstanceClass, + Integer allocatedStorage, + String engineVersion, + Boolean allowMajorVersionUpgrade) { + + /** + * The engines whose AllocatedStorage member documents "the value supplied must be at least 10% + * greater than the current value". SQL Server, the fourth engine Floci models, is not one of + * them and takes the size it is given. + */ + private static final Set TEN_PERCENT_MINIMUM_INCREASE = + Set.of(DatabaseEngine.POSTGRES, DatabaseEngine.MYSQL, DatabaseEngine.MARIADB); + + public static DbInstanceScalingChanges unchanged() { + return new DbInstanceScalingChanges(null, null, null, null); + } + + /** + * The same changes with AllocatedStorage resolved against the instance and every rule checked, + * which leaves {@link #applyTo} pure assignment. AWS refuses a request as a whole, and the + * instance a modify works on is the stored object rather than a copy, so a member written + * before a later member is refused would stay written and read back as drift. + */ + public DbInstanceScalingChanges resolveFor(DbInstance instance) { + if (engineVersion != null && !engineVersion.isBlank()) { + requireMajorVersionUpgradeAllowed(instance.getEngineVersion()); + } + Integer resolvedStorage = + allocatedStorage == null ? null : resolvedAllocatedStorage(instance); + return new DbInstanceScalingChanges(dbInstanceClass, resolvedStorage, engineVersion, + allowMajorVersionUpgrade); + } + + /** Assigns the members of an instance resolved by {@link #resolveFor}. */ + public void applyTo(DbInstance instance) { + if (dbInstanceClass != null && !dbInstanceClass.isBlank()) { + instance.setDbInstanceClass(dbInstanceClass); + } + if (allocatedStorage != null) { + instance.setAllocatedStorage(allocatedStorage); + } + if (engineVersion != null && !engineVersion.isBlank()) { + instance.setEngineVersion(engineVersion); + } + } + + /** + * The size the instance ends up with. RDS storage only ever grows: a smaller size is refused, + * and an increase of less than 10% is rounded up to 10% rather than refused, both as the + * AllocatedStorage member documents. The same size is left alone, since it is not a change. + */ + private int resolvedAllocatedStorage(DbInstance instance) { + int current = instance.getAllocatedStorage(); + if (allocatedStorage == current) { + return current; + } + if (allocatedStorage < current) { + throw new AwsException("InvalidParameterCombination", + "Invalid storage size for engine name " + instance.getEngineIdentifier() + + " and storage type " + DbInstance.DEFAULT_STORAGE_TYPE + ": " + + allocatedStorage, 400); + } + if (!TEN_PERCENT_MINIMUM_INCREASE.contains(instance.getEngine())) { + return allocatedStorage; + } + return Math.max(allocatedStorage, Math.ceilDiv(current * 11, 10)); + } + + /** + * AllowMajorVersionUpgrade states the rule as a constraint on EngineVersion: it "must be + * allowed when specifying a value for the EngineVersion parameter that's a different major + * version than the DB instance's current version". + */ + private void requireMajorVersionUpgradeAllowed(String currentEngineVersion) { + if (sameMajorVersion(currentEngineVersion, engineVersion) + || Boolean.TRUE.equals(allowMajorVersionUpgrade)) { + return; + } + throw new AwsException("InvalidParameterCombination", + "The AllowMajorVersionUpgrade flag must be present when upgrading to a new major " + + "version.", 400); + } + + private static boolean sameMajorVersion(String current, String requested) { + if (current == null || requested == null) { + return true; + } + return current.split("\\.")[0].equals(requested.split("\\.")[0]); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/RdsInstanceScalingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/RdsInstanceScalingIntegrationTest.java new file mode 100644 index 0000000000..0060869a3a --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/rds/RdsInstanceScalingIntegrationTest.java @@ -0,0 +1,142 @@ +package io.github.hectorvent.floci.services.rds; + +import io.github.hectorvent.floci.testing.RdsMockProfile; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.response.ValidatableResponse; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static io.restassured.http.ContentType.URLENC; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; + +/** + * ModifyDBInstance read DBInstanceClass, AllocatedStorage and EngineVersion from the request and + * threw them away, so a resize or an engine upgrade returned 200 while DescribeDBInstances kept + * reporting the values the instance was created with. A caller that diffs its configuration + * against a read-back, Terraform above all, saw the same pending change on every run. + */ +@QuarkusTest +@TestProfile(RdsMockProfile.class) +class RdsInstanceScalingIntegrationTest { + + private static final String ID = "scaling-db"; + private static final String RESULT = + "DescribeDBInstancesResponse.DescribeDBInstancesResult.DBInstances.DBInstance."; + + private static RequestSpecification rds(String action) { + return given().header("Authorization", + "AWS4-HMAC-SHA256 Credential=test/20260615/us-east-1/rds/aws4_request, " + + "SignedHeaders=content-type;host, Signature=test") + .contentType(URLENC) + .formParam("Action", action) + .formParam("Version", "2014-10-31"); + } + + private static void create() { + rds("CreateDBInstance") + .formParam("DBInstanceIdentifier", ID) + .formParam("Engine", "postgres") + .formParam("EngineVersion", "13") + .formParam("DBInstanceClass", "db.t3.micro") + .formParam("MasterUsername", "adminuser") + .formParam("MasterUserPassword", "secret123") + .formParam("AllocatedStorage", "20") + .when().post("/").then().statusCode(200); + } + + private static RequestSpecification modify() { + return rds("ModifyDBInstance").formParam("DBInstanceIdentifier", ID); + } + + private static ValidatableResponse describe() { + return rds("DescribeDBInstances").formParam("DBInstanceIdentifier", ID) + .when().post("/").then().statusCode(200); + } + + @AfterEach + void cleanUp() { + rds("DeleteDBInstance").formParam("DBInstanceIdentifier", ID) + .formParam("SkipFinalSnapshot", "true").when().post("/"); + } + + @Test + void modifyDBInstance_roundTripsTheNewClassStorageAndEngineVersion() { + create(); + + modify() + .formParam("DBInstanceClass", "db.t3.large") + .formParam("AllocatedStorage", "100") + .formParam("EngineVersion", "13.7") + .when().post("/").then().statusCode(200) + .body(containsString("db.t3.large")) + .body(containsString("100")) + .body(containsString("13.7")); + + describe() + .body(RESULT + "DBInstanceClass", equalTo("db.t3.large")) + .body(RESULT + "AllocatedStorage", equalTo("100")) + .body(RESULT + "EngineVersion", equalTo("13.7")); + } + + @Test + void modifyDBInstance_roundsAnIncreaseUnderTenPercentUpTheWayAwsDoes() { + create(); + + modify().formParam("AllocatedStorage", "21") + .when().post("/").then().statusCode(200); + + describe().body(RESULT + "AllocatedStorage", equalTo("22")); + } + + @Test + void modifyDBInstance_refusesToShrinkAllocatedStorage() { + create(); + + modify().formParam("AllocatedStorage", "10") + .when().post("/").then().statusCode(400) + .body(containsString("InvalidParameterCombination")); + + describe().body(RESULT + "AllocatedStorage", equalTo("20")); + } + + @Test + void modifyDBInstance_refusesAMajorEngineVersionUpgradeWithoutTheFlag() { + create(); + + modify().formParam("EngineVersion", "14") + .when().post("/").then().statusCode(400) + .body(containsString("InvalidParameterCombination")); + + describe().body(RESULT + "EngineVersion", equalTo("13")); + } + + @Test + void modifyDBInstance_appliesNothingWhenOneMemberIsRefused() { + create(); + + modify() + .formParam("DBInstanceClass", "db.t3.large") + .formParam("AllocatedStorage", "10") + .when().post("/").then().statusCode(400) + .body(containsString("InvalidParameterCombination")); + + describe() + .body(RESULT + "DBInstanceClass", equalTo("db.t3.micro")) + .body(RESULT + "AllocatedStorage", equalTo("20")); + } + + @Test + void modifyDBInstance_upgradesAMajorEngineVersionWhenTheFlagIsPresent() { + create(); + + modify().formParam("EngineVersion", "14") + .formParam("AllowMajorVersionUpgrade", "true") + .when().post("/").then().statusCode(200); + + describe().body(RESULT + "EngineVersion", equalTo("14")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/RdsQueryHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/RdsQueryHandlerTest.java index 173fb73317..610dffde3b 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/RdsQueryHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/RdsQueryHandlerTest.java @@ -9,6 +9,7 @@ import io.github.hectorvent.floci.services.rds.model.DbClusterParameterGroup; import io.github.hectorvent.floci.services.docdb.DocDbQueryHandler; import io.github.hectorvent.floci.services.neptune.NeptuneQueryHandler; import io.github.hectorvent.floci.services.rds.model.DbInstance; +import io.github.hectorvent.floci.services.rds.model.DbInstanceScalingChanges; import io.github.hectorvent.floci.services.rds.model.DbInstanceSettings; import io.github.hectorvent.floci.services.rds.model.DbInstanceStatus; import io.github.hectorvent.floci.services.rds.model.DbParameterGroup; @@ -121,7 +122,8 @@ class RdsQueryHandlerTest { @Test void modifyDbInstance_forwardsPubliclyAccessible() { when(service.modifyDbInstance(eq("mydb"), isNull(), isNull(), isNull(), any(), isNull(), any(), - isNull(), any(DbInstanceSettings.class), eq(true))).thenReturn(makeInstance("mydb")); + isNull(), any(DbInstanceSettings.class), eq(true), any(DbInstanceScalingChanges.class))) + .thenReturn(makeInstance("mydb")); MultivaluedMap p = params(); p.putSingle("DBInstanceIdentifier", "mydb"); p.putSingle("PubliclyAccessible", "true"); @@ -129,7 +131,7 @@ class RdsQueryHandlerTest { handler.handle("ModifyDBInstance", p); verify(service).modifyDbInstance(eq("mydb"), isNull(), isNull(), isNull(), any(), isNull(), any(), - isNull(), any(DbInstanceSettings.class), eq(true)); + isNull(), any(DbInstanceSettings.class), eq(true), any(DbInstanceScalingChanges.class)); } @Test @@ -142,7 +144,8 @@ class RdsQueryHandlerTest { assertEquals(400, response.getStatus()); assertTrue(((String) response.getEntity()).contains("InvalidParameterValue")); - verify(service, never()).modifyDbInstance(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(service, never()).modifyDbInstance(any(), any(), any(), any(), any(), any(), any(), + any(), any(), any(), any()); } @Test @@ -337,7 +340,8 @@ class RdsQueryHandlerTest { when(service.listDbInstances(null, "us-west-2")).thenReturn(List.of()); when(service.getDbInstance("mydb", "us-west-2")).thenReturn(instance); when(service.modifyDbInstance( - eq("mydb"), isNull(), isNull(), isNull(), anyList(), isNull(), eq("us-west-2"), isNull(), any(DbInstanceSettings.class), isNull())) + eq("mydb"), isNull(), isNull(), isNull(), anyList(), isNull(), eq("us-west-2"), isNull(), + any(DbInstanceSettings.class), isNull(), any(DbInstanceScalingChanges.class))) .thenReturn(instance); when(service.rebootDbInstance("mydb", "us-west-2")).thenReturn(instance); when(service.listDbClusters(null, "us-west-2")).thenReturn(List.of()); @@ -363,7 +367,8 @@ class RdsQueryHandlerTest { verify(service).getDbInstance("mydb", "us-west-2"); verify(service).deleteDbInstance("mydb", "us-west-2"); verify(service).modifyDbInstance( - eq("mydb"), isNull(), isNull(), isNull(), anyList(), isNull(), eq("us-west-2"), isNull(), any(DbInstanceSettings.class), isNull()); + eq("mydb"), isNull(), isNull(), isNull(), anyList(), isNull(), eq("us-west-2"), isNull(), + any(DbInstanceSettings.class), isNull(), any(DbInstanceScalingChanges.class)); verify(service).rebootDbInstance("mydb", "us-west-2"); verify(service).listDbClusters(null, "us-west-2"); verify(service).getDbCluster("mycluster", "us-west-2"); @@ -612,8 +617,8 @@ class RdsQueryHandlerTest { assertEquals(400, response.getStatus()); assertTrue(((String) response.getEntity()).contains("InvalidParameterValue")); - verify(service, never()).modifyDbInstance( - any(), any(), any(), any(), any(), any(), any()); + verify(service, never()).modifyDbInstance(any(), any(), any(), any(), any(), any(), any(), + any(), any(), any(), any()); } @Test @@ -2827,7 +2832,8 @@ class RdsQueryHandlerTest { void modifyDbInstance_passesBackupSettingsToService() { DbInstance instance = makeInstance("mydb"); when(service.modifyDbInstance(eq("mydb"), isNull(), isNull(), isNull(), anyList(), isNull(), - isNull(), isNull(), any(DbInstanceSettings.class), isNull())).thenReturn(instance); + isNull(), isNull(), any(DbInstanceSettings.class), isNull(), + any(DbInstanceScalingChanges.class))).thenReturn(instance); MultivaluedMap p = params(); p.add("DBInstanceIdentifier", "mydb"); @@ -2841,10 +2847,66 @@ class RdsQueryHandlerTest { ArgumentCaptor captor = ArgumentCaptor.forClass(DbInstanceSettings.class); verify(service).modifyDbInstance(eq("mydb"), isNull(), isNull(), isNull(), anyList(), isNull(), - isNull(), isNull(), captor.capture(), isNull()); + isNull(), isNull(), captor.capture(), isNull(), any(DbInstanceScalingChanges.class)); assertEquals(new DbInstanceSettings(null, null, 3, "01:00-01:30", null, true), captor.getValue()); } + @Test + void modifyDbInstance_passesScalingChangesToService() { + DbInstance instance = makeInstance("mydb"); + when(service.modifyDbInstance(eq("mydb"), isNull(), isNull(), isNull(), anyList(), isNull(), + isNull(), isNull(), any(DbInstanceSettings.class), isNull(), + any(DbInstanceScalingChanges.class))).thenReturn(instance); + + MultivaluedMap p = params(); + p.add("DBInstanceIdentifier", "mydb"); + p.add("DBInstanceClass", "db.t3.large"); + p.add("AllocatedStorage", "100"); + p.add("EngineVersion", "14.7"); + p.add("AllowMajorVersionUpgrade", "true"); + assertEquals(200, handler.handle("ModifyDBInstance", p).getStatus()); + + ArgumentCaptor captor = + ArgumentCaptor.forClass(DbInstanceScalingChanges.class); + verify(service).modifyDbInstance(eq("mydb"), isNull(), isNull(), isNull(), anyList(), isNull(), + isNull(), isNull(), any(DbInstanceSettings.class), isNull(), captor.capture()); + assertEquals(new DbInstanceScalingChanges("db.t3.large", 100, "14.7", true), captor.getValue()); + } + + @Test + void modifyDbInstance_leavesScalingChangesUnsetWhenTheRequestOmitsThem() { + DbInstance instance = makeInstance("mydb"); + when(service.modifyDbInstance(eq("mydb"), isNull(), isNull(), isNull(), anyList(), isNull(), + isNull(), isNull(), any(DbInstanceSettings.class), isNull(), + any(DbInstanceScalingChanges.class))).thenReturn(instance); + + MultivaluedMap p = params(); + p.add("DBInstanceIdentifier", "mydb"); + p.add("BackupRetentionPeriod", "3"); + assertEquals(200, handler.handle("ModifyDBInstance", p).getStatus()); + + ArgumentCaptor captor = + ArgumentCaptor.forClass(DbInstanceScalingChanges.class); + verify(service).modifyDbInstance(eq("mydb"), isNull(), isNull(), isNull(), anyList(), isNull(), + isNull(), isNull(), any(DbInstanceSettings.class), isNull(), captor.capture()); + assertEquals(DbInstanceScalingChanges.unchanged(), captor.getValue()); + } + + @Test + void modifyDbInstance_rejectsMalformedAllocatedStorage() { + MultivaluedMap p = params(); + p.add("DBInstanceIdentifier", "mydb"); + p.add("AllocatedStorage", "not-a-number"); + + Response response = handler.handle("ModifyDBInstance", p); + String body = (String) response.getEntity(); + + assertEquals(400, response.getStatus()); + assertTrue(body.contains("InvalidParameterValue"), body); + verify(service, never()).modifyDbInstance(any(), any(), any(), any(), any(), any(), any(), + any(), any(), any(), any()); + } + @Test void unhandledExceptionRendersXmlInternalFailure() { when(service.createDbInstance(any(), any(), any(), any(), any(), any(), diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java index dedc35c3cf..769465e5bd 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java @@ -22,6 +22,7 @@ import io.github.hectorvent.floci.services.rds.model.DbEndpoint; import io.github.hectorvent.floci.services.rds.model.DbInstance; import io.github.hectorvent.floci.services.kms.KmsService; import io.github.hectorvent.floci.services.kms.model.KmsKey; +import io.github.hectorvent.floci.services.rds.model.DbInstanceScalingChanges; import io.github.hectorvent.floci.services.rds.model.DbInstanceSettings; import io.github.hectorvent.floci.services.rds.model.DbInstanceStatus; import io.github.hectorvent.floci.services.rds.model.DbParameterGroup; @@ -332,6 +333,159 @@ class RdsServiceTest { assertFalse(rdsService.getDbInstance("pubdb").isPubliclyAccessible()); } + @Test + void modifyDbInstanceAppliesInstanceClassStorageAndEngineVersion() { + createScalingInstance("scaled", "postgres", "13", 20); + + DbInstance modified = rdsService.modifyDbInstance("scaled", null, null, null, + null, null, null, null, DbInstanceSettings.unchanged(), null, + new DbInstanceScalingChanges("db.t3.large", 100, "13.7", null)); + + assertEquals("db.t3.large", modified.getDbInstanceClass()); + assertEquals(100, modified.getAllocatedStorage()); + assertEquals("13.7", modified.getEngineVersion()); + + DbInstance stored = rdsService.getDbInstance("scaled"); + assertEquals("db.t3.large", stored.getDbInstanceClass()); + assertEquals(100, stored.getAllocatedStorage()); + assertEquals("13.7", stored.getEngineVersion()); + } + + @Test + void modifyDbInstanceLeavesScalingMembersAloneWhenTheRequestOmitsThem() { + createScalingInstance("untouched", "postgres", "13", 20); + + DbInstance modified = rdsService.modifyDbInstance("untouched", null, null, null, + null, null, null, null, DbInstanceSettings.unchanged(), null, + DbInstanceScalingChanges.unchanged()); + + assertEquals("db.t3.micro", modified.getDbInstanceClass()); + assertEquals(20, modified.getAllocatedStorage()); + assertEquals("13", modified.getEngineVersion()); + } + + @Test + void modifyDbInstanceRoundsAllocatedStorageUpToTenPercentGreater() { + createScalingInstance("rounded", "postgres", "13", 20); + + DbInstance modified = rdsService.modifyDbInstance("rounded", null, null, null, + null, null, null, null, DbInstanceSettings.unchanged(), null, + new DbInstanceScalingChanges(null, 21, null, null)); + + assertEquals(22, modified.getAllocatedStorage()); + } + + @Test + void modifyDbInstanceKeepsSqlServerStorageExactlyAsAsked() { + createScalingInstance("mssql", "sqlserver-se", "15.00", 20); + + DbInstance modified = rdsService.modifyDbInstance("mssql", null, null, null, + null, null, null, null, DbInstanceSettings.unchanged(), null, + new DbInstanceScalingChanges(null, 21, null, null)); + + assertEquals(21, modified.getAllocatedStorage()); + } + + @Test + void modifyDbInstanceLeavesAllocatedStorageAloneWhenItIsUnchanged() { + createScalingInstance("same-storage", "postgres", "13", 20); + + DbInstance modified = rdsService.modifyDbInstance("same-storage", null, null, null, + null, null, null, null, DbInstanceSettings.unchanged(), null, + new DbInstanceScalingChanges(null, 20, null, null)); + + assertEquals(20, modified.getAllocatedStorage()); + } + + @Test + void modifyDbInstanceRejectsAllocatedStorageDecrease() { + createScalingInstance("shrinking", "postgres", "13", 20); + + AwsException error = assertThrows(AwsException.class, () -> + rdsService.modifyDbInstance("shrinking", null, null, null, + null, null, null, null, DbInstanceSettings.unchanged(), null, + new DbInstanceScalingChanges(null, 10, null, null))); + + assertEquals("InvalidParameterCombination", error.getErrorCode()); + assertEquals(400, error.getHttpStatus()); + assertEquals(20, rdsService.getDbInstance("shrinking").getAllocatedStorage()); + } + + @Test + void modifyDbInstanceRejectsMajorEngineVersionUpgradeWithoutTheFlag() { + createScalingInstance("major", "postgres", "13", 20); + + AwsException error = assertThrows(AwsException.class, () -> + rdsService.modifyDbInstance("major", null, null, null, + null, null, null, null, DbInstanceSettings.unchanged(), null, + new DbInstanceScalingChanges(null, null, "14", null))); + + assertEquals("InvalidParameterCombination", error.getErrorCode()); + assertEquals("13", rdsService.getDbInstance("major").getEngineVersion()); + } + + @Test + void modifyDbInstanceAppliesMajorEngineVersionUpgradeWithTheFlag() { + createScalingInstance("major-allowed", "postgres", "13", 20); + + DbInstance modified = rdsService.modifyDbInstance("major-allowed", null, null, null, + null, null, null, null, DbInstanceSettings.unchanged(), null, + new DbInstanceScalingChanges(null, null, "14", true)); + + assertEquals("14", modified.getEngineVersion()); + } + + @Test + void modifyDbInstanceLeavesInstanceClassAloneWhenTheStorageShrinkIsRejected() { + createScalingInstance("rejected-shrink", "postgres", "13", 20); + + assertThrows(AwsException.class, () -> + rdsService.modifyDbInstance("rejected-shrink", null, null, null, + null, null, null, null, DbInstanceSettings.unchanged(), null, + new DbInstanceScalingChanges("db.t3.large", 10, null, null))); + + DbInstance stored = rdsService.getDbInstance("rejected-shrink"); + assertEquals("db.t3.micro", stored.getDbInstanceClass()); + assertEquals(20, stored.getAllocatedStorage()); + } + + @Test + void modifyDbInstanceLeavesClassAndStorageAloneWhenTheMajorUpgradeIsRejected() { + createScalingInstance("rejected-upgrade", "postgres", "13", 20); + + assertThrows(AwsException.class, () -> + rdsService.modifyDbInstance("rejected-upgrade", null, null, null, + null, null, null, null, DbInstanceSettings.unchanged(), null, + new DbInstanceScalingChanges("db.t3.large", 100, "14", null))); + + DbInstance stored = rdsService.getDbInstance("rejected-upgrade"); + assertEquals("db.t3.micro", stored.getDbInstanceClass()); + assertEquals(20, stored.getAllocatedStorage()); + assertEquals("13", stored.getEngineVersion()); + } + + @Test + void modifyDbInstanceLeavesEveryOtherMemberAloneWhenAScalingChangeIsRejected() { + createScalingInstance("rejected-whole", "postgres", "13", 20); + + assertThrows(AwsException.class, () -> + rdsService.modifyDbInstance("rejected-whole", null, null, null, + null, null, null, false, + new DbInstanceSettings(null, null, 7, null, null, null), null, + new DbInstanceScalingChanges(null, 10, null, null))); + + DbInstance stored = rdsService.getDbInstance("rejected-whole"); + assertTrue(stored.isAutoMinorVersionUpgrade()); + assertEquals(1, stored.getBackupRetentionPeriod()); + } + + private void createScalingInstance(String id, String engine, String engineVersion, int storage) { + String dbName = engine.startsWith("sqlserver") ? null : "dbname"; + rdsService.createDbInstance(id, engine, engineVersion, + "admin", "Password123!", dbName, "db.t3.micro", + storage, false, null, null, null, null, false); + } + @Test void createDbInstanceOmittedPubliclyAccessibleDefaultsTrueForNonAuroraWithNoSubnetGroup() { DbInstance instance = rdsService.createDbInstance("plain-db", "postgres", "13",