diff --git a/docs/configuration/advanced/application-yml.md b/docs/configuration/advanced/application-yml.md index 17ee5a24d0..3dfee5cbb0 100644 --- a/docs/configuration/advanced/application-yml.md +++ b/docs/configuration/advanced/application-yml.md @@ -164,6 +164,7 @@ floci: mock: false # true = clusters/instances created without Docker (useful for CI) proxy-base-port: 7001 proxy-max-port: 7099 + # endpoint-host: localhost # Hostname clients use; enables published-port translation in Docker default-postgres-image: "postgres:16-alpine" default-mysql-image: "mysql:8.0" default-mariadb-image: "mariadb:11" diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md index 1d63f6a1bf..7762a50b63 100644 --- a/docs/configuration/environment-variables.md +++ b/docs/configuration/environment-variables.md @@ -334,6 +334,7 @@ These services spawn Docker containers. They require access to the Docker socket | `FLOCI_SERVICES_RDS_MOCK` | `false` | When `true`, DB clusters and instances are created instantly without a real container or auth proxy (API only) | | `FLOCI_SERVICES_RDS_PROXY_BASE_PORT` | `7001` | First port in the RDS proxy range | | `FLOCI_SERVICES_RDS_PROXY_MAX_PORT` | `7099` | Last port in the RDS proxy range | +| `FLOCI_SERVICES_RDS_ENDPOINT_HOST` | _(auto-detected)_ | Hostname advertised in RDS endpoints; when set in Docker, Floci advertises each proxy's published host port | | `FLOCI_SERVICES_RDS_DEFAULT_POSTGRES_IMAGE` | `postgres:16-alpine` | Default PostgreSQL Docker image | | `FLOCI_SERVICES_RDS_DEFAULT_MYSQL_IMAGE` | `mysql:8.0` | Default MySQL Docker image | | `FLOCI_SERVICES_RDS_DEFAULT_MARIADB_IMAGE` | `mariadb:11` | Default MariaDB Docker image | diff --git a/docs/services/rds.md b/docs/services/rds.md index 5a9f5fff42..aeebaf1bc1 100644 --- a/docs/services/rds.md +++ b/docs/services/rds.md @@ -53,6 +53,7 @@ RDS Data API (`rds-data`) is documented separately because it uses REST JSON rou | `FLOCI_SERVICES_RDS_MOCK` | `false` | `true` = metadata only (no Docker container or auth proxy) | | `FLOCI_SERVICES_RDS_PROXY_BASE_PORT` | `7000` | First host port in the RDS proxy range | | `FLOCI_SERVICES_RDS_PROXY_MAX_PORT` | `7099` | Last host port in the RDS proxy range | +| `FLOCI_SERVICES_RDS_ENDPOINT_HOST` | _(auto-detected)_ | Hostname advertised in RDS endpoints; when set in Docker, Floci advertises each proxy's published host port | | `FLOCI_SERVICES_RDS_DEFAULT_POSTGRES_IMAGE` | `postgres:16-alpine` | Docker image for PostgreSQL instances | | `FLOCI_SERVICES_RDS_DEFAULT_MYSQL_IMAGE` | `mysql:8.0` | Docker image for MySQL instances | | `FLOCI_SERVICES_RDS_DEFAULT_MARIADB_IMAGE` | `mariadb:11` | Docker image for MariaDB instances | @@ -61,6 +62,11 @@ RDS Data API (`rds-data`) is documented separately because it uses REST JSON rou RDS requires the Docker socket and port range exposure. For private registry authentication and other Docker settings see [Docker Configuration](../configuration/docker.md). +When Docker publishes RDS proxy ports dynamically, set `FLOCI_SERVICES_RDS_ENDPOINT_HOST` to the +hostname used by clients. Floci inspects its own container through the Docker socket and returns the +corresponding published port from `DescribeDBInstances` and `DescribeDBClusters`. Leave the setting +unset to retain the auto-detected endpoint host and configured proxy port. + ```yaml services: floci: diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index 3409b2cd21..5056eb85a3 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -901,6 +901,9 @@ public interface EmulatorConfig { @WithDefault("mariadb:11") String defaultMariadbImage(); + /** Hostname advertised for RDS endpoints. Uses published Docker ports when configured. */ + Optional endpointHost(); + /** Docker network to attach DB containers to. Empty = default bridge. */ Optional dockerNetwork(); } diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/CurrentContainerNetworkResolver.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/CurrentContainerNetworkResolver.java index 3bae761a27..e28ed6065f 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/docker/CurrentContainerNetworkResolver.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/CurrentContainerNetworkResolver.java @@ -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 cachedPublishedPorts = new ConcurrentHashMap<>(); private volatile Optional 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 resolve() { Optional 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 detect() { if (!containerDetector.isRunningInContainer()) { return Optional.empty(); diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java index 53f38a7893..3f80260ca0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java @@ -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 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>() {}); this.clusters = storageFactory.create("rds", "rds-clusters.json", @@ -132,7 +137,7 @@ public class RdsService implements Resettable { StorageBackend 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 clusterParameterGroups, StorageBackend 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 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; diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 8e1819fe96..b5c23bf726 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -265,6 +265,7 @@ floci: mock: false # FLOCI_SERVICES_RDS_MOCK — true = metadata only, no Docker (useful for CI) proxy-base-port: 7001 proxy-max-port: 7099 + # endpoint-host: localhost # Hostname clients use; enables published-port translation in Docker default-postgres-image: "postgres:16-alpine" default-mysql-image: "mysql:8.0" default-mariadb-image: "mariadb:11" diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/CurrentContainerNetworkResolverTest.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/CurrentContainerNetworkResolverTest.java index 3fd4786e5d..0fede063ba 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/docker/CurrentContainerNetworkResolverTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/CurrentContainerNetworkResolverTest.java @@ -4,11 +4,14 @@ import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.command.InspectContainerCmd; 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 org.junit.jupiter.api.Test; import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; +import java.util.OptionalInt; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -52,6 +55,35 @@ class CurrentContainerNetworkResolverTest { assertTrue(resolver.resolveNetworkName().isEmpty()); } + @Test + void resolvePublishedPort_retriesUntilSuccessfulAndCachesResult() { + DockerClient dockerClient = mock(DockerClient.class); + ContainerDetector containerDetector = mock(ContainerDetector.class); + when(containerDetector.isRunningInContainer()).thenReturn(true); + + InspectContainerCmd inspectCmd = mock(InspectContainerCmd.class); + InspectContainerResponse inspect = mock(InspectContainerResponse.class, RETURNS_DEEP_STUBS); + Ports ports = new Ports(); + ports.getBindings().put(ExposedPort.tcp(7000), new Ports.Binding[] {null}); + when(dockerClient.inspectContainerCmd("floci-container")).thenReturn(inspectCmd); + when(inspectCmd.exec()).thenReturn(inspect); + when(inspect.getNetworkSettings().getPorts()).thenReturn(ports); + + CurrentContainerNetworkResolver resolver = + new TestResolver(dockerClient, containerDetector, "floci-container"); + + assertTrue(resolver.resolvePublishedPort(7000).isEmpty()); + + ports.getBindings().put(ExposedPort.tcp(7000), new Ports.Binding[] { + null, + Ports.Binding.bindPort(49173) + }); + assertEquals(OptionalInt.of(49173), resolver.resolvePublishedPort(7000)); + + ports.getBindings().put(ExposedPort.tcp(7000), new Ports.Binding[] {Ports.Binding.bindPort(49174)}); + assertEquals(OptionalInt.of(49173), resolver.resolvePublishedPort(7000)); + } + private static Map networks(String firstName, String firstIp, String secondName, String secondIp) { Map networks = new LinkedHashMap<>(); diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java index 1720e86641..4545647e35 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.rds; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; +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.InMemoryStorage; import io.github.hectorvent.floci.core.storage.StorageBackend; @@ -29,6 +30,8 @@ import org.mockito.ArgumentCaptor; import java.util.Collection; import java.util.List; import java.util.Map; +import java.util.Optional; +import java.util.OptionalInt; import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.*; @@ -187,7 +190,7 @@ class RdsServiceTest { when(dockerHostResolver.resolve()).thenReturn("floci.local"); RdsService service = new RdsService(containerManager, proxyManager, ec2Service, regionResolver, config, new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), - new InMemoryStorage<>(), new InMemoryStorage<>(), null, dockerHostResolver); + new InMemoryStorage<>(), new InMemoryStorage<>(), null, dockerHostResolver, null); DbInstance instance = service.createDbInstance("mydb", "postgres", "13", "admin", "password", "dbname", "db.t3.micro", @@ -196,6 +199,24 @@ class RdsServiceTest { assertEquals("floci.local", instance.getEndpoint().address()); } + @Test + void dbInstanceEndpointUsesPublishedProxyPort() { + CurrentContainerNetworkResolver currentContainerNetworkResolver = mock(CurrentContainerNetworkResolver.class); + when(config.services().rds().endpointHost()).thenReturn(Optional.of("localhost")); + when(currentContainerNetworkResolver.resolvePublishedPort(7000)).thenReturn(OptionalInt.of(49173)); + RdsService service = new RdsService(containerManager, proxyManager, ec2Service, regionResolver, config, + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), null, null, currentContainerNetworkResolver); + + DbInstance instance = service.createDbInstance("mydb", "postgres", "13", + "admin", "password", "dbname", "db.t3.micro", + 20, false, null, null, null); + + assertEquals("localhost", instance.getEndpoint().address()); + assertEquals(49173, instance.getEndpoint().port()); + assertEquals(7000, instance.getProxyPort()); + } + @Test void createDbInstanceWithManagedMasterPasswordCreatesSecret() { SecretsManagerService secretsManager = mock(SecretsManagerService.class); @@ -1114,7 +1135,7 @@ class RdsServiceTest { SecretsManagerService secretsManager) { return new RdsService(containerManager, proxyManager, ec2Service, regionResolver, config, instances, clusters, parameterGroups, clusterParameterGroups, new InMemoryStorage<>(), - secretsManager, null); + secretsManager, null, null); } private static List defaultSubnets() {