diff --git a/.github/ci/prefetch-images.sh b/.github/ci/prefetch-images.sh index 71a8bc06c6..0f87789f77 100755 --- a/.github/ci/prefetch-images.sh +++ b/.github/ci/prefetch-images.sh @@ -121,10 +121,11 @@ starts ElbV2LambdaTargetDataPlaneIntegrationTest && ecr public.ecr.aws/lambda/py # EmrServerlessCustomImageNightlyIntegrationTest builds its custom image on it, # EmrFlociContainerNightlyIntegrationTest runs a cluster's steps in it from Floci in a container, # EmrPigStepsNightlyIntegrationTest a cluster's Pig steps, EmrAppUiNightlyIntegrationTest a MapReduce step, -# and EmrClusterShrinkNightlyIntegrationTest a cluster shrink. +# EmrClusterShrinkNightlyIntegrationTest a cluster shrink, and EmrTrinoNightlyIntegrationTest a cluster's trino-cli +# steps. starts EmrDockerRunnerNightlyIntegrationTest EmrHiveStepsNightlyIntegrationTest EmrServerlessCustomImageNightlyIntegrationTest \ EmrFlociContainerNightlyIntegrationTest EmrPigStepsNightlyIntegrationTest EmrNotebookExecutionNightlyIntegrationTest \ - EmrAppUiNightlyIntegrationTest EmrClusterShrinkNightlyIntegrationTest \ + EmrAppUiNightlyIntegrationTest EmrClusterShrinkNightlyIntegrationTest EmrTrinoNightlyIntegrationTest \ && ecr public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest # EmrServerlessHiveDockerIntegrationTest runs EMR Serverless Hive job runs, and EmrHiveStepsNightlyIntegrationTest EMR # Hive steps, in the emr-7.5.0 Hive image the runner's default Hive template names, 2.7 GB; every EMR cluster runs its @@ -134,7 +135,11 @@ starts EmrDockerRunnerNightlyIntegrationTest EmrHiveStepsNightlyIntegrationTest starts EmrServerlessHiveDockerIntegrationTest EmrHiveStepsNightlyIntegrationTest EmrDockerRunnerNightlyIntegrationTest \ EmrFlociContainerNightlyIntegrationTest EmrPigStepsNightlyIntegrationTest EmrSessionServerNightlyIntegrationTest \ EmrNotebookExecutionNightlyIntegrationTest EmrAppUiNightlyIntegrationTest EmrClusterShrinkNightlyIntegrationTest \ + EmrTrinoNightlyIntegrationTest \ && ecr public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest +# EmrTrinoNightlyIntegrationTest runs a cluster's Trino coordinator from the Trino project's image of emr-7.5.0's +# Trino, 446, about 1 GB, from Docker Hub. +starts EmrTrinoNightlyIntegrationTest && pull trinodb/trino:446 # The nightly EmrServerlessSparkConnectNightlyIntegrationTest runs a session's Spark Connect server, and its client, in # the emr-7.13.0 image, 3.7 GB, the first release with sessions, and EmrServerlessDashboardNightlyIntegrationTest a job # run and a session in it, whose dashboards it opens. diff --git a/.github/workflows/nightly-checks.yml b/.github/workflows/nightly-checks.yml index ac4d3a5613..0d6380a80b 100644 --- a/.github/workflows/nightly-checks.yml +++ b/.github/workflows/nightly-checks.yml @@ -34,9 +34,10 @@ jobs: # EmrDockerRunnerNightlyIntegrationTest's eleven two-minute tests and two-minute setup, # 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, and EmrContainersGatewayNightlyIntegrationTest's twenty-four-minute, seven-minute - # and eighteen-minute methods and 21-minute image pull, 170 minutes. A check added, or a bound raised, raises its - # group's timeout with it, so a slow check fails with its own message. + # 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 two seven-minute methods + # and ten-minute image pull, 194 minutes. A check added, or a bound raised, raises its group's timeout with it, so + # a slow check fails with its own message. strategy: fail-fast: false matrix: @@ -44,7 +45,7 @@ jobs: - group: standard timeout: 359 - group: docker-runner - timeout: 190 + timeout: 214 timeout-minutes: ${{ matrix.timeout }} # A fork's schedule would spend its owner's minutes on checks it never asked for; a draft waits until it is # ready for review, as the CI shards do. @@ -77,7 +78,7 @@ jobs: mv selected.txt all-nightly.txt fi fi - runner='/(EmrDockerRunner|EmrClusterShrink|EmrContainersSpark|EmrContainersGateway)NightlyIntegrationTest$' + runner='/(EmrDockerRunner|EmrClusterShrink|EmrContainersSpark|EmrContainersGateway|EmrTrino)NightlyIntegrationTest$' if [ "$GROUP" = "docker-runner" ]; then grep -E "$runner" all-nightly.txt > nightly.txt || true else diff --git a/docs/services/emr.md b/docs/services/emr.md index 4baaf78623..8dc102f54a 100644 --- a/docs/services/emr.md +++ b/docs/services/emr.md @@ -610,7 +610,7 @@ holding the driver and its executors, or a command or a script. The cluster itse release, which has no Hive image, from `emr-7.5.0`'s, with their data in a third volume and permissions off. Where the cluster was created with core nodes the DataNodes are theirs instead (see **YARN**), and HDFS keeps what EMR's does, one copy of a block below four core nodes, two below ten and three otherwise, or what the `hdfs-site` classification's - `dfs.replication` says, which is the one property of that classification Floci applies. On a cluster with Hive or HCatalog (see **Which steps run**), the same container runs Hive's + `dfs.replication` says, which is the one property of that classification Floci applies. On a cluster with Hive or HCatalog (see **Which steps run**), or Floci's Trino (see **Trino**), the same container runs Hive's metastore service, which EMR's HCatalog server is, on port 9083, its Derby database in that volume and its warehouse in the HDFS; it reaches the S3 locations of tables through Floci's S3 as the role of the cluster's EC2 instance profile, as the bootstrap actions do, with a session that goes with the container. It gets the cluster's `core-site` @@ -828,6 +828,27 @@ holding the driver and its executors, or a command or a script. The cluster itse such a cluster, `command-runner.jar pig ...` or a script's, gets the same. With `pig.enabled` off, a Pig step on a cluster whose `Applications` name Pig is `FAILED` without running ("Floci does not run this step: Pig is not in the 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)". 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 catalog, `hive`, is that metastore, its warehouse in the + cluster's HDFS and its tables' S3 locations on Floci's S3. With `trino-connector-hive` setting `hive.metastore` to + `glue`, as the Release Guide's "Launch an Amazon EMR cluster with Trino" does, the catalog is Floci's Glue Data + Catalog instead; the classification's other properties go into the catalog after Floci's, a later configuration's + winning. Trino reaches S3 and Glue as the cluster's EC2 instance profile's role, with a session of its own, as the + metastore does. A step runs `trino-cli`, as the Release Guide's "Start the Trino CLI by running trino-cli" does on + the primary node, through `command-runner.jar`: the CLI of the same Trino, which Floci copies into the cluster's + image from Trino's image as it makes it, on the image's Java 17, connects to the coordinator unless the step names a + `--server` of its own. The cluster's first step starts Trino, with its HDFS, and waits up to three minutes for it to + answer, a Trino that does not failing the step. It goes before its primary node, whose network it shares, when the + cluster ends, on a reset and on a shutdown, and one an earlier Floci left goes when the EMR service starts, whatever + its cluster, as its session went with that Floci: the cluster's next step starts another. * **S3DistCp**: the image has no `s3-dist-cp`, so a `command-runner.jar` step whose first argument is `s3-dist-cp`, the Release Guide's form, runs Floci's own program instead, through `spark-submit` in the step's container, copying through Hadoop's file systems: `--src` and `--dest` take @@ -1044,6 +1065,14 @@ holding the driver and its executors, or a command or a script. The cluster itse - **Pig is Apache's 0.18.0, and only with `pig.enabled`.** EMR's 7.x releases ship Pig 0.17.0, whose Apache build is for Hadoop 2; no AWS image carries Pig, so Floci downloads Apache's 0.18.0, for Hadoop 3, when it is enabled, and runs it on the image's Tez (see **Pig steps**). +- **Trino is the Trino project's build, from the first step, with its `hive` catalog alone, and only with + `trino.enabled`.** EMR ships its own `-amzn` builds; Floci runs the Trino project's image of the same version (see + **Trino**). The cluster's first step starts it, as it does the primary node's HDFS, where EMR's runs once the + cluster is up, and Floci gives no address to reach it from outside the cluster's network. Its one catalog is + `hive`: no other `trino-connector-*` classification, nor `trino-config`, applies yet. With `docker-network` set to + `host`, `container:` or `none` it does not run, as the metastore service does not. From `emr-7.14.0` on, "When + you select Trino as the only application at launch, Amazon EMR no longer starts YARN and HDFS"; Floci's primary node + still runs the HDFS, beside the metastore. - **Tez's intermediate data is not compressed on YARN.** The images name the LZO codec for it, whose native library they lack, so Floci turns that compression off, which a `tez-site` classification can turn back on with a codec they have. - **No Hive metastore service in a network namespace the steps share.** With `docker-network` set to `host` or @@ -1110,6 +1139,9 @@ 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_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_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 27b42a9af9..8d8e038f89 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -2456,6 +2456,9 @@ public interface EmulatorConfig { /** Apache Pig for a {@code docker} cluster's Pig steps, which no AWS image carries; off unless enabled. */ EmrPigConfig pig(); + /** Trino on a {@code docker} cluster's primary node, which no AWS image carries; off unless enabled. */ + EmrTrinoConfig trino(); + /** * When true, Floci removes, in the {@code docker} runner mode, every EMR step driver and bootstrap * container a previous run of this same Floci left on the daemon (matched by the @@ -2500,6 +2503,35 @@ public interface EmulatorConfig { String sha256(); } + interface EmrTrinoConfig { + /** + * When true, a {@code docker} cluster whose {@code Applications} name Trino runs Trino's coordinator on its + * primary node, from {@link #image()}, and its steps run {@code trino-cli}. Off by default, as the image is the + * Trino project's, not AWS's, about 1 GB to pull, and its container takes {@link #memoryMb()}. + * + * Env var: FLOCI_SERVICES_EMR_TRINO_ENABLED + */ + @WithDefault("false") + boolean enabled(); + + /** + * The image Trino runs from, {@code %s} the Trino version of the cluster's release as the Release Guide gives + * it, without AWS's build suffix. One with no {@code %s} serves every release. + * + * Env var: FLOCI_SERVICES_EMR_TRINO_IMAGE + */ + @WithDefault("trinodb/trino:%s") + String image(); + + /** + * The memory, in MiB, of the container Trino runs in, 80% of which its image gives Trino's heap. + * + * Env var: FLOCI_SERVICES_EMR_TRINO_MEMORY_MB + */ + @WithDefault("2048") + int memoryMb(); + } + interface WafV2ServiceConfig { @WithDefault("true") boolean enabled(); 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 4e3dd737ac..61da94a278 100644 --- a/src/main/java/io/floci/aws/services/emr/ClusterStorage.java +++ b/src/main/java/io/floci/aws/services/emr/ClusterStorage.java @@ -82,9 +82,10 @@ public interface ClusterStorage { * unless it is running, and returns the cluster's storage with them: its primary node's {@code host} name, which a * step's container resolves to the address given, on the network given, the metastore's URI, and YARN's * ResourceManager with the address Floci has on that network, the metastore and YARN only on a network of the - * cluster's own. Its core and task nodes, {@code yarn}'s, run in containers of their own on that network, and - * {@code yarn} is read as they start, so a resize since the step was queued counts. A failure to start them is - * thrown, and {@link Stopped} once {@code stopped} says the step is past starting, or a teardown + * cluster's own, where Trino's coordinator runs too, in a container of its own on the primary node's network, + * when {@code hiveMetastore} asks for it. Its core and task nodes, {@code yarn}'s, run in containers of their own + * on that network, and {@code yarn} is read as they start, so a resize since the step was queued counts. A failure + * to start them is thrown, and {@link Stopped} once {@code stopped} says the step is past starting, or a teardown * has stopped the HDFS. */ SparkJobRunner.Storage hdfs(String clusterId, String accountId, String region, String host, String image, @@ -109,9 +110,23 @@ public interface ClusterStorage { /** * Hive's metastore service on a cluster's primary node, which reaches S3 as the cluster's EC2 instance profile's * {@code role} does, or as its account when that is null, with the cluster's {@code settings}, its - * {@code core-site} and {@code hive-site} properties, after its own. + * {@code core-site} and {@code hive-site} properties, after its own, and {@code trino} beside it unless that is + * null, as EMR installs {@code hcatalog-server} with Trino. */ - record HiveMetastore(String role, Map settings) { + record HiveMetastore(String role, Map settings, Trino trino) { + + /** The metastore alone. */ + HiveMetastore(String role, Map settings) { + this(role, settings, null); + } + } + + /** + * Trino's coordinator on a cluster's primary node: the {@code image} it runs from, the memory its container gets, + * and the cluster's {@code trino-connector-hive} properties, which its {@code hive} catalog gets after Floci's + * (see {@link EmrTrino#hiveCatalog}). It reaches S3 and Glue as the metastore does. + */ + record Trino(String image, int memoryMb, Map hiveConnector) { } /** 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 653d725aec..af7b79f543 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrClusterStorage.java +++ b/src/main/java/io/floci/aws/services/emr/EmrClusterStorage.java @@ -108,7 +108,7 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { // The cluster's core-site and hive-site, as --hiveconf settings one to a line, which the service gets after its // own. private static final String HIVE_METASTORE_SITE_VARIABLE = "FLOCI_HIVE_METASTORE_SITE"; - private static final int HIVE_METASTORE_PORT = 9083; + static final int HIVE_METASTORE_PORT = 9083; // The folder a Hive session uploads Hive's exec jar to when it is not there, named after its SHA-256, under the // image's hive.user.install.directory: the primary node puts it there first, as two sessions uploading it at once // can leave one with a jar that changed under it, whose Tez tasks then fail to launch. @@ -192,6 +192,13 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { // gives up. private static final Duration HDFS_START_TIMEOUT = Duration.ofSeconds(120); private static final Duration HDFS_POLL_INTERVAL = Duration.ofMillis(500); + // How long Trino's coordinator has to answer once its container starts: it took 18 s on a laptop, its image's + // catalogs loaded. + private static final Duration TRINO_START_TIMEOUT = Duration.ofMinutes(3); + // How long Trino keeps running a query before it counts as ready. A query that reads a catalog needs a node that + // serves it, which Trino's node manager learns from the nodes' announcements as it refreshes, every five seconds + // (DiscoveryNodeManager), and Trino runs a query with no catalog before then: twice that, from its first answer. + private static final Duration TRINO_SETTLE = Duration.ofSeconds(10); // 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); @@ -545,6 +552,11 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { private final Set running = ConcurrentHashMap.newKeySet(); // The core and task nodes' containers this process has started or found, by name. private final Set runningNodes = ConcurrentHashMap.newKeySet(); + // 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. + private final Set readyTrino = ConcurrentHashMap.newKeySet(); // 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. @@ -846,6 +858,11 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { String imageId = lifecycleManager.resolveImageForLaunch(containerBuilder.resolveImage(image), ImagePullBehavior.PREFER_CACHED, null).imageId(); boolean shared = sharesNamespace(network); + // Trino's too, about 1 GB at its first pull, where it runs: beside the metastore, on a network of the + // cluster's own. + Trino trino = hiveMetastore != null && !shared ? hiveMetastore.trino() : null; + String trinoImageId = trino == null ? null : lifecycleManager.resolveImageForLaunch( + containerBuilder.resolveImage(trino.image()), ImagePullBehavior.PREFER_CACHED, null).imageId(); long deadline = nanoTime.getAsLong() + hdfsStartTimeout.toNanos(); synchronized (starting.computeIfAbsent(clusterId, id -> new Object())) { // Read here, so a resize before this took the lock counts, and one after it waits and finds these nodes. @@ -891,6 +908,11 @@ 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. + if (trino != null) { + trino(clusterId, accountId, region, containerId, trinoImageId, hiveMetastore.role(), trino, teardown, + stopped); + } SparkJobRunner.Storage storage = volumes(clusterId).withHdfs(host, address(clusterId, containerId), name); if (hiveMetastore != null) { storage = storage.withHiveMetastore("thrift://" + host + ":" + HIVE_METASTORE_PORT); @@ -1442,7 +1464,9 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { private String createContainer(String clusterId, String accountId, String region, String host, String imageId, String network, boolean shared, HiveMetastore hiveMetastore, Yarn yarn) { String name = hdfsName(clusterId); - // One left stopped goes first, and a removal Docker refuses fails the start as it is, not as a name clash. + // One left stopped goes first, and a removal Docker refuses fails the start as it is, not as a name clash: the + // Trino on its network before it. + removeTrino(trinoName(clusterId)); lifecycleManager.removeIfExistsStrict(name); releaseSession(name); lifecycleManager.ensureVolume(name, labels(clusterId, accountId, region, COMPONENT)); @@ -1550,6 +1574,149 @@ 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) { + 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) { + removeTrino(name); + String endpoint = flociEndpointOn(hdfsName(clusterId)); + Optional credentials = roleCredentials.forRole(role, accountId, name); + sessions.put(name, new MetastoreSession(accountId, + credentials.map(SessionCreds::accessKeyId).orElse(null), endpoint)); + // Known before it starts, so a teardown while it starts removes it. + runningTrino.add(name); + try { + lifecycleManager.createAndStart(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)) + .withEnv(EmrTrino.CONFIG_VARIABLE, EmrTrino.CONFIG) + .withEnv(EmrTrino.CATALOG_VARIABLE, + EmrTrino.properties(EmrTrino.hiveCatalog(trino.hiveConnector(), endpoint, region))) + .withJavaTrustStore() + .withLogRotation() + .withLabels(labels(clusterId, accountId, region, EmrTrino.COMPONENT)) + .build()); + } catch (RuntimeException e) { + releaseSession(name); + throw e; + } + // A teardown that looked for it before Docker made it has passed it by: it goes now, with the HDFS. + stopIfStopped(clusterId, teardown, stopped); + LOG.infov("Started the Trino of EMR cluster {0}", clusterId); + } + awaitTrino(clusterId, name, teardown, stopped); + readyTrino.add(name); + } + + // Whether the Trino container named so runs on network, the namespace of the primary node now running, with a + // session of this process's; one an earlier process left has none. + private boolean trinoCurrent(String name, String network) { + if (!sessions.containsKey(name) || lifecycleManager.probeContainer(name) != ContainerLiveness.RUNNING) { + return false; + } + try { + HostConfig hostConfig = lifecycleManager.getDockerClient().inspectContainerCmd(name).exec() + .getHostConfig(); + return hostConfig != null && network.equals(hostConfig.getNetworkMode()); + } catch (NotFoundException e) { + return false; + } + } + + // Removes the Trino container named so, and its session, a removal Docker refuses thrown. + private void removeTrino(String name) { + lifecycleManager.removeIfExistsStrict(name); + releaseSession(name); + runningTrino.remove(name); + readyTrino.remove(name); + } + + // Removes the Trino container named so, a removal Docker refuses logged and the container kept known, so the next + // reset or shutdown tries again. Whether it is gone. + private boolean removeTrinoKnown(String name) { + try { + removeTrino(name); + return true; + } catch (RuntimeException e) { + LOG.warnv(e, "Could not remove the Trino container {0}: {1}", name, e.getMessage()); + return false; + } + } + + // Waits for the Trino container named so to have run a query for TRINO_SETTLE, within TRINO_START_TIMEOUT: 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) { + 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"); + } + ContainerExec.Result query; + try { + query = ContainerExec.run(lifecycleManager.getDockerClient(), name, + EmrTrino.READY_QUERY.toArray(String[]::new), 30); + } catch (RuntimeException e) { + // It may have stopped after it was looked at, which makes Docker refuse the exec: the next look + // says so. + if (lifecycleManager.probeContainer(name) == ContainerLiveness.NOT_RUNNING) { + continue; + } + throw e; + } + long now = nanoTime.getAsLong(); + if (query.exitCode() != 0) { + answering = Long.MIN_VALUE; + } else if (answering == Long.MIN_VALUE) { + answering = now; + } + if (answering != Long.MIN_VALUE && now - answering >= TRINO_SETTLE.toNanos()) { + return; + } + if (now >= deadline) { + logTrinoOutput(clusterId, name); + throw new IllegalStateException("The Trino of EMR cluster " + clusterId + " 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); + } + } + 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, + lifecycleManager.lastLogLines(name, NODE_LOG_LINES, NODE_LOG_READ)); + } + + private String trinoName(String clusterId) { + return ContainerStorageHelper.dockerName(config, SERVICE + "-" + clusterId + "-trino"); + } + // 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 @@ -1920,6 +2087,8 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { // cluster's end or a teardown that has not reached the HDFS yet, stops and leaves it to the cluster's other steps. private void stopIfStopped(String clusterId, long teardown, BooleanSupplier stopped) { if (teardowns.get() != teardown) { + // Its Trino first, which shares the HDFS container's network. + removeTrinoKnown(trinoName(clusterId)); removeKnown(hdfsName(clusterId)); throw new ClusterStorage.Stopped("Floci stopped the HDFS of EMR cluster " + clusterId); } @@ -1978,7 +2147,9 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { LOG.warnv(e, "Could not find the nodes of EMR cluster {0} to remove: {1}", clusterId, e.getMessage()); nodesGone = false; } - boolean containerGone = removeKnown(hdfsName(clusterId)); + // Its Trino before its primary node, whose network it shares. + boolean trinoGone = removeTrinoKnown(trinoName(clusterId)); + boolean containerGone = trinoGone && removeKnown(hdfsName(clusterId)); // Its relay goes, trusted no more, and every address given on its network with it. boolean relayGone = relays == null || relays.stop(clusterId); identities.remove(clusterId); @@ -1990,7 +2161,7 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { boolean homeGone = lifecycleManager.removeVolume(storage.home()); boolean mntGone = lifecycleManager.removeVolume(storage.mnt()); return lifecycleManager.removeVolume(hdfsName(clusterId)) && mntGone && homeGone && networkGone - && containerGone && nodesGone && relayGone; + && containerGone && trinoGone && nodesGone && relayGone; } /** @@ -2008,6 +2179,9 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { for (String name : List.copyOf(runningNodes)) { removeNode(name, false); } + for (String name : List.copyOf(runningTrino)) { + removeTrinoKnown(name); + } for (String name : List.copyOf(running)) { // What its history interfaces show goes into its kept history first, as nothing reads its HDFS after. if (lifecycleManager.probeContainer(name) == ContainerLiveness.RUNNING) { @@ -2053,7 +2227,21 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { @Override public void removeAllBut(Set kept) { - // Each sweep on its own, so Docker refusing one list does not keep the others from going. + // Each sweep on its own, so Docker refusing one list does not keep the others from going. The Trino an earlier + // process left goes whatever its cluster, as its session went with that process: its cluster's next step + // starts another. It goes first, as it shares its primary node's network. + try { + for (Container container : lifecycleManager.getDockerClient().listContainersCmd().withShowAll(true) + .withLabelFilter(Map.of(ContainerStorageHelper.COMPONENT_LABEL, EmrTrino.COMPONENT, + ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config))) + .exec()) { + String name = container.getNames()[0].substring(1); + runningTrino.add(name); + removeTrinoKnown(name); + } + } catch (RuntimeException e) { + LOG.warnv(e, "Could not remove the Trino an earlier Floci left: {0}", e.getMessage()); + } try { for (Container container : lifecycleManager.getDockerClient().listContainersCmd().withShowAll(true) .withLabelFilter(Map.of(ContainerStorageHelper.COMPONENT_LABEL, NODE_COMPONENT, diff --git a/src/main/java/io/floci/aws/services/emr/EmrReleaseImages.java b/src/main/java/io/floci/aws/services/emr/EmrReleaseImages.java index e9ec52fabe..c0238fa2f0 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrReleaseImages.java +++ b/src/main/java/io/floci/aws/services/emr/EmrReleaseImages.java @@ -49,7 +49,9 @@ import java.util.concurrent.ConcurrentHashMap; * release's HDFS and YARN do not run on its newer Hadoop, so its image gets the whole of that release's Hadoop, in a * folder apart, which only its primary node's daemons run from. For a cluster with Pig, which no AWS image carries, * the image gets Tez, as Pig's scripts run on it, and Apache Pig, downloaded as it is made ({@link PigDistribution}), - * whose checksum its name holds. + * whose checksum its name holds. For a cluster with Floci's Trino, it gets Trino's CLI from the Trino image the + * cluster's coordinator runs, never started either, and EMR's {@code trino-cli} command ({@link EmrTrino#COMMAND}), + * and its name holds that image's id. */ @ApplicationScoped public class EmrReleaseImages implements ReleaseImages { @@ -94,6 +96,9 @@ public class EmrReleaseImages implements ReleaseImages { new Copy("/usr/lib/tez", "/usr/lib"), new Copy("/etc/tez", "/etc"), new Copy(GOODIES, EMR_SHARE, HIVE_GOODIES)); + // What a cluster with Floci's Trino adds, from Trino's image: Trino's CLI, for its trino-cli (EmrTrino.COMMAND). + static final Copy TRINO_CLI = new Copy(EmrTrino.IMAGE_CLI, "/usr/lib", + EmrTrino.CLI.substring("/usr/lib/".length())); private static final String HADOOP_APART = "/opt"; // What it adds for a release of the AWS runtime for Apache Spark: another release's Hadoop, whole and kept apart. static final List HADOOP_APART_COPIES = List.of( @@ -140,27 +145,33 @@ public class EmrReleaseImages implements ReleaseImages { */ @Override public String image(String releaseLabel, String sparkImage, String hiveImage, boolean withHive, - boolean withPig) { + boolean withPig, String trinoImage) { List copies = copies(releaseLabel, withHive, withPig); PigDistribution pig = withPig && hadoopFolder(releaseLabel) == null ? pigDistribution : null; - // What is copied, and the Pig written after it, by its checksum. - String content = copies + (pig != null ? "\n" + pig.identity() : ""); + String trino = trinoImage != null ? containerBuilder.resolveImage(trinoImage) : null; + // What is copied, the Pig written after it, by its checksum, and Trino's CLI with its command. + String content = copies + (pig != null ? "\n" + pig.identity() : "") + + (trino != null ? "\n" + TRINO_CLI + "\n" + EmrTrino.COMMAND : ""); String spark = containerBuilder.resolveImage(sparkImage); String hive = containerBuilder.resolveImage(hiveImage); String repository = ContainerStorageHelper.dockerName(config, COMPONENT); - String kind = Digests.sha256Hex(releaseLabel + "\n" + spark + "\n" + hive + "\n" + content).substring(0, 12); + String kind = Digests.sha256Hex(releaseLabel + "\n" + spark + "\n" + hive + "\n" + content + + (trino != null ? "\n" + trino : "")).substring(0, 12); synchronized (making.computeIfAbsent(repository + ":" + kind, name -> new Object())) { String sparkId = imageCacheService.resolveForLaunch(spark, ImagePullBehavior.PREFER_CACHED, null) .imageId(); String hiveId = imageCacheService.resolveForLaunch(hive, ImagePullBehavior.PREFER_CACHED, null).imageId(); - String tag = releaseLabel + "-" - + Digests.sha256Hex(sparkId + "\n" + hiveId + "\n" + content).substring(0, 12); + String trinoId = trino != null + ? imageCacheService.resolveForLaunch(trino, ImagePullBehavior.PREFER_CACHED, null).imageId() : null; + String tag = releaseLabel + "-" + Digests.sha256Hex(sparkId + "\n" + hiveId + "\n" + content + + (trinoId != null ? "\n" + trinoId : "")).substring(0, 12); DockerClient docker = lifecycleManager.getDockerClient(); try { return hold(docker.inspectImageCmd(repository + ":" + tag).exec().getId()); } catch (NotFoundException e) { LOG.infov("Making {0}:{1} for EMR clusters {2}, from {3} and {4}", repository, tag, - (withHive ? "with Hive" : "without Hive") + (pig != null ? ", with Pig" : ""), spark, hive); + (withHive ? "with Hive" : "without Hive") + (pig != null ? ", with Pig" : "") + + (trino != null ? ", with Trino's CLI from " + trino : ""), spark, hive); } String user = docker.inspectImageCmd(sparkId).exec().getConfig().getUser(); Map labels = new LinkedHashMap<>(); @@ -192,6 +203,15 @@ public class EmrReleaseImages implements ReleaseImages { RetryingTarCopier.copyBytes(docker, target, PigDistribution.COMMAND_FOLDER, PigDistribution.NAME, PigDistribution.COMMAND.getBytes(StandardCharsets.UTF_8), 0755); } + if (trinoId != null) { + String cli = docker.createContainerCmd(trinoId).withLabels(labels).exec().getId(); + containers.add(cli); + RetryingTarCopier.copyStreamed(docker, target, TRINO_CLI.into(), TRINO_CLI.from(), + out -> copy(docker.copyArchiveFromContainerCmd(cli, TRINO_CLI.from()).exec(), out, + TRINO_CLI)); + RetryingTarCopier.copyBytes(docker, target, EmrTrino.COMMAND_FOLDER, EmrTrino.COMMAND_NAME, + EmrTrino.COMMAND.getBytes(StandardCharsets.UTF_8), 0755); + } made = lifecycleManager.commit(target, repository, tag, user == null || user.isBlank() ? "root" : user, labels); } finally { 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 a1466cb778..79ccef89d3 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrService.java +++ b/src/main/java/io/floci/aws/services/emr/EmrService.java @@ -201,6 +201,11 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear private final String dockerNetwork; // 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. + private final boolean trinoEnabled; + private final String trinoImageTemplate; + private final int trinoMemoryMb; // What the NodeManager of a cluster that runs YARN offers its containers. private final ClusterStorage.Yarn nodeManager; private final int maxWorkerNodes; @@ -383,6 +388,9 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear this.hiveImageTemplate = config.services().emr().hiveImageTemplate().orElse(null); this.dockerNetwork = config.services().emr().dockerNetwork().orElse(null); this.pigEnabled = config.services().emr().pig().enabled(); + 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.nodeManager = new ClusterStorage.Yarn(config.services().emr().yarnNodeMemoryMb(), config.services().emr().yarnNodeVcores()); this.maxWorkerNodes = config.services().emr().yarnMaxWorkerNodes(); @@ -3097,10 +3105,12 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear String hdfsHost = masterPrivateDnsName(cluster); String hdfsImage = hdfsImage(cluster.getReleaseLabel()); Supplier nodeYarn = runsYarn(cluster) ? currentYarn(cluster, accountId, region) : null; - ClusterStorage.HiveMetastore hiveMetastore = EmrSparkSteps.installsHive(cluster.getReleaseLabel(), - cluster.getApplications(), SNAPSHOT_MAPPER) + String trinoImage = trinoImage(cluster); + ClusterStorage.Trino trino = trinoImage == null ? null : new ClusterStorage.Trino(trinoImage, trinoMemoryMb, + EmrSparkSteps.trinoHiveConnector(cluster.getConfigurations(), SNAPSHOT_MAPPER)); + ClusterStorage.HiveMetastore hiveMetastore = withHiveImage(cluster) ? new ClusterStorage.HiveMetastore(instanceProfileRole(cluster, accountId), - EmrSparkSteps.hiveMetastoreSettings(cluster.getConfigurations(), SNAPSHOT_MAPPER)) + EmrSparkSteps.hiveMetastoreSettings(cluster.getConfigurations(), SNAPSHOT_MAPPER), trino) : null; BiFunction hdfs = volumes == null ? null : (stepImage, stopped) -> clusterStorage.hdfs(clusterId, accountId, region, hdfsHost, @@ -3154,7 +3164,9 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear EmrSparkSteps.sparkDefaults(cluster.getConfigurations(), SNAPSHOT_MAPPER), application != null ? application : List.of(), command, Duration.ZERO, EmrSparkSteps.logFolder(cluster, step), null, - stepEnvironment(step, cluster, command != null && pig), List.of(), + stepEnvironment(step, cluster, command != null && pig, + trinoImage(cluster) != null ? EmrTrino.server(masterPrivateDnsName(cluster)) : null), + List.of(), storage, EmrSparkSteps.coreSite(cluster.getConfigurations(), SNAPSHOT_MAPPER), EmrSparkSteps.sparkLog4j2(cluster.getConfigurations(), SNAPSHOT_MAPPER), EmrSparkSteps.mapredSite(cluster.getConfigurations(), SNAPSHOT_MAPPER), @@ -3358,8 +3370,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear if (releaseImages == null) { return null; } - boolean withHive = EmrSparkSteps.installsHive(cluster.getReleaseLabel(), cluster.getApplications(), - SNAPSHOT_MAPPER); + boolean withHive = withHiveImage(cluster); boolean withPig = withPig(cluster); if (!withHive && !withPig && !runsYarn(cluster)) { return null; @@ -3367,7 +3378,25 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear String release = cluster.getReleaseLabel(); String spark = EmrServerlessSparkRunner.image(imageTemplate, release); String hive = hdfsImage(release); - return () -> releaseImages.image(release, spark, hive, withHive, withPig); + String trino = trinoImage(cluster); + return () -> releaseImages.image(release, spark, hive, withHive, withPig, trino); + } + + // Whether a cluster's image has Hive, and its primary node Hive's metastore service: it installs Hive or HCatalog, + // or runs Floci's Trino, with which EMR installs hive-client and hcatalog-server. + private boolean withHiveImage(EmrCluster cluster) { + return EmrSparkSteps.installsHive(cluster.getReleaseLabel(), cluster.getApplications(), SNAPSHOT_MAPPER) + || trinoImage(cluster) != null; + } + + // The image a cluster's Trino runs from: it installs Trino, floci.services.emr.trino.enabled runs it, and its + // release's Trino version is known (EmrTrino.image); null otherwise. + private String trinoImage(EmrCluster cluster) { + if (!trinoEnabled || !EmrSparkSteps.installsTrino(cluster.getReleaseLabel(), cluster.getApplications(), + SNAPSHOT_MAPPER)) { + return null; + } + return EmrTrino.image(trinoImageTemplate, cluster.getReleaseLabel()); } // Whether a cluster's image has Floci's Pig: it installs Pig, and floci.services.emr.pig.enabled adds it. @@ -3377,12 +3406,17 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear } // The variables a step that is not a Hive step runs with: its cluster's spark-env exports and its own Properties - // (see EmrSparkSteps.environment), and for a command on a cluster with Floci's Pig, its Pig configuration. - private static Map stepEnvironment(EmrStep step, EmrCluster cluster, boolean pig) { + // (see EmrSparkSteps.environment), for a command on a cluster with Floci's Pig, its Pig configuration, and on one + // with Floci's Trino, where its trino-cli reaches the coordinator, unless trinoServer is null. + private static Map stepEnvironment(EmrStep step, EmrCluster cluster, boolean pig, + String trinoServer) { Map variables = EmrSparkSteps.environment(step, cluster.getConfigurations(), SNAPSHOT_MAPPER); if (pig) { variables.putAll(EmrSparkSteps.pigEnvironment(cluster.getConfigurations(), SNAPSHOT_MAPPER)); } + if (trinoServer != null) { + variables.put(EmrTrino.SERVER_VARIABLE, trinoServer); + } return variables; } @@ -3393,14 +3427,13 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear */ // The YARN timeline server runs on a cluster with Hadoop, and the Tez UI on one with Tez too, as their persistent // interfaces are there (EmrAppUiService), but for a release of the AWS runtime for Apache Spark; the Tez UI only - // where the cluster's image has Tez, which one with Hive or Floci's Pig has (releaseImage). + // where the cluster's image has Tez, which one with Hive, Floci's Trino or Floci's Pig has (releaseImage). private ClusterStorage.Yarn yarnOf(EmrCluster cluster) { List nodes = workerNodes(cluster); boolean timeline = EmrSparkSteps.names(cluster.getApplications(), SNAPSHOT_MAPPER, "Hadoop") && !(cluster.getReleaseLabel() != null && EmrServerlessSparkRunner.sparkRuntime(cluster.getReleaseLabel())); - boolean tezImage = EmrSparkSteps.installsHive(cluster.getReleaseLabel(), cluster.getApplications(), - SNAPSHOT_MAPPER) || withPig(cluster); + boolean tezImage = withHiveImage(cluster) || withPig(cluster); long coreNodes = nodes.stream().filter(ClusterStorage.Node::core).count(); return nodeManager.withHadoopFolder(EmrReleaseImages.hadoopFolder(cluster.getReleaseLabel())) .onNodes(nodes, (int) Math.max(1, Math.min(replication(cluster), coreNodes)), diff --git a/src/main/java/io/floci/aws/services/emr/EmrSparkSteps.java b/src/main/java/io/floci/aws/services/emr/EmrSparkSteps.java index b0d441812b..e96977c835 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrSparkSteps.java +++ b/src/main/java/io/floci/aws/services/emr/EmrSparkSteps.java @@ -270,8 +270,21 @@ final class EmrSparkSteps { return installs(releaseLabel, applications, objectMapper, PIG); } + /** + * Whether a cluster installs Trino: its {@code Applications} name it, unless its release is of the AWS runtime for + * Apache Spark, whose applications do not include it. + */ + static boolean installsTrino(String releaseLabel, String applications, ObjectMapper objectMapper) { + return installs(releaseLabel, applications, objectMapper, EmrTrino.APPLICATION); + } + + /** The properties of a cluster's {@code trino-connector-hive}, which its Trino's {@code hive} catalog gets. */ + static Map trinoHiveConnector(String configurations, ObjectMapper objectMapper) { + return properties(configurations, objectMapper, EmrTrino.HIVE_CONNECTOR); + } + // Whether a cluster's Applications name any of names, in any case, unless its release is of the AWS runtime for - // Apache Spark, which installs neither Hive, HCatalog nor Pig. + // Apache Spark, which installs none of Hive, HCatalog, Pig and Trino. private static boolean installs(String releaseLabel, String applications, ObjectMapper objectMapper, String... names) { return (releaseLabel == null || !EmrServerlessSparkRunner.sparkRuntime(releaseLabel)) diff --git a/src/main/java/io/floci/aws/services/emr/EmrTrino.java b/src/main/java/io/floci/aws/services/emr/EmrTrino.java new file mode 100644 index 0000000000..9650084b0a --- /dev/null +++ b/src/main/java/io/floci/aws/services/emr/EmrTrino.java @@ -0,0 +1,136 @@ +package io.floci.aws.services.emr; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +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. + * "By default, Amazon EMR configures the Presto web interface on the Presto coordinator to use port 8889 (for PrestoDB + * and Trino)", where it listens. EMR installs {@code hcatalog-server} with Trino, so its {@code hive} catalog is the + * cluster's Hive metastore, unless the cluster's {@code trino-connector-hive} classification sets + * {@code hive.metastore} to {@code glue}, as the Release Guide's "Launch an Amazon EMR cluster with Trino" does. Its + * steps run {@code trino-cli}, EMR's command for Trino's CLI, which this class writes for the image they run in. + */ +final class EmrTrino { + + /** The application's name, as the Release Guide's list of applications spells it. */ + static final String APPLICATION = "Trino"; + /** The port Trino listens on, on the primary node. */ + static final int PORT = 8889; + /** The classification whose properties go into the {@code hive} catalog. */ + static final String HIVE_CONNECTOR = "trino-connector-hive"; + /** The component label of a cluster's Trino container, which goes with its primary node's. */ + static final String COMPONENT = "emr-trino"; + /** The variable a step's {@code trino-cli} reads the coordinator's address from. */ + static final String SERVER_VARIABLE = "FLOCI_TRINO_SERVER"; + /** Trino's CLI in its image, an executable jar, which the cluster's image takes. */ + static final String IMAGE_CLI = "/usr/bin/trino"; + /** Where the cluster's image keeps that jar. */ + static final String CLI = "/usr/lib/trino/trino-cli"; + /** The folder of EMR's {@code trino-cli} command, and its name. */ + static final String COMMAND_FOLDER = "/usr/bin"; + static final String COMMAND_NAME = "trino-cli"; + /** + * EMR's {@code trino-cli}: the CLI on the image's Java 17, which a release whose default is Java 8 has besides, to + * the cluster's coordinator, unless the step names a server of its own. + */ + static final String COMMAND = """ + #!/bin/bash + java=/usr/lib/jvm/jre-17/bin/java + [ -x "$java" ] || java=java + for argument in "$@"; do + case "$argument" in + --server|--server=*) exec "$java" -jar %1$s "$@" ;; + esac + done + exec "$java" -jar %1$s --server "${%2$s:-localhost:%3$d}" "$@" + """.formatted(CLI, SERVER_VARIABLE, PORT); + /** What tells the Trino container is ready: a query, run with the CLI of its image. */ + static final List READY_QUERY = List.of(IMAGE_CLI, "--server", "localhost:" + PORT, "--execute", + "SELECT 1"); + /** The variables the Trino container's entrypoint writes its configuration from. */ + static final String CONFIG_VARIABLE = "FLOCI_TRINO_CONFIG"; + static final String CATALOG_VARIABLE = "FLOCI_TRINO_CATALOG_HIVE"; + /** + * The Trino container's entrypoint: its configuration, and its {@code hive} catalog alone, as EMR's Trino has the + * catalogs the cluster configures, then Trino, as its image starts it. Its image names the node after its host, + * which is the primary node's, whose dots Trino refuses in a node's id, so the node is named with hyphens instead. + */ + static final String ENTRYPOINT = "printf '%s\\n' \"$" + CONFIG_VARIABLE + "\" > /etc/trino/config.properties" + + " && rm -f /etc/trino/catalog/*.properties" + + " && printf '%s\\n' \"$" + CATALOG_VARIABLE + "\" > /etc/trino/catalog/hive.properties" + + " && printf 'node.id=%s\\n' \"${HOSTNAME//./-}\" >> /etc/trino/node.properties" + + " && exec /usr/lib/trino/bin/run-trino"; + /** A coordinator that runs the queries too, on {@link #PORT}. */ + static final String CONFIG = """ + coordinator=true + node-scheduler.include-coordinator=true + http-server.http.port=%1$d + discovery.uri=http://localhost:%1$d""".formatted(PORT); + + private static final String GLUE = "glue"; + + private EmrTrino() { + } + + /** + * The image Trino runs from for a release: {@code template} with the release's Trino version for {@code %s}, as + * its page in the Release Guide gives it without AWS's build suffix, or {@code template} itself when it has no + * {@code %s}. Null for a release whose version Floci does not know, which then runs no Trino. + */ + static String image(String template, String releaseLabel) { + if (template == null || template.isBlank()) { + return null; + } + if (!template.contains("%s")) { + return template; + } + return EmrReleaseCatalog.release(releaseLabel) + .flatMap(release -> release.applications().stream() + .filter(application -> APPLICATION.equals(application.name())).findFirst()) + .map(application -> template.formatted(application.version())) + .orElse(null); + } + + /** The address a step's {@code trino-cli} reaches the coordinator at, on the primary node named {@code host}. */ + static String server(String host) { + return "http://" + host + ":" + PORT; + } + + /** + * The {@code hive} catalog: the cluster's metastore, which runs beside Trino on the primary node, or, with + * {@code hive.metastore} set to {@code glue}, Floci's Glue; Floci's S3 at {@code endpoint} in {@code region}, by + * path, the HDFS of the cluster's warehouse through Hadoop's file system; and the cluster's + * {@code trino-connector-hive} 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 hiveCatalog(Map classification, String endpoint, String region) { + Map catalog = new LinkedHashMap<>(); + catalog.put("connector.name", "hive"); + if (GLUE.equalsIgnoreCase(classification.get("hive.metastore"))) { + catalog.put("hive.metastore", GLUE); + catalog.put("hive.metastore.glue.region", region); + catalog.put("hive.metastore.glue.endpoint-url", endpoint); + } else { + catalog.put("hive.metastore.uri", "thrift://localhost:" + EmrClusterStorage.HIVE_METASTORE_PORT); + } + catalog.put("fs.native-s3.enabled", "true"); + catalog.put("fs.hadoop.enabled", "true"); + catalog.put("s3.endpoint", endpoint); + catalog.put("s3.region", region); + catalog.put("s3.path-style-access", "true"); + catalog.putAll(classification); + return catalog; + } + + /** {@code properties} as the lines of a Java properties file, in their order. */ + static String properties(Map properties) { + return properties.entrySet().stream().map(entry -> entry.getKey() + "=" + entry.getValue()) + .collect(Collectors.joining("\n")); + } +} diff --git a/src/main/java/io/floci/aws/services/emr/ReleaseImages.java b/src/main/java/io/floci/aws/services/emr/ReleaseImages.java index 7118e742c4..d6d99ee088 100644 --- a/src/main/java/io/floci/aws/services/emr/ReleaseImages.java +++ b/src/main/java/io/floci/aws/services/emr/ReleaseImages.java @@ -14,7 +14,17 @@ public interface ReleaseImages { * Hadoop's services alone, and with Pig or without, made first when the Docker daemon does not have it, which may * take as long as pulling the two, and downloading Pig; a failure is thrown. */ - String image(String releaseLabel, String sparkImage, String hiveImage, boolean withHive, boolean withPig); + default String image(String releaseLabel, String sparkImage, String hiveImage, boolean withHive, + boolean withPig) { + return image(releaseLabel, sparkImage, hiveImage, withHive, withPig, null); + } + + /** + * {@link #image(String, String, String, boolean, boolean)}, with EMR's {@code trino-cli} for the Trino of + * {@code trinoImage}, unless that is null, which pulling that image may take long too. + */ + String image(String releaseLabel, String sparkImage, String hiveImage, boolean withHive, boolean withPig, + String trinoImage); /** * The step or the bootstrap that {@link #image} gave {@code imageId} to has ended, so a newer image of its kind may diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 6d46815dfb..07255f6086 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -728,6 +728,10 @@ floci: enabled: false # true = add Apache Pig, downloaded, to a docker cluster that installs 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 # sha256: 6845adb936a3c3bcc71451765953cae4103e410ba2f6c5a47cc9becade0a434a + 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 # 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 73b247866b..0a74f5e895 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrClusterStorageTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrClusterStorageTest.java @@ -41,11 +41,14 @@ import io.floci.aws.services.lambda.launcher.BootstrapProcess; import io.floci.aws.services.lambda.launcher.ImageCacheService; import io.floci.aws.services.lambda.launcher.LambdaExecutionRoleCredentials; import io.floci.aws.services.s3.S3Service; +import io.floci.aws.testing.ParallelLocks; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.api.parallel.ResourceAccessMode; +import org.junit.jupiter.api.parallel.ResourceLock; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; @@ -102,6 +105,8 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** A cluster's storage: Docker volumes, and its HDFS in a container of its own, on its primary node. */ +// It names Trino's port, localhost:8889, and opens no socket. +@ResourceLock(value = ParallelLocks.PORTS, mode = ResourceAccessMode.READ) class EmrClusterStorageTest { private static final String IMAGE = "public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest"; @@ -119,6 +124,10 @@ class EmrClusterStorageTest { // A cluster with Hive, whose EC2 instance profile's role is r, with no core-site or hive-site. private static final ClusterStorage.HiveMetastore METASTORE = new ClusterStorage.HiveMetastore("arn:aws:iam::123456789012:role/r", Map.of()); + // The same with Trino beside it, from the image of emr-7.5.0's Trino. + 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())); private final EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); private final DockerClient docker = mock(DockerClient.class); @@ -131,6 +140,12 @@ class EmrClusterStorageTest { private final S3Service s3 = mock(S3Service.class); private final EmrClusterStorage storage = new EmrClusterStorage(lifecycle, containerBuilder, awsEnv, roleCredentials, currentContainer, config, s3, Duration.ofSeconds(120), System::nanoTime); + // A storage whose clock moves on five seconds each time it is read, so Trino's ten seconds of answering pass + // at once. + private final AtomicLong fiveSecondTicks = new AtomicLong(); + private final EmrClusterStorage ticking = new EmrClusterStorage(lifecycle, containerBuilder, awsEnv, + roleCredentials, currentContainer, config, s3, Duration.ofSeconds(120), + () -> fiveSecondTicks.addAndGet(TimeUnit.SECONDS.toNanos(5))); private final String hdfsName = ContainerStorageHelper.dockerName(config, "emr-j-1-hdfs"); private final String historyName = ContainerStorageHelper.dockerName(config, "emr-j-1-history"); private final String coreName = ContainerStorageHelper.dockerName(config, "emr-j-1-node-1-1"); @@ -1970,6 +1985,164 @@ class EmrClusterStorageTest { verify(roleCredentials).unregister("123456789012", "ASIAMETASTORE"); } + @Test + void trinoRunsBesideTheMetastoreOnThePrimaryNodesNetworkAndGoesBeforeIt() { + String trinoName = ContainerStorageHelper.dockerName(config, "emr-j-1-trino"); + when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-6", Map.of()), + new ContainerLifecycleManager.ContainerInfo("t-1", Map.of())); + TrinoStubs trino = trinoStarts(trinoName); + ContainerBuilder.Builder trinoSpec = trino.spec(); + List> asked = trino.asked(); + List removed = trino.removed(); + + ticking.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", TRINO_METASTORE, null, + NOT_STOPPED); + + verify(trinoSpec).withName(trinoName); + // On the primary node's network, as a daemon of it, with its memory, its configuration and its hive catalog. + 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.CONFIG); + verify(trinoSpec).withEnv(EmrTrino.CATALOG_VARIABLE, EmrTrino.properties(EmrTrino.hiveCatalog(Map.of(), + "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 -> + EmrTrino.COMPONENT.equals(labels.get(ContainerStorageHelper.COMPONENT_LABEL)))); + // Waited for, until it has run a query for ten seconds: its first query fails, the next three answer. + List query = List.of("/usr/bin/trino", "--server", "localhost:8889", "--execute", "SELECT 1"); + assertEquals(List.of(query, query, query, query), asked); + + ticking.remove("j-1"); + + // It goes before the primary node, whose network it shares, and its session with it. + assertEquals(List.of(trinoName, hdfsName), removed.subList(removed.size() - 2, removed.size())); + verify(roleCredentials).unregister("123456789012", "ASIATRINO"); + } + + @Test + void trinoIsReadyOnceItHasRunAQueryForTenSecondsAFailureBetweenStartingThemAgain() { + String trinoName = ContainerStorageHelper.dockerName(config, "emr-j-1-trino"); + when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-6", Map.of()), + new ContainerLifecycleManager.ContainerInfo("t-1", Map.of())); + trinoStarts(trinoName); + // It answers, then fails, as Trino may before its node manager has caught up, then answers on. + List> asked = ContainerExecStubs.completeEveryExec(docker, trinoName, List.of(0L, 1L, 0L), "", + ""); + + ticking.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", TRINO_METASTORE, null, + NOT_STOPPED); + + // Five seconds between each: ten seconds of answers only from the third. + assertEquals(5, asked.size(), asked.toString()); + } + + @Test + void theClustersNextStepHasATrinoThatBecameReadyAtOnce() { + String trinoName = ContainerStorageHelper.dockerName(config, "emr-j-1-trino"); + when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-6", Map.of()), + new ContainerLifecycleManager.ContainerInfo("t-1", Map.of())); + TrinoStubs trino = trinoStarts(trinoName); + // Started by this process, then found running by the cluster's next step, Trino on its network. + when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING, 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"); + ticking.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", TRINO_METASTORE, null, + NOT_STOPPED); + int asked = trino.asked().size(); + + ticking.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", TRINO_METASTORE, null, + NOT_STOPPED); + + // No other container, and no other wait. + verify(lifecycle, times(2)).createAndStart(any()); + assertEquals(asked, trino.asked().size()); + } + + @Test + void aTrinoATeardownPassedByWhileDockerMadeItGoesWithTheHdfs() { + String trinoName = ContainerStorageHelper.dockerName(config, "emr-j-1-trino"); + TrinoStubs trino = trinoStarts(trinoName); + // A reset looks for Trino while Docker makes its container, so it finds none to remove. + when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-6", Map.of())) + .thenAnswer(starting -> { + ticking.stopManagedContainers(); + trino.removed().add("made"); + return new ContainerLifecycleManager.ContainerInfo("t-1", Map.of()); + }); + + assertThrows(ClusterStorage.Stopped.class, () -> ticking.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, + "floci-network", TRINO_METASTORE, null, NOT_STOPPED)); + + // Once made, it goes, before the HDFS it shares a network with, and is not waited for. + List afterMade = trino.removed().subList(trino.removed().indexOf("made") + 1, trino.removed().size()); + assertEquals(List.of(trinoName, hdfsName), afterMade); + assertEquals(List.of(), trino.asked()); + verify(roleCredentials).unregister("123456789012", "ASIATRINO"); + } + + @Test + void trinoStartsOnceTheNodesAreReadySoItsWaitLeavesThemTheirDeadline() { + String trinoName = ContainerStorageHelper.dockerName(config, "emr-j-1-trino"); + trinoStarts(trinoName); + when(awsEnv.flociEndpoint()).thenReturn("http://floci:4566"); + // When the nodes are looked at, and when Trino's container is made. + List events = new ArrayList<>(); + when(lifecycle.createAndStart(any())).thenAnswer(creating -> { + ContainerSpec created = creating.getArgument(0); + events.add("made " + created.image()); + return new ContainerLifecycleManager.ContainerInfo("sha256:trino".equals(created.image()) ? "t-1" : "c-6", + Map.of()); + }); + for (String node : List.of(coreName, taskName)) { + when(lifecycle.probeContainer(node)).thenAnswer(looking -> { + events.add("looked at " + node); + return ContainerLiveness.RUNNING; + }); + ContainerExecStubs.completeEveryExec(docker, node, 0L, "", ""); + } + + ticking.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", TRINO_METASTORE, + () -> TWO_NODES, NOT_STOPPED); + + assertTrue(events.contains("made sha256:trino"), events.toString()); + assertTrue(events.lastIndexOf("looked at " + coreName) < events.indexOf("made sha256:trino"), + events.toString()); + assertTrue(events.lastIndexOf("looked at " + taskName) < events.indexOf("made sha256:trino"), + events.toString()); + } + + @Test + void theTrinoAnEarlierFlociLeftGoesAtStartWhateverItsCluster() { + String trinoName = ContainerStorageHelper.dockerName(config, "emr-j-up-trino"); + Container left = nodeOf("j-up", trinoName); + AtomicReference> filter = new AtomicReference<>(); + ListContainersCmd list = mock(ListContainersCmd.class, RETURNS_SELF); + when(docker.listContainersCmd()).thenReturn(list); + when(list.withLabelFilter(any(Map.class))).thenAnswer(asked -> { + filter.set(asked.getArgument(0)); + return list; + }); + when(list.exec()).thenAnswer(reading -> + EmrTrino.COMPONENT.equals(filter.get().get(ContainerStorageHelper.COMPONENT_LABEL)) + ? List.of(left) : List.of()); + ListNetworksCmd networks = mock(ListNetworksCmd.class, RETURNS_SELF); + when(docker.listNetworksCmd()).thenReturn(networks); + when(networks.exec()).thenReturn(List.of()); + ListVolumesCmd volumes = mock(ListVolumesCmd.class, RETURNS_SELF); + when(docker.listVolumesCmd()).thenReturn(volumes); + when(volumes.exec()).thenReturn(mock(ListVolumesResponse.class)); + + // Its cluster is up, but its session went with the Floci that left it: the cluster's next step starts another. + storage.removeAllBut(Set.of("j-up")); + + verify(lifecycle).removeIfExistsStrict(trinoName); + } + @Test void aMetastoresSessionGoesWithItsContainerOnAResetOrAShutdownAndWhenItCannotStart() { ClusterStorage.HiveMetastore metastore = METASTORE; @@ -2997,6 +3170,45 @@ class EmrClusterStorageTest { return volume; } + // What a Trino container named trinoName meets beside a primary node that starts as c-6: its image, the query + // it runs once its coordinator schedules on itself, failing first, its session, and the removals, in order. + private TrinoStubs trinoStarts(String trinoName) { + when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING); + when(lifecycle.probeContainer("c-6")).thenReturn(ContainerLiveness.RUNNING); + when(lifecycle.resolveContainerNetworkIp("c-6", hdfsName)).thenReturn("172.18.0.7"); + ContainerExecStubs.completeEveryExec(docker, "c-6", 0L, "", ""); + InspectContainerCmd primary = mock(InspectContainerCmd.class, RETURNS_DEEP_STUBS); + when(primary.exec().getId()).thenReturn("c6c6c6"); + when(docker.inspectContainerCmd("c-6")).thenReturn(primary); + // Trino's image, pulled as the HDFS's is, and its container, which runs a query once its coordinator + // schedules on itself. + ContainerBuilder.Builder trinoSpec = mock(ContainerBuilder.Builder.class, RETURNS_SELF); + when(containerBuilder.resolveImage("trinodb/trino:446")).thenReturn("trinodb/trino:446"); + when(lifecycle.resolveImageForLaunch("trinodb/trino:446", ImagePullBehavior.PREFER_CACHED, null)) + .thenReturn(new ImageCacheService.LaunchImage("sha256:trino", null)); + when(containerBuilder.newContainer("sha256:trino")).thenReturn(trinoSpec); + when(trinoSpec.build()).thenReturn(new ContainerSpec("sha256:trino")); + when(lifecycle.probeContainer(trinoName)).thenReturn(ContainerLiveness.RUNNING); + List> asked = ContainerExecStubs.completeEveryExec(docker, trinoName, List.of(1L, 0L), "\"1\"", + ""); + // Its own session for the cluster's instance profile's role, as the metastore has. + Optional trinoSession = Optional.of(new SessionCreds("ASIATRINO", "s", "t")); + when(roleCredentials.forRole("arn:aws:iam::123456789012:role/r", "123456789012", hdfsName)) + .thenReturn(Optional.of(new SessionCreds("ASIAMETASTORE", "s", "t"))); + when(roleCredentials.forRole("arn:aws:iam::123456789012:role/r", "123456789012", trinoName)) + .thenReturn(trinoSession); + when(awsEnv.flociEndpoint(false)).thenReturn("http://host.docker.internal:4566"); + when(awsEnv.sdkBaselineEnv(anyString(), any(), anyString(), any(), anyString())).thenReturn(List.of()); + when(awsEnv.sdkBaselineEnv("us-east-1", Optional.empty(), "http://host.docker.internal:4566", trinoSession, + "123456789012")).thenReturn(List.of("AWS_ACCESS_KEY_ID=ASIATRINO")); + List removed = new ArrayList<>(); + doAnswer(removing -> removed.add(removing.getArgument(0))).when(lifecycle).removeIfExistsStrict(anyString()); + return new TrinoStubs(trinoSpec, asked, removed); + } + + private record TrinoStubs(ContainerBuilder.Builder spec, List> asked, List removed) { + } + 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/EmrReleaseImagesTest.java b/src/test/java/io/floci/aws/services/emr/EmrReleaseImagesTest.java index 6e495530b7..c5d7470ef2 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrReleaseImagesTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrReleaseImagesTest.java @@ -179,6 +179,27 @@ class EmrReleaseImagesTest { assertTrue(withHive.containsAll(EmrReleaseImages.TEZ_COPIES)); } + @Test + void anImageForAClusterWithFlocisTrinoHasTrinosCliFromItsImageAndANameOfItsOwn() { + List copied = makesMissing("emr-7.5.0", true, false, "trinodb/trino:446"); + + // Hive's, then the CLI, from a container of the Trino image the coordinator runs, never started. + List expected = new ArrayList<>(EmrReleaseImages.COPIES.stream().map(EmrReleaseImages.Copy::from) + .toList()); + expected.add("cli:/usr/bin/trino"); + assertEquals(expected, copied); + assertEquals("/usr/lib", EmrReleaseImages.TRINO_CLI.into()); + assertEquals("trino/trino-cli", EmrReleaseImages.TRINO_CLI.as()); + verify(docker).removeContainerCmd("cli"); + ArgumentCaptor tags = ArgumentCaptor.forClass(String.class); + ArgumentCaptor> labels = mapCaptor(); + images.image("emr-7.5.0", SPARK, HIVE, true, false); + verify(lifecycle, times(2)).commit(eq("target"), anyString(), tags.capture(), anyString(), labels.capture()); + assertNotEquals(tags.getAllValues().get(0), tags.getAllValues().get(1)); + assertNotEquals(labels.getAllValues().get(0).get(EmrReleaseImages.KIND_LABEL), + labels.getAllValues().get(1).get(EmrReleaseImages.KIND_LABEL)); + } + @Test void aReleaseOfTheAwsRuntimeForSparkGetsNoPig() throws IOException { // "Pig and Oozie are not included." @@ -500,6 +521,11 @@ class EmrReleaseImagesTest { } private List makesMissing(String release, boolean withHive, boolean withPig) { + return makesMissing(release, withHive, withPig, null); + } + + // What the image made copies, a path of the Trino image's container as cli:, with Trino's CLI of trino. + private List makesMissing(String release, boolean withHive, boolean withPig, String trino) { when(lifecycle.getDockerClient()).thenReturn(docker); String repository = ContainerStorageHelper.dockerName(config, "emr-release"); // The two are pulled as a container's image would be, from the image-registry-base it names. @@ -527,6 +553,16 @@ class EmrReleaseImagesTest { when(from.exec()).thenAnswer(read -> new ByteArrayInputStream(new byte[0])); return from; }); + if (trino != null) { + resolves("mirror/" + trino, "sha256:trino"); + container("sha256:trino", "cli"); + when(docker.copyArchiveFromContainerCmd(eq("cli"), anyString())).thenAnswer(invocation -> { + copied.add("cli:" + invocation.getArgument(1)); + CopyArchiveFromContainerCmd from = mock(CopyArchiveFromContainerCmd.class); + when(from.exec()).thenAnswer(read -> new ByteArrayInputStream(new byte[0])); + return from; + }); + } when(docker.copyArchiveToContainerCmd("target")) .thenReturn(copyCommand()); when(lifecycle.commit(eq("target"), eq(repository), anyString(), eq("hadoop:hadoop"), any())) @@ -535,7 +571,7 @@ class EmrReleaseImagesTest { when(listImages.exec()).thenAnswer(invocation -> listed); when(docker.listImagesCmd()).thenReturn(listImages); - assertEquals("sha256:made", images.image(release, SPARK, HIVE, withHive, withPig)); + assertEquals("sha256:made", images.image(release, SPARK, HIVE, withHive, withPig, trino)); return copied; } 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 f7a34b2f19..f9949813dc 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java @@ -69,6 +69,7 @@ class EmrServiceContainerStepsTest { private static final String DRIVER_FAILED = "The Spark driver exited with code 1."; private static final String INSTALL = "s3://bucket/bootstrap/install.sh"; private static final String PIG = "[{\"Name\": \"Hadoop\"}, {\"Name\": \"Pig\"}]"; + private static final String TRINO = "[{\"Name\": \"Trino\"}]"; private static final String ERROR_CODE_PAGES = "https://docs.aws.amazon.com/emr/latest/ManagementGuide/"; // The id of the image a bootstrap kept, which the cluster's steps run in. private static final String IMAGE = "sha256:" + "2".repeat(64); @@ -1098,6 +1099,49 @@ class EmrServiceContainerStepsTest { job.environment().get("FLOCI_PIG_PROPERTIES")); } + @Test + void aClusterWithFlocisTrinoRunsItBesideTheMetastoreWhereItsStepsTrinoCliReachesIt() { + EmrService withTrino = fixture.withTrino(); + EmrStep query = sparkStep("query", "CONTINUE"); + List args = List.of("trino-cli", "--execute", "SHOW CATALOGS"); + query.setArgs(args); + EmrCluster requested = cluster("trino", true, query); + requested.setApplications(TRINO); + requested.setConfigurations("[{\"Classification\": \"trino-connector-hive\", \"Properties\": " + + "{\"hive.metastore\": \"glue\"}}]"); + withTrino.runJobFlow(requested, REGION); + + fixture.runStepThread(); + + // The image has Hive, as EMR installs hive-client and hcatalog-server with Trino, and the CLI of the Trino the + // release ships, 446 for emr-7.5.0. + assertEquals(List.of(List.of("emr-7.5.0", "public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest", + "public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest", "true", "false")), + fixture.releaseImages.asked); + assertEquals(List.of("trinodb/trino:446"), fixture.releaseImages.trinoImages); + assertEquals(new ClusterStorage.Trino("trinodb/trino:446", 2048, Map.of("hive.metastore", "glue")), + 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); + assertEquals("http://" + host + ":8889", job.environment().get("FLOCI_TRINO_SERVER")); + } + + @Test + void aClusterWithTrinoRunsNoneWhileFlocisTrinoIsOff() { + EmrStep query = sparkStep("query", "CONTINUE"); + query.setArgs(List.of("trino-cli", "--execute", "SHOW CATALOGS")); + EmrCluster requested = cluster("trino", true, query); + requested.setApplications(TRINO); + service.runJobFlow(requested, REGION); + + fixture.runStepThread(); + + assertEquals(List.of(), fixture.releaseImages.asked); + assertEquals(List.of(), fixture.clusterStorage.metastores); + assertFalse(runner.jobs.get(0).environment().containsKey("FLOCI_TRINO_SERVER")); + } + @Test void aStreamingStepRunsItsCommandOnTheClustersStorage() { EmrStep streaming = sparkStep("Streaming program", "CONTINUE"); 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 5b6408d70c..cfdac41200 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrServiceFixture.java +++ b/src/test/java/io/floci/aws/services/emr/EmrServiceFixture.java @@ -256,14 +256,17 @@ final class EmrServiceFixture { static final String IMAGE = "sha256:" + "3".repeat(64); // Each image asked for: its release, then the two it is made of, then whether it has Hive, and Pig. final List> asked = new ArrayList<>(); + // The Trino image each one asked for has the CLI of, null for none, in the same order. + final List trinoImages = new ArrayList<>(); // Each image released, by id. final List released = new ArrayList<>(); RuntimeException failure; @Override public String image(String releaseLabel, String sparkImage, String hiveImage, boolean withHive, - boolean withPig) { + boolean withPig, String trinoImage) { asked.add(List.of(releaseLabel, sparkImage, hiveImage, String.valueOf(withHive), String.valueOf(withPig))); + trinoImages.add(trinoImage); if (failure != null) { throw failure; } @@ -427,6 +430,20 @@ final class EmrServiceFixture { iam); } + /** + * A new service on the same storage and clock, as {@link #restart} builds, with Floci's Trino on at its defaults, + * its steps' threads this fixture's, and its events not delivered. + */ + EmrService withTrino() { + EmulatorConfig config = config(false); + 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); + return new EmrService(storage, config, new RegionResolver(REGION, ACCOUNT), publisher, clock, + mock(EmrService.Wakeups.class), runner, bootstrap, clusterStorage, releaseImages, this::handToThread, + iam); + } + /** A new service on the same storage and clock, as {@link #restart} builds, with this default release label. */ EmrService withDefaultReleaseLabel(String label) { EmulatorConfig config = config(false); diff --git a/src/test/java/io/floci/aws/services/emr/EmrSparkStepsTest.java b/src/test/java/io/floci/aws/services/emr/EmrSparkStepsTest.java index a4c428eadd..5160ff1b17 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrSparkStepsTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrSparkStepsTest.java @@ -232,6 +232,34 @@ class EmrSparkStepsTest { assertFalse(EmrSparkSteps.installsPig("emr-spark-8.1.0", "[{\"Name\": \"Pig\"}]", objectMapper)); } + @Test + void aClusterInstallsTrinoWhereItsApplicationsNameItOnANumberedRelease() { + assertTrue(EmrSparkSteps.installsTrino(RELEASE, "[{\"Name\": \"Trino\"}]", objectMapper)); + assertTrue(EmrSparkSteps.installsTrino(RELEASE, "[{\"Name\": \"Spark\"}, {\"Name\": \"trino\"}]", + objectMapper)); + for (String applications : new String[]{HIVE_AND_SPARK, "[]", null, "[{"}) { + assertFalse(EmrSparkSteps.installsTrino(RELEASE, applications, objectMapper)); + } + // The AWS runtime for Apache Spark's applications are "AmazonCloudWatchAgent, Delta, Hudi, Iceberg, + // JupyterEnterpriseGateway, Livy, and Spark". + assertFalse(EmrSparkSteps.installsTrino("emr-spark-8.1.0", "[{\"Name\": \"Trino\"}]", objectMapper)); + } + + @Test + void trinosHiveCatalogGetsTheClustersTrinoConnectorHiveALaterConfigurationWinning() { + String configurations = """ + [{"Classification": "trino-connector-hive", "Properties": {"hive.metastore": "glue", + "hive.metastore.glue.catalogid": "111122223333"}}, + {"Classification": "hive-site", "Properties": {"hive.metastore.uris": "thrift://elsewhere:9083"}}, + {"Classification": "trino-connector-hive", + "Properties": {"hive.metastore.glue.catalogid": "444455556666"}}] + """; + + assertEquals(Map.of("hive.metastore", "glue", "hive.metastore.glue.catalogid", "444455556666"), + EmrSparkSteps.trinoHiveConnector(configurations, objectMapper)); + assertEquals(Map.of(), EmrSparkSteps.trinoHiveConnector(null, objectMapper)); + } + @Test void aPigCommandRunsOnTezWithTheClustersTezSiteThenItsPigProperties() { String configurations = """ diff --git a/src/test/java/io/floci/aws/services/emr/EmrTrinoNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/emr/EmrTrinoNightlyIntegrationTest.java new file mode 100644 index 0000000000..c3bc1ff7be --- /dev/null +++ b/src/test/java/io/floci/aws/services/emr/EmrTrinoNightlyIntegrationTest.java @@ -0,0 +1,210 @@ +package io.floci.aws.services.emr; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.PullImageResultCallback; +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.CloudFormationSettingsProfile; +import io.floci.aws.testing.DockerAvailability; +import io.floci.aws.testing.EmrRequests; +import io.floci.aws.testing.PartitionCleanup; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.floci.aws.testing.S3TestClients; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import jakarta.inject.Inject; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.api.extension.RegisterExtension; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.glue.GlueClient; +import software.amazon.awssdk.services.glue.model.EntityNotFoundException; +import software.amazon.awssdk.services.glue.model.Table; +import software.amazon.awssdk.services.s3.S3Client; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import static io.floci.aws.testing.EmrRequests.awaitStep; +import static io.floci.aws.testing.EmrRequests.emr; +import static io.floci.aws.testing.EmrRequests.terminateClusterAndAwaitCleanup; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Trino on an EMR cluster through Floci's Docker runner for real, with {@code floci.services.emr.trino.enabled} on: a + * cluster whose {@code Applications} name Trino runs its coordinator on its primary node, and a step runs EMR's + * {@code trino-cli} against it, as the Release Guide's "Connect to the primary node for the Amazon EMR cluster and run + * queries" does, over a CSV in Floci's S3. Its {@code hive} catalog is the cluster's Hive metastore, or, with + * {@code trino-connector-hive} setting {@code hive.metastore} to {@code glue}, Floci's Glue Data Catalog. + * + *

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. + */ +@QuarkusTest +@TestProfile(EmrTrinoNightlyIntegrationTest.TrinoProfile.class) +@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true") +// One instance, so that the image is pulled once for the class. +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class EmrTrinoNightlyIntegrationTest { + + private static final ObjectMapper JSON = new ObjectMapper(); + private static final String TRINO_IMAGE = "trinodb/trino:446"; + private static final String SALES = "1,apple,3\n2,pear,5\n3,apple,7\n"; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @Inject + EmrService emrService; + + @Inject + DockerClient docker; + + private S3Client s3; + private String bucket; + private String clusterId; + + /** The Docker data planes, with Floci's Trino on. */ + public static class TrinoProfile extends CloudFormationSettingsProfile { + @Override + public Map getConfigOverrides() { + Map overrides = new HashMap<>(super.getConfigOverrides()); + overrides.put("floci.services.emr.trino.enabled", "true"); + return overrides; + } + } + + @BeforeAll + static void configure() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + // Trino's image is there before a step's five minutes start, as the step would pull it while the cluster's image + // is made. + @BeforeAll + @Timeout(value = 10, unit = TimeUnit.MINUTES) + void pullImage() throws InterruptedException { + assertTrue(DockerAvailability.isAvailable(), "the nightly check needs a Docker daemon"); + docker.pullImageCmd(TRINO_IMAGE).exec(new PullImageResultCallback()).awaitCompletion(9, TimeUnit.MINUTES); + } + + @BeforeEach + void putSales() { + s3 = AwsTestClients.create(S3Client.builder().forcePathStyle(true), "000000000000", Region.US_EAST_1); + cleanup.register(s3::close); + bucket = "emr-trino-" + UUID.randomUUID().toString().substring(0, 8); + s3.createBucket(request -> request.bucket(bucket)); + cleanup.register(() -> S3TestClients.deleteBucket(s3, bucket)); + s3.putObject(request -> request.bucket(bucket).key("data/sales/sales.csv"), RequestBody.fromString(SALES)); + } + + // The cluster's image made with Trino's CLI, its HDFS and metastore started, then Trino, within the step's five + // minutes, and the cluster's end. + @Test + @Timeout(value = 7, unit = TimeUnit.MINUTES) + void trinoCliQueriesTheClustersMetastoreTablesOnFlocisS3() { + String schema = bucket.replace('-', '_'); + GlueClient glue = AwsTestClients.create(GlueClient.builder(), "000000000000", Region.US_EAST_1); + cleanup.register(glue::close); + startCluster("[]"); + + String step = trinoStep("SHOW CATALOGS; " + tables(schema)); + + assertEquals("COMPLETED", state(step), () -> logs(step)); + String logs = logs(step); + // Its one catalog, as EMR's Trino has the catalogs the cluster configures, and its sums. + assertTrue(logs.contains("\"hive\"\n\"system\"") || logs.contains("\"system\"\n\"hive\""), logs); + assertTrue(logs.contains("\"apple\",\"10\"\n\"pear\",\"5\""), logs); + // The table Trino made, in its schema's folder of Floci's S3. + assertFalse(s3.listObjectsV2(request -> request.bucket(bucket).prefix("warehouse/totals/")).contents() + .isEmpty()); + // The cluster's metastore holds them, not Floci's Glue. + assertThrows(EntityNotFoundException.class, () -> glue.getDatabase(request -> request.name(schema))); + } + + @Test + @Timeout(value = 7, unit = TimeUnit.MINUTES) + void withTrinoConnectorHiveOnGlueTrinoCliQueriesFlocisGlueDataCatalog() { + String schema = bucket.replace('-', '_'); + GlueClient glue = AwsTestClients.create(GlueClient.builder(), "000000000000", Region.US_EAST_1); + cleanup.register(glue::close); + cleanup.register(() -> { + for (Table table : glue.getTables(request -> request.databaseName(schema)).tableList()) { + glue.deleteTable(request -> request.databaseName(schema).name(table.name())); + } + glue.deleteDatabase(request -> request.name(schema)); + }); + // The Release Guide's configuration for Trino on the Glue Data Catalog. + startCluster(""" + [{"Classification": "trino-connector-hive", "Properties": {"hive.metastore": "glue"}}]"""); + + String step = trinoStep(tables(schema)); + + assertEquals("COMPLETED", state(step), () -> logs(step)); + assertTrue(logs(step).contains("\"apple\",\"10\"\n\"pear\",\"5\""), () -> logs(step)); + assertEquals(List.of("sales", "totals"), glue.getTables(request -> request.databaseName(schema)).tableList() + .stream().map(Table::name).sorted().toList()); + } + + // A schema in the bucket's warehouse folder, an external table over the CSV, a table of each item's sum, then the + // sums. + private String tables(String schema) { + return "CREATE SCHEMA hive." + schema + " WITH (location = '" + s3Uri("warehouse/") + "'); " + + "CREATE TABLE hive." + schema + ".sales (id integer, item varchar, qty integer) WITH (format = " + + "'TEXTFILE', textfile_field_separator = ',', external_location = '" + s3Uri("data/sales/") + "'); " + + "CREATE TABLE hive." + schema + ".totals AS SELECT item, sum(qty) AS total FROM hive." + schema + + ".sales GROUP BY item; " + + "SELECT item, total FROM hive." + schema + ".totals ORDER BY item"; + } + + private void startCluster(String configurations) { + ObjectNode request = JSON.createObjectNode().put("Name", "trino").put("ReleaseLabel", "emr-7.5.0") + .put("LogUri", s3Uri("logs/")); + try { + request.set("Applications", JSON.readTree("[{\"Name\":\"Trino\"}]")); + request.set("Configurations", JSON.readTree(configurations)); + } 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") + .put("InstanceCount", 1); + clusterId = emr("RunJobFlow", request.toString()).then().statusCode(200).extract().jsonPath() + .getString("JobFlowId"); + cleanup.register(() -> terminateClusterAndAwaitCleanup(clusterId, emrService)); + } + + // EMR's trino-cli, through command-runner.jar, running the statements given. + private String trinoStep(String statements) { + return EmrRequests.addStep(clusterId, "trino", "command-runner.jar", "trino-cli", "--execute", statements); + } + + private String state(String stepId) { + return awaitStep(clusterId, stepId).jsonPath().getString("Step.Status.State"); + } + + // What a step wrote to its standard output, then its standard error. + private String logs(String stepId) { + String folder = "logs/" + clusterId + "/steps/" + stepId + "/"; + return S3TestClients.gunzipped(s3, bucket, folder + "stdout.gz") + "\n" + + S3TestClients.gunzipped(s3, bucket, folder + "stderr.gz"); + } + + private String s3Uri(String key) { + return "s3://" + bucket + "/" + key; + } +} diff --git a/src/test/java/io/floci/aws/services/emr/EmrTrinoTest.java b/src/test/java/io/floci/aws/services/emr/EmrTrinoTest.java new file mode 100644 index 0000000000..64045009a1 --- /dev/null +++ b/src/test/java/io/floci/aws/services/emr/EmrTrinoTest.java @@ -0,0 +1,143 @@ +package io.floci.aws.services.emr; + +import io.floci.aws.testing.ParallelLocks; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.api.parallel.ResourceAccessMode; +import org.junit.jupiter.api.parallel.ResourceLock; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +// It names Trino's port, localhost:8889, and opens no socket. +@ResourceLock(value = ParallelLocks.PORTS, mode = ResourceAccessMode.READ) +class EmrTrinoTest { + + private static final String ENDPOINT = "http://floci:4566"; + private static final String SERVER = "http://ip-10-0-0-1.ec2.internal:8889"; + + @Test + void theImageIsOfTheTrinoTheReleaseShips() { + assertEquals("trinodb/trino:446", EmrTrino.image("trinodb/trino:%s", "emr-7.5.0")); + assertEquals("trinodb/trino:479", EmrTrino.image("trinodb/trino:%s", "emr-7.14.0")); + // The AWS runtime for Apache Spark ships none, and a release Floci does not list has no version. + assertNull(EmrTrino.image("trinodb/trino:%s", "emr-spark-8.0.0")); + assertNull(EmrTrino.image("trinodb/trino:%s", "emr-9.9.9")); + // An image with no %s serves every release. + assertEquals("registry.internal/trino:446", EmrTrino.image("registry.internal/trino:446", "emr-9.9.9")); + } + + @Test + void theHiveCatalogIsTheClustersMetastoreOnFlocisS3() { + Map catalog = EmrTrino.hiveCatalog(Map.of(), 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, + "s3.region=us-east-1", "s3.path-style-access=true"), + List.of(EmrTrino.properties(catalog).split("\n"))); + } + + @Test + void theHiveCatalogIsFlocisGlueWhenTheClassificationSaysSoItsOwnPropertiesWinning() { + Map classification = new LinkedHashMap<>(); + classification.put("hive.metastore", "glue"); + classification.put("hive.metastore.glue.catalogid", "111122223333"); + classification.put("s3.path-style-access", "false"); + + Map catalog = EmrTrino.hiveCatalog(classification, 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", + "fs.hadoop.enabled=true", "s3.endpoint=" + ENDPOINT, "s3.region=eu-west-1", + "s3.path-style-access=false", "hive.metastore.glue.catalogid=111122223333"), + List.of(EmrTrino.properties(catalog).split("\n"))); + } + + @Test + void theCoordinatorRunsTheQueriesTooOnEmrsPort() { + assertEquals(List.of("coordinator=true", "node-scheduler.include-coordinator=true", + "http-server.http.port=8889", "discovery.uri=http://localhost:8889"), + List.of(EmrTrino.CONFIG.split("\n"))); + } + + @Test + void theEntrypointWritesTheConfigurationTheHiveCatalogAloneAndANodeIdTrinoTakes(@TempDir Path etc) + throws Exception { + Files.createDirectories(etc.resolve("catalog")); + Files.writeString(etc.resolve("catalog/tpch.properties"), "connector.name=tpch\n"); + Files.writeString(etc.resolve("node.properties"), "node.environment=docker\n"); + // The image's /etc/trino here, and its Trino left out. + String entrypoint = EmrTrino.ENTRYPOINT.replace("/etc/trino", etc.toString()) + .replace("exec /usr/lib/trino/bin/run-trino", "true"); + assertTrue(EmrTrino.ENTRYPOINT.endsWith("exec /usr/lib/trino/bin/run-trino")); + ProcessBuilder builder = new ProcessBuilder("bash", "-c", entrypoint).redirectErrorStream(true); + builder.environment().put(EmrTrino.CONFIG_VARIABLE, EmrTrino.CONFIG); + builder.environment().put(EmrTrino.CATALOG_VARIABLE, "connector.name=hive"); + // The primary node's host name, which the container shares. + builder.environment().put("HOSTNAME", "ip-10-0-0-1.ec2.internal"); + Process process = builder.start(); + String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8); + assertTrue(process.waitFor(30, TimeUnit.SECONDS)); + assertEquals(0, process.exitValue(), output); + + assertEquals(EmrTrino.CONFIG + "\n", Files.readString(etc.resolve("config.properties"))); + try (Stream catalogs = Files.list(etc.resolve("catalog"))) { + assertEquals(List.of("hive.properties"), catalogs.map(path -> path.getFileName().toString()).toList()); + } + assertEquals("connector.name=hive\n", Files.readString(etc.resolve("catalog/hive.properties"))); + // Trino takes letters, digits, hyphens and underscores in a node's id, and the image's run-trino names none + // once node.properties does. + assertEquals("node.environment=docker\nnode.id=ip-10-0-0-1-ec2-internal\n", + Files.readString(etc.resolve("node.properties"))); + } + + @Test + void trinoCliReachesTheClustersCoordinatorUnlessTheStepNamesAServer(@TempDir Path folder) throws Exception { + // A java that prints its arguments, one to a line, in place of the image's Java 17. + Path java = folder.resolve("java"); + Files.writeString(java, "#!/bin/sh\nprintf '%s\\n' \"$@\"\n"); + Files.setPosixFilePermissions(java, PosixFilePermissions.fromString("rwxr-xr-x")); + Path command = folder.resolve("trino-cli"); + assertTrue(EmrTrino.COMMAND.contains("/usr/lib/jvm/jre-17/bin/java")); + Files.writeString(command, EmrTrino.COMMAND.replace("/usr/lib/jvm/jre-17/bin/java", java.toString())); + + assertEquals(List.of("-jar", EmrTrino.CLI, "--server", SERVER, "--execute", "SHOW CATALOGS"), + run(command, SERVER, "--execute", "SHOW CATALOGS")); + assertEquals(List.of("-jar", EmrTrino.CLI, "--server", "localhost:8889", "--version"), + run(command, null, "--version")); + assertEquals(List.of("-jar", EmrTrino.CLI, "--server=http://other:8080", "--version"), + run(command, SERVER, "--server=http://other:8080", "--version")); + assertEquals(List.of("-jar", EmrTrino.CLI, "--execute", "SELECT 1", "--server", "http://other:8080"), + run(command, SERVER, "--execute", "SELECT 1", "--server", "http://other:8080")); + } + + // What command passes its java, run with server as its FLOCI_TRINO_SERVER, unless that is null. + private static List run(Path command, String server, String... arguments) + throws IOException, InterruptedException { + List line = new ArrayList<>(List.of("bash", command.toString())); + line.addAll(List.of(arguments)); + ProcessBuilder builder = new ProcessBuilder(line).redirectErrorStream(true); + builder.environment().remove(EmrTrino.SERVER_VARIABLE); + if (server != null) { + builder.environment().put(EmrTrino.SERVER_VARIABLE, server); + } + Process process = builder.start(); + String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8); + assertTrue(process.waitFor(30, TimeUnit.SECONDS)); + assertEquals(0, process.exitValue(), output); + return List.of(output.strip().split("\n")); + } +}