diff --git a/.github/ci/prefetch-images.sh b/.github/ci/prefetch-images.sh index 7c69cbb381..f5041a10b4 100755 --- a/.github/ci/prefetch-images.sh +++ b/.github/ci/prefetch-images.sh @@ -205,7 +205,6 @@ starts EmrContainersGatewayNightlyIntegrationTest \ # package token in shard.txt -> images its tests are known to launch # (measured inline pulls; update alongside image-catalog changes) -grep -q '/docdb/' "$SHARD_FILE" && pull mongo:7.0 configured_image() { image="$(bash .github/ci/service-image.sh "$1" "$2")" if [ -n "$image" ]; then @@ -224,8 +223,10 @@ if starts NeptuneGraphVolumeDockerNightlyIntegrationTest NeptuneClusterRestartDo configured_image neptune default-image configured_image neptune default-neo4j-image fi -# DocDbClusterRestartDockerNightlyIntegrationTest restarts clusters on the configured MongoDB image. -starts DocDbClusterRestartDockerNightlyIntegrationTest && configured_image docdb default-image +if starts DocDbClusterRestartDockerNightlyIntegrationTest DocDbClusterSnapshotDockerNightlyIntegrationTest \ + || grep -q '/docdb/' "$SHARD_FILE"; then + configured_image docdb default-image +fi 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 16155b1526..b332543cec 100644 --- a/docs/services/docdb.md +++ b/docs/services/docdb.md @@ -75,6 +75,12 @@ 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. +Snapshots taken with a MongoDB backend preserve documents, collection indexes, users and roles. +Floci restores collection data and indexes before replacing the target's users and roles. If the +new cluster has no backend to receive the archive, the restore returns `InvalidRestoreFault`. +Floci discards the failed target even if the request enabled deletion protection. You can retry +from the same snapshot. Snapshots taken in mock mode contain only metadata. + ### Restarts With a persistent storage mode, Floci's shutdown removes each cluster's MongoDB container and keeps 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 30c6b3ef49..1f9dac5296 100644 --- a/src/main/java/io/floci/aws/services/docdb/DocDbService.java +++ b/src/main/java/io/floci/aws/services/docdb/DocDbService.java @@ -1190,14 +1190,18 @@ public class DocDbService { } private void loadInto(DocDbCluster cluster, String data) { - if (config.services().docdb().mock() || data.isEmpty() || cluster.getContainerId() == null) { + if (config.services().docdb().mock() || data.isEmpty()) { return; } try { - containerManager.restoreCluster(cluster.getContainerId(), data); + String containerId = cluster.getContainerId(); + if (containerId == null) { + throw new IllegalStateException("No running MongoDB backend is available for the restored cluster"); + } + containerManager.restoreCluster(containerId, data); } catch (RuntimeException e) { try { - discardRestoredCluster(cluster.getDbClusterIdentifier()); + discardRestoredCluster(cluster); } catch (RuntimeException cleanup) { LOG.warnv(cleanup, "Could not remove DocDB cluster {0} after its failed restore", cluster.getDbClusterIdentifier()); @@ -1212,10 +1216,13 @@ public class DocDbService { * Removes a cluster this restore just created and could not load. It bypasses deletion * protection, which the request may have asked for: the caller never received the cluster. */ - private void discardRestoredCluster(String id) { + private void discardRestoredCluster(DocDbCluster restored) { + String id = restored.getDbClusterIdentifier(); String region = regionResolver.getRegion(); synchronized (lockFor("cluster:" + key(region, id))) { - findCluster(region, id).ifPresent(cluster -> removeCluster(region, cluster, true)); + findCluster(region, id) + .filter(cluster -> Objects.equals(cluster.getDbClusterResourceId(), restored.getDbClusterResourceId())) + .ifPresent(cluster -> removeCluster(region, cluster, true)); } } 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 4135ca3a72..4e3d432f32 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 @@ -320,8 +320,16 @@ public class DocDbContainerManager { throw new RuntimeException("MongoDB did not accept writes before the restore: " + (probe != null ? probe.stderr() : "")); } - String[] cmd = {"bash", "-c", "mongorestore --quiet --host 127.0.0.1 --port " + MONGO_PORT + auth - + " --drop --nsExclude='config.*' --archive=/tmp/floci-docdb-restore.archive.gz --gzip" + String restore = "mongorestore --quiet --host 127.0.0.1 --port " + MONGO_PORT + auth + + " --drop --archive=/tmp/floci-docdb-restore.archive.gz --gzip"; + // Replacing users invalidates the connection used to build indexes. Load authentication + // last, including its schema version, while preserving custom collections in admin. + String[] cmd = {"bash", "-c", restore + + " --nsExclude='config.*' --nsExclude='admin.system.users'" + + " --nsExclude='admin.system.roles' --nsExclude='admin.system.version'" + + " && " + restore + + " --nsInclude='admin.system.users' --nsInclude='admin.system.roles'" + + " --nsInclude='admin.system.version' --noIndexRestore" + " && rm -f /tmp/floci-docdb-restore.archive.gz"}; ContainerExec.Result result = ContainerExec.run(lifecycleManager.getDockerClient(), containerId, cmd, 600); if (result.exitCode() != 0) { diff --git a/src/test/java/io/floci/aws/services/docdb/DocDbClusterRestartDockerNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/docdb/DocDbClusterRestartDockerNightlyIntegrationTest.java index ddccc18677..248e757732 100644 --- a/src/test/java/io/floci/aws/services/docdb/DocDbClusterRestartDockerNightlyIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/docdb/DocDbClusterRestartDockerNightlyIntegrationTest.java @@ -3,7 +3,6 @@ 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; @@ -25,6 +24,7 @@ import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; +import static io.floci.aws.services.docdb.DocDbTestShell.mongosh; import static io.restassured.RestAssured.given; import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -152,7 +152,7 @@ class DocDbClusterRestartDockerNightlyIntegrationTest { /** 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, + .until(() -> mongosh(dockerClient, containerId, "db.getSiblingDB('app').items.insertOne({_id: 'kept', value: '" + value + "'})") .exitCode() == 0); } @@ -163,18 +163,12 @@ class DocDbClusterRestartDockerNightlyIntegrationTest { */ private String read(String containerId) { return await("document read").atMost(Duration.ofMinutes(1)).pollInterval(Duration.ofSeconds(2)) - .until(() -> mongosh(containerId, + .until(() -> mongosh(dockerClient, 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) diff --git a/src/test/java/io/floci/aws/services/docdb/DocDbClusterSnapshotDockerNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/docdb/DocDbClusterSnapshotDockerNightlyIntegrationTest.java new file mode 100644 index 0000000000..f6f11a5034 --- /dev/null +++ b/src/test/java/io/floci/aws/services/docdb/DocDbClusterSnapshotDockerNightlyIntegrationTest.java @@ -0,0 +1,221 @@ +package io.floci.aws.services.docdb; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.dockerjava.api.command.InspectContainerResponse; +import com.github.dockerjava.api.exception.NotFoundException; +import io.floci.aws.core.common.XmlParser; +import io.floci.aws.core.common.docker.ContainerExec; +import io.floci.aws.core.common.docker.ContainerLifecycleManager; +import io.floci.aws.testing.QueryRequests; +import io.floci.aws.testing.SidecarContainersProfile; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.response.Response; +import jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static io.floci.aws.services.docdb.DocDbTestShell.mongosh; +import static io.floci.aws.testing.RdsRequests.assumeDocker; +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertAll; +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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** AWS Query control requests with real authenticated MongoDB documents and mongodump/mongorestore. */ +@QuarkusTest +@Tag("docker") +@TestProfile(SidecarContainersProfile.class) +@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true") +class DocDbClusterSnapshotDockerNightlyIntegrationTest { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final String ORIGINAL = """ + [{"_id":"alpha","counter":7,"active":true,"nested":{"city":"Oslo"},"labels":["a","b"]}, + {"_id":"beta","counter":12,"active":false,"nested":{"city":"Lima"},"labels":["c"]}] + """; + private static final String CHANGED = """ + [{"_id":"beta","counter":999,"active":false,"nested":{"city":"Lima"},"labels":["later"]}, + {"_id":"gamma","counter":3}] + """; + private static final String DOCUMENTS = + "print(JSON.stringify(db.getSiblingDB('snapshot_test').documents.find().sort({_id:1}).toArray()))"; + private static final String ADMIN_DOCUMENTS = + "print(JSON.stringify(db.getSiblingDB('admin').snapshot_notes.find().sort({_id:1}).toArray()))"; + + @Inject + DocDbService service; + + @Inject + ContainerLifecycleManager containers; + + private final String source = "docdb-data-" + UUID.randomUUID().toString().substring(0, 12); + private final String target = source + "-restored"; + private final String snapshot = source + "-snapshot"; + private final String secondSnapshot = source + "-second"; + private final String readerPassword = UUID.randomUUID().toString(); + private final List ownedContainers = new ArrayList<>(); + private final List ownedVolumes = new ArrayList<>(); + private boolean createAttempted; + + @Test + void storedArchiveRestoresOriginalDocumentsAfterSourceMutationAndDeletion() throws Exception { + assumeDocker(); + createAttempted = true; + call("CreateDBCluster", Map.of("DBClusterIdentifier", source, "Engine", "docdb", + "MasterUsername", "archiveadmin", "MasterUserPassword", UUID.randomUUID().toString())) + .then().statusCode(200); + String sourceContainer = trackBackend(source); + await().atMost(Duration.ofSeconds(90)).pollInterval(Duration.ofSeconds(1)) + .untilAsserted(() -> assertEquals(0L, mongosh(containers.getDockerClient(), sourceContainer, + "quit(db.hello().isWritablePrimary ? 0 : 3)").exitCode())); + seedCollections(sourceContainer); + assertEquals(JSON.readTree(ORIGINAL), documents(sourceContainer)); + assertEquals(JSON.readTree(ORIGINAL), readerDocuments(sourceContainer)); + + String snapshotArn = createSnapshot(source, snapshot); + assertFalse(service.getDbClusterSnapshot(snapshot).isMetadataOnly()); + assertTrue(service.getDbClusterSnapshot(snapshot).getSizeBytes() > 0); + + execute(sourceContainer, """ + const c = db.getSiblingDB('snapshot_test').documents; + c.deleteOne({_id: 'alpha'}); + c.updateOne({_id: 'beta'}, {$set: {counter: 999, labels: ['later']}}); + c.insertOne({_id: 'gamma', counter: 3}); + """); + assertEquals(JSON.readTree(CHANGED), documents(sourceContainer)); + deleteCluster(source).then().statusCode(200); + assertGone(sourceContainer); + + call("RestoreDBClusterFromSnapshot", Map.of("DBClusterIdentifier", target, + "SnapshotIdentifier", snapshotArn, "Engine", "docdb")).then().statusCode(200); + String targetContainer = trackBackend(target); + assertNotEquals(sourceContainer, targetContainer); + assertEquals(JSON.readTree(ORIGINAL), documents(targetContainer)); + assertIndex(targetContainer, "snapshot_test", "documents", "by_counter"); + assertEquals(JSON.readTree("[{\"_id\":\"note\",\"value\":5}]"), + JSON.readTree(execute(targetContainer, ADMIN_DOCUMENTS))); + assertIndex(targetContainer, "admin", "snapshot_notes", "by_value"); + assertEquals(JSON.readTree(ORIGINAL), readerDocuments(targetContainer)); + + // A fresh authenticated dump also proves the restored master credentials remain usable. + createSnapshot(target, secondSnapshot); + deleteSnapshot(snapshot).then().statusCode(200); + assertEquals(JSON.readTree(ORIGINAL), documents(targetContainer)); + } + + @AfterEach + void removeSnapshotsAndClusters() { + if (!createAttempted) { + return; + } + assertAll(() -> assertDeletedOrMissing(deleteSnapshot(secondSnapshot), "DBClusterSnapshotNotFoundFault"), + () -> assertDeletedOrMissing(deleteSnapshot(snapshot), "DBClusterSnapshotNotFoundFault"), + () -> assertDeletedOrMissing(deleteCluster(target), "DBClusterNotFoundFault"), + () -> assertDeletedOrMissing(deleteCluster(source), "DBClusterNotFoundFault"), + () -> assertAll(ownedContainers.stream().map(id -> () -> assertGone(id))), + () -> assertAll(ownedVolumes.stream().map(volume -> () -> containers.removeVolumeStrict(volume)))); + } + + private String trackBackend(String clusterId) { + String id = service.getDbCluster(clusterId).getContainerId(); + assertNotNull(id, "This test requires a real MongoDB backend"); + ownedContainers.add(id); + InspectContainerResponse container = containers.getDockerClient().inspectContainerCmd(id).exec(); + for (InspectContainerResponse.Mount mount : container.getMounts()) { + String path = mount.getDestination().getPath(); + if (mount.getName() != null && ("/data/db".equals(path) || "/data/configdb".equals(path))) { + ownedVolumes.add(mount.getName()); + } + } + return id; + } + + private void seedCollections(String containerId) { + execute(containerId, """ + const app = db.getSiblingDB('snapshot_test'); + app.documents.insertMany(%s); + app.documents.createIndex({counter: 1}, {name: 'by_counter'}); + const notes = db.getSiblingDB('admin').snapshot_notes; + notes.insertOne({_id: 'note', value: 5}); + notes.createIndex({value: 1}, {name: 'by_value'}); + app.createRole({role: 'archive_reader', privileges: [ + {resource: {db: 'snapshot_test', collection: 'documents'}, actions: ['find']} + ], roles: []}); + app.createUser({user: 'archive_reader', pwd: '%s', roles: ['archive_reader']}); + """.formatted(ORIGINAL, readerPassword)); + } + + private void assertIndex(String containerId, String database, String collection, String index) throws Exception { + String script = "print(JSON.stringify(db.getSiblingDB('%s').getCollection('%s').getIndexes().map(i => i.name)))" + .formatted(database, collection); + List names = JSON.readerForListOf(String.class).readValue(execute(containerId, script)); + assertTrue(names.contains(index), () -> "Expected " + index + " in " + names); + } + + private JsonNode documents(String containerId) throws Exception { + return JSON.readTree(execute(containerId, DOCUMENTS)); + } + + private JsonNode readerDocuments(String containerId) throws Exception { + ContainerExec.Result result = ContainerExec.run(containers.getDockerClient(), containerId, new String[]{ + "mongosh", "--quiet", "--host", "127.0.0.1", "--port", "27017", "--username", "archive_reader", + "--password", readerPassword, "--authenticationDatabase", "snapshot_test", + "--eval", DOCUMENTS}, 30); + assertEquals(0L, result.exitCode(), result::summary); + assertFalse(result.timedOut()); + return JSON.readTree(result.stdout()); + } + + private String execute(String containerId, String script) { + ContainerExec.Result result = mongosh(containers.getDockerClient(), containerId, script); + assertEquals(0L, result.exitCode(), result::summary); + assertFalse(result.timedOut()); + return result.stdout().trim(); + } + + private void assertGone(String containerId) { + assertThrows(NotFoundException.class, () -> containers.getDockerClient().inspectContainerCmd(containerId).exec()); + } + + private static Response call(String action, Map params) { + return QueryRequests.request("000000000000", "rds", action).formParams(params).post("/"); + } + + private static String createSnapshot(String clusterId, String snapshotId) { + String body = call("CreateDBClusterSnapshot", Map.of("DBClusterIdentifier", clusterId, + "DBClusterSnapshotIdentifier", snapshotId)).then().statusCode(200).extract().asString(); + assertEquals("available", XmlParser.extractFirst(body, "Status", null)); + String arn = XmlParser.extractFirst(body, "DBClusterSnapshotArn", null); + assertNotNull(arn, body); + return arn; + } + + private static Response deleteCluster(String id) { + return call("DeleteDBCluster", Map.of("DBClusterIdentifier", id, "SkipFinalSnapshot", "true")); + } + + private static Response deleteSnapshot(String id) { + return call("DeleteDBClusterSnapshot", Map.of("DBClusterSnapshotIdentifier", id)); + } + + private static void assertDeletedOrMissing(Response response, String notFoundCode) { + if (response.statusCode() == 404) { + assertEquals(notFoundCode, XmlParser.extractFirst(response.asString(), "Code", null)); + } else { + response.then().statusCode(200); + } + } +} diff --git a/src/test/java/io/floci/aws/services/docdb/DocDbClusterSnapshotServiceTest.java b/src/test/java/io/floci/aws/services/docdb/DocDbClusterSnapshotServiceTest.java index 867f7fed9b..df36ffd3ee 100644 --- a/src/test/java/io/floci/aws/services/docdb/DocDbClusterSnapshotServiceTest.java +++ b/src/test/java/io/floci/aws/services/docdb/DocDbClusterSnapshotServiceTest.java @@ -17,6 +17,8 @@ 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.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import java.util.List; @@ -32,6 +34,7 @@ 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.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; @@ -149,6 +152,23 @@ class DocDbClusterSnapshotServiceTest { verify(containerManager).stop(argThat(handle -> "container-restored".equals(handle.getContainerId()))); } + @Test + void aFailedRestoreLeavesAReplacementClusterWithTheSameIdentifierAlone() { + source(DocDbClusterSettings.defaults()); + docDbService.createDbClusterSnapshot("snap", "source", Map.of()); + doAnswer(invocation -> { + docDbService.deleteDbCluster("restored"); + docDbService.createDbCluster("restored", "5.0.0", "replacement", "replacement-password", false); + throw new IllegalStateException("The original restore target was deleted"); + }).when(containerManager).restoreCluster("container-restored", ARCHIVE); + + AwsException failure = assertThrows(AwsException.class, () -> docDbService.restoreDbClusterFromSnapshot( + "restored", "snap", null, DocDbClusterSettings.defaults(), Map.of())); + + assertEquals("InvalidRestoreFault", failure.getErrorCode()); + assertEquals("replacement", docDbService.getDbCluster("restored").getMasterUsername()); + } + @Test void aFailedLoadDiscardsTheRestoredClustersVolumeWhateverTheStoragePolicy() { when(storageConfig.mode()).thenReturn("persistent"); @@ -168,6 +188,38 @@ class DocDbClusterSnapshotServiceTest { verify(containerManager, never()).removeStorage(any()); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void anUnavailableRestoreTargetFailsAndLeavesItsSourceAndArchiveIntact(boolean pointInTime) { + source(DocDbClusterSettings.defaults()); + DocDbClusterSnapshot snapshot = docDbService.createDbClusterSnapshot("snap", "source", Map.of("saved", "yes")); + List savedArchives = List.copyOf(archives.scan(value -> true)); + when(containerManager.tryStart(eq("restored"), anyString(), anyString(), anyString(), anyString(), any())) + .thenReturn(null); + DocDbClusterSettings protectedCluster = new DocDbClusterSettings(null, null, null, null, null, null, + null, null, true); + + AwsException failure = assertThrows(AwsException.class, () -> { + if (pointInTime) { + docDbService.restoreDbClusterToPointInTime("restored", "source", protectedCluster, Map.of()); + } else { + docDbService.restoreDbClusterFromSnapshot("restored", "snap", null, protectedCluster, Map.of()); + } + }); + + assertEquals("InvalidRestoreFault", failure.getErrorCode()); + assertEquals(400, failure.getHttpStatus()); + AwsException absent = assertThrows(AwsException.class, () -> docDbService.getDbCluster("restored")); + assertEquals("DBClusterNotFoundFault", absent.getErrorCode()); + assertEquals("container-source", docDbService.getDbCluster("source").getContainerId()); + assertEquals("available", docDbService.getDbCluster("source").getStatus()); + assertEquals(snapshot, docDbService.getDbClusterSnapshot("snap")); + assertEquals(Map.of("saved", "yes"), docDbService.getDbClusterSnapshot("snap").getTags()); + assertEquals(savedArchives, archives.scan(value -> true)); + verify(containerManager, never()).restoreCluster(anyString(), anyString()); + verify(containerManager, never()).stop(any()); + } + @Test void bothRestoresKeepTheSourcesEncryptionAndKey() { source(new DocDbClusterSettings(null, null, null, true, KEY_ARN, null, null, null, null)); diff --git a/src/test/java/io/floci/aws/services/docdb/DocDbTestShell.java b/src/test/java/io/floci/aws/services/docdb/DocDbTestShell.java new file mode 100644 index 0000000000..78515bc697 --- /dev/null +++ b/src/test/java/io/floci/aws/services/docdb/DocDbTestShell.java @@ -0,0 +1,16 @@ +package io.floci.aws.services.docdb; + +import com.github.dockerjava.api.DockerClient; +import io.floci.aws.core.common.docker.ContainerExec; + +final class DocDbTestShell { + private DocDbTestShell() {} + + /** Runs a script as the cluster's master user with the credentials from its MongoDB container. */ + static ContainerExec.Result mongosh(DockerClient docker, String containerId, String script) { + return ContainerExec.run(docker, containerId, new String[]{ + "bash", "-c", "exec mongosh --quiet --host 127.0.0.1 --port 27017 " + + "--username \"$MONGO_INITDB_ROOT_USERNAME\" --password \"$MONGO_INITDB_ROOT_PASSWORD\" " + + "--authenticationDatabase admin --eval \"$1\"", "mongosh", script}, 60); + } +}