fix(docdb): isolate container identity by account and region (#8888)

A DocumentDB cluster's MongoDB container was named after the cluster
identifier alone, and the manager kept its live handles under that
identifier too. Creating a same-named cluster in another account or
Region removed the first cluster's container and replaced its handle,
so a later delete or shutdown could no longer reach it.

Container names now carry the account and Region
(floci-aws-docdb-<account>-<region>-<cluster>), and live handles are
kept by Docker ID. Deleting a cluster closes the log stream its
container was started with, which the handle DeleteDBCluster rebuilds
from the stored record does not carry.

Ported from #5724.

Co-authored-by: Daniël van Ziel <159726064+danielvanza@users.noreply.github.com>
This commit is contained in:
Priamo GermosenandDaniël van Ziel authored and GitHub committed 2026-11-18 17:19:46 -04:00
1 parent 6afd82c9fb
commit 1df1af297d
5 files changed
+78 -6

No files matched your search

+4
View File
@@ -66,6 +66,10 @@ Mock mode is useful for control-plane tests that do not need a live database; th
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`.
Container names include the account ID, region, and cluster identifier, so identically named
clusters in different accounts or regions use independent MongoDB containers. With no Docker
resource namespace configured, the name is `floci-aws-docdb-<account>-<region>-<cluster>`.
```yaml
services:
floci:
@@ -110,6 +110,13 @@ public final class ContainerStorageHelper {
return dockerName(config, service + "-" + (volumeId != null ? volumeId : fallbackId));
}
/** Scopes name-based resources without changing the identity of an existing data volume. */
public static String resourceName(EmulatorConfig config, String service, String volumeId, String fallbackId,
String accountId, String region) {
return resourceName(config, service, volumeId,
sanitizeNamePart(accountId) + "-" + sanitizeNamePart(region) + "-" + fallbackId);
}
/**
* Prefixes {@code baseName} with {@code floci-aws-} and the configured resource namespace,
* which lands after the cloud token: {@code floci-aws-<namespace>-<base>}.
@@ -108,7 +108,9 @@ public class DocDbContainerManager {
String region) {
LOG.infov("Starting DocumentDB container for cluster: {0}", clusterId);
String containerName = ContainerStorageHelper.resourceName(config, "docdb", null, clusterId);
String accountId = regionResolver.getAccountId();
String containerName = ContainerStorageHelper.resourceName(config, "docdb", null, clusterId,
accountId, region);
lifecycleManager.removeIfExists(containerName);
List<String> envVars = List.of(
@@ -122,7 +124,7 @@ public class DocDbContainerManager {
.withLogRotation()
.withEnv(envVars)
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"docdb", clusterId, regionResolver.getAccountId(), region));
"docdb", clusterId, accountId, region));
if (!containerDetector.isRunningInContainer()) {
specBuilder.withDynamicPort(MONGO_PORT);
@@ -139,7 +141,8 @@ public class DocDbContainerManager {
DocDbContainerHandle handle = new DocDbContainerHandle(
info.containerId(), clusterId, endpoint.host(), endpoint.port());
activeContainers.put(clusterId, handle);
// 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)
@@ -160,8 +163,9 @@ public class DocDbContainerManager {
if (handle == null) {
return;
}
activeContainers.remove(handle.getClusterId());
lifecycleManager.stopAndRemove(handle.getContainerId(), handle.getLogStream());
DocDbContainerHandle active = activeContainers.remove(handle.getContainerId());
lifecycleManager.stopAndRemove(handle.getContainerId(),
active == null ? handle.getLogStream() : active.getLogStream());
}
public void stopAll() {
@@ -45,6 +45,16 @@ class ContainerStorageHelperTest {
assertEquals("floci-aws-ec2-i-123", ContainerStorageHelper.dockerName(config(""), "ec2-i-123"));
}
@Test
void scopedResourceNamesPreserveNamespaceAndExistingVolumeIdentity() {
EmulatorConfig config = config("run-one");
assertEquals("floci-aws-run-one-docdb-111111111111-eu-west-1-shared",
ContainerStorageHelper.resourceName(config, "docdb", null, "shared", "111111111111", "eu-west-1"));
assertEquals("floci-aws-run-one-docdb-existing-volume",
ContainerStorageHelper.resourceName(config, "docdb", "existing-volume", "shared",
"111111111111", "eu-west-1"));
}
@Test
void alreadyPrefixedNamesAreNormalisedNotPrefixedTwice() {
// A persisted name is fed straight back in when a container is named after the volume it
@@ -12,9 +12,12 @@ import org.jboss.logging.Logger;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.io.Closeable;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -24,8 +27,12 @@ import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -149,7 +156,45 @@ class DocDbContainerManagerTest {
}
}
@Test
void sameNamedClustersHaveIndependentContainersAcrossAccountsAndRegions() throws IOException {
try (ServerSocket backend = new ServerSocket(0)) {
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
List<String> names = new ArrayList<>();
doAnswer(call -> {
names.add(call.getArgument(0));
return null;
}).when(lifecycle).removeIfExists(anyString());
when(lifecycle.createAndStart(any())).thenAnswer(call ->
new ContainerLifecycleManager.ContainerInfo("container-" + names.size(), Map.of(27017,
new ContainerLifecycleManager.EndpointInfo("127.0.0.1", backend.getLocalPort()))));
RegionResolver resolver = mock(RegionResolver.class);
DocDbContainerManager manager = newManager(lifecycle, resolver);
List<DocDbContainerHandle> handles = new ArrayList<>();
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));
}
}
assertEquals(4, names.stream().distinct().count());
assertEquals("floci-aws-docdb-111111111111-us-east-1-shared", names.getFirst());
// Delete reconstructs the handle from persisted metadata, outside its original scope.
DocDbContainerHandle first = handles.getFirst();
manager.stop(new DocDbContainerHandle(first.getContainerId(), "shared", first.getHost(), first.getPort()));
verify(lifecycle, never()).stopAndRemove(eq(handles.get(1).getContainerId()), any());
manager.stopAll();
for (DocDbContainerHandle handle : handles) {
verify(lifecycle, times(1)).stopAndRemove(handle.getContainerId(), handle.getLogStream());
}
}
}
private DocDbContainerManager newManager(ContainerLifecycleManager lifecycleManager) {
return newManager(lifecycleManager, new RegionResolver("us-east-1", "000000000000"));
}
private DocDbContainerManager newManager(ContainerLifecycleManager lifecycleManager, RegionResolver resolver) {
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
@@ -157,6 +202,8 @@ class DocDbContainerManagerTest {
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
lenient().when(logStreamer.attach(anyString(), anyString(), anyString(), anyString(), anyString()))
.thenAnswer(call -> mock(Closeable.class));
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
@@ -166,6 +213,6 @@ class DocDbContainerManagerTest {
when(docdb.dockerNetwork()).thenReturn(Optional.empty());
return new DocDbContainerManager(containerBuilder, lifecycleManager, logStreamer,
mock(ContainerDetector.class), config, new RegionResolver("us-east-1", "000000000000"));
mock(ContainerDetector.class), config, resolver);
}
}