From 171f42ce6edfd43bebf5ae8141e2bde3a71bf601 Mon Sep 17 00:00:00 2001 From: Jackson Price <59149601+jprice8@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:48:48 -0600 Subject: [PATCH] fix(rds): acknowledge instance creation before database startup (#9599) CreateDBInstance waited for the Docker backend before answering, so a client with the SDK's default timeouts could retry a create that had already succeeded and get DBInstanceAlreadyExists. It now stores the instance and answers creating, as AWS does. DescribeDBInstances sees the record while a background worker starts the container and proxy outside the instance lock, and the worker publishes the backend only if the same instance is still creating. ModifyDBInstance and RebootDBInstance refuse a creating instance with InvalidDBInstanceState and AWS's messages. A delete accepted during startup keeps the record and the caller's backup choice until the worker has torn down what it started, and after a restart Floci reopens the PostgreSQL volume to save a retained backup before removing it. A state reset waits up to 15 seconds for pending starts and otherwise refuses with 503 from checkReset, before any container stops. Signed-off-by: Jackson Price --- .../sdk-test-awscli/test/rds.bats | 6 + .../java/com/floci/test/TestFixtures.java | 8 + .../floci/test/RdsAutoscalingMinimumTest.java | 1 + .../com/floci/test/RdsControlPlaneTest.java | 21 +- .../test/RdsInstanceSnapshotIamTest.java | 1 + .../com/floci/test/RdsStorageTypeTest.java | 7 + docs/services/rds.md | 16 +- .../io/floci/aws/core/common/Resettable.java | 3 + .../aws/lifecycle/EmulatorInfoController.java | 24 +- .../aws/lifecycle/EmulatorLifecycle.java | 1 + .../aws/services/rds/RdsQueryHandler.java | 5 +- .../io/floci/aws/services/rds/RdsService.java | 465 ++++++++++++++++-- .../aws/services/rds/model/DbInstance.java | 9 +- .../lifecycle/EmulatorInfoControllerTest.java | 3 + .../aws/lifecycle/EmulatorLifecycleTest.java | 5 +- ...intsInVpcDockerNightlyIntegrationTest.java | 5 +- ...neVersionDockerNightlyIntegrationTest.java | 3 +- .../rds/RdsLogFilesDockerIntegrationTest.java | 5 +- ...lSnapshotDockerNightlyIntegrationTest.java | 7 +- ...oupEngineDockerNightlyIntegrationTest.java | 3 +- .../aws/services/rds/RdsQueryHandlerTest.java | 50 +- ...adReplicaDockerNightlyIntegrationTest.java | 11 +- ...sociationDockerNightlyIntegrationTest.java | 2 + .../aws/services/rds/RdsServiceTest.java | 336 +++++++++++++ ...hotExportDockerNightlyIntegrationTest.java | 16 +- ...PgBouncerDockerNightlyIntegrationTest.java | 12 +- .../io/floci/aws/testing/RdsRequests.java | 20 +- 27 files changed, 917 insertions(+), 128 deletions(-) diff --git a/compatibility-tests/sdk-test-awscli/test/rds.bats b/compatibility-tests/sdk-test-awscli/test/rds.bats index 180fd8596a..143a551a63 100644 --- a/compatibility-tests/sdk-test-awscli/test/rds.bats +++ b/compatibility-tests/sdk-test-awscli/test/rds.bats @@ -373,6 +373,8 @@ teardown() { assert_output --partial '"23:30-00:00"' assert_output --partial '"sun:03:08-sun:03:38"' + run aws_cmd rds wait db-instance-available --db-instance-identifier "$DB_ID" + assert_success run aws_cmd rds modify-db-instance --db-instance-identifier "$DB_ID" \ --backup-retention-period 3 --preferred-backup-window 01:00-01:30 --apply-immediately assert_success @@ -404,6 +406,8 @@ teardown() { [ "$status_create" -eq 0 ] [ "$(json_get "$create_output" '.DBInstance.CACertificateIdentifier')" = "rds-ca-ecc384-g1" ] + run aws_cmd rds wait db-instance-available --db-instance-identifier "$DB_ID" + assert_success run aws_cmd rds modify-db-instance --db-instance-identifier "$DB_ID" \ --ca-certificate-identifier rds-ca-rsa4096-g1 --apply-immediately assert_success @@ -512,6 +516,8 @@ teardown() { assert_success dbi="$(json_get "$output" '.DBInstance.DbiResourceId')" source_arn="$(json_get "$output" '.DBInstance.DBInstanceArn')" + run aws_cmd rds wait db-instance-available --db-instance-identifier "$DB_ID" + assert_success run aws_cmd rds describe-db-instance-automated-backups --dbi-resource-id "$dbi" assert_success diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java index 627443b675..bdd6560bae 100644 --- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java +++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java @@ -116,6 +116,7 @@ import software.amazon.awssdk.services.pipes.PipesClient; import software.amazon.awssdk.services.quicksight.QuickSightClient; import software.amazon.awssdk.services.ram.RamClient; import software.amazon.awssdk.services.rds.RdsClient; +import software.amazon.awssdk.services.rds.model.DescribeDbInstancesRequest; import software.amazon.awssdk.services.redshift.RedshiftClient; import software.amazon.awssdk.services.redshiftdata.RedshiftDataClient; import software.amazon.awssdk.services.redshiftserverless.RedshiftServerlessClient; @@ -1467,6 +1468,13 @@ public final class TestFixtures { .build(); } + public static void waitForAvailableDbInstance(RdsClient client, String id) { + Duration timeout = Duration.ofMinutes(isRealAws() ? 30 : 2); + DescribeDbInstancesRequest request = DescribeDbInstancesRequest.builder().dbInstanceIdentifier(id).build(); + client.waiter().waitUntilDBInstanceAvailable(request, waiterOverride(timeout)) + .matched().response().orElseThrow(); + } + public static DatabaseMigrationClient databaseMigrationClient() { return DatabaseMigrationClient.builder() .endpointOverride(ENDPOINT) diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsAutoscalingMinimumTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsAutoscalingMinimumTest.java index 0b4767df6d..7a71ff79ea 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsAutoscalingMinimumTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsAutoscalingMinimumTest.java @@ -115,6 +115,7 @@ class RdsAutoscalingMinimumTest { rds.createDBInstance(r -> r.dbInstanceIdentifier(id).engine("postgres").dbInstanceClass("db.t3.micro") .masterUsername("adminuser").masterUserPassword("secret123").allocatedStorage(allocated) .maxAllocatedStorage(100).backupRetentionPeriod(7)); + TestFixtures.waitForAvailableDbInstance(rds, id); assertState(rds, id, allocated, 100, 7); } 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 79c07d8f17..56d1273435 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 @@ -47,6 +47,7 @@ import software.amazon.awssdk.services.rds.model.DbSnapshotAlreadyExistsExceptio import software.amazon.awssdk.services.rds.model.DbSnapshotNotFoundException; import software.amazon.awssdk.services.rds.model.DescribeCertificatesResponse; import software.amazon.awssdk.services.rds.model.DescribeDBLogFilesDetails; +import software.amazon.awssdk.services.rds.model.DescribeDbInstancesRequest; import software.amazon.awssdk.services.rds.model.DescribeDbProxiesResponse; import software.amazon.awssdk.services.rds.model.DescribeDbProxyEndpointsResponse; import software.amazon.awssdk.services.rds.model.DescribeDbProxyTargetGroupsResponse; @@ -78,6 +79,7 @@ import software.amazon.awssdk.services.rds.model.Tag; import software.amazon.awssdk.services.rds.model.UpgradeTarget; import software.amazon.awssdk.services.rds.model.ValidStorageOptions; +import java.time.Duration; import java.time.Instant; import java.util.List; import java.util.logging.Level; @@ -1123,7 +1125,7 @@ class RdsControlPlaneTest { private static CreateDbInstanceResponse createDbInstance( RdsClient client, String name, String password) { - return client.createDBInstance(b -> b + CreateDbInstanceResponse created = client.createDBInstance(b -> b .dbInstanceIdentifier(name) .engine("postgres") .engineVersion("16.3") @@ -1132,6 +1134,8 @@ class RdsControlPlaneTest { .dbName("app") .dbInstanceClass("db.t3.micro") .allocatedStorage(20)); + TestFixtures.waitForAvailableDbInstance(client, name); + return created; } private static RdsClient rdsClient(Region region) { @@ -1259,7 +1263,7 @@ class RdsControlPlaneTest { .optionGroupName(optionGroupName))) .isInstanceOf(InvalidOptionGroupStateException.class); - deleteDbInstance(rds, instanceName); + deleteDbInstanceAndWait(rds, instanceName); rds.deleteOptionGroup(b -> b.optionGroupName(optionGroupName)); } finally { deleteDbInstance(rds, instanceName); @@ -1300,14 +1304,19 @@ class RdsControlPlaneTest { private static void deleteDbInstance(RdsClient client, String name) { try { - client.deleteDBInstance(b -> b - .dbInstanceIdentifier(name) - .skipFinalSnapshot(true)); + deleteDbInstanceAndWait(client, name); } catch (Exception e) { - LOG.log(Level.FINE, "RDS DB instance already absent during cleanup " + name, e); + LOG.log(Level.FINE, "Could not confirm deletion of RDS DB instance " + name, e); } } + private static void deleteDbInstanceAndWait(RdsClient client, String name) { + client.deleteDBInstance(b -> b.dbInstanceIdentifier(name).skipFinalSnapshot(true)); + Duration timeout = Duration.ofMinutes(TestFixtures.isRealAws() ? 30 : 2); + DescribeDbInstancesRequest request = DescribeDbInstancesRequest.builder().dbInstanceIdentifier(name).build(); + client.waiter().waitUntilDBInstanceDeleted(request, TestFixtures.waiterOverride(timeout)); + } + private static void deregisterProxyTarget( RdsClient client, String proxyName, String instanceName) { try { diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsInstanceSnapshotIamTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsInstanceSnapshotIamTest.java index efcfae4256..68e85c04d2 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsInstanceSnapshotIamTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsInstanceSnapshotIamTest.java @@ -25,6 +25,7 @@ class RdsInstanceSnapshotIamTest { .dbInstanceClass("db.t3.micro").allocatedStorage(20) .masterUsername("admin").masterUserPassword("Password123!") .enableIAMDatabaseAuthentication(sourceEnabled)); + TestFixtures.waitForAvailableDbInstance(rds, source); rds.createDBSnapshot(b -> b.dbInstanceIdentifier(source).dbSnapshotIdentifier(snapshot)); for (Boolean flag : new Boolean[]{null, false, true}) { String target = source + "-" + (flag == null ? "omitted" : flag.toString()); diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsStorageTypeTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsStorageTypeTest.java index 0f644d2d71..00995d7ed4 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsStorageTypeTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsStorageTypeTest.java @@ -9,6 +9,7 @@ import software.amazon.awssdk.services.rds.model.DBInstance; import software.amazon.awssdk.services.rds.model.DbInstanceNotFoundException; import software.amazon.awssdk.services.rds.model.StorageTypeNotSupportedException; + import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertAll; @@ -23,6 +24,8 @@ class RdsStorageTypeTest { DBInstance created = rds.createDBInstance(r -> r.dbInstanceIdentifier(id).engine("postgres") .dbInstanceClass("db.t3.micro").masterUsername("admin").masterUserPassword("password123") .allocatedStorage(20).storageType("gp3").backupRetentionPeriod(2)).dbInstance(); + assertThat(created.dbInstanceStatus()).isEqualTo("creating"); + TestFixtures.waitForAvailableDbInstance(rds, id); assertThat(created.storageType()).isEqualTo("gp3"); assertThat(rds.describeDBInstances(r -> r.dbInstanceIdentifier(id)).dbInstances().get(0).storageType()) .isEqualTo("gp3"); @@ -56,6 +59,8 @@ class RdsStorageTypeTest { DBInstance created = rds.createDBInstance(r -> r.dbInstanceIdentifier(id).engine("postgres") .dbInstanceClass("db.t3.micro").masterUsername("admin").masterUserPassword("password123") .allocatedStorage(100).storageType(storageType)).dbInstance(); + assertThat(created.dbInstanceStatus()).isEqualTo("creating"); + TestFixtures.waitForAvailableDbInstance(rds, id); assertThat(created.storageType()).isEqualTo(storageType); assertThat(created.iops()).isNull(); assertThat(rds.modifyDBInstance(r -> r.dbInstanceIdentifier(id).storageType("gp3")) @@ -87,6 +92,7 @@ class RdsStorageTypeTest { assertThat(rds.createDBInstance(r -> r.dbInstanceIdentifier(id).engine("postgres") .dbInstanceClass("db.t3.micro").masterUsername("admin").masterUserPassword("password123") .allocatedStorage(20).storageType("gp3")).dbInstance().storageType()).isEqualTo("gp3"); + TestFixtures.waitForAvailableDbInstance(rds, id); } finally { remove(rds, id); } @@ -106,6 +112,7 @@ class RdsStorageTypeTest { rds.createDBInstance(r -> r.dbInstanceIdentifier(source).engine("postgres") .dbInstanceClass("db.t3.micro").masterUsername("admin").masterUserPassword("password123") .allocatedStorage(20).storageType("gp3").backupRetentionPeriod(2)); + TestFixtures.waitForAvailableDbInstance(rds, source); DBInstance derived; if ("snapshot".equals(operation)) { assertThat(rds.createDBSnapshot(r -> r.dbInstanceIdentifier(source).dbSnapshotIdentifier(snapshot)) diff --git a/docs/services/rds.md b/docs/services/rds.md index b0b183650a..60e46fd545 100644 --- a/docs/services/rds.md +++ b/docs/services/rds.md @@ -4,6 +4,16 @@ **Management Endpoint:** `POST http://localhost:4566/` **Data Endpoint:** `localhost:` (TCP) +`CreateDBInstance` returns `creating`. Use the SDK instance-available waiter before modifying the instance, taking a snapshot or connecting to the database. A standalone instance starts its database and proxy in the background. Its record is visible to `DescribeDBInstances` while startup runs. Modify and reboot requests during startup return `InvalidDBInstanceState`. If you delete the instance while its container or proxy is starting, it stays `deleting` until Floci can remove those resources. + +A state reset waits up to 15 seconds for instance startup. If startup is still running, reset returns +HTTP 503 before stopping any managed containers or clearing stored data. A create refused during +reset leaves its identifier free. Retry the create with the same name once the reset finishes or is refused. + +If you keep a PostgreSQL automated backup, Floci saves it before removing the volume, even if the +delete arrives before the database starts. If Docker is unavailable after a restart, the instance +stays `deleting`. Retry the delete or restart Floci once Docker is available. + ### Recoverable backend startup failures If a persisted database's container or authentication relay cannot start when Floci restarts, @@ -12,8 +22,7 @@ backend is next needed. A failed restore does not release or renumber a reserved or the next boot uses the same port. This recoverable emulator condition uses `available`, the same metadata-only status as a restart without a reachable Docker daemon, not AWS's terminal `failed` state. It does not -guarantee that a database connection is ready while Docker is unavailable. Port allocation -failures still report `failed` because no endpoint could be allocated. +guarantee that a database connection is ready while Docker is unavailable. Port allocation failures report `failed`. If an instance was still being created or was already failed, another startup failure leaves it `failed`. A successful lazy retry updates legacy `failed` records to `available` only after the container and relay are ready. Older records whose endpoint was cleared receive a new relay endpoint on @@ -416,8 +425,7 @@ a warning naming the missing daemon. Nothing listens behind the endpoint in that state. The backing container is retried by every operation that needs the live database, so it starts as soon as a daemon becomes reachable. Until then, RDS Data API calls fail with a modelled `InternalServerErrorException` that names the missing -daemon. A daemon that is reachable but cannot start the container still fails `CreateDBInstance` -outright, since that is a real error rather than a degraded mode. +daemon. When a reachable daemon fails to start a new standalone database, `DescribeDBInstances` reports `failed` and the instance can be deleted. ### Mock mode (CI / tests) diff --git a/src/main/java/io/floci/aws/core/common/Resettable.java b/src/main/java/io/floci/aws/core/common/Resettable.java index f4fc668453..f51b47777d 100644 --- a/src/main/java/io/floci/aws/core/common/Resettable.java +++ b/src/main/java/io/floci/aws/core/common/Resettable.java @@ -13,6 +13,9 @@ public interface Resettable { */ default void checkReset() {} + /** Release reservations made by checkReset() if this or a later check refuses the reset. */ + default void cancelResetCheck() {} + /** Stop accepting work and drain active writes before any storage is cleared. */ default void beforeReset() {} diff --git a/src/main/java/io/floci/aws/lifecycle/EmulatorInfoController.java b/src/main/java/io/floci/aws/lifecycle/EmulatorInfoController.java index 3c917c07b0..9018ac222b 100644 --- a/src/main/java/io/floci/aws/lifecycle/EmulatorInfoController.java +++ b/src/main/java/io/floci/aws/lifecycle/EmulatorInfoController.java @@ -219,6 +219,25 @@ public class EmulatorInfoController { return reset(); } + private static void checkReset(List services) { + List checked = new ArrayList<>(); + try { + for (Resettable service : services) { + checked.add(service); + service.checkReset(); + } + } catch (RuntimeException refusal) { + for (Resettable service : checked.reversed()) { + try { + service.cancelResetCheck(); + } catch (RuntimeException cleanupFailure) { + refusal.addSuppressed(cleanupFailure); + } + } + throw refusal; + } + } + private synchronized void performReset() { // Resolve live instances before taking any storage locks. Serialize resets so one reset // cannot resume a publisher while another is still wiping its storage. @@ -226,10 +245,7 @@ public class EmulatorInfoController { for (Resettable service : resettables) { services.add(service); } - // Every service may refuse before the first destructive step, so a refusal changes nothing. - for (Resettable service : services) { - service.checkReset(); - } + checkReset(services); // Containers next: they are tracked independently of StorageBackend, so this can run // in any order relative to the storage wipe below, but stopping them here means a // client's reset actually reflects a clean slate instead of leaving Batch, CodeBuild, diff --git a/src/main/java/io/floci/aws/lifecycle/EmulatorLifecycle.java b/src/main/java/io/floci/aws/lifecycle/EmulatorLifecycle.java index cc598c5950..034dedf0a5 100644 --- a/src/main/java/io/floci/aws/lifecycle/EmulatorLifecycle.java +++ b/src/main/java/io/floci/aws/lifecycle/EmulatorLifecycle.java @@ -510,6 +510,7 @@ public class EmulatorLifecycle { runCleanup("Redshift zero-ETL consumer", redshiftZeroEtlConsumer::shutdown); runCleanup("storage flush", storageFactory::flushAll); List prepared = ContainerTeardowns.prepareAll(containerTeardowns, LOG); + runCleanup("RDS instance starts", rdsService::shutdownInstanceStarts); runCleanup("EC2 metadata server", () -> { if (isMetadataServerNeeded()) { ec2MetadataServer.stop(); diff --git a/src/main/java/io/floci/aws/services/rds/RdsQueryHandler.java b/src/main/java/io/floci/aws/services/rds/RdsQueryHandler.java index 2d09c27d1f..dbf095611f 100644 --- a/src/main/java/io/floci/aws/services/rds/RdsQueryHandler.java +++ b/src/main/java/io/floci/aws/services/rds/RdsQueryHandler.java @@ -406,14 +406,15 @@ public class RdsQueryHandler { RdsService.validatePromotionTier(promotionTier); List vpcSecurityGroupIds = vpcSecurityGroupIds(params); Integer requestedPort = parseIntegerParam(params, "Port"); - DbInstance instance = service.createDbInstance(id, engine, engineVersion, masterUsername, + DbInstance instance = service.beginCreateDbInstance(id, engine, engineVersion, masterUsername, masterPassword, dbName, dbInstanceClass, allocatedStorage, iamEnabled, paramGroupName, dbSubnetGroupName, dbClusterIdentifier, availabilityZone, multiAz, manageMasterUserPassword, masterUserSecretKmsKeyId, tags, vpcSecurityGroupIds, optionGroupName, region, autoMinorVersionUpgrade, settings, publiclyAccessible, requestedPort, deletionProtection); if (promotionTier != null) { - instance = service.setInstancePromotionTier(region, id, promotionTier); + service.setInstancePromotionTier(region, id, promotionTier); + instance.setPromotionTier(promotionTier); } String result = dbInstanceXml(instance); return Response.ok(AwsQueryResponse.envelope("CreateDBInstance", AwsNamespaces.RDS, result)).build(); 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 a69a20e813..9bd4324c7d 100644 --- a/src/main/java/io/floci/aws/services/rds/RdsService.java +++ b/src/main/java/io/floci/aws/services/rds/RdsService.java @@ -11,6 +11,7 @@ import io.floci.aws.core.common.AwsEndpoints; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.AwsRegions; import io.floci.aws.core.common.BackupWindows; +import io.floci.aws.core.common.ContainerTeardown; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.RequestScopes; import io.floci.aws.core.common.Resettable; @@ -97,6 +98,10 @@ import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; @@ -110,7 +115,7 @@ import java.util.stream.Collectors; * Starts DB containers and auth proxies on creation. */ @ApplicationScoped -public class RdsService implements Resettable, ResourceProvider { +public class RdsService implements ContainerTeardown, Resettable, ResourceProvider { private static final Logger LOG = Logger.getLogger(RdsService.class); private static final ObjectMapper JSON = new ObjectMapper(); @@ -203,13 +208,15 @@ public class RdsService implements Resettable, ResourceProvider { private final StorageBackend clusterAutomatedBackups; private final RdsContainerManager containerManager; private final RdsProxyManager proxyManager; - // CreateDBCluster/CreateDBInstance register the new resource only after the - // backing container is provisioned, and an image pull can hold that window - // open long enough for a client-side retry to pass the exists-check again - // and provision a second container for the same identifier. The sentinel - // serializes creates per identifier so the duplicate fails fast with the - // same fault a completed create produces. + // Reserve each identifier until its metadata exists, including internal creates that wait for Docker. private final Set provisioningIds = ConcurrentHashMap.newKeySet(); + private final Map standaloneStarts = new ConcurrentHashMap<>(); + private final Object instanceCreationLock = new Object(); + private final ExecutorService instanceStarts = Executors.newVirtualThreadPerTaskExecutor(); + private int pendingInstanceStarts; + private long instanceStartDeadline; + private CountDownLatch instanceStartDrain; + private volatile boolean discardLateInstanceStarts; private final Ec2Service ec2Service; private final RegionResolver regionResolver; private final EmulatorConfig config; @@ -531,6 +538,71 @@ public class RdsService implements Resettable, ResourceProvider { backfillInstanceEngineIdentifiers(); } + @Override + public void beginTeardown() { + if (!drainInstanceStarts()) { + LOG.warn("RDS instance startup did not finish before teardown"); + } + } + + @Override + public void stopManagedContainers() { + // EmulatorLifecycle stops the RDS proxy and container managers after preparing all services. + } + + public void shutdownInstanceStarts() { + synchronized (instanceCreationLock) { + instanceStarts.shutdown(); + } + if (!drainInstanceStarts()) { + discardLateInstanceStarts = true; + instanceStarts.shutdownNow(); + } + } + + @Override + public void checkReset() { + if (!drainInstanceStarts()) { + throw new AwsException("ServiceUnavailable", "RDS instance startup is still in progress. Retry the reset.", 503); + } + } + + private boolean drainInstanceStarts() { + CountDownLatch drain; + long remaining; + synchronized (instanceCreationLock) { + if (instanceStartDrain == null) { + instanceStartDrain = new CountDownLatch(pendingInstanceStarts); + instanceStartDeadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(15); + } + drain = instanceStartDrain; + remaining = instanceStartDeadline - System.nanoTime(); + } + try { + return drain.await(remaining, TimeUnit.NANOSECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + return false; + } + } + + @Override + public void cancelResetCheck() { + resumeInstanceStarts(); + } + + @Override + public void afterReset() { + resumeInstanceStarts(); + } + + private void resumeInstanceStarts() { + synchronized (instanceCreationLock) { + instanceStartDrain = null; + } + } + + @Override public void clear() { usedPorts.clear(); reportedMemberRelayFailures.clear(); @@ -760,6 +832,57 @@ public class RdsService implements Resettable, ResourceProvider { Boolean publiclyAccessible, Integer requestedPort, Boolean deletionProtection) { + return createDbInstance(id, engineParam, engineVersion, masterUsername, masterPassword, + dbName, dbInstanceClass, allocatedStorage, iamEnabled, paramGroupName, + dbSubnetGroupName, dbClusterIdentifier, availabilityZone, multiAz, + manageMasterUserPassword, masterUserSecretKmsKeyId, tags, vpcSecurityGroupIds, + optionGroupName, region, autoMinorVersionUpgrade, settings, publiclyAccessible, + requestedPort, deletionProtection, false); + } + + /** Acknowledges the public CreateDBInstance request after validation and publishes a stable creating response. */ + public DbInstance beginCreateDbInstance(String id, String engineParam, String engineVersion, + String masterUsername, String masterPassword, + String dbName, String dbInstanceClass, + int allocatedStorage, boolean iamEnabled, + String paramGroupName, String dbSubnetGroupName, + String dbClusterIdentifier, String availabilityZone, + boolean multiAz, boolean manageMasterUserPassword, + String masterUserSecretKmsKeyId, + Map tags, + List vpcSecurityGroupIds, + String optionGroupName, + String region, + boolean autoMinorVersionUpgrade, + DbInstanceSettings settings, + Boolean publiclyAccessible, + Integer requestedPort, + Boolean deletionProtection) { + return createDbInstance(id, engineParam, engineVersion, masterUsername, masterPassword, + dbName, dbInstanceClass, allocatedStorage, iamEnabled, paramGroupName, + dbSubnetGroupName, dbClusterIdentifier, availabilityZone, multiAz, + manageMasterUserPassword, masterUserSecretKmsKeyId, tags, vpcSecurityGroupIds, + optionGroupName, region, autoMinorVersionUpgrade, settings, publiclyAccessible, + requestedPort, deletionProtection, true); + } + + private DbInstance createDbInstance(String id, String engineParam, String engineVersion, + String masterUsername, String masterPassword, + String dbName, String dbInstanceClass, + int allocatedStorage, boolean iamEnabled, + String paramGroupName, String dbSubnetGroupName, + String dbClusterIdentifier, String availabilityZone, + boolean multiAz, boolean manageMasterUserPassword, + String masterUserSecretKmsKeyId, + Map tags, + List vpcSecurityGroupIds, + String optionGroupName, + String region, + boolean autoMinorVersionUpgrade, + DbInstanceSettings settings, + Boolean publiclyAccessible, + Integer requestedPort, + Boolean deletionProtection, boolean acknowledgeCreate) { validateInstanceSettings(settings); String provisioningKey = "instance:" + currentAccountId() + ":" + dbResourceKey(effectiveRegion(region), id); @@ -773,7 +896,7 @@ public class RdsService implements Resettable, ResourceProvider { paramGroupName, dbSubnetGroupName, dbClusterIdentifier, availabilityZone, multiAz, manageMasterUserPassword, masterUserSecretKmsKeyId, tags, vpcSecurityGroupIds, optionGroupName, region, autoMinorVersionUpgrade, - settings, publiclyAccessible, requestedPort, deletionProtection); + settings, publiclyAccessible, requestedPort, deletionProtection, acknowledgeCreate); } finally { provisioningIds.remove(provisioningKey); } @@ -794,7 +917,7 @@ public class RdsService implements Resettable, ResourceProvider { boolean autoMinorVersionUpgrade, DbInstanceSettings settings, Boolean publiclyAccessible, Integer requestedPort, - Boolean deletionProtection) { + Boolean deletionProtection, boolean acknowledgeCreate) { String effectiveRegion = effectiveRegion(region); String dbiResourceId = "db-" + UUID.randomUUID().toString() .replace("-", "").substring(0, 24).toUpperCase(); @@ -948,13 +1071,13 @@ public class RdsService implements Resettable, ResourceProvider { throw failure; } - DbEndpoint endpoint; + boolean backgroundStart = acknowledgeCreate && isBlank(dbClusterIdentifier) && !mock; DbInstance instance; // A cluster member reports its cluster's port, as AWS does, unless it asks for its own. Integer advertisedPort = requestedPort != null || publicationCluster == null ? requestedPort : publicationCluster.getRequestedPort(); try { - endpoint = advertised(mock ? new DbEndpoint("localhost", proxyPort) : proxyEndpoint(proxyPort), + DbEndpoint endpoint = advertised(mock ? new DbEndpoint("localhost", proxyPort) : proxyEndpoint(proxyPort), advertisedPort); instance = new DbInstance(id, engine, engineVersion, masterUsername, masterPassword, dbName, dbInstanceClass, allocatedStorage, DbInstanceStatus.CREATING, @@ -984,35 +1107,23 @@ public class RdsService implements Resettable, ResourceProvider { instance.setDeletionProtection(Boolean.TRUE.equals(deletionProtection)); instance.setDbiResourceId(dbiResourceId); instance.setDbInstanceArn(dbInstanceArn); - if (isBlank(dbClusterIdentifier) && endpointAddresses != null && endpointAddresses.assign(instance)) { - endpoint = instanceEndpoint(instance, proxyPort); - instance.setEndpoint(endpoint); - // Known from now on, so the name resolves to no address rather than to Floci until it is served. - endpointAddresses.remember(instance, currentAccountId(), effectiveRegion); + if (isBlank(dbClusterIdentifier) && !backgroundStart) { + placeStandaloneEndpoint(instance, currentAccountId(), effectiveRegion); } } catch (RuntimeException | Error failure) { releaseProxyPort(proxyPort); throw failure; } String accountId = accountIdFromArn(instance.getDbInstanceArn()); + if (backgroundStart) { + return beginStandaloneInstanceStart(instance, effectiveRegion, instanceImage, instanceEngineParameters, + manageInstancePassword, masterUserSecretKmsKeyId, effectiveSecretKmsKeyId); + } if (isBlank(dbClusterIdentifier) && !mock) { try { - RdsContainerHandle handle = containerManager.tryStart( - dbInstanceArn, id, instanceStorageResourceId, - instanceDockerVolumeName, engine, instanceImage, - masterUsername, masterPassword, dbName, instanceEngineParameters); - if (handle != null) { - backendHost = handle.getHost(); - backendPort = handle.getPort(); - instance.setContainerId(handle.getContainerId()); - 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); - } + startStandaloneInstanceContainer(instance, instanceImage, instanceEngineParameters); + backendHost = instance.getContainerHost(); + backendPort = instance.getContainerPort(); } catch (RuntimeException | Error failure) { synchronized (instance) { rollbackFailedStandaloneInstanceCreate(failure, instance, accountId, @@ -1082,18 +1193,8 @@ public class RdsService implements Resettable, ResourceProvider { putInstanceForScope(accountId, effectiveRegion, id, instance); if (!mock && hasBackend(backendHost, backendPort)) { - final String instanceRegion = regionResolver.regionOf(instance.getDbInstanceArn()); - InstanceBackendIdentity backendIdentity = instanceBackendIdentity(instance); proxyStartAttempted = true; - proxyManager.startProxy(rdsResourceRelayKey(instance.getDbInstanceArn(), id), - backendIdentity.runtimeId(), engine, iamEnabled, proxyPort, - backendHost, backendPort, instance.getEndpoint().address(), - instance.getMasterUsername(), instance.getMasterPassword(), dbName, - (user, pw) -> validateDbPasswordForScope( - accountId, instanceRegion, id, user, pw), - proxyBinding(engine, instance.getEndpoint().address(), instance.getEndpoint().port(), - instanceRegion, accountId, backendIdentity.dbUserResourceId())); - serveInVpc(instance); + startCreatedInstanceProxy(instance, accountId, effectiveRegion); } if (currentCluster != null) { @@ -1124,7 +1225,204 @@ public class RdsService implements Resettable, ResourceProvider { } LOG.infov("DB instance {0} created, engine={1}, endpoint={2}:{3}", id, engine, instance.getEndpoint().address(), String.valueOf(instance.getEndpoint().port())); - return instance; + return acknowledgeCreate ? creatingResponse(instance) : instance; + } + + private static DbInstance creatingResponse(DbInstance instance) { + DbInstance response = RESPONSE_COPIER.convertValue(instance, DbInstance.class); + response.setStatus(DbInstanceStatus.CREATING); + return response; + } + + private enum InstanceStartPhase { QUEUED, STARTING } + + private void placeStandaloneEndpoint(DbInstance instance, String account, String region) { + if (endpointAddresses != null && endpointAddresses.assign(instance)) { + instance.setEndpoint(instanceEndpoint(instance, instance.getProxyPort())); + endpointAddresses.remember(instance, account, region); + } + } + + private DbInstance beginStandaloneInstanceStart(DbInstance instance, String region, String image, + Map parameters, boolean managePassword, + String kmsKeyId, String effectiveKmsKeyId) { + String account = accountIdFromArn(instance.getDbInstanceArn()); + String id = instance.getDbInstanceIdentifier(); + synchronized (instanceCreationLock) { + try { + if (instanceStartDrain != null || instanceStarts.isShutdown()) { + throw new AwsException("ServiceUnavailable", "RDS is not accepting instance starts.", 503); + } + placeStandaloneEndpoint(instance, account, region); + } catch (RuntimeException | Error failure) { + releaseProxyPort(instance.getProxyPort()); + throw failure; + } + boolean writeStarted = false; + try { + if (managePassword) { + attachManagedMasterUserSecret(instance, region, kmsKeyId, effectiveKmsKeyId); + } + DbInstance response = creatingResponse(instance); + standaloneStarts.put(instance, InstanceStartPhase.QUEUED); + writeStarted = true; + putInstanceForScope(account, region, id, instance); + instanceStarts.execute(() -> { + try { + RequestScopes.runAs(account, region, + () -> finishStandaloneInstanceStart(instance, account, region, image, parameters)); + } finally { + instanceStartFinished(instance); + } + }); + pendingInstanceStarts++; + return response; + } catch (RuntimeException | Error failure) { + standaloneStarts.remove(instance); + rollbackFailedStandaloneInstanceCreate(failure, instance, account, region, + writeStarted, false, managePassword, false); + throw failure; + } + } + } + + private void instanceStartFinished(DbInstance instance) { + synchronized (instanceCreationLock) { + standaloneStarts.remove(instance); + pendingInstanceStarts--; + if (instanceStartDrain != null) { + instanceStartDrain.countDown(); + } + } + } + + private void finishStandaloneInstanceStart(DbInstance instance, String account, String region, + String image, Map parameters) { + String id = instance.getDbInstanceIdentifier(); + DbInstance starting; + synchronized (instance) { + if (findInstanceForScope(account, region, id) != instance) { + return; + } + if (instance.getStatus() != DbInstanceStatus.CREATING) { + standaloneStarts.remove(instance); + finishDeferredInstanceDelete(instance, region); + return; + } + starting = creatingResponse(instance); + standaloneStarts.put(instance, InstanceStartPhase.STARTING); + } + startInstanceRuntime(instance, starting, account, region, image, parameters); + if (discardLateInstanceStarts) { + stopServingStoppedInVpc(starting); + try { + proxyManager.stopProxy(rdsResourceRelayKey(starting.getDbInstanceArn(), id)); + } finally { + containerManager.stopByRuntimeId(starting.getDbInstanceArn()); + } + return; + } + synchronized (instance) { + standaloneStarts.remove(instance); + if (findInstanceForScope(account, region, id) != instance) { + return; + } + if (instance.getStatus() == DbInstanceStatus.DELETING) { + instance.setVpcEndpointAddress(starting.getVpcEndpointAddress()); + finishDeferredInstanceDelete(instance, region); + } else if (instance.getStatus() == DbInstanceStatus.CREATING) { + publishStandaloneInstanceStart(instance, starting, account, region); + } + } + } + + private void startInstanceRuntime(DbInstance instance, DbInstance starting, String account, String region, + String image, Map parameters) { + try { + startStandaloneInstanceContainer(starting, image, parameters); + if (!discardLateInstanceStarts && instance.getStatus() == DbInstanceStatus.CREATING + && hasBackend(starting.getContainerHost(), starting.getContainerPort())) { + startCreatedInstanceProxy(starting, account, region); + } + starting.setStatus(DbInstanceStatus.AVAILABLE); + } catch (RuntimeException failure) { + stopFailedInstanceStart(starting, failure); + } + } + + private void publishStandaloneInstanceStart(DbInstance instance, DbInstance starting, String account, String region) { + copyStartedRuntime(instance, starting); + try { + putInstanceForScope(account, region, instance.getDbInstanceIdentifier(), instance); + } catch (RuntimeException failure) { + stopFailedInstanceStart(starting, failure); + copyStartedRuntime(instance, starting); + try { + putInstanceForScope(account, region, instance.getDbInstanceIdentifier(), instance); + } catch (RuntimeException persistFailure) { + failure.addSuppressed(persistFailure); + LOG.errorv(failure, "Could not persist failed DB instance {0}", instance.getDbInstanceArn()); + } + } + } + + private static void copyStartedRuntime(DbInstance instance, DbInstance starting) { + instance.setContainerId(starting.getContainerId()); + instance.setContainerHost(starting.getContainerHost()); + instance.setContainerPort(starting.getContainerPort()); + instance.setBackendNeverStarted(starting.isBackendNeverStarted()); + instance.setVpcEndpointAddress(starting.getVpcEndpointAddress()); + instance.setStatus(starting.getStatus()); + } + + private void stopFailedInstanceStart(DbInstance starting, RuntimeException failure) { + if (hasBackend(starting.getContainerHost(), starting.getContainerPort())) { + try { + proxyManager.stopProxy(rdsResourceRelayKey( + starting.getDbInstanceArn(), starting.getDbInstanceIdentifier())); + } catch (RuntimeException cleanup) { + failure.addSuppressed(cleanup); + } + } + try { + containerManager.stopByRuntimeId(starting.getDbInstanceArn()); + starting.setContainerId(null); + starting.setContainerHost(null); + starting.setContainerPort(0); + } catch (RuntimeException cleanup) { + failure.addSuppressed(cleanup); + } + starting.setStatus(DbInstanceStatus.FAILED); + LOG.errorv(failure, "Failed to start DB instance {0}", starting.getDbInstanceArn()); + } + + private void startStandaloneInstanceContainer(DbInstance instance, String image, Map parameters) { + String arn = instance.getDbInstanceArn(); + RdsContainerHandle handle = containerManager.tryStart(arn, instance.getDbInstanceIdentifier(), + instance.getContainerStorageResourceId(), instance.getDockerVolumeName(), instance.getEngine(), image, + instance.getMasterUsername(), instance.getMasterPassword(), instance.getDbName(), parameters); + if (handle != null) { + instance.setContainerId(handle.getContainerId()); + instance.setContainerHost(handle.getHost()); + instance.setContainerPort(handle.getPort()); + } else if (!containerManager.refusedParameterGroup(arn)) { + instance.setBackendNeverStarted(containerManager.getActiveHandle(arn) == null); + LOG.warnv("DB instance {0} has no reachable Docker daemon. Metadata is available.", arn); + } + } + + private void startCreatedInstanceProxy(DbInstance instance, String account, String region) { + String id = instance.getDbInstanceIdentifier(); + InstanceBackendIdentity identity = instanceBackendIdentity(instance); + DbEndpoint endpoint = instance.getEndpoint(); + proxyManager.startProxy(rdsResourceRelayKey(instance.getDbInstanceArn(), id), identity.runtimeId(), + instance.getEngine(), instance.isIamDatabaseAuthenticationEnabled(), instance.getProxyPort(), + instance.getContainerHost(), instance.getContainerPort(), endpoint.address(), instance.getMasterUsername(), + instance.getMasterPassword(), instance.getDbName(), + (user, pw) -> validateDbPasswordForScope(account, region, id, user, pw), + proxyBinding(instance.getEngine(), endpoint.address(), endpoint.port(), region, account, + identity.dbUserResourceId())); + serveInVpc(instance); } private void rollbackFailedStandaloneInstanceCreate( @@ -2124,7 +2422,12 @@ public class RdsService implements Resettable, ResourceProvider { if (instance.getStatus() == DbInstanceStatus.DELETING && snapshotData.get(dataKey).isPresent()) { backup.setDataSaved(true); } else { - String dump = saveBackupData(instance.getEngine(), instance.getContainerId(), instance.getMasterUsername(), + String containerId = instance.getContainerId(); + if (instance.getDeleteAutomatedBackupsAfterStart() != null + && instance.getEngine() == DatabaseEngine.POSTGRES) { + containerId = recoverDeferredBackupContainer(instance); + } + String dump = saveBackupData(instance.getEngine(), containerId, instance.getMasterUsername(), "DB instance " + instance.getDbInstanceIdentifier(), "InvalidDBInstanceState"); if (dump != null) { snapshotData.put(dataKey, dump); @@ -2134,6 +2437,21 @@ public class RdsService implements Resettable, ResourceProvider { return backup; } + /** A delete accepted during startup owns the volume even if the container ID was never persisted. */ + private String recoverDeferredBackupContainer(DbInstance instance) { + if (!config.services().rds().mock()) { + RdsContainerHandle handle = containerManager.getActiveHandle(instance.getDbInstanceArn()); + if (handle == null || !hasBackend(handle.getHost(), handle.getPort())) { + handle = startInstanceContainer(instance); + } + if (handle != null) { + return handle.getContainerId(); + } + } + throw new AwsException("InvalidDBInstanceState", "Cannot retain the automated backup of DB instance " + + instance.getDbInstanceIdentifier() + " until its PostgreSQL database is running.", 400); + } + private DbClusterAutomatedBackup retainedClusterBackupOf(DbCluster cluster, String region) { Instant now = Instant.now(); DbClusterAutomatedBackup backup = new DbClusterAutomatedBackup(); @@ -4197,10 +4515,13 @@ public class RdsService implements Resettable, ResourceProvider { validateInstanceSettings(settings); String effectiveRegion = effectiveRegion(region); DbInstance instance = getDbInstance(id, effectiveRegion); - // "You can't modify a stopped DB instance" (user guide, stopping an instance temporarily). - if (isStoppedOrInTransit(instance.getStatus())) { + DbInstanceStatus status = instance.getStatus(); + if (status == DbInstanceStatus.CREATING) { + throw new AwsException("InvalidDBInstanceState", "Database instance is not in available state.", 400); + } + if (status == DbInstanceStatus.DELETING || isStoppedOrInTransit(status)) { throw new AwsException("InvalidDBInstanceState", - "DB instance " + id + " is in state " + instance.getStatus().name().toLowerCase(Locale.ROOT) + "DB instance " + id + " is in state " + status.name().toLowerCase(Locale.ROOT) + " and cannot be modified.", 400); } // Resolved before the first setter runs, since the checks it carries read the instance's @@ -5198,6 +5519,15 @@ public class RdsService implements Resettable, ResourceProvider { String effectiveRegion = effectiveRegion(region); DbInstance instance = getDbInstance(id, effectiveRegion); + if (instance.getStatus() == DbInstanceStatus.CREATING) { + throw new AwsException("InvalidDBInstanceState", + "Can only reboot db instances with state in: available, storage-optimization, " + + "storage-initialization, incompatible-credentials, incompatible-parameters. " + + "Instance " + id + " has state: creating.", 400); + } + if (instance.getStatus() == DbInstanceStatus.DELETING) { + throw new AwsException("InvalidDBInstanceState", "DB instance " + id + " is not in available state.", 400); + } instance.setStatus(DbInstanceStatus.REBOOTING); putInstanceForScope(currentAccountId(), effectiveRegion, id, instance); @@ -5395,7 +5725,9 @@ public class RdsService implements Resettable, ResourceProvider { private synchronized DbInstance doEnsureInstanceBackend(String id, String region) { String effectiveRegion = effectiveRegion(region); DbInstance instance = getDbInstance(id, effectiveRegion); - if (config.services().rds().mock()) { + if (standaloneStarts.get(instance) == InstanceStartPhase.STARTING + || instance.getStatus() == DbInstanceStatus.DELETING + || config.services().rds().mock()) { return instance; } if (hasBackend(instance.getContainerHost(), instance.getContainerPort())) { @@ -5471,7 +5803,7 @@ public class RdsService implements Resettable, ResourceProvider { instance.setContainerPort(backendPort); instance.setProxyPort(relayPort); instance.setEndpoint(relayEndpoint); - if (instance.getStatus() == DbInstanceStatus.FAILED) { + if (instance.getStatus() == DbInstanceStatus.FAILED || instance.getStatus() == DbInstanceStatus.CREATING) { instance.setStatus(DbInstanceStatus.AVAILABLE); } putInstanceForScope(currentAccountId(), effectiveRegion, id, instance); @@ -5764,6 +6096,19 @@ public class RdsService implements Resettable, ResourceProvider { "DB instance " + id + " is the source of a blue/green deployment being created.", 400); } + if (standaloneStarts.containsKey(instance)) { + // Keep the record, port and runtime identity until the worker can tear down everything it started. + if (instance.getDeleteAutomatedBackupsAfterStart() == null) { + instance.setDeleteAutomatedBackupsAfterStart(deleteAutomatedBackups); + } + instance.setBackendCleanupRequired(true); + instance.setStatus(DbInstanceStatus.DELETING); + putInstanceForScope(currentAccountId(), effectiveRegion, id, instance); + return; + } + if (instance.getDeleteAutomatedBackupsAfterStart() != null) { + deleteAutomatedBackups = instance.getDeleteAutomatedBackupsAfterStart(); + } String clusterId = instance.getDbClusterIdentifier(); // Taken before the instance changes, so a failed copy of its data leaves it as it was. DbInstanceAutomatedBackup retained = !deleteAutomatedBackups && isBlank(clusterId) @@ -10909,11 +11254,29 @@ public class RdsService implements Resettable, ResourceProvider { } } + private void finishDeferredInstanceDelete(DbInstance instance, String region) { + Boolean deleteBackups = instance.getDeleteAutomatedBackupsAfterStart(); + if (deleteBackups != null) { + try { + deleteDbInstance(instance.getDbInstanceIdentifier(), region, deleteBackups); + } catch (RuntimeException failure) { + LOG.warnv(failure, "Could not finish deleting DB instance {0}", instance.getDbInstanceArn()); + } + } + } + private void restoreInstances(Map persistedPortOwners) { for (DbInstance instance : allInstances()) { if (instance.getStatus() == DbInstanceStatus.DELETING) { + if (instance.getDeleteAutomatedBackupsAfterStart() != null) { + String region = regionResolver.regionOf(instance.getDbInstanceArn()); + RequestScopes.runAs(accountIdFromArn(instance.getDbInstanceArn()), region, + () -> finishDeferredInstanceDelete(instance, region)); + } continue; } + boolean previouslyUnready = instance.getStatus() == DbInstanceStatus.CREATING + || instance.getStatus() == DbInstanceStatus.FAILED; boolean wasInVpc = RdsEndpointAddresses.inVpc(instance); placeRestoredEndpoint(instance); boolean inVpc = RdsEndpointAddresses.inVpc(instance); @@ -11055,7 +11418,7 @@ public class RdsService implements Resettable, ResourceProvider { instance.setProxyPort(0); instance.setEndpoint(null); } - instance.setStatus(portReserved ? DbInstanceStatus.AVAILABLE : DbInstanceStatus.FAILED); + instance.setStatus(portReserved && !previouslyUnready ? DbInstanceStatus.AVAILABLE : DbInstanceStatus.FAILED); String retainedContainerId = !containerCleaned && cleanupHandle != null ? cleanupHandle.getContainerId() : restoredHandle == null ? persistedContainerId : 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 5dfa73e3be..71b03b3fb4 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 @@ -33,7 +33,7 @@ public class DbInstance { private String caCertificateIdentifier; /** The license model the request named; null means the engine's default. */ private String licenseModel; - private DbInstanceStatus status; + private volatile DbInstanceStatus status; private DbEndpoint endpoint; private boolean iamDatabaseAuthenticationEnabled; private String parameterGroupName; @@ -106,6 +106,8 @@ public class DbInstance { // Legacy records default to protected: only a confirmed never-started backend may change versions. private boolean backendNeverStarted; private boolean backendCleanupRequired; + // An accepted deletion while Docker is starting must keep its backup choice across a restart. + private Boolean deleteAutomatedBackupsAfterStart; private boolean managedSecretCleanupRequired; private transient String containerId; @@ -341,6 +343,11 @@ public class DbInstance { this.backendNeverStarted = backendNeverStarted; } + public Boolean getDeleteAutomatedBackupsAfterStart() { return deleteAutomatedBackupsAfterStart; } + public void setDeleteAutomatedBackupsAfterStart(Boolean deleteAutomatedBackupsAfterStart) { + this.deleteAutomatedBackupsAfterStart = deleteAutomatedBackupsAfterStart; + } + public boolean isBackendCleanupRequired() { return backendCleanupRequired; } public void setBackendCleanupRequired(boolean backendCleanupRequired) { this.backendCleanupRequired = backendCleanupRequired; diff --git a/src/test/java/io/floci/aws/lifecycle/EmulatorInfoControllerTest.java b/src/test/java/io/floci/aws/lifecycle/EmulatorInfoControllerTest.java index eb05433359..105c250ad5 100644 --- a/src/test/java/io/floci/aws/lifecycle/EmulatorInfoControllerTest.java +++ b/src/test/java/io/floci/aws/lifecycle/EmulatorInfoControllerTest.java @@ -214,6 +214,9 @@ class EmulatorInfoControllerTest { verify(resettable).checkReset(); verify(refusing).checkReset(); + InOrder rollback = inOrder(refusing, resettable); + rollback.verify(refusing).cancelResetCheck(); + rollback.verify(resettable).cancelResetCheck(); verifyNoMoreInteractions(resettable, refusing); verify(sageMakerTeardown, never()).stopManagedContainers(); verifyNoInteractions(storageFactory); diff --git a/src/test/java/io/floci/aws/lifecycle/EmulatorLifecycleTest.java b/src/test/java/io/floci/aws/lifecycle/EmulatorLifecycleTest.java index 6a5cb9ffcf..59912808fd 100644 --- a/src/test/java/io/floci/aws/lifecycle/EmulatorLifecycleTest.java +++ b/src/test/java/io/floci/aws/lifecycle/EmulatorLifecycleTest.java @@ -1091,8 +1091,11 @@ class EmulatorLifecycleTest { // shutdown can't be cut off by the SIGTERM grace window before data is persisted // (regression guard for issue #1521). shutdownAll() still runs last to stop the flush // schedulers and capture any shutdown-time writes. - InOrder inOrder = Mockito.inOrder(storageFactory, rdsContainerManager, elastiCacheContainerManager); + InOrder inOrder = Mockito.inOrder(storageFactory, rdsService, rdsProxyManager, rdsContainerManager, + elastiCacheContainerManager); inOrder.verify(storageFactory).flushAll(); + inOrder.verify(rdsService).shutdownInstanceStarts(); + inOrder.verify(rdsProxyManager).stopAll(); inOrder.verify(elastiCacheContainerManager).stopAll(); inOrder.verify(rdsContainerManager).stopAll(); inOrder.verify(storageFactory).shutdownAll(); diff --git a/src/test/java/io/floci/aws/services/rds/RdsEndpointsInVpcDockerNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/rds/RdsEndpointsInVpcDockerNightlyIntegrationTest.java index f9d8814a43..974d90863f 100644 --- a/src/test/java/io/floci/aws/services/rds/RdsEndpointsInVpcDockerNightlyIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/rds/RdsEndpointsInVpcDockerNightlyIntegrationTest.java @@ -34,6 +34,7 @@ import java.util.Set; import java.util.UUID; import java.util.concurrent.TimeUnit; +import static io.floci.aws.testing.RdsRequests.waitForAvailableInstance; import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; @@ -113,8 +114,7 @@ class RdsEndpointsInVpcDockerNightlyIntegrationTest { String firstName = AwsEndpoints.rdsInstanceHost(first, ACCOUNT, REGION); String secondName = AwsEndpoints.rdsInstanceHost(second, ACCOUNT, REGION); for (String id : List.of(first, second)) { - DBInstance described = rds.describeDBInstances(r -> r.dbInstanceIdentifier(id)) - .dbInstances().getFirst(); + DBInstance described = waitForAvailableInstance(rds, id); assertEquals(AwsEndpoints.rdsInstanceHost(id, ACCOUNT, REGION), described.endpoint().address()); assertEquals(5432, described.endpoint().port()); } @@ -251,6 +251,7 @@ class RdsEndpointsInVpcDockerNightlyIntegrationTest { .secretArn("arn:aws:secretsmanager:" + REGION + ":" + ACCOUNT + ":secret:db-AbCdEf") .build())).dbProxy().endpoint(); assertEquals(AwsEndpoints.rdsProxyHost(proxyName, ACCOUNT, REGION), proxyEndpoint); + waitForAvailableInstance(rds, instanceId); rds.registerDBProxyTargets(r -> r.dbProxyName(proxyName).dbInstanceIdentifiers(instanceId)); String added = rds.createDBProxyEndpoint(r -> r.dbProxyName(proxyName) .dbProxyEndpointName(endpointName).vpcSubnetIds(subnets)).dbProxyEndpoint().endpoint(); diff --git a/src/test/java/io/floci/aws/services/rds/RdsEngineVersionDockerNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/rds/RdsEngineVersionDockerNightlyIntegrationTest.java index a65b8da8cf..1f5c6b0efe 100644 --- a/src/test/java/io/floci/aws/services/rds/RdsEngineVersionDockerNightlyIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/rds/RdsEngineVersionDockerNightlyIntegrationTest.java @@ -21,6 +21,7 @@ import java.util.concurrent.TimeUnit; import static io.floci.aws.testing.RdsRequests.assumeDocker; import static io.floci.aws.testing.RdsRequests.cleanupDockerInstance; import static io.floci.aws.testing.RdsRequests.rdsDockerClient; +import static io.floci.aws.testing.RdsRequests.waitForAvailableInstance; import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -56,7 +57,7 @@ class RdsEngineVersionDockerNightlyIntegrationTest { createFailure = failure; throw failure; } - DBInstance original = describe(client, id); + DBInstance original = waitForAvailableInstance(client, id); int port = original.endpoint().port(); await().atMost(Duration.ofSeconds(60)).untilAsserted(() -> assertTrue(query(port, "SHOW server_version").startsWith("16.4"))); diff --git a/src/test/java/io/floci/aws/services/rds/RdsLogFilesDockerIntegrationTest.java b/src/test/java/io/floci/aws/services/rds/RdsLogFilesDockerIntegrationTest.java index f7b89db8e0..a2b834a5c6 100644 --- a/src/test/java/io/floci/aws/services/rds/RdsLogFilesDockerIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/rds/RdsLogFilesDockerIntegrationTest.java @@ -2,7 +2,6 @@ package io.floci.aws.services.rds; import com.github.dockerjava.api.DockerClient; import io.quarkus.test.junit.QuarkusTest; -import io.restassured.path.xml.XmlPath; import io.restassured.specification.RequestSpecification; import jakarta.inject.Inject; import org.junit.jupiter.api.BeforeEach; @@ -11,6 +10,7 @@ import org.junit.jupiter.api.Test; import java.util.List; +import static io.floci.aws.testing.RdsRequests.waitForAvailableInstance; import static io.restassured.RestAssured.given; import static io.restassured.http.ContentType.URLENC; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -62,8 +62,7 @@ class RdsLogFilesDockerIntegrationTest { .formParam("AllocatedStorage", "20") .when().post("/").then().statusCode(200); - // CreateDBInstance returns once the database accepts connections, so its startup log is - // already in the container's output: the first call must see it. + waitForAvailableInstance(id); List names = query("DescribeDBLogFiles").formParam("DBInstanceIdentifier", id) .when().post("/").then().statusCode(200).extract().xmlPath() .getList("**.findAll { it.name() == 'LogFileName' }", String.class); diff --git a/src/test/java/io/floci/aws/services/rds/RdsMysqlSnapshotDockerNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/rds/RdsMysqlSnapshotDockerNightlyIntegrationTest.java index 176f777846..ef9f4fa9c2 100644 --- a/src/test/java/io/floci/aws/services/rds/RdsMysqlSnapshotDockerNightlyIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/rds/RdsMysqlSnapshotDockerNightlyIntegrationTest.java @@ -19,6 +19,7 @@ import java.util.concurrent.atomic.AtomicReference; import static io.floci.aws.testing.RdsRequests.assumeDocker; import static io.floci.aws.testing.RdsRequests.deleteInstance; import static io.floci.aws.testing.RdsRequests.rds; +import static io.floci.aws.testing.RdsRequests.waitForAvailableInstance; import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -98,7 +99,7 @@ class RdsMysqlSnapshotDockerNightlyIntegrationTest { } private static int createInstance(String instanceId, String engine, String version) { - return rds("CreateDBInstance") + rds("CreateDBInstance") .formParam("DBInstanceIdentifier", instanceId) .formParam("Engine", engine) .formParam("EngineVersion", version) @@ -107,8 +108,8 @@ class RdsMysqlSnapshotDockerNightlyIntegrationTest { .formParam("MasterUsername", MASTER_USER) .formParam("MasterUserPassword", MASTER_PASSWORD) .formParam("DBName", "appdb") - .when().post("/").then().statusCode(200).extract().xmlPath() - .getInt("CreateDBInstanceResponse.CreateDBInstanceResult.DBInstance.Endpoint.Port"); + .when().post("/").then().statusCode(200); + return waitForAvailableInstance(instanceId).endpoint().port(); } /** Runs the statements in one connection, once the server accepts it (see {@link #whenConnected}). */ diff --git a/src/test/java/io/floci/aws/services/rds/RdsParameterGroupEngineDockerNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/rds/RdsParameterGroupEngineDockerNightlyIntegrationTest.java index 64a4495372..8590d9e642 100644 --- a/src/test/java/io/floci/aws/services/rds/RdsParameterGroupEngineDockerNightlyIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/rds/RdsParameterGroupEngineDockerNightlyIntegrationTest.java @@ -20,6 +20,7 @@ import java.util.concurrent.TimeUnit; import static io.floci.aws.testing.RdsRequests.assumeDocker; import static io.floci.aws.testing.RdsRequests.deleteInstance; import static io.floci.aws.testing.RdsRequests.rds; +import static org.awaitility.Awaitility.await; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -207,7 +208,7 @@ class RdsParameterGroupEngineDockerNightlyIntegrationTest { createParameterGroup(group, "mysql8.0", "sql_mode", "NOT_A_MODE"); try { int port = createInstance(instanceId, "mysql", "8.0", group); - assertThat(instanceStatus(instanceId), equalTo("incompatible-parameters")); + await().atMost(90, TimeUnit.SECONDS).until(() -> instanceStatus(instanceId), equalTo("incompatible-parameters")); modifyParameterGroup(group, "sql_mode", "STRICT_TRANS_TABLES", "immediate"); rebootInstance(instanceId); diff --git a/src/test/java/io/floci/aws/services/rds/RdsQueryHandlerTest.java b/src/test/java/io/floci/aws/services/rds/RdsQueryHandlerTest.java index 948a6e4e05..b8eccac229 100644 --- a/src/test/java/io/floci/aws/services/rds/RdsQueryHandlerTest.java +++ b/src/test/java/io/floci/aws/services/rds/RdsQueryHandlerTest.java @@ -304,7 +304,7 @@ class RdsQueryHandlerTest { boolean enabled = Boolean.parseBoolean(value); Boolean setting = value == null ? null : enabled; ArgumentCaptor settings = ArgumentCaptor.forClass(DbInstanceSettings.class); - when(service.createDbInstance(eq("mydb"), eq("postgres"), eq("16.3"), + when(service.beginCreateDbInstance(eq("mydb"), eq("postgres"), eq("16.3"), isNull(), isNull(), isNull(), eq("db.t3.micro"), eq(20), eq(enabled), isNull(), isNull(), isNull(), isNull(), eq(enabled), eq(enabled), isNull(), eq(Map.of()), eq(List.of()), isNull(), isNull(), eq(true), settings.capture(), @@ -355,7 +355,7 @@ class RdsQueryHandlerTest { @Test void caCertificateIdentifierReachesTheServiceFromEveryActionThatTakesIt() { ArgumentCaptor created = ArgumentCaptor.forClass(DbInstanceSettings.class); - when(service.createDbInstance(eq("mydb"), any(), any(), any(), any(), any(), any(), anyInt(), anyBoolean(), + when(service.beginCreateDbInstance(eq("mydb"), any(), any(), any(), any(), any(), any(), anyInt(), anyBoolean(), any(), any(), any(), any(), anyBoolean(), anyBoolean(), any(), any(), any(), any(), any(), anyBoolean(), created.capture(), any(), any(), any())).thenReturn(makeInstance("mydb")); ArgumentCaptor modified = ArgumentCaptor.forClass(DbInstanceSettings.class); @@ -659,7 +659,7 @@ class RdsQueryHandlerTest { @Test void createDbInstance_forwardsDeletionProtection() { DbInstance instance = makeInstance("mydb"); - when(service.createDbInstance(eq("mydb"), eq("postgres"), eq("16.3"), + when(service.beginCreateDbInstance(eq("mydb"), eq("postgres"), eq("16.3"), eq(null), eq(null), eq(null), eq("db.t3.micro"), eq(20), eq(false), eq(null), eq(null), eq(null), eq(null), eq(false), eq(false), eq(null), any(), any(), isNull(), isNull(), eq(true), any(DbInstanceSettings.class), isNull(), isNull(), eq(true))) @@ -672,7 +672,7 @@ class RdsQueryHandlerTest { handler.handle("CreateDBInstance", p); - verify(service).createDbInstance(eq("mydb"), eq("postgres"), eq("16.3"), + verify(service).beginCreateDbInstance(eq("mydb"), eq("postgres"), eq("16.3"), eq(null), eq(null), eq(null), eq("db.t3.micro"), eq(20), eq(false), eq(null), eq(null), eq(null), eq(null), eq(false), eq(false), eq(null), any(), any(), isNull(), isNull(), eq(true), any(DbInstanceSettings.class), isNull(), isNull(), eq(true)); @@ -1155,7 +1155,7 @@ class RdsQueryHandlerTest { @Test void createDbInstance_passesCreateTagsToService() { DbInstance instance = makeInstance("mydb"); - when(service.createDbInstance(eq("mydb"), eq("postgres"), eq("16.3"), + when(service.beginCreateDbInstance(eq("mydb"), eq("postgres"), eq("16.3"), eq(null), eq(null), eq(null), eq("db.t3.micro"), eq(20), eq(false), eq(null), eq(null), eq(null), eq(null), eq(false), eq(false), eq(null), eq(Map.of("example:ClusterId", "cluster-a", "Name", "mydb")), eq(List.of()), isNull(), isNull(), eq(true), any(DbInstanceSettings.class), isNull(), isNull(), isNull())) @@ -1170,7 +1170,7 @@ class RdsQueryHandlerTest { p.add("Tags.member.2.Value", "mydb"); handler.handle("CreateDBInstance", p); - verify(service).createDbInstance("mydb", "postgres", "16.3", + verify(service).beginCreateDbInstance("mydb", "postgres", "16.3", null, null, null, "db.t3.micro", 20, false, null, null, null, null, false, false, null, Map.of("example:ClusterId", "cluster-a", "Name", "mydb"), List.of(), null, null, true, DbInstanceSettings.defaults(), null, null, null); } @@ -1179,7 +1179,7 @@ class RdsQueryHandlerTest { void createDbInstance_passesVpcSecurityGroupsToServiceAndXml() { DbInstance instance = makeInstance("mydb"); instance.setVpcSecurityGroupIds(List.of("sg-123", "sg-456")); - when(service.createDbInstance(eq("mydb"), eq("postgres"), eq("16.3"), + when(service.beginCreateDbInstance(eq("mydb"), eq("postgres"), eq("16.3"), eq(null), eq(null), eq(null), eq("db.t3.micro"), eq(20), eq(false), eq(null), eq(null), eq(null), eq(null), eq(false), eq(false), eq(null), eq(Map.of()), eq(List.of("sg-123", "sg-456")), isNull(), isNull(), eq(true), any(DbInstanceSettings.class), isNull(), isNull(), isNull())) @@ -1195,7 +1195,7 @@ class RdsQueryHandlerTest { String body = (String) response.getEntity(); assertTrue(body.contains("sg-123")); assertTrue(body.contains("sg-456")); - verify(service).createDbInstance("mydb", "postgres", "16.3", + verify(service).beginCreateDbInstance("mydb", "postgres", "16.3", null, null, null, "db.t3.micro", 20, false, null, null, null, null, false, false, null, Map.of(), List.of("sg-123", "sg-456"), null, null, true, DbInstanceSettings.defaults(), null, null, null); } @@ -1211,7 +1211,7 @@ class RdsQueryHandlerTest { assertEquals(400, response.getStatus()); assertTrue(((String) response.getEntity()).contains("InvalidParameterValue")); - verify(service, never()).createDbInstance(any(), any(), any(), any(), any(), any(), any(), + verify(service, never()).beginCreateDbInstance(any(), any(), any(), any(), any(), any(), any(), anyInt(), anyBoolean(), any(), any(), any(), any(), anyBoolean(), anyBoolean(), any(), any(), any(), any(), any(), anyBoolean(), any(DbInstanceSettings.class), isNull(), isNull(), isNull()); } @@ -1326,7 +1326,7 @@ class RdsQueryHandlerTest { @Test void createDbInstance_invalidAllocatedStorageFallsBackToDefaultAndEngineVersionDefaults() { DbInstance instance = makeInstance("mydb"); - when(service.createDbInstance(eq("mydb"), eq("postgres"), eq("16.3"), + when(service.beginCreateDbInstance(eq("mydb"), eq("postgres"), eq("16.3"), eq("admin"), eq("secret"), eq("dbname"), eq("db.t3.micro"), eq(20), eq(false), eq(null), eq(null), eq(null), eq(null), eq(false), eq(false), eq(null), eq(Map.of()), eq(List.of()), isNull(), isNull(), eq(true), any(DbInstanceSettings.class), isNull(), isNull(), isNull())) @@ -1341,7 +1341,7 @@ class RdsQueryHandlerTest { p.add("AllocatedStorage", "not-a-number"); handler.handle("CreateDBInstance", p); - verify(service).createDbInstance("mydb", "postgres", "16.3", + verify(service).beginCreateDbInstance("mydb", "postgres", "16.3", "admin", "secret", "dbname", "db.t3.micro", 20, false, null, null, null, null, false, false, null, Map.of(), List.of(), null, null, true, DbInstanceSettings.defaults(), null, null, null); } @@ -1352,7 +1352,7 @@ class RdsQueryHandlerTest { instance.setMasterUserSecretArn("arn:aws:secretsmanager:us-east-1:000000000000:secret:rds!db-123456"); instance.setMasterUserSecretStatus("active"); instance.setMasterUserSecretKmsKeyId("kms-key-1"); - when(service.createDbInstance(eq("mydb"), eq("postgres"), eq("16.3"), + when(service.beginCreateDbInstance(eq("mydb"), eq("postgres"), eq("16.3"), eq("admin"), eq(null), eq("dbname"), eq("db.t3.micro"), eq(20), eq(false), eq(null), eq(null), eq(null), eq(null), eq(false), eq(true), eq("kms-key-1"), eq(Map.of()), eq(List.of()), isNull(), isNull(), eq(true), any(DbInstanceSettings.class), isNull(), isNull(), isNull())) @@ -1372,7 +1372,7 @@ class RdsQueryHandlerTest { assertTrue(body.contains("arn:aws:secretsmanager:us-east-1:000000000000:secret:rds!db-123456")); assertTrue(body.contains("active")); assertTrue(body.contains("kms-key-1")); - verify(service).createDbInstance("mydb", "postgres", "16.3", + verify(service).beginCreateDbInstance("mydb", "postgres", "16.3", "admin", null, "dbname", "db.t3.micro", 20, false, null, null, null, null, false, true, "kms-key-1", Map.of(), List.of(), null, null, true, DbInstanceSettings.defaults(), null, null, null); } @@ -1384,7 +1384,7 @@ class RdsQueryHandlerTest { instance.setDbSubnetGroupName("default"); instance.setAvailabilityZone("ap-northeast-1a"); instance.setMultiAz(true); - when(service.createDbInstance(eq("mydb"), eq("postgres"), eq("16.3"), + when(service.beginCreateDbInstance(eq("mydb"), eq("postgres"), eq("16.3"), eq("admin"), eq("secret"), eq("dbname"), eq("db.t3.micro"), eq(20), eq(false), eq(null), eq("default"), eq(null), eq("ap-northeast-1a"), eq(true), eq(false), eq(null), eq(Map.of()), eq(List.of()), isNull(), isNull(), eq(true), any(DbInstanceSettings.class), isNull(), isNull(), isNull())) @@ -1414,7 +1414,7 @@ class RdsQueryHandlerTest { void createDbInstance_honorsExplicitAutoMinorVersionUpgradeFalse() { DbInstance instance = makeInstance("mydb"); instance.setAutoMinorVersionUpgrade(false); - when(service.createDbInstance(eq("mydb"), eq("postgres"), eq("16.3"), + when(service.beginCreateDbInstance(eq("mydb"), eq("postgres"), eq("16.3"), eq(null), eq(null), eq(null), eq("db.t3.micro"), eq(20), eq(false), eq(null), eq(null), eq(null), eq(null), eq(false), eq(false), eq(null), eq(Map.of()), eq(List.of()), isNull(), isNull(), eq(false), any(DbInstanceSettings.class), isNull(), isNull(), isNull())) @@ -1434,7 +1434,7 @@ class RdsQueryHandlerTest { @Test void createDbInstance_unknownSubnetGroupShouldFailValidation() { - when(service.createDbInstance(eq("mydb"), eq("postgres"), eq("16.3"), + when(service.beginCreateDbInstance(eq("mydb"), eq("postgres"), eq("16.3"), eq("admin"), eq("secret"), eq("dbname"), eq("db.t3.micro"), eq(20), eq(false), eq(null), eq("missing-subnet-group"), eq(null), eq(null), eq(false), eq(false), eq(null), eq(Map.of()), eq(List.of()), isNull(), isNull(), eq(true), any(DbInstanceSettings.class), isNull(), isNull(), isNull())) @@ -1526,7 +1526,7 @@ class RdsQueryHandlerTest { // Handler defaults version to "1.0" for unknown engines, then the service // rejects the engine. Verify the full error path: version defaulting + // AwsException wrapping into a 400 query error. - when(service.createDbInstance(eq("mydb"), eq("oracle"), eq("1.0"), + when(service.beginCreateDbInstance(eq("mydb"), eq("oracle"), eq("1.0"), eq(null), eq(null), eq(null), eq("db.t3.micro"), eq(20), eq(false), eq(null), eq(null), eq(null), eq(null), eq(false), eq(false), eq(null), eq(Map.of()), eq(List.of()), isNull(), isNull(), eq(true), any(DbInstanceSettings.class), isNull(), isNull(), isNull())) @@ -3442,7 +3442,7 @@ class RdsQueryHandlerTest { @Test void createDbInstance_passesOptionGroupName() { DbInstance instance = makeInstance("mydb"); - when(service.createDbInstance(any(), any(), any(), any(), any(), any(), any(), + when(service.beginCreateDbInstance(any(), any(), any(), any(), any(), any(), any(), anyInt(), anyBoolean(), any(), any(), any(), any(), anyBoolean(), anyBoolean(), any(), any(), anyList(), any(), any(), anyBoolean(), any(DbInstanceSettings.class), isNull(), isNull(), isNull())) .thenReturn(instance); @@ -3454,7 +3454,7 @@ class RdsQueryHandlerTest { Response response = handler.handle("CreateDBInstance", p); assertEquals(200, response.getStatus()); - verify(service).createDbInstance(eq("mydb"), eq("mysql"), any(), any(), any(), any(), + verify(service).beginCreateDbInstance(eq("mydb"), eq("mysql"), any(), any(), any(), any(), any(), anyInt(), anyBoolean(), any(), any(), any(), any(), anyBoolean(), anyBoolean(), any(), any(), anyList(), eq("og1"), any(), anyBoolean(), any(DbInstanceSettings.class), isNull(), isNull(), isNull()); } @@ -3828,7 +3828,7 @@ class RdsQueryHandlerTest { @Test void createDbInstance_passesStorageAndBackupSettingsToService() { DbInstance instance = makeInstance("mydb"); - when(service.createDbInstance(any(), any(), any(), any(), any(), any(), any(), + when(service.beginCreateDbInstance(any(), any(), any(), any(), any(), any(), any(), anyInt(), anyBoolean(), any(), any(), any(), any(), anyBoolean(), anyBoolean(), any(), any(), anyList(), any(), any(), anyBoolean(), any(DbInstanceSettings.class), isNull(), isNull(), isNull())) .thenReturn(instance); @@ -3846,7 +3846,7 @@ class RdsQueryHandlerTest { assertEquals(200, handler.handle("CreateDBInstance", p).getStatus()); ArgumentCaptor captor = ArgumentCaptor.forClass(DbInstanceSettings.class); - verify(service).createDbInstance(any(), any(), any(), any(), any(), any(), any(), + verify(service).beginCreateDbInstance(any(), any(), any(), any(), any(), any(), any(), anyInt(), anyBoolean(), any(), any(), any(), any(), anyBoolean(), anyBoolean(), any(), any(), anyList(), any(), any(), anyBoolean(), captor.capture(), isNull(), isNull(), isNull()); DbInstanceSettings settings = captor.getValue(); @@ -3861,7 +3861,7 @@ class RdsQueryHandlerTest { @Test void createDbInstance_omittedSettingsReachServiceAsNull() { DbInstance instance = makeInstance("mydb"); - when(service.createDbInstance(any(), any(), any(), any(), any(), any(), any(), + when(service.beginCreateDbInstance(any(), any(), any(), any(), any(), any(), any(), anyInt(), anyBoolean(), any(), any(), any(), any(), anyBoolean(), anyBoolean(), any(), any(), anyList(), any(), any(), anyBoolean(), any(DbInstanceSettings.class), isNull(), isNull(), isNull())) .thenReturn(instance); @@ -3872,7 +3872,7 @@ class RdsQueryHandlerTest { handler.handle("CreateDBInstance", p); ArgumentCaptor captor = ArgumentCaptor.forClass(DbInstanceSettings.class); - verify(service).createDbInstance(any(), any(), any(), any(), any(), any(), any(), + verify(service).beginCreateDbInstance(any(), any(), any(), any(), any(), any(), any(), anyInt(), anyBoolean(), any(), any(), any(), any(), anyBoolean(), anyBoolean(), any(), any(), anyList(), any(), any(), anyBoolean(), captor.capture(), isNull(), isNull(), isNull()); assertEquals(DbInstanceSettings.defaults(), captor.getValue()); @@ -3890,7 +3890,7 @@ class RdsQueryHandlerTest { assertEquals(400, response.getStatus()); String body = (String) response.getEntity(); assertTrue(body.contains("InvalidParameterValue"), body); - verify(service, never()).createDbInstance(any(), any(), any(), any(), any(), any(), any(), + verify(service, never()).beginCreateDbInstance(any(), any(), any(), any(), any(), any(), any(), anyInt(), anyBoolean(), any(), any(), any(), any(), anyBoolean(), anyBoolean(), any(), any(), anyList(), any(), any(), anyBoolean(), any(DbInstanceSettings.class), isNull(), isNull(), isNull()); } @@ -4020,7 +4020,7 @@ class RdsQueryHandlerTest { @Test void unhandledExceptionRendersXmlInternalFailure() { - when(service.createDbInstance(any(), any(), any(), any(), any(), any(), + when(service.beginCreateDbInstance(any(), any(), any(), any(), any(), any(), any(), anyInt(), anyBoolean(), any(), any(), any(), any(), anyBoolean(), anyBoolean(), any(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), any())) .thenThrow(new RuntimeException("Docker daemon connection failed")); diff --git a/src/test/java/io/floci/aws/services/rds/RdsReadReplicaDockerNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/rds/RdsReadReplicaDockerNightlyIntegrationTest.java index 82b1210ec9..e3bce9096d 100644 --- a/src/test/java/io/floci/aws/services/rds/RdsReadReplicaDockerNightlyIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/rds/RdsReadReplicaDockerNightlyIntegrationTest.java @@ -9,6 +9,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import static io.floci.aws.testing.RdsRequests.waitForAvailableInstance; import static io.restassured.RestAssured.given; import static io.restassured.http.ContentType.URLENC; import static org.hamcrest.Matchers.containsString; @@ -52,13 +53,15 @@ class RdsReadReplicaDockerNightlyIntegrationTest { if (!engine.startsWith("sqlserver")) { request.formParam("DBName", "appdb"); } - return request.when().post("/").then(); + ValidatableResponse created = request.when().post("/").then().statusCode(200); + waitForAvailableInstance(id); + return created; } @Test @Order(1) void createReadReplicaLinksBothEndsInDescribeDbInstances() { - createInstance(SOURCE, "postgres", "16.3", "password123").statusCode(200) + createInstance(SOURCE, "postgres", "16.3", "password123") .body(containsString("")) .body(not(containsString(""))); @@ -180,7 +183,7 @@ class RdsReadReplicaDockerNightlyIntegrationTest { @Test @Order(6) void createReadReplicaAcceptsAMysqlSourceAndRefusesSqlServer() { - createInstance("replica-test-mysql", "mysql", "8.0.36", "password123").statusCode(200); + createInstance("replica-test-mysql", "mysql", "8.0.36", "password123"); query("CreateDBInstanceReadReplica") .formParam("DBInstanceIdentifier", "replica-test-mysql-reader") @@ -192,7 +195,7 @@ class RdsReadReplicaDockerNightlyIntegrationTest { .body(containsString("replica-test-mysql" + "")); - createInstance("replica-test-sqlserver", "sqlserver-se", "15.00", "Password123!").statusCode(200); + createInstance("replica-test-sqlserver", "sqlserver-se", "15.00", "Password123!"); query("CreateDBInstanceReadReplica") .formParam("DBInstanceIdentifier", "replica-test-sqlserver-reader") diff --git a/src/test/java/io/floci/aws/services/rds/RdsRoleAssociationDockerNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/rds/RdsRoleAssociationDockerNightlyIntegrationTest.java index 6bffc88a01..03367aab62 100644 --- a/src/test/java/io/floci/aws/services/rds/RdsRoleAssociationDockerNightlyIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/rds/RdsRoleAssociationDockerNightlyIntegrationTest.java @@ -8,6 +8,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import static io.floci.aws.testing.RdsRequests.waitForAvailableInstance; import static io.restassured.RestAssured.given; import static io.restassured.http.ContentType.URLENC; import static org.hamcrest.Matchers.contains; @@ -72,6 +73,7 @@ class RdsRoleAssociationDockerNightlyIntegrationTest { .formParam("MasterUserPassword", "password123") .formParam("AllocatedStorage", "20") .when().post("/").then().statusCode(200); + waitForAvailableInstance(INSTANCE); } @Test 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 ee5eb4afad..1ff3cbfa96 100644 --- a/src/test/java/io/floci/aws/services/rds/RdsServiceTest.java +++ b/src/test/java/io/floci/aws/services/rds/RdsServiceTest.java @@ -4,7 +4,9 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.ContainerTeardown; import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.Resettable; import io.floci.aws.core.common.docker.ContainerLiveness; import io.floci.aws.core.common.docker.CurrentContainerNetworkResolver; import io.floci.aws.core.common.docker.DockerHostResolver; @@ -14,6 +16,7 @@ import io.floci.aws.core.storage.PersistentStorage; import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.core.storage.WalStorage; +import io.floci.aws.lifecycle.EmulatorInfoController; import io.floci.aws.services.dsql.DsqlPrincipals; import io.floci.aws.services.dsql.dataplane.DsqlDatabases; import io.floci.aws.services.dsql.dataplane.DsqlEndpoint; @@ -256,6 +259,339 @@ class RdsServiceTest { .toList()); } + @Test + void createAcknowledgesAndPublishesBeforeTheDatabaseStarts() throws Exception { + when(rdsConfig.mock()).thenReturn(false); + CountDownLatch starting = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenAnswer(call -> { + starting.countDown(); + if (!release.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Test did not release database startup"); + } + return new RdsContainerHandle("test-container", "test-runtime", "localhost", 5432); + }); + try { + DbInstance response = beginStandaloneCreate("starting-db"); + assertTrue(starting.await(5, TimeUnit.SECONDS)); + assertEquals(DbInstanceStatus.CREATING, response.getStatus()); + assertEquals(DbInstanceStatus.CREATING, rdsService.getDbInstance("starting-db").getStatus()); + AwsException duplicate = assertThrows(AwsException.class, () -> beginStandaloneCreate("starting-db")); + assertEquals("DBInstanceAlreadyExists", duplicate.getErrorCode()); + assertTimeoutPreemptively(Duration.ofSeconds(2), () -> { + AwsException modify = assertThrows(AwsException.class, () -> rdsService.modifyDbInstance( + "starting-db", null, null, null, null, null, "us-east-1", false)); + assertEquals("InvalidDBInstanceState", modify.getErrorCode()); + AwsException reboot = assertThrows(AwsException.class, () -> rdsService.rebootDbInstance("starting-db")); + assertEquals("InvalidDBInstanceState", reboot.getErrorCode()); + assertEquals(400, reboot.getHttpStatus()); + assertEquals("Can only reboot db instances with state in: available, storage-optimization, " + + "storage-initialization, incompatible-credentials, incompatible-parameters. " + + "Instance starting-db has state: creating.", reboot.getMessage()); + DbInstance pending = rdsService.ensureInstanceBackend("starting-db", "us-east-1"); + assertEquals(DbInstanceStatus.CREATING, pending.getStatus()); + assertNull(pending.getContainerId()); + }); + release.countDown(); + await().atMost(Duration.ofSeconds(5)).until(() -> + rdsService.getDbInstance("starting-db").getStatus() == DbInstanceStatus.AVAILABLE); + assertEquals(DbInstanceStatus.CREATING, response.getStatus()); + } finally { + release.countDown(); + rdsService.checkReset(); + } + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void stalledInstanceStartHasABoundedDrain(boolean shutdown) throws Exception { + when(rdsConfig.mock()).thenReturn(false); + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + when(containerManager.tryStart(any(), eq("slow-start"), any(), any(), any(), any(), any(), any(), any(), any())) + .thenAnswer(call -> { + started.countDown(); + try { + release.await(); + } catch (InterruptedException interrupted) { + // The Docker call can finish after shutdown interrupts the worker. + release.await(); + } + return new RdsContainerHandle("slow-container", "slow-start", "localhost", 5432); + }); + try { + beginStandaloneCreate("slow-start"); + assertTrue(started.await(5, TimeUnit.SECONDS)); + if (shutdown) { + assertTimeoutPreemptively(Duration.ofSeconds(25), rdsService::shutdownInstanceStarts); + release.countDown(); + await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> + verify(containerManager, atLeastOnce()).stopByRuntimeId(anyString())); + assertEquals(DbInstanceStatus.CREATING, rdsService.getDbInstance("slow-start").getStatus()); + verify(proxyManager, never()).startProxy(any(), any(), any(), anyBoolean(), anyInt(), any(), anyInt(), + any(), any(), any(), any(), any(), any()); + } else { + StorageFactory storage = mock(); + ContainerTeardown otherContainers = mock(); + EmulatorInfoController controller = resetController(storage, otherContainers, List.of(rdsService)); + AwsException busy = assertTimeoutPreemptively(Duration.ofSeconds(25), + () -> assertThrows(AwsException.class, controller::reset)); + assertEquals(503, busy.getHttpStatus()); + assertEquals("ServiceUnavailable", busy.getErrorCode()); + verifyNoInteractions(otherContainers, storage); + beginStandaloneCreate("next-start"); + release.countDown(); + rdsService.checkReset(); + assertEquals(DbInstanceStatus.AVAILABLE, rdsService.getDbInstance("slow-start").getStatus()); + assertEquals(DbInstanceStatus.AVAILABLE, rdsService.getDbInstance("next-start").getStatus()); + } + } finally { + release.countDown(); + rdsService.afterReset(); + rdsService.shutdownInstanceStarts(); + } + } + + @Test + void laterResetRefusalReopensInstanceCreation() { + when(rdsConfig.mock()).thenReturn(false); + when(rdsConfig.proxyMaxPort()).thenReturn(7000); + doThrow(new IllegalStateException("Docker unavailable")).when(containerManager).stopForDelete(any(), any()); + Resettable refusing = mock(); + IllegalStateException refusal = new IllegalStateException("reset refused"); + doAnswer(call -> { + AwsException busy = assertThrows(AwsException.class, () -> beginStandaloneCreate("during-check")); + assertEquals(503, busy.getHttpStatus()); + assertEquals("DBInstanceNotFound", assertThrows(AwsException.class, + () -> rdsService.getDbInstance("during-check")).getErrorCode()); + verifyNoInteractions(containerManager, proxyManager); + throw refusal; + }).when(refusing).checkReset(); + StorageFactory storage = mock(); + ContainerTeardown otherContainers = mock(); + EmulatorInfoController controller = resetController(storage, otherContainers, List.of(rdsService, refusing)); + + try { + assertSame(refusal, assertThrows(IllegalStateException.class, controller::reset)); + verifyNoInteractions(otherContainers, storage); + assertEquals(7000, beginStandaloneCreate("during-check").getProxyPort()); + } finally { + rdsService.shutdownInstanceStarts(); + } + } + + private EmulatorInfoController resetController(StorageFactory storage, ContainerTeardown otherContainers, + List services) { + Instance resettables = mock(); + when(resettables.iterator()).thenAnswer(call -> services.iterator()); + Instance teardowns = mock(); + when(teardowns.iterator()).thenAnswer(call -> List.of(otherContainers, rdsService).iterator()); + return new EmulatorInfoController(null, null, storage, resettables, teardowns, null, config, null); + } + + @Test + void deleteDuringProxyStartupKeepsTheIdentifierUntilCleanup() throws Exception { + when(rdsConfig.mock()).thenReturn(false); + CountDownLatch proxyStarting = new CountDownLatch(1); + CountDownLatch releaseProxy = new CountDownLatch(1); + doAnswer(call -> { + proxyStarting.countDown(); + if (!releaseProxy.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Test did not release proxy startup"); + } + return null; + }).when(proxyManager).startProxy(any(), any(), any(), anyBoolean(), anyInt(), any(), anyInt(), + any(), any(), any(), any(), any(), any()); + String id = "delete-during-start"; + try { + beginStandaloneCreate(id); + assertTrue(proxyStarting.await(5, TimeUnit.SECONDS)); + DbInstance instance = rdsService.getDbInstance(id); + assertNull(instance.getContainerHost()); + when(containerManager.getActiveHandle(instance.getDbInstanceArn())) + .thenReturn(new RdsContainerHandle("cont-id", instance.getDbInstanceArn(), id, "localhost", 5432)); + when(containerManager.createPostgresSnapshot("cont-id", "admin")).thenReturn("retained dump"); + assertTimeoutPreemptively(Duration.ofSeconds(2), () -> rdsService.deleteDbInstance(id, "us-east-1", false)); + rdsService.deleteDbInstance(id); + assertEquals(DbInstanceStatus.DELETING, rdsService.getDbInstance(id).getStatus()); + AwsException duplicate = assertThrows(AwsException.class, () -> beginStandaloneCreate(id)); + assertEquals("DBInstanceAlreadyExists", duplicate.getErrorCode()); + } finally { + releaseProxy.countDown(); + rdsService.checkReset(); + } + AwsException deleted = assertThrows(AwsException.class, () -> rdsService.getDbInstance(id)); + assertEquals("DBInstanceNotFound", deleted.getErrorCode()); + verify(containerManager).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(containerManager).createPostgresSnapshot("cont-id", "admin"); + verify(proxyManager).stopProxy(anyString()); + verify(containerManager).removeVolume(any(), any(), any()); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void deferredDeleteRecoversTheRetainedBackupBeforeRemovingTheVolume(boolean retryOnBoot, @TempDir Path tempDir) + throws Exception { + when(rdsConfig.mock()).thenReturn(false); + String id = "delete-on-restore"; + String region = "us-east-1"; + DbInstance instance = rdsService.createDbInstance(id, "postgres", "16.3", "admin", "password", + "app", "db.t3.micro", 20, false, null, null, null); + // Startup had not published its runtime when the delete was accepted. + instance.setContainerId(null); + instance.setContainerHost(null); + instance.setContainerPort(0); + instance.setDeleteAutomatedBackupsAfterStart(false); + instance.setBackendCleanupRequired(true); + instance.setStatus(DbInstanceStatus.DELETING); + Path file = tempDir.resolve("instances.json"); + TypeReference> type = new TypeReference<>() {}; + new PersistentStorage(file, type).put(region + "::" + id, instance); + PersistentStorage instances = new PersistentStorage<>(file, type); + instances.load(); + RdsContainerManager manager = mock(RdsContainerManager.class); + RdsService restarted = newService(manager, mock(RdsProxyManager.class), instances, new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>()); + + restarted.restorePersistedRuntime(); + assertEquals(DbInstanceStatus.DELETING, restarted.getDbInstance(id).getStatus()); + verify(manager, never()).stopForDelete(any(), any()); + verify(manager, never()).removeVolume(any(), any(), any()); + + String arn = instance.getDbInstanceArn(); + when(manager.tryStart(eq(arn), eq(id), eq(instance.getContainerStorageResourceId()), + eq(instance.getDockerVolumeName()), eq(DatabaseEngine.POSTGRES), any(), eq("admin"), eq("password"), + eq("app"), any())).thenReturn(new RdsContainerHandle("recovered", arn, id, "localhost", 5432)); + when(manager.createPostgresSnapshot("recovered", "admin")).thenReturn("retained dump"); + if (retryOnBoot) { + restarted.restorePersistedRuntime(); + } else { + restarted.deleteDbInstance(id, region, true); + } + verify(manager).removeVolume(arn, instance.getContainerStorageResourceId(), instance.getDockerVolumeName()); + assertEquals("DBInstanceNotFound", assertThrows(AwsException.class, () -> restarted.getDbInstance(id)) + .getErrorCode()); + + String target = "restored-db"; + when(manager.tryStart(any(), eq(target), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(new RdsContainerHandle("restored", target, "localhost", 5432)); + restarted.restoreDbInstanceToPointInTime(restoreLatestBackup(target, instance), region); + verify(manager).restorePostgresSnapshot("restored", "admin", "retained dump"); + } + + @Test + void firstDataRequestCanFinishStartingTheInstanceBeforeTheCreateWorkerRuns() { + when(rdsConfig.mock()).thenReturn(false); + onFirstInstanceWrite(() -> rdsService.ensureInstanceBackend("early-request", "us-east-1")); + try { + assertEquals(DbInstanceStatus.CREATING, beginStandaloneCreate("early-request").getStatus()); + } finally { + rdsService.checkReset(); + } + DbInstance instance = rdsService.getDbInstance("early-request"); + assertEquals(DbInstanceStatus.AVAILABLE, instance.getStatus()); + assertEquals("cont-id", instance.getContainerId()); + verify(containerManager).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(containerManager, never()).stopByRuntimeId(any()); + } + + @Test + void deleteBeforeStartupKeepsARestorableBackup() { + String id = "early-delete"; + String region = "us-east-1"; + when(containerManager.createPostgresSnapshot("cont-id", "admin")).thenReturn("retained dump"); + onFirstInstanceWrite(() -> { + rdsService.deleteDbInstance(id, region, false); + assertEquals(DbInstanceStatus.DELETING, rdsService.getDbInstance(id).getStatus()); + verify(containerManager, never()).removeVolume(any(), any(), any()); + }); + DbInstance created; + try { + created = beginStandaloneCreate(id); + rdsService.checkReset(); + } finally { + rdsService.afterReset(); + } + assertEquals("DBInstanceNotFound", assertThrows(AwsException.class, + () -> rdsService.getDbInstance(id)).getErrorCode()); + rdsService.restoreDbInstanceToPointInTime(restoreLatestBackup("restored-db", created), region); + verify(containerManager).restorePostgresSnapshot("cont-id", "admin", "retained dump"); + } + + private static PointInTimeRestoreRequest restoreLatestBackup(String target, DbInstance source) { + return new PointInTimeRestoreRequest(target, null, source.getDbiResourceId(), null, null, true, + null, null, null, null, null, null, null, null, null, null, null, null, null, null, + null, null, Map.of()); + } + + @Test + void modifyingACreatingInstanceLeavesStartupToTheWorker() { + when(rdsConfig.mock()).thenReturn(false); + String id = "early-modify"; + onFirstInstanceWrite(() -> { + AwsException failure = assertThrows(AwsException.class, + () -> rdsService.modifyDbInstance(id, null, null, null, null, null, "us-east-1", false)); + assertEquals("InvalidDBInstanceState", failure.getErrorCode()); + assertEquals(400, failure.getHttpStatus()); + assertEquals("Database instance is not in available state.", failure.getMessage()); + DbInstance pending = rdsService.getDbInstance(id); + assertEquals(DbInstanceStatus.CREATING, pending.getStatus()); + assertTrue(pending.isAutoMinorVersionUpgrade()); + }); + try { + assertEquals(DbInstanceStatus.CREATING, beginStandaloneCreate(id).getStatus()); + } finally { + rdsService.checkReset(); + } + DbInstance ready = rdsService.getDbInstance(id); + assertEquals(DbInstanceStatus.AVAILABLE, ready.getStatus()); + assertEquals("cont-id", ready.getContainerId()); + verify(proxyManager).startProxy(any(), any(), any(), anyBoolean(), eq(ready.getProxyPort()), any(), + anyInt(), any(), any(), any(), any(), any(), any()); + DbInstance modified = rdsService.modifyDbInstance(id, null, null, null, null, null, "us-east-1", false); + assertFalse(modified.isAutoMinorVersionUpgrade()); + } + + private void onFirstInstanceWrite(Runnable request) { + StorageBackend instances = spy(new InMemoryStorage()); + rdsService = newService(containerManager, proxyManager, instances, new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>()); + AtomicBoolean firstWrite = new AtomicBoolean(true); + doAnswer(call -> { + call.callRealMethod(); + if (firstWrite.getAndSet(false)) { + // The instance is visible here, before the create worker has been scheduled. + request.run(); + } + return null; + }).when(instances).put(anyString(), any()); + } + + @Test + void failedBackgroundStartStaysFailedIfRecoveryCannotStartTheDatabase() { + when(rdsConfig.mock()).thenReturn(false); + when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenThrow(new IllegalStateException("database refused startup")); + try { + assertEquals(DbInstanceStatus.CREATING, beginStandaloneCreate("failed-start").getStatus()); + await().atMost(Duration.ofSeconds(5)).until(() -> + rdsService.getDbInstance("failed-start").getStatus() == DbInstanceStatus.FAILED); + rdsService.checkReset(); + rdsService.clear(); + rdsService.restorePersistedRuntime(); + assertEquals(DbInstanceStatus.FAILED, rdsService.getDbInstance("failed-start").getStatus()); + } finally { + rdsService.checkReset(); + } + } + + private DbInstance beginStandaloneCreate(String id) { + return rdsService.beginCreateDbInstance(id, "postgres", "16.3", "admin", "password", "dbname", + "db.t3.micro", 20, false, null, null, null, null, false, false, null, + Map.of(), List.of(), null, null, true, DbInstanceSettings.defaults(), null, null, null); + } + @Test void startingAnInstanceWaitsForItsLockWithoutHoldingTheServiceLock() throws Exception { when(rdsConfig.mock()).thenReturn(true); diff --git a/src/test/java/io/floci/aws/services/rds/export/RdsSnapshotExportDockerNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/rds/export/RdsSnapshotExportDockerNightlyIntegrationTest.java index 13600fe9df..d3a20d0914 100644 --- a/src/test/java/io/floci/aws/services/rds/export/RdsSnapshotExportDockerNightlyIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/rds/export/RdsSnapshotExportDockerNightlyIntegrationTest.java @@ -35,6 +35,7 @@ import java.util.Map; import java.util.Properties; import java.util.UUID; +import static io.floci.aws.testing.RdsRequests.waitForAvailableInstance; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.containsString; @@ -88,15 +89,16 @@ class RdsSnapshotExportDockerNightlyIntegrationTest { String taskId = "export-" + suffix; s3Service.createBucket(bucket, "us-east-1"); try (RdsClient rds = rdsClient()) { - DBInstance instance = rds.createDBInstance(request -> request + rds.createDBInstance(request -> request .dbInstanceIdentifier(dbId) .engine("postgres") .masterUsername(MASTER_USER) .masterUserPassword(MASTER_PASSWORD) .dbName("appdb") .allocatedStorage(20) - .dbInstanceClass("db.t3.micro")).dbInstance(); + .dbInstanceClass("db.t3.micro")); try { + DBInstance instance = waitForAvailableInstance(rds, dbId); asMaster(instance.endpoint().port(), "CREATE TABLE items (id int PRIMARY KEY, small int2, big int8, ratio float8, flag bool, " + "name text, price numeric(10,2), created_at timestamptz, attrs jsonb, " @@ -191,15 +193,16 @@ class RdsSnapshotExportDockerNightlyIntegrationTest { String taskId = "export-" + suffix; s3Service.createBucket(bucket, "us-east-1"); try (RdsClient rds = rdsClient()) { - DBInstance instance = rds.createDBInstance(request -> request + rds.createDBInstance(request -> request .dbInstanceIdentifier(dbId) .engine("postgres") .masterUsername(MASTER_USER) .masterUserPassword(MASTER_PASSWORD) .dbName("appdb") .allocatedStorage(20) - .dbInstanceClass("db.t3.micro")).dbInstance(); + .dbInstanceClass("db.t3.micro")); try { + DBInstance instance = waitForAvailableInstance(rds, dbId); asMaster(instance.endpoint().port(), "CREATE TABLE events (id int)", "CREATE TABLE late_events () INHERITS (events)", @@ -241,15 +244,16 @@ class RdsSnapshotExportDockerNightlyIntegrationTest { String taskId = "export-" + suffix; s3Service.createBucket(bucket, "us-east-1"); try (RdsClient rds = rdsClient()) { - DBInstance instance = rds.createDBInstance(request -> request + rds.createDBInstance(request -> request .dbInstanceIdentifier(dbId) .engine("postgres") .masterUsername(MASTER_USER) .masterUserPassword(MASTER_PASSWORD) .dbName("appdb") .allocatedStorage(20) - .dbInstanceClass("db.t3.micro")).dbInstance(); + .dbInstanceClass("db.t3.micro")); try { + DBInstance instance = waitForAvailableInstance(rds, dbId); asMaster(instance.endpoint().port(), "CREATE DOMAIN public.int4 AS text", "CREATE TABLE labelled (id int, label public.int4)", diff --git a/src/test/java/io/floci/aws/services/rds/proxy/RdsPgBouncerDockerNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/rds/proxy/RdsPgBouncerDockerNightlyIntegrationTest.java index 487cf78f7a..502f13a5f1 100644 --- a/src/test/java/io/floci/aws/services/rds/proxy/RdsPgBouncerDockerNightlyIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/rds/proxy/RdsPgBouncerDockerNightlyIntegrationTest.java @@ -28,6 +28,7 @@ import java.util.List; import java.util.Properties; import java.util.Set; +import static io.floci.aws.testing.RdsRequests.createPostgresInstance; import static io.floci.aws.testing.RdsRequests.rds; import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -59,16 +60,7 @@ class RdsPgBouncerDockerNightlyIntegrationTest { void freshPgBouncerServerLoginsKeepWorking(String serverTlsMode) throws Exception { String suffix = Long.toString(System.nanoTime(), 36); String dbId = "pgbouncer-" + suffix; - int proxyPort = rds("CreateDBInstance") - .formParam("DBInstanceIdentifier", dbId) - .formParam("Engine", "postgres") - .formParam("MasterUsername", "master") - .formParam("MasterUserPassword", "Master123!") - .formParam("DBName", "appdb") - .formParam("AllocatedStorage", "20") - .formParam("DBInstanceClass", "db.t3.micro") - .when().post("/").then().statusCode(200).extract().xmlPath() - .getInt("CreateDBInstanceResponse.CreateDBInstanceResult.DBInstance.Endpoint.Port"); + int proxyPort = createPostgresInstance(dbId, "master", "Master123!", false); ContainerInfo pooler = null; Closeable poolerLogs = null; try { diff --git a/src/test/java/io/floci/aws/testing/RdsRequests.java b/src/test/java/io/floci/aws/testing/RdsRequests.java index cb872159d6..b7d0128862 100644 --- a/src/test/java/io/floci/aws/testing/RdsRequests.java +++ b/src/test/java/io/floci/aws/testing/RdsRequests.java @@ -5,11 +5,13 @@ import io.restassured.specification.RequestSpecification; import org.jboss.logging.Logger; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.core.retry.backoff.FixedDelayBackoffStrategy; import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.retries.StandardRetryStrategy; import software.amazon.awssdk.services.rds.RdsClient; import software.amazon.awssdk.services.rds.RdsClientBuilder; +import software.amazon.awssdk.services.rds.model.DBInstance; import software.amazon.awssdk.services.rds.model.DbInstanceNotFoundException; import software.amazon.awssdk.services.rds.model.RdsException; import software.amazon.awssdk.services.rds.model.VpcSecurityGroupMembership; @@ -135,10 +137,20 @@ public final class RdsRequests { if (parameterGroupName != null) { request.formParam("DBParameterGroupName", parameterGroupName); } - return request - .when().post("/").then().statusCode(200) - .extract().xmlPath() - .getInt("CreateDBInstanceResponse.CreateDBInstanceResult.DBInstance.Endpoint.Port"); + request.when().post("/").then().statusCode(200); + return waitForAvailableInstance(id).endpoint().port(); + } + + public static DBInstance waitForAvailableInstance(String id) { + try (RdsClient client = rdsClient("us-east-1", "test")) { + return waitForAvailableInstance(client, id); + } + } + + public static DBInstance waitForAvailableInstance(RdsClient client, String id) { + return client.waiter().waitUntilDBInstanceAvailable(r -> r.dbInstanceIdentifier(id), + o -> o.maxAttempts(120).backoffStrategy(FixedDelayBackoffStrategy.create(Duration.ofSeconds(1)))) + .matched().response().orElseThrow().dbInstances().getFirst(); } public static RequestSpecification createAuroraPostgresCluster(String id) {