diff --git a/.github/ci/prefetch-images.sh b/.github/ci/prefetch-images.sh index c9cfedd8ce..6803981c14 100755 --- a/.github/ci/prefetch-images.sh +++ b/.github/ci/prefetch-images.sh @@ -194,6 +194,8 @@ if grep -q '/neptune/' "$SHARD_FILE"; then configured_image neptune default-neo4j-image configured_image neptune default-image fi +# DocDbClusterRestartDockerNightlyIntegrationTest restarts clusters on the configured MongoDB image. +starts DocDbClusterRestartDockerNightlyIntegrationTest && configured_image docdb default-image grep -q '/elasticache/' "$SHARD_FILE" && { pull valkey/valkey:8; pull memcached:1.6; } grep -q '/memorydb/' "$SHARD_FILE" && pull valkey/valkey:8 grep -q '/ecr/' "$SHARD_FILE" && pull registry:2 diff --git a/docs/services/docdb.md b/docs/services/docdb.md index 46a1224dba..16155b1526 100644 --- a/docs/services/docdb.md +++ b/docs/services/docdb.md @@ -75,6 +75,24 @@ create or restore that fails leaves no volume behind. A cluster created again un identifier starts on a new, empty volume. In `memory` mode a cluster's data lasts only as long as its container. +### Restarts + +With a persistent storage mode, Floci's shutdown removes each cluster's MongoDB container and keeps +its volume, and the next start brings the container back. While it starts again in the background, +the cluster reports `maintenance` and its instances `starting`. The new container runs on the +cluster's volume with the cluster's master password, so the data is there and snapshots keep +working. The cluster and its instances then report the new container's port and `available`. With +no Docker daemon reachable they come back `available` with no container, as a cluster created then +does. A cluster whose container does not start is left with none and its instances `failed`, and is +tried again at the next start. A `DeleteDBCluster` during the restore leaves the cluster `deleting` +until its container has started, and removes it then. `CreateDBInstance` is refused with +`InvalidDBClusterStateFault` for a cluster that is not `available`, as for RDS. + +A cluster created by a Floci that did not keep its master password reads it from the container it +left, if one is still there. With none left there is no password to start a container with, so the +cluster comes back without one, its instances `failed`: delete it and create it again. A cluster +whose data was not kept in a volume gets a new, empty one. + ### Docker Compose DocumentDB needs the Docker socket so it can launch MongoDB containers. Each cluster's container is published on a dynamically assigned host port, returned by `DescribeDBClusters`. diff --git a/src/main/java/io/floci/aws/lifecycle/EmulatorLifecycle.java b/src/main/java/io/floci/aws/lifecycle/EmulatorLifecycle.java index 9dcae64641..425b8b193d 100644 --- a/src/main/java/io/floci/aws/lifecycle/EmulatorLifecycle.java +++ b/src/main/java/io/floci/aws/lifecycle/EmulatorLifecycle.java @@ -13,6 +13,7 @@ import io.floci.aws.services.amazonmq.container.RabbitMqManager; import io.floci.aws.services.appsync.graphql.SchemaCreationWorker; import io.floci.aws.services.cloudwatch.metrics.CloudWatchMetricsService; import io.floci.aws.services.codeartifact.CodeArtifactService; +import io.floci.aws.services.docdb.DocDbService; import io.floci.aws.services.docdb.container.DocDbContainerManager; import io.floci.aws.services.dynamodb.DynamoDbRuntime; import io.floci.aws.services.ec2.Ec2MetadataServer; @@ -104,6 +105,7 @@ public class EmulatorLifecycle { private final MemoryDbProxyManager memoryDbProxyManager; private final MemoryDbService memoryDbService; private final DocDbContainerManager docDbContainerManager; + private final DocDbService docDbService; private final NeptuneContainerManager neptuneContainerManager; private final NeptuneProxyManager neptuneProxyManager; private final RabbitMqManager rabbitMqManager; @@ -157,6 +159,7 @@ public class EmulatorLifecycle { MemoryDbProxyManager memoryDbProxyManager, MemoryDbService memoryDbService, DocDbContainerManager docDbContainerManager, + DocDbService docDbService, NeptuneContainerManager neptuneContainerManager, NeptuneProxyManager neptuneProxyManager, RabbitMqManager rabbitMqManager, @@ -207,6 +210,7 @@ public class EmulatorLifecycle { this.memoryDbProxyManager = memoryDbProxyManager; this.memoryDbService = memoryDbService; this.docDbContainerManager = docDbContainerManager; + this.docDbService = docDbService; this.neptuneContainerManager = neptuneContainerManager; this.neptuneProxyManager = neptuneProxyManager; this.rabbitMqManager = rabbitMqManager; @@ -355,6 +359,13 @@ public class EmulatorLifecycle { return null; }); } + if (config.services().docdb().enabled()) { + // Starts the clusters' containers in the background, failing the future with the ones it could not. + docDbService.restorePersistedRuntime().exceptionally(ex -> { + LOG.error("Failed to restore persisted DocumentDB clusters at startup", ex); + return null; + }); + } if (config.services().elbv2().enabled()) { elbV2Service.restorePersistedRuntime(); } diff --git a/src/main/java/io/floci/aws/services/docdb/DocDbService.java b/src/main/java/io/floci/aws/services/docdb/DocDbService.java index bc44eefb17..15524fd09e 100644 --- a/src/main/java/io/floci/aws/services/docdb/DocDbService.java +++ b/src/main/java/io/floci/aws/services/docdb/DocDbService.java @@ -6,7 +6,9 @@ import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.BackupWindows; import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.RequestScopes; import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.core.storage.AccountAwareStorageBackend.AccountEntry; import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.services.docdb.container.DocDbContainerHandle; @@ -35,6 +37,7 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.UUID; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; import java.util.function.Function; @@ -251,6 +254,7 @@ public class DocDbService { if (!"memory".equals(config.storage().mode())) { cluster.setVolumeId(UUID.randomUUID().toString()); } + cluster.setMasterPassword(masterPassword); // A cluster record is metadata: its identifier, ARN and tags need no Docker, so the // cluster is created and reaches 'available' even when no daemon is reachable. Only // connecting to the database needs the container. @@ -623,6 +627,15 @@ public class DocDbService { throw new AwsException("InvalidDBClusterStateFault", "Cannot delete DocDB cluster " + id + " — it still has DB instances.", 400); } + if ("maintenance".equals(cluster.getStatus()) || "deleting".equals(cluster.getStatus())) { + // Only the startup restore reports maintenance, while the cluster's container starts again, and a + // stored cluster reads deleting only while a delete waits on that restore, which removes the cluster + // once the container has started. + cluster.setStatus("deleting"); + clusters.put(key(region, id), cluster); + LOG.infov("DocDB cluster {0} is deleted once its container has started", id); + return; + } removeCluster(region, cluster, false); } @@ -654,6 +667,291 @@ public class DocDbService { LOG.infov("DocDB cluster {0} deleted", id); } + // ── Restart ─────────────────────────────────────────────────────────────── + + /** + * Brings the stored clusters' MongoDB containers back after Floci restarts. Shutdown removes them and keeps their + * data volumes, so a cluster read back from storage reported itself available with nothing behind its endpoint. + * Each cluster reports {@code maintenance}, and its instances {@code starting}, at once, and its container comes + * back in the background, so Floci does not wait for Docker or an image pull. The new container starts on the + * cluster's volume with the master password its data was set up with, and the cluster and its instances then + * report its endpoint and {@code available}. With no Docker daemon reachable they report {@code available} with + * no container, as a cluster created then does. + * + *

A cluster recorded before Floci kept the master password reads it from the container it left, if one is + * there; one recorded before it kept the data in a volume gets a volume now, its data having gone with its + * container. A cluster whose container does not start is left with none and its instances {@code failed}, and is + * tried again at the next start; one still {@code deleting} at startup is removed then. A cluster deleted during + * its restore is {@code deleting} until its container has started, and goes then. Every cluster is tried, and the + * ones that could not be restored fail the returned future together. A shutdown during the restore leaves the + * clusters not started yet as they are, for the next start. + */ + public CompletableFuture restorePersistedRuntime() { + if (config.services().docdb().mock() + || !(clusters instanceof AccountAwareStorageBackend aware)) { + return CompletableFuture.completedFuture(null); + } + Map stored = new LinkedHashMap<>(); + for (AccountEntry entry : aware.scanAllAccountEntries(storedKey -> true)) { + String region = entry.key().contains("::") + ? entry.key().substring(0, entry.key().indexOf("::")) : regionResolver.getDefaultRegion(); + String id = entry.value().getDbClusterIdentifier(); + stored.putIfAbsent(entry.accountId() + "/" + key(region, id), + new RestoringCluster(entry.accountId(), region, id, null, false)); + } + List pending = new ArrayList<>(); + List prepareFailures = new ArrayList<>(); + // Marking is quick and calls no Docker, so it runs before startup goes on; Docker work is all in the background. + for (RestoringCluster candidate : stored.values()) { + try { + RestoringCluster restoring = RequestScopes.callAs(candidate.accountId(), candidate.region(), + () -> prepareRestore(candidate)); + if (restoring != null) { + pending.add(restoring); + } + } catch (RuntimeException e) { + prepareFailures.add(restoreFailure(candidate, e)); + } + } + return CompletableFuture.runAsync(() -> { + List failures = new ArrayList<>(prepareFailures); + for (RestoringCluster restoring : pending) { + if (containerManager.isShuttingDown()) { + // Clusters not reached yet stay as they are, which the next start restores. + break; + } + try { + RequestScopes.runAs(restoring.accountId(), restoring.region(), () -> { + if (restoring.deleting()) { + finishDelete(restoring); + } else { + restoreCluster(restoring); + } + }); + } catch (RuntimeException e) { + failures.add(restoreFailure(restoring, e)); + } + } + if (!failures.isEmpty()) { + RuntimeException failure = failures.getFirst(); + failures.subList(1, failures.size()).forEach(failure::addSuppressed); + throw failure; + } + }); + } + + private static RuntimeException restoreFailure(RestoringCluster restoring, RuntimeException cause) { + return new IllegalStateException("Could not restore DocumentDB cluster " + restoring.id() + " of account " + + restoring.accountId() + " in " + restoring.region(), cause); + } + + /** + * Marks a stored cluster as being restored, under its lock, or, for a delete Floci did not live to finish, as + * one to remove; null for one gone meanwhile. A cluster recorded before its data was kept in a volume is given + * one here, kept before any Docker call, so a failed start leaves no volume behind that nothing names. + */ + private RestoringCluster prepareRestore(RestoringCluster candidate) { + String region = candidate.region(); + String key = key(region, candidate.id()); + RestoringCluster restoring; + List members; + synchronized (lockFor("cluster:" + key)) { + // Read as DescribeDBClusters reads it, which moves a record stored under a legacy key onto its key. + DocDbCluster cluster = findCluster(region, candidate.id()).orElse(null); + if (cluster == null) { + return null; + } + boolean deleting = "deleting".equals(cluster.getStatus()); + restoring = new RestoringCluster(candidate.accountId(), region, candidate.id(), + cluster.getDbClusterResourceId(), deleting); + if (deleting) { + return restoring; + } + members = List.copyOf(cluster.getDbClusterMembers()); + if (cluster.getVolumeId() == null && !"memory".equals(config.storage().mode())) { + cluster.setVolumeId(UUID.randomUUID().toString()); + } + cluster.setStatus("maintenance"); + clusters.put(key, cluster); + } + updateInstances(region, candidate.id(), members, "starting", null, 0); + return restoring; + } + + /** Removes a cluster a delete Floci did not live to finish left behind, its container and volume with it. */ + private void finishDelete(RestoringCluster restoring) { + synchronized (lockFor("cluster:" + key(restoring.region(), restoring.id()))) { + DocDbCluster cluster = restoreTarget(restoring); + if (cluster != null) { + removeCluster(restoring.region(), cluster, false); + } + } + } + + private void restoreCluster(RestoringCluster restoring) { + DocDbContainerHandle handle = null; + try { + DocDbCluster cluster = restoreTarget(restoring); + if (cluster == null) { + return; + } + String password = cluster.getMasterPassword() != null ? cluster.getMasterPassword() + : containerManager.survivingMasterPassword(cluster.getContainerId()); + if (password == null) { + throw new IllegalStateException("DocumentDB cluster " + restoring.id() + " was created before Floci" + + " kept master passwords, and no container of it is left to read its password from;" + + " delete the cluster and create it again"); + } + if (cluster.getMasterPassword() == null) { + // Kept before the container it was read from is replaced, so a failed start does not lose it. + keepPassword(restoring, password); + } + handle = containerManager.tryStart(restoring.id(), config.services().docdb().defaultImage(), + cluster.getMasterUsername(), password, restoring.region(), cluster.getVolumeId()); + finishRestore(restoring, handle); + } catch (RuntimeException e) { + if (handle != null) { + try { + containerManager.stop(handle); + } catch (RuntimeException cleanup) { + e.addSuppressed(cleanup); + } + } + if (containerManager.isShuttingDown()) { + // Left as it is, which the next start restores. + LOG.debugv("DocDB cluster {0} not restored: {1}", restoring.id(), e.getMessage()); + return; + } + try { + failRestore(restoring); + } catch (RuntimeException recordFailure) { + e.addSuppressed(recordFailure); + } + throw e; + } + } + + /** + * Gives the cluster and its instances the container started for it, or none when no Docker daemon is reachable, + * and makes them available; a cluster deleted while it started is removed now. + */ + private void finishRestore(RestoringCluster restoring, DocDbContainerHandle handle) { + String region = restoring.region(); + String key = key(region, restoring.id()); + DocDbCluster cluster; + List members; + synchronized (lockFor("cluster:" + key)) { + cluster = restoreTarget(restoring); + if (cluster == null) { + if (handle != null) { + containerManager.stop(handle); + } + return; + } + if (handle != null) { + cluster.setEndpoint(handle.getHost()); + cluster.setReaderEndpoint(handle.getHost()); + cluster.setPort(handle.getPort()); + cluster.setContainerId(handle.getContainerId()); + cluster.setContainerHost(handle.getHost()); + cluster.setContainerPort(handle.getPort()); + } else { + clearContainer(cluster); + } + if ("deleting".equals(cluster.getStatus())) { + removeCluster(region, cluster, false); + return; + } + cluster.setStatus("available"); + clusters.put(key, cluster); + members = List.copyOf(cluster.getDbClusterMembers()); + } + updateInstances(region, restoring.id(), members, "available", cluster.getEndpoint(), cluster.getPort()); + } + + /** Puts the master password read from a container left behind into the cluster's record. */ + private void keepPassword(RestoringCluster restoring, String password) { + String key = key(restoring.region(), restoring.id()); + synchronized (lockFor("cluster:" + key)) { + DocDbCluster cluster = restoreTarget(restoring); + if (cluster != null) { + cluster.setMasterPassword(password); + clusters.put(key, cluster); + } + } + } + + /** Leaves a cluster whose container did not start with none, and its instances failed, for the next start. */ + private void failRestore(RestoringCluster restoring) { + String region = restoring.region(); + String key = key(region, restoring.id()); + DocDbCluster cluster; + List members; + synchronized (lockFor("cluster:" + key)) { + cluster = restoreTarget(restoring); + if (cluster == null) { + return; + } + if ("deleting".equals(cluster.getStatus())) { + removeCluster(region, cluster, false); + return; + } + clearContainer(cluster); + cluster.setStatus("available"); + clusters.put(key, cluster); + members = List.copyOf(cluster.getDbClusterMembers()); + } + updateInstances(region, restoring.id(), members, "failed", cluster.getEndpoint(), cluster.getPort()); + } + + /** The cluster the restore is for, or null when it is gone or another cluster has taken its identifier. */ + private DocDbCluster restoreTarget(RestoringCluster restoring) { + return findCluster(restoring.region(), restoring.id()) + .filter(cluster -> Objects.equals(cluster.getDbClusterResourceId(), restoring.resourceId())) + .orElse(null); + } + + /** What a cluster with no container reports, as one created with no Docker daemon reachable does. */ + private void clearContainer(DocDbCluster cluster) { + cluster.setEndpoint(resolveEndpointHost()); + cluster.setReaderEndpoint(resolveEndpointHost()); + cluster.setPort(MONGO_PORT); + cluster.setContainerId(null); + cluster.setContainerHost(null); + cluster.setContainerPort(0); + } + + /** + * Sets the status of a cluster's instances and, when given, the endpoint they report, each under its own lock, + * which every path that holds both takes before the cluster's. + */ + private void updateInstances(String region, String clusterId, List members, String status, + String endpoint, int port) { + for (String instanceId : members) { + String key = key(region, instanceId); + synchronized (lockFor("instance:" + key)) { + findInstance(region, instanceId) + .filter(instance -> clusterId.equals(instance.getDbClusterIdentifier())) + .ifPresent(instance -> { + instance.setStatus(status); + if (endpoint != null) { + instance.setEndpoint(endpoint); + instance.setPort(port); + } + instances.put(key, instance); + }); + } + } + } + + /** + * A cluster the startup restore brings back, or removes when {@code deleting}, by the account and Region it is + * stored in and the resource ID it had when marked. + */ + private record RestoringCluster(String accountId, String region, String id, String resourceId, + boolean deleting) { + } + // ── Cluster snapshots ───────────────────────────────────────────────────── /** What a snapshot or a point-in-time restore takes from a cluster: its data and master password. */ @@ -936,6 +1234,10 @@ public class DocDbService { } DocDbCluster cluster = getDbCluster(dbClusterIdentifier); + if (cluster.getStatus() != null && !"available".equals(cluster.getStatus())) { + throw new AwsException("InvalidDBClusterStateFault", + "DB cluster is not available for member creation.", 400); + } DocDbInstance instance = new DocDbInstance(); instance.setDbInstanceIdentifier(id); diff --git a/src/main/java/io/floci/aws/services/docdb/container/DocDbContainerManager.java b/src/main/java/io/floci/aws/services/docdb/container/DocDbContainerManager.java index a0eddacdc5..4135ca3a72 100644 --- a/src/main/java/io/floci/aws/services/docdb/container/DocDbContainerManager.java +++ b/src/main/java/io/floci/aws/services/docdb/container/DocDbContainerManager.java @@ -1,6 +1,6 @@ package io.floci.aws.services.docdb.container; - +import com.github.dockerjava.api.exception.NotFoundException; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.docker.ContainerBuilder; @@ -45,6 +45,7 @@ public class DocDbContainerManager { private final RegionResolver regionResolver; private final Map activeContainers = new ConcurrentHashMap<>(); private volatile boolean dockerUnavailableLogged; + private volatile boolean shuttingDown; @Inject public DocDbContainerManager(ContainerBuilder containerBuilder, @@ -106,6 +107,9 @@ public class DocDbContainerManager { */ public DocDbContainerHandle start(String clusterId, String image, String masterUsername, String masterPassword, String region, String volumeId) { + if (shuttingDown) { + throw new IllegalStateException("DocumentDB is shutting down"); + } LOG.infov("Starting DocumentDB container for cluster: {0}", clusterId); String accountId = regionResolver.getAccountId(); @@ -169,6 +173,10 @@ public class DocDbContainerManager { handle.setLogStream(logHandle); waitForBackendReady(clusterId, endpoint.host(), endpoint.port()); + if (shuttingDown) { + throw new IllegalStateException("DocumentDB shut down while the container for cluster " + + clusterId + " was starting"); + } return handle; } catch (RuntimeException e) { @@ -213,7 +221,17 @@ public class DocDbContainerManager { return ContainerStorageHelper.dockerName(config, "docdb-" + volumeId); } + /** Whether shutdown has begun, after which no container starts. */ + public boolean isShuttingDown() { + return shuttingDown; + } + + /** + * Stops every container, at shutdown. No container starts after this begins, and one already starting removes + * itself when it finishes, so none outlives it. + */ public void stopAll() { + shuttingDown = true; List handles = new ArrayList<>(activeContainers.values()); if (!handles.isEmpty()) { LOG.infov("Stopping {0} DocumentDB container(s) on shutdown", handles.size()); @@ -240,6 +258,21 @@ public class DocDbContainerManager { return null; } + /** + * The master password a container left behind was started with, or null when no container of that ID is left. A + * cluster recorded before Floci kept the password has nowhere else to read it from. + */ + public String survivingMasterPassword(String containerId) { + if (containerId == null) { + return null; + } + try { + return masterPassword(containerId); + } catch (NotFoundException e) { + return null; + } + } + /** * A snapshot of the cluster's data: a gzipped {@code mongodump} archive of every database, * users and roles included, base64 encoded so it travels through the exec's text output. diff --git a/src/main/java/io/floci/aws/services/docdb/model/DocDbCluster.java b/src/main/java/io/floci/aws/services/docdb/model/DocDbCluster.java index 370addfd96..289752cdfd 100644 --- a/src/main/java/io/floci/aws/services/docdb/model/DocDbCluster.java +++ b/src/main/java/io/floci/aws/services/docdb/model/DocDbCluster.java @@ -41,6 +41,11 @@ public class DocDbCluster { private int containerPort; /** Names the cluster's data volume; null for a cluster whose data is not kept, in memory mode or mock mode. */ private String volumeId; + /** + * Kept so a container started again after a restart takes the credentials its data was set up with, which a + * snapshot authenticates with; never returned by the API. + */ + private String masterPassword; public DocDbCluster (){} @@ -115,6 +120,9 @@ public class DocDbCluster { public String getVolumeId() { return volumeId; } public void setVolumeId(String volumeId) { this.volumeId = volumeId; } + public String getMasterPassword() { return masterPassword; } + public void setMasterPassword(String masterPassword) { this.masterPassword = masterPassword; } + public Map getTags() { return tags; } /** Normalizes null: a record persisted before tags were stored deserializes without them. */ diff --git a/src/test/java/io/floci/aws/lifecycle/EmulatorLifecycleTest.java b/src/test/java/io/floci/aws/lifecycle/EmulatorLifecycleTest.java index 177ae35a3d..ad3df221b0 100644 --- a/src/test/java/io/floci/aws/lifecycle/EmulatorLifecycleTest.java +++ b/src/test/java/io/floci/aws/lifecycle/EmulatorLifecycleTest.java @@ -12,6 +12,7 @@ import io.floci.aws.services.amazonmq.container.RabbitMqManager; import io.floci.aws.services.appsync.graphql.SchemaCreationWorker; import io.floci.aws.services.cloudwatch.metrics.CloudWatchMetricsService; import io.floci.aws.services.codeartifact.CodeArtifactService; +import io.floci.aws.services.docdb.DocDbService; import io.floci.aws.services.docdb.container.DocDbContainerManager; import io.floci.aws.services.dynamodb.DynamoDbRuntime; import io.floci.aws.services.ec2.Ec2MetadataServer; @@ -134,6 +135,8 @@ class EmulatorLifecycleTest { @Mock private OpenSearchService openSearchService; @Mock private EmulatorConfig.OpenSearchServiceConfig openSearchServiceConfig; @Mock private MwaaService mwaaService; + @Mock private DocDbService docDbService; + @Mock private EmulatorConfig.DocDbServiceConfig docDbServiceConfig; @Mock private EmulatorConfig.MwaaServiceConfig mwaaServiceConfig; @Mock private EmulatorConfig.AmazonMqServiceConfig amazonMqServiceConfig; @Mock private EmulatorConfig.SageMakerServiceConfig sageMakerServiceConfig; @@ -191,6 +194,8 @@ class EmulatorLifecycleTest { Mockito.lenient().when(openSearchServiceConfig.enabled()).thenReturn(false); Mockito.lenient().when(servicesConfig.mwaa()).thenReturn(mwaaServiceConfig); Mockito.lenient().when(mwaaServiceConfig.enabled()).thenReturn(false); + Mockito.lenient().when(servicesConfig.docdb()).thenReturn(docDbServiceConfig); + Mockito.lenient().when(docDbServiceConfig.enabled()).thenReturn(false); Mockito.lenient().when(servicesConfig.amazonmq()).thenReturn(amazonMqServiceConfig); Mockito.lenient().when(amazonMqServiceConfig.enabled()).thenReturn(false); Mockito.lenient().when(servicesConfig.sagemaker()).thenReturn(sageMakerServiceConfig); @@ -209,7 +214,7 @@ class EmulatorLifecycleTest { elastiCacheContainerManager, elastiCacheMemcachedContainerManager, elastiCacheProxyManager, rdsContainerManager, rdsProxyManager, memoryDbContainerManager, memoryDbProxyManager, memoryDbService, - docDbContainerManager, neptuneContainerManager, neptuneProxyManager, + docDbContainerManager, docDbService, neptuneContainerManager, neptuneProxyManager, rabbitMqManager, amazonMqService, flinkContainerManager, kinesisAnalyticsService, openSearchService, mwaaService, sageMakerService, rdsService, timestreamInfluxDbService, @@ -656,6 +661,48 @@ class EmulatorLifecycleTest { verify(initLifecycleState).markReadyCompleted(); } + @Test + void restoresPersistedDocDbClustersAfterStorageLoad() { + stubStorageConfig(); + when(docDbServiceConfig.enabled()).thenReturn(true); + when(docDbService.restorePersistedRuntime()).thenReturn(CompletableFuture.completedFuture(null)); + when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false); + when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false); + + emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class)); + + InOrder inOrder = Mockito.inOrder(storageFactory, docDbService); + inOrder.verify(storageFactory).loadAll(); + inOrder.verify(docDbService).restorePersistedRuntime(); + } + + @Test + void aFailedDocDbRestoreDoesNotStopTheOtherRestores() { + stubStorageConfig(); + when(docDbServiceConfig.enabled()).thenReturn(true); + when(elbv2ServiceConfig.enabled()).thenReturn(true); + when(docDbService.restorePersistedRuntime()).thenReturn(CompletableFuture.failedFuture( + new IllegalStateException("Could not restore DocumentDB cluster demo"))); + when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false); + when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false); + + emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class)); + + verify(elbV2Service).restorePersistedRuntime(); + verify(initLifecycleState).markReadyCompleted(); + } + + @Test + void leavesDocDbClustersUntouchedWhenDocDbIsDisabled() { + stubStorageConfig(); + when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false); + when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false); + + emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class)); + + verify(docDbService, never()).restorePersistedRuntime(); + } + @Test void leavesMwaaEnvironmentsUntouchedWhenMwaaIsDisabled() { stubStorageConfig(); diff --git a/src/test/java/io/floci/aws/services/docdb/DocDbClusterRestartDockerNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/docdb/DocDbClusterRestartDockerNightlyIntegrationTest.java new file mode 100644 index 0000000000..ddccc18677 --- /dev/null +++ b/src/test/java/io/floci/aws/services/docdb/DocDbClusterRestartDockerNightlyIntegrationTest.java @@ -0,0 +1,189 @@ +package io.floci.aws.services.docdb; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.github.dockerjava.api.DockerClient; +import io.floci.aws.core.common.RequestScopes; +import io.floci.aws.core.common.docker.ContainerExec; +import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.services.docdb.container.DocDbContainerHandle; +import io.floci.aws.services.docdb.container.DocDbContainerManager; +import io.floci.aws.services.docdb.model.DocDbCluster; +import io.floci.aws.services.docdb.model.DocDbInstance; +import io.floci.aws.testing.DockerAvailability; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; + +import java.time.Duration; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import static io.restassured.RestAssured.given; +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * #5664: a DocumentDB cluster comes back after Floci restarts with the data it held. Shutdown removes each cluster's + * MongoDB container and keeps its volume; the startup restore starts a new container on it with the master password + * the data was set up with, so a document written before reads back, and a snapshot, which authenticates with that + * password, still works. Stopping the containers, as shutdown does, stands in for the shutdown, reloading the records + * from disk for what a restart reads back, and the restore is what startup calls. One cluster is in another account + * and Region, so the restore is seen starting each in its own. + * + *

A Docker end-to-end check: it runs real MongoDB containers with the cluster records on disk, which the shared + * test configuration keeps in memory. + */ +@QuarkusTest +@TestProfile(DocDbClusterRestartDockerNightlyIntegrationTest.Profile.class) +@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true") +@Timeout(value = 10, unit = TimeUnit.MINUTES) +class DocDbClusterRestartDockerNightlyIntegrationTest { + + /** Real MongoDB containers, the cluster records on disk, and volumes removed with their clusters. */ + public static final class Profile implements QuarkusTestProfile { + private static final String DATA = "./target/test-data/docdb-restart-" + UUID.randomUUID(); + + @Override + public Map getConfigOverrides() { + return Map.of("floci.services.docdb.mock", "false", + "floci.storage.mode", "persistent", + "floci.storage.persistent-path", DATA, + "floci.storage.prune-volumes-on-delete", "true"); + } + } + + private static final String FORM = "application/x-www-form-urlencoded"; + private static final String OTHER_ACCOUNT = "111111111111"; + private static final String OTHER_REGION = "eu-west-1"; + private static final String USERNAME = "docdbadmin"; + private static final String PASSWORD = "restart99password"; + + @Inject + DockerClient dockerClient; + + @Inject + DocDbService docDbService; + + @Inject + DocDbContainerManager containerManager; + + @Inject + StorageFactory storageFactory; + + @BeforeEach + void requireDocker() { + Assumptions.assumeTrue(DockerAvailability.answers(dockerClient), + "Docker daemon must be available for the DocumentDB restart check"); + } + + @Test + void aClusterKeepsItsDataAcrossARestart() { + String id = "restart-" + UUID.randomUUID().toString().substring(0, 8); + String instanceId = id + "-1"; + String defaultAuth = auth("000000000000", "us-east-1"); + String otherAuth = auth(OTHER_ACCOUNT, OTHER_REGION); + try { + call(defaultAuth, "CreateDBCluster", Map.of("DBClusterIdentifier", id, "Engine", "docdb", + "MasterUsername", USERNAME, "MasterUserPassword", PASSWORD)); + call(defaultAuth, "CreateDBInstance", Map.of("DBInstanceIdentifier", instanceId, + "DBClusterIdentifier", id, "DBInstanceClass", "db.r5.large", "Engine", "docdb")); + call(otherAuth, "CreateDBCluster", Map.of("DBClusterIdentifier", id, "Engine", "docdb", + "MasterUsername", USERNAME, "MasterUserPassword", PASSWORD)); + DocDbCluster before = docDbService.getDbCluster(id, "us-east-1"); + DocDbCluster otherBefore = otherCluster(id); + write(before.getContainerId(), "here"); + write(otherBefore.getContainerId(), "elsewhere"); + + for (DocDbCluster cluster : new DocDbCluster[] {before, otherBefore}) { + containerManager.stop(new DocDbContainerHandle(cluster.getContainerId(), id, + cluster.getContainerHost(), cluster.getContainerPort())); + } + storageFactory.create("docdb", "docdb-clusters.json", + new TypeReference>() {}).load(); + storageFactory.create("docdb", "docdb-instances.json", + new TypeReference>() {}).load(); + assertNotSame(before, docDbService.getDbCluster(id, "us-east-1")); + docDbService.restorePersistedRuntime().join(); + + DocDbCluster after = docDbService.getDbCluster(id, "us-east-1"); + assertEquals("available", after.getStatus()); + assertNotEquals(before.getContainerId(), after.getContainerId()); + assertEquals("here", read(after.getContainerId())); + DocDbInstance instance = docDbService.getDbInstance(instanceId, "us-east-1"); + assertEquals("available", instance.getStatus()); + assertEquals(after.getPort(), instance.getPort()); + DocDbCluster otherAfter = otherCluster(id); + assertEquals("available", otherAfter.getStatus()); + assertNotEquals(otherBefore.getContainerId(), otherAfter.getContainerId()); + assertEquals("elsewhere", read(otherAfter.getContainerId())); + + String snapshot = call(defaultAuth, "CreateDBClusterSnapshot", + Map.of("DBClusterSnapshotIdentifier", id + "-snap", "DBClusterIdentifier", id)); + assertTrue(snapshot.contains("available"), snapshot); + } finally { + given().header("Authorization", defaultAuth).contentType(FORM) + .formParam("Action", "DeleteDBClusterSnapshot") + .formParam("DBClusterSnapshotIdentifier", id + "-snap").when().post("/"); + given().header("Authorization", defaultAuth).contentType(FORM) + .formParam("Action", "DeleteDBInstance").formParam("DBInstanceIdentifier", instanceId) + .when().post("/"); + for (String auth : new String[] {defaultAuth, otherAuth}) { + given().header("Authorization", auth).contentType(FORM) + .formParam("Action", "DeleteDBCluster").formParam("DBClusterIdentifier", id) + .formParam("SkipFinalSnapshot", "true").when().post("/"); + } + } + } + + private DocDbCluster otherCluster(String id) { + return RequestScopes.callAs(OTHER_ACCOUNT, OTHER_REGION, () -> docDbService.getDbCluster(id, OTHER_REGION)); + } + + /** Writes a document holding {@code value} into the cluster, through mongosh inside its container. */ + private void write(String containerId, String value) { + await("document written").atMost(Duration.ofMinutes(1)).pollInterval(Duration.ofSeconds(2)) + .until(() -> mongosh(containerId, + "db.getSiblingDB('app').items.insertOne({_id: 'kept', value: '" + value + "'})") + .exitCode() == 0); + } + + /** + * The value of the document {@link #write} wrote, read back from the cluster once its server accepts + * connections, which can be a moment after its published port does. + */ + private String read(String containerId) { + return await("document read").atMost(Duration.ofMinutes(1)).pollInterval(Duration.ofSeconds(2)) + .until(() -> mongosh(containerId, + "print(db.getSiblingDB('app').items.findOne({_id: 'kept'}).value)"), + result -> result.exitCode() == 0) + .stdout().trim(); + } + + private ContainerExec.Result mongosh(String containerId, String script) { + return ContainerExec.run(dockerClient, containerId, new String[] {"mongosh", "--quiet", + "--username", USERNAME, "--password", PASSWORD, "--authenticationDatabase", "admin", + "--eval", script}, 60); + } + + private static String call(String auth, String action, Map params) { + return given().header("Authorization", auth).contentType(FORM).formParam("Action", action) + .formParams(params) + .when().post("/") + .then().statusCode(200).extract().asString(); + } + + private static String auth(String account, String region) { + return "AWS4-HMAC-SHA256 Credential=" + account + "/20260615/" + region + "/docdb/aws4_request, " + + "SignedHeaders=content-type;host, Signature=test"; + } +} diff --git a/src/test/java/io/floci/aws/services/docdb/DocDbRestartTest.java b/src/test/java/io/floci/aws/services/docdb/DocDbRestartTest.java new file mode 100644 index 0000000000..6d93aab715 --- /dev/null +++ b/src/test/java/io/floci/aws/services/docdb/DocDbRestartTest.java @@ -0,0 +1,621 @@ +package io.floci.aws.services.docdb; + +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.core.storage.InMemoryStorage; +import io.floci.aws.core.storage.StorageBackend; +import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.services.docdb.container.DocDbContainerHandle; +import io.floci.aws.services.docdb.container.DocDbContainerManager; +import io.floci.aws.services.docdb.model.DocDbCluster; +import io.floci.aws.services.docdb.model.DocDbInstance; +import io.floci.aws.services.ec2.Ec2Service; +import io.floci.aws.services.kms.KmsService; +import io.floci.aws.services.rds.RdsService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.time.Duration; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** #5664: a DocumentDB cluster's container comes back when Floci restarts, on its volume and with its password. */ +class DocDbRestartTest { + + private static final String DEFAULT_ACCOUNT = "000000000000"; + + private final AtomicInteger started = new AtomicInteger(); + /** The Region requests are signed for, which a test switches to create a cluster elsewhere. */ + private volatile String requestRegion = "us-east-1"; + /** Fails every write of an available instance, once set. */ + private final AtomicBoolean refuseAvailableInstances = new AtomicBoolean(); + /** Runs once, inside the next read of instance {@code c-1}. */ + private volatile Runnable onInstanceRead; + /** The cluster whose marking for the restore the cluster store refuses to write. */ + private volatile String refuseMarking; + private final AtomicBoolean shuttingDown = new AtomicBoolean(); + private RegionResolver regionResolver; + private EmulatorConfig.DocDbServiceConfig docdbConfig; + private DocDbContainerManager containers; + private StorageBackend clusterStore; + private DocDbService service; + + @BeforeEach + void setUp() { + StorageFactory storageFactory = mock(StorageFactory.class); + when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv -> { + StorageBackend store = AccountAwareStorageBackend.inMemory(DEFAULT_ACCOUNT); + if ("docdb-clusters.json".equals(inv.getArgument(1))) { + AccountAwareStorageBackend clustersStore = + new AccountAwareStorageBackend<>(new ClusterStore(), null, DEFAULT_ACCOUNT); + clusterStore = clustersStore; + return clustersStore; + } + if ("docdb-instances.json".equals(inv.getArgument(1))) { + return new AccountAwareStorageBackend<>(new InstanceStore(), null, DEFAULT_ACCOUNT); + } + return store; + }); + EmulatorConfig config = mock(EmulatorConfig.class); + EmulatorConfig.ServicesConfig servicesConfig = mock(EmulatorConfig.ServicesConfig.class); + docdbConfig = mock(EmulatorConfig.DocDbServiceConfig.class); + EmulatorConfig.StorageConfig storageConfig = mock(EmulatorConfig.StorageConfig.class); + when(config.services()).thenReturn(servicesConfig); + when(servicesConfig.docdb()).thenReturn(docdbConfig); + when(docdbConfig.mock()).thenReturn(false); + when(docdbConfig.defaultImage()).thenReturn("mongo:7.0"); + when(config.hostname()).thenReturn(Optional.of("localhost")); + when(config.storage()).thenReturn(storageConfig); + when(storageConfig.mode()).thenReturn("persistent"); + + regionResolver = spy(new RegionResolver("us-east-1", DEFAULT_ACCOUNT)); + doAnswer(inv -> requestRegion).when(regionResolver).getRegion(); + containers = mock(DocDbContainerManager.class); + startsContainers(); + when(containers.isShuttingDown()).thenAnswer(inv -> shuttingDown.get()); + RdsService rdsService = mock(RdsService.class); + when(rdsService.isManagedClusterParameterGroup(any())).thenReturn(true); + Ec2Service ec2Service = mock(Ec2Service.class); + when(ec2Service.resolveDefaultSecurityGroupId(anyString())) + .thenAnswer(inv -> Ec2Service.defaultSecurityGroupId(inv.getArgument(0), DEFAULT_ACCOUNT)); + service = new DocDbService(config, regionResolver, containers, storageFactory, rdsService, ec2Service, + mock(KmsService.class)); + } + + @Test + void eachClustersContainerStartsAgainOnItsVolumeWithItsPassword() { + DocDbCluster orders = service.createDbCluster("orders", null, "admin", "secret-a", false); + service.createDbInstance("orders-1", "orders", null, null, false); + String before = orders.getContainerId(); + int portBefore = orders.getPort(); + requestRegion = "eu-west-1"; + DocDbCluster other = service.createDbCluster("orders", null, "owner", "secret-b", false); + requestRegion = "us-east-1"; + String otherBefore = other.getContainerId(); + assertEquals("secret-a", orders.getMasterPassword()); + clearInvocations(containers); + + service.restorePersistedRuntime().join(); + + verify(containers).tryStart("orders", "mongo:7.0", "admin", "secret-a", "us-east-1", orders.getVolumeId()); + verify(containers).tryStart("orders", "mongo:7.0", "owner", "secret-b", "eu-west-1", other.getVolumeId()); + DocDbCluster restored = service.getDbCluster("orders"); + assertEquals("available", restored.getStatus()); + assertNotEquals(before, restored.getContainerId()); + assertNotEquals(portBefore, restored.getPort()); + DocDbInstance instance = service.getDbInstance("orders-1"); + assertEquals("available", instance.getStatus()); + assertEquals(restored.getPort(), instance.getPort()); + DocDbCluster restoredOther = service.getDbCluster("orders", "eu-west-1"); + assertEquals("available", restoredOther.getStatus()); + assertNotEquals(otherBefore, restoredOther.getContainerId()); + assertNotEquals(restored.getContainerId(), restoredOther.getContainerId()); + } + + @Test + void aClusterIsInMaintenanceAndItsInstancesStartingWhileItsContainerComesBack() throws Exception { + service.createDbCluster("c", null, "admin", "secret", false); + service.createDbInstance("c-1", "c", null, null, false); + CountDownLatch starting = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + blockStarts(starting, release); + + CompletableFuture restore = service.restorePersistedRuntime(); + assertEquals("maintenance", service.getDbCluster("c").getStatus()); + assertEquals("starting", service.getDbInstance("c-1").getStatus()); + assertTrue(starting.await(10, TimeUnit.SECONDS)); + assertEquals("maintenance", service.getDbCluster("c").getStatus()); + release.countDown(); + restore.join(); + + assertEquals("available", service.getDbCluster("c").getStatus()); + assertEquals("available", service.getDbInstance("c-1").getStatus()); + } + + @Test + void withNoDockerDaemonAClusterComesBackWithoutAContainer() { + service.createDbCluster("c", null, "admin", "secret", false); + service.createDbInstance("c-1", "c", null, null, false); + doReturn(null).when(containers).tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), any()); + + service.restorePersistedRuntime().join(); + + DocDbCluster cluster = service.getDbCluster("c"); + assertEquals("available", cluster.getStatus()); + assertNull(cluster.getContainerId()); + assertEquals("localhost", cluster.getEndpoint()); + assertEquals(27017, cluster.getPort()); + assertEquals("available", service.getDbInstance("c-1").getStatus()); + assertEquals(27017, service.getDbInstance("c-1").getPort()); + } + + @Test + void aClusterWhoseContainerDoesNotStartIsLeftWithoutOneAndTriedAgainAtTheNextStart() { + service.createDbCluster("bad", null, "admin", "secret", false); + service.createDbInstance("bad-1", "bad", null, null, false); + service.createDbCluster("good", null, "admin", "secret", false); + doThrow(new IllegalStateException("no such image: mongo:7.0")) + .when(containers).tryStart(eq("bad"), anyString(), anyString(), anyString(), anyString(), any()); + + CompletionException failure = assertThrows(CompletionException.class, + () -> service.restorePersistedRuntime().join()); + + assertTrue(failure.getCause().getMessage().contains("bad"), failure.getCause().getMessage()); + assertEquals("available", service.getDbCluster("good").getStatus()); + DocDbCluster bad = service.getDbCluster("bad"); + assertEquals("available", bad.getStatus()); + assertNull(bad.getContainerId()); + assertEquals("failed", service.getDbInstance("bad-1").getStatus()); + + startsContainers(); + service.restorePersistedRuntime().join(); + assertNotNull(service.getDbCluster("bad").getContainerId()); + assertEquals("available", service.getDbInstance("bad-1").getStatus()); + } + + @Test + void aClusterRecordedBeforeThePasswordWasKeptReadsItFromTheContainerItLeft() { + DocDbCluster cluster = service.createDbCluster("c", null, "admin", "secret", false); + String leftBehind = cluster.getContainerId(); + cluster.setMasterPassword(null); + when(containers.survivingMasterPassword(leftBehind)).thenReturn("from-its-env"); + + service.restorePersistedRuntime().join(); + + verify(containers).tryStart("c", "mongo:7.0", "admin", "from-its-env", "us-east-1", cluster.getVolumeId()); + assertEquals("from-its-env", service.getDbCluster("c").getMasterPassword()); + } + + @Test + void aPasswordReadFromTheContainerLeftBehindIsKeptEvenWhenTheStartFails() { + DocDbCluster cluster = service.createDbCluster("c", null, "admin", "secret", false); + when(containers.survivingMasterPassword(cluster.getContainerId())).thenReturn("from-its-env"); + cluster.setMasterPassword(null); + doThrow(new IllegalStateException("no such image: mongo:7.0")) + .when(containers).tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), any()); + + assertThrows(CompletionException.class, () -> service.restorePersistedRuntime().join()); + + assertEquals("from-its-env", service.getDbCluster("c").getMasterPassword()); + startsContainers(); + clearInvocations(containers); + service.restorePersistedRuntime().join(); + verify(containers).tryStart("c", "mongo:7.0", "admin", "from-its-env", "us-east-1", cluster.getVolumeId()); + } + + @Test + void aClusterWithNoPasswordToStartWithIsLeftWithoutAContainer() { + DocDbCluster cluster = service.createDbCluster("c", null, "admin", "secret", false); + service.createDbInstance("c-1", "c", null, null, false); + cluster.setMasterPassword(null); + clearInvocations(containers); + + CompletionException failure = assertThrows(CompletionException.class, + () -> service.restorePersistedRuntime().join()); + + assertTrue(failure.getCause().getCause().getMessage().contains("before Floci kept master passwords"), + failure.getCause().getCause().getMessage()); + verify(containers, never()).tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), any()); + assertNull(service.getDbCluster("c").getContainerId()); + assertEquals("failed", service.getDbInstance("c-1").getStatus()); + } + + @Test + void aClusterRecordedBeforeItsDataWasKeptGetsAVolumeOfItsOwn() { + DocDbCluster cluster = service.createDbCluster("c", null, "admin", "secret", false); + cluster.setVolumeId(null); + clearInvocations(containers); + + service.restorePersistedRuntime().join(); + + ArgumentCaptor volume = ArgumentCaptor.forClass(String.class); + verify(containers).tryStart(eq("c"), anyString(), anyString(), anyString(), anyString(), volume.capture()); + assertNotNull(volume.getValue()); + assertEquals(volume.getValue(), service.getDbCluster("c").getVolumeId()); + } + + @Test + void aDeleteFlociDidNotLiveToFinishIsFinishedAtStartup() { + DocDbCluster cluster = service.createDbCluster("c", null, "admin", "secret", false); + cluster.setStatus("deleting"); + clearInvocations(containers); + + service.restorePersistedRuntime().join(); + + assertFalse(service.hasCluster("c")); + verify(containers).stop(argThat(handle -> cluster.getContainerId().equals(handle.getContainerId()))); + verify(containers).removeStorage(cluster.getVolumeId()); + verify(containers, never()).tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), any()); + } + + @Test + void aClusterDeletedDuringItsRestoreGoesOnceItsContainerHasStarted() throws Exception { + DocDbCluster cluster = service.createDbCluster("c", null, "admin", "secret", false); + CountDownLatch starting = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + blockStarts(starting, release); + + CompletableFuture restore = service.restorePersistedRuntime(); + assertTrue(starting.await(10, TimeUnit.SECONDS)); + service.deleteDbCluster("c"); + assertEquals("deleting", service.getDbCluster("c").getStatus()); + verify(containers, never()).removeStorage(any()); + release.countDown(); + restore.join(); + + assertFalse(service.hasCluster("c")); + verify(containers).stop(argThat(handle -> "container-2".equals(handle.getContainerId()))); + verify(containers).removeStorage(cluster.getVolumeId()); + } + + @Test + void aSecondDeleteDuringTheRestoreStillWaitsForTheContainer() throws Exception { + service.createDbCluster("c", null, "admin", "secret", false); + CountDownLatch starting = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + blockStarts(starting, release); + + CompletableFuture restore = service.restorePersistedRuntime(); + assertTrue(starting.await(10, TimeUnit.SECONDS)); + service.deleteDbCluster("c"); + service.deleteDbCluster("c"); + assertEquals("deleting", service.getDbCluster("c").getStatus()); + release.countDown(); + restore.join(); + + assertFalse(service.hasCluster("c")); + verify(containers).stop(argThat(handle -> "container-2".equals(handle.getContainerId()))); + } + + @Test + void noInstanceJoinsAClusterWhileItsContainerComesBackOrItWaitsToBeDeleted() throws Exception { + service.createDbCluster("c", null, "admin", "secret", false); + CountDownLatch starting = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + blockStarts(starting, release); + + CompletableFuture restore = service.restorePersistedRuntime(); + assertTrue(starting.await(10, TimeUnit.SECONDS)); + AwsException whileStarting = assertThrows(AwsException.class, + () -> service.createDbInstance("c-1", "c", null, null, false)); + service.deleteDbCluster("c"); + AwsException whileDeleting = assertThrows(AwsException.class, + () -> service.createDbInstance("c-1", "c", null, null, false)); + release.countDown(); + restore.join(); + + for (AwsException refused : List.of(whileStarting, whileDeleting)) { + assertEquals("InvalidDBClusterStateFault", refused.getErrorCode()); + assertEquals(400, refused.getHttpStatus()); + } + assertFalse(service.hasCluster("c")); + assertFalse(service.hasInstance("c-1")); + } + + @Test + void aClusterDeletedWhileItsStartFailsIsStillRemoved() throws Exception { + service.createDbCluster("c", null, "admin", "secret", false); + CountDownLatch starting = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + doAnswer(inv -> { + starting.countDown(); + assertTrue(release.await(10, TimeUnit.SECONDS)); + throw new IllegalStateException("no such image: mongo:7.0"); + }).when(containers).tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), any()); + + CompletableFuture restore = service.restorePersistedRuntime(); + assertTrue(starting.await(10, TimeUnit.SECONDS)); + service.deleteDbCluster("c"); + release.countDown(); + + assertThrows(CompletionException.class, restore::join); + assertFalse(service.hasCluster("c")); + } + + @Test + void aClusterGoneDuringItsRestoreHasTheContainerStartedForItStopped() throws Exception { + service.createDbCluster("c", null, "admin", "secret", false); + CountDownLatch starting = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + blockStarts(starting, release); + + CompletableFuture restore = service.restorePersistedRuntime(); + assertTrue(starting.await(10, TimeUnit.SECONDS)); + clusterStore.delete("us-east-1::c"); + release.countDown(); + restore.join(); + + assertFalse(service.hasCluster("c")); + verify(containers).stop(argThat(handle -> "container-2".equals(handle.getContainerId()))); + } + + @Test + void aClusterReplacedDuringItsRestoreKeepsItsOwnRecord() throws Exception { + service.createDbCluster("c", null, "admin", "secret", false); + CountDownLatch starting = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + blockStarts(starting, release); + + CompletableFuture restore = service.restorePersistedRuntime(); + assertTrue(starting.await(10, TimeUnit.SECONDS)); + DocDbCluster replacement = new DocDbCluster(); + replacement.setDbClusterIdentifier("c"); + replacement.setDbClusterResourceId("cluster-REPLACEMENT"); + replacement.setStatus("available"); + replacement.setContainerId("replacement-container"); + replacement.setMasterPassword("its-own"); + clusterStore.put("us-east-1::c", replacement); + release.countDown(); + restore.join(); + + DocDbCluster stored = service.getDbCluster("c"); + assertEquals("replacement-container", stored.getContainerId()); + assertEquals("its-own", stored.getMasterPassword()); + verify(containers).stop(argThat(handle -> "container-2".equals(handle.getContainerId()))); + } + + @Test + void aVolumeGivenAtTheRestoreIsKeptEvenWhenTheStartFails() { + DocDbCluster cluster = service.createDbCluster("c", null, "admin", "secret", false); + cluster.setVolumeId(null); + doThrow(new IllegalStateException("no such image: mongo:7.0")) + .when(containers).tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), any()); + clearInvocations(containers); + + assertThrows(CompletionException.class, () -> service.restorePersistedRuntime().join()); + + String given = service.getDbCluster("c").getVolumeId(); + assertNotNull(given); + verify(containers).tryStart(eq("c"), anyString(), anyString(), anyString(), anyString(), eq(given)); + startsContainers(); + service.restorePersistedRuntime().join(); + assertEquals(given, service.getDbCluster("c").getVolumeId()); + } + + @Test + void aClusterThatCannotBeMarkedIsReportedWithoutStoppingStartupOrTheOthers() { + service.createDbCluster("broken", null, "admin", "secret", false); + service.createDbCluster("good", null, "admin", "secret", false); + refuseMarking = "broken"; + clearInvocations(containers); + + CompletableFuture restore = service.restorePersistedRuntime(); + CompletionException failure = assertThrows(CompletionException.class, restore::join); + + assertTrue(failure.getCause().getMessage().contains("broken"), failure.getCause().getMessage()); + assertEquals("available", service.getDbCluster("good").getStatus()); + verify(containers).tryStart(eq("good"), anyString(), anyString(), anyString(), anyString(), any()); + verify(containers, never()).tryStart(eq("broken"), anyString(), anyString(), anyString(), anyString(), any()); + } + + @Test + void finishingALeftoverDeleteDoesNotHoldUpStartup() { + service.createDbCluster("gone", null, "admin", "secret", false).setStatus("deleting"); + CountDownLatch release = new CountDownLatch(1); + doAnswer(inv -> { + assertTrue(release.await(10, TimeUnit.SECONDS)); + return null; + }).when(containers).stop(any()); + + CompletableFuture restore = assertTimeoutPreemptively(Duration.ofSeconds(5), + () -> service.restorePersistedRuntime()); + release.countDown(); + restore.join(); + + assertFalse(service.hasCluster("gone")); + } + + @Test + void aShutdownDuringTheRestoreLeavesTheClustersForTheNextStart() { + service.createDbCluster("first", null, "admin", "secret", false); + service.createDbInstance("first-1", "first", null, null, false); + service.createDbCluster("second", null, "admin", "secret", false); + service.createDbInstance("second-1", "second", null, null, false); + clearInvocations(containers); + doAnswer(inv -> { + shuttingDown.set(true); + throw new IllegalStateException("DocumentDB is shutting down"); + }).when(containers).tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), any()); + + service.restorePersistedRuntime().join(); + + verify(containers, times(1)).tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), any()); + for (String id : List.of("first", "second")) { + assertEquals("maintenance", service.getDbCluster(id).getStatus()); + assertEquals("starting", service.getDbInstance(id + "-1").getStatus()); + } + } + + @Test + void aRestoreThatFailsOnceItsContainerHasStartedStopsThatContainer() { + service.createDbCluster("c", null, "admin", "secret", false); + service.createDbInstance("c-1", "c", null, null, false); + refuseAvailableInstances.set(true); + + assertThrows(CompletionException.class, () -> service.restorePersistedRuntime().join()); + + verify(containers).stop(argThat(handle -> "container-2".equals(handle.getContainerId()))); + assertNull(service.getDbCluster("c").getContainerId()); + assertEquals("failed", service.getDbInstance("c-1").getStatus()); + } + + @Test + void anInstanceMovedToAnotherClusterDuringTheRestoreKeepsThatClustersEndpoint() throws Exception { + service.createDbCluster("c", null, "admin", "secret", false); + service.createDbInstance("c-1", "c", null, null, false); + CountDownLatch starting = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + blockStarts(starting, release); + doReturn(new DocDbContainerHandle("container-d", "d", "localhost", 49999)) + .when(containers).tryStart(eq("d"), anyString(), anyString(), anyString(), anyString(), any()); + + CompletableFuture restore = service.restorePersistedRuntime(); + assertTrue(starting.await(10, TimeUnit.SECONDS)); + service.createDbCluster("d", null, "admin", "secret", false); + onInstanceRead = () -> { + service.deleteDbInstance("c-1"); + service.createDbInstance("c-1", "d", null, null, false); + }; + release.countDown(); + restore.join(); + + DocDbInstance moved = service.getDbInstance("c-1"); + assertEquals("d", moved.getDbClusterIdentifier()); + assertEquals(49999, moved.getPort()); + assertEquals("available", moved.getStatus()); + } + + @Test + void aDeleteAfterAFailedRestoreRemovesTheClusterAtOnce() { + service.createDbCluster("c", null, "admin", "secret", false); + doThrow(new IllegalStateException("no such image: mongo:7.0")) + .when(containers).tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), any()); + assertThrows(CompletionException.class, () -> service.restorePersistedRuntime().join()); + + service.deleteDbCluster("c"); + + assertFalse(service.hasCluster("c")); + } + + @Test + void aDeleteAfterTheRestoreRemovesTheClusterAtOnce() { + service.createDbCluster("c", null, "admin", "secret", false); + service.restorePersistedRuntime().join(); + + service.deleteDbCluster("c"); + + assertFalse(service.hasCluster("c")); + } + + @Test + void mockClustersAreLeftAsTheyAre() { + when(docdbConfig.mock()).thenReturn(true); + DocDbCluster cluster = service.createDbCluster("c", null, "admin", "secret", false); + clearInvocations(containers); + + service.restorePersistedRuntime().join(); + + assertNull(cluster.getMasterPassword()); + assertEquals("available", service.getDbCluster("c").getStatus()); + verify(containers, never()).tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), any()); + } + + @Test + void aDeleteThatCannotFinishAtStartupIsReportedWithoutStoppingTheOthers() { + DocDbCluster gone = service.createDbCluster("gone", null, "admin", "secret", false); + gone.setStatus("deleting"); + service.createDbCluster("good", null, "admin", "secret", false); + doThrow(new IllegalStateException("Docker refused")).when(containers).stop(any()); + clearInvocations(containers); + + CompletionException failure = assertThrows(CompletionException.class, + () -> service.restorePersistedRuntime().join()); + + assertTrue(failure.getCause().getMessage().contains("gone"), failure.getCause().getMessage()); + assertEquals("available", service.getDbCluster("good").getStatus()); + verify(containers).tryStart(eq("good"), anyString(), anyString(), anyString(), anyString(), any()); + assertEquals("deleting", service.getDbCluster("gone").getStatus()); + } + + /** Each start gives a container of its own, numbered in start order, its port after it. */ + private void startsContainers() { + doAnswer(inv -> { + int n = started.incrementAndGet(); + return new DocDbContainerHandle("container-" + n, inv.getArgument(0), "localhost", 40000 + n); + }).when(containers).tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), any()); + } + + /** Starts that signal {@code starting} and wait for {@code release} before giving their container. */ + private void blockStarts(CountDownLatch starting, CountDownLatch release) { + doAnswer(inv -> { + starting.countDown(); + assertTrue(release.await(10, TimeUnit.SECONDS)); + int n = started.incrementAndGet(); + return new DocDbContainerHandle("container-" + n, inv.getArgument(0), "localhost", 40000 + n); + }).when(containers).tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), any()); + } + + /** The cluster store, which a test can have refuse to mark a cluster for the restore. */ + private final class ClusterStore extends InMemoryStorage { + @Override + public synchronized void put(String key, DocDbCluster value) { + if ("maintenance".equals(value.getStatus()) && value.getDbClusterIdentifier().equals(refuseMarking)) { + throw new IllegalStateException("the cluster store refused the write"); + } + super.put(key, value); + } + } + + /** The instance store, which a test can refuse writes to or act inside a read of. */ + private final class InstanceStore extends InMemoryStorage { + @Override + public synchronized void put(String key, DocDbInstance value) { + if (refuseAvailableInstances.get() && "available".equals(value.getStatus())) { + throw new IllegalStateException("the instance store refused the write"); + } + super.put(key, value); + } + + @Override + public Optional get(String key) { + Runnable hook = onInstanceRead; + if (hook != null && key.endsWith("::c-1")) { + onInstanceRead = null; + hook.run(); + } + return super.get(key); + } + } +} diff --git a/src/test/java/io/floci/aws/services/docdb/container/DocDbContainerManagerTest.java b/src/test/java/io/floci/aws/services/docdb/container/DocDbContainerManagerTest.java index e028b3b1b6..ce78fbaa3f 100644 --- a/src/test/java/io/floci/aws/services/docdb/container/DocDbContainerManagerTest.java +++ b/src/test/java/io/floci/aws/services/docdb/container/DocDbContainerManagerTest.java @@ -1,5 +1,10 @@ package io.floci.aws.services.docdb.container; +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.InspectContainerCmd; +import com.github.dockerjava.api.command.InspectContainerResponse; +import com.github.dockerjava.api.exception.NotFoundException; +import com.github.dockerjava.api.model.ContainerConfig; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.docker.ContainerBuilder; @@ -25,6 +30,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.concurrent.atomic.AtomicReference; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -276,6 +282,64 @@ class DocDbContainerManagerTest { } } + @Test + void noContainerStartsOnceShutdownHasBegun() { + ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class); + DocDbContainerManager manager = newManager(lifecycle); + + manager.stopAll(); + + assertTrue(manager.isShuttingDown()); + assertThrows(IllegalStateException.class, + () -> manager.start("cluster1", "mongo:7.0", "admin", "secret", "us-east-1", null)); + verify(lifecycle, never()).createAndStart(any()); + } + + @Test + void aStartThatShutdownOvertakesRemovesItsContainer() throws IOException { + try (ServerSocket backend = new ServerSocket(0)) { + ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class); + AtomicReference shutDownBy = new AtomicReference<>(); + when(lifecycle.createAndStart(any())).thenAnswer(call -> { + shutDownBy.get().stopAll(); + return new ContainerLifecycleManager.ContainerInfo("container-id", Map.of(27017, + new ContainerLifecycleManager.EndpointInfo("127.0.0.1", backend.getLocalPort()))); + }); + DocDbContainerManager manager = newManager(lifecycle); + shutDownBy.set(manager); + + assertThrows(IllegalStateException.class, + () -> manager.start("cluster1", "mongo:7.0", "admin", "secret", "us-east-1", null)); + + verify(lifecycle).stopAndRemove(eq("container-id"), any()); + manager.stopAll(); + verify(lifecycle, times(1)).stopAndRemove(anyString(), any()); + } + } + + @Test + void aSurvivingContainersPasswordIsReadFromItsEnvironment() { + ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class); + DockerClient docker = mock(DockerClient.class); + when(lifecycle.getDockerClient()).thenReturn(docker); + InspectContainerCmd left = mock(InspectContainerCmd.class); + InspectContainerResponse response = mock(InspectContainerResponse.class); + ContainerConfig containerConfig = mock(ContainerConfig.class); + when(docker.inspectContainerCmd("left")).thenReturn(left); + when(left.exec()).thenReturn(response); + when(response.getConfig()).thenReturn(containerConfig); + when(containerConfig.getEnv()).thenReturn(new String[] { + "MONGO_INITDB_ROOT_USERNAME=admin", "MONGO_INITDB_ROOT_PASSWORD=kept"}); + InspectContainerCmd gone = mock(InspectContainerCmd.class); + when(docker.inspectContainerCmd("gone")).thenReturn(gone); + when(gone.exec()).thenThrow(new NotFoundException("No such container: gone")); + DocDbContainerManager manager = newManager(lifecycle); + + assertEquals("kept", manager.survivingMasterPassword("left")); + assertNull(manager.survivingMasterPassword("gone")); + assertNull(manager.survivingMasterPassword(null)); + } + @Test void removingStorageDropsTheVolumeWhenVolumesArePrunedOnDelete() { ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);