fix(docdb): keep each cluster's data in a Docker volume of its own (#9491)

A DocumentDB cluster's MongoDB container kept its data in the unnamed
volume the mongo image declares for /data/db. Removing the container, as
Floci's shutdown does, left that volume behind with nothing to find it
by, so a cluster could never be started again on its data.

With a persistent storage mode (persistent, hybrid or wal), a new
cluster now gets a volume ID, kept in its record, and its container
mounts floci-aws-docdb-<volume-id> at /data/db, or binds
<host-path>/docdb/<volume-id> when the host persistent path is an
absolute path. Memory mode and mock mode are unchanged.

DeleteDBCluster removes the volume as the storage policy says: a
persistent mode keeps it unless prune-volumes-on-delete is set. A
cluster whose create fails, or that a failed snapshot or point-in-time
restore discards, never reached the caller, so its volume goes whatever
the policy. A container that started but whose MongoDB never answered
is removed too, so it holds no volume. A cluster created again under a
deleted one's identifier starts on a new, empty volume.

Starting the clusters' containers again on these volumes when Floci
restarts comes next.

Part of #5664.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-25 23:00:18 -04:00
1 parent 6196543370
commit 733895a953
7 files changed
+389 -54

No files matched your search

+13
View File
@@ -62,6 +62,19 @@ is refused with `Cannot find version X for docdb`, on create and on modify.
Mock mode is useful for control-plane tests that do not need a live database; the cluster reports `localhost:27017` and no container is started.
### Cluster data
With `FLOCI_STORAGE_MODE` set to `persistent`, `hybrid` or `wal`, each cluster keeps its MongoDB
data in a Docker volume of its own, `floci-aws-docdb-<volume-id>` (`floci-aws-<namespace>-docdb-<volume-id>`
when `FLOCI_DOCKER_RESOURCE_NAMESPACE` is set), so the data outlives the cluster's container. When
`FLOCI_STORAGE_HOST_PERSISTENT_PATH` is an absolute path, the data goes in
`<host-path>/[<namespace>/]docdb/<volume-id>` on the Docker host instead. Deleting the cluster keeps
its volume, for you to remove with `docker volume rm`, unless
`FLOCI_STORAGE_PRUNE_VOLUMES_ON_DELETE=true`; a directory under the host path is always kept. A
create or restore that fails leaves no volume behind. A cluster created again under a deleted one's
identifier starts on a new, empty volume. In `memory`
mode a cluster's data lasts only as long as its container.
### 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`.
@@ -248,11 +248,21 @@ public class DocDbService {
} else {
String image = config.services().docdb().defaultImage();
LOG.infov("Creating DocDB cluster {0}, image={1}", id, image);
if (!"memory".equals(config.storage().mode())) {
cluster.setVolumeId(UUID.randomUUID().toString());
}
// 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.
DocDbContainerHandle handle = containerManager.tryStart(id, image, masterUsername, masterPassword,
region);
DocDbContainerHandle handle;
try {
handle = containerManager.tryStart(id, image, masterUsername, masterPassword,
region, cluster.getVolumeId());
} catch (RuntimeException e) {
// The cluster is not created, so the volume made for it goes too.
containerManager.discardStorage(cluster.getVolumeId());
throw e;
}
if (handle != null) {
cluster.setEndpoint(handle.getHost());
cluster.setReaderEndpoint(handle.getHost());
@@ -614,12 +624,16 @@ public class DocDbService {
"Cannot delete DocDB cluster " + id + " — it still has DB instances.", 400);
}
removeCluster(region, cluster);
removeCluster(region, cluster, false);
}
}
/** Stops a cluster's container and removes its record; the caller holds the cluster's lock. */
private void removeCluster(String region, DocDbCluster cluster) {
/**
* Stops a cluster's container and removes its record and its data volume; the caller holds the
* cluster's lock. A deleted cluster's volume stays when the storage policy keeps volumes on
* delete; a discarded one's, which never reached the caller, goes whatever the policy.
*/
private void removeCluster(String region, DocDbCluster cluster, boolean discarded) {
String id = cluster.getDbClusterIdentifier();
cluster.setStatus("deleting");
clusters.put(key(region, id), cluster);
@@ -629,6 +643,11 @@ public class DocDbService {
cluster.getContainerId(), id,
cluster.getContainerHost(), cluster.getContainerPort()));
}
if (discarded) {
containerManager.discardStorage(cluster.getVolumeId());
} else {
containerManager.removeStorage(cluster.getVolumeId());
}
clusters.delete(key(region, id));
writeLocks.remove("cluster:" + key(region, id));
@@ -883,7 +902,7 @@ public class DocDbService {
private void discardRestoredCluster(String id) {
String region = regionResolver.getRegion();
synchronized (lockFor("cluster:" + key(region, id))) {
findCluster(region, id).ifPresent(cluster -> removeCluster(region, cluster));
findCluster(region, id).ifPresent(cluster -> removeCluster(region, cluster, true));
}
}
@@ -32,6 +32,7 @@ public class DocDbContainerManager {
private static final Logger LOG = Logger.getLogger(DocDbContainerManager.class);
private static final int MONGO_PORT = 27017;
private static final String DATA_PATH = "/data/db";
private static final int BACKEND_READY_DEADLINE_MS = 60_000;
private static final int BACKEND_READY_RETRY_MS = 200;
private static final int BACKEND_PROBE_CONNECT_MS = 2_000;
@@ -70,9 +71,9 @@ public class DocDbContainerManager {
* @return the container handle, or {@code null} when no Docker daemon is reachable
*/
public DocDbContainerHandle tryStart(String clusterId, String image, String masterUsername, String masterPassword,
String region) {
String region, String volumeId) {
try {
DocDbContainerHandle handle = start(clusterId, image, masterUsername, masterPassword, region);
DocDbContainerHandle handle = start(clusterId, image, masterUsername, masterPassword, region, volumeId);
dockerUnavailableLogged = false;
return handle;
} catch (RuntimeException e) {
@@ -98,8 +99,13 @@ public class DocDbContainerManager {
return lifecycleManager.isDockerReachable();
}
/**
* Starts the cluster's MongoDB container. With a {@code volumeId} its data directory is the
* cluster's own volume, or its directory under the host persistent path, which outlives the
* container; without one the data goes when the container does.
*/
public DocDbContainerHandle start(String clusterId, String image, String masterUsername, String masterPassword,
String region) {
String region, String volumeId) {
LOG.infov("Starting DocumentDB container for cluster: {0}", clusterId);
String accountId = regionResolver.getAccountId();
@@ -121,6 +127,17 @@ public class DocDbContainerManager {
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"docdb", clusterId, accountId, region));
if (volumeId != null) {
if (ContainerStorageHelper.isNamedVolumeMode(config)) {
ContainerStorageHelper.applyNamedVolume(specBuilder, lifecycleManager,
volumeName(volumeId), DATA_PATH);
} else {
String path = ContainerStorageHelper.hostResourcePath(config, "docdb", volumeId).toString();
ContainerStorageHelper.ensureHostDir(containerDetector, path);
specBuilder.withBind(path, DATA_PATH);
}
}
if (!containerDetector.isRunningInContainer()) {
specBuilder.withDynamicPort(MONGO_PORT);
} else {
@@ -130,28 +147,40 @@ public class DocDbContainerManager {
ContainerSpec spec = specBuilder.build();
ContainerInfo info = lifecycleManager.createAndStart(spec);
EndpointInfo endpoint = info.getEndpoint(MONGO_PORT);
DocDbContainerHandle handle = null;
try {
EndpointInfo endpoint = info.getEndpoint(MONGO_PORT);
LOG.infov("DocumentDB container for cluster {0}: {1}", clusterId, endpoint);
LOG.infov("DocumentDB container for cluster {0}: {1}", clusterId, endpoint);
DocDbContainerHandle handle = new DocDbContainerHandle(
info.containerId(), clusterId, endpoint.host(), endpoint.port());
// Docker IDs remain unique across accounts, regions, and same-named cluster replacements.
activeContainers.put(info.containerId(), handle);
handle = new DocDbContainerHandle(
info.containerId(), clusterId, endpoint.host(), endpoint.port());
// Docker IDs remain unique across accounts, regions, and same-named cluster replacements.
activeContainers.put(info.containerId(), handle);
String shortId = info.containerId().length() >= 8
? info.containerId().substring(0, 8)
: info.containerId();
String logGroup = "/aws/docdb/cluster/" + clusterId + "/audit";
String logStream = logStreamer.generateLogStreamName(shortId);
String shortId = info.containerId().length() >= 8
? info.containerId().substring(0, 8)
: info.containerId();
String logGroup = "/aws/docdb/cluster/" + clusterId + "/audit";
String logStream = logStreamer.generateLogStreamName(shortId);
Closeable logHandle = logStreamer.attachPolled(
info.containerId(), logGroup, logStream, region, "docdb:" + clusterId);
handle.setLogStream(logHandle);
Closeable logHandle = logStreamer.attachPolled(
info.containerId(), logGroup, logStream, region, "docdb:" + clusterId);
handle.setLogStream(logHandle);
waitForBackendReady(clusterId, endpoint.host(), endpoint.port());
waitForBackendReady(clusterId, endpoint.host(), endpoint.port());
return handle;
return handle;
} catch (RuntimeException e) {
// The caller gets no container, so the one started goes, and with it its hold on the volume.
activeContainers.remove(info.containerId());
try {
lifecycleManager.stopAndRemove(info.containerId(), handle != null ? handle.getLogStream() : null);
} catch (RuntimeException cleanup) {
e.addSuppressed(cleanup);
}
throw e;
}
}
public void stop(DocDbContainerHandle handle) {
@@ -163,6 +192,27 @@ public class DocDbContainerManager {
active == null ? handle.getLogStream() : active.getLogStream());
}
/**
* Removes a deleted cluster's data volume, unless the storage policy keeps volumes on delete.
* A directory under the host persistent path is left in place.
*/
public void removeStorage(String volumeId) {
if (volumeId != null && ContainerStorageHelper.isNamedVolumeMode(config)) {
ContainerStorageHelper.removeNamedVolume(config, lifecycleManager, volumeName(volumeId));
}
}
/** Removes the data volume of a cluster that never reached its caller, whatever the storage policy. */
public void discardStorage(String volumeId) {
if (volumeId != null && ContainerStorageHelper.isNamedVolumeMode(config)) {
lifecycleManager.removeVolume(volumeName(volumeId));
}
}
private String volumeName(String volumeId) {
return ContainerStorageHelper.dockerName(config, "docdb-" + volumeId);
}
public void stopAll() {
List<DocDbContainerHandle> handles = new ArrayList<>(activeContainers.values());
if (!handles.isEmpty()) {
@@ -39,6 +39,8 @@ public class DocDbCluster {
private String containerId;
private String containerHost;
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;
public DocDbCluster (){}
@@ -110,6 +112,9 @@ public class DocDbCluster {
public int getContainerPort() { return containerPort; }
public void setContainerPort(int containerPort) { this.containerPort = containerPort; }
public String getVolumeId() { return volumeId; }
public void setVolumeId(String volumeId) { this.volumeId = volumeId; }
public Map<String, String> getTags() { return tags; }
/** Normalizes null: a record persisted before tags were stored deserializes without them. */
@@ -17,12 +17,14 @@ import io.floci.aws.services.kms.model.KmsKey;
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.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
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.assertTrue;
@@ -50,6 +52,7 @@ class DocDbClusterSnapshotServiceTest {
private DocDbService docDbService;
private DocDbContainerManager containerManager;
private EmulatorConfig.DocDbServiceConfig docdbConfig;
private EmulatorConfig.StorageConfig storageConfig;
private StorageBackend<String, String> archives;
@BeforeEach
@@ -69,9 +72,12 @@ class DocDbClusterSnapshotServiceTest {
when(servicesConfig.docdb()).thenReturn(docdbConfig);
when(docdbConfig.mock()).thenReturn(false);
when(docdbConfig.defaultImage()).thenReturn("mongo:7.0");
storageConfig = mock(EmulatorConfig.StorageConfig.class);
when(config.storage()).thenReturn(storageConfig);
when(storageConfig.mode()).thenReturn("memory");
containerManager = mock(DocDbContainerManager.class);
// Every cluster gets a container named after it.
when(containerManager.tryStart(anyString(), anyString(), anyString(), anyString(), anyString()))
when(containerManager.tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), any()))
.thenAnswer(inv -> new DocDbContainerHandle("container-" + inv.getArgument(0),
inv.getArgument(0), "localhost", 27017));
when(containerManager.dumpCluster("container-source")).thenReturn(ARCHIVE);
@@ -96,7 +102,7 @@ class DocDbClusterSnapshotServiceTest {
docDbService.restoreDbClusterFromSnapshot("restored", "snap", null, DocDbClusterSettings.defaults(), Map.of());
verify(containerManager).tryStart(eq("restored"), anyString(), eq("admin"), eq("source-password"), anyString());
verify(containerManager).tryStart(eq("restored"), anyString(), eq("admin"), eq("source-password"), anyString(), any());
verify(containerManager).restoreCluster("container-restored", ARCHIVE);
}
@@ -107,7 +113,7 @@ class DocDbClusterSnapshotServiceTest {
docDbService.restoreDbClusterToPointInTime("copy", "source", DocDbClusterSettings.defaults(), Map.of());
verify(containerManager).dumpCluster("container-source");
verify(containerManager).tryStart(eq("copy"), anyString(), eq("admin"), eq("source-password"), anyString());
verify(containerManager).tryStart(eq("copy"), anyString(), eq("admin"), eq("source-password"), anyString(), any());
verify(containerManager).restoreCluster("container-copy", ARCHIVE);
}
@@ -122,7 +128,7 @@ class DocDbClusterSnapshotServiceTest {
assertEquals("InvalidDBClusterStateFault", e.getErrorCode());
assertEquals(400, e.getHttpStatus());
assertThrows(AwsException.class, () -> docDbService.getDbCluster("copy"));
verify(containerManager, never()).tryStart(eq("copy"), anyString(), anyString(), anyString(), anyString());
verify(containerManager, never()).tryStart(eq("copy"), anyString(), anyString(), anyString(), anyString(), any());
}
@Test
@@ -143,6 +149,25 @@ class DocDbClusterSnapshotServiceTest {
verify(containerManager).stop(argThat(handle -> "container-restored".equals(handle.getContainerId())));
}
@Test
void aFailedLoadDiscardsTheRestoredClustersVolumeWhateverTheStoragePolicy() {
when(storageConfig.mode()).thenReturn("persistent");
source(DocDbClusterSettings.defaults());
docDbService.createDbClusterSnapshot("snap", "source", Map.of());
doThrow(new IllegalStateException("mongorestore exited 1"))
.when(containerManager).restoreCluster("container-restored", ARCHIVE);
assertThrows(AwsException.class, () -> docDbService.restoreDbClusterFromSnapshot(
"restored", "snap", null, DocDbClusterSettings.defaults(), Map.of()));
ArgumentCaptor<String> volume = ArgumentCaptor.forClass(String.class);
verify(containerManager).tryStart(eq("restored"), anyString(), anyString(), anyString(), anyString(),
volume.capture());
assertNotNull(volume.getValue());
verify(containerManager).discardStorage(volume.getValue());
verify(containerManager, never()).removeStorage(any());
}
@Test
void bothRestoresKeepTheSourcesEncryptionAndKey() {
source(new DocDbClusterSettings(null, null, null, true, KEY_ARN, null, null, null, null));
@@ -196,7 +221,7 @@ class DocDbClusterSnapshotServiceTest {
assertEquals("InvalidDBClusterSnapshotStateFault", e.getErrorCode());
assertThrows(AwsException.class, () -> docDbService.getDbCluster("restored"));
verify(containerManager, never()).tryStart(eq("restored"), anyString(), anyString(), anyString(), anyString());
verify(containerManager, never()).tryStart(eq("restored"), anyString(), anyString(), anyString(), anyString(), any());
}
@Test
@@ -8,6 +8,7 @@ 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.DocDbClusterSettings;
@@ -21,6 +22,7 @@ import io.floci.aws.services.rds.model.DbClusterParameterGroup;
import io.floci.aws.services.rds.model.DbSubnetGroup;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import java.util.List;
@@ -31,6 +33,7 @@ import java.util.Set;
import static io.floci.aws.testing.Ec2ServiceFixtures.securityGroup;
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;
@@ -39,6 +42,7 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -114,7 +118,7 @@ class DocDbServiceTest {
assertEquals(27017, cluster.getPort());
assertTrue(cluster.getDbClusterArn().contains("mock-cluster"));
verify(containerManager, never()).start(anyString(), anyString(), anyString(), anyString(), any());
verify(containerManager, never()).start(anyString(), anyString(), anyString(), anyString(), any(), any());
}
@Test
@@ -183,24 +187,10 @@ class DocDbServiceTest {
// tryStart() returns null when no Docker daemon is reachable. The cluster record is
// metadata, so the create still succeeds and the cluster reaches 'available' on the
// first describe (what SDK/Terraform waiters poll).
StorageFactory storageFactory = Mockito.mock(StorageFactory.class);
when(storageFactory.create(anyString(), anyString(), any()))
.thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000"));
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.DocDbServiceConfig docdbConfig = Mockito.mock(EmulatorConfig.DocDbServiceConfig.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"));
DocDbContainerManager noDaemonContainerManager = Mockito.mock(DocDbContainerManager.class);
when(noDaemonContainerManager.tryStart(anyString(), anyString(), anyString(), anyString(), any()))
when(noDaemonContainerManager.tryStart(anyString(), anyString(), anyString(), anyString(), any(), any()))
.thenReturn(null);
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
DocDbService noDaemonService = new DocDbService(config, regionResolver, noDaemonContainerManager, storageFactory,
rdsService, ec2Service, kmsService);
DocDbService noDaemonService = containerBackedService("memory", noDaemonContainerManager);
DocDbCluster created = noDaemonService.createDbCluster(
"no-docker-cluster", null, "admin", "secret", false);
@@ -217,6 +207,78 @@ class DocDbServiceTest {
verify(noDaemonContainerManager, never()).stop(any());
}
@Test
void aClusterKeepsItsDataInAVolumeOfItsOwnWhenStorageIsPersistent() {
DocDbContainerManager manager = Mockito.mock(DocDbContainerManager.class);
when(manager.tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), any()))
.thenAnswer(inv -> new DocDbContainerHandle("container-" + inv.getArgument(0),
inv.getArgument(0), "localhost", 27017));
DocDbService service = containerBackedService("persistent", manager);
String first = service.createDbCluster("first", null, "admin", "secret", false).getVolumeId();
String second = service.createDbCluster("second", null, "admin", "secret", false).getVolumeId();
assertNotNull(first);
assertNotEquals(first, second);
assertEquals(first, service.getDbCluster("first").getVolumeId());
verify(manager).tryStart(eq("first"), anyString(), eq("admin"), eq("secret"), eq("us-east-1"), eq(first));
service.deleteDbCluster("first");
verify(manager).removeStorage(first);
verify(manager, never()).discardStorage(any());
String recreated = service.createDbCluster("first", null, "admin", "secret", false).getVolumeId();
assertNotNull(recreated);
assertNotEquals(first, recreated);
}
@Test
void aFailedCreateDiscardsTheVolumeMadeForIt() {
DocDbContainerManager manager = Mockito.mock(DocDbContainerManager.class);
when(manager.tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), any()))
.thenThrow(new IllegalStateException("no such image: mongo:7.0"));
DocDbService service = containerBackedService("persistent", manager);
assertThrows(IllegalStateException.class,
() -> service.createDbCluster("c", null, "admin", "secret", false));
ArgumentCaptor<String> volume = ArgumentCaptor.forClass(String.class);
verify(manager).tryStart(eq("c"), anyString(), anyString(), anyString(), anyString(), volume.capture());
assertNotNull(volume.getValue());
verify(manager).discardStorage(volume.getValue());
assertThrows(AwsException.class, () -> service.getDbCluster("c"));
}
@Test
void aClusterHasNoDataVolumeInMemoryMode() {
DocDbContainerManager manager = Mockito.mock(DocDbContainerManager.class);
when(manager.tryStart(anyString(), anyString(), anyString(), anyString(), anyString(), any()))
.thenAnswer(inv -> new DocDbContainerHandle("container-" + inv.getArgument(0),
inv.getArgument(0), "localhost", 27017));
DocDbService service = containerBackedService("memory", manager);
assertNull(service.createDbCluster("c", null, "admin", "secret", false).getVolumeId());
verify(manager).tryStart(eq("c"), anyString(), eq("admin"), eq("secret"), eq("us-east-1"), isNull());
}
private DocDbService containerBackedService(String storageMode, DocDbContainerManager manager) {
StorageFactory storageFactory = Mockito.mock(StorageFactory.class);
when(storageFactory.create(anyString(), anyString(), any()))
.thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000"));
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.DocDbServiceConfig docdbConfig = Mockito.mock(EmulatorConfig.DocDbServiceConfig.class);
EmulatorConfig.StorageConfig storageConfig = Mockito.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(storageMode);
return new DocDbService(config, new RegionResolver("us-east-1", "000000000000"), manager, storageFactory,
rdsService, ec2Service, kmsService);
}
@Test
void tagsAreAnsweredOnlyForAnArnInThisRegionAndAccount() {
// The router reaches this service only for an ARN it already matched, so these checks
@@ -549,7 +611,7 @@ class DocDbServiceTest {
e = refused(new DocDbClusterSettings(null, null, null, null, null, null, "02:00-02:30", "tue:02:15-tue:02:45", null));
assertEquals("The backup window and maintenance window must not overlap.", e.getMessage());
assertThrows(AwsException.class, () -> docDbService.getDbCluster("c1"));
verify(containerManager, never()).tryStart(any(), any(), any(), any(), any());
verify(containerManager, never()).tryStart(any(), any(), any(), any(), any(), any());
// a window given alone is paired with a default clear of it
docDbService.createDbCluster("alone", "5.0.0", "u", "pw", false,
@@ -10,6 +10,7 @@ import io.floci.aws.core.common.docker.ContainerSpec;
import io.floci.aws.testing.ParallelLocks;
import org.jboss.logging.Logger;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.api.parallel.ResourceAccessMode;
import org.junit.jupiter.api.parallel.ResourceLock;
import org.mockito.Mockito;
@@ -18,6 +19,8 @@ import java.io.Closeable;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -27,6 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
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.eq;
@@ -55,7 +59,7 @@ class DocDbContainerManagerTest {
DocDbContainerManager manager = newManager(lifecycleManager);
for (int attempt = 0; attempt < 3; attempt++) {
assertNull(manager.tryStart("cluster1", "mongo:7.0", "admin", "secret", "us-east-1"),
assertNull(manager.tryStart("cluster1", "mongo:7.0", "admin", "secret", "us-east-1", null),
"attempt " + attempt + " should report unavailable");
}
assertFalse(manager.isDockerReachable());
@@ -73,7 +77,7 @@ class DocDbContainerManagerTest {
DocDbContainerManager manager = newManager(lifecycleManager);
RuntimeException failure = assertThrows(RuntimeException.class,
() -> manager.tryStart("cluster1", "mongo:7.0", "admin", "secret", "us-east-1"));
() -> manager.tryStart("cluster1", "mongo:7.0", "admin", "secret", "us-east-1", null));
assertEquals("no such image: mongo:7.0", failure.getMessage());
}
@@ -100,7 +104,7 @@ class DocDbContainerManagerTest {
DocDbContainerManager manager = newManager(lifecycleManager);
DocDbContainerHandle handle = manager.tryStart("cluster1", "mongo:7.0", "admin", "secret", "us-east-1");
DocDbContainerHandle handle = manager.tryStart("cluster1", "mongo:7.0", "admin", "secret", "us-east-1", null);
assertEquals("container-id", handle.getContainerId());
assertEquals(serverSocket.getLocalPort(), handle.getPort());
@@ -146,7 +150,7 @@ class DocDbContainerManagerTest {
logStreamer, mock(ContainerDetector.class), config,
new RegionResolver("us-east-1", "000000000000"));
manager.start("cluster1", "mongo:7.0", "admin", "secret", "eu-west-1");
manager.start("cluster1", "mongo:7.0", "admin", "secret", "eu-west-1", null);
verify(builder).withLabels(Map.of(
"io.floci", "aws",
@@ -175,7 +179,7 @@ class DocDbContainerManagerTest {
for (String account : List.of("111111111111", "222222222222")) {
when(resolver.getAccountId()).thenReturn(account);
for (String region : List.of("us-east-1", "eu-west-1")) {
handles.add(manager.start("shared", "mongo:7.0", "admin", "secret", region));
handles.add(manager.start("shared", "mongo:7.0", "admin", "secret", region, null));
}
}
assertEquals(4, names.stream().distinct().count());
@@ -191,13 +195,169 @@ class DocDbContainerManagerTest {
}
}
@Test
void aClusterWithAVolumeKeepsItsDataInANamedVolumeOfItsOwn() throws IOException {
try (ServerSocket backend = new ServerSocket(0)) {
ContainerLifecycleManager lifecycle = backedBy(backend);
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);
DocDbContainerManager manager = newManager(lifecycle, builder, storage("persistent", null, false));
manager.start("cluster1", "mongo:7.0", "admin", "secret", "us-east-1", "vol-1");
verify(lifecycle).ensureVolume("floci-aws-docdb-vol-1");
verify(builder).withNamedVolume("floci-aws-docdb-vol-1", "/data/db");
verify(builder, never()).withBind(anyString(), anyString());
}
}
@Test
void aClusterWithAVolumeKeepsItsDataUnderTheHostPersistentPath(@TempDir Path hostPath) throws IOException {
try (ServerSocket backend = new ServerSocket(0)) {
ContainerLifecycleManager lifecycle = backedBy(backend);
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);
DocDbContainerManager manager = newManager(lifecycle, builder,
storage("persistent", hostPath.toString(), false));
manager.start("cluster1", "mongo:7.0", "admin", "secret", "us-east-1", "vol-1");
Path dataDir = hostPath.resolve("docdb").resolve("vol-1");
verify(builder).withBind(dataDir.toString(), "/data/db");
assertTrue(Files.isDirectory(dataDir));
verify(builder, never()).withNamedVolume(anyString(), anyString());
verify(lifecycle, never()).ensureVolume(anyString());
}
}
@Test
void aClusterWithoutAVolumeMountsNothing() throws IOException {
try (ServerSocket backend = new ServerSocket(0)) {
ContainerLifecycleManager lifecycle = backedBy(backend);
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);
DocDbContainerManager manager = newManager(lifecycle, builder, storage("memory", null, false));
manager.start("cluster1", "mongo:7.0", "admin", "secret", "us-east-1", null);
verify(builder, never()).withNamedVolume(anyString(), anyString());
verify(builder, never()).withBind(anyString(), anyString());
verify(lifecycle, never()).ensureVolume(anyString());
}
}
@Test
void aStartThatCannotFinishRemovesTheContainerItStarted() throws IOException {
try (ServerSocket backend = new ServerSocket(0)) {
ContainerLifecycleManager lifecycle = backedBy(backend);
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(builder.build()).thenReturn(new ContainerSpec("test-image"));
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
when(logStreamer.attachPolled(anyString(), anyString(), anyString(), anyString(), anyString()))
.thenThrow(new IllegalStateException("log stream refused"));
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.DocDbServiceConfig docdb = mock(EmulatorConfig.DocDbServiceConfig.class);
when(config.services()).thenReturn(services);
when(services.docdb()).thenReturn(docdb);
when(docdb.dockerNetwork()).thenReturn(Optional.empty());
EmulatorConfig.StorageConfig storage = storage("persistent", null, false);
when(config.storage()).thenReturn(storage);
DocDbContainerManager manager = new DocDbContainerManager(containerBuilder, lifecycle, logStreamer,
mock(ContainerDetector.class), config, new RegionResolver("us-east-1", "000000000000"));
assertThrows(IllegalStateException.class,
() -> manager.start("cluster1", "mongo:7.0", "admin", "secret", "us-east-1", "vol-1"));
verify(lifecycle).stopAndRemove("container-id", null);
manager.stopAll();
verify(lifecycle, times(1)).stopAndRemove(anyString(), any());
verify(lifecycle, never()).removeVolume(anyString());
}
}
@Test
void removingStorageDropsTheVolumeWhenVolumesArePrunedOnDelete() {
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
DocDbContainerManager manager = newManager(lifecycle, mock(ContainerBuilder.Builder.class),
storage("persistent", null, true));
manager.removeStorage("vol-1");
verify(lifecycle).removeVolume("floci-aws-docdb-vol-1");
}
@Test
void removingStorageKeepsTheVolumeWhenAPersistentModeRetainsVolumes() {
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
DocDbContainerManager manager = newManager(lifecycle, mock(ContainerBuilder.Builder.class),
storage("persistent", null, false));
manager.removeStorage("vol-1");
verify(lifecycle, never()).removeVolume(anyString());
}
@Test
void removingStorageLeavesAHostDirectoryAndAClusterWithoutAVolumeAlone(@TempDir Path hostPath) {
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
newManager(lifecycle, mock(ContainerBuilder.Builder.class), storage("persistent", hostPath.toString(), true))
.removeStorage("vol-1");
newManager(lifecycle, mock(ContainerBuilder.Builder.class), storage("persistent", null, true))
.removeStorage(null);
verify(lifecycle, never()).removeVolume(anyString());
}
@Test
void discardingStorageDropsTheVolumeEvenWhenThePolicyRetainsVolumes(@TempDir Path hostPath) {
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
DocDbContainerManager manager = newManager(lifecycle, mock(ContainerBuilder.Builder.class),
storage("persistent", null, false));
manager.discardStorage("vol-1");
manager.discardStorage(null);
newManager(lifecycle, mock(ContainerBuilder.Builder.class), storage("persistent", hostPath.toString(), false))
.discardStorage("vol-2");
verify(lifecycle).removeVolume("floci-aws-docdb-vol-1");
verify(lifecycle, times(1)).removeVolume(anyString());
}
private static ContainerLifecycleManager backedBy(ServerSocket backend) {
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo(
"container-id", Map.of(27017, new ContainerLifecycleManager.EndpointInfo(
"127.0.0.1", backend.getLocalPort()))));
return lifecycle;
}
private static EmulatorConfig.StorageConfig storage(String mode, String hostPersistentPath, boolean prune) {
EmulatorConfig.StorageConfig storage = mock(EmulatorConfig.StorageConfig.class);
when(storage.mode()).thenReturn(mode);
when(storage.hostPersistentPath()).thenReturn(hostPersistentPath);
when(storage.pruneVolumesOnDelete()).thenReturn(prune);
return storage;
}
private DocDbContainerManager newManager(ContainerLifecycleManager lifecycleManager) {
return newManager(lifecycleManager, new RegionResolver("us-east-1", "000000000000"));
}
private DocDbContainerManager newManager(ContainerLifecycleManager lifecycleManager, RegionResolver resolver) {
return newManager(lifecycleManager, resolver, mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF), null);
}
private DocDbContainerManager newManager(ContainerLifecycleManager lifecycleManager,
ContainerBuilder.Builder builder,
EmulatorConfig.StorageConfig storage) {
return newManager(lifecycleManager, new RegionResolver("us-east-1", "000000000000"), builder, storage);
}
private DocDbContainerManager newManager(ContainerLifecycleManager lifecycleManager, RegionResolver resolver,
ContainerBuilder.Builder builder,
EmulatorConfig.StorageConfig storage) {
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(builder.build()).thenReturn(new ContainerSpec("test-image"));
@@ -212,6 +372,7 @@ class DocDbContainerManagerTest {
when(config.services()).thenReturn(services);
when(services.docdb()).thenReturn(docdb);
when(docdb.dockerNetwork()).thenReturn(Optional.empty());
when(config.storage()).thenReturn(storage);
return new DocDbContainerManager(containerBuilder, lifecycleManager, logStreamer,
mock(ContainerDetector.class), config, resolver);