Light, fluffy, and always free - The AWS Local Emulator alternative
fix(core): give launched containers the port Floci listens on (#5754)
Allen Sanborn8362d0817d4d
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerReachableEndpoint.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerReachableEndpoint.javaindex 76172271a8..a76dc21d03 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerReachableEndpoint.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerReachableEndpoint.java@@ -21,6 +21,7 @@ import org.eclipse.microprofile.config.inject.ConfigProperty;* <li>{@code Ec2ContainerManager}, for the {@code AWS_ENDPOINT_URL} of EC2 instance containers</li>* <li>{@code CustomResourceCfnProvisioner}, for the {@code ResponseURL} a custom resource* Lambda PUTs its result to</li>+ * <li>{@code FlociDuckClient}, for the S3 endpoint the DuckDB sidecar calls</li>* </ul>** <p>Kubernetes pods do not use it: {@code KubernetesFlociAddressResolver} builds their endpoint@@ -56,10 +57,14 @@ public class ContainerReachableEndpoint {* listener is {@code TlsProxyServer} on {@code floci.port}.*/public String baseUrl() {- int flociPort = config.tls().enabled() ? config.port() : httpPort;String flociHostname = embeddedDnsServer.getServerIp().isPresent()? config.hostname().orElse(EmbeddedDnsServer.DEFAULT_SUFFIX): dockerHostResolver.resolve();- return "http://" + flociHostname + ":" + flociPort;+ return "http://" + flociHostname + ":" + port();+ }++ /** The port of {@link #baseUrl()}: the one a launched container can reach Floci on. */+ public int port() {+ return config.tls().enabled() ? config.port() : httpPort;}}diff --git a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.javaindex 4bf9c42e81..8ee4df35e7 100644--- a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java+++ b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java@@ -61,7 +61,6 @@ import java.util.Optional;public class EmulatorLifecycle {private static final Logger LOG = Logger.getLogger(EmulatorLifecycle.class);- private static final int TLS_HTTP_BACKEND_PORT = 4510;@ConfigProperty(name = "quarkus.application.version", defaultValue = "")Optional<String> appVersion = Optional.empty();@@ -74,6 +73,10 @@ public class EmulatorLifecycle {@ConfigProperty(name = "localstack.parity", defaultValue = "true")String localstackParity = "true";+ /** The port Quarkus HTTP listens on; under TLS, TlsConfigSource pins it to the internal backend. */+ @ConfigProperty(name = "quarkus.http.port")+ int httpPort = 4566;+private final StorageFactory storageFactory;private final ServiceRegistry serviceRegistry;private final EmulatorConfig config;@@ -298,12 +301,10 @@ public class EmulatorLifecycle {}void onHttpStart(@ObservesAsync HttpServerStart event) {- // Non-TLS: Quarkus listens on floci.port (quarkus.http.port: ${floci.port} in- // application.yml). TLS mode: TlsConfigSource pins the HTTP backend to 4510 and the- // public port is served by TlsProxyServer. Comparing against a hardcoded 4566 here- // made start/ready hooks never run when FLOCI_PORT was non-default (#2437).- int expectedPort = config.tls().enabled() ? TLS_HTTP_BACKEND_PORT : config.port();- if (event.options().getPort() != expectedPort) {+ // Compare against quarkus.http.port, not floci.port: it can be overridden alone, and+ // under TLS it is the internal backend while TlsProxyServer serves floci.port. A+ // hardcoded 4566 here made start/ready hooks never run on a non-default port (#2437).+ if (event.options().getPort() != httpPort) {return;}boolean hasStart = initializationHooksRunner.hasHooks(InitializationHook.START);diff --git a/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildRunner.java b/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildRunner.javaindex 3424d00971..cdc90cfc55 100644--- a/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildRunner.java+++ b/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildRunner.java@@ -13,6 +13,7 @@ import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;import io.github.hectorvent.floci.core.common.docker.ContainerDetector;import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;+import io.github.hectorvent.floci.core.common.docker.ContainerReachableEndpoint;import io.github.hectorvent.floci.core.common.docker.ContainerSpec;import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;import io.github.hectorvent.floci.services.codebuild.BuildspecParser.ParsedArtifacts;@@ -73,6 +74,7 @@ public class CodeBuildRunner implements ContainerTeardown {private final EmulatorConfig config;private final ContainerDetector containerDetector;private final RegionResolver regionResolver;+ private final ContainerReachableEndpoint containerEndpoint;private final ConcurrentHashMap<String, String> runningContainers = new ConcurrentHashMap<>();private final ConcurrentHashMap<String, AtomicBoolean> stopFlags = new ConcurrentHashMap<>();@@ -87,7 +89,8 @@ public class CodeBuildRunner implements ContainerTeardown {SecretsManagerService secretsManagerService,EmulatorConfig config,ContainerDetector containerDetector,- RegionResolver regionResolver) {+ RegionResolver regionResolver,+ ContainerReachableEndpoint containerEndpoint) {this.dockerClient = dockerClient;this.containerBuilder = containerBuilder;this.lifecycleManager = lifecycleManager;@@ -98,6 +101,7 @@ public class CodeBuildRunner implements ContainerTeardown {this.config = config;this.containerDetector = containerDetector;this.regionResolver = regionResolver;+ this.containerEndpoint = containerEndpoint;}/**@@ -485,12 +489,12 @@ public class CodeBuildRunner implements ContainerTeardown {return result;}- private String resolveEndpointUrl() {+ String resolveEndpointUrl() {if (containerDetector.isRunningInContainer()) {String suffix = config.hostname().orElse(EmbeddedDnsServer.DEFAULT_SUFFIX);- return "http://" + suffix + ":" + config.port();+ return "http://" + suffix + ":" + containerEndpoint.port();} else {- return "http://host.docker.internal:" + config.port();+ return "http://host.docker.internal:" + containerEndpoint.port();}}diff --git a/src/main/java/io/github/hectorvent/floci/services/floci/duck/FlociDuckClient.java b/src/main/java/io/github/hectorvent/floci/services/floci/duck/FlociDuckClient.javaindex 5f6b5be6a1..034aa06ce8 100644--- a/src/main/java/io/github/hectorvent/floci/services/floci/duck/FlociDuckClient.java+++ b/src/main/java/io/github/hectorvent/floci/services/floci/duck/FlociDuckClient.java@@ -3,8 +3,7 @@ package io.github.hectorvent.floci.services.floci.duck;import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;import io.github.hectorvent.floci.config.EmulatorConfig;-import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;-import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;+import io.github.hectorvent.floci.core.common.docker.ContainerReachableEndpoint;import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Inject;@@ -29,21 +28,18 @@ public class FlociDuckClient {private final FlociDuckManager duckManager;private final EmulatorConfig config;- private final EmbeddedDnsServer embeddedDnsServer;- private final DockerHostResolver dockerHostResolver;+ private final ContainerReachableEndpoint containerEndpoint;private final ObjectMapper mapper;private final HttpClient httpClient;@Injectpublic FlociDuckClient(FlociDuckManager duckManager,EmulatorConfig config,- EmbeddedDnsServer embeddedDnsServer,- DockerHostResolver dockerHostResolver,+ ContainerReachableEndpoint containerEndpoint,ObjectMapper mapper) {this.duckManager = duckManager;this.config = config;- this.embeddedDnsServer = embeddedDnsServer;- this.dockerHostResolver = dockerHostResolver;+ this.containerEndpoint = containerEndpoint;this.mapper = mapper;this.httpClient = HttpClient.newHttpClient();}@@ -125,7 +121,7 @@ public class FlociDuckClient {if (setupDdl != null && !setupDdl.isBlank()) {body.put("setup_sql", setupDdl);}- body.put("s3_endpoint", resolveFlociEndpoint());+ body.put("s3_endpoint", containerEndpoint.baseUrl());body.put("s3_region", config.defaultRegion());// A 12-digit access key flows through AccountResolver and selects the// matching account partition for any S3 read/write the SQL performs.@@ -136,19 +132,6 @@ public class FlociDuckClient {return body;}- /**- * Returns the Floci S3 endpoint URL as reachable from inside a floci-duck container.- * Uses the embedded DNS hostname when the DNS server is active, falls back to the- * raw Docker host IP for local dev mode.- */- private String resolveFlociEndpoint() {- int port = URI.create(config.baseUrl()).getPort();- String hostname = embeddedDnsServer.getServerIp().isPresent()- ? config.hostname().orElse(EmbeddedDnsServer.DEFAULT_SUFFIX)- : dockerHostResolver.resolve();- return "http://" + hostname + ":" + port;- }-private String post(String url, Map<String, Object> body, String operation) {try {String json = mapper.writeValueAsString(body);diff --git a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.javaindex 3eed1f8c23..a0fa7949ef 100644--- a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java+++ b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java@@ -418,7 +418,6 @@ class EmulatorLifecycleTest {@Test@DisplayName("onHttpStart on port 4566 (non-TLS) triggers hook execution and marks lifecycle completed")void onHttpStart_nonTls_triggersHooksOnPort4566() throws IOException, InterruptedException {- when(tlsConfig.enabled()).thenReturn(false);when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(true);when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false);@@ -432,7 +431,7 @@ class EmulatorLifecycleTest {@DisplayName("onHttpStart on a non-default floci.port (non-TLS) triggers hook execution (#2437)")void onHttpStart_nonTls_triggersHooksOnCustomPort() throws IOException, InterruptedException {Mockito.lenient().when(config.port()).thenReturn(4577);- when(tlsConfig.enabled()).thenReturn(false);+ emulatorLifecycle.httpPort = 4577;when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(true);when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(true);@@ -444,10 +443,23 @@ class EmulatorLifecycleTest {verify(initLifecycleState).markReadyCompleted();}+ @Test+ @DisplayName("onHttpStart on quarkus.http.port overridden alone (non-TLS) triggers hook execution")+ void onHttpStart_nonTls_triggersHooksOnHttpPortOverride() throws IOException, InterruptedException {+ // QUARKUS_HTTP_PORT=4811 with floci.port left at 4566: the server listens on 4811.+ emulatorLifecycle.httpPort = 4811;+ when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(true);+ when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false);++ emulatorLifecycle.onHttpStart(new HttpServerStart(new HttpServerOptions().setPort(4811)));++ verify(initializationHooksRunner).run(InitializationHook.START);+ verify(initLifecycleState).markStartCompleted();+ }+@Test@DisplayName("onHttpStart on wrong port (non-TLS) is ignored")void onHttpStart_nonTls_ignoresWrongPort() throws IOException, InterruptedException {- when(tlsConfig.enabled()).thenReturn(false);emulatorLifecycle.onHttpStart(new HttpServerStart(new HttpServerOptions().setPort(4510)));@@ -458,7 +470,8 @@ class EmulatorLifecycleTest {@Test@DisplayName("onHttpStart on port 4510 (TLS mode) triggers hook execution and marks lifecycle completed")void onHttpStart_tls_triggersHooksOnBackendPort4510() throws IOException, InterruptedException {- when(tlsConfig.enabled()).thenReturn(true);+ // TlsConfigSource pins quarkus.http.port to the internal HTTP backend.+ emulatorLifecycle.httpPort = 4510;when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(true);when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false);@@ -471,7 +484,8 @@ class EmulatorLifecycleTest {@Test@DisplayName("onHttpStart on port 4566 (TLS mode) is ignored — public port is not the backend port")void onHttpStart_tls_ignoresPublicPort4566() throws IOException, InterruptedException {- when(tlsConfig.enabled()).thenReturn(true);+ // TlsConfigSource pins quarkus.http.port to the internal HTTP backend.+ emulatorLifecycle.httpPort = 4510;emulatorLifecycle.onHttpStart(new HttpServerStart(new HttpServerOptions().setPort(4566)));@@ -482,7 +496,6 @@ class EmulatorLifecycleTest {@Test@DisplayName("onHttpStart exits the process when a startup hook is interrupted")void onHttpStart_hookInterrupted_exitsProcess() throws IOException, InterruptedException {- when(tlsConfig.enabled()).thenReturn(false);when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(true);when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false);doThrow(new InterruptedException("interrupted"))@@ -741,7 +754,6 @@ class EmulatorLifecycleTest {@Test@DisplayName("Should emit the parity \"Ready.\" line on the deferred onHttpStart ready path too")void shouldEmitParityReadyLineOnHttpStartPath() throws IOException, InterruptedException {- when(tlsConfig.enabled()).thenReturn(false);when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(true);when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false);diff --git a/src/test/java/io/github/hectorvent/floci/services/codebuild/CodeBuildRunnerTest.java b/src/test/java/io/github/hectorvent/floci/services/codebuild/CodeBuildRunnerTest.javaindex 68762a7074..cb81bd4122 100644--- a/src/test/java/io/github/hectorvent/floci/services/codebuild/CodeBuildRunnerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/codebuild/CodeBuildRunnerTest.java@@ -9,6 +9,9 @@ import com.github.dockerjava.api.command.InspectExecCmd;import com.github.dockerjava.api.command.InspectExecResponse;import com.github.dockerjava.api.model.Frame;import com.github.dockerjava.api.model.StreamType;+import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.core.common.docker.ContainerDetector;+import io.github.hectorvent.floci.core.common.docker.ContainerReachableEndpoint;import org.junit.jupiter.api.Test;import java.nio.charset.StandardCharsets;@@ -33,7 +36,7 @@ class CodeBuildRunnerTest {int chunkCount = 320;String lastLine = "error: build step failed\n";DockerClient dockerClient = dockerClientStreaming(chunk, chunkCount, lastLine, 2L);- CodeBuildRunner runner = new CodeBuildRunner(dockerClient, null, null, null, null, null, null, null, null, null);+ CodeBuildRunner runner = new CodeBuildRunner(dockerClient, null, null, null, null, null, null, null, null, null, null);CodeBuildRunner.PhaseResult result = runner.runPhase("container-1", "/src", List.of(),List.of("./build.sh"), 60, new AtomicBoolean(false));@@ -46,7 +49,7 @@ class CodeBuildRunnerTest {@Testvoid failureMessageIgnoresLongTrailingWhitespace() {DockerClient dockerClient = dockerClientStreaming(new byte[0], 0, "tests failed" + "\n".repeat(10_000), 1L);- CodeBuildRunner runner = new CodeBuildRunner(dockerClient, null, null, null, null, null, null, null, null, null);+ CodeBuildRunner runner = new CodeBuildRunner(dockerClient, null, null, null, null, null, null, null, null, null, null);CodeBuildRunner.PhaseResult result = runner.runPhase("container-1", "/src", List.of(),List.of("./test.sh"), 60, new AtomicBoolean(false));@@ -54,6 +57,20 @@ class CodeBuildRunnerTest {assertEquals("Exit code 1: tests failed", result.errorMessage());}+ @Test+ void endpointUrlUsesListenPortNotFlociPort() {+ // QUARKUS_HTTP_PORT=4811 with floci.port left at 4566: the server listens on 4811.+ EmulatorConfig config = mock(EmulatorConfig.class);+ when(config.tls()).thenReturn(mock(EmulatorConfig.TlsConfig.class));+ when(config.port()).thenReturn(4566);+ ContainerDetector containerDetector = mock(ContainerDetector.class);+ ContainerReachableEndpoint endpoint = new ContainerReachableEndpoint(config, null, null, 4811);+ CodeBuildRunner runner = new CodeBuildRunner(null, null, null, null, null, null, null,+ config, containerDetector, null, endpoint);++ assertEquals("http://host.docker.internal:4811", runner.resolveEndpointUrl());+ }+private static DockerClient dockerClientStreaming(byte[] chunk, int chunkCount, String lastLine, long exitCode) {DockerClient dockerClient = mock(DockerClient.class);diff --git a/src/test/java/io/github/hectorvent/floci/services/floci/duck/FlociDuckClientServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/floci/duck/FlociDuckClientServiceTest.javaindex e222e4e21c..3585d955c6 100644--- a/src/test/java/io/github/hectorvent/floci/services/floci/duck/FlociDuckClientServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/floci/duck/FlociDuckClientServiceTest.java@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;import com.sun.net.httpserver.HttpServer;import io.github.hectorvent.floci.config.EmulatorConfig;import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;+import io.github.hectorvent.floci.core.common.docker.ContainerReachableEndpoint;import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;import org.junit.jupiter.api.AfterEach;import org.junit.jupiter.api.Test;@@ -53,11 +54,44 @@ class FlociDuckClientServiceTest {when(config.hostname()).thenReturn(Optional.of("floci.internal"));when(embeddedDnsServer.getServerIp()).thenReturn(Optional.of("127.0.0.1"));- FlociDuckClient client = new FlociDuckClient(- duckManager, config, embeddedDnsServer, dockerHostResolver, mapper);+ when(config.tls()).thenReturn(mock(EmulatorConfig.TlsConfig.class));++ FlociDuckClient client = new FlociDuckClient(duckManager, config,+ new ContainerReachableEndpoint(config, dockerHostResolver, embeddedDnsServer, 4566), mapper);client.execute("CREATE VIEW example AS SELECT 1", "", null);assertEquals("CREATE VIEW example AS SELECT 1", requestBody.get().path("sql").asText());assertFalse(requestBody.get().has("output_s3_path"));}++ @Test+ void s3EndpointUsesListenPortNotAdvertisedPort() throws Exception {+ // docker run -p 4811:4566 -e FLOCI_BASE_URL=http://localhost:4811: 4811 exists only on the+ // host, so the sidecar must call Floci on the port it listens on.+ ObjectMapper mapper = new ObjectMapper();+ AtomicReference<JsonNode> requestBody = new AtomicReference<>();+ server = HttpServer.create(new InetSocketAddress(0), 0);+ server.createContext("/execute", exchange -> {+ requestBody.set(mapper.readTree(exchange.getRequestBody().readAllBytes()));+ exchange.sendResponseHeaders(200, -1);+ exchange.close();+ });+ server.start();++ FlociDuckManager duckManager = mock(FlociDuckManager.class);+ EmulatorConfig config = mock(EmulatorConfig.class);+ DockerHostResolver dockerHostResolver = mock(DockerHostResolver.class);+ EmbeddedDnsServer embeddedDnsServer = mock(EmbeddedDnsServer.class);+ when(duckManager.ensureReady()).thenReturn("http://localhost:" + server.getAddress().getPort());+ when(config.baseUrl()).thenReturn("http://localhost:4811");+ when(config.tls()).thenReturn(mock(EmulatorConfig.TlsConfig.class));+ when(embeddedDnsServer.getServerIp()).thenReturn(Optional.empty());+ when(dockerHostResolver.resolve()).thenReturn("172.18.0.2");++ FlociDuckClient client = new FlociDuckClient(duckManager, config,+ new ContainerReachableEndpoint(config, dockerHostResolver, embeddedDnsServer, 4566), mapper);+ client.execute("SELECT 1", "", null);++ assertEquals("http://172.18.0.2:4566", requestBody.get().path("s3_endpoint").asText());+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftSpectrumIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftSpectrumIntegrationTest.javaindex f123ed8d94..f685aec556 100644--- a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftSpectrumIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftSpectrumIntegrationTest.java@@ -53,7 +53,8 @@ class RedshiftSpectrumIntegrationTest {public static class SpectrumProfile implements QuarkusTestProfile {@Overridepublic Map<String, String> getConfigOverrides() {- return Map.of("quarkus.http.test-port", "17866", "floci.base-url", "http://localhost:17866",+ return Map.of("quarkus.http.test-port", "17866", "quarkus.http.port", "17866",+ "floci.base-url", "http://localhost:17866","floci.docker.resource-namespace", "spectrum-relational-tests");}}diff --git a/src/test/java/io/github/hectorvent/floci/testing/SynchronousBillingEmissionProfile.java b/src/test/java/io/github/hectorvent/floci/testing/SynchronousBillingEmissionProfile.javaindex 9a70b7ad3f..e714a4f2a4 100644--- a/src/test/java/io/github/hectorvent/floci/testing/SynchronousBillingEmissionProfile.java+++ b/src/test/java/io/github/hectorvent/floci/testing/SynchronousBillingEmissionProfile.java@@ -16,6 +16,7 @@ public class SynchronousBillingEmissionProfile implements QuarkusTestProfile {public Map<String, String> getConfigOverrides() {return Map.of("quarkus.http.test-port", "4566",+ "quarkus.http.port", "4566","floci.base-url", "http://localhost:4566","floci.services.cur.emit-mode", "synchronous","floci.services.bcm-data-exports.emit-mode", "synchronous");