feat(emr): start a cluster's Trino with it and reach it from outside Docker (#9534)

A cluster with Floci's Trino now starts its primary node, and Trino on it,
in the background as it becomes ready, steps or none, the way an
application UI link already does; the cluster goes WAITING as before.

Clients outside the cluster reach Trino through Floci on a host of the
cluster's own, <cluster-id>.emr-trino.<Floci's host>, through the app UI
proxy: Trino's port is published on the primary node's loopback like the
node's web interfaces, the request keeps its Host, which Trino names its
next pages by, and goes on with X-Forwarded-Proto, which Trino honours
with http-server.process-forwarded. Until Trino answers the host gives a
503, which Trino's clients retry, and starts the node where it is not
running; an ending or ended cluster gives a 404. Floci's TLS certificate
names the new host label.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-26 12:49:29 -04:00
1 parent 31befa5e92
commit ad51bc5ecc
18 files changed
+595 -31

No files matched your search

+1 -1
View File
@@ -103,7 +103,7 @@ grep -vE "$RUNNER|$DOCKER_E2E" "$work/selected.txt" > "$work/standard.txt" || tr
# Timeouts in minutes: each group's checks run one after another, plus about twenty minutes for compilation, the image
# and the prefetch (see nightly-checks.yml). docker-e2e's tests took about 23 minutes in the shards on 2026-11-23.
matrix='[]'
for entry in standard:359 docker-runner:221 docker-e2e:60; do
for entry in standard:359 docker-runner:228 docker-e2e:60; do
group="${entry%%:*}"
timeout="${entry##*:}"
count=$(wc -l < "$work/$group.txt" | tr -d ' ')
+2 -2
View File
@@ -77,8 +77,8 @@ jobs:
# EmrClusterShrinkNightlyIntegrationTest's sixteen-minute method and two-minute setup, and
# EmrContainersSparkNightlyIntegrationTest's three six-minute methods, eleven-minute method, two-minute setup before
# each and 21-minute image pull, EmrContainersGatewayNightlyIntegrationTest's twenty-four-minute, seven-minute and
# eighteen-minute methods and 21-minute image pull, and EmrTrinoNightlyIntegrationTest's three seven-minute
# methods and ten-minute image pull, 201 minutes. docker-e2e holds the *DockerNightlyIntegrationTest
# eighteen-minute methods and 21-minute image pull, and EmrTrinoNightlyIntegrationTest's four seven-minute
# methods and ten-minute image pull, 208 minutes. docker-e2e holds the *DockerNightlyIntegrationTest
# classes, about 23 minutes of tests on 2026-11-23 when they still ran in the shards. A check added, or a bound
# raised, raises its group's timeout with it, so a slow check fails with its own message.
strategy:
+26 -13
View File
@@ -851,12 +851,25 @@ holding the driver and its executors, or a command or a script. The cluster itse
cluster's EC2 instance profile's role, with a session of its own, as the metastore does. A step runs `trino-cli`, as
the Release Guide's "Start the Trino CLI by running trino-cli" does on the primary node, through `command-runner.jar`:
the CLI of the same Trino, which Floci copies into the cluster's image from Trino's image as it makes it, on the
image's Java 17, connects to the coordinator unless the step names a `--server` of its own. The cluster's first step
starts Trino, with its HDFS, and waits up to three minutes until it has answered a query for ten seconds, as Trino
runs a query that reads a catalog once it has learnt that its node serves the catalog, a Trino that does not failing
the step; the cluster's next steps have it at once. It goes before its primary node, whose network it shares, when the
cluster ends, on a reset and on a shutdown, and one an earlier Floci left goes when the EMR service starts, whatever
its cluster, as its session went with that Floci: the cluster's next step starts another.
image's Java 17, connects to the coordinator unless the step names a `--server` of its own. As the cluster becomes
ready, its bootstrap done, Floci starts its primary node, with its HDFS and Trino, in the background, steps or none,
as an application UI link does, the cluster `WAITING` or `RUNNING` meanwhile; Trino is ready once it has answered a
query for ten seconds, within three minutes, as Trino runs a query that reads a catalog once it has learnt that its
node serves the catalog. A step that comes first starts them itself and waits for Trino, a Trino that does not answer
failing the step; the cluster's next steps have it at once. Clients outside the cluster reach it through Floci, on a
host of the cluster's own, `http://<cluster-id>.emr-trino.<floci-host>:<port>`, as EMR's reach Trino's port on the
primary node: Trino's CLI with `--server=http://j-2AXXXXXXGAPLF.emr-trino.localhost:4566`, or
`jdbc:trino://j-2AXXXXXXGAPLF.emr-trino.localhost:4566/hive`. Floci's host must resolve its subdomains, as for
application UIs: `localhost` and `localhost.floci.io` do, and Floci's TLS certificate names `*.emr-trino.localhost`
and `*.emr-trino.localhost.floci.io`. The host takes no credentials, as Floci's Trino has no authentication, so
whoever reaches Floci's port reaches the cluster's Trino. Trino names a query's next pages by the host it was asked
on, and by the scheme the client used, which Floci passes on as `X-Forwarded-Proto` (Floci sets
`http-server.process-forwarded` in `config.properties`). Until Trino answers, the host answers with a `503`, which
Trino's clients ask again on, and starts the primary node where it is not running, as after a restart; once the
cluster is ending or has ended, a `404`. Trino's port is published on the primary node's container, on the host's
loopback interface alone, as the node's web interfaces' are. It goes before its primary node, whose network it shares,
when the cluster ends, on a reset and on a shutdown, and one an earlier Floci left goes when the EMR service starts,
whatever its cluster, as its session went with that Floci: the cluster's next step, or a client, starts another.
* **S3DistCp**: the image has no `s3-dist-cp`, so a `command-runner.jar` step whose
first argument is `s3-dist-cp`, the Release Guide's form, runs Floci's own program instead, through
`spark-submit` in the step's container, copying through Hadoop's file systems: `--src` and `--dest` take
@@ -1073,15 +1086,15 @@ holding the driver and its executors, or a command or a script. The cluster itse
- **Pig is Apache's 0.18.0, and only with `pig.enabled`.** EMR's 7.x releases ship Pig 0.17.0, whose Apache build is
for Hadoop 2; no AWS image carries Pig, so Floci downloads Apache's 0.18.0, for Hadoop 3, when it is enabled, and
runs it on the image's Tez (see **Pig steps**).
- **Trino is the Trino project's build, from the first step, and only with `trino.enabled`.** EMR ships its own
`-amzn` builds; Floci runs the Trino project's image of the same version (see **Trino**), so a connector that
image has no plugin for stops Trino, with what it logged, and the step. The cluster's first step starts it, as it
does the primary node's HDFS, where EMR's runs once the cluster is up, and Floci gives no address to reach it from
outside the cluster's network. Its `trino-connector-*` classifications and `trino-config` apply; `trino-node`,
- **Trino is the Trino project's build, started after the cluster is up, and only with `trino.enabled`.** EMR ships its
own `-amzn` builds; Floci runs the Trino project's image of the same version (see **Trino**), so a connector that
image has no plugin for stops Trino, with what it logged, and the step. Floci starts it in the background as the
cluster becomes ready, so the cluster is `WAITING` before Trino answers, where EMR's runs once the cluster is up, and
a client meanwhile gets a `503`. Its `trino-connector-*` classifications and `trino-config` apply; `trino-node`,
`trino-log`, `trino-env`, `trino-password-authenticator` and `trino-exchange-manager` do not yet. With
`docker-network` set to `host`, `container:<id>` or `none` it does not run, as the metastore service does not. From
`emr-7.14.0` on, "When you select Trino as the only application at launch, Amazon EMR no longer starts YARN and
HDFS"; Floci's primary node still runs the HDFS, beside the metastore.
`emr-7.14.0` on, "When you select Trino as the only application at launch, Amazon EMR no longer starts YARN and HDFS";
Floci's primary node still runs the HDFS, beside the metastore.
- **Tez's intermediate data is not compressed on YARN.** The images name the LZO codec for it, whose native library they
lack, so Floci turns that compression off, which a `tez-site` classification can turn back on with a codec they have.
- **No Hive metastore service in a network namespace the steps share.** With `docker-network` set to `host` or
@@ -79,6 +79,7 @@ public class TlsConfigSource implements ConfigSource {
"*.execute-api.localhost.localstack.cloud",
"*.cloudfront.localhost.floci.io", "*.cloudfront.localhost",
"*.emrappui.localhost.floci.io", "*.emrappui.localhost",
"*.emr-trino.localhost.floci.io", "*.emr-trino.localhost",
"*.emr-serverless-ui.localhost.floci.io", "*.emr-serverless-ui.localhost",
"host.docker.internal"));
for (String region : AwsRegions.KNOWN_IDS.stream().sorted().toList()) {
@@ -141,6 +141,7 @@ public class AppUiProxy {
}
}
options.putHeader("accept-encoding", "identity");
route.headers().forEach(options::putHeader);
HttpServerResponse response = request.response();
client.request(options).onComplete(opened -> {
if (opened.failed()) {
@@ -7,10 +7,17 @@ import java.util.Map;
* its sibling interfaces its pages hold, as their daemons write it, and as the browser reaches that interface; what
* to do when the address does not answer, and how such a request is answered, {@code unansweredStatus} with a page
* saying {@code unanswered}, or, where that is null, a {@code 502} saying why; else why the request is refused, with
* its HTTP status.
* its HTTP status; and the {@code headers} the request goes on with besides its own, in place of any it has of
* those names.
*/
public record AppUiRoute(String host, int port, Map<String, String> rewrites, Runnable unreachable, int status,
String refusal, int unansweredStatus, String unanswered) {
String refusal, int unansweredStatus, String unanswered, Map<String, String> headers) {
/** A route that adds no header of its own. */
public AppUiRoute(String host, int port, Map<String, String> rewrites, Runnable unreachable, int status,
String refusal, int unansweredStatus, String unanswered) {
this(host, port, rewrites, unreachable, status, refusal, unansweredStatus, unanswered, Map.of());
}
/** A route whose interface, when it does not answer, is a {@code 502}. */
public AppUiRoute(String host, int port, Map<String, String> rewrites, Runnable unreachable, int status,
@@ -30,4 +37,10 @@ public record AppUiRoute(String host, int port, Map<String, String> rewrites, Ru
public static AppUiRoute to(String host, int port, int unansweredStatus, String unanswered) {
return new AppUiRoute(host, port, Map.of(), () -> { }, 0, null, unansweredStatus, unanswered);
}
/** This route, its requests going on with {@code headers} too. */
public AppUiRoute withHeaders(Map<String, String> headers) {
return new AppUiRoute(host, port, rewrites, unreachable, status, refusal, unansweredStatus, unanswered,
Map.copyOf(headers));
}
}
@@ -200,6 +200,14 @@ public interface ClusterStorage {
return Optional.empty();
}
/**
* Where Floci reaches {@code port}, its Trino's, on {@code clusterId}'s primary node: empty until that Trino has
* answered queries ({@link #hdfs}), and while it is not running, or where Floci cannot reach it.
*/
default Optional<ContainerLifecycleManager.EndpointInfo> trinoInterface(String clusterId, int port) {
return Optional.empty();
}
/**
* Keeps what a cluster's history interfaces show once it has ended, before its storage goes: the Spark
* applications' event logs, copied out of its HDFS into the volume of its primary node that already holds the
@@ -76,6 +76,12 @@ final class EmrClusterLifecycle {
/** {@code step} of {@code cluster} has just gone RUNNING. */
void start(EmrCluster cluster, EmrStep step, String region);
/**
* {@code cluster}'s bootstrap is done and it runs or waits for steps, as its applications are up on EMR; what
* this sets going runs once the change is stored.
*/
void ready(EmrCluster cluster, String region);
/**
* {@code step}, which was RUNNING, has just been cancelled: with {@code terminateProcess} its process is killed
* at once, and else sent SIGTERM and left to end.
@@ -302,6 +308,9 @@ final class EmrClusterLifecycle {
cluster.setState(RUNNING);
instancesFollow(cluster);
runSteps(cluster, at, region);
if (execution != null && (RUNNING.equals(cluster.getState()) || WAITING.equals(cluster.getState()))) {
execution.ready(cluster, region);
}
}
/**
@@ -1499,6 +1499,11 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
spec.withLinkLocalIp(address);
}
}
if (hiveMetastore != null && hiveMetastore.trino() != null && !shared) {
// Its Trino's port, as Trino's container shares its network, which clients outside the cluster reach
// through Floci (see trinoInterface), as they do its web interfaces.
spec.withLoopbackPortBinding(EmrTrino.port(hiveMetastore.trino().config()), 0);
}
if (yarn != null && !shared) {
// Its web interfaces, which Floci's application UI links reach, published on the host's loopback interface
// alone, as Floci on the host reaches them there, and they take no credentials.
@@ -1834,6 +1839,25 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
}
}
/**
* Where Floci reaches the cluster's Trino on {@code port}, once it has answered queries and while it runs: at the
* port its primary node's container publishes for it, as for the node's web interfaces ({@link #webInterface}).
*/
@Override
public Optional<ContainerLifecycleManager.EndpointInfo> trinoInterface(String clusterId, int port) {
String name = trinoName(clusterId);
try {
if (!readyTrino.contains(name) || lifecycleManager.probeContainer(name) != ContainerLiveness.RUNNING) {
return Optional.empty();
}
} catch (RuntimeException e) {
// Docker did not answer: as for a node not running, the client is told to try again.
LOG.debugv(e, "The Trino of EMR cluster {0} could not be looked at: {1}", clusterId, e.getMessage());
return Optional.empty();
}
return webInterface(clusterId, port);
}
@Override
public boolean keepHistory(String clusterId) {
try {
@@ -126,7 +126,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
static final Duration HISTORY_KEPT = Duration.ofDays(30);
// How long after its 30 days a cluster's kept history is looked at again, to remove it.
private static final Duration HISTORY_SWEEP_MARGIN = Duration.ofMinutes(1);
// How long the command that starts a cluster's primary node for its application UIs may run: it runs nothing.
// How long the command that starts a cluster's primary node for its application UIs or its Trino may run: it runs
// nothing.
private static final Duration PRIMARY_NODE_START = Duration.ofMinutes(5);
// AWS's answer to a change on a terminated cluster, for AddJobFlowSteps and ModifyInstanceFleet; Floci
// gives it to AddInstanceGroups and AddInstanceFleet too, for one shutting down.
@@ -1065,9 +1066,41 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
}
/**
* Starts the cluster's primary node, its HDFS and YARN, as its first step would, by running nothing on it
* ({@link #runOnCluster}), unless such a start is under way already: an application UI link may be asked for
* before any step has run.
* A cluster's Trino as clients outside the cluster reach it: the cluster's account, Region, id and state, and the
* port Trino listens on.
*/
public record TrinoCluster(String accountId, String region, String clusterId, String state, int port) {
}
/**
* The cluster of that id, whichever account and Region holds it, as the host clients reach its Trino at names it
* ({@link EmrTrino#address}); empty where there is none, or it runs no Trino of Floci's. Looked up by its id in
* each account that holds clusters, not by a scan, as every request to its Trino asks.
*/
public Optional<TrinoCluster> trinoCluster(String clusterId) {
AccountAwareStorageBackend.AccountEntry<EmrCluster> entry = call(() -> clusterStore
.findAllAccountEntries(clusterId).stream().findFirst().orElse(null));
if (entry == null || entry.value().getRegion() == null) {
return Optional.empty();
}
String accountId = entry.accountId();
String region = entry.value().getRegion();
return RequestScopes.callAs(accountId, region, () -> findDescribedCluster(entry.key()))
.filter(this::runsTrino)
.map(cluster -> new TrinoCluster(accountId, region, cluster.getId(), cluster.getState(),
EmrTrino.port(EmrSparkSteps.trinoConfig(cluster.getConfigurations(), SNAPSHOT_MAPPER))));
}
/** Where Floci reaches the cluster's Trino on {@code port}, once it has answered queries. */
public Optional<ContainerLifecycleManager.EndpointInfo> trinoInterface(String clusterId, int port) {
return clusterStorage == null ? Optional.empty() : clusterStorage.trinoInterface(clusterId, port);
}
/**
* Starts the cluster's primary node, its HDFS and YARN, and its Trino where it runs Floci's, as its first step
* would, by running nothing on it ({@link #runOnCluster}), unless such a start is under way already: an
* application UI link, or a client of its Trino, may ask for it before any step has run, and a cluster with Trino
* starts it as it becomes ready.
*/
public void startPrimaryNode(String clusterId) {
String key = regionResolver.getAccountId() + "/" + clusterId;
@@ -1085,8 +1118,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
public void ended(SparkJobRunner.Outcome outcome) {
primaryNodeStarts.remove(key);
if (outcome.failure() != null) {
LOG.warnv("Could not start the primary node of EMR cluster {0} for its application"
+ " UIs: {1}", clusterId, outcome.failure());
LOG.warnv("Could not start the primary node of EMR cluster {0}: {1}", clusterId,
outcome.failure());
}
}
@@ -3193,6 +3226,25 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
sparkRunner.interrupt(step.getId());
}
}
// A cluster with Trino starts its primary node, and Trino on it, as it becomes ready, steps or none.
@Override
public void ready(EmrCluster cluster, String region) {
if (tornDown || !runsTrino(cluster)) {
return;
}
String accountId = regionResolver.getAccountId();
String clusterId = cluster.getId();
LOG.infov("EMR cluster {0} starts its Trino, which clients outside the cluster reach at {1}", clusterId,
EmrTrino.address(baseUrl, clusterId));
try {
// On a thread of its own, which reads the cluster under the service's lock, so once this is stored.
stepExecutor.execute(() -> RequestScopes.runAs(accountId, region, () -> startPrimaryNode(clusterId)));
} catch (RuntimeException e) {
LOG.warnv(e, "Could not start the primary node of EMR cluster {0} for its Trino: {1}", clusterId,
e.getMessage());
}
}
}
/**
@@ -3392,6 +3444,12 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
|| trinoImage(cluster) != null;
}
// Whether a cluster runs Floci's Trino: in the docker runner mode, on a network of the cluster's own, where its
// primary node runs the metastore, with an image for its Trino (trinoImage).
private boolean runsTrino(EmrCluster cluster) {
return runsOnClusters() && clusterStorage.ownNetwork(dockerNetwork) && trinoImage(cluster) != null;
}
// The image a cluster's Trino runs from: it installs Trino, floci.services.emr.trino.enabled runs it, and its
// release's Trino version is known (EmrTrino.image); null otherwise.
private String trinoImage(EmrCluster cluster) {
@@ -1,7 +1,9 @@
package io.floci.aws.services.emr;
import java.net.URI;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
@@ -19,8 +21,10 @@ import java.util.stream.Collectors;
* {@code <catalog>.properties} file". EMR installs {@code hcatalog-server} with Trino, so the catalogs whose tables
* are in S3, {@code hive}, {@code delta}, {@code hudi} and {@code iceberg}, are on the cluster's Hive metastore, as
* the Release Guide's Delta Lake and Iceberg tutorials have them at {@code thrift://localhost:9083}, unless the
* classification puts them in the Glue Data Catalog, as "Launch an Amazon EMR cluster with Trino" does. Its steps run
* {@code trino-cli}, EMR's command for Trino's CLI, which this class writes for the image they run in.
* classification puts them in the Glue Data Catalog, as "Launch an Amazon EMR cluster with Trino" does. It starts as
* the cluster becomes ready, with the primary node, steps or none. Its steps run {@code trino-cli}, EMR's command for
* Trino's CLI, which this class writes for the image they run in, and clients outside the cluster reach it through
* Floci on a host of the cluster's own ({@link EmrTrinoRoutes}).
*/
final class EmrTrino {
@@ -41,6 +45,11 @@ final class EmrTrino {
static final Pattern CATALOG_NAME = Pattern.compile("[a-z][a-z0-9_]*");
/** The component label of a cluster's Trino container, which goes with its primary node's. */
static final String COMPONENT = "emr-trino";
/**
* The label under Floci's host name of the hosts clients outside the cluster reach a cluster's Trino at, one per
* cluster ({@link #address}).
*/
static final String HOST_LABEL = "emr-trino";
/** The variable a step's {@code trino-cli} reads the coordinator's address from. */
static final String SERVER_VARIABLE = "FLOCI_TRINO_SERVER";
/** Trino's CLI in its image, an executable jar, which the cluster's image takes. */
@@ -128,6 +137,16 @@ final class EmrTrino {
return "http://" + host + ":" + port;
}
/**
* The address clients outside the cluster reach its Trino at, through Floci at {@code baseUrl}: a host of the
* cluster's own under {@link #HOST_LABEL}, as EMR's clients reach the primary node's.
*/
static String address(String baseUrl, String clusterId) {
URI base = URI.create(baseUrl);
return base.getScheme() + "://" + clusterId.toLowerCase(Locale.ROOT) + "." + HOST_LABEL + "."
+ base.getRawAuthority();
}
/** What tells the Trino container is ready: a query, run with the CLI of its image on {@code port}. */
static List<String> readyQuery(int port) {
return List.of(IMAGE_CLI, "--server", "localhost:" + port, "--execute", "SELECT 1");
@@ -135,8 +154,9 @@ final class EmrTrino {
/**
* The coordinator's {@code config.properties}: a coordinator that runs the queries too, on its {@link #port}, its
* discovery at that port unless the cluster's {@code trino-config} names another, and that classification's
* properties after these, each in its place.
* discovery at that port unless the cluster's {@code trino-config} names another; the scheme a client reached it
* over through Floci taken from {@code X-Forwarded-Proto}, as it names the query's next pages by the host and
* scheme it was asked on; and that classification's properties after these, each in its place.
*/
static Map<String, String> config(Map<String, String> classification) {
Map<String, String> config = new LinkedHashMap<>();
@@ -144,6 +164,7 @@ final class EmrTrino {
config.put("node-scheduler.include-coordinator", "true");
config.put("http-server.http.port", String.valueOf(PORT));
config.put("discovery.uri", "http://localhost:" + port(classification));
config.put("http-server.process-forwarded", "true");
config.putAll(classification);
return config;
}
@@ -0,0 +1,115 @@
package io.floci.aws.services.emr;
import io.floci.aws.core.common.AppUiRoute;
import io.floci.aws.core.common.AppUiRoutes;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
/**
* A cluster's Trino as clients outside the cluster reach it, through Floci, on a host of the cluster's own,
* {@code <cluster id>.}{@value EmrTrino#HOST_LABEL}{@code .<Floci's host and port>} ({@link EmrTrino#address}), as
* EMR's clients reach Trino on the primary node: no AWS API gives an address for it. The host takes no credentials, as
* Floci's Trino has no authentication, so whoever reaches Floci's port reaches the cluster's Trino. Trino names a
* query's next pages by the host it was asked on, which the request keeps, and by the scheme it was reached over,
* which goes on as {@code X-Forwarded-Proto}. A cluster whose Trino is not running yet has its primary node started,
* as an application UI link does, and the request answered with a {@code 503}, which Trino's clients try again on.
*/
@ApplicationScoped
public class EmrTrinoRoutes implements AppUiRoutes {
// No source gives these, as no AWS API serves Trino; they are Floci's.
static final String NO_SUCH_CLUSTER = "No EMR cluster %s runs Floci's Trino.";
static final String CLUSTER_ENDED = "EMR cluster %s is no longer running, and its Trino is there only while it is"
+ " RUNNING or WAITING.";
static final String NOT_READY = "The Trino of EMR cluster %s is starting. Try again in a moment.";
// How long a port found for a cluster's Trino is used before it is asked for again, as for the application UIs.
private static final Duration ENDPOINT_RECHECK = Duration.ofSeconds(10);
// A cluster's id, as a host name holds it, without case.
private static final Pattern CLUSTER_ID = Pattern.compile("j-[a-z0-9]+");
private final EmrService clusters;
private final Clock clock;
// Where Floci found each cluster's Trino, and when, by account and cluster.
private final Map<String, Found> endpoints = new ConcurrentHashMap<>();
@Inject
public EmrTrinoRoutes(EmrService clusters) {
this(clusters, Clock.systemUTC());
}
EmrTrinoRoutes(EmrService clusters, Clock clock) {
this.clusters = clusters;
this.clock = clock;
}
private record Found(ContainerLifecycleManager.EndpointInfo endpoint, Instant at) {
}
@Override
public String hostLabel() {
return EmrTrino.HOST_LABEL;
}
@Override
public String service() {
return "emr";
}
/**
* The route of a request whose {@code Host} is {@code hostHeader}, over {@code scheme}: to the Trino of the
* cluster the host names, once it answers queries; null where the host is not one of a cluster's Trino.
*/
@Override
public AppUiRoute route(String hostHeader, String scheme) {
String host = hostHeader.toLowerCase(Locale.ROOT);
int dot = host.indexOf('.');
if (dot <= 0 || !host.startsWith(EmrTrino.HOST_LABEL + ".", dot + 1)
|| !CLUSTER_ID.matcher(host.substring(0, dot)).matches()) {
return null;
}
// A cluster's id is j- and capitals and digits, which the host holds in lower case.
String clusterId = "j-" + host.substring(2, dot).toUpperCase(Locale.ROOT);
EmrService.TrinoCluster cluster = clusters.trinoCluster(clusterId).orElse(null);
if (cluster == null) {
return AppUiRoute.refused(404, String.format(NO_SUCH_CLUSTER, clusterId));
}
String key = cluster.accountId() + "/" + cluster.clusterId();
if (!EmrClusterLifecycle.RUNNING.equals(cluster.state())
&& !EmrClusterLifecycle.WAITING.equals(cluster.state())) {
endpoints.remove(key);
return EmrClusterLifecycle.isTerminated(cluster.state())
|| EmrClusterLifecycle.TERMINATING.equals(cluster.state())
? AppUiRoute.refused(404, String.format(CLUSTER_ENDED, cluster.clusterId()))
: AppUiRoute.refused(503, String.format(NOT_READY, cluster.clusterId()));
}
Instant now = clock.instant();
Found found = endpoints.get(key);
if (found == null || !now.isBefore(found.at().plus(ENDPOINT_RECHECK))) {
ContainerLifecycleManager.EndpointInfo endpoint = RequestScopes.callAs(cluster.accountId(),
cluster.region(), () -> clusters.trinoInterface(cluster.clusterId(), cluster.port()))
.orElse(null);
if (endpoint == null) {
endpoints.remove(key);
RequestScopes.runAs(cluster.accountId(), cluster.region(),
() -> clusters.startPrimaryNode(cluster.clusterId()));
return AppUiRoute.refused(503, String.format(NOT_READY, cluster.clusterId()));
}
found = new Found(endpoint, now);
endpoints.put(key, found);
}
Found routed = found;
return new AppUiRoute(found.endpoint().host(), found.endpoint().port(), Map.of(),
() -> endpoints.remove(key, routed), 0, null, 503, String.format(NOT_READY, cluster.clusterId()))
.withHeaders(Map.of("X-Forwarded-Proto", scheme));
}
}
@@ -229,6 +229,21 @@ class AppUiProxyTest {
assertEquals(host + ":4566", interfaceSaw.get().get("host"));
}
@Test
void aRoutesOwnHeadersGoOnInPlaceOfTheClientsOfThoseNames() throws Exception {
when(appUis.route(eq(HOST + ":4566"), eq("http"))).thenReturn(AppUiRoute.to("127.0.0.1",
node.actualPort(), 503, null).withHeaders(Map.of("X-Forwarded-Proto", "https")));
answer = (response, body) -> response.putHeader("content-type", "text/plain").end("answered");
Answered response = send(HOST, HttpMethod.POST, "/v1/statement", "SELECT 1",
Map.of("x-forwarded-proto", "http", "X-Trino-User", "someone"));
assertEquals(200, response.statusCode());
assertEquals(List.of("https"), interfaceSaw.get().getAll("X-Forwarded-Proto"));
assertEquals("someone", interfaceSaw.get().get("X-Trino-User"));
assertEquals(HOST + ":4566", interfaceSaw.get().get("host"));
}
@Test
void anInterfaceThatIsNotUpYetIsAnsweredAsItsRouteSays() throws Exception {
int closed = node.actualPort();
@@ -275,9 +290,15 @@ class AppUiProxyTest {
}
private Answered send(String host, HttpMethod method, String uri, String body) throws Exception {
return send(host, method, uri, body, Map.of());
}
private Answered send(String host, HttpMethod method, String uri, String body, Map<String, String> headers)
throws Exception {
RequestOptions options = new RequestOptions().setMethod(method)
.setServer(SocketAddress.inetSocketAddress(floci.actualPort(), "127.0.0.1"))
.setHost(host).setPort(4566).setURI(uri);
headers.forEach(options::putHeader);
return await(client.request(options).compose(request -> body == null ? request.send()
: request.send(Buffer.buffer(body)))
.compose(response -> response.body().map(read -> new Answered(response, read))));
@@ -1941,6 +1941,8 @@ class EmrClusterStorageTest {
verify(spec, never()).withJoinedNetwork(any());
verify(spec, never()).withEmbeddedDns();
verify(lifecycle, never()).ensureConnected(anyString(), anyString(), anyString());
// No Trino, so no port for one.
verify(spec, never()).withLoopbackPortBinding(anyInt(), anyInt());
// Floci's S3 through S3A, as for the cluster's steps.
verify(spec).withEnv(eq("FLOCI_HIVE_METASTORE"), argThat(settings -> settings.startsWith(
"--hiveconf fs.s3a.endpoint=http://host.docker.internal:4566"
@@ -2021,6 +2023,37 @@ class EmrClusterStorageTest {
verify(roleCredentials).unregister("123456789012", "ASIATRINO");
}
@Test
void trinosPortIsPublishedOnThePrimaryNodeAndReachedOnceTrinoIsReadyUntilItGoes() {
String trinoName = ContainerStorageHelper.dockerName(config, "emr-j-1-trino");
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-6", Map.of()),
new ContainerLifecycleManager.ContainerInfo("t-1", Map.of()));
trinoStarts(trinoName);
ContainerLifecycleManager.EndpointInfo published = new ContainerLifecycleManager.EndpointInfo("localhost",
32802);
when(lifecycle.resolveEndpoint(hdfsName, 8889, hdfsName)).thenReturn(published);
when(currentContainer.resolveContainerId()).thenReturn(Optional.empty());
// Not started yet.
assertTrue(ticking.trinoInterface("j-1", 8889).isEmpty());
ticking.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", TRINO_METASTORE, null,
NOT_STOPPED);
// Its port, on the node's container, whose network Trino's shares, as the node's web interfaces' are.
verify(spec).withLoopbackPortBinding(8889, 0);
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.RUNNING);
ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", "");
assertEquals(Optional.of(published), ticking.trinoInterface("j-1", 8889));
// A Trino that has stopped is not reached.
when(lifecycle.probeContainer(trinoName)).thenReturn(ContainerLiveness.NOT_RUNNING);
assertTrue(ticking.trinoInterface("j-1", 8889).isEmpty());
when(lifecycle.probeContainer(trinoName)).thenReturn(ContainerLiveness.RUNNING);
ticking.remove("j-1");
assertTrue(ticking.trinoInterface("j-1", 8889).isEmpty());
}
@Test
void trinoIsReadyOnceItHasRunAQueryForTenSecondsAFailureBetweenStartingThemAgain() {
String trinoName = ContainerStorageHelper.dockerName(config, "emr-j-1-trino");
@@ -1130,6 +1130,64 @@ class EmrServiceContainerStepsTest {
assertEquals("http://" + host + ":8890", job.environment().get("FLOCI_TRINO_SERVER"));
}
@Test
void aClusterWithFlocisTrinoStartsItsPrimaryNodeAndTrinoAsItBecomesReadyStepsOrNone() {
fixture.clusterStorage.ownNetwork = true;
EmrService withTrino = fixture.withTrino();
EmrCluster requested = cluster("trino", true);
requested.setApplications(TRINO);
String clusterId = withTrino.runJobFlow(requested, REGION).getId();
assertEquals("WAITING", withTrino.describeCluster(clusterId).getState());
// On a thread of its own, which starts the node as an application UI link does, by running nothing on it.
assertEquals(1, fixture.stepThreadsWaiting());
fixture.runStepThread();
fixture.runStepThread();
assertEquals(List.of("true"), runner.jobs.get(0).command());
assertEquals(new ClusterStorage.Trino("trinodb/trino:446", 2048, Map.of(), Map.of()),
fixture.clusterStorage.metastores.get(0).trino());
assertEquals(0, fixture.stepThreadsWaiting());
}
@Test
void aClusterWithoutFlocisTrinoStartsNothingAsItBecomesReady() {
fixture.clusterStorage.ownNetwork = true;
EmrCluster trino = cluster("trino", true);
trino.setApplications(TRINO);
EmrCluster hive = cluster("hive", true);
hive.setApplications("[{\"Name\": \"Hive\"}]");
// Floci's Trino off, and on for a cluster that does not install Trino.
service.runJobFlow(trino, REGION);
fixture.withTrino().runJobFlow(hive, REGION);
assertEquals(0, fixture.stepThreadsWaiting());
}
@Test
void aClustersTrinoIsFoundByItsIdOnThePortItsTrinoConfigNames() {
fixture.clusterStorage.ownNetwork = true;
EmrService withTrino = fixture.withTrino();
EmrCluster trino = cluster("trino", true);
trino.setApplications(TRINO);
trino.setConfigurations("[{\"Classification\": \"trino-config\", \"Properties\": "
+ "{\"http-server.http.port\": \"8890\"}}]");
String trinoId = withTrino.runJobFlow(trino, REGION).getId();
EmrCluster hive = cluster("hive", true);
hive.setApplications("[{\"Name\": \"Hive\"}]");
String hiveId = withTrino.runJobFlow(hive, REGION).getId();
assertEquals(Optional.of(new EmrService.TrinoCluster(ACCOUNT, REGION, trinoId, "WAITING", 8890)),
withTrino.trinoCluster(trinoId));
assertEquals(Optional.empty(), withTrino.trinoCluster(hiveId));
assertEquals(Optional.empty(), withTrino.trinoCluster("j-NOSUCHCLUSTER"));
// With Floci's Trino off, or on a network its steps share, it runs none.
assertEquals(Optional.empty(), service.trinoCluster(trinoId));
fixture.clusterStorage.ownNetwork = false;
assertEquals(Optional.empty(), withTrino.trinoCluster(trinoId));
}
@Test
void aClusterWithTrinoRunsNoneWhileFlocisTrinoIsOff() {
EmrStep query = sparkStep("query", "CONTINUE");
@@ -13,6 +13,10 @@ import io.floci.aws.testing.RestAssuredJsonUtils;
import io.floci.aws.testing.S3TestClients;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
@@ -30,6 +34,9 @@ import software.amazon.awssdk.services.s3.S3Client;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URI;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
@@ -40,8 +47,11 @@ import java.util.concurrent.TimeUnit;
import static io.floci.aws.testing.EmrRequests.awaitStep;
import static io.floci.aws.testing.EmrRequests.emr;
import static io.floci.aws.testing.EmrRequests.terminateClusterAndAwaitCleanup;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -52,7 +62,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
* queries" does, over a CSV in Floci's S3. Its {@code hive} catalog is the cluster's Hive metastore, or, with
* {@code trino-connector-hive} setting {@code hive.metastore} to {@code glue}, Floci's Glue Data Catalog. The
* cluster's other {@code trino-connector-<catalog>} classifications add catalogs, Iceberg's on Glue as the Release
* Guide's "Use an Iceberg cluster with Trino" has it, and its {@code trino-config} moves Trino to another port.
* Guide's "Use an Iceberg cluster with Trino" has it, and its {@code trino-config} moves Trino to another port. A
* cluster with no step starts its Trino as it becomes ready, and a client outside the cluster queries it through Floci
* on the cluster's own host.
*
* <p>A nightly check: it pulls the Trino image of {@code emr-7.5.0}'s Trino, 446, about 1 GB, and the release's Spark
* and Hive images.
@@ -196,6 +208,21 @@ class EmrTrinoNightlyIntegrationTest {
assertFalse(s3.listObjectsV2(request -> request.bucket(bucket).prefix("iceberg/")).contents().isEmpty());
}
// No step: Trino starts with the cluster, and a client outside the cluster's network queries it through Floci on
// the cluster's own host, the query's next pages on that host too.
@Test
@Timeout(value = 7, unit = TimeUnit.MINUTES)
void trinoStartsWithTheClusterAndAClientOutsideItQueriesItThroughFlocisHostForIt() {
startCluster("[]");
String host = clusterId.toLowerCase(Locale.ROOT) + "." + EmrTrino.HOST_LABEL + ".localhost:" + RestAssured.port;
assertEquals(List.of(List.of("hive"), List.of("system")), query(host, "SHOW CATALOGS"));
// A catalog read, on the cluster's metastore, once Trino's node serves it.
assertTrue(query(host, "SHOW SCHEMAS FROM hive").contains(List.of("default")));
assertEquals("WAITING", emr("DescribeCluster", "{\"ClusterId\":\"" + clusterId + "\"}").then()
.statusCode(200).extract().jsonPath().getString("Cluster.Status.State"));
}
// A schema in the bucket's warehouse folder, an external table over the CSV, a table of each item's sum, then the
// sums.
private String tables(String schema) {
@@ -224,6 +251,37 @@ class EmrTrinoNightlyIntegrationTest {
cleanup.register(() -> terminateClusterAndAwaitCleanup(clusterId, emrService));
}
// A client outside the cluster: the statement posted to Trino through Floci's host for the cluster, asked again
// while that answers 503 as Trino's clients do, Trino starting with the cluster, then each next page Trino names
// followed, on the host it was asked on, until the last; the rows they hold together.
private static List<List<Object>> query(String host, String statement) {
Response[] first = new Response[1];
await("the Trino of the cluster to take a query").atMost(Duration.ofMinutes(5))
.pollInterval(Duration.ofSeconds(1))
.until(() -> (first[0] = trino(host).body(statement).post("/v1/statement")).statusCode() != 503);
JsonPath page = first[0].then().statusCode(200).extract().jsonPath();
List<List<Object>> rows = new ArrayList<>();
while (true) {
List<List<Object>> data = page.getList("data");
if (data != null) {
rows.addAll(data);
}
String next = page.getString("nextUri");
if (next == null) {
JsonPath last = page;
assertNull(last.get("error"), last::prettify);
return rows;
}
URI uri = URI.create(next);
assertEquals(host, uri.getRawAuthority());
page = trino(host).get(uri.getRawPath()).then().statusCode(200).extract().jsonPath();
}
}
private static RequestSpecification trino(String host) {
return given().header("Host", host).header("X-Trino-User", "floci");
}
// EMR's trino-cli, through command-runner.jar, running the statements given.
private String trinoStep(String statements) {
return EmrRequests.addStep(clusterId, "trino", "command-runner.jar", "trino-cli", "--execute", statements);
@@ -0,0 +1,120 @@
package io.floci.aws.services.emr;
import io.floci.aws.core.common.AppUiRoute;
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
import io.floci.aws.testing.ManualClock;
import io.floci.aws.testing.ParallelLocks;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.ResourceAccessMode;
import org.junit.jupiter.api.parallel.ResourceLock;
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
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;
// It names Floci's port, localhost:4566, and opens no socket.
@ResourceLock(value = ParallelLocks.PORTS, mode = ResourceAccessMode.READ)
class EmrTrinoRoutesTest {
private static final String CLUSTER = "j-2AXXXXXXGAPLF";
private static final String HOST = "j-2axxxxxxgaplf.emr-trino.localhost:4566";
private static final ContainerLifecycleManager.EndpointInfo ENDPOINT =
new ContainerLifecycleManager.EndpointInfo("127.0.0.1", 41234);
private final EmrService clusters = mock(EmrService.class);
private final ManualClock clock = new ManualClock(Instant.parse("2026-11-26T12:00:00Z"));
private EmrTrinoRoutes routes;
@BeforeEach
void setUp() {
routes = new EmrTrinoRoutes(clusters, clock);
}
@Test
void aHostOfAnotherKindIsNoneOfItsRoutes() {
assertNull(routes.route("j-2axxxxxxgaplf.emrappui.localhost:4566", "http"));
assertNull(routes.route("localhost:4566", "http"));
assertNull(routes.route("my-bucket.emr-trino.localhost:4566", "http"));
assertNull(routes.route("emr-trino.localhost:4566", "http"));
}
@Test
void aClusterWithNoTrinoOfFlocisIsNotFound() {
when(clusters.trinoCluster(CLUSTER)).thenReturn(Optional.empty());
AppUiRoute route = routes.route(HOST, "http");
assertEquals(404, route.status());
assertEquals(String.format(EmrTrinoRoutes.NO_SUCH_CLUSTER, CLUSTER), route.refusal());
}
@Test
void aClusterStillStartingIsAskedAgainAndOneThatHasEndedIsGone() {
when(clusters.trinoCluster(CLUSTER)).thenReturn(Optional.of(cluster("STARTING")));
assertEquals(503, routes.route(HOST, "http").status());
when(clusters.trinoCluster(CLUSTER)).thenReturn(Optional.of(cluster("TERMINATED")));
assertEquals(404, routes.route(HOST, "http").status());
when(clusters.trinoCluster(CLUSTER)).thenReturn(Optional.of(cluster("TERMINATING")));
assertEquals(String.format(EmrTrinoRoutes.CLUSTER_ENDED, CLUSTER), routes.route(HOST, "http").refusal());
verify(clusters, never()).startPrimaryNode(anyString());
verify(clusters, never()).trinoInterface(anyString(), anyInt());
}
@Test
void aTrinoNotAnsweringYetHasItsPrimaryNodeStartedAndTheClientAskedAgain() {
when(clusters.trinoCluster(CLUSTER)).thenReturn(Optional.of(cluster("WAITING")));
when(clusters.trinoInterface(CLUSTER, 8890)).thenReturn(Optional.empty());
AppUiRoute route = routes.route(HOST, "http");
assertEquals(503, route.status());
assertEquals(String.format(EmrTrinoRoutes.NOT_READY, CLUSTER), route.refusal());
verify(clusters).startPrimaryNode(CLUSTER);
}
@Test
void aRunningTrinoIsReachedWithTheSchemeTheClientUsedItsPortFoundOnceInTenSeconds() {
when(clusters.trinoCluster(CLUSTER)).thenReturn(Optional.of(cluster("RUNNING")));
when(clusters.trinoInterface(CLUSTER, 8890)).thenReturn(Optional.of(ENDPOINT));
// A host name is read without case.
AppUiRoute route = routes.route(HOST.toUpperCase(), "https");
assertNull(route.refusal());
assertEquals("127.0.0.1", route.host());
assertEquals(41234, route.port());
assertEquals(Map.of("X-Forwarded-Proto", "https"), route.headers());
assertEquals(Map.of(), route.rewrites());
assertEquals(503, route.unansweredStatus());
assertEquals(Map.of("X-Forwarded-Proto", "http"), routes.route(HOST, "http").headers());
verify(clusters, times(1)).trinoInterface(CLUSTER, 8890);
clock.advance(Duration.ofSeconds(10));
routes.route(HOST, "http");
verify(clusters, times(2)).trinoInterface(CLUSTER, 8890);
// One that does not answer is looked for again.
routes.route(HOST, "http").unreachable().run();
routes.route(HOST, "http");
verify(clusters, times(3)).trinoInterface(CLUSTER, 8890);
verify(clusters, never()).startPrimaryNode(anyString());
}
private static EmrService.TrinoCluster cluster(String state) {
return new EmrService.TrinoCluster("000000000000", "us-east-1", CLUSTER, state, 8890);
}
}
@@ -128,15 +128,18 @@ class EmrTrinoTest {
@Test
void theCoordinatorRunsTheQueriesTooOnEmrsPortOrTheOneTrinoConfigNames() {
// Clients through Floci reach it on a host of the cluster's own, over the scheme they used.
assertEquals(List.of("coordinator=true", "node-scheduler.include-coordinator=true",
"http-server.http.port=8889", "discovery.uri=http://localhost:8889"),
"http-server.http.port=8889", "discovery.uri=http://localhost:8889",
"http-server.process-forwarded=true"),
List.of(EmrTrino.properties(EmrTrino.config(Map.of())).split("\n")));
// "To change the port, use the presto-config configuration classification to set the http-server.http.port
// property", trino-config for Trino: its discovery follows.
Map<String, String> moved = EmrTrino.config(Map.of("http-server.http.port", "8890",
"query.max-memory", "1GB"));
assertEquals(List.of("coordinator=true", "node-scheduler.include-coordinator=true",
"http-server.http.port=8890", "discovery.uri=http://localhost:8890", "query.max-memory=1GB"),
"http-server.http.port=8890", "discovery.uri=http://localhost:8890",
"http-server.process-forwarded=true", "query.max-memory=1GB"),
List.of(EmrTrino.properties(moved).split("\n")));
assertEquals(8890, EmrTrino.port(moved));
assertEquals(8889, EmrTrino.port(Map.of("http-server.http.port", "eighty")));
@@ -145,6 +148,14 @@ class EmrTrinoTest {
EmrTrino.readyQuery(8890));
}
@Test
void clientsOutsideTheClusterReachItsTrinoOnAHostOfTheClustersOwnUnderFlocis() {
assertEquals("http://j-2axxxxxxgaplf.emr-trino.localhost:4566",
EmrTrino.address("http://localhost:4566", "j-2AXXXXXXGAPLF"));
assertEquals("https://j-2axxxxxxgaplf.emr-trino.localhost.floci.io:4566",
EmrTrino.address("https://localhost.floci.io:4566/", "j-2AXXXXXXGAPLF"));
}
@Test
void theEntrypointWritesTheConfigurationTheCatalogsFlociGivesAloneAndANodeIdTrinoTakes(@TempDir Path etc)
throws Exception {