From 4792c97902660c98f437e846a0d8fa24c816e2f7 Mon Sep 17 00:00:00 2001
From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com>
Date: Thu, 26 Nov 2026 01:01:13 -0400
Subject: [PATCH] fix(docdb): start clusters' containers again when Floci
restarts (#9498)
Floci's shutdown removed every DocumentDB cluster's MongoDB container
and nothing started them again, so after a restart with persistent
storage a cluster reported available with nothing behind its endpoint.
At startup each cluster now reports maintenance, and its instances
starting, and its container comes back in the background on the volume
the cluster's data is kept in, with the master password the data was
set up with. Floci now keeps that password in the cluster's record,
never returned by the API, since a snapshot authenticates with it. 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. The restore runs in each
cluster's own account and Region.
A cluster recorded before Floci kept the master password reads it from
the container it left, if one is there, and keeps it in its record
before that container is replaced; with none left it cannot be started,
and the restore says to create it again. One recorded before
its data was kept in a volume gets a new volume, kept in its record
before any Docker call.
Marking the clusters calls no Docker; the containers, and the removal
of a delete Floci did not live to finish, are all in the background.
A DeleteDBCluster during the restore leaves the cluster deleting until
its container has started, a second one too, and the restore removes it
then; one still deleting at the next start is removed then. The restore
applies its result only to the cluster it marked. CreateDBInstance is
refused with InvalidDBClusterStateFault for a cluster that is not
available, as RDS refuses it, so a deferred delete leaves no instance
behind. Shutdown now marks the
container manager first, after which no container starts, and a start
it overtakes removes its container.
Part of #5664.
---
.github/ci/prefetch-images.sh | 2 +
docs/services/docdb.md | 18 +
.../aws/lifecycle/EmulatorLifecycle.java | 11 +
.../aws/services/docdb/DocDbService.java | 302 +++++++++
.../container/DocDbContainerManager.java | 35 +-
.../services/docdb/model/DocDbCluster.java | 8 +
.../aws/lifecycle/EmulatorLifecycleTest.java | 49 +-
...erRestartDockerNightlyIntegrationTest.java | 189 ++++++
.../aws/services/docdb/DocDbRestartTest.java | 621 ++++++++++++++++++
.../container/DocDbContainerManagerTest.java | 64 ++
10 files changed, 1297 insertions(+), 2 deletions(-)
create mode 100644 src/test/java/io/floci/aws/services/docdb/DocDbClusterRestartDockerNightlyIntegrationTest.java
create mode 100644 src/test/java/io/floci/aws/services/docdb/DocDbRestartTest.java
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