From ac3be910aeda1ed182c1c7a9fa82e358a711fa3b Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:25:52 -0400 Subject: [PATCH] feat(emr): run Trino workers on a cluster's core and task nodes (#9797) EMR's Trino follows a "coordinator-worker model, where each component has a specialized role in query execution", and Floci ran the coordinator alone. Each core and task node Floci runs now runs a Trino worker, in a container that shares the node's network, up to trino.max-workers with trino.worker-memory-mb each, and the coordinator runs the queries itself only on a cluster with no workers. Every node shares a secret Floci makes as the coordinator starts, and a worker starts and goes with its node, a resize's among them. --- .github/ci/select-nightly-checks.sh | 2 +- .github/workflows/nightly-checks.yml | 4 +- docs/services/emr.md | 72 +++-- .../io/floci/aws/config/EmulatorConfig.java | 20 +- .../aws/services/emr/ClusterStorage.java | 17 +- .../aws/services/emr/EmrClusterStorage.java | 306 ++++++++++++++---- .../io/floci/aws/services/emr/EmrService.java | 8 +- .../io/floci/aws/services/emr/EmrTrino.java | 135 +++++--- src/main/resources/application.yml | 4 +- .../services/emr/EmrClusterStorageTest.java | 195 ++++++++++- .../emr/EmrServiceContainerStepsTest.java | 6 +- .../aws/services/emr/EmrServiceFixture.java | 2 + .../emr/EmrTrinoNightlyIntegrationTest.java | 39 ++- .../floci/aws/services/emr/EmrTrinoTest.java | 153 +++++---- 14 files changed, 746 insertions(+), 217 deletions(-) diff --git a/.github/ci/select-nightly-checks.sh b/.github/ci/select-nightly-checks.sh index 081dcfa19d..9c68fda056 100755 --- a/.github/ci/select-nightly-checks.sh +++ b/.github/ci/select-nightly-checks.sh @@ -111,7 +111,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:235 docker-e2e:60; do +for entry in standard:359 docker-runner:242 docker-e2e:60; do group="${entry%%:*}" timeout="${entry##*:}" count=$(wc -l < "$work/$group.txt" | tr -d ' ') diff --git a/.github/workflows/nightly-checks.yml b/.github/workflows/nightly-checks.yml index d0732c73c8..0212ae085e 100644 --- a/.github/workflows/nightly-checks.yml +++ b/.github/workflows/nightly-checks.yml @@ -78,8 +78,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 five seven-minute - # methods and ten-minute image pull, 215 minutes. docker-e2e holds the *DockerNightlyIntegrationTest + # eighteen-minute methods and 21-minute image pull, and EmrTrinoNightlyIntegrationTest's six seven-minute + # methods and ten-minute image pull, 222 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: diff --git a/docs/services/emr.md b/docs/services/emr.md index 2b267b8735..0cddaa136f 100644 --- a/docs/services/emr.md +++ b/docs/services/emr.md @@ -831,21 +831,34 @@ holding the driver and its executors, or a command or a script. The cluster itse image steps run in. floci.services.emr.pig.enabled adds Apache Pig to it."). * **Trino**: no AWS image carries Trino, so Floci runs it on a cluster whose `Applications` name it only with `trino.enabled` on (`FLOCI_SERVICES_EMR_TRINO_ENABLED=true`), off by default, as its image is the Trino project's, - about 1 GB to pull. The cluster's primary node then runs Trino's coordinator, which runs the queries too, as a cluster - of one node's does, in a container of its own that shares the node's network, as a daemon of the node: from - `trino.image`, `trinodb/trino:%s` by default, `%s` the Trino version the release's page in the Release Guide gives - without AWS's `-amzn-N` suffix (446 for `emr-7.5.0`), with `trino.memory-mb` of memory, 2048 by default, 80% of which - the image gives Trino's heap. It listens on 8889: "By default, Amazon EMR configures the Presto web interface on the - Presto coordinator to use port 8889 (for PrestoDB and Trino)", or on the `http-server.http.port` of the cluster's - `trino-config`, which changes "Trino's config.properties file": its properties go there after Floci's, a coordinator - that runs the queries too. EMR installs `hive-client` and `hcatalog-server` with Trino, so the cluster's image has - Hive and its primary node runs Hive's metastore service, as on a cluster with HCatalog (see **Storage**), and Trino's + about 1 GB to pull. The cluster's primary node then runs Trino's coordinator, in a container of its own that shares + the node's network, as a daemon of the node, and each of the core and task nodes Floci runs (`yarn-max-worker-nodes`) + a Trino worker the same way, EMR's "coordinator-worker model, where each component has a specialized role in query + execution", up to `trino.max-workers`, 4 by default, core nodes first, 0 running none: from `trino.image`, + `trinodb/trino:%s` by default, `%s` the Trino version the release's page in the Release Guide gives without AWS's + `-amzn-N` suffix (446 for `emr-7.5.0`), the coordinator with `trino.memory-mb` of memory and each worker with + `trino.worker-memory-mb`, 2048 by default each, 80% of which the image gives Trino's heap. The coordinator runs the + queries too only on a cluster with no workers as it starts, as Trino's deployment guide has a coordinator with workers + run none (`node-scheduler.include-coordinator`), and a query it is asked before it has learnt of a worker waits for + one, as Trino's `query-manager.required-workers`, 1, has it, about 20 seconds after Trino starts (measured on Trino + 446). It listens on 8889: "By default, Amazon EMR configures the Presto web interface on the Presto coordinator to + use port 8889 (for PrestoDB and Trino)", or on the `http-server.http.port` of the cluster's `trino-config`, which + changes "Trino's config.properties file": its properties go there after Floci's, on the coordinator and on each + worker, as "configuration properties must be set on the coordinator and all worker nodes". A worker finds the + coordinator on the primary node at that port, is reached at its node's host name (`node.internal-address`), as the + node's addresses include a link-local one, and has the cluster's `trino-node`, `trino-log`, `trino-env`, catalogs, + exchange manager and password authenticator, as the coordinator does, its catalogs' metastore on the primary node. It + starts and goes with its node, a resize's among them; one whose node leaves goes at once, a query's tasks on it + failing, as Floci shuts no worker down gracefully. EMR installs `hive-client` and `hcatalog-server` with Trino, so + the cluster's image has Hive and its primary node runs Hive's metastore service, as on a cluster with HCatalog (see + **Storage**), and Trino's `hive` catalog is that metastore, its warehouse in the cluster's HDFS and its tables' S3 locations on Floci's S3. From `emr-7.14.0` on, "When you select Trino as the only application at launch, Amazon EMR no longer starts YARN and HDFS. To add Hadoop and HDFS to a Trino cluster, these applications will need to be explicitly added to the list of applications at cluster launch": a cluster whose `Applications` name Trino alone runs neither, its primary node the - metastore EMR still installs with Trino, and Trino, and its core and task nodes nothing, as Floci runs no Trino - workers. Its metastore's warehouse is still in HDFS, so a schema there needs a location of its own, in S3: a + metastore EMR still installs with Trino, and Trino, and its core and task nodes nothing, as Floci runs Trino workers + only on the core and task nodes it runs for YARN and HDFS. Its metastore's warehouse is still in HDFS, so a schema + there needs a location of its own, in S3: a `CREATE SCHEMA` without one fails, "Call From ... failed on connection exception" (measured on Hive 3.1.3). A bare `trino-exchange-manager` spools in HDFS too, so on such a cluster its `exchange.base-directories` names S3. With `trino-connector-hive` setting `hive.metastore` to `glue`, as the Release Guide's "Launch an Amazon EMR cluster with @@ -874,27 +887,32 @@ holding the driver and its executors, or a command or a script. The cluster itse password-authenticator.properties file", makes Trino's password authenticator, which a `trino-config` `http-server.authentication.type` of `PASSWORD` turns on, as the Release Guide's "Using LDAP authentication for Presto on Amazon EMR" has it for Trino. The files its `file.password-file`, `ldap.ssl.keystore.path` and - `ldap.ssl.truststore.path` (or that one's older name, `ldap.ssl-trust-certificate`) name are copied into Trino's - container, readable by its `trino` user, from the image the cluster's bootstrap actions left, as EMR's Trino finds - what they wrote on the primary node it runs on; one that image does not hold stays as Trino's own image has it. Trino - reads each into its memory, so one larger than the `trino.memory-mb` its container gets, or than the Docker host's - memory where a `trino.memory-mb` of 0 sets no limit, is refused, and Trino does not start, before Floci reads any of - it. Trino - refuses to start with authentication on and no shared secret for its internal communication, so Floci gives it a new - one each time it starts, unless `trino-config` names one, as EMR "automatically configures a shared secret key for - secure internal communication between cluster nodes ... and you can override the configuration with your own secret - key". Trino takes a password only over HTTPS, and answers a request over plain HTTP with a `403`, with a password or + `ldap.ssl.truststore.path` (or that one's older name, `ldap.ssl-trust-certificate`) name are copied into the + coordinator's container, readable by its `trino` user, from the image the cluster's bootstrap actions left, as EMR's + Trino finds what they wrote on the primary node it runs on, and into a worker's from the image its node's own + bootstrap actions left, else that one, as a worker with `PASSWORD` and no password authenticator does not start + ("file does not exist: etc/password-authenticator.properties", measured on Trino 446); one that image does not hold + stays as Trino's own image has it. Trino reads each into its memory, so one larger than the `trino.memory-mb` or + `trino.worker-memory-mb` its container gets, or than the Docker host's memory where 0 sets no limit, is refused, and + that Trino does not start, before Floci reads any of it. Trino refuses to start with authentication on and no shared + secret for its internal communication, and its nodes sign their requests to each other with it, so Floci makes one + each time the coordinator starts, which its workers then share, unless `trino-config` names one, as EMR + "automatically configures a shared secret key for secure internal communication between cluster nodes ... and you can + override the configuration with your own secret key"; it is in each Trino container's environment, as the rest of + their configuration is. Trino takes a password only over HTTPS, and answers a request over plain HTTP with a `403`, + with a password or without (measured on Trino 446), so a client sends one through Floci with its TLS on (see below), and a step's `trino-cli`, which reaches Trino over plain HTTP, gets that `403` (see **Known limitations**). Trino reaches S3 and - Glue as the cluster's EC2 instance profile's role, with a + Glue as the cluster's EC2 instance profile's role, each node 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. 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 its image's health check, which asks Trino's `/v1/info` - whether it is still starting and takes no credentials, has passed 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 + whether it is still starting and takes no credentials, has passed for ten seconds on the coordinator and on each + worker, within three minutes each, as Trino runs a query that reads a catalog once it has learnt that a node serves + the catalog; a worker a resize starts joins as it becomes ready. 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://.emr-trino.:`, as EMR's reach Trino's port on the primary node: Trino's CLI with @@ -1204,9 +1222,11 @@ its `STARTING` event, has its events sent after the rest of that call's. | `FLOCI_SERVICES_EMR_PIG_ENABLED` | `false` | Add Apache Pig, downloaded once per release's image, to a `docker` cluster whose `Applications` name Pig, so its Pig steps run (see [Running steps](#running-steps)) | | `FLOCI_SERVICES_EMR_PIG_URLS` | `https://dlcdn.apache.org/pig/pig-0.18.0/pig-0.18.0.tar.gz,https://archive.apache.org/dist/pig/pig-0.18.0/pig-0.18.0.tar.gz` | Where Floci downloads Pig's binary distribution from, the first that answers; a mirror names its own | | `FLOCI_SERVICES_EMR_PIG_SHA256` | `6845adb936a3c3bcc71451765953cae4103e410ba2f6c5a47cc9becade0a434a`, `pig-0.18.0.tar.gz`'s | The SHA-256 the download must have; set it with another distribution | -| `FLOCI_SERVICES_EMR_TRINO_ENABLED` | `false` | Run Trino's coordinator on the primary node of a `docker` cluster whose `Applications` name Trino, with `trino-cli` for its steps (see [Running steps](#running-steps)) | +| `FLOCI_SERVICES_EMR_TRINO_ENABLED` | `false` | Run Trino's coordinator on the primary node of a `docker` cluster whose `Applications` name Trino, and its workers on the core and task nodes, with `trino-cli` for its steps (see [Running steps](#running-steps)) | | `FLOCI_SERVICES_EMR_TRINO_IMAGE` | `trinodb/trino:%s` | The image Trino runs from, `%s` the Trino version of the cluster's release; one with no `%s` serves every release | -| `FLOCI_SERVICES_EMR_TRINO_MEMORY_MB` | `2048` | The memory of Trino's container, in MiB, 80% of which is its heap | +| `FLOCI_SERVICES_EMR_TRINO_MEMORY_MB` | `2048` | The memory of Trino's coordinator's container, in MiB, 80% of which is its heap | +| `FLOCI_SERVICES_EMR_TRINO_MAX_WORKERS` | `4` | The most Trino workers a cluster runs, one on each core or task node Floci runs, core nodes first; 0 runs none, the coordinator then running the queries itself | +| `FLOCI_SERVICES_EMR_TRINO_WORKER_MEMORY_MB` | `2048` | The memory of each Trino worker's container, in MiB, 80% of which is its heap | | `FLOCI_SERVICES_EMR_RECONCILE_CONTAINERS_ON_STARTUP` | `true` | Remove the step drivers and bootstrap containers a previous run of this Floci left on the Docker daemon, and the images bootstrap actions left for clusters that are gone or have ended, when the EMR service starts; turn it off when two Floci instances share a daemon with the same port and no resource namespace | ## Release catalogue diff --git a/src/main/java/io/floci/aws/config/EmulatorConfig.java b/src/main/java/io/floci/aws/config/EmulatorConfig.java index 2e237c0ffe..1ce8a87823 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -2543,12 +2543,30 @@ public interface EmulatorConfig { String image(); /** - * The memory, in MiB, of the container Trino runs in, 80% of which its image gives Trino's heap. + * The memory, in MiB, of the container Trino's coordinator runs in, 80% of which its image gives Trino's heap. * * Env var: FLOCI_SERVICES_EMR_TRINO_MEMORY_MB */ @WithDefault("2048") int memoryMb(); + + /** + * The most Trino workers a cluster runs: one on each of its core and task nodes, as EMR's do, of those Floci + * runs ({@code yarn-max-worker-nodes}), up to this many, core nodes first; 0 runs none, the coordinator then + * running the queries itself. + * + * Env var: FLOCI_SERVICES_EMR_TRINO_MAX_WORKERS + */ + @WithDefault("4") + int maxWorkers(); + + /** + * The memory, in MiB, of the container each Trino worker runs in, 80% of which its image gives Trino's heap. + * + * Env var: FLOCI_SERVICES_EMR_TRINO_WORKER_MEMORY_MB + */ + @WithDefault("2048") + int workerMemoryMb(); } interface WafV2ServiceConfig { diff --git a/src/main/java/io/floci/aws/services/emr/ClusterStorage.java b/src/main/java/io/floci/aws/services/emr/ClusterStorage.java index 96060b680f..ea2b6d0e05 100644 --- a/src/main/java/io/floci/aws/services/emr/ClusterStorage.java +++ b/src/main/java/io/floci/aws/services/emr/ClusterStorage.java @@ -129,7 +129,9 @@ public interface ClusterStorage { } /** - * Trino's coordinator on a cluster's primary node: the {@code image} it runs from, the memory its container gets, + * Trino on a cluster: its coordinator on the primary node, and its workers on the core and task nodes, no more than + * {@code maxWorkers} of them, each container getting {@code workerMemoryMb}. The {@code image} they run from, the + * memory the coordinator's container gets, * the cluster's {@code trino-connector-} properties by catalog, which its catalogs get after Floci's (see * {@link EmrTrino#catalogs}), its {@code trino-config} properties, which its {@code config.properties} gets after * Floci's (see {@link EmrTrino#config}), its {@code trino-node} and {@code trino-log} properties, which its @@ -138,13 +140,20 @@ public interface ClusterStorage { * {@code trino-exchange-manager} properties, null where it has none, which make its exchange manager (see * {@link EmrTrino#exchangeManager}), its {@code trino-password-authenticator} properties, which make its password * authenticator, and the image its bootstrap actions left, null where it has none, from which the files those - * properties name are copied into Trino's container ({@link EmrTrino#authenticatorFiles}), as EMR's Trino finds - * what they wrote on the primary node it runs on. It reaches S3 and Glue as the metastore does. + * properties name are copied into the coordinator's container ({@link EmrTrino#authenticatorFiles}), as EMR's + * Trino finds what they wrote on the primary node it runs on, and into a worker's from its node's own, else that + * one. Every node reaches S3 and Glue as the metastore does. */ record Trino(String image, int memoryMb, Map> connectors, Map config, Map node, Map log, Map environment, Map exchangeManager, Map passwordAuthenticator, - String bootstrapImage) { + String bootstrapImage, int maxWorkers, int workerMemoryMb) { + + /** These nodes' first {@code maxWorkers}, the core nodes first, as they come, each of which runs a worker. */ + List workers(Yarn yarn) { + List nodes = yarn != null ? yarn.nodes() : List.of(); + return List.copyOf(nodes.subList(0, Math.max(0, Math.min(maxWorkers, nodes.size())))); + } } /** diff --git a/src/main/java/io/floci/aws/services/emr/EmrClusterStorage.java b/src/main/java/io/floci/aws/services/emr/EmrClusterStorage.java index d805e5c47b..b1e731b96f 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrClusterStorage.java +++ b/src/main/java/io/floci/aws/services/emr/EmrClusterStorage.java @@ -39,9 +39,12 @@ import java.io.OutputStream; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; +import java.security.SecureRandom; import java.time.Duration; import java.util.ArrayList; +import java.util.Base64; import java.util.Collection; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -205,6 +208,8 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { // seconds (DiscoveryNodeManager), and Trino says it has started, and runs a query with no catalog, before then: // twice that, from the first time it says so. private static final Duration TRINO_SETTLE = Duration.ofSeconds(10); + // What a Trino worker's container is named after its node's. + private static final String WORKER_SUFFIX = "-trino"; // How long a node being decommissioned may take before it goes anyway: EMR's default for a graceful one, "3600s // (one hour)", and a minute more for the ResourceManager's own timeout to pass first. private static final Duration GRACEFUL_DECOMMISSION = Duration.ofHours(1); @@ -570,8 +575,14 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { // The Trino containers this process has started, which a reset or a shutdown removes before the primary nodes whose // network they share. private final Set runningTrino = ConcurrentHashMap.newKeySet(); - // Those of them that have become ready, which a later step finds running and has at once. + // Those of them that have become ready, coordinators and workers, which a later step finds running and has at once. private final Set readyTrino = ConcurrentHashMap.newKeySet(); + // For each cluster whose Trino coordinator this process started, what its workers start from. + private final Map trinoClusters = new ConcurrentHashMap<>(); + // The shared secret each Trino worker this process started was given, by container name. + private final Map workerSecrets = new ConcurrentHashMap<>(); + // Where each cluster's Trino gets its shared secret from. + private final SecureRandom secrets = new SecureRandom(); // What each cluster's last step started its nodes from, which a resize starts new ones from. private final Map nodeRequests = new ConcurrentHashMap<>(); // For each cluster, the nodes being decommissioned, by container name. @@ -927,10 +938,10 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { awaitNodes(nodeRequest, nodes, deadline, teardown, stopped); nodeRequests.put(clusterId, nodeRequest); } - // After the nodes, whose wait has the HDFS's deadline, as Trino's has its own. + // After the nodes, whose wait has the HDFS's deadline, as Trino's has its own, its workers on them. if (trino != null) { - trino(clusterId, accountId, region, containerId, trinoImageId, hiveMetastore.role(), trino, teardown, - stopped); + trino(clusterId, accountId, region, containerId, host, trinoImageId, hiveMetastore.role(), trino, + trino.workers(yarn), teardown, stopped); } SparkJobRunner.Storage storage = volumes(clusterId).withHdfs(host, address(clusterId, containerId), name); if (hiveMetastore != null) { @@ -967,6 +978,11 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { NodeRequest request = known.resizedTo(yarn.get()); nodeRequests.put(clusterId, request); reconcileNodes(request, teardown); + // Trino's workers follow the nodes, where the cluster's Trino runs, and join it as they become ready. + TrinoCluster run = trinoClusters.get(clusterId); + if (run != null && readyTrino.contains(trinoName(clusterId))) { + trinoWorkers(clusterId, run.trino().workers(request.yarn()), teardown); + } } } catch (RuntimeException e) { LOG.warnv(e, "Could not resize the nodes of EMR cluster {0}: {1}", clusterId, e.getMessage()); @@ -1325,6 +1341,10 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { // Removes a node's container and, when asked, its volume; a removal Docker refuses leaves it known, so the next // reset or shutdown tries again. Whether it has gone. private boolean removeNode(String name, boolean withVolume) { + // Its Trino worker first, which shares its network. + if (!removeTrinoKnown(workerName(name))) { + return false; + } try { lifecycleManager.removeIfExistsStrict(name); } catch (RuntimeException e) { @@ -1601,23 +1621,22 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { return containerId; } - // Trino's coordinator beside the metastore on cluster clusterId's primary node, the container primary, in a - // container of its own that shares that node's network, as a daemon of the node does, reaching Floci's S3 and Glue - // with a session for role, as the metastore does: one there is kept when it runs on this primary node with a - // session of this process's, else another starts. Until it has become ready it is waited for, as the step that - // asks runs trino-cli at once. - private void trino(String clusterId, String accountId, String region, String primary, String imageId, String role, - Trino trino, long teardown, BooleanSupplier stopped) { + // Trino's coordinator beside the metastore on cluster clusterId's primary node, the container primary, named host, + // in a container of its own that shares that node's network, as a daemon of the node does, reaching Floci's S3 and + // Glue with a session for role, as the metastore does, and a worker on each of workers, core and task nodes, the + // same way (trinoWorkers): one there is kept when it runs on this primary node with a session of this process's, + // else another starts, with a shared secret of its own, which its workers then share. Until the coordinator and + // each worker have become ready they are waited for, as the step that asks runs trino-cli at once: one an earlier + // step or a resize started too, which has not passed its health check yet. + private void trino(String clusterId, String accountId, String region, String primary, String host, String imageId, + String role, Trino trino, List workers, long teardown, BooleanSupplier stopped) { String name = trinoName(clusterId); String network = CONTAINER_NETWORK_PREFIX + lifecycleManager.getDockerClient().inspectContainerCmd(primary).exec().getId(); - boolean current = trinoCurrent(name, network); - if (current && readyTrino.contains(name)) { - // It became ready for an earlier step, and runs on. - return; - } - if (!current) { + if (!trinoCurrent(name, network) || !trinoClusters.containsKey(clusterId)) { removeTrino(name); + TrinoCluster run = new TrinoCluster(accountId, region, host, role, trino, imageId, newSecret()); + trinoClusters.put(clusterId, run); String endpoint = flociEndpointOn(hdfsName(clusterId)); Optional credentials = roleCredentials.forRole(role, accountId, name); sessions.put(name, new MetastoreSession(accountId, @@ -1625,37 +1644,15 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { // Known before it starts, so a teardown while it starts removes it. runningTrino.add(name); try { - ContainerBuilder.Builder spec = containerBuilder.newContainer(imageId) - .withName(name) - .withNetworkMode(network) - .withMemoryMb(trino.memoryMb()) - .withEntrypoint(List.of("/bin/bash", "-c", EmrTrino.ENTRYPOINT)) - .withEnv(awsEnv.sdkBaselineEnv(region, Optional.empty(), endpoint, credentials, accountId)) - // After Floci's AWS settings, which an export may change as its trino-env.sh would, and before - // the files Floci writes, which it may not: Docker keeps the last of a variable given twice. - .withEnv(trino.environment().entrySet().stream() - .map(variable -> variable.getKey() + "=" + variable.getValue()).toList()) - .withEnv(EmrTrino.CONFIG_VARIABLE, EmrTrino.properties(EmrTrino.config(trino.config()))) - .withEnv(EmrTrino.NODE_VARIABLE, EmrTrino.properties(trino.node())) - .withEnv(EmrTrino.LOG_VARIABLE, EmrTrino.properties(trino.log())) - .withEnv(EmrTrino.PASSWORD_AUTHENTICATOR_VARIABLE, - EmrTrino.properties(trino.passwordAuthenticator())) - .withJavaTrustStore() - .withLogRotation() - .withLabels(labels(clusterId, accountId, region, EmrTrino.COMPONENT)); - EmrTrino.catalogs(trino.connectors(), endpoint, region).forEach((catalog, properties) -> + ContainerBuilder.Builder spec = trinoSpec(clusterId, run, name, network, trino.memoryMb(), endpoint, + credentials.orElse(null)) + .withEnv(EmrTrino.CONFIG_VARIABLE, EmrTrino.properties(EmrTrino.config(trino.config(), + !workers.isEmpty(), run.secret()))) + .withEnv(EmrTrino.NODE_VARIABLE, EmrTrino.properties(trino.node())); + EmrTrino.catalogs(trino.connectors(), "localhost", endpoint, region).forEach((catalog, properties) -> spec.withEnv(EmrTrino.CATALOG_PREFIX + catalog, EmrTrino.properties(properties))); - if (trino.exchangeManager() != null) { - spec.withEnv(EmrTrino.EXCHANGE_VARIABLE, EmrTrino.properties(EmrTrino.exchangeManager( - trino.exchangeManager(), endpoint, region))); - } - List files = EmrTrino.authenticatorFiles(trino.passwordAuthenticator()); - if (files.isEmpty() || trino.bootstrapImage() == null) { - lifecycleManager.createAndStart(spec.build()); - } else { - lifecycleManager.createAndStart(spec.build(), container -> copyAuthenticatorFiles(clusterId, - accountId, region, container, trino.bootstrapImage(), files, trino.memoryMb())); - } + startTrino(clusterId, run, spec, trino.bootstrapImage(), trino.memoryMb(), + "Trino of EMR cluster " + clusterId, "trino.memory-mb"); } catch (RuntimeException e) { releaseSession(name); throw e; @@ -1664,8 +1661,159 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { stopIfStopped(clusterId, teardown, stopped); LOG.infov("Started the Trino of EMR cluster {0}", clusterId); } - awaitTrino(clusterId, name, teardown, stopped); - readyTrino.add(name); + // Started before the coordinator is waited for, so that they start as it does. + trinoWorkers(clusterId, workers, teardown); + if (!readyTrino.contains(name)) { + awaitTrino(clusterId, name, "Trino of EMR cluster " + clusterId, teardown, stopped); + readyTrino.add(name); + } + // A query the coordinator is asked before it has learnt of any worker waits for one, as Trino's + // query-manager.required-workers, 1, has it. + for (Node node : workers) { + String worker = workerName(nodeName(clusterId, node)); + if (runningTrino.contains(worker) && !readyTrino.contains(worker)) { + awaitTrino(clusterId, worker, workerWho(clusterId, node.host()), teardown, stopped); + readyTrino.add(worker); + } + } + } + + // A worker on each of nodes, cluster clusterId's core and task nodes that run one, in a container of its own that + // shares the node's network, as a daemon of the node does, reaching Floci's S3 and Glue with a session for the + // cluster's role, as the coordinator does: one there is kept when it runs on that node's container now, with the + // shared secret of the coordinator now running and a session of this process's, else another starts; one on a node + // no longer among them goes, as its node is decommissioned or leaves. None where this process runs no coordinator + // for the cluster. One it starts has yet to become ready. + private void trinoWorkers(String clusterId, List nodes, long teardown) { + TrinoCluster run = trinoClusters.get(clusterId); + if (run == null) { + return; + } + Set wanted = new HashSet<>(); + for (Node node : nodes) { + String nodeName = nodeName(clusterId, node); + String name = workerName(nodeName); + wanted.add(name); + String network; + try { + network = CONTAINER_NETWORK_PREFIX + + lifecycleManager.getDockerClient().inspectContainerCmd(nodeName).exec().getId(); + } catch (NotFoundException e) { + // Its node did not start: it runs no worker either. + LOG.warnv("Node {0} of EMR cluster {1} runs no Trino worker, as its container is not there", + node.host(), clusterId); + continue; + } + if (trinoCurrent(name, network) && run.secret().equals(workerSecrets.get(name))) { + continue; + } + removeTrino(name); + startWorker(clusterId, run, node, name, network); + if (teardowns.get() != teardown) { + // A teardown that looked for it before Docker made it has passed it by. + removeTrinoKnown(name); + return; + } + } + for (String name : List.copyOf(runningTrino)) { + if (workerOf(clusterId, name) && !wanted.contains(name)) { + removeTrinoKnown(name); + } + } + } + + // Cluster clusterId's Trino worker on node, its node's container sharing network: as the coordinator, but a worker + // finding it on the primary node, at the address of its node's host, with the memory a worker gets, its catalogs' + // metastore on the primary node, the files its password authenticator names copied from the image its node's own + // bootstrap actions left, else the cluster's. + private void startWorker(String clusterId, TrinoCluster run, Node node, String name, String network) { + Trino trino = run.trino(); + String endpoint = flociEndpointOn(hdfsName(clusterId)); + Optional credentials = roleCredentials.forRole(run.role(), run.accountId(), name); + sessions.put(name, new MetastoreSession(run.accountId(), + credentials.map(SessionCreds::accessKeyId).orElse(null), endpoint)); + // Known before it starts, so a teardown while it starts removes it. + runningTrino.add(name); + workerSecrets.put(name, run.secret()); + try { + ContainerBuilder.Builder spec = trinoSpec(clusterId, run, name, network, trino.workerMemoryMb(), endpoint, + credentials.orElse(null)) + .withEnv(EmrTrino.CONFIG_VARIABLE, EmrTrino.properties(EmrTrino.workerConfig(trino.config(), + run.host(), run.secret()))) + .withEnv(EmrTrino.NODE_VARIABLE, EmrTrino.properties(EmrTrino.workerNode(trino.node(), + node.host()))); + EmrTrino.catalogs(trino.connectors(), run.host(), endpoint, run.region()).forEach((catalog, properties) -> + spec.withEnv(EmrTrino.CATALOG_PREFIX + catalog, EmrTrino.properties(properties))); + startTrino(clusterId, run, spec, node.image() != null ? node.image() : trino.bootstrapImage(), + trino.workerMemoryMb(), workerWho(clusterId, node.host()), "trino.worker-memory-mb"); + } catch (RuntimeException e) { + releaseSession(name); + workerSecrets.remove(name); + throw e; + } + LOG.infov("Started the Trino worker of EMR cluster {0} on node {1}", clusterId, node.host()); + } + + // A Trino container named so, the coordinator's or a worker's, from the cluster's Trino image in network with + // memoryMb, reaching Floci's S3 and Glue at endpoint with credentials, null where there are none, with what every + // node of the cluster's Trino has: its environment, log properties, exchange manager and password authenticator. + // Its configuration, node properties and catalogs are its own, the caller's to add. + private ContainerBuilder.Builder trinoSpec(String clusterId, TrinoCluster run, String name, String network, + int memoryMb, String endpoint, SessionCreds credentials) { + Trino trino = run.trino(); + ContainerBuilder.Builder spec = containerBuilder.newContainer(run.imageId()) + .withName(name) + .withNetworkMode(network) + .withMemoryMb(memoryMb) + .withEntrypoint(List.of("/bin/bash", "-c", EmrTrino.ENTRYPOINT)) + .withEnv(awsEnv.sdkBaselineEnv(run.region(), Optional.empty(), endpoint, + Optional.ofNullable(credentials), run.accountId())) + // After Floci's AWS settings, which an export may change as its trino-env.sh would, and before the + // files Floci writes, which it may not: Docker keeps the last of a variable given twice. + .withEnv(trino.environment().entrySet().stream() + .map(variable -> variable.getKey() + "=" + variable.getValue()).toList()) + .withEnv(EmrTrino.LOG_VARIABLE, EmrTrino.properties(trino.log())) + .withEnv(EmrTrino.PASSWORD_AUTHENTICATOR_VARIABLE, EmrTrino.properties(trino.passwordAuthenticator())) + .withJavaTrustStore() + .withLogRotation() + .withLabels(labels(clusterId, run.accountId(), run.region(), EmrTrino.COMPONENT)); + if (trino.exchangeManager() != null) { + // The same NameNode on every node, as a worker spools to the files the coordinator names. + String namenode = EmrTrino.namenode(run.host()); + spec.withEnv(EmrTrino.EXCHANGE_VARIABLE, EmrTrino.properties(EmrTrino.exchangeManager( + trino.exchangeManager(), namenode, endpoint, run.region()))) + .withEnv(EmrTrino.EXCHANGE_SITE_VARIABLE, EmrTrino.exchangeSite(namenode)); + } + return spec; + } + + // Starts a Trino container from spec, the files its password authenticator names copied in first from image, where + // there is one, none larger than memoryMb, the setting named so, lets the container read: who names it, as "Trino + // of EMR cluster j-1". + private void startTrino(String clusterId, TrinoCluster run, ContainerBuilder.Builder spec, String image, + int memoryMb, String who, String setting) { + List files = EmrTrino.authenticatorFiles(run.trino().passwordAuthenticator()); + if (files.isEmpty() || image == null) { + lifecycleManager.createAndStart(spec.build()); + } else { + lifecycleManager.createAndStart(spec.build(), container -> copyAuthenticatorFiles(clusterId, + run.accountId(), run.region(), container, image, files, memoryMb, who, setting)); + } + } + + // A new shared secret for a cluster's Trino nodes, as EMR "automatically configures a shared secret key": 32 + // random bytes, in Base64. It is in each Trino container's environment, as the rest of their configuration is. + private String newSecret() { + byte[] bytes = new byte[32]; + secrets.nextBytes(bytes); + return Base64.getEncoder().encodeToString(bytes); + } + + // What a cluster's Trino workers start from: the account and Region of the cluster, its primary node's host, the + // role its nodes reach S3 and Glue with, its Trino, the image Trino runs from, and the shared secret of the + // coordinator now running. + private record TrinoCluster(String accountId, String region, String host, String role, Trino trino, + String imageId, String secret) { } // The files the cluster's password authenticator names, copied into container, its Trino's, made and not started, @@ -1678,7 +1826,7 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { // start. The image is read in a container made from it and never started, labelled as the cluster's Trino, so that // a Floci that stops while it copies sweeps it with that Trino. private void copyAuthenticatorFiles(String clusterId, String accountId, String region, String container, - String image, List files, int memoryMb) { + String image, List files, int memoryMb, String who, String setting) { DockerClient docker = lifecycleManager.getDockerClient(); String source = docker.createContainerCmd(image) .withLabels(labels(clusterId, accountId, region, EmrTrino.COMPONENT)).exec().getId(); @@ -1689,8 +1837,8 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { try { copied = ContainerFiles.copy(docker, source, file, container, 0644, maxBytes); } catch (IllegalArgumentException e) { - throw new IllegalArgumentException("The Trino of EMR cluster " + clusterId + " cannot read " + file - + " into the memory its container gets (trino.memory-mb): " + e.getMessage(), e); + throw new IllegalArgumentException("The " + who + " cannot read " + file + + " into the memory its container gets (" + setting + "): " + e.getMessage(), e); } if (!copied) { LOG.infov("The image the bootstrap actions of EMR cluster {0} left holds no {1}, which its" @@ -1736,6 +1884,7 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { private void removeTrino(String name) { lifecycleManager.removeIfExistsStrict(name); releaseSession(name); + workerSecrets.remove(name); runningTrino.remove(name); readyTrino.remove(name); } @@ -1752,18 +1901,18 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { } } - // Waits for the Trino container named so to have said it has started for TRINO_SETTLE, within TRINO_START_TIMEOUT - // (EmrTrino.READY_CHECK): until its node manager has learnt that it serves its catalogs, a query that reads one - // fails "No nodes available to run query", one with none running already. - private void awaitTrino(String clusterId, String name, long teardown, BooleanSupplier stopped) { + // Waits for the Trino container named so, the coordinator's or a worker's, who names it, to have said it has + // started for TRINO_SETTLE, within TRINO_START_TIMEOUT (EmrTrino.READY_CHECK): until the coordinator's node + // manager has learnt that a node serves its catalogs, a query that reads one fails "No nodes available to run + // query", one with none running already. + private void awaitTrino(String clusterId, String name, String who, long teardown, BooleanSupplier stopped) { long deadline = nanoTime.getAsLong() + TRINO_START_TIMEOUT.toNanos(); long answering = Long.MIN_VALUE; while (teardowns.get() == teardown && !stopped.getAsBoolean()) { // Docker refuses an exec into a container that has stopped, so that is looked at first. if (lifecycleManager.probeContainer(name) == ContainerLiveness.NOT_RUNNING) { - logTrinoOutput(clusterId, name); - throw new IllegalStateException("The Trino of EMR cluster " + clusterId - + " stopped before it was ready"); + logTrinoOutput(who, name); + throw new IllegalStateException("The " + who + " stopped before it was ready"); } ContainerExec.Result check; try { @@ -1787,23 +1936,24 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { return; } if (now >= deadline) { - logTrinoOutput(clusterId, name); - throw new IllegalStateException("The Trino of EMR cluster " + clusterId + " did not start within " + logTrinoOutput(who, name); + throw new IllegalStateException("The " + who + " did not start within " + TRINO_START_TIMEOUT.toSeconds() + " seconds"); } try { Thread.sleep(HDFS_POLL_INTERVAL.toMillis()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); - throw new IllegalStateException("Stopped waiting for the Trino of EMR cluster " + clusterId, e); + throw new IllegalStateException("Stopped waiting for the " + who, e); } } stopIfStopped(clusterId, teardown, stopped); } - // What a Trino that did not become ready last wrote, in Floci's log, as its container goes with its cluster. - private void logTrinoOutput(String clusterId, String name) { - LOG.warnv("The Trino of EMR cluster {0} did not become ready. It last wrote:\n{1}", clusterId, + // What a Trino that did not become ready, who names it, last wrote, in Floci's log, as its container goes with its + // cluster. + private void logTrinoOutput(String who, String name) { + LOG.warnv("The {0} did not become ready. It last wrote:\n{1}", who, lifecycleManager.lastLogLines(name, NODE_LOG_LINES, NODE_LOG_READ)); } @@ -1811,6 +1961,22 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { return ContainerStorageHelper.dockerName(config, SERVICE + "-" + clusterId + "-trino"); } + // The container of the Trino worker on the core or task node whose container is named nodeName. + private static String workerName(String nodeName) { + return nodeName + WORKER_SUFFIX; + } + + // Whether the container named so is one of cluster clusterId's Trino workers. + private boolean workerOf(String clusterId, String name) { + return name.startsWith(ContainerStorageHelper.dockerName(config, SERVICE + "-" + clusterId + "-node-")) + && name.endsWith(WORKER_SUFFIX); + } + + // What names the Trino worker on the node named host in messages. + private static String workerWho(String clusterId, String host) { + return "Trino worker on node " + host + " of EMR cluster " + clusterId; + } + // The subnet of a cluster's own network, which exists, as Docker says it: where it is known, the cluster's nodes join // the steps' network too, their HDFS and YARN listening on their address in that subnet alone (see BIND_SETUP), so // the steps' network's containers, other clusters' among them, reach neither; where it is not, they stay on their @@ -2246,7 +2412,15 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { nodeRequests.remove(clusterId); draining.remove(clusterId); departed.remove(clusterId); + trinoClusters.remove(clusterId); + // Its Trino workers first, which share their nodes' networks, those this process knows even where Docker + // lists no node, then any that goes with its node. boolean nodesGone = true; + for (String name : List.copyOf(runningTrino)) { + if (workerOf(clusterId, name)) { + nodesGone &= removeTrinoKnown(name); + } + } try { for (String node : nodeContainers(clusterId).keySet()) { nodesGone &= removeNode(node, true); @@ -2289,6 +2463,8 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { nodeRequests.clear(); draining.clear(); departed.clear(); + trinoClusters.clear(); + // Each node with its Trino worker, which shares its network. for (String name : List.copyOf(runningNodes)) { removeNode(name, false); } diff --git a/src/main/java/io/floci/aws/services/emr/EmrService.java b/src/main/java/io/floci/aws/services/emr/EmrService.java index a54988b14d..eaf6ac6b12 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrService.java +++ b/src/main/java/io/floci/aws/services/emr/EmrService.java @@ -203,10 +203,12 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear // Whether a cluster whose Applications name Pig gets Apache Pig in its image (floci.services.emr.pig.enabled). private final boolean pigEnabled; // Whether a cluster whose Applications name Trino runs it (floci.services.emr.trino.enabled), from which image, the - // release's Trino version for %s, and with how much memory. + // release's Trino version for %s, with how much memory for its coordinator, and how many workers with how much. private final boolean trinoEnabled; private final String trinoImageTemplate; private final int trinoMemoryMb; + private final int trinoMaxWorkers; + private final int trinoWorkerMemoryMb; // What the NodeManager of a cluster that runs YARN offers its containers. private final ClusterStorage.Yarn nodeManager; private final int maxWorkerNodes; @@ -392,6 +394,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear this.trinoEnabled = config.services().emr().trino().enabled(); this.trinoImageTemplate = trinoEnabled ? config.services().emr().trino().image() : null; this.trinoMemoryMb = trinoEnabled ? config.services().emr().trino().memoryMb() : 0; + this.trinoMaxWorkers = trinoEnabled ? config.services().emr().trino().maxWorkers() : 0; + this.trinoWorkerMemoryMb = trinoEnabled ? config.services().emr().trino().workerMemoryMb() : 0; this.nodeManager = new ClusterStorage.Yarn(config.services().emr().yarnNodeMemoryMb(), config.services().emr().yarnNodeVcores()); this.maxWorkerNodes = config.services().emr().yarnMaxWorkerNodes(); @@ -3153,7 +3157,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear EmrSparkSteps.trinoEnvironment(cluster.getConfigurations(), SNAPSHOT_MAPPER), EmrSparkSteps.trinoExchangeManager(cluster.getConfigurations(), SNAPSHOT_MAPPER), EmrSparkSteps.trinoPasswordAuthenticator(cluster.getConfigurations(), SNAPSHOT_MAPPER), - cluster.getBootstrapImage()); + cluster.getBootstrapImage(), trinoMaxWorkers, trinoWorkerMemoryMb); boolean withHdfs = !EmrSparkSteps.trinoAlone(cluster.getReleaseLabel(), cluster.getApplications(), SNAPSHOT_MAPPER); ClusterStorage.HiveMetastore hiveMetastore = withHiveImage(cluster) diff --git a/src/main/java/io/floci/aws/services/emr/EmrTrino.java b/src/main/java/io/floci/aws/services/emr/EmrTrino.java index 3cdb44dba8..e33cc239af 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrTrino.java +++ b/src/main/java/io/floci/aws/services/emr/EmrTrino.java @@ -11,10 +11,13 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; /** - * Trino on the primary node of a {@code docker} cluster whose {@code Applications} name it, with - * {@code floci.services.emr.trino.enabled} on: no AWS image carries Trino, so its coordinator, which runs the queries - * too, as a cluster of one node's does, runs from the Trino project's image of the version the release's page in the - * Release Guide gives, in a container of its own that shares the primary node's network, as a daemon of that node. + * Trino on a {@code docker} cluster whose {@code Applications} name it, with + * {@code floci.services.emr.trino.enabled} on: no AWS image carries Trino, so its coordinator runs on the primary node + * from the Trino project's image of the version the release's page in the Release Guide gives, in a container of its + * own that shares the primary node's network, as a daemon of that node, and a worker the same way on each of the core + * and task nodes Floci runs, up to {@code trino.max-workers}, in EMR's "coordinator-worker model". The coordinator runs + * the queries too only on a cluster with no workers, as Trino's deployment guide has a coordinator with workers run + * none, and a cluster of one node run them. * "By default, Amazon EMR configures the Presto web interface on the Presto coordinator to use port 8889 (for PrestoDB * and Trino)", where it listens unless the cluster's {@code trino-config} sets {@code http-server.http.port}, which * classification changes "Trino's config.properties file". Its catalogs are the {@code hive} one and those the @@ -97,40 +100,36 @@ final class EmrTrino { static final String LOG_VARIABLE = "FLOCI_TRINO_LOG"; static final String EXCHANGE_VARIABLE = "FLOCI_TRINO_EXCHANGE"; static final String PASSWORD_AUTHENTICATOR_VARIABLE = "FLOCI_TRINO_PASSWORD_AUTHENTICATOR"; - /** The cluster's NameNode, which Trino reaches on the primary node whose network it shares. */ - static final String NAMENODE = "hdfs://localhost:8020"; /** * The Hadoop configuration Trino's {@code hdfs} exchange manager reads, as EMR's {@code hdfs.config.resources} - * names "the paths to core-site.xml, hdfs-site.xml files": its default file system the cluster's NameNode, without - * which Trino takes an {@code hdfs://} directory for another file system's, "Wrong FS ... expected: file:///". + * names "the paths to core-site.xml, hdfs-site.xml files", which the entrypoint writes from the variable after + * ({@link #exchangeSite}). */ static final String EXCHANGE_HDFS_CONFIG = "/etc/trino/exchange-core-site.xml"; - static final String EXCHANGE_CORE_SITE = "fs.defaultFS" + NAMENODE - + ""; + static final String EXCHANGE_SITE_VARIABLE = "FLOCI_TRINO_EXCHANGE_SITE"; + /** + * The property of Trino's {@code config.properties} that holds the secret its nodes sign their requests to each + * other with, which Trino needs with authentication on and every node shares. + */ + static final String SHARED_SECRET = "internal-communication.shared-secret"; /** The prefix of the variables it writes its catalogs from, one each, the rest of whose name names it. */ static final String CATALOG_PREFIX = "FLOCI_TRINO_CATALOG_"; /** - * The Trino container's entrypoint: its configuration, with a shared secret for Trino's internal communication - * unless the cluster's {@code trino-config} names one, as EMR "automatically configures a shared secret key for - * secure internal communication between cluster nodes ... and you can override the configuration with your own - * secret key", without which Trino refuses to start with authentication on, a new one each time it starts, which - * its one node shares with none; the cluster's node and log properties after those of its image's own files, which - * a property given twice takes the later of, so an image of the cluster's own keeps its settings; its password - * authenticator, where the cluster gives one; and the catalogs Floci gives it alone, as EMR's Trino has the - * catalogs the cluster configures; then Trino, as its image starts it. Where {@code node.properties} gives the node - * no id, its image names it after its host, the primary node's, whose dots Trino refuses in a node's id, so Floci - * names it with hyphens instead. + * A Trino container's entrypoint, the coordinator's or a worker's: its configuration, as Floci gives it, the + * cluster's shared secret in it ({@link #config}); the cluster's node and log properties after those of its image's + * own files, which a property given twice takes the later of, so an image of the cluster's own keeps its settings; + * its exchange manager and password authenticator, where the cluster gives them; and the catalogs Floci gives it + * alone, as EMR's Trino has the catalogs the cluster configures; then Trino, as its image starts it. Where + * {@code node.properties} gives the node no id, its image names it after its host, the node's, whose dots Trino + * refuses in a node's id, so Floci names it with hyphens instead. */ static final String ENTRYPOINT = "printf '%s\\n' \"$" + CONFIG_VARIABLE + "\" > /etc/trino/config.properties" - + " && { grep -q '^internal-communication\\.shared-secret=' /etc/trino/config.properties" - + " || printf 'internal-communication.shared-secret=%s\\n' \"$(head -c 32 /dev/urandom | base64 -w0)\"" - + " >> /etc/trino/config.properties; }" + " && { [ -z \"$" + NODE_VARIABLE + "\" ] || printf '\\n%s\\n' \"$" + NODE_VARIABLE + "\"" + " >> /etc/trino/node.properties; }" + " && { [ -z \"$" + LOG_VARIABLE + "\" ] || printf '\\n%s\\n' \"$" + LOG_VARIABLE + "\"" + " >> /etc/trino/log.properties; }" + " && { [ -z \"$" + EXCHANGE_VARIABLE + "\" ] || { printf '%s\\n' \"$" + EXCHANGE_VARIABLE + "\"" - + " > /etc/trino/exchange-manager.properties && printf '%s\\n' '" + EXCHANGE_CORE_SITE + "' > " + + " > /etc/trino/exchange-manager.properties && printf '%s\\n' \"$" + EXCHANGE_SITE_VARIABLE + "\" > " + EXCHANGE_HDFS_CONFIG + "; }; }" + " && { [ -z \"$" + PASSWORD_AUTHENTICATOR_VARIABLE + "\" ] || printf '%s\\n' \"$" + PASSWORD_AUTHENTICATOR_VARIABLE + "\" > /etc/trino/password-authenticator.properties; }" @@ -146,7 +145,7 @@ final class EmrTrino { private static final String USE_LOCAL_HDFS = "exchange.use-local-hdfs"; private static final String BASE_DIRECTORIES = "exchange.base-directories"; // "spooling occurs in the trino-exchange/ directory by default", relative, so in the HDFS home of the user Trino - // runs as, its image's trino, on the cluster's NameNode, which Trino reaches on the primary node it shares. + // runs as, its image's trino, on the cluster's NameNode. private static final String DEFAULT_EXCHANGE_DIRECTORY = "trino-exchange/"; private static final String HDFS_HOME = "/user/trino/"; private static final String METASTORE_URI = "hive.metastore.uri"; @@ -213,22 +212,69 @@ final class EmrTrino { static final List READY_CHECK = List.of("/usr/lib/trino/bin/health-check"); /** - * 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; 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. + * The coordinator's {@code config.properties}: a coordinator that runs the queries too only where the cluster has + * no workers, on its {@link #port}, its 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; the cluster's {@code secret}, as EMR "automatically + * configures a shared secret key for secure internal communication between cluster nodes"; and that + * classification's properties after these, each in its place, as "you can override the configuration with your own + * secret key". */ - static Map config(Map classification) { + static Map config(Map classification, boolean withWorkers, String secret) { Map config = new LinkedHashMap<>(); config.put("coordinator", "true"); - config.put("node-scheduler.include-coordinator", "true"); + config.put("node-scheduler.include-coordinator", String.valueOf(!withWorkers)); 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.put(SHARED_SECRET, secret); config.putAll(classification); return config; } + /** + * A worker's {@code config.properties}: no coordinator, on the cluster's {@link #port}, finding the coordinator + * on the primary node named {@code primaryHost} at that port; the cluster's {@code secret}; and the cluster's + * {@code trino-config} after these, as "configuration properties must be set on the coordinator and all worker + * nodes" unless Trino says otherwise of one. + */ + static Map workerConfig(Map classification, String primaryHost, String secret) { + Map config = new LinkedHashMap<>(); + config.put("coordinator", "false"); + config.put("http-server.http.port", String.valueOf(PORT)); + config.put("discovery.uri", server(primaryHost, port(classification))); + config.put(SHARED_SECRET, secret); + config.putAll(classification); + return config; + } + + /** + * A worker's {@code node.properties} additions: the address the other nodes reach it at, its node's + * {@code host}, which Trino would otherwise pick from the node's addresses, link-local ones and those of other + * networks among them; then the cluster's {@code trino-node}, each in its place. + */ + static Map workerNode(Map classification, String host) { + Map node = new LinkedHashMap<>(); + node.put("node.internal-address", host); + node.putAll(classification); + return node; + } + + /** The cluster's NameNode, on the primary node named {@code primaryHost}, as every node reaches it. */ + static String namenode(String primaryHost) { + return "hdfs://" + primaryHost + ":8020"; + } + + /** + * The Hadoop configuration for Trino's {@code hdfs} exchange manager ({@link #EXCHANGE_HDFS_CONFIG}): its default + * file system the cluster's {@code namenode}, without which Trino takes an {@code hdfs://} directory for another + * file system's, "Wrong FS ... expected: file:///". + */ + static String exchangeSite(String namenode) { + return "fs.defaultFS" + namenode + + ""; + } + /** * Trino's {@code exchange-manager.properties} for a cluster's {@code trino-exchange-manager}, which on EMR * "internally creates a etc/exchange-manager.properties configuration file" and "sets exchange-manager.name ... to @@ -236,10 +282,12 @@ final class EmrTrino { * spooling "in the trino-exchange/ directory", or where {@code exchange.base-directories} says, which with * {@code exchange.use-local-hdfs} names HDFS directories. The Trino project's Trino takes neither EMR's * {@code exchange.use-local-hdfs} nor an {@code hdfs://} directory in a {@code filesystem} exchange manager, so a - * directory with no scheme is the cluster's HDFS in its own {@code hdfs} exchange manager; one in S3 is Floci's S3 - * at {@code endpoint} in {@code region}, by path; and the classification's other properties come after these. + * directory with no scheme is the cluster's HDFS, at {@code namenode}, in its own {@code hdfs} exchange manager, + * the same on every node, as the coordinator names the files its workers spool to; one in S3 is Floci's S3 at + * {@code endpoint} in {@code region}, by path; and the classification's other properties come after these. */ - static Map exchangeManager(Map classification, String endpoint, String region) { + static Map exchangeManager(Map classification, String namenode, String endpoint, + String region) { List directories = new ArrayList<>(); for (String directory : classification.getOrDefault(BASE_DIRECTORIES, DEFAULT_EXCHANGE_DIRECTORY).split(",")) { String trimmed = directory.trim(); @@ -247,7 +295,7 @@ final class EmrTrino { continue; } directories.add(trimmed.contains("://") ? trimmed - : NAMENODE + (trimmed.startsWith("/") ? trimmed : HDFS_HOME + trimmed)); + : namenode + (trimmed.startsWith("/") ? trimmed : HDFS_HOME + trimmed)); } boolean hdfs = directories.stream().anyMatch(directory -> directory.startsWith("hdfs://")); Map exchange = new LinkedHashMap<>(); @@ -274,27 +322,28 @@ final class EmrTrino { * Trino's catalogs, by name: {@code hive}, then each that {@code connectors}, the cluster's * {@code trino-connector-} classifications' properties by catalog, name (see {@link #catalog}). */ - static Map> catalogs(Map> connectors, String endpoint, - String region) { + static Map> catalogs(Map> connectors, + String metastoreHost, String endpoint, String region) { Map> catalogs = new LinkedHashMap<>(); - catalogs.put(HIVE, catalog(HIVE, connectors.getOrDefault(HIVE, Map.of()), endpoint, region)); + catalogs.put(HIVE, catalog(HIVE, connectors.getOrDefault(HIVE, Map.of()), metastoreHost, endpoint, region)); connectors.forEach((name, classification) -> catalogs.computeIfAbsent(name, - catalog -> catalog(catalog, classification, endpoint, region))); + catalog -> catalog(catalog, classification, metastoreHost, endpoint, region))); return catalogs; } /** * A catalog: the connector of its name, as the Release Guide's Delta Lake tutorial gives {@code delta} no * {@code connector.name} of its own; for {@code hive}, {@code delta}, {@code hudi} and {@code iceberg}, the - * cluster's metastore, which runs beside Trino on the primary node, or Floci's Glue where the classification says + * cluster's metastore on the primary node, at {@code metastoreHost}, {@code localhost} for the coordinator beside + * it and the primary node's host for a worker, or Floci's Glue where the classification says * {@code glue} ({@code hive.metastore}, or Iceberg's {@code iceberg.catalog.type}), and Floci's S3 at * {@code endpoint} in {@code region}, by path, with the HDFS of the cluster's warehouse through Hadoop's file * system; for {@code delta}, writes to S3, which the tutorial makes with only a metastore configured; and the * classification's properties after these, each in its place. Credentials come from the container's environment, * as neither file system has a setting for a session's token. */ - static Map catalog(String name, Map classification, String endpoint, - String region) { + static Map catalog(String name, Map classification, String metastoreHost, + String endpoint, String region) { Map catalog = new LinkedHashMap<>(); catalog.put("connector.name", CONNECTORS.getOrDefault(name, name)); if (LAKES.contains(name)) { @@ -305,7 +354,7 @@ final class EmrTrino { catalog.put("hive.metastore.glue.region", region); catalog.put("hive.metastore.glue.endpoint-url", endpoint); } else if (type == null || "thrift".equalsIgnoreCase(type) || "hive_metastore".equalsIgnoreCase(type)) { - catalog.put(METASTORE_URI, "thrift://localhost:" + EmrClusterStorage.HIVE_METASTORE_PORT); + catalog.put(METASTORE_URI, "thrift://" + metastoreHost + ":" + EmrClusterStorage.HIVE_METASTORE_PORT); } catalog.put("fs.native-s3.enabled", "true"); catalog.put("fs.hadoop.enabled", "true"); diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 16bcd15086..6061c30736 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -740,7 +740,9 @@ floci: trino: enabled: false # true = run Trino on a docker cluster that installs Trino # image: trinodb/trino:%s # %s = the release's Trino version - # memory-mb: 2048 # its container's memory, 80% of which is Trino's heap + # memory-mb: 2048 # its coordinator's container's memory, 80% of which is Trino's heap + # max-workers: 4 # the most workers a cluster runs, one per core or task node; 0 = none + # worker-memory-mb: 2048 # each worker's container's memory, 80% of which is Trino's heap # Remove the step drivers a previous run of this deployment left on the daemon, and the images # bootstrap actions left for clusters that are gone or have ended, when the EMR service starts. # Scoped to this deployment's own containers and images. diff --git a/src/test/java/io/floci/aws/services/emr/EmrClusterStorageTest.java b/src/test/java/io/floci/aws/services/emr/EmrClusterStorageTest.java index 4af186a3b2..56659a51f5 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrClusterStorageTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrClusterStorageTest.java @@ -68,6 +68,7 @@ import java.nio.file.Path; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; +import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -137,7 +138,7 @@ class EmrClusterStorageTest { private static final ClusterStorage.HiveMetastore TRINO_METASTORE = new ClusterStorage.HiveMetastore("arn:aws:iam::123456789012:role/r", Map.of(), new ClusterStorage.Trino("trinodb/trino:446", 2048, Map.of(), Map.of(), Map.of(), Map.of(), - Map.of(), null, Map.of(), null)); + Map.of(), null, Map.of(), null, 0, 1024)); private final EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); private final DockerClient docker = mock(DockerClient.class); @@ -160,6 +161,8 @@ class EmrClusterStorageTest { private final String historyName = ContainerStorageHelper.dockerName(config, "emr-j-1-history"); private final String coreName = ContainerStorageHelper.dockerName(config, "emr-j-1-node-1-1"); private final String taskName = ContainerStorageHelper.dockerName(config, "emr-j-1-node-2-1"); + private final String coreWorker = coreName + "-trino"; + private final String taskWorker = taskName + "-trino"; @BeforeEach void docker() { @@ -2016,13 +2019,14 @@ class EmrClusterStorageTest { verify(trinoSpec).withNetworkMode("container:c6c6c6"); verify(trinoSpec).withMemoryMb(2048); verify(trinoSpec).withEnv(List.of("AWS_ACCESS_KEY_ID=ASIATRINO")); - verify(trinoSpec).withEnv(EmrTrino.CONFIG_VARIABLE, EmrTrino.properties(EmrTrino.config(Map.of()))); + // A coordinator that runs the queries too, as the cluster has no workers, with a shared secret of its own. + verify(trinoSpec).withEnv(eq(EmrTrino.CONFIG_VARIABLE), argThat(config -> coordinatorConfig(true, config))); verify(trinoSpec).withEnv(EmrTrino.NODE_VARIABLE, ""); verify(trinoSpec).withEnv(EmrTrino.LOG_VARIABLE, ""); // No trino-exchange-manager, so no exchange manager, as on EMR. verify(trinoSpec, never()).withEnv(eq(EmrTrino.EXCHANGE_VARIABLE), anyString()); verify(trinoSpec).withEnv(EmrTrino.CATALOG_PREFIX + "hive", EmrTrino.properties(EmrTrino.catalog("hive", - Map.of(), "http://host.docker.internal:4566", "us-east-1"))); + Map.of(), "localhost", "http://host.docker.internal:4566", "us-east-1"))); verify(trinoSpec).withEntrypoint(List.of("/bin/bash", "-c", EmrTrino.ENTRYPOINT)); verify(trinoSpec).withJavaTrustStore(); verify(trinoSpec).withLabels(argThat(labels -> @@ -2083,7 +2087,7 @@ class EmrClusterStorageTest { Map.of(), new ClusterStorage.Trino("trinodb/trino:446", 2048, Map.of(), Map.of(), Map.of("node.environment", "production"), Map.of("io.trino", "DEBUG"), Map.of("DB_PASSWORD", "s3cret"), Map.of("exchange.base-directories", "s3://spool/exchange"), - authenticator, null)); + authenticator, null, 0, 1024)); ticking.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", metastore, null, NOT_STOPPED); @@ -2092,11 +2096,12 @@ class EmrClusterStorageTest { InOrder order = inOrder(trinoSpec); order.verify(trinoSpec).withEnv(List.of("AWS_ACCESS_KEY_ID=ASIATRINO")); order.verify(trinoSpec).withEnv(List.of("DB_PASSWORD=s3cret")); - order.verify(trinoSpec).withEnv(EmrTrino.CONFIG_VARIABLE, EmrTrino.properties(EmrTrino.config(Map.of()))); - order.verify(trinoSpec).withEnv(EmrTrino.NODE_VARIABLE, "node.environment=production"); order.verify(trinoSpec).withEnv(EmrTrino.LOG_VARIABLE, "io.trino=DEBUG"); order.verify(trinoSpec).withEnv(EmrTrino.PASSWORD_AUTHENTICATOR_VARIABLE, "password-authenticator.name=file\nfile.password-file=/etc/trino/password.db"); + order.verify(trinoSpec).withEnv(eq(EmrTrino.CONFIG_VARIABLE), + argThat(config -> coordinatorConfig(true, config))); + order.verify(trinoSpec).withEnv(EmrTrino.NODE_VARIABLE, "node.environment=production"); // With no image the cluster's bootstrap actions left, nothing to copy its password file from: Trino's own // image may hold it. verify(lifecycle, never()).createAndStart(any(), any(Consumer.class)); @@ -2107,6 +2112,175 @@ class EmrClusterStorageTest { + "exchange.s3.region=us-east-1\nexchange.s3.path-style-access=true"); } + @Test + void trinosWorkersRunOnTheCoreAndTaskNodesNetworksFindingTheCoordinatorWithItsSecret() { + WorkerStubs stubs = trinoAndWorkersStart(coreName, taskName); + ContainerBuilder.Builder trinoSpec = stubs.trino().spec(); + Optional coreSession = Optional.of(new SessionCreds("ASIACOREWORKER", "s", "t")); + when(roleCredentials.forRole("arn:aws:iam::123456789012:role/r", "123456789012", coreWorker)) + .thenReturn(coreSession); + when(awsEnv.sdkBaselineEnv("us-east-1", Optional.empty(), "http://host.docker.internal:4566", coreSession, + "123456789012")).thenReturn(List.of("AWS_ACCESS_KEY_ID=ASIACOREWORKER")); + + ticking.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", trinoWithWorkers(4), + () -> TWO_NODES, NOT_STOPPED); + + // A worker on each node, in its own container on the node's network, as a daemon of the node, with the memory + // a worker gets. + verify(trinoSpec).withName(coreWorker); + verify(trinoSpec).withName(taskWorker); + verify(trinoSpec).withNetworkMode("container:" + coreName + "-id"); + verify(trinoSpec).withNetworkMode("container:" + taskName + "-id"); + verify(trinoSpec, times(2)).withMemoryMb(1024); + // The coordinator leaves the queries to them, and they find it on the primary node, all with its secret. + ArgumentCaptor configs = ArgumentCaptor.forClass(String.class); + verify(trinoSpec, times(3)).withEnv(eq(EmrTrino.CONFIG_VARIABLE), configs.capture()); + String coordinator = configs.getAllValues().get(0); + assertTrue(coordinatorConfig(false, coordinator), coordinator); + String secret = coordinator.substring(coordinator.indexOf(EmrTrino.SHARED_SECRET + "=") + + EmrTrino.SHARED_SECRET.length() + 1).split("\n")[0]; + String worker = EmrTrino.properties(EmrTrino.workerConfig(Map.of(), HOST, secret)); + assertEquals(List.of(worker, worker), configs.getAllValues().subList(1, 3)); + // Each reached at its node's host, its catalogs' metastore on the primary node. + verify(trinoSpec).withEnv(EmrTrino.NODE_VARIABLE, "node.internal-address=" + CORE_HOST); + verify(trinoSpec).withEnv(EmrTrino.NODE_VARIABLE, "node.internal-address=" + TASK_HOST); + verify(trinoSpec, times(2)).withEnv(EmrTrino.CATALOG_PREFIX + "hive", EmrTrino.properties( + EmrTrino.catalog("hive", Map.of(), HOST, "http://host.docker.internal:4566", "us-east-1"))); + // Each with a session of its own for the cluster's role, and waited for as the coordinator is. + verify(trinoSpec).withEnv(List.of("AWS_ACCESS_KEY_ID=ASIACOREWORKER")); + assertFalse(stubs.asked().get(coreWorker).isEmpty()); + assertFalse(stubs.asked().get(taskWorker).isEmpty()); + runningNodes(node(coreName, "running", IMAGE, CORE_HOST, true), + node(taskName, "running", IMAGE, TASK_HOST, false)); + + ticking.remove("j-1"); + + // Each goes before its node, whose network it shares, and its session with it. + List removed = stubs.trino().removed(); + assertTrue(removed.lastIndexOf(coreWorker) < removed.lastIndexOf(coreName), removed.toString()); + assertTrue(removed.lastIndexOf(taskWorker) < removed.lastIndexOf(taskName), removed.toString()); + verify(roleCredentials).unregister("123456789012", "ASIACOREWORKER"); + } + + @Test + void aClusterRunsNoMoreTrinoWorkersThanTrinoMaxWorkersCoreNodesFirst() { + ContainerBuilder.Builder trinoSpec = trinoAndWorkersStart(coreName, taskName).trino().spec(); + + ticking.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", trinoWithWorkers(1), + () -> TWO_NODES, NOT_STOPPED); + + verify(trinoSpec).withName(coreWorker); + verify(trinoSpec, never()).withName(taskWorker); + verify(trinoSpec).withEnv(eq(EmrTrino.CONFIG_VARIABLE), argThat(config -> coordinatorConfig(false, config))); + } + + @Test + void aClusterWithNoTrinoWorkersHasItsCoordinatorRunTheQueries() { + ContainerBuilder.Builder trinoSpec = trinoAndWorkersStart(coreName, taskName).trino().spec(); + + // trino.max-workers 0. + ticking.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", trinoWithWorkers(0), + () -> TWO_NODES, NOT_STOPPED); + + verify(trinoSpec, never()).withName(coreWorker); + verify(trinoSpec, never()).withName(taskWorker); + verify(trinoSpec).withEnv(eq(EmrTrino.CONFIG_VARIABLE), argThat(config -> coordinatorConfig(true, config))); + } + + @Test + void aResizeStartsATrinoWorkerOnANewNodeAndRemovesTheOneOnANodeThatLeaves() { + WorkerStubs stubs = trinoAndWorkersStart(coreName, taskName); + ContainerBuilder.Builder trinoSpec = stubs.trino().spec(); + ticking.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", trinoWithWorkers(4), + () -> CORE_ONLY, NOT_STOPPED); + verify(trinoSpec).withName(coreWorker); + runningNodes(node(coreName, "running", IMAGE, CORE_HOST, true)); + List removed = stubs.trino().removed(); + int before = removed.size(); + + ticking.resize("j-1", () -> new ClusterStorage.Yarn(4096, 4).onNodes(List.of(TASK_NODE), 1, null)); + + // The new node's worker joins the coordinator as it becomes ready; the leaving node's goes, as Floci shuts + // no worker down gracefully. + verify(trinoSpec).withName(taskWorker); + verify(trinoSpec).withNetworkMode("container:" + taskName + "-id"); + assertTrue(removed.subList(before, removed.size()).contains(coreWorker), removed.toString()); + } + + @Test + void aTrinoWorkerThatStopsBeforeItIsReadyFailsTheStepWithItsNode() { + trinoAndWorkersStart(coreName); + when(lifecycle.probeContainer(coreWorker)).thenReturn(ContainerLiveness.NOT_RUNNING); + when(lifecycle.lastLogLines(eq(coreWorker), anyInt(), any())).thenReturn("Configuration is invalid"); + + IllegalStateException failed = assertThrows(IllegalStateException.class, () -> ticking.hdfs("j-1", + "123456789012", "us-east-1", HOST, IMAGE, "floci-network", trinoWithWorkers(4), () -> CORE_ONLY, + NOT_STOPPED)); + + assertEquals("The Trino worker on node " + CORE_HOST + " of EMR cluster j-1 stopped before it was ready", + failed.getMessage()); + } + + @Test + void aTrinoWorkerThatHasNotBecomeReadyIsWaitedForByTheNextStep() { + WorkerStubs stubs = trinoAndWorkersStart(coreName); + String trinoName = ContainerStorageHelper.dockerName(config, "emr-j-1-trino"); + // Its health check fails past the three minutes the first step waits, the worker running on. + ContainerExecStubs.completeEveryExec(docker, coreWorker, 1L, "", ""); + IllegalStateException first = assertThrows(IllegalStateException.class, () -> ticking.hdfs("j-1", + "123456789012", "us-east-1", HOST, IMAGE, "floci-network", trinoWithWorkers(4), () -> CORE_ONLY, + NOT_STOPPED)); + assertEquals("The Trino worker on node " + CORE_HOST + " of EMR cluster j-1 did not start within 180 seconds", + first.getMessage()); + // The next step finds the primary node, its coordinator and the worker running as they were. + when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.RUNNING); + when(lifecycle.resolveContainerNetworkIp(anyString(), eq(hdfsName))).thenReturn("172.18.0.7"); + runningOn(hdfsName, hdfsName); + when(docker.inspectContainerCmd(hdfsName).exec().getId()).thenReturn("c6c6c6"); + ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", ""); + runningOn(trinoName, "container:c6c6c6"); + runningOn(coreWorker, "container:" + coreName + "-id"); + List> asked = ContainerExecStubs.completeEveryExec(docker, coreWorker, 0L, "", ""); + + ticking.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", trinoWithWorkers(4), + () -> CORE_ONLY, NOT_STOPPED); + + // Kept, and waited for until it has passed, as the first step never saw it pass. + verify(stubs.trino().spec(), times(1)).withName(coreWorker); + verify(stubs.trino().spec(), times(1)).withName(trinoName); + assertFalse(asked.isEmpty()); + } + + // A cluster whose Trino runs up to maxWorkers workers, each container getting 1024 MB. + private static ClusterStorage.HiveMetastore trinoWithWorkers(int maxWorkers) { + return new ClusterStorage.HiveMetastore("arn:aws:iam::123456789012:role/r", Map.of(), + new ClusterStorage.Trino("trinodb/trino:446", 2048, Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), + null, Map.of(), null, maxWorkers, 1024)); + } + + // Trino's coordinator as trinoStarts has it, and each node named so running in a container whose id is its name's + // with -id, ready at once, its worker's health check passing each time it is asked: what each worker is asked. + private WorkerStubs trinoAndWorkersStart(String... nodes) { + String trinoName = ContainerStorageHelper.dockerName(config, "emr-j-1-trino"); + when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-6", Map.of())); + TrinoStubs trino = trinoStarts(trinoName); + Map>> asked = new HashMap<>(); + for (String node : nodes) { + when(lifecycle.probeContainer(node)).thenReturn(ContainerLiveness.RUNNING); + ContainerExecStubs.completeEveryExec(docker, node, 0L, "", ""); + InspectContainerCmd inspect = mock(InspectContainerCmd.class, RETURNS_DEEP_STUBS); + when(inspect.exec().getId()).thenReturn(node + "-id"); + when(docker.inspectContainerCmd(node)).thenReturn(inspect); + String worker = node + "-trino"; + when(lifecycle.probeContainer(worker)).thenReturn(ContainerLiveness.RUNNING); + asked.put(worker, ContainerExecStubs.completeEveryExec(docker, worker, 0L, "", "")); + } + return new WorkerStubs(trino, asked); + } + + private record WorkerStubs(TrinoStubs trino, Map>> asked) { + } + @Test void theFilesTrinosPasswordAuthenticatorNamesComeFromTheBootstrapImageBeforeItStarts() throws IOException { BootstrapImageStubs image = trinoCopiesFromTheBootstrapImage(); @@ -2228,7 +2402,7 @@ class EmrClusterStorageTest { ldap.put("ldap.ssl.keystore.path", "/home/hadoop/ldap/keystore.pem"); return new ClusterStorage.HiveMetastore("arn:aws:iam::123456789012:role/r", Map.of(), new ClusterStorage.Trino("trinodb/trino:446", memoryMb, Map.of(), Map.of(), Map.of(), Map.of(), - Map.of(), null, ldap, "sha256:bootstrapped")); + Map.of(), null, ldap, "sha256:bootstrapped", 0, 1024)); } // An archive whose one file's header says it is size bytes, with none of its content after it. @@ -3480,6 +3654,13 @@ class EmrClusterStorageTest { private record TrinoStubs(ContainerBuilder.Builder spec, List> asked, List removed) { } + // Whether config is the coordinator's configuration, running the queries too or not, with a shared secret Floci + // made: 32 random bytes in Base64. + private static boolean coordinatorConfig(boolean includesItself, String config) { + String expected = EmrTrino.properties(EmrTrino.config(Map.of(), !includesItself, "SECRET")); + return Pattern.matches(Pattern.quote(expected).replace("SECRET", "\\E[A-Za-z0-9+/]{43}=\\Q"), config); + } + private static Container nodeOf(String clusterId, String name) { Container container = mock(Container.class); when(container.getNames()).thenReturn(new String[]{"/" + name}); diff --git a/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java b/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java index 63c0abb23f..5116971281 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java @@ -1132,7 +1132,7 @@ class EmrServiceContainerStepsTest { "glue"), "tpch", Map.of()), Map.of("http-server.http.port", "8890"), Map.of("node.environment", "production"), Map.of("io.trino", "DEBUG"), Map.of("DB_PASSWORD", "s3cret"), Map.of(), Map.of("password-authenticator.name", "ldap", "ldap.url", - "ldaps://ldap.example.com:636"), null), fixture.clusterStorage.metastores.get(0).trino()); + "ldaps://ldap.example.com:636"), null, 4, 1024), fixture.clusterStorage.metastores.get(0).trino()); SparkJobRunner.Job job = runner.jobs.get(0); assertEquals(args, job.command()); String host = fixture.clusterStorage.hdfs.get(0).get(1); @@ -1156,7 +1156,7 @@ class EmrServiceContainerStepsTest { fixture.runStepThread(); assertEquals(List.of("true"), runner.jobs.get(0).command()); assertEquals(new ClusterStorage.Trino("trinodb/trino:446", 2048, Map.of(), Map.of(), Map.of(), Map.of(), - Map.of(), null, Map.of(), null), fixture.clusterStorage.metastores.get(0).trino()); + Map.of(), null, Map.of(), null, 4, 1024), fixture.clusterStorage.metastores.get(0).trino()); assertEquals(0, fixture.stepThreadsWaiting()); } @@ -1183,7 +1183,7 @@ class EmrServiceContainerStepsTest { assertEquals(new ClusterStorage.Trino("trinodb/trino:446", 2048, Map.of(), Map.of("http-server.authentication.type", "PASSWORD"), Map.of(), Map.of(), Map.of(), null, Map.of("password-authenticator.name", "file", "file.password-file", "/home/hadoop/password.db"), - "sha256:" + id), bootstrapping.clusterStorage.metastores.get(0).trino()); + "sha256:" + id, 4, 1024), bootstrapping.clusterStorage.metastores.get(0).trino()); } @Test diff --git a/src/test/java/io/floci/aws/services/emr/EmrServiceFixture.java b/src/test/java/io/floci/aws/services/emr/EmrServiceFixture.java index cfdac41200..529f1ae1f1 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrServiceFixture.java +++ b/src/test/java/io/floci/aws/services/emr/EmrServiceFixture.java @@ -439,6 +439,8 @@ final class EmrServiceFixture { when(config.services().emr().trino().enabled()).thenReturn(true); when(config.services().emr().trino().image()).thenReturn("trinodb/trino:%s"); when(config.services().emr().trino().memoryMb()).thenReturn(2048); + when(config.services().emr().trino().maxWorkers()).thenReturn(4); + when(config.services().emr().trino().workerMemoryMb()).thenReturn(1024); return new EmrService(storage, config, new RegionResolver(REGION, ACCOUNT), publisher, clock, mock(EmrService.Wakeups.class), runner, bootstrap, clusterStorage, releaseImages, this::handToThread, iam); diff --git a/src/test/java/io/floci/aws/services/emr/EmrTrinoNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/emr/EmrTrinoNightlyIntegrationTest.java index 4927bb2f85..34c51f21e7 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrTrinoNightlyIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrTrinoNightlyIntegrationTest.java @@ -1,6 +1,7 @@ package io.floci.aws.services.emr; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.command.PullImageResultCallback; @@ -67,7 +68,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; * {@code trino-exchange-manager} spools a fault-tolerant query in the cluster's HDFS. 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. With {@code trino-password-authenticator}, Trino checks passwords against a file a - * bootstrap action wrote, over HTTPS alone. + * bootstrap action wrote, over HTTPS alone. A core node runs a Trino worker, which runs the cluster's queries. * *

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. @@ -277,6 +278,28 @@ class EmrTrinoNightlyIntegrationTest { // A schema in the bucket's warehouse folder, an external table over the CSV, a table of each item's sum, then the // sums. + // A core node runs a Trino worker, in EMR's "coordinator-worker model", and the coordinator, which then runs none + // of the work, leaves the queries to it: a table it makes in Floci's S3, through the metastore on the primary node, + // and the nodes Trino knows, the coordinator and the worker. + @Test + @Timeout(value = 7, unit = TimeUnit.MINUTES) + void aCoreNodeRunsATrinoWorkerThatRunsTheClustersQueries() { + String schema = bucket.replace('-', '_'); + startCluster("[{\"Classification\": \"trino-connector-tpch\", \"Properties\": {}}]", null, 1); + + String query = trinoStep("CREATE SCHEMA hive." + schema + " WITH (location = '" + s3Uri("warehouse/") + + "'); CREATE TABLE hive." + schema + ".nation AS SELECT nationkey, name FROM tpch.tiny.nation; " + + "SELECT count(*) FROM hive." + schema + ".nation; " + + "SELECT coordinator, count(*) FROM system.runtime.nodes GROUP BY coordinator ORDER BY coordinator"); + + assertEquals("COMPLETED", state(query), () -> logs(query)); + String logs = logs(query); + assertTrue(logs.contains("\"25\"\n"), logs); + assertTrue(logs.contains("\"false\",\"1\"\n\"true\",\"1\""), logs); + assertFalse(s3.listObjectsV2(request -> request.bucket(bucket).prefix("warehouse/nation/")).contents() + .isEmpty()); + } + private String tables(String schema) { return "CREATE SCHEMA hive." + schema + " WITH (location = '" + s3Uri("warehouse/") + "'); " + "CREATE TABLE hive." + schema + ".sales (id integer, item varchar, qty integer) WITH (format = " @@ -293,6 +316,11 @@ class EmrTrinoNightlyIntegrationTest { // A cluster with Trino and configurations, and bootstrapActions unless that is null. private void startCluster(String configurations, String bootstrapActions) { + startCluster(configurations, bootstrapActions, 0); + } + + // The same with coreNodes core nodes. + private void startCluster(String configurations, String bootstrapActions, int coreNodes) { ObjectNode request = JSON.createObjectNode().put("Name", "trino").put("ReleaseLabel", "emr-7.5.0") .put("LogUri", s3Uri("logs/")); try { @@ -304,9 +332,14 @@ class EmrTrinoNightlyIntegrationTest { } catch (IOException e) { throw new UncheckedIOException(e); } - request.putObject("Instances").put("KeepJobFlowAliveWhenNoSteps", true).putArray("InstanceGroups") - .addObject().put("Name", "primary").put("InstanceRole", "MASTER").put("InstanceType", "m5.xlarge") + ArrayNode groups = request.putObject("Instances").put("KeepJobFlowAliveWhenNoSteps", true) + .putArray("InstanceGroups"); + groups.addObject().put("Name", "primary").put("InstanceRole", "MASTER").put("InstanceType", "m5.xlarge") .put("InstanceCount", 1); + if (coreNodes > 0) { + groups.addObject().put("Name", "core").put("InstanceRole", "CORE").put("InstanceType", "m5.xlarge") + .put("InstanceCount", coreNodes); + } clusterId = emr("RunJobFlow", request.toString()).then().statusCode(200).extract().jsonPath() .getString("JobFlowId"); cleanup.register(() -> terminateClusterAndAwaitCleanup(clusterId, emrService)); diff --git a/src/test/java/io/floci/aws/services/emr/EmrTrinoTest.java b/src/test/java/io/floci/aws/services/emr/EmrTrinoTest.java index a633a62331..1f685507c9 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrTrinoTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrTrinoTest.java @@ -16,7 +16,6 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; -import java.util.regex.Pattern; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -30,9 +29,8 @@ class EmrTrinoTest { private static final String ENDPOINT = "http://floci:4566"; private static final String SERVER = "http://ip-10-0-0-1.ec2.internal:8889"; - // The line of a shared secret the entrypoint makes: 32 random bytes in Base64. - private static final Pattern SHARED_SECRET = - Pattern.compile("internal-communication\\.shared-secret=[A-Za-z0-9+/]{43}=\n"); + private static final String PRIMARY = "ip-10-0-0-1.ec2.internal"; + private static final String NAMENODE = EmrTrino.namenode(PRIMARY); @Test void theImageIsOfTheTrinoTheReleaseShips() { @@ -47,7 +45,7 @@ class EmrTrinoTest { @Test void theHiveCatalogIsTheClustersMetastoreOnFlocisS3() { - Map catalog = EmrTrino.catalog("hive", Map.of(), ENDPOINT, "us-east-1"); + Map catalog = EmrTrino.catalog("hive", Map.of(), "localhost", ENDPOINT, "us-east-1"); assertEquals(List.of("connector.name=hive", "hive.metastore.uri=thrift://localhost:9083", "fs.native-s3.enabled=true", "fs.hadoop.enabled=true", "s3.endpoint=" + ENDPOINT, @@ -62,7 +60,7 @@ class EmrTrinoTest { classification.put("hive.metastore.glue.catalogid", "111122223333"); classification.put("s3.path-style-access", "false"); - Map catalog = EmrTrino.catalog("hive", classification, ENDPOINT, "eu-west-1"); + Map catalog = EmrTrino.catalog("hive", classification, "localhost", ENDPOINT, "eu-west-1"); assertEquals(List.of("connector.name=hive", "hive.metastore=glue", "hive.metastore.glue.region=eu-west-1", "hive.metastore.glue.endpoint-url=" + ENDPOINT, "fs.native-s3.enabled=true", @@ -75,7 +73,7 @@ class EmrTrinoTest { void deltaIsTrinosDeltaLakeConnectorOnTheClustersMetastoreAsTheGuidesTutorialHasIt() { // "trino-connector-delta" with "hive.metastore.uri":"thrift://localhost:9083" and no connector of its own. Map catalog = EmrTrino.catalog("delta", Map.of("hive.metastore.uri", - "thrift://localhost:9083"), ENDPOINT, "us-east-1"); + "thrift://localhost:9083"), "localhost", ENDPOINT, "us-east-1"); assertEquals("delta_lake", catalog.get("connector.name")); assertEquals("thrift://localhost:9083", catalog.get("hive.metastore.uri")); @@ -83,17 +81,17 @@ class EmrTrinoTest { // Its INSERT INTO a table in S3, which Trino makes only so; the classification may say otherwise. assertEquals("true", catalog.get("delta.enable-non-concurrent-writes")); assertEquals("false", EmrTrino.catalog("delta", Map.of("delta.enable-non-concurrent-writes", "false"), - ENDPOINT, "us-east-1").get("delta.enable-non-concurrent-writes")); + "localhost", ENDPOINT, "us-east-1").get("delta.enable-non-concurrent-writes")); } @Test void icebergIsOnFlocisGlueWithItsCatalogTypeGlueElseOnTheClustersMetastore() { Map glue = EmrTrino.catalog("iceberg", Map.of("connector.name", "iceberg", - "iceberg.catalog.type", "glue"), ENDPOINT, "us-east-1"); - Map metastore = EmrTrino.catalog("iceberg", Map.of("connector.name", "iceberg"), ENDPOINT, - "us-east-1"); - Map rest = EmrTrino.catalog("iceberg", Map.of("iceberg.catalog.type", "rest"), ENDPOINT, - "us-east-1"); + "iceberg.catalog.type", "glue"), "localhost", ENDPOINT, "us-east-1"); + Map metastore = EmrTrino.catalog("iceberg", Map.of("connector.name", "iceberg"), "localhost", + ENDPOINT, "us-east-1"); + Map rest = EmrTrino.catalog("iceberg", Map.of("iceberg.catalog.type", "rest"), "localhost", + ENDPOINT, "us-east-1"); assertEquals("glue", glue.get("iceberg.catalog.type")); assertEquals(ENDPOINT, glue.get("hive.metastore.glue.endpoint-url")); @@ -110,12 +108,13 @@ class EmrTrinoTest { @Test void aCatalogNotInS3IsItsConnectorAndTheClassificationsPropertiesAlone() { - assertEquals(Map.of("connector.name", "tpch"), EmrTrino.catalog("tpch", Map.of(), ENDPOINT, "us-east-1")); - assertEquals(Map.of("connector.name", "raptor_legacy"), EmrTrino.catalog("raptor", Map.of(), ENDPOINT, - "us-east-1")); + assertEquals(Map.of("connector.name", "tpch"), + EmrTrino.catalog("tpch", Map.of(), "localhost", ENDPOINT, "us-east-1")); + assertEquals(Map.of("connector.name", "raptor_legacy"), EmrTrino.catalog("raptor", Map.of(), "localhost", + ENDPOINT, "us-east-1")); assertEquals(Map.of("connector.name", "postgresql", "connection-url", "jdbc:postgresql://db:5432/app"), - EmrTrino.catalog("postgresql", Map.of("connection-url", "jdbc:postgresql://db:5432/app"), ENDPOINT, - "us-east-1")); + EmrTrino.catalog("postgresql", Map.of("connection-url", "jdbc:postgresql://db:5432/app"), "localhost", + ENDPOINT, "us-east-1")); } @Test @@ -124,27 +123,30 @@ class EmrTrinoTest { connectors.put("tpch", Map.of()); connectors.put("hive", Map.of("hive.metastore", "glue")); - Map> catalogs = EmrTrino.catalogs(connectors, ENDPOINT, "us-east-1"); + Map> catalogs = EmrTrino.catalogs(connectors, "localhost", ENDPOINT, "us-east-1"); assertEquals(List.of("hive", "tpch"), List.copyOf(catalogs.keySet())); assertEquals("glue", catalogs.get("hive").get("hive.metastore")); - assertEquals(List.of("hive"), List.copyOf(EmrTrino.catalogs(Map.of(), ENDPOINT, "us-east-1").keySet())); + assertEquals(List.of("hive"), + List.copyOf(EmrTrino.catalogs(Map.of(), "localhost", ENDPOINT, "us-east-1").keySet())); } @Test void theCoordinatorRunsTheQueriesTooOnEmrsPortOrTheOneTrinoConfigNames() { - // Clients through Floci reach it on a host of the cluster's own, over the scheme they used. + // Clients through Floci reach it on a host of the cluster's own, over the scheme they used, and EMR + // "automatically configures a shared secret key for secure internal communication between cluster nodes". assertEquals(List.of("coordinator=true", "node-scheduler.include-coordinator=true", "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"))); + "http-server.process-forwarded=true", "internal-communication.shared-secret=s3cret"), + List.of(EmrTrino.properties(EmrTrino.config(Map.of(), false, "s3cret")).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 moved = EmrTrino.config(Map.of("http-server.http.port", "8890", - "query.max-memory", "1GB")); + "query.max-memory", "1GB"), false, "s3cret"); assertEquals(List.of("coordinator=true", "node-scheduler.include-coordinator=true", "http-server.http.port=8890", "discovery.uri=http://localhost:8890", - "http-server.process-forwarded=true", "query.max-memory=1GB"), + "http-server.process-forwarded=true", "internal-communication.shared-secret=s3cret", + "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"))); @@ -153,6 +155,55 @@ class EmrTrinoTest { assertEquals(List.of("/usr/lib/trino/bin/health-check"), EmrTrino.READY_CHECK); } + @Test + void aCoordinatorWithWorkersLeavesTheQueriesToThem() { + // Trino's deployment guide: a coordinator of a cluster with workers runs none of their work, as AWS's + // "coordinator-worker model, where each component has a specialized role in query execution" has it. + assertEquals("false", EmrTrino.config(Map.of(), true, "s3cret").get("node-scheduler.include-coordinator")); + // The cluster's trino-config says otherwise, if it does. + assertEquals("true", EmrTrino.config(Map.of("node-scheduler.include-coordinator", "true"), true, "s3cret") + .get("node-scheduler.include-coordinator")); + } + + @Test + void aSharedSecretTheClusterGivesIsTrinosOwn() { + // "you can override the configuration with your own secret key", on every node. + Map own = Map.of("internal-communication.shared-secret", "mine"); + + assertEquals("mine", EmrTrino.config(own, true, "s3cret").get(EmrTrino.SHARED_SECRET)); + assertEquals("mine", EmrTrino.workerConfig(own, PRIMARY, "s3cret").get(EmrTrino.SHARED_SECRET)); + } + + @Test + void aWorkerFindsTheCoordinatorOnThePrimaryNodeAndTakesTheClustersTrinoConfig() { + assertEquals(List.of("coordinator=false", "http-server.http.port=8889", + "discovery.uri=http://ip-10-0-0-1.ec2.internal:8889", "internal-communication.shared-secret=s3cret"), + List.of(EmrTrino.properties(EmrTrino.workerConfig(Map.of(), PRIMARY, "s3cret")).split("\n"))); + // "configuration properties must be set on the coordinator and all worker nodes": a port of the cluster's own + // is every node's, the coordinator's discovery with it. + Map classification = new LinkedHashMap<>(); + classification.put("http-server.http.port", "8890"); + classification.put("query.max-memory-per-node", "512MB"); + assertEquals(List.of("coordinator=false", "http-server.http.port=8890", + "discovery.uri=http://ip-10-0-0-1.ec2.internal:8890", "internal-communication.shared-secret=s3cret", + "query.max-memory-per-node=512MB"), + List.of(EmrTrino.properties(EmrTrino.workerConfig(classification, PRIMARY, "s3cret")).split("\n"))); + } + + @Test + void aWorkerIsReachedAtItsNodesHostTheClustersTrinoNodeAfter() { + // Not at whichever of the node's addresses Trino would pick, a link-local one among them. + assertEquals(List.of("node.internal-address=ip-10-0-0-2.ec2.internal", "node.environment=production"), + List.of(EmrTrino.properties(EmrTrino.workerNode(Map.of("node.environment", "production"), + "ip-10-0-0-2.ec2.internal")).split("\n"))); + } + + @Test + void aWorkersCatalogsReachTheMetastoreOnThePrimaryNode() { + assertEquals("thrift://ip-10-0-0-1.ec2.internal:9083", + EmrTrino.catalogs(Map.of(), PRIMARY, ENDPOINT, "us-east-1").get("hive").get("hive.metastore.uri")); + } + @Test void theFilesAPasswordAuthenticatorNamesAreItsAbsolutePathsEachOnce() { Map ldap = new LinkedHashMap<>(); @@ -174,18 +225,21 @@ class EmrTrinoTest { // "To use the default settings, set the following configuration: // { "Classification": "trino-exchange-manager" }" assertEquals(List.of("exchange-manager.name=hdfs", - "exchange.base-directories=hdfs://localhost:8020/user/trino/trino-exchange/", + "exchange.base-directories=hdfs://ip-10-0-0-1.ec2.internal:8020/user/trino/trino-exchange/", "hdfs.config.resources=/etc/trino/exchange-core-site.xml"), - List.of(EmrTrino.properties(EmrTrino.exchangeManager(Map.of(), ENDPOINT, "us-east-1")).split("\n"))); + List.of(EmrTrino.properties(EmrTrino.exchangeManager(Map.of(), NAMENODE, ENDPOINT, "us-east-1")) + .split("\n"))); // "Set exchange.use-local-hdfs to true. Set exchange.base-directories to the custom directory location in // HDFS", a property the Trino project's Trino does not take; the HDFS settings EMR lists go on. Map custom = new LinkedHashMap<>(); custom.put("exchange.use-local-hdfs", "true"); custom.put("exchange.base-directories", "/exchange"); custom.put("exchange.hdfs.block-size", "8MB"); - assertEquals(List.of("exchange-manager.name=hdfs", "exchange.base-directories=hdfs://localhost:8020/exchange", + assertEquals(List.of("exchange-manager.name=hdfs", + "exchange.base-directories=hdfs://ip-10-0-0-1.ec2.internal:8020/exchange", "hdfs.config.resources=/etc/trino/exchange-core-site.xml", "exchange.hdfs.block-size=8MB"), - List.of(EmrTrino.properties(EmrTrino.exchangeManager(custom, ENDPOINT, "us-east-1")).split("\n"))); + List.of(EmrTrino.properties(EmrTrino.exchangeManager(custom, NAMENODE, ENDPOINT, "us-east-1")) + .split("\n"))); } @Test @@ -199,7 +253,8 @@ class EmrTrinoTest { "exchange.base-directories=s3://spool-a/exchange,s3://spool-b/exchange", "exchange.s3.endpoint=" + ENDPOINT, "exchange.s3.region=eu-west-1", "exchange.s3.path-style-access=false", "exchange.sink-buffers-per-partition=4"), - List.of(EmrTrino.properties(EmrTrino.exchangeManager(s3, ENDPOINT, "eu-west-1")).split("\n"))); + List.of(EmrTrino.properties(EmrTrino.exchangeManager(s3, NAMENODE, ENDPOINT, "eu-west-1")) + .split("\n"))); } @Test @@ -213,7 +268,7 @@ class EmrTrinoTest { @Test void theEntrypointWritesTheConfigurationNodeLogAndCatalogsFlociGivesAloneAndANodeIdTrinoTakes(@TempDir Path etc) throws Exception { - String config = EmrTrino.properties(EmrTrino.config(Map.of())); + String config = EmrTrino.properties(EmrTrino.config(Map.of(), false, "s3cret")); Map environment = new LinkedHashMap<>(); environment.put(EmrTrino.CONFIG_VARIABLE, config); environment.put(EmrTrino.NODE_VARIABLE, "node.environment=production"); @@ -223,10 +278,8 @@ class EmrTrinoTest { runEntrypoint(etc, environment); - // A shared secret for Trino's internal communication after Floci's configuration, which EMR configures too. - String written = Files.readString(etc.resolve("config.properties")); - assertTrue(written.startsWith(config + "\n"), written); - assertTrue(SHARED_SECRET.matcher(written.substring(config.length() + 1)).matches(), written); + // Floci's configuration, the cluster's shared secret in it. + assertEquals(config + "\n", Files.readString(etc.resolve("config.properties"))); try (Stream catalogs = Files.list(etc.resolve("catalog"))) { assertEquals(List.of("hive.properties", "iceberg.properties"), catalogs.map(path -> path.getFileName().toString()).sorted().toList()); @@ -255,26 +308,6 @@ class EmrTrinoTest { assertFalse(Files.exists(etc.resolve("password-authenticator.properties"))); } - @Test - void aSharedSecretTheClusterGivesIsTrinosOwnElseTrinoGetsANewOneEachStart(@TempDir Path first, - @TempDir Path second) throws Exception { - // "you can override the configuration with your own secret key" - Path own = first.resolve("own"); - Files.createDirectories(own); - String config = EmrTrino.properties(EmrTrino.config(Map.of("internal-communication.shared-secret", "mine"))); - - runEntrypoint(own, Map.of(EmrTrino.CONFIG_VARIABLE, config)); - runEntrypoint(first, Map.of(EmrTrino.CONFIG_VARIABLE, "")); - runEntrypoint(second, Map.of(EmrTrino.CONFIG_VARIABLE, "")); - - assertEquals(config + "\n", Files.readString(own.resolve("config.properties"))); - String once = Files.readString(first.resolve("config.properties")); - String again = Files.readString(second.resolve("config.properties")); - assertTrue(SHARED_SECRET.matcher(once.substring(1)).matches(), once); - assertTrue(SHARED_SECRET.matcher(again.substring(1)).matches(), again); - assertFalse(once.equals(again), once); - } - @Test void theEntrypointWritesThePasswordAuthenticatorTheClusterGives(@TempDir Path etc) throws Exception { String authenticator = "password-authenticator.name=file\nfile.password-file=/home/hadoop/password.db"; @@ -286,14 +319,16 @@ class EmrTrinoTest { @Test void theEntrypointWritesTheExchangeManagerTheClusterGives(@TempDir Path etc) throws Exception { - String exchange = EmrTrino.properties(EmrTrino.exchangeManager(Map.of(), ENDPOINT, "us-east-1")); + String exchange = EmrTrino.properties(EmrTrino.exchangeManager(Map.of(), NAMENODE, ENDPOINT, "us-east-1")); - runEntrypoint(etc, Map.of(EmrTrino.EXCHANGE_VARIABLE, exchange)); + runEntrypoint(etc, Map.of(EmrTrino.EXCHANGE_VARIABLE, exchange, EmrTrino.EXCHANGE_SITE_VARIABLE, + EmrTrino.exchangeSite(NAMENODE))); assertEquals(exchange + "\n", Files.readString(etc.resolve("exchange-manager.properties"))); // The Hadoop configuration its hdfs.config.resources names, the cluster's NameNode its default file system. - assertEquals("fs.defaultFShdfs://localhost:8020" - + "\n", Files.readString(etc.resolve("exchange-core-site.xml"))); + assertEquals("fs.defaultFS" + + "hdfs://ip-10-0-0-1.ec2.internal:8020\n", + Files.readString(etc.resolve("exchange-core-site.xml"))); } @Test