fix(rds): advertise reachable endpoints (#2074)

RDS endpoints currently expose the proxy's container port even when
Docker publishes it on a random host port. That works when the host can
route to the container network, but fails with VM-backed Docker
runtimes.

Resolve the current container's published port when an external
endpoint host is configured while preserving the internal proxy port
used by the listener.
This commit is contained in:
Jan Waś authored and GitHub committed 2026-08-10 22:03:52 -04:00
1 parent 28e9f6ed63
commit f417164d42
9 files changed
+157 -13

No files matched your search

@@ -901,6 +901,9 @@ public interface EmulatorConfig {
@WithDefault("mariadb:11")
String defaultMariadbImage();
/** Hostname advertised for RDS endpoints. Uses published Docker ports when configured. */
Optional<String> endpointHost();
/** Docker network to attach DB containers to. Empty = default bridge. */
Optional<String> dockerNetwork();
}
@@ -3,6 +3,8 @@ package io.github.hectorvent.floci.core.common.docker;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.model.ContainerNetwork;
import com.github.dockerjava.api.model.ExposedPort;
import com.github.dockerjava.api.model.Ports;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -11,6 +13,8 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.concurrent.ConcurrentHashMap;
/**
* Resolves the Docker network used by the Floci container itself.
@@ -28,6 +32,7 @@ public class CurrentContainerNetworkResolver {
private final DockerClient dockerClient;
private final ContainerDetector containerDetector;
private final Map<Integer, Integer> cachedPublishedPorts = new ConcurrentHashMap<>();
private volatile Optional<CurrentContainerNetwork> cachedNetwork;
@@ -45,6 +50,18 @@ public class CurrentContainerNetworkResolver {
return resolve().map(CurrentContainerNetwork::ipAddress);
}
public OptionalInt resolvePublishedPort(int containerPort) {
Integer cachedPublishedPort = cachedPublishedPorts.get(containerPort);
if (cachedPublishedPort != null) {
return OptionalInt.of(cachedPublishedPort);
}
OptionalInt resolvedPublishedPort = detectPublishedPort(containerPort);
resolvedPublishedPort.ifPresent(port -> cachedPublishedPorts.putIfAbsent(containerPort, port));
Integer publishedPort = cachedPublishedPorts.get(containerPort);
return publishedPort == null ? OptionalInt.empty() : OptionalInt.of(publishedPort);
}
Optional<CurrentContainerNetwork> resolve() {
Optional<CurrentContainerNetwork> cached = cachedNetwork;
if (cached != null) {
@@ -54,6 +71,46 @@ public class CurrentContainerNetworkResolver {
return cachedNetwork;
}
private OptionalInt detectPublishedPort(int containerPort) {
if (!containerDetector.isRunningInContainer()) {
return OptionalInt.empty();
}
String containerId = currentContainerId();
if (containerId.isBlank()) {
LOG.debug("Could not determine current Docker container id");
return OptionalInt.empty();
}
try {
InspectContainerResponse inspect = dockerClient.inspectContainerCmd(containerId).exec();
Ports ports = inspect.getNetworkSettings().getPorts();
if (ports == null || ports.getBindings() == null) {
return OptionalInt.empty();
}
Ports.Binding[] bindings = ports.getBindings().get(ExposedPort.tcp(containerPort));
if (bindings == null || bindings.length == 0) {
return OptionalInt.empty();
}
for (Ports.Binding binding : bindings) {
if (binding == null) {
continue;
}
String hostPort = binding.getHostPortSpec();
if (hostPort != null && !hostPort.isBlank()) {
return OptionalInt.of(Integer.parseInt(hostPort));
}
}
return OptionalInt.empty();
} catch (Exception e) {
LOG.debugv("Could not resolve published port {0} for current Docker container {1}: {2}",
String.valueOf(containerPort), containerId, e.getMessage());
return OptionalInt.empty();
}
}
private Optional<CurrentContainerNetwork> detect() {
if (!containerDetector.isRunningInContainer()) {
return Optional.empty();
@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
import io.github.hectorvent.floci.core.common.docker.CurrentContainerNetworkResolver;
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
@@ -41,6 +42,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
@@ -88,6 +90,7 @@ public class RdsService implements Resettable {
private final EmulatorConfig config;
private final SecretsManagerService secretsManagerService;
private final DockerHostResolver dockerHostResolver;
private final CurrentContainerNetworkResolver currentContainerNetworkResolver;
private final Set<Integer> usedPorts = ConcurrentHashMap.newKeySet();
private static final Pattern IMAGE_TAG_VERSION_PATTERN = Pattern.compile("^(\\d+(?:\\.\\d+)*)(.*)$");
private static final Pattern SAFE_IMAGE_TAG_PATTERN = Pattern.compile("[A-Za-z0-9._-]+");
@@ -100,7 +103,8 @@ public class RdsService implements Resettable {
EmulatorConfig config,
StorageFactory storageFactory,
SecretsManagerService secretsManagerService,
DockerHostResolver dockerHostResolver) {
DockerHostResolver dockerHostResolver,
CurrentContainerNetworkResolver currentContainerNetworkResolver) {
this.containerManager = containerManager;
this.proxyManager = proxyManager;
this.ec2Service = ec2Service;
@@ -108,6 +112,7 @@ public class RdsService implements Resettable {
this.config = config;
this.secretsManagerService = secretsManagerService;
this.dockerHostResolver = dockerHostResolver;
this.currentContainerNetworkResolver = currentContainerNetworkResolver;
this.instances = storageFactory.create("rds", "rds-instances.json",
new TypeReference<Map<String, DbInstance>>() {});
this.clusters = storageFactory.create("rds", "rds-clusters.json",
@@ -132,7 +137,7 @@ public class RdsService implements Resettable {
StorageBackend<String, DbSubnetGroup> subnetGroups) {
this(containerManager, proxyManager, ec2Service, regionResolver, config,
instances, clusters, parameterGroups, clusterParameterGroups, subnetGroups,
null, null);
null, null, null);
}
RdsService(RdsContainerManager containerManager,
@@ -146,7 +151,8 @@ public class RdsService implements Resettable {
StorageBackend<String, DbClusterParameterGroup> clusterParameterGroups,
StorageBackend<String, DbSubnetGroup> subnetGroups,
SecretsManagerService secretsManagerService,
DockerHostResolver dockerHostResolver) {
DockerHostResolver dockerHostResolver,
CurrentContainerNetworkResolver currentContainerNetworkResolver) {
this.containerManager = containerManager;
this.proxyManager = proxyManager;
this.ec2Service = ec2Service;
@@ -154,6 +160,7 @@ public class RdsService implements Resettable {
this.config = config;
this.secretsManagerService = secretsManagerService;
this.dockerHostResolver = dockerHostResolver;
this.currentContainerNetworkResolver = currentContainerNetworkResolver;
this.instances = instances;
this.clusters = clusters;
this.parameterGroups = parameterGroups;
@@ -348,7 +355,7 @@ public class RdsService implements Resettable {
}
}
DbEndpoint endpoint = new DbEndpoint(mock ? "localhost" : proxyEndpointHost(), proxyPort);
DbEndpoint endpoint = mock ? new DbEndpoint("localhost", proxyPort) : proxyEndpoint(proxyPort);
DbInstance instance = new DbInstance(id, engine, engineVersion, masterUsername, masterPassword,
dbName, dbInstanceClass, allocatedStorage, DbInstanceStatus.AVAILABLE,
endpoint, iamEnabled, paramGroupName, dbClusterIdentifier, Instant.now(), proxyPort);
@@ -387,7 +394,8 @@ public class RdsService implements Resettable {
}
instances.put(id, instance);
LOG.infov("DB instance {0} created, engine={1}, endpoint=localhost:{2}", id, engine, String.valueOf(proxyPort));
LOG.infov("DB instance {0} created, engine={1}, endpoint={2}:{3}",
id, engine, endpoint.address(), String.valueOf(endpoint.port()));
return instance;
}
@@ -712,7 +720,7 @@ public class RdsService implements Resettable {
// Always reserve a unique port (even in mock) so endpoints stay distinct and usedPorts
// is consistent; mock mode only skips starting the container and auth proxy.
int proxyPort = allocateProxyPort();
DbEndpoint endpoint = new DbEndpoint(mock ? "localhost" : proxyEndpointHost(), proxyPort);
DbEndpoint endpoint = mock ? new DbEndpoint("localhost", proxyPort) : proxyEndpoint(proxyPort);
DbCluster cluster = new DbCluster(id, engine, engineVersion, masterUsername, masterPassword,
databaseName, DbInstanceStatus.AVAILABLE, endpoint, endpoint,
iamEnabled, new ArrayList<>(), paramGroupName, Instant.now(), proxyPort);
@@ -743,8 +751,8 @@ public class RdsService implements Resettable {
}
clusters.put(id, cluster);
LOG.infov("DB cluster {0} created (mock={1}), engine={2}, endpoint=localhost:{3}",
id, String.valueOf(mock), engine, String.valueOf(proxyPort));
LOG.infov("DB cluster {0} created (mock={1}), engine={2}, endpoint={3}:{4}",
id, String.valueOf(mock), engine, endpoint.address(), String.valueOf(endpoint.port()));
return cluster;
}
@@ -1221,6 +1229,19 @@ public class RdsService implements Resettable {
usedPorts.remove(port);
}
private DbEndpoint proxyEndpoint(int proxyPort) {
Optional<String> endpointHost = config.services().rds().endpointHost()
.filter(host -> !host.isBlank());
if (endpointHost.isEmpty()) {
return new DbEndpoint(proxyEndpointHost(), proxyPort);
}
int endpointPort = currentContainerNetworkResolver == null
? proxyPort
: currentContainerNetworkResolver.resolvePublishedPort(proxyPort).orElse(proxyPort);
return new DbEndpoint(endpointHost.get(), endpointPort);
}
private String proxyEndpointHost() {
return dockerHostResolver != null ? dockerHostResolver.resolve() : "localhost";
}
@@ -1240,8 +1261,9 @@ public class RdsService implements Resettable {
}
int proxyPort = reserveOrAllocateProxyPort(cluster.getProxyPort());
cluster.setProxyPort(proxyPort);
cluster.setEndpoint(new DbEndpoint(proxyEndpointHost(), proxyPort));
cluster.setReaderEndpoint(new DbEndpoint(proxyEndpointHost(), proxyPort));
DbEndpoint endpoint = proxyEndpoint(proxyPort);
cluster.setEndpoint(endpoint);
cluster.setReaderEndpoint(endpoint);
if (cluster.getDockerVolumeName() == null) {
cluster.setDockerVolumeName(volumeName(cluster.getVolumeId(), cluster.getDbClusterIdentifier()));
}
@@ -1283,7 +1305,7 @@ public class RdsService implements Resettable {
}
int proxyPort = reserveOrAllocateProxyPort(instance.getProxyPort());
instance.setProxyPort(proxyPort);
instance.setEndpoint(new DbEndpoint(proxyEndpointHost(), proxyPort));
instance.setEndpoint(proxyEndpoint(proxyPort));
try {
String backendHost;
int backendPort;