From 7b74d7f797c09a85da335c2d0ef0e2fbecc2918e Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Mon, 30 Nov 2026 13:14:08 -0400 Subject: [PATCH] refactor(emr): run Floci's Trino through a query engine interface (#9848) Floci's Trino machinery, its coordinator beside the metastore, its workers, catalogs, CLI step command, outside host, readiness and password authenticator files, now reads what is Trino's own from an EmrQueryEngine, which EmrTrino implements, so that PrestoDB can be another engine. Nothing a user sees changes: container names, labels, messages, settings and the cluster image's name stay as they were. The variables a Trino container's entrypoint writes its files from are now FLOCI_ENGINE_*. --- .../aws/services/emr/ClusterStorage.java | 92 +-- .../aws/services/emr/EmrClusterStorage.java | 615 ++++++++++-------- .../aws/services/emr/EmrQueryEngine.java | 193 ++++++ .../services/emr/EmrQueryEngineRoutes.java | 115 ++++ .../aws/services/emr/EmrReleaseImages.java | 57 +- .../io/floci/aws/services/emr/EmrService.java | 216 +++--- .../floci/aws/services/emr/EmrSparkSteps.java | 79 ++- .../io/floci/aws/services/emr/EmrTrino.java | 143 ++-- .../aws/services/emr/EmrTrinoRoutes.java | 89 +-- .../floci/aws/services/emr/ReleaseImages.java | 8 +- .../services/emr/EmrClusterStorageTest.java | 51 +- .../services/emr/EmrReleaseImagesTest.java | 7 +- .../emr/EmrServiceContainerStepsTest.java | 39 +- .../aws/services/emr/EmrServiceFixture.java | 4 +- .../aws/services/emr/EmrSparkStepsTest.java | 31 +- .../emr/EmrTrinoHttpsIntegrationTest.java | 6 +- .../aws/services/emr/EmrTrinoRoutesTest.java | 35 +- .../floci/aws/services/emr/EmrTrinoTest.java | 71 +- 18 files changed, 1098 insertions(+), 753 deletions(-) create mode 100644 src/main/java/io/floci/aws/services/emr/EmrQueryEngine.java create mode 100644 src/main/java/io/floci/aws/services/emr/EmrQueryEngineRoutes.java 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 10bbfd64ed..5c7f9edbe0 100644 --- a/src/main/java/io/floci/aws/services/emr/ClusterStorage.java +++ b/src/main/java/io/floci/aws/services/emr/ClusterStorage.java @@ -46,8 +46,8 @@ public interface ClusterStorage { } /** - * Cluster {@code clusterId}'s network, its own, made when missing, with its instance metadata relay running there in - * {@code relayImage}, which the cluster's containers join to read their nodes' metadata at 169.254.169.254; null + * Cluster {@code clusterId}'s network, its own, made when missing, with its instance metadata relay running there + * in {@code relayImage}, which the cluster's containers join to read their nodes' metadata at 169.254.169.254; null * where its steps share a namespace or have no network, or no relay serves the metadata. */ default String metadataNetwork(String clusterId, String accountId, String region, String relayImage, @@ -82,12 +82,11 @@ 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, where Trino's coordinator runs too, in a container of its own on the primary node's network, - * when {@code hiveMetastore} asks for it, and its workers ({@link Trino}). 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, as Trino's own nodes are. 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. + * cluster's own, where its query engine's coordinator runs too, in a container of its own on the primary node's + * network, when {@code hiveMetastore} asks for it, and its workers ({@link QueryEngine}). 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, as the engine's own nodes are. 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, String dockerNetwork, HiveMetastore hiveMetastore, Supplier yarn, @@ -101,12 +100,12 @@ public interface ClusterStorage { void resize(String clusterId, Supplier yarn); /** - * Brings the Trino workers of {@code clusterId}, a cluster whose Trino has nodes of its own - * ({@link Trino#ownNodes}), to its core and task nodes as they are at that moment, when a step has started its - * Trino: a worker on a node that is new starts, and one on a node that is no longer wanted goes, while the rest - * carry on. Clusters no step has started yet get theirs when one does. + * Brings the query engine's workers of {@code clusterId}, a cluster whose engine has nodes of its own + * ({@link QueryEngine#ownNodes}), to its core and task nodes as they are at that moment, when a step has started + * its engine: a worker on a node that is new starts, and one on a node that is no longer wanted goes, while the + * rest carry on. Clusters no step has started yet get theirs when one does. */ - default void resizeTrino(String clusterId) { + default void resizeQueryEngine(String clusterId) { } /** @@ -119,49 +118,50 @@ 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, and {@code trino} beside it unless that is + * {@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, and {@code queryEngine} beside it unless that is * null, as EMR installs {@code hcatalog-server} with Trino; with the cluster's HDFS unless {@code hdfs} is false, - * as on a cluster with Trino alone from emr-7.14.0 ({@link EmrSparkSteps#trinoAlone}), whose primary node runs - * the metastore without it. + * as on a cluster with Trino alone from emr-7.14.0 ({@link EmrSparkSteps#trinoAlone}), whose primary node runs the + * metastore without it. */ - record HiveMetastore(String role, Map settings, Trino trino, boolean hdfs) { + record HiveMetastore(String role, Map settings, QueryEngine queryEngine, boolean hdfs) { /** The metastore alone, beside the cluster's HDFS. */ HiveMetastore(String role, Map settings) { this(role, settings, null, true); } - /** The metastore and {@code trino}, beside the cluster's HDFS. */ - HiveMetastore(String role, Map settings, Trino trino) { - this(role, settings, trino, true); + /** The metastore and {@code queryEngine}, beside the cluster's HDFS. */ + HiveMetastore(String role, Map settings, QueryEngine queryEngine) { + this(role, settings, queryEngine, true); } } /** - * Trino on a cluster: its coordinator on the primary node, and its workers on the core and task nodes, no more than - * {@code maxWorkers} of them, each container getting {@code workerMemoryMb}. The {@code image} they run from, the - * memory the coordinator's container gets, - * the cluster's {@code trino-connector-} properties by catalog, which its catalogs get after Floci's (see - * {@link EmrTrino#catalogs}), its {@code trino-config} properties, which its {@code config.properties} gets after - * Floci's (see {@link EmrTrino#config}), its {@code trino-node} and {@code trino-log} properties, which its - * {@code node.properties} and {@code log.properties} get after its image's own (see {@link EmrTrino#ENTRYPOINT}), - * the variables its {@code trino-env} exports, which its environment gets after Floci's own, its - * {@code trino-exchange-manager} properties, null where it has none, which make its exchange manager (see - * {@link EmrTrino#exchangeManager}), its {@code trino-password-authenticator} properties, which make its password - * authenticator, and the image its bootstrap actions left, null where it has none, from which the files those - * properties name are copied into the coordinator's container ({@link EmrTrino#authenticatorFiles}), as EMR's - * Trino finds what they wrote on the primary node it runs on, and into a worker's from its node's own, else that - * one. Every node reaches S3 and Glue as the metastore does. Its workers run on {@code yarn}'s nodes, sharing each - * node's network, on a cluster that runs YARN, and on {@code ownNodes}, its core and task nodes as they are when - * read, on one with Trino alone from emr-7.14.0, whose nodes run no YARN or HDFS - * ({@link EmrSparkSteps#trinoAlone}): there a worker is all its node runs, in a container of its own on the - * cluster's network at its node's host name. {@code ownNodes} is null on any other cluster. + * A query engine on a cluster, {@code engine}, Trino: its coordinator on the primary node, and its workers on the + * core and task nodes, no more than {@code maxWorkers} of them, each container getting {@code workerMemoryMb}. The + * {@code image} they run from, the memory the coordinator's container gets, the cluster's {@code + * -connector-} properties by catalog, which its catalogs get after Floci's (see {@link + * EmrQueryEngine#catalogs}), its {@code -config} properties, which its {@code config.properties} gets after + * Floci's (see {@link EmrQueryEngine#config}), its {@code -node} and {@code -log} properties, which + * its {@code node.properties} and {@code log.properties} get after its image's own (see {@link + * EmrQueryEngine#entrypoint}), the variables its {@code -env} exports, which its environment gets after + * Floci's own, its {@code trino-exchange-manager} properties, null where it has none, which make its exchange + * manager (see {@link EmrTrino#exchangeManager}), its {@code -password-authenticator} properties, which + * make its password authenticator, and the image its bootstrap actions left, null where it has none, from which the + * files those properties name are copied into the coordinator's container ({@link + * EmrQueryEngine#authenticatorFiles}), as EMR's engine finds what they wrote on the primary node it runs on, and + * into a worker's from its node's own, else that one. Every node reaches S3 and Glue as the metastore does. Its + * workers run on {@code yarn}'s nodes, sharing each node's network, on a cluster that runs YARN, and on {@code + * ownNodes}, its core and task nodes as they are when read, on one with Trino alone from emr-7.14.0, whose nodes + * run no YARN or HDFS ({@link EmrSparkSteps#trinoAlone}): there a worker is all its node runs, in a container of + * its own on the cluster's network at its node's host name. {@code ownNodes} is null on any other cluster. */ - record Trino(String image, int memoryMb, Map> connectors, Map config, - Map node, Map log, Map environment, - Map exchangeManager, Map passwordAuthenticator, - String bootstrapImage, int maxWorkers, int workerMemoryMb, Supplier> ownNodes) { + record QueryEngine(EmrQueryEngine engine, String image, int memoryMb, Map> connectors, + Map config, Map node, Map log, + Map environment, Map exchangeManager, + Map passwordAuthenticator, String bootstrapImage, int maxWorkers, + int workerMemoryMb, Supplier> ownNodes) { /** * The nodes that run its workers: {@code yarn}'s, else its own, read now, else none @@ -248,10 +248,10 @@ public interface ClusterStorage { } /** - * Where Floci reaches {@code port}, its Trino's, on {@code clusterId}'s primary node: empty until that Trino has - * answered queries ({@link #hdfs}), and while it is not running, or where Floci cannot reach it. + * Where Floci reaches {@code port}, its query engine's, on {@code clusterId}'s primary node: empty until that + * engine has answered queries ({@link #hdfs}), and while it is not running, or where Floci cannot reach it. */ - default Optional trinoInterface(String clusterId, int port) { + default Optional queryEngineInterface(String clusterId, int port) { return Optional.empty(); } 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 c86ea6b5da..534de2a990 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrClusterStorage.java +++ b/src/main/java/io/floci/aws/services/emr/EmrClusterStorage.java @@ -66,23 +66,23 @@ import java.util.zip.GZIPOutputStream; /** * Keeps each EMR cluster's storage in Docker volumes, one for its primary node's {@code /home/hadoop} and one for its * {@code /mnt}. Both paths belong to the image's {@code hadoop} user, and Docker gives an empty volume what the image - * has at the path it is first mounted on, owner included, so the steps, which run as that user, can write to both, - * and what the cluster's bootstrap left there comes with them. Its HDFS, which every EMR cluster runs (from - * emr-7.14.0 on, "When you select Trino as the only application at launch, Amazon EMR no longer starts YARN and - * HDFS", which Floci follows), is a NameNode and a DataNode in a container of their own, the cluster's - * primary node's, with their data in a third volume, so that the first container to mount the {@code /mnt} one is a - * step's, which fills it from the step's image. On a cluster with Hive or HCatalog the same container runs Hive's - * metastore service, as EMR's primary node does, with its database in that third volume, reaching S3 with a session - * for the cluster's instance profile's role, which goes with the container. Where it has core nodes, "Core nodes run - * the Data Node daemon" and "a core node runs YARN NodeManager daemons", and "Task nodes don't run the Data Node - * daemon", each is a container of its own on the cluster's network, with its data in a volume of its own. Each node is - * on the network the cluster's steps run on too, the one Floci's other containers are on, MSK's brokers and RDS's - * databases among them, from before it starts, with Floci's DNS, so a cluster-mode driver or an executor on it reaches - * them by the endpoints Floci gives, as a cluster's nodes reach what is in their VPC, and a virtual-hosted bucket name - * under Floci's host name resolves. Their HDFS and YARN listen on their address on the cluster's network alone (see - * BIND_SETUP), so that network's other containers reach neither; Hive 3's metastore has no setting for the address it - * listens on, so the primary node of a cluster with Hive or HCatalog, which runs it, stays off that network, and so does - * every node where Docker does not say the subnet of the cluster's network. + * has at the path it is first mounted on, owner included, so the steps, which run as that user, can write to both, and + * what the cluster's bootstrap left there comes with them. Its HDFS, which every EMR cluster runs (from emr-7.14.0 on, + * "When you select Trino as the only application at launch, Amazon EMR no longer starts YARN and HDFS", which Floci + * follows), is a NameNode and a DataNode in a container of their own, the cluster's primary node's, with their data in + * a third volume, so that the first container to mount the {@code /mnt} one is a step's, which fills it from the step's + * image. On a cluster with Hive or HCatalog the same container runs Hive's metastore service, as EMR's primary node + * does, with its database in that third volume, reaching S3 with a session for the cluster's instance profile's role, + * which goes with the container. Where it has core nodes, "Core nodes run the Data Node daemon" and "a core node runs + * YARN NodeManager daemons", and "Task nodes don't run the Data Node daemon", each is a container of its own on the + * cluster's network, with its data in a volume of its own. Each node is on the network the cluster's steps run on too, + * the one Floci's other containers are on, MSK's brokers and RDS's databases among them, from before it starts, with + * Floci's DNS, so a cluster-mode driver or an executor on it reaches them by the endpoints Floci gives, as a cluster's + * nodes reach what is in their VPC, and a virtual-hosted bucket name under Floci's host name resolves. Their HDFS and + * YARN listen on their address on the cluster's network alone (see BIND_SETUP), so that network's other containers + * reach neither; Hive 3's metastore has no setting for the address it listens on, so the primary node of a cluster with + * Hive or HCatalog, which runs it, stays off that network, and so does every node where Docker does not say the subnet + * of the cluster's network. */ @ApplicationScoped public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { @@ -100,8 +100,8 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { // The address a node's daemons listen on, which its start writes here for what asks them later (see BIND_SETUP). private static final String BIND_FILE = "/tmp/floci-hdfs-bind"; private static final String BIND = "$(cat " + BIND_FILE + ")"; - // The subnet of the cluster's own network, set where its node joins the steps' network too, whose containers then do - // not reach the node's daemons, which listen on its address on the cluster's network alone. + // The subnet of the cluster's own network, set where its node joins the steps' network too, whose containers then + // do not reach the node's daemons, which listen on its address on the cluster's network alone. private static final String SUBNET_VARIABLE = "FLOCI_HDFS_SUBNET"; // The NameNode's JMX on its web port, which says when the DataNode has joined and safe mode has ended without // starting a JVM of hdfs's own each time it is asked; each look is given five seconds, so one the NameNode does not @@ -122,7 +122,8 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { // whose primary node runs YARN. private static final String YARN_MEMORY_VARIABLE = "FLOCI_YARN_MEMORY_MB"; private static final String YARN_VCORES_VARIABLE = "FLOCI_YARN_VCORES"; - // The folder of the image holding the Hadoop the node's daemons run from; set only when that is not the image's own. + // The folder of the image holding the Hadoop the node's daemons run from; set only when that is not the image's + // own. private static final String HADOOP_FOLDER_VARIABLE = "FLOCI_HADOOP_FOLDER"; // A core or task node's container: its host name, and whether it holds a DataNode, as a resize must know them again // after Floci restarts. @@ -200,16 +201,14 @@ 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 saying it has started 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 says it has started, and runs a query with no catalog, before then: - // twice that, from the first time it says so. - private static final Duration TRINO_SETTLE = Duration.ofSeconds(10); - // What a Trino worker's container is named after its node's. - private static final String WORKER_SUFFIX = "-trino"; + // How long a query engine's coordinator has to answer once its container starts: Trino's took 18 s on a laptop, its + // image's catalogs loaded. + private static final Duration ENGINE_START_TIMEOUT = Duration.ofMinutes(3); + // How long a query engine keeps saying it has started 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 says it has started, and runs a query with no catalog, before + // then: twice that, from the first time it says so. + private static final Duration ENGINE_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); @@ -217,8 +216,9 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { private static final Duration DECOMMISSION_POLL = Duration.ofSeconds(3); // A core node that has gone stays in HDFS's exclude list until the NameNode has it dead: taken out while the // NameNode still has it live, it is back in service, the copies of its blocks count again, and the NameNode drops - // one copy of each block now held twice, which may be the remaining node's. The NameNode has a node dead after twice - // its heartbeat recheck interval and ten heartbeats, 2 x 5s + 10 x 3s with NODE_SETUP's setting; this has a margin. + // one copy of each block now held twice, which may be the remaining node's. The NameNode has a node dead after + // twice its heartbeat recheck interval and ten heartbeats, 2 x 5s + 10 x 3s with NODE_SETUP's setting; this has a + // margin. private static final Duration DEAD_NODE_WAIT = Duration.ofSeconds(60); private static final int NODE_COMMAND_SECONDS = 120; // How much of a node's output is logged when it does not become ready, and how long reading it may take. @@ -359,14 +359,14 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { // does. HDFS_READY then says the node is ready, once the metastore takes connections, the NodeManager has // registered, and the JobHistory server and the Spark History Server answer. A daemon that exits, before or after, // the metastore among them, ends the container, its readiness gone, so the next step starts it again on its data. - // With HADOOP_FOLDER_VARIABLE set, every daemon runs from the Hadoop in that folder. With NO_HDFS_VARIABLE set, as on - // a cluster with Trino alone from emr-7.14.0, no NameNode or DataNode runs, and nothing waits for them or puts + // With HADOOP_FOLDER_VARIABLE set, every daemon runs from the Hadoop in that folder. With NO_HDFS_VARIABLE set, as + // on a cluster with Trino alone from emr-7.14.0, no NameNode or DataNode runs, and nothing waits for them or puts // anything in the HDFS: the node is ready once the metastore takes connections. The metastore's warehouse stays in // that HDFS, which Hive 3 starts without, so a schema made without a location of its own fails, "Call From ... - // failed on connection exception" (measured on emr-7.5.0's Hive image). - // Where a node's daemons listen: FLOCI_HDFS_BIND, or, with SUBNET_VARIABLE set, the node's own address in that subnet, - // its cluster's network, alone, so another network it joins does not reach its HDFS or its YARN; written to - // BIND_FILE. Hive 3's metastore has no setting for the address it listens on, so it takes every one. + // failed on connection exception" (measured on emr-7.5.0's Hive image). Where a node's daemons listen: + // FLOCI_HDFS_BIND, or, with SUBNET_VARIABLE set, the node's own address in that subnet, its cluster's network, + // alone, so another network it joins does not reach its HDFS or its YARN; written to BIND_FILE. Hive 3's metastore + // has no setting for the address it listens on, so it takes every one. private static final String BIND_SETUP = String.join("\n", "if [ -n \"${" + SUBNET_VARIABLE + ":-}\" ]; then", " int() { local IFS=.; set -- $1; echo $(( ($1 << 24) + ($2 << 16) + ($3 << 8) + $4 )); }", @@ -572,16 +572,16 @@ 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(); + // The query engine containers this process has started, which a reset or a shutdown removes before the primary + // nodes whose network they share. + private final Set runningEngines = ConcurrentHashMap.newKeySet(); // Those of them that have become ready, coordinators and workers, which a later step finds running and has at once. - private final Set readyTrino = ConcurrentHashMap.newKeySet(); - // For each cluster whose Trino coordinator this process started, what its workers start from. - private final Map trinoClusters = new ConcurrentHashMap<>(); - // What each Trino worker this process started was started from, by container name. + private final Set readyEngines = ConcurrentHashMap.newKeySet(); + // For each cluster whose query engine's coordinator this process started, what its workers start from. + private final Map engineClusters = new ConcurrentHashMap<>(); + // What each query engine worker this process started was started from, by container name. private final Map workerStarts = new ConcurrentHashMap<>(); - // Where each cluster's Trino gets its shared secret from. + // Where each cluster's query engine gets its shared secret from. private final SecureRandom secrets = new SecureRandom(); // What each cluster's last step started its nodes from, which a resize starts new ones from. private final Map nodeRequests = new ConcurrentHashMap<>(); @@ -713,8 +713,8 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { } // The node's container logs whose size is not the one already in S3, as //, but the - // launch scripts: only those are read from Docker, so a step's end does not bring every earlier application's again. - // A primary node whose core nodes run the NodeManagers has no such folder, and so none. + // launch scripts: only those are read from Docker, so a step's end does not bring every earlier application's + // again. A primary node whose core nodes run the NodeManagers has no such folder, and so none. private List changedLogs(String name, Map archived) { ContainerExec.Result listed = ContainerExec.run(lifecycleManager.getDockerClient(), name, new String[]{"bash", "-c", "[ ! -d " + YARN_LOGS + " ] || exec find " + YARN_LOGS @@ -734,8 +734,9 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { return changed; } - // A stopped node answers no command, a decommissioned one among them, whose NodeManager exits once it is, which ends - // its container, but Docker still copies its files: the whole folder, as this is the last look at a node that goes. + // A stopped node answers no command, a decommissioned one among them, whose NodeManager exits once it is, which + // ends its container, but Docker still copies its files: the whole folder, as this is the last look at a node that + // goes. private void archiveStoppedNodeLogs(String name, Map archived, String accountId, String region, S3Uri folder) throws IOException { try (InputStream archive = lifecycleManager.getDockerClient().copyArchiveFromContainerCmd(name, YARN_LOGS) @@ -888,11 +889,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(); + // Its query engine's too, Trino's about 1 GB at its first pull, where it runs: beside the metastore, on a + // network of the cluster's own. + QueryEngine queryEngine = hiveMetastore != null && !shared ? hiveMetastore.queryEngine() : null; + String engineImageId = queryEngine == null ? null : lifecycleManager.resolveImageForLaunch( + containerBuilder.resolveImage(queryEngine.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. @@ -938,10 +939,10 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { awaitNodes(nodeRequest, nodes, deadline, teardown, stopped); nodeRequests.put(clusterId, nodeRequest); } - // After the nodes, whose wait has the HDFS's deadline, as Trino's has its own, its workers on them. - if (trino != null) { - trino(clusterId, accountId, region, containerId, host, trinoImageId, hiveMetastore.role(), trino, - trino.workers(yarn), teardown, stopped); + // After the nodes, whose wait has the HDFS's deadline, as the engine's has its own, its workers on them. + if (queryEngine != null) { + startQueryEngine(clusterId, accountId, region, containerId, host, engineImageId, hiveMetastore.role(), + queryEngine, queryEngine.workers(yarn), teardown, stopped); } SparkJobRunner.Storage storage = volumes(clusterId).withHdfs(host, address(clusterId, containerId), name); if (hiveMetastore != null) { @@ -978,10 +979,11 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { NodeRequest request = known.resizedTo(yarn.get()); nodeRequests.put(clusterId, request); reconcileNodes(request, teardown); - // Trino's workers follow the nodes, where the cluster's Trino runs, and join it as they become ready. - TrinoCluster run = trinoClusters.get(clusterId); - if (run != null && readyTrino.contains(trinoName(clusterId))) { - trinoWorkers(clusterId, run.trino().workers(request.yarn()), teardown); + // The engine's workers follow the nodes, where the cluster's engine runs, and join it as they become + // ready. + EngineCluster run = engineClusters.get(clusterId); + if (run != null && readyEngines.contains(engineName(clusterId, run.queryEngine().engine()))) { + engineWorkers(clusterId, run.queryEngine().workers(request.yarn()), teardown); } } } catch (RuntimeException e) { @@ -990,27 +992,29 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { } @Override - public void resizeTrino(String clusterId) { + public void resizeQueryEngine(String clusterId) { long teardown = teardowns.get(); try { synchronized (starting.computeIfAbsent(clusterId, id -> new Object())) { // Its nodes read here, so of two resizes the one that takes the lock last applies what the cluster says // now; they join the coordinator as they become ready. - TrinoCluster run = trinoClusters.get(clusterId); - if (run != null && run.trino().ownNodes() != null && readyTrino.contains(trinoName(clusterId))) { - trinoWorkers(clusterId, run.trino().workers(null), teardown); + EngineCluster run = engineClusters.get(clusterId); + if (run != null && run.queryEngine().ownNodes() != null + && readyEngines.contains(engineName(clusterId, run.queryEngine().engine()))) { + engineWorkers(clusterId, run.queryEngine().workers(null), teardown); } } } catch (RuntimeException e) { - LOG.warnv(e, "Could not resize the Trino workers of EMR cluster {0}: {1}", clusterId, e.getMessage()); + LOG.warnv(e, "Could not resize the query engine workers of EMR cluster {0}: {1}", clusterId, + e.getMessage()); } } - // A cluster's core and task nodes: one wanted and not running in the image starts, on the data its volume keeps, one - // no longer wanted is decommissioned on a thread of its own, and one being decommissioned that is wanted again - // carries on. A core node found only as its volume, as a shutdown leaves one it cut off while it was decommissioned, - // starts again on its data to be decommissioned, so HDFS moves its blocks; a task node's volume goes, as it holds - // none. The names of those wanted. + // A cluster's core and task nodes: one wanted and not running in the image starts, on the data its volume keeps, + // one no longer wanted is decommissioned on a thread of its own, and one being decommissioned that is wanted again + // carries on. A core node found only as its volume, as a shutdown leaves one it cut off while it was + // decommissioned, starts again on its data to be decommissioned, so HDFS moves its blocks; a task node's volume + // goes, as it holds none. The names of those wanted. private List reconcileNodes(NodeRequest request, long teardown) { String clusterId = request.clusterId(); Map present = nodeContainers(clusterId); @@ -1230,8 +1234,8 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { // A thread's work: each node being decommissioned goes once HDFS and YARN have let it, or the time it was given is // up, and its containers' logs with it. It ends once the last core node to go is dead to the NameNode, or with its - // cluster or a teardown. A round that fails, Docker or a command on the primary node failing, leaves every node as it - // is, and the next asks again. + // cluster or a teardown. A round that fails, Docker or a command on the primary node failing, leaves every node as + // it is, and the next asks again. private void decommission(NodeRequest request, long teardown) { String clusterId = request.clusterId(); boolean ended = false; @@ -1305,9 +1309,9 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { return false; } - // Whether YARN has finished with a node HDFS has finished with, or it has stopped with nothing left for HDFS to move. - // A core node that stopped before HDFS moved its blocks holds them still, so it starts again on its data, and one - // Docker cannot tell the state of is asked about again on the next round. + // Whether YARN has finished with a node HDFS has finished with, or it has stopped with nothing left for HDFS to + // move. A core node that stopped before HDFS moved its blocks holds them still, so it starts again on its data, and + // one Docker cannot tell the state of is asked about again on the next round. private boolean decommissioned(NodeRequest request, String name, Draining node, long teardown) { ContainerLiveness liveness = lifecycleManager.probeContainer(name); if (liveness == ContainerLiveness.UNKNOWN) { @@ -1358,9 +1362,11 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { // Removes a node's container and, when asked, its volume; a removal Docker refuses leaves it known, so the next // reset or shutdown tries again. Whether it has gone. private boolean removeNode(String name, boolean withVolume) { - // Its Trino worker first, which shares its network. - if (!removeTrinoKnown(workerName(name))) { - return false; + // Its query engine's worker first, which shares its network. + for (EmrQueryEngine engine : EmrQueryEngine.all()) { + if (!removeEngineKnown(workerName(name, engine))) { + return false; + } } try { lifecycleManager.removeIfExistsStrict(name); @@ -1521,8 +1527,10 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { 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: the - // Trino on its network before it. - removeTrino(trinoName(clusterId)); + // query engine on its network before it. + for (EmrQueryEngine engine : EmrQueryEngine.all()) { + removeEngine(engineName(clusterId, engine)); + } lifecycleManager.removeIfExistsStrict(name); releaseSession(name); lifecycleManager.ensureVolume(name, labels(clusterId, accountId, region, COMPONENT)); @@ -1555,10 +1563,10 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { spec.withLinkLocalIp(address); } } - if (hiveMetastore != null && hiveMetastore.trino() != null && !shared) { - // Its Trino's port, as Trino's container shares its network, which clients outside the cluster reach - // through Floci (see trinoInterface), as they do its web interfaces. - spec.withLoopbackPortBinding(EmrTrino.port(hiveMetastore.trino().config()), 0); + if (hiveMetastore != null && hiveMetastore.queryEngine() != null && !shared) { + // Its query engine's port, as the engine's container shares its network, which clients outside the cluster + // reach through Floci (see queryEngineInterface), as they do its web interfaces. + spec.withLoopbackPortBinding(EmrQueryEngine.port(hiveMetastore.queryEngine().config()), 0); } if (yarn != null && !shared) { // Its web interfaces, which Floci's application UI links reach, published on the host's loopback interface @@ -1638,83 +1646,87 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { return containerId; } - // Trino's coordinator beside the metastore on cluster clusterId's primary node, the container primary, named host, - // in a container of its own that shares that node's network, as a daemon of the node does, reaching Floci's S3 and - // Glue with a session for role, as the metastore does, and a worker on each of workers, core and task nodes, the - // same way (trinoWorkers): one there is kept when it runs on this primary node with a session of this process's, - // else another starts, with a shared secret of its own, which its workers then share. Until the coordinator and - // each worker have become ready they are waited for, as the step that asks runs trino-cli at once: one an earlier - // step or a resize started too, which has not passed its health check yet. - private void trino(String clusterId, String accountId, String region, String primary, String host, String imageId, - String role, Trino trino, List workers, long teardown, BooleanSupplier stopped) { - String name = trinoName(clusterId); + // The query engine's coordinator beside the metastore on cluster clusterId's primary node, the container primary, + // named host, in a container of its own that shares that node's network, as a daemon of the node does, reaching + // Floci's S3 and Glue with a session for role, as the metastore does, and a worker on each of workers, core and + // task nodes, the same way (engineWorkers): one there is kept when it runs on this primary node with a session of + // this process's, else another starts, with a shared secret of its own, which its workers then share. Until the + // coordinator and each worker have become ready they are waited for, as the step that asks runs the engine's CLI at + // once: one an earlier step or a resize started too, which has not passed its health check yet. + private void startQueryEngine(String clusterId, String accountId, String region, String primary, String host, + String imageId, String role, QueryEngine queryEngine, List workers, + long teardown, BooleanSupplier stopped) { + EmrQueryEngine engine = queryEngine.engine(); + String name = engineName(clusterId, engine); String network = CONTAINER_NETWORK_PREFIX + lifecycleManager.getDockerClient().inspectContainerCmd(primary).exec().getId(); - if (!trinoCurrent(name, network) || !trinoClusters.containsKey(clusterId)) { - removeTrino(name); - TrinoCluster run = new TrinoCluster(accountId, region, host, role, trino, imageId, newSecret()); - trinoClusters.put(clusterId, run); + if (!engineCurrent(name, network) || !engineClusters.containsKey(clusterId)) { + removeEngine(name); + EngineCluster run = new EngineCluster(accountId, region, host, role, queryEngine, imageId, newSecret()); + engineClusters.put(clusterId, run); 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); + runningEngines.add(name); try { - ContainerBuilder.Builder spec = trinoSpec(clusterId, run, name, network, trino.memoryMb(), endpoint, - credentials.orElse(null)) - .withEnv(EmrTrino.CONFIG_VARIABLE, EmrTrino.properties(EmrTrino.config(trino.config(), - !workers.isEmpty(), run.secret()))) - .withEnv(EmrTrino.NODE_VARIABLE, EmrTrino.properties(trino.node())); - EmrTrino.catalogs(trino.connectors(), "localhost", endpoint, region).forEach((catalog, properties) -> - spec.withEnv(EmrTrino.CATALOG_PREFIX + catalog, EmrTrino.properties(properties))); - startTrino(clusterId, run, spec, trino.bootstrapImage(), trino.memoryMb(), - "Trino of EMR cluster " + clusterId, "trino.memory-mb"); + ContainerBuilder.Builder spec = engineSpec(clusterId, run, name, network, queryEngine.memoryMb(), + endpoint, credentials.orElse(null)) + .withEnv(EmrQueryEngine.CONFIG_VARIABLE, EmrQueryEngine.properties(engine.config( + queryEngine.config(), !workers.isEmpty(), run.secret()))) + .withEnv(EmrQueryEngine.NODE_VARIABLE, EmrQueryEngine.properties(queryEngine.node())); + engine.catalogs(queryEngine.connectors(), "localhost", endpoint, region) + .forEach((catalog, properties) -> spec.withEnv(EmrQueryEngine.CATALOG_PREFIX + catalog, + EmrQueryEngine.properties(properties))); + startEngine(clusterId, run, spec, queryEngine.bootstrapImage(), queryEngine.memoryMb(), + engineWho(clusterId, engine), engine.prefix() + ".memory-mb"); } 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); + LOG.infov("Started the {0}", engineWho(clusterId, engine)); } // Started before the coordinator is waited for, so that they start as it does. - trinoWorkers(clusterId, workers, teardown); - if (!readyTrino.contains(name)) { - awaitTrino(clusterId, name, "Trino of EMR cluster " + clusterId, teardown, stopped); - readyTrino.add(name); + engineWorkers(clusterId, workers, teardown); + if (!readyEngines.contains(name)) { + awaitEngine(clusterId, engine, name, engineWho(clusterId, engine), teardown, stopped); + readyEngines.add(name); } - // A query the coordinator is asked before it has learnt of any worker waits for one, as Trino's + // A query the coordinator is asked before it has learnt of any worker waits for one, as the engine's // query-manager.required-workers, 1, has it. for (Node node : workers) { - String worker = workerName(nodeName(clusterId, node)); - if (runningTrino.contains(worker) && !readyTrino.contains(worker)) { - awaitTrino(clusterId, worker, workerWho(clusterId, node.host()), teardown, stopped); - readyTrino.add(worker); + String worker = workerName(nodeName(clusterId, node), engine); + if (runningEngines.contains(worker) && !readyEngines.contains(worker)) { + awaitEngine(clusterId, engine, worker, workerWho(clusterId, node.host(), engine), teardown, stopped); + readyEngines.add(worker); } } } // A worker on each of nodes, cluster clusterId's core and task nodes that run one, in a container of its own that - // shares the node's network, as a daemon of the node does, or, where the cluster's Trino has nodes of its own - // (Trino.ownNodes), whose nodes run nothing else, on the cluster's network at its node's host name, reaching + // shares the node's network, as a daemon of the node does, or, where the cluster's engine has nodes of its own + // (QueryEngine.ownNodes), whose nodes run nothing else, on the cluster's network at its node's host name, reaching // Floci's S3 and Glue with a session for the cluster's role, as the coordinator does: one there is kept when it // runs there now, with the shared secret of the coordinator now running, the files of the image its node has now, // and a session of this process's, else another starts, as one started before its node's own bootstrap ended has // the cluster's files; one on a node no longer among them goes, as its node is decommissioned or leaves. None where // this process runs no coordinator for the cluster. One it starts has yet to become ready. - private void trinoWorkers(String clusterId, List nodes, long teardown) { - TrinoCluster run = trinoClusters.get(clusterId); + private void engineWorkers(String clusterId, List nodes, long teardown) { + EngineCluster run = engineClusters.get(clusterId); if (run == null) { return; } + EmrQueryEngine engine = run.queryEngine().engine(); Set wanted = new HashSet<>(); for (Node node : nodes) { String nodeName = nodeName(clusterId, node); - String name = workerName(nodeName); + String name = workerName(nodeName, engine); wanted.add(name); String network; - if (run.trino().ownNodes() != null) { + if (run.queryEngine().ownNodes() != null) { network = hdfsName(clusterId); } else { try { @@ -1722,52 +1734,53 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { + lifecycleManager.getDockerClient().inspectContainerCmd(nodeName).exec().getId(); } catch (NotFoundException e) { // Its node did not start: it runs no worker either. - LOG.warnv("Node {0} of EMR cluster {1} runs no Trino worker, as its container is not there", - node.host(), clusterId); + LOG.warnv("Node {0} of EMR cluster {1} runs no {2} worker, as its container is not there", + node.host(), clusterId, engine.application()); continue; } } - if (trinoCurrent(name, network) + if (engineCurrent(name, network) && new WorkerStart(run.secret(), workerImage(run, node)).equals(workerStarts.get(name))) { continue; } - removeTrino(name); + removeEngine(name); startWorker(clusterId, run, node, name, network); if (teardowns.get() != teardown) { // A teardown that looked for it before Docker made it has passed it by. - removeTrinoKnown(name); + removeEngineKnown(name); return; } } - for (String name : List.copyOf(runningTrino)) { + for (String name : List.copyOf(runningEngines)) { if (workerOf(clusterId, name) && !wanted.contains(name)) { - removeTrinoKnown(name); + removeEngineKnown(name); } } } - // Cluster clusterId's Trino worker on node, on network, its node's container's, or the cluster's own, where it - // takes its node's host name and instance metadata: as the coordinator, but a worker finding it on the primary - // node, at the address of its node's host, with the memory a worker gets, its catalogs' metastore on the primary - // node, the files its password authenticator names copied from the image its node's own bootstrap actions left, - // else the cluster's. - private void startWorker(String clusterId, TrinoCluster run, Node node, String name, String network) { - Trino trino = run.trino(); + // Cluster clusterId's query engine's worker on node, on network, its node's container's, or the cluster's own, + // where it takes its node's host name and instance metadata: as the coordinator, but a worker finding it on the + // primary node, at the address of its node's host, with the memory a worker gets, its catalogs' metastore on the + // primary node, the files its password authenticator names copied from the image its node's own bootstrap actions + // left, else the cluster's. + private void startWorker(String clusterId, EngineCluster run, Node node, String name, String network) { + QueryEngine queryEngine = run.queryEngine(); + EmrQueryEngine engine = queryEngine.engine(); String endpoint = flociEndpointOn(hdfsName(clusterId)); Optional credentials = roleCredentials.forRole(run.role(), run.accountId(), name); sessions.put(name, new MetastoreSession(run.accountId(), credentials.map(SessionCreds::accessKeyId).orElse(null), endpoint)); // Known before it starts, so a teardown while it starts removes it. - runningTrino.add(name); + runningEngines.add(name); workerStarts.put(name, new WorkerStart(run.secret(), workerImage(run, node))); try { - ContainerBuilder.Builder spec = trinoSpec(clusterId, run, name, network, trino.workerMemoryMb(), endpoint, - credentials.orElse(null)) - .withEnv(EmrTrino.CONFIG_VARIABLE, EmrTrino.properties(EmrTrino.workerConfig(trino.config(), - run.host(), run.secret()))) - .withEnv(EmrTrino.NODE_VARIABLE, EmrTrino.properties(EmrTrino.workerNode(trino.node(), - node.host()))); - if (trino.ownNodes() != null) { + ContainerBuilder.Builder spec = engineSpec(clusterId, run, name, network, queryEngine.workerMemoryMb(), + endpoint, credentials.orElse(null)) + .withEnv(EmrQueryEngine.CONFIG_VARIABLE, EmrQueryEngine.properties(engine.workerConfig( + queryEngine.config(), run.host(), run.secret()))) + .withEnv(EmrQueryEngine.NODE_VARIABLE, EmrQueryEngine.properties(engine.workerNode( + queryEngine.node(), node.host()))); + if (queryEngine.ownNodes() != null) { // Its node's host name, which the coordinator reaches it by on the cluster's network, and its node's // instance metadata, as it is all its node runs. spec.withDnsName(node.host()); @@ -1776,108 +1789,114 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { spec.withLinkLocalIp(address); } } - EmrTrino.catalogs(trino.connectors(), run.host(), endpoint, run.region()).forEach((catalog, properties) -> - spec.withEnv(EmrTrino.CATALOG_PREFIX + catalog, EmrTrino.properties(properties))); - startTrino(clusterId, run, spec, workerImage(run, node), trino.workerMemoryMb(), - workerWho(clusterId, node.host()), "trino.worker-memory-mb"); + engine.catalogs(queryEngine.connectors(), run.host(), endpoint, run.region()) + .forEach((catalog, properties) -> spec.withEnv(EmrQueryEngine.CATALOG_PREFIX + catalog, + EmrQueryEngine.properties(properties))); + startEngine(clusterId, run, spec, workerImage(run, node), queryEngine.workerMemoryMb(), + workerWho(clusterId, node.host(), engine), engine.prefix() + ".worker-memory-mb"); } catch (RuntimeException e) { releaseSession(name); releaseNodeAddress(name); workerStarts.remove(name); throw e; } - LOG.infov("Started the Trino worker of EMR cluster {0} on node {1}", clusterId, node.host()); + LOG.infov("Started the {0}", workerWho(clusterId, node.host(), engine)); } - // A Trino container named so, the coordinator's or a worker's, from the cluster's Trino image in network with - // memoryMb, reaching Floci's S3 and Glue at endpoint with credentials, null where there are none, with what every - // node of the cluster's Trino has: its environment, log properties, exchange manager and password authenticator. - // Its configuration, node properties and catalogs are its own, the caller's to add. - private ContainerBuilder.Builder trinoSpec(String clusterId, TrinoCluster run, String name, String network, - int memoryMb, String endpoint, SessionCreds credentials) { - Trino trino = run.trino(); + // A query engine's container named so, the coordinator's or a worker's, from the cluster's engine image in network + // with memoryMb, reaching Floci's S3 and Glue at endpoint with credentials, null where there are none, with what + // every node of the cluster's engine has: its environment, log properties, exchange manager and password + // authenticator. Its configuration, node properties and catalogs are its own, the caller's to add. + private ContainerBuilder.Builder engineSpec(String clusterId, EngineCluster run, String name, String network, + int memoryMb, String endpoint, SessionCreds credentials) { + QueryEngine queryEngine = run.queryEngine(); + EmrQueryEngine engine = queryEngine.engine(); ContainerBuilder.Builder spec = containerBuilder.newContainer(run.imageId()) .withName(name) .withNetworkMode(network) .withMemoryMb(memoryMb) - .withEntrypoint(List.of("/bin/bash", "-c", EmrTrino.ENTRYPOINT)) + .withEntrypoint(List.of("/bin/bash", "-c", engine.entrypoint())) .withEnv(awsEnv.sdkBaselineEnv(run.region(), Optional.empty(), endpoint, Optional.ofNullable(credentials), run.accountId())) // After Floci's AWS settings, which an export may change as its trino-env.sh would, and before the // files Floci writes, which it may not: Docker keeps the last of a variable given twice. - .withEnv(trino.environment().entrySet().stream() + .withEnv(queryEngine.environment().entrySet().stream() .map(variable -> variable.getKey() + "=" + variable.getValue()).toList()) - .withEnv(EmrTrino.LOG_VARIABLE, EmrTrino.properties(trino.log())) - .withEnv(EmrTrino.PASSWORD_AUTHENTICATOR_VARIABLE, EmrTrino.properties(trino.passwordAuthenticator())) + .withEnv(EmrQueryEngine.LOG_VARIABLE, EmrQueryEngine.properties(queryEngine.log())) + .withEnv(EmrQueryEngine.PASSWORD_AUTHENTICATOR_VARIABLE, + EmrQueryEngine.properties(queryEngine.passwordAuthenticator())) .withJavaTrustStore() .withLogRotation() - .withLabels(labels(clusterId, run.accountId(), run.region(), EmrTrino.COMPONENT)); - if (trino.exchangeManager() != null) { - // The same NameNode on every node, as a worker spools to the files the coordinator names. + .withLabels(labels(clusterId, run.accountId(), run.region(), engine.component())); + if (queryEngine.exchangeManager() != null) { + // Trino's alone, the same NameNode on every node, as a worker spools to the files the coordinator names. String namenode = EmrTrino.namenode(run.host()); - spec.withEnv(EmrTrino.EXCHANGE_VARIABLE, EmrTrino.properties(EmrTrino.exchangeManager( - trino.exchangeManager(), namenode, endpoint, run.region()))) - .withEnv(EmrTrino.EXCHANGE_SITE_VARIABLE, EmrTrino.exchangeSite(namenode)); + spec.withEnv(EmrQueryEngine.EXCHANGE_VARIABLE, EmrQueryEngine.properties(EmrTrino.exchangeManager( + queryEngine.exchangeManager(), namenode, endpoint, run.region()))) + .withEnv(EmrQueryEngine.EXCHANGE_SITE_VARIABLE, EmrTrino.exchangeSite(namenode)); } return spec; } - // Starts a Trino container from spec, the files its password authenticator names copied in first from image, where - // there is one, none larger than memoryMb, the setting named so, lets the container read: who names it, as "Trino - // of EMR cluster j-1". - private void startTrino(String clusterId, TrinoCluster run, ContainerBuilder.Builder spec, String image, - int memoryMb, String who, String setting) { - List files = EmrTrino.authenticatorFiles(run.trino().passwordAuthenticator()); + // Starts a query engine's container from spec, the files its password authenticator names copied in first from + // image, where there is one, none larger than memoryMb, the setting named so, lets the container read: who names + // it, as "Trino of EMR cluster j-1". + private void startEngine(String clusterId, EngineCluster run, ContainerBuilder.Builder spec, String image, + int memoryMb, String who, String setting) { + List files = run.queryEngine().engine().authenticatorFiles(run.queryEngine().passwordAuthenticator()); if (files.isEmpty() || image == null) { lifecycleManager.createAndStart(spec.build()); } else { lifecycleManager.createAndStart(spec.build(), container -> copyAuthenticatorFiles(clusterId, - run.accountId(), run.region(), container, image, files, memoryMb, who, setting)); + run.accountId(), run.region(), run.queryEngine().engine(), container, image, files, memoryMb, who, + setting)); } } - // A new shared secret for a cluster's Trino nodes, as EMR "automatically configures a shared secret key": 32 - // random bytes, in Base64. It is in each Trino container's environment, as the rest of their configuration is. + // A new shared secret for a cluster's query engine nodes, as EMR "automatically configures a shared secret key" for + // Trino: 32 random bytes, in Base64. It is in each engine container's environment, as the rest of their + // configuration is. private String newSecret() { byte[] bytes = new byte[32]; secrets.nextBytes(bytes); return Base64.getEncoder().encodeToString(bytes); } - // The image a Trino worker on node copies its password authenticator's files from: the one its node's own bootstrap - // actions left, else the cluster's, null where there is neither. - private static String workerImage(TrinoCluster run, Node node) { - return node.image() != null ? node.image() : run.trino().bootstrapImage(); + // The image a query engine worker on node copies its password authenticator's files from: the one its node's own + // bootstrap actions left, else the cluster's, null where there is neither. + private static String workerImage(EngineCluster run, Node node) { + return node.image() != null ? node.image() : run.queryEngine().bootstrapImage(); } - // What a Trino worker was started from: the shared secret of its coordinator, and the image its password + // What a query engine worker was started from: the shared secret of its coordinator, and the image its password // authenticator's files came from (workerImage). private record WorkerStart(String secret, String image) { } - // What a cluster's Trino workers start from: the account and Region of the cluster, its primary node's host, the - // role its nodes reach S3 and Glue with, its Trino, the image Trino runs from, and the shared secret of the - // coordinator now running. - private record TrinoCluster(String accountId, String region, String host, String role, Trino trino, + // What a cluster's query engine workers start from: the account and Region of the cluster, its primary node's host, + // the role its nodes reach S3 and Glue with, its engine, the image the engine runs from, and the shared secret of + // the coordinator now running. + private record EngineCluster(String accountId, String region, String host, String role, QueryEngine queryEngine, String imageId, String secret) { } - // The files the cluster's password authenticator names, copied into container, its Trino's, made and not started, - // from image, the one its bootstrap actions left, as EMR's Trino finds what they wrote on the primary node it runs - // on: readable by the user Trino runs as, whoever owned them there. One the image does not hold is left to Trino's - // own image, and Trino says so where neither holds it. Each goes through a temporary file, never held in Floci's - // memory, as the cluster makes it as large as it likes (ContainerFiles.copy), but none larger than the memory - // Trino's container gets (trinoMemoryBytes): Trino reads the password file and the key and trust stores into its - // memory, so a larger one could never serve it, and it is refused before Floci reads any of it, failing Trino's - // start. The image is read in a container made from it and never started, labelled as the cluster's Trino, so that - // a Floci that stops while it copies sweeps it with that Trino. - private void copyAuthenticatorFiles(String clusterId, String accountId, String region, String container, - String image, List files, int memoryMb, String who, String setting) { + // The files the cluster's password authenticator names, copied into container, its engine's, made and not started, + // from image, the one its bootstrap actions left, as EMR's engine finds what they wrote on the primary node it runs + // on: readable by the user the engine runs as, whoever owned them there. One the image does not hold is left to the + // engine's own image, and the engine says so where neither holds it. Each goes through a temporary file, never held + // in Floci's memory, as the cluster makes it as large as it likes (ContainerFiles.copy), but none larger than the + // memory the engine's container gets (engineMemoryBytes): the engine reads the password file and the key and trust + // stores into its memory, so a larger one could never serve it, and it is refused before Floci reads any of it, + // failing the engine's start. The image is read in a container made from it and never started, labelled as the + // cluster's engine, so that a Floci that stops while it copies sweeps it with that engine. + private void copyAuthenticatorFiles(String clusterId, String accountId, String region, EmrQueryEngine engine, + String container, String image, List files, int memoryMb, String who, + String setting) { DockerClient docker = lifecycleManager.getDockerClient(); String source = docker.createContainerCmd(image) - .withLabels(labels(clusterId, accountId, region, EmrTrino.COMPONENT)).exec().getId(); + .withLabels(labels(clusterId, accountId, region, engine.component())).exec().getId(); try { - long maxBytes = trinoMemoryBytes(docker, memoryMb); + long maxBytes = engineMemoryBytes(docker, memoryMb); for (String file : files) { boolean copied; try { @@ -1888,22 +1907,23 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { } if (!copied) { LOG.infov("The image the bootstrap actions of EMR cluster {0} left holds no {1}, which its" - + " password authenticator names: Trino's own image may", clusterId, file); + + " password authenticator names: {2}'s own image may", clusterId, file, + engine.application()); } } } finally { try { docker.removeContainerCmd(source).withForce(true).exec(); } catch (RuntimeException e) { - LOG.warnv("Could not remove container {0}, made to copy the Trino files of EMR cluster {1}: {2}", - source, clusterId, e.getMessage()); + LOG.warnv("Could not remove container {0}, made to copy the {1} files of EMR cluster {2}: {3}", + source, engine.application(), clusterId, e.getMessage()); } } } - // The memory Trino's container gets: memoryMb, or, where that is not positive and its container has no limit, the - // Docker host's, all of which it then has; none where Docker does not say how much that is. - private static long trinoMemoryBytes(DockerClient docker, int memoryMb) { + // The memory an engine's container gets: memoryMb, or, where that is not positive and its container has no limit, + // the Docker host's, all of which it then has; none where Docker does not say how much that is. + private static long engineMemoryBytes(DockerClient docker, int memoryMb) { if (memoryMb > 0) { return memoryMb * 1024L * 1024L; } @@ -1911,9 +1931,9 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { return host != null && host > 0 ? host : 0; } - // 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) { + // Whether the query engine's 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 engineCurrent(String name, String network) { if (!sessions.containsKey(name) || lifecycleManager.probeContainer(name) != ContainerLiveness.RUNNING) { return false; } @@ -1926,46 +1946,47 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { } } - // Removes the Trino container named so, and its session and its node's metadata address, where it has them, a - // removal Docker refuses thrown. - private void removeTrino(String name) { + // Removes the query engine's container named so, and its session and its node's metadata address, where it has + // them, a removal Docker refuses thrown. + private void removeEngine(String name) { lifecycleManager.removeIfExistsStrict(name); releaseSession(name); releaseNodeAddress(name); workerStarts.remove(name); - runningTrino.remove(name); - readyTrino.remove(name); + runningEngines.remove(name); + readyEngines.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) { + // Removes the query engine's 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 removeEngineKnown(String name) { try { - removeTrino(name); + removeEngine(name); return true; } catch (RuntimeException e) { - LOG.warnv(e, "Could not remove the Trino container {0}: {1}", name, e.getMessage()); + LOG.warnv(e, "Could not remove the query engine container {0}: {1}", name, e.getMessage()); return false; } } - // Waits for the Trino container named so, the coordinator's or a worker's, who names it, to have said it has - // started for TRINO_SETTLE, within TRINO_START_TIMEOUT (EmrTrino.READY_CHECK): until the coordinator's node - // manager has learnt that a node serves its catalogs, a query that reads one fails "No nodes available to run - // query", one with none running already. - private void awaitTrino(String clusterId, String name, String who, long teardown, BooleanSupplier stopped) { - long deadline = nanoTime.getAsLong() + TRINO_START_TIMEOUT.toNanos(); + // Waits for engine's container named so, the coordinator's or a worker's, who names it, to have said it has started + // for ENGINE_SETTLE, within ENGINE_START_TIMEOUT (EmrQueryEngine.readyCheck): until the coordinator's node manager + // has learnt that a node serves its catalogs, a query that reads one fails "No nodes available to run query", one + // with none running already. + private void awaitEngine(String clusterId, EmrQueryEngine engine, String name, String who, long teardown, + BooleanSupplier stopped) { + long deadline = nanoTime.getAsLong() + ENGINE_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(who, name); + logEngineOutput(who, name); throw new IllegalStateException("The " + who + " stopped before it was ready"); } ContainerExec.Result check; try { check = ContainerExec.run(lifecycleManager.getDockerClient(), name, - EmrTrino.READY_CHECK.toArray(String[]::new), 30); + engine.readyCheck().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. @@ -1980,13 +2001,13 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { } else if (answering == Long.MIN_VALUE) { answering = now; } - if (answering != Long.MIN_VALUE && now - answering >= TRINO_SETTLE.toNanos()) { + if (answering != Long.MIN_VALUE && now - answering >= ENGINE_SETTLE.toNanos()) { return; } if (now >= deadline) { - logTrinoOutput(who, name); + logEngineOutput(who, name); throw new IllegalStateException("The " + who + " did not start within " - + TRINO_START_TIMEOUT.toSeconds() + " seconds"); + + ENGINE_START_TIMEOUT.toSeconds() + " seconds"); } try { Thread.sleep(HDFS_POLL_INTERVAL.toMillis()); @@ -1998,37 +2019,52 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { stopIfStopped(clusterId, teardown, stopped); } - // What a Trino that did not become ready, who names it, last wrote, in Floci's log, as its container goes with its - // cluster. - private void logTrinoOutput(String who, String name) { + // What an engine that did not become ready, who names it, last wrote, in Floci's log, as its container goes with + // its cluster. + private void logEngineOutput(String who, String name) { LOG.warnv("The {0} did not become ready. It last wrote:\n{1}", who, lifecycleManager.lastLogLines(name, NODE_LOG_LINES, NODE_LOG_READ)); } - private String trinoName(String clusterId) { - return ContainerStorageHelper.dockerName(config, SERVICE + "-" + clusterId + "-trino"); + // Removes cluster clusterId's coordinator of each engine, as removeEngineKnown does. Whether they are gone. + private boolean removeEnginesKnown(String clusterId) { + boolean gone = true; + for (EmrQueryEngine engine : EmrQueryEngine.all()) { + gone &= removeEngineKnown(engineName(clusterId, engine)); + } + return gone; } - // The container of the Trino worker on the core or task node whose container is named nodeName. - private static String workerName(String nodeName) { - return nodeName + WORKER_SUFFIX; + // The container of cluster clusterId's coordinator of engine. + private String engineName(String clusterId, EmrQueryEngine engine) { + return ContainerStorageHelper.dockerName(config, SERVICE + "-" + clusterId + "-" + engine.prefix()); } - // Whether the container named so is one of cluster clusterId's Trino workers. + // The container of engine's worker on the core or task node whose container is named nodeName. + private static String workerName(String nodeName, EmrQueryEngine engine) { + return nodeName + "-" + engine.prefix(); + } + + // Whether the container named so is one of cluster clusterId's query engine's workers. private boolean workerOf(String clusterId, String name) { return name.startsWith(ContainerStorageHelper.dockerName(config, SERVICE + "-" + clusterId + "-node-")) - && name.endsWith(WORKER_SUFFIX); + && EmrQueryEngine.all().stream().anyMatch(engine -> name.endsWith("-" + engine.prefix())); } - // What names the Trino worker on the node named host in messages. - private static String workerWho(String clusterId, String host) { - return "Trino worker on node " + host + " of EMR cluster " + clusterId; + // What names cluster clusterId's coordinator of engine in messages, as "Trino of EMR cluster j-1". + private static String engineWho(String clusterId, EmrQueryEngine engine) { + return engine.application() + " of EMR cluster " + clusterId; } - // The subnet of a cluster's own network, which exists, as Docker says it: where it is known, the cluster's nodes join - // the steps' network too, their HDFS and YARN listening on their address in that subnet alone (see BIND_SETUP), so - // the steps' network's containers, other clusters' among them, reach neither; where it is not, they stay on their - // cluster's network alone, as is logged. Kept once read, for the network keeps it. + // What names engine's worker on the node named host in messages. + private static String workerWho(String clusterId, String host, EmrQueryEngine engine) { + return engine.application() + " worker on node " + host + " of EMR cluster " + clusterId; + } + + // The subnet of a cluster's own network, which exists, as Docker says it: where it is known, the cluster's nodes + // join the steps' network too, their HDFS and YARN listening on their address in that subnet alone (see + // BIND_SETUP), so the steps' network's containers, other clusters' among them, reach neither; where it is not, they + // stay on their cluster's network alone, as is logged. Kept once read, for the network keeps it. private String clusterSubnet(String clusterId) { String known = subnets.get(clusterId); if (known != null) { @@ -2143,19 +2179,25 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { } /** - * Where Floci reaches the cluster's Trino on {@code port}, once it has answered queries and while it runs: at the - * port its primary node's container publishes for it, as for the node's web interfaces ({@link #webInterface}). + * Where Floci reaches the cluster's query engine on {@code port}, once it has answered queries and while it runs: + * at the port its primary node's container publishes for it, as for the node's web interfaces + * ({@link #webInterface}). */ @Override - public Optional trinoInterface(String clusterId, int port) { - String name = trinoName(clusterId); + public Optional queryEngineInterface(String clusterId, int port) { + EngineCluster run = engineClusters.get(clusterId); + if (run == null) { + return Optional.empty(); + } + String name = engineName(clusterId, run.queryEngine().engine()); try { - if (!readyTrino.contains(name) || lifecycleManager.probeContainer(name) != ContainerLiveness.RUNNING) { + if (!readyEngines.contains(name) || lifecycleManager.probeContainer(name) != ContainerLiveness.RUNNING) { return Optional.empty(); } } catch (RuntimeException e) { // Docker did not answer: as for a node not running, the client is told to try again. - LOG.debugv(e, "The Trino of EMR cluster {0} could not be looked at: {1}", clusterId, e.getMessage()); + LOG.debugv(e, "The query engine of EMR cluster {0} could not be looked at: {1}", clusterId, + e.getMessage()); return Optional.empty(); } return webInterface(clusterId, port); @@ -2414,8 +2456,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)); + // Its query engine first, which shares the HDFS container's network. + removeEnginesKnown(clusterId); removeKnown(hdfsName(clusterId)); throw new ClusterStorage.Stopped("Floci stopped the HDFS of EMR cluster " + clusterId); } @@ -2460,13 +2502,13 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { nodeRequests.remove(clusterId); draining.remove(clusterId); departed.remove(clusterId); - trinoClusters.remove(clusterId); - // Its Trino workers first, which share their nodes' networks or are on the cluster's, those this process knows - // even where Docker lists no node, then any that goes with its node. + engineClusters.remove(clusterId); + // Its query engine's workers first, which share their nodes' networks or are on the cluster's, those this + // process knows even where Docker lists no node, then any that goes with its node. boolean nodesGone = true; - for (String name : List.copyOf(runningTrino)) { + for (String name : List.copyOf(runningEngines)) { if (workerOf(clusterId, name)) { - nodesGone &= removeTrinoKnown(name); + nodesGone &= removeEngineKnown(name); } } try { @@ -2482,9 +2524,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; } - // Its Trino before its primary node, whose network it shares. - boolean trinoGone = removeTrinoKnown(trinoName(clusterId)); - boolean containerGone = trinoGone && removeKnown(hdfsName(clusterId)); + // Its query engine before its primary node, whose network it shares. + boolean engineGone = removeEnginesKnown(clusterId); + boolean containerGone = engineGone && 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); @@ -2496,7 +2538,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 && trinoGone && nodesGone && relayGone; + && containerGone && engineGone && nodesGone && relayGone; } /** @@ -2511,13 +2553,13 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { nodeRequests.clear(); draining.clear(); departed.clear(); - trinoClusters.clear(); - // Each node with its Trino worker, which shares its network. + engineClusters.clear(); + // Each node with its query engine's worker, which shares its network. for (String name : List.copyOf(runningNodes)) { removeNode(name, false); } - for (String name : List.copyOf(runningTrino)) { - removeTrinoKnown(name); + for (String name : List.copyOf(runningEngines)) { + removeEngineKnown(name); } for (String name : List.copyOf(running)) { // What its history interfaces show goes into its kept history first, as nothing reads its HDFS after. @@ -2564,20 +2606,23 @@ 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. 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); + // Each sweep on its own, so Docker refusing one list does not keep the others from going. The query engine 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. + for (EmrQueryEngine engine : EmrQueryEngine.all()) { + try { + for (Container container : lifecycleManager.getDockerClient().listContainersCmd().withShowAll(true) + .withLabelFilter(Map.of(ContainerStorageHelper.COMPONENT_LABEL, engine.component(), + ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config))) + .exec()) { + String name = container.getNames()[0].substring(1); + runningEngines.add(name); + removeEngineKnown(name); + } + } catch (RuntimeException e) { + LOG.warnv(e, "Could not remove the {0} an earlier Floci left: {1}", engine.application(), + e.getMessage()); } - } 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) @@ -2617,8 +2662,8 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { } catch (RuntimeException e) { LOG.warnv(e, "Could not remove the HDFS of EMR clusters that have ended: {0}", e.getMessage()); } - // The instance metadata relays an earlier process left, whose networks they would keep: the next bootstrap or step - // of a cluster still up starts another. + // The instance metadata relays an earlier process left, whose networks they would keep: the next bootstrap or + // step of a cluster still up starts another. try { for (Container container : lifecycleManager.getDockerClient().listContainersCmd().withShowAll(true) .withLabelFilter(Map.of(ContainerStorageHelper.COMPONENT_LABEL, EmrMetadataRelays.COMPONENT, diff --git a/src/main/java/io/floci/aws/services/emr/EmrQueryEngine.java b/src/main/java/io/floci/aws/services/emr/EmrQueryEngine.java new file mode 100644 index 0000000000..870806cdaa --- /dev/null +++ b/src/main/java/io/floci/aws/services/emr/EmrQueryEngine.java @@ -0,0 +1,193 @@ +package io.floci.aws.services.emr; + +import java.net.URI; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +/** + * A SQL query engine of the Presto line that Floci runs on a {@code docker} cluster whose {@code Applications} name it, + * with its setting on: Trino ({@link EmrTrino}). No AWS image carries one, so its coordinator runs on the primary node + * from its 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, beside the cluster's Hive metastore, and a worker the same way on each of the core + * and task nodes Floci runs, up to its setting. Its steps run its CLI, and clients outside the cluster reach it through + * Floci on a host of the cluster's own. What one engine does otherwise than another is here; a container's entrypoint + * writes the engine's files from the variables below, which every engine shares. + */ +interface EmrQueryEngine { + + /** + * The port the coordinator listens on, on the primary node, unless the cluster's {@code -config} names + * another: "By default, Amazon EMR configures the Presto web interface on the Presto coordinator to use port 8889 + * (for PrestoDB and Trino)". + */ + int PORT = 8889; + /** + * A catalog's name as Floci takes it: the engine's own, letters, digits and underscores, which the entrypoint + * passes as the name of a shell variable. + */ + Pattern CATALOG_NAME = Pattern.compile("[a-z][a-z0-9_]*"); + /** The variables an engine's container's entrypoint writes its configuration, node and log properties from. */ + String CONFIG_VARIABLE = "FLOCI_ENGINE_CONFIG"; + String NODE_VARIABLE = "FLOCI_ENGINE_NODE"; + String LOG_VARIABLE = "FLOCI_ENGINE_LOG"; + /** The variables it writes its exchange manager and that manager's Hadoop configuration from, where it has one. */ + String EXCHANGE_VARIABLE = "FLOCI_ENGINE_EXCHANGE"; + String EXCHANGE_SITE_VARIABLE = "FLOCI_ENGINE_EXCHANGE_SITE"; + /** The variable it writes its password authenticator from. */ + String PASSWORD_AUTHENTICATOR_VARIABLE = "FLOCI_ENGINE_PASSWORD_AUTHENTICATOR"; + /** The prefix of the variables it writes its catalogs from, one each, the rest of whose name names it. */ + String CATALOG_PREFIX = "FLOCI_ENGINE_CATALOG_"; + /** The folder of the cluster's image that holds EMR's command for the engine's CLI ({@link #commandName}). */ + String COMMAND_FOLDER = "/usr/bin"; + + /** The application's name, as the Release Guide's list of applications spells it, such as {@code Trino}. */ + String application(); + + /** + * What the names of the engine's classifications start with, such as {@code trino}: {@code -config} changes + * its {@code config.properties} and {@code -connector-} a catalog's properties. + */ + String prefix(); + + /** + * The component label of the engine's containers on a cluster, which go with its nodes, and the last part of their + * names, such as {@code emr-trino}. + */ + String component(); + + /** + * The label under Floci's host name of the hosts clients outside the cluster reach the engine at, one per cluster + * ({@link #address}). + */ + String hostLabel(); + + /** + * Whether the engine has an exchange manager, which the cluster's {@code -exchange-manager} makes, for its + * fault-tolerant execution: Trino's ({@link EmrTrino#exchangeManager}). + */ + boolean exchanges(); + + /** The variable a step's CLI command reads the coordinator's address from. */ + String serverVariable(); + + /** + * An engine's container's entrypoint, the coordinator's or a worker's, which writes the engine's files from the + * variables this interface names, then starts the engine as its image does. + */ + String entrypoint(); + + /** + * What tells the engine's container is ready, a command run in it that takes no credentials, as a query would need + * those of an engine that takes passwords, which Floci does not have. + */ + List readyCheck(); + + /** The engine's CLI in its image, an executable jar, which the cluster's image takes. */ + String imageCli(); + + /** Where the cluster's image keeps that jar. */ + String cli(); + + /** The name of EMR's command for the CLI, in {@link #COMMAND_FOLDER} of the cluster's image. */ + String commandName(); + + /** That command: the CLI to the cluster's coordinator, unless the step names a server of its own. */ + String command(); + + /** + * The coordinator's {@code config.properties}: a coordinator that runs the queries too only where the cluster has + * no workers, on the cluster's {@link #port}, the cluster's {@code secret} for its nodes, and the cluster's + * {@code -config} after Floci's. + */ + Map config(Map classification, boolean withWorkers, String secret); + + /** + * A worker's {@code config.properties}: no coordinator, finding it on the primary node named {@code primaryHost} at + * the cluster's {@link #port}, the cluster's {@code secret}, and the cluster's {@code -config} after these. + */ + Map workerConfig(Map classification, String primaryHost, String secret); + + /** + * A worker's {@code node.properties} additions: the address the other nodes reach it at, its node's {@code host}, + * then the cluster's {@code -node}, but the node's id, which must be every node's own. + */ + Map workerNode(Map classification, String host); + + /** + * The engine's catalogs, by name, for {@code connectors}, the cluster's {@code -connector-} + * classifications' properties by catalog: their metastore on the primary node, at {@code metastoreHost}, and + * Floci's S3 and Glue at {@code endpoint} in {@code region}. + */ + Map> catalogs(Map> connectors, String metastoreHost, + String endpoint, String region); + + /** + * The files a cluster's {@code -password-authenticator} properties name, each once, in their order: those + * whose path is absolute, as the engine's container has no folder of the cluster's own a relative one would be in. + */ + List authenticatorFiles(Map passwordAuthenticator); + + /** + * The image the engine runs from for a release: {@code template} with the release's version of the engine 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 engine. + */ + default 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 clients outside the cluster reach its engine at, through Floci at {@code baseUrl}: a host of the + * cluster's own under {@link #hostLabel}, as EMR's clients reach the primary node's. + */ + default String address(String baseUrl, String clusterId) { + URI base = URI.create(baseUrl); + return base.getScheme() + "://" + clusterId.toLowerCase(Locale.ROOT) + "." + hostLabel() + "." + + base.getRawAuthority(); + } + + /** Every engine Floci runs. */ + static List all() { + return List.of(EmrTrino.ENGINE); + } + + /** + * The port the engine listens on: the {@code http-server.http.port} of the cluster's {@code -config}, or + * EMR's. + */ + static int port(Map config) { + String port = config.get("http-server.http.port"); + if (port != null) { + try { + return Integer.parseInt(port.trim()); + } catch (NumberFormatException ignored) { + // The engine refuses it as it starts, and says so in its log. + } + } + return PORT; + } + + /** The address a step's CLI reaches the coordinator at, on the primary node named {@code host}. */ + static String server(String host, int port) { + return "http://" + host + ":" + port; + } + + /** {@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/EmrQueryEngineRoutes.java b/src/main/java/io/floci/aws/services/emr/EmrQueryEngineRoutes.java new file mode 100644 index 0000000000..8b4158ca3b --- /dev/null +++ b/src/main/java/io/floci/aws/services/emr/EmrQueryEngineRoutes.java @@ -0,0 +1,115 @@ +package io.floci.aws.services.emr; + +import io.floci.aws.core.common.AppUiRoute; +import io.floci.aws.core.common.AppUiRoutes; +import io.floci.aws.core.common.RequestScopes; +import io.floci.aws.core.common.docker.ContainerLifecycleManager; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.regex.Pattern; + +/** + * A cluster's query engine as clients outside the cluster reach it, through Floci, on a host of the cluster's own, + * {@code ..} ({@link EmrQueryEngine#address}), as EMR's + * clients reach the engine on the primary node: no AWS API gives an address for it. The host asks for no credentials + * of its own: the cluster's engine asks for those its {@code -config} and + * {@code -password-authenticator} configure, and where they configure none, whoever reaches Floci's port + * reaches the cluster's engine. The engine names a query's next pages by the host it was asked on, which the request + * keeps, and by the scheme it was reached over, which goes on as {@code X-Forwarded-Proto}. A cluster whose engine is + * not running yet has its primary node started, as an application UI link does, and the request answered with a + * {@code 503}, which the engine's clients try again on. One of these serves each engine, for the bean of its routes + * ({@link EmrTrinoRoutes}). + */ +final class EmrQueryEngineRoutes implements AppUiRoutes { + + // No source gives these, as no AWS API serves the engines; they are Floci's: the cluster's id, then the engine's + // name. + static final String NO_SUCH_CLUSTER = "No EMR cluster %s runs Floci's %s."; + static final String CLUSTER_ENDED = "EMR cluster %s is no longer running, and its %s is there only while it is" + + " RUNNING or WAITING."; + static final String NOT_READY = "The %2$s of EMR cluster %1$s is starting. Try again in a moment."; + // How long a port found for a cluster's engine is used before it is asked for again, as for the application UIs. + private static final Duration ENDPOINT_RECHECK = Duration.ofSeconds(10); + // A cluster's id, as a host name holds it, without case. + private static final Pattern CLUSTER_ID = Pattern.compile("j-[a-z0-9]+"); + + private final EmrQueryEngine engine; + private final EmrService clusters; + private final Clock clock; + // Where Floci found each cluster's engine, and when, by account and cluster. + private final Map endpoints = new ConcurrentHashMap<>(); + + EmrQueryEngineRoutes(EmrQueryEngine engine, EmrService clusters, Clock clock) { + this.engine = engine; + this.clusters = clusters; + this.clock = clock; + } + + private record Found(ContainerLifecycleManager.EndpointInfo endpoint, Instant at) { + } + + @Override + public String hostLabel() { + return engine.hostLabel(); + } + + @Override + public String service() { + return "emr"; + } + + /** + * The route of a request whose {@code Host} is {@code hostHeader}, over {@code scheme}: to the engine of the + * cluster the host names, once it answers queries; null where the host is not one of a cluster's engine. + */ + @Override + public AppUiRoute route(String hostHeader, String scheme) { + String host = hostHeader.toLowerCase(Locale.ROOT); + int dot = host.indexOf('.'); + if (dot <= 0 || !host.startsWith(engine.hostLabel() + ".", dot + 1) + || !CLUSTER_ID.matcher(host.substring(0, dot)).matches()) { + return null; + } + // A cluster's id is j- and capitals and digits, which the host holds in lower case. + String clusterId = "j-" + host.substring(2, dot).toUpperCase(Locale.ROOT); + EmrService.QueryEngineCluster cluster = clusters.queryEngineCluster(clusterId) + .filter(found -> found.engine() == engine).orElse(null); + String name = engine.application(); + if (cluster == null) { + return AppUiRoute.refused(404, String.format(NO_SUCH_CLUSTER, clusterId, name)); + } + String key = cluster.accountId() + "/" + cluster.clusterId(); + if (!EmrClusterLifecycle.RUNNING.equals(cluster.state()) + && !EmrClusterLifecycle.WAITING.equals(cluster.state())) { + endpoints.remove(key); + return EmrClusterLifecycle.isTerminated(cluster.state()) + || EmrClusterLifecycle.TERMINATING.equals(cluster.state()) + ? AppUiRoute.refused(404, String.format(CLUSTER_ENDED, cluster.clusterId(), name)) + : AppUiRoute.refused(503, String.format(NOT_READY, cluster.clusterId(), name)); + } + Instant now = clock.instant(); + Found found = endpoints.get(key); + if (found == null || !now.isBefore(found.at().plus(ENDPOINT_RECHECK))) { + ContainerLifecycleManager.EndpointInfo endpoint = RequestScopes.callAs(cluster.accountId(), + cluster.region(), () -> clusters.queryEngineInterface(cluster.clusterId(), cluster.port())) + .orElse(null); + if (endpoint == null) { + endpoints.remove(key); + RequestScopes.runAs(cluster.accountId(), cluster.region(), + () -> clusters.startPrimaryNode(cluster.clusterId())); + return AppUiRoute.refused(503, String.format(NOT_READY, cluster.clusterId(), name)); + } + found = new Found(endpoint, now); + endpoints.put(key, found); + } + Found routed = found; + return new AppUiRoute(found.endpoint().host(), found.endpoint().port(), Map.of(), + () -> endpoints.remove(key, routed), 0, null, 503, String.format(NOT_READY, cluster.clusterId(), name)) + .withHeaders(Map.of("X-Forwarded-Proto", scheme)); + } +} 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 c0238fa2f0..08a656ef5f 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrReleaseImages.java +++ b/src/main/java/io/floci/aws/services/emr/EmrReleaseImages.java @@ -49,8 +49,8 @@ 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. 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}), + * whose checksum its name holds. For a cluster with Floci's query engine, it gets the engine's CLI from the image + * the cluster's coordinator runs, never started either, and EMR's command for it ({@link EmrQueryEngine#command}), * and its name holds that image's id. */ @ApplicationScoped @@ -65,8 +65,8 @@ public class EmrReleaseImages implements ReleaseImages { private static final String EMR_SHARE = "/usr/share/aws/emr"; private static final String GOODIES = EMR_SHARE + "/serverless-goodies/lib"; private static final String HIVE_GOODIES = "serverless-goodies-hive/lib"; - // What the Hive image adds for a cluster without Hive: the Hadoop services the EMR Serverless image lacks, which its - // own Hadoop's client links name. + // What the Hive image adds for a cluster without Hive: the Hadoop services the EMR Serverless image lacks, which + // its own Hadoop's client links name. static final List HADOOP_COPIES = List.of( new Copy("/usr/lib/hadoop-hdfs", "/usr/lib"), new Copy("/usr/lib/hadoop-mapreduce", "/usr/lib"), @@ -96,9 +96,6 @@ 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( @@ -145,33 +142,37 @@ public class EmrReleaseImages implements ReleaseImages { */ @Override public String image(String releaseLabel, String sparkImage, String hiveImage, boolean withHive, - boolean withPig, String trinoImage) { + boolean withPig, EmrQueryEngine queryEngine, String engineImage) { List copies = copies(releaseLabel, withHive, withPig); PigDistribution pig = withPig && hadoopFolder(releaseLabel) == null ? pigDistribution : null; - 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 engine = engineImage != null ? containerBuilder.resolveImage(engineImage) : null; + Copy cli = engine != null ? engineCli(queryEngine) : null; + // What is copied, the Pig written after it, by its checksum, and the engine's CLI with its command. String content = copies + (pig != null ? "\n" + pig.identity() : "") - + (trino != null ? "\n" + TRINO_CLI + "\n" + EmrTrino.COMMAND : ""); + + (engine != null ? "\n" + cli + "\n" + queryEngine.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 - + (trino != null ? "\n" + trino : "")).substring(0, 12); + + (engine != null ? "\n" + engine : "")).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 trinoId = trino != null - ? imageCacheService.resolveForLaunch(trino, ImagePullBehavior.PREFER_CACHED, null).imageId() : null; + String engineId = engine != null + ? imageCacheService.resolveForLaunch(engine, ImagePullBehavior.PREFER_CACHED, null).imageId() + : null; String tag = releaseLabel + "-" + Digests.sha256Hex(sparkId + "\n" + hiveId + "\n" + content - + (trinoId != null ? "\n" + trinoId : "")).substring(0, 12); + + (engineId != null ? "\n" + engineId : "")).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" : "") - + (trino != null ? ", with Trino's CLI from " + trino : ""), spark, hive); + + (engine != null ? ", with " + queryEngine.application() + "'s CLI from " + engine + : ""), + spark, hive); } String user = docker.inspectImageCmd(sparkId).exec().getConfig().getUser(); Map labels = new LinkedHashMap<>(); @@ -203,14 +204,14 @@ 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); + if (engineId != null) { + String cliSource = docker.createContainerCmd(engineId).withLabels(labels).exec().getId(); + containers.add(cliSource); + RetryingTarCopier.copyStreamed(docker, target, cli.into(), cli.from(), + out -> copy(docker.copyArchiveFromContainerCmd(cliSource, cli.from()).exec(), out, + cli)); + RetryingTarCopier.copyBytes(docker, target, EmrQueryEngine.COMMAND_FOLDER, + queryEngine.commandName(), queryEngine.command().getBytes(StandardCharsets.UTF_8), 0755); } made = lifecycleManager.commit(target, repository, tag, user == null || user.isBlank() ? "root" : user, labels); @@ -239,6 +240,14 @@ public class EmrReleaseImages implements ReleaseImages { // Another release's Hadoop for an emr-spark-* release, which has neither Hive nor Pig; Hive, Tez and those Hadoop // services for a cluster with Hive; Tez and those services for one with Pig alone; those services alone otherwise. + /** + * What a cluster with Floci's {@code engine} adds, from the engine's image: its CLI, for EMR's command for it + * ({@link EmrQueryEngine#command}). + */ + static Copy engineCli(EmrQueryEngine engine) { + return new Copy(engine.imageCli(), "/usr/lib", engine.cli().substring("/usr/lib/".length())); + } + static List copies(String releaseLabel, boolean withHive, boolean withPig) { if (hadoopFolder(releaseLabel) != null) { return HADOOP_APART_COPIES; 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 fc24f41a93..611f35b7b0 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrService.java +++ b/src/main/java/io/floci/aws/services/emr/EmrService.java @@ -202,13 +202,9 @@ 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, with how much memory for its coordinator, and how many workers with how much. - private final boolean trinoEnabled; - private final String trinoImageTemplate; - private final int trinoMemoryMb; - private final int trinoMaxWorkers; - private final int trinoWorkerMemoryMb; + // The query engines a cluster whose Applications name one runs, by engine, each with its settings: Trino where + // floci.services.emr.trino.enabled runs it. + private final Map engineSettings; // What the NodeManager of a cluster that runs YARN offers its containers. private final ClusterStorage.Yarn nodeManager; private final int maxWorkerNodes; @@ -391,11 +387,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.trinoMaxWorkers = trinoEnabled ? config.services().emr().trino().maxWorkers() : 0; - this.trinoWorkerMemoryMb = trinoEnabled ? config.services().emr().trino().workerMemoryMb() : 0; + EmulatorConfig.EmrTrinoConfig trino = config.services().emr().trino(); + this.engineSettings = trino.enabled() ? Map.of(EmrTrino.ENGINE, new EngineSettings(trino.image(), + trino.memoryMb(), trino.maxWorkers(), trino.workerMemoryMb())) : Map.of(); this.nodeManager = new ClusterStorage.Yarn(config.services().emr().yarnNodeMemoryMb(), config.services().emr().yarnNodeVcores()); this.maxWorkerNodes = config.services().emr().yarnMaxWorkerNodes(); @@ -1070,18 +1064,19 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear } /** - * A cluster's Trino as clients outside the cluster reach it: the cluster's account, Region, id and state, and the - * port Trino listens on. + * A cluster's query engine as clients outside the cluster reach it: the cluster's account, Region, id and state, + * the engine, and the port it listens on. */ - public record TrinoCluster(String accountId, String region, String clusterId, String state, int port) { + public record QueryEngineCluster(String accountId, String region, String clusterId, String state, + EmrQueryEngine engine, int port) { } /** - * The cluster of that id, whichever account and Region holds it, as the host clients reach its Trino at names it - * ({@link EmrTrino#address}); empty where there is none, or it runs no Trino of Floci's. Looked up by its id in - * each account that holds clusters, not by a scan, as every request to its Trino asks. + * The cluster of that id, whichever account and Region holds it, as the host clients reach its query engine at + * names it ({@link EmrQueryEngine#address}); empty where there is none, or it runs no engine of Floci's. Looked up + * by its id in each account that holds clusters, not by a scan, as every request to its engine asks. */ - public Optional trinoCluster(String clusterId) { + public Optional queryEngineCluster(String clusterId) { AccountAwareStorageBackend.AccountEntry entry = call(() -> clusterStore .findAllAccountEntries(clusterId).stream().findFirst().orElse(null)); if (entry == null || entry.value().getRegion() == null) { @@ -1090,14 +1085,18 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear String accountId = entry.accountId(); String region = entry.value().getRegion(); return RequestScopes.callAs(accountId, region, () -> findDescribedCluster(entry.key())) - .filter(this::runsTrino) - .map(cluster -> new TrinoCluster(accountId, region, cluster.getId(), cluster.getState(), - EmrTrino.port(EmrSparkSteps.trinoConfig(cluster.getConfigurations(), SNAPSHOT_MAPPER)))); + .filter(this::runsQueryEngine) + .map(cluster -> { + EmrQueryEngine engine = queryEngineOf(cluster); + return new QueryEngineCluster(accountId, region, cluster.getId(), cluster.getState(), engine, + EmrQueryEngine.port(EmrSparkSteps.engineConfig(engine, cluster.getConfigurations(), + SNAPSHOT_MAPPER))); + }); } - /** Where Floci reaches the cluster's Trino on {@code port}, once it has answered queries. */ - public Optional trinoInterface(String clusterId, int port) { - return clusterStorage == null ? Optional.empty() : clusterStorage.trinoInterface(clusterId, port); + /** Where Floci reaches the cluster's query engine on {@code port}, once it has answered queries. */ + public Optional queryEngineInterface(String clusterId, int port) { + return clusterStorage == null ? Optional.empty() : clusterStorage.queryEngineInterface(clusterId, port); } /** @@ -1449,9 +1448,9 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear /** * The session's ServerUrl, "The Spark Connect server URL for the session", which a client uses "with the * Credentials returned by GetSessionEndpoint to connect directly to the session": Floci's own address in Spark - * Connect's {@code sc://} form, where {@link SparkConnectProxy} takes a call carrying GetSessionEndpoint's token - * on to the session's server, so that no client reaches the server without one. The model gives no example of - * AWS's. + * Connect's {@code sc://} form, where {@link SparkConnectProxy} takes a call carrying GetSessionEndpoint's + * token on to the session's server, so that no client reaches the server without one. The model gives no + * example of AWS's. */ @Override protected void ready(EmrSession stored) { @@ -2086,8 +2085,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear } /** - * Whether {@code key} is a Region's configuration's, {@code ::}. A name may hold "::" itself, so a key - * stored before is told apart by what precedes the first one: a Region {@link RegionResolver#isKnownRegion} + * Whether {@code key} is a Region's configuration's, {@code ::}. A name may hold "::" itself, so a + * key stored before is told apart by what precedes the first one: a Region {@link RegionResolver#isKnownRegion} * admits, as {@code RegionScopedStorage} tells its keys apart. */ private static boolean isRegionalKey(String key) { @@ -3148,23 +3147,13 @@ 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; - String trinoImage = trinoImage(cluster); - ClusterStorage.Trino trino = trinoImage == null ? null : new ClusterStorage.Trino(trinoImage, trinoMemoryMb, - EmrSparkSteps.trinoConnectors(cluster.getConfigurations(), SNAPSHOT_MAPPER), - EmrSparkSteps.trinoConfig(cluster.getConfigurations(), SNAPSHOT_MAPPER), - EmrSparkSteps.trinoNode(cluster.getConfigurations(), SNAPSHOT_MAPPER), - EmrSparkSteps.trinoLog(cluster.getConfigurations(), SNAPSHOT_MAPPER), - EmrSparkSteps.trinoEnvironment(cluster.getConfigurations(), SNAPSHOT_MAPPER), - EmrSparkSteps.trinoExchangeManager(cluster.getConfigurations(), SNAPSHOT_MAPPER), - EmrSparkSteps.trinoPasswordAuthenticator(cluster.getConfigurations(), SNAPSHOT_MAPPER), - cluster.getBootstrapImage(), trinoMaxWorkers, trinoWorkerMemoryMb, - trinoOwnNodes(cluster) ? currentNodes(cluster, accountId, region) : null); + ClusterStorage.QueryEngine queryEngine = queryEngine(cluster, accountId, region); boolean withHdfs = !EmrSparkSteps.trinoAlone(cluster.getReleaseLabel(), cluster.getApplications(), SNAPSHOT_MAPPER); ClusterStorage.HiveMetastore hiveMetastore = withHiveImage(cluster) ? new ClusterStorage.HiveMetastore(instanceProfileRole(cluster, accountId), - EmrSparkSteps.hiveMetastoreSettings(cluster.getConfigurations(), SNAPSHOT_MAPPER), trino, - withHdfs) + EmrSparkSteps.hiveMetastoreSettings(cluster.getConfigurations(), SNAPSHOT_MAPPER), + queryEngine, withHdfs) : null; SparkJobRunner.Storage onlyVolumes = volumes; BiFunction hdfs = volumes == null ? null @@ -3221,9 +3210,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear application != null ? application : List.of(), command, Duration.ZERO, EmrSparkSteps.logFolder(cluster, step), null, stepEnvironment(step, cluster, command != null && pig, - runsTrino(cluster) ? EmrTrino.server(masterPrivateDnsName(cluster), - EmrTrino.port(EmrSparkSteps.trinoConfig(cluster.getConfigurations(), - SNAPSHOT_MAPPER))) : null), + runsQueryEngine(cluster) ? queryEngineOf(cluster) : null), List.of(), storage, EmrSparkSteps.coreSite(cluster.getConfigurations(), SNAPSHOT_MAPPER), EmrSparkSteps.sparkLog4j2(cluster.getConfigurations(), SNAPSHOT_MAPPER), @@ -3249,22 +3236,24 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear } } - // A cluster with Trino starts its primary node, and Trino on it, as it becomes ready, steps or none. + // A cluster with a query engine starts its primary node, and the engine on it, as it becomes ready, steps or + // none. @Override public void ready(EmrCluster cluster, String region) { - if (tornDown || !runsTrino(cluster)) { + if (tornDown || !runsQueryEngine(cluster)) { return; } String accountId = regionResolver.getAccountId(); String clusterId = cluster.getId(); - LOG.infov("EMR cluster {0} starts its Trino, which clients outside the cluster reach at {1}", clusterId, - EmrTrino.address(baseUrl, clusterId)); + EmrQueryEngine engine = queryEngineOf(cluster); + LOG.infov("EMR cluster {0} starts its {1}, which clients outside the cluster reach at {2}", clusterId, + engine.application(), engine.address(baseUrl, clusterId)); try { // On a thread of its own, which reads the cluster under the service's lock, so once this is stored. stepExecutor.execute(() -> RequestScopes.runAs(accountId, region, () -> startPrimaryNode(clusterId))); } catch (RuntimeException e) { - LOG.warnv(e, "Could not start the primary node of EMR cluster {0} for its Trino: {1}", clusterId, - e.getMessage()); + LOG.warnv(e, "Could not start the primary node of EMR cluster {0} for its {1}: {2}", clusterId, + engine.application(), e.getMessage()); } } } @@ -3366,8 +3355,9 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear clusterStorage.remove(launch.clusterId()); } if (outcome.stopped()) { - // A cancelled step's cluster-mode driver wrote only to its application's logs, which go in S3 before its - // cluster's storage can; one that never ran has none, and Floci's own teardown leaves them on the node. + // A cancelled step's cluster-mode driver wrote only to its application's logs, which go in S3 before + // its cluster's storage can; one that never ran has none, and Floci's own teardown leaves them on the + // node. if (containerLogs != null && progress.driverStarted && teardowns.get() == launch.teardownsBefore()) { clusterStorage.archiveContainerLogs(launch.clusterId(), launch.accountId(), launch.region(), containerLogs); @@ -3456,31 +3446,71 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear String release = cluster.getReleaseLabel(); String spark = EmrServerlessSparkRunner.image(imageTemplate, release); String hive = hdfsImage(release); - String trino = trinoImage(cluster); - return () -> releaseImages.image(release, spark, hive, withHive, withPig, trino); + EmrQueryEngine engine = queryEngineOf(cluster); + String engineImage = engineImage(cluster); + return () -> releaseImages.image(release, spark, hive, withHive, withPig, engine, engineImage); } // 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. + // or runs Floci's query engine, 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; + || queryEngineOf(cluster) != null; } - // Whether a cluster runs Floci's Trino: in the docker runner mode, on a network of the cluster's own, where its - // primary node runs the metastore, with an image for its Trino (trinoImage). - private boolean runsTrino(EmrCluster cluster) { - return runsOnClusters() && clusterStorage.ownNetwork(dockerNetwork) && trinoImage(cluster) != null; + // Whether a cluster runs Floci's query engine: in the docker runner mode, on a network of the cluster's own, where + // its primary node runs the metastore, with an engine (queryEngineOf). + private boolean runsQueryEngine(EmrCluster cluster) { + return runsOnClusters() && clusterStorage.ownNetwork(dockerNetwork) && queryEngineOf(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)) { + // The query engine a cluster runs: one its Applications name, whose setting runs it (engineSettings), where its + // release's version of it is known (EmrQueryEngine.image); null otherwise. + private EmrQueryEngine queryEngineOf(EmrCluster cluster) { + for (Map.Entry settings : engineSettings.entrySet()) { + EmrQueryEngine engine = settings.getKey(); + if (EmrSparkSteps.installsEngine(engine, cluster.getReleaseLabel(), cluster.getApplications(), + SNAPSHOT_MAPPER) + && engine.image(settings.getValue().imageTemplate(), cluster.getReleaseLabel()) != null) { + return engine; + } + } + return null; + } + + // The image a cluster's query engine runs from (queryEngineOf); null where it runs none. + private String engineImage(EmrCluster cluster) { + EmrQueryEngine engine = queryEngineOf(cluster); + return engine == null ? null + : engine.image(engineSettings.get(engine).imageTemplate(), cluster.getReleaseLabel()); + } + + // A cluster's query engine as its storage starts it, from the engine's settings and the cluster's classifications + // for it, its workers on nodes of its own where it has them (engineOwnNodes); null where it runs none. + private ClusterStorage.QueryEngine queryEngine(EmrCluster cluster, String accountId, String region) { + EmrQueryEngine engine = queryEngineOf(cluster); + if (engine == null) { return null; } - return EmrTrino.image(trinoImageTemplate, cluster.getReleaseLabel()); + EngineSettings settings = engineSettings.get(engine); + String configurations = cluster.getConfigurations(); + return new ClusterStorage.QueryEngine(engine, engineImage(cluster), settings.memoryMb(), + EmrSparkSteps.engineConnectors(engine, configurations, SNAPSHOT_MAPPER), + EmrSparkSteps.engineConfig(engine, configurations, SNAPSHOT_MAPPER), + EmrSparkSteps.engineNode(engine, configurations, SNAPSHOT_MAPPER), + EmrSparkSteps.engineLog(engine, configurations, SNAPSHOT_MAPPER), + EmrSparkSteps.engineEnvironment(engine, configurations, SNAPSHOT_MAPPER), + EmrSparkSteps.engineExchangeManager(engine, configurations, SNAPSHOT_MAPPER), + EmrSparkSteps.enginePasswordAuthenticator(engine, configurations, SNAPSHOT_MAPPER), + cluster.getBootstrapImage(), settings.maxWorkers(), settings.workerMemoryMb(), + engineOwnNodes(cluster) ? currentNodes(cluster, accountId, region) : null); + } + + /** + * What Floci runs a query engine with: the image of its project its version for {@code %s} makes, the memory its + * coordinator's container gets, and how many workers it runs with how much each. + */ + private record EngineSettings(String imageTemplate, int memoryMb, int maxWorkers, int workerMemoryMb) { } // Whether a cluster's image has Floci's Pig: it installs Pig, and floci.services.emr.pig.enabled adds it. @@ -3491,15 +3521,18 @@ 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), 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. + // with Floci's query engine, engine unless that is null, where the engine's CLI reaches the coordinator on the + // primary node, at the port its -config names. private static Map stepEnvironment(EmrStep step, EmrCluster cluster, boolean pig, - String trinoServer) { + EmrQueryEngine engine) { 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); + if (engine != null) { + variables.put(engine.serverVariable(), EmrQueryEngine.server(masterPrivateDnsName(cluster), + EmrQueryEngine.port(EmrSparkSteps.engineConfig(engine, cluster.getConfigurations(), + SNAPSHOT_MAPPER)))); } return variables; } @@ -3528,7 +3561,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear && EmrSparkSteps.names(cluster.getApplications(), SNAPSHOT_MAPPER, "Tez")); } - // What a cluster asks of YARN when it is read, which may be later than now; what it asks now, if it has gone by then. + // What a cluster asks of YARN when it is read, which may be later than now; what it asks now, if it has gone by + // then. private Supplier currentYarn(EmrCluster cluster, String accountId, String region) { String clusterId = cluster.getId(); ClusterStorage.Yarn asked = yarnOf(cluster); @@ -3545,10 +3579,11 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear () -> call(() -> clusterStore.get(clusterId).map(this::workerNodes).orElse(asked))); } - // Whether a cluster's Trino has nodes of its own (ClusterStorage.Trino.ownNodes): Floci runs its Trino, and it has - // Trino alone from emr-7.14.0, whose core and task nodes run Trino's workers and no YARN or HDFS. - private boolean trinoOwnNodes(EmrCluster cluster) { - return runsTrino(cluster) + // Whether a cluster's query engine has nodes of its own (ClusterStorage.QueryEngine.ownNodes): Floci runs its + // engine, and it has Trino alone from emr-7.14.0, whose core and task nodes run Trino's workers and no YARN or + // HDFS. + private boolean engineOwnNodes(EmrCluster cluster) { + return runsQueryEngine(cluster) && EmrSparkSteps.trinoAlone(cluster.getReleaseLabel(), cluster.getApplications(), SNAPSHOT_MAPPER); } @@ -3559,7 +3594,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear if (runsYarn(cluster)) { return workerNodes(cluster); } - return trinoOwnNodes(cluster) ? ClusterStorage.Trino.workers(workerNodes(cluster), trinoMaxWorkers) : List.of(); + return engineOwnNodes(cluster) ? ClusterStorage.QueryEngine.workers(workerNodes(cluster), + engineSettings.get(queryEngineOf(cluster)).maxWorkers()) : List.of(); } // A resize reaches the nodes of a cluster a step has started them on, on another thread, as they take a while, and @@ -3567,7 +3603,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear // those it asks for then. private void resizeNodes(EmrCluster cluster) { boolean yarnNodes = runsYarn(cluster); - if (cluster.isStorageCreated() && (yarnNodes || trinoOwnNodes(cluster))) { + if (cluster.isStorageCreated() && (yarnNodes || engineOwnNodes(cluster))) { String accountId = regionResolver.getAccountId(); String region = regionOf(cluster); Supplier yarn = yarnNodes ? currentYarn(cluster, accountId, region) : null; @@ -3588,7 +3624,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear if (yarn != null) { clusterStorage.resize(clusterId, yarn); } else { - clusterStorage.resizeTrino(clusterId); + clusterStorage.resizeQueryEngine(clusterId); } }); } @@ -3684,11 +3720,11 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear /** * Whether a cluster's primary node runs YARN, which its steps' Spark runs on: "the primary node runs the YARN - * ResourceManager service", and a core node "YARN NodeManager daemons, Hadoop MapReduce tasks, and Spark executors". - * It does on a network of the cluster's own, as its metastore does, unless the cluster has Trino alone from - * emr-7.14.0, which runs no YARN ({@link EmrSparkSteps#trinoAlone}). A cluster bootstrapped by an earlier Floci - * runs from an image that may hold no YARN, so it keeps to local mode, its HDFS in the release's Hive image, as it - * did. + * ResourceManager service", and a core node "YARN NodeManager daemons, Hadoop MapReduce tasks, and Spark + * executors". It does on a network of the cluster's own, as its metastore does, unless the cluster has Trino alone + * from emr-7.14.0, which runs no YARN ({@link EmrSparkSteps#trinoAlone}). A cluster bootstrapped by an earlier + * Floci runs from an image that may hold no YARN, so it keeps to local mode, its HDFS in the release's Hive image, + * as it did. */ private boolean runsYarn(EmrCluster cluster) { return releaseImages != null && clusterStorage != null && clusterStorage.ownNetwork(dockerNetwork) @@ -4009,7 +4045,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear private AddedNodes addedNodes(String clusterId, String accountId) { Optional found = clusterStore.get(clusterId).filter(EmrService::nodesMayStart); if (found.isEmpty() || found.get().getBootstrapImage() == null - || !runsYarn(found.get()) && !trinoOwnNodes(found.get())) { + || !runsYarn(found.get()) && !engineOwnNodes(found.get())) { return null; } EmrCluster cluster = found.get(); @@ -4347,8 +4383,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear return instance; } - // The EC2 instance a cluster's node, named as ClusterStorage.identify has it, is as the cluster stands now; null for - // a cluster that is gone. + // The EC2 instance a cluster's node, named as ClusterStorage.identify has it, is as the cluster stands now; null + // for a cluster that is gone. private Instance nodeIdentity(String clusterId, String accountId, String region, String node) { int dash = node.indexOf('-'); int group = Integer.parseInt(node.substring(0, dash)); @@ -4358,8 +4394,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear } /** - * The availability zone a cluster's instances are in: the one DescribeCluster's {@code Ec2InstanceAttributes} gives, - * else its Region's first. + * The availability zone a cluster's instances are in: the one DescribeCluster's {@code Ec2InstanceAttributes} + * gives, else its Region's first. */ static String availabilityZone(EmrCluster cluster) { String recorded = null; 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 13e324d5e4..0c74d83a79 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrSparkSteps.java +++ b/src/main/java/io/floci/aws/services/emr/EmrSparkSteps.java @@ -168,11 +168,11 @@ final class EmrSparkSteps { } /** - * The command a step that is not a Spark step runs, or null for one Floci does not run: a - * {@code command-runner.jar} step's arguments, its command first, unless it runs {@code pig-script} on a cluster - * that installs Pig, which Floci has not added ({@code pigMissing}), where EMR's would run it; on one that does not, - * EMR's {@code pig-script} runs and finds no {@code pig}, as it does there. Floci's S3DistCp with the arguments of an - * {@code s3-dist-cp} one; a {@code script-runner.jar} step's script, the first of its arguments, with the rest. + * The command a step that is not a Spark step runs, or null for one Floci does not run: a {@code + * command-runner.jar} step's arguments, its command first, unless it runs {@code pig-script} on a cluster that + * installs Pig, which Floci has not added ({@code pigMissing}), where EMR's would run it; on one that does not, + * EMR's {@code pig-script} runs and finds no {@code pig}, as it does there. Floci's S3DistCp with the arguments of + * an {@code s3-dist-cp} one; a {@code script-runner.jar} step's script, the first of its arguments, with the rest. */ static List command(EmrStep step, boolean pigMissing) { String jar = step.getJar(); @@ -297,20 +297,28 @@ final class EmrSparkSteps { return true; } + /** Whether a cluster installs {@code engine}: its {@code Applications} name it, as {@link #installs} has it. */ + static boolean installsEngine(EmrQueryEngine engine, String releaseLabel, String applications, + ObjectMapper objectMapper) { + return installs(releaseLabel, applications, objectMapper, engine.application()); + } + /** - * The properties of a cluster's {@code trino-connector-} classifications by catalog, in the order they - * come, a later configuration's winning, each of which changes "Trino's {@code .properties} file". One - * whose catalog is not a name Trino takes ({@link EmrTrino#CATALOG_NAME}) names none. + * The properties of a cluster's {@code -connector-} classifications by catalog, in the order they + * come, a later configuration's winning, each of which changes "Trino's {@code .properties} file", for + * Trino. One whose catalog is not a name the engine takes ({@link EmrQueryEngine#CATALOG_NAME}) names none. */ - static Map> trinoConnectors(String configurations, ObjectMapper objectMapper) { + static Map> engineConnectors(EmrQueryEngine engine, String configurations, + ObjectMapper objectMapper) { + String prefix = engine.prefix() + "-connector-"; Map> connectors = new LinkedHashMap<>(); for (JsonNode configuration : stored(configurations, objectMapper)) { String classification = configuration.path("Classification").asText(); - if (!classification.startsWith(EmrTrino.CONNECTOR_PREFIX)) { + if (!classification.startsWith(prefix)) { continue; } - String catalog = classification.substring(EmrTrino.CONNECTOR_PREFIX.length()); - if (!EmrTrino.CATALOG_NAME.matcher(catalog).matches()) { + String catalog = classification.substring(prefix.length()); + if (!EmrQueryEngine.CATALOG_NAME.matcher(catalog).matches()) { continue; } Map properties = connectors.computeIfAbsent(catalog, name -> new LinkedHashMap<>()); @@ -320,45 +328,50 @@ final class EmrSparkSteps { return connectors; } - /** The properties of a cluster's {@code trino-config}, which its Trino's {@code config.properties} gets. */ - static Map trinoConfig(String configurations, ObjectMapper objectMapper) { - return properties(configurations, objectMapper, EmrTrino.CONFIG_CLASSIFICATION); + /** The properties of a cluster's {@code -config}, which its engine's {@code config.properties} gets. */ + static Map engineConfig(EmrQueryEngine engine, String configurations, ObjectMapper objectMapper) { + return properties(configurations, objectMapper, engine.prefix() + "-config"); } - /** The properties of a cluster's {@code trino-node}, which its Trino's {@code node.properties} gets. */ - static Map trinoNode(String configurations, ObjectMapper objectMapper) { - return properties(configurations, objectMapper, EmrTrino.NODE_CLASSIFICATION); + /** The properties of a cluster's {@code -node}, which its engine's {@code node.properties} gets. */ + static Map engineNode(EmrQueryEngine engine, String configurations, ObjectMapper objectMapper) { + return properties(configurations, objectMapper, engine.prefix() + "-node"); } /** * The properties of a cluster's {@code trino-exchange-manager}, which make its Trino's exchange manager, or null - * where it has none: one with no properties gives EMR's default, "To use the default settings, set the following - * configuration: { "Classification": "trino-exchange-manager" }". + * where it has none, as on a cluster of an engine with no exchange manager ({@link EmrQueryEngine#exchanges}): + * one with no properties gives EMR's default, "To use the default settings, set the following configuration: + * { "Classification": "trino-exchange-manager" }". */ - static Map trinoExchangeManager(String configurations, ObjectMapper objectMapper) { - return classified(configurations, objectMapper, EmrTrino.EXCHANGE_CLASSIFICATION).isEmpty() ? null - : properties(configurations, objectMapper, EmrTrino.EXCHANGE_CLASSIFICATION); + static Map engineExchangeManager(EmrQueryEngine engine, String configurations, + ObjectMapper objectMapper) { + String classification = engine.prefix() + "-exchange-manager"; + return !engine.exchanges() || classified(configurations, objectMapper, classification).isEmpty() ? null + : properties(configurations, objectMapper, classification); } /** - * The properties of a cluster's {@code trino-password-authenticator}, which make its Trino's + * The properties of a cluster's {@code -password-authenticator}, which make its engine's * {@code password-authenticator.properties}. */ - static Map trinoPasswordAuthenticator(String configurations, ObjectMapper objectMapper) { - return properties(configurations, objectMapper, EmrTrino.PASSWORD_AUTHENTICATOR_CLASSIFICATION); + static Map enginePasswordAuthenticator(EmrQueryEngine engine, String configurations, + ObjectMapper objectMapper) { + return properties(configurations, objectMapper, engine.prefix() + "-password-authenticator"); } - /** The properties of a cluster's {@code trino-log}, which make its Trino's {@code log.properties}. */ - static Map trinoLog(String configurations, ObjectMapper objectMapper) { - return properties(configurations, objectMapper, EmrTrino.LOG_CLASSIFICATION); + /** The properties of a cluster's {@code -log}, which make its engine's {@code log.properties}. */ + static Map engineLog(EmrQueryEngine engine, String configurations, ObjectMapper objectMapper) { + return properties(configurations, objectMapper, engine.prefix() + "-log"); } /** - * The variables a cluster's {@code trino-env} exports, its nested {@code export} classification's properties, as - * "If any classification ends in env, use the export sub-classification", which its Trino's environment gets. + * The variables a cluster's {@code -env} exports, its nested {@code export} classification's properties, + * as "If any classification ends in env, use the export sub-classification", which its engine's environment gets. */ - static Map trinoEnvironment(String configurations, ObjectMapper objectMapper) { - return exports(configurations, objectMapper, EmrTrino.ENV_CLASSIFICATION); + static Map engineEnvironment(EmrQueryEngine engine, String configurations, + ObjectMapper objectMapper) { + return exports(configurations, objectMapper, engine.prefix() + "-env"); } // Whether a cluster's Applications name any of names, in any case, unless its release is of the AWS runtime for diff --git a/src/main/java/io/floci/aws/services/emr/EmrTrino.java b/src/main/java/io/floci/aws/services/emr/EmrTrino.java index b1b578232b..a094a8c6fc 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrTrino.java +++ b/src/main/java/io/floci/aws/services/emr/EmrTrino.java @@ -1,14 +1,10 @@ package io.floci.aws.services.emr; -import java.net.URI; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; -import java.util.Locale; import java.util.Map; import java.util.Set; -import java.util.regex.Pattern; -import java.util.stream.Collectors; /** * Trino on a {@code docker} cluster whose {@code Applications} name it, with @@ -30,12 +26,12 @@ import java.util.stream.Collectors; * Trino's CLI, which this class writes for the image they run in, and clients outside the cluster reach it through * Floci on a host of the cluster's own ({@link EmrTrinoRoutes}). */ -final class EmrTrino { +final class EmrTrino implements EmrQueryEngine { + /** Trino, the one engine of this class. */ + static final EmrTrino ENGINE = new 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, unless the cluster's {@code trino-config} names another. */ - static final int PORT = 8889; /** The prefix of the classifications that each change a catalog, the rest of whose name names it. */ static final String CONNECTOR_PREFIX = "trino-connector-"; /** The classification that changes Trino's {@code config.properties}. */ @@ -58,11 +54,6 @@ final class EmrTrino { "ldap.ssl.truststore.path", "ldap.ssl-trust-certificate"); /** The catalog every Trino cluster has. */ static final String HIVE = "hive"; - /** - * A catalog's name as Floci takes it: Trino's own, letters, digits and underscores, which the entrypoint passes as - * the name of a shell variable. - */ - static final Pattern CATALOG_NAME = Pattern.compile("[a-z][a-z0-9_]*"); /** The component label of a cluster's Trino container, which goes with its primary node's. */ static final String COMPONENT = "emr-trino"; /** @@ -76,8 +67,7 @@ final class EmrTrino { 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"; + /** The name of EMR's {@code trino-cli} command, in {@link #COMMAND_FOLDER}. */ 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 @@ -94,19 +84,12 @@ final class EmrTrino { done exec "$java" -jar %1$s --server "${%2$s:-localhost:%3$d}" "$@" """.formatted(CLI, SERVER_VARIABLE, PORT); - /** The variables the Trino container's entrypoint writes its configuration, node and log properties from. */ - static final String CONFIG_VARIABLE = "FLOCI_TRINO_CONFIG"; - static final String NODE_VARIABLE = "FLOCI_TRINO_NODE"; - static final String LOG_VARIABLE = "FLOCI_TRINO_LOG"; - static final String EXCHANGE_VARIABLE = "FLOCI_TRINO_EXCHANGE"; - static final String PASSWORD_AUTHENTICATOR_VARIABLE = "FLOCI_TRINO_PASSWORD_AUTHENTICATOR"; /** * The Hadoop configuration Trino's {@code hdfs} exchange manager reads, as EMR's {@code hdfs.config.resources} * names "the paths to core-site.xml, hdfs-site.xml files", which the entrypoint writes from the variable after * ({@link #exchangeSite}). */ static final String EXCHANGE_HDFS_CONFIG = "/etc/trino/exchange-core-site.xml"; - static final String EXCHANGE_SITE_VARIABLE = "FLOCI_TRINO_EXCHANGE_SITE"; /** * The property of Trino's {@code config.properties} that holds the secret its nodes sign their requests to each * other with, which Trino needs with authentication on and every node shares. @@ -114,8 +97,6 @@ final class EmrTrino { static final String SHARED_SECRET = "internal-communication.shared-secret"; /** The property of Trino's {@code node.properties} that names a node, which must be every node's own. */ static final String NODE_ID = "node.id"; - /** The prefix of the variables it writes its catalogs from, one each, the rest of whose name names it. */ - static final String CATALOG_PREFIX = "FLOCI_TRINO_CATALOG_"; /** * A Trino container's entrypoint, the coordinator's or a worker's: its configuration, as Floci gives it, the * cluster's shared secret in it ({@link #config}); the cluster's node and log properties after those of its image's @@ -159,51 +140,64 @@ final class EmrTrino { 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); + @Override + public String application() { + return APPLICATION; } - /** The port Trino listens on: the {@code http-server.http.port} of the cluster's {@code trino-config}, or EMR's. */ - static int port(Map config) { - String port = config.get("http-server.http.port"); - if (port != null) { - try { - return Integer.parseInt(port.trim()); - } catch (NumberFormatException ignored) { - // Trino refuses it as it starts, and says so in its log. - } - } - return PORT; + @Override + public String prefix() { + return "trino"; } - /** The address a step's {@code trino-cli} reaches the coordinator at, on the primary node named {@code host}. */ - static String server(String host, int port) { - return "http://" + host + ":" + port; + @Override + public String component() { + return COMPONENT; } - /** - * The address clients outside the cluster reach its Trino at, through Floci at {@code baseUrl}: a host of the - * cluster's own under {@link #HOST_LABEL}, as EMR's clients reach the primary node's. - */ - static String address(String baseUrl, String clusterId) { - URI base = URI.create(baseUrl); - return base.getScheme() + "://" + clusterId.toLowerCase(Locale.ROOT) + "." + HOST_LABEL + "." - + base.getRawAuthority(); + @Override + public String hostLabel() { + return HOST_LABEL; + } + + @Override + public boolean exchanges() { + return true; + } + + @Override + public String serverVariable() { + return SERVER_VARIABLE; + } + + @Override + public String entrypoint() { + return ENTRYPOINT; + } + + @Override + public List readyCheck() { + return READY_CHECK; + } + + @Override + public String imageCli() { + return IMAGE_CLI; + } + + @Override + public String cli() { + return CLI; + } + + @Override + public String commandName() { + return COMMAND_NAME; + } + + @Override + public String command() { + return COMMAND; } /** @@ -222,12 +216,13 @@ final class EmrTrino { * classification's properties after these, each in its place, as "you can override the configuration with your own * secret key". */ - static Map config(Map classification, boolean withWorkers, String secret) { + @Override + public Map config(Map classification, boolean withWorkers, String secret) { Map config = new LinkedHashMap<>(); config.put("coordinator", "true"); config.put("node-scheduler.include-coordinator", String.valueOf(!withWorkers)); config.put("http-server.http.port", String.valueOf(PORT)); - config.put("discovery.uri", "http://localhost:" + port(classification)); + config.put("discovery.uri", "http://localhost:" + EmrQueryEngine.port(classification)); config.put("http-server.process-forwarded", "true"); config.put(SHARED_SECRET, secret); config.putAll(classification); @@ -240,11 +235,12 @@ final class EmrTrino { * {@code trino-config} after these, as "configuration properties must be set on the coordinator and all worker * nodes" unless Trino says otherwise of one. */ - static Map workerConfig(Map classification, String primaryHost, String secret) { + @Override + public Map workerConfig(Map classification, String primaryHost, String secret) { Map config = new LinkedHashMap<>(); config.put("coordinator", "false"); config.put("http-server.http.port", String.valueOf(PORT)); - config.put("discovery.uri", server(primaryHost, port(classification))); + config.put("discovery.uri", EmrQueryEngine.server(primaryHost, EmrQueryEngine.port(classification))); config.put(SHARED_SECRET, secret); config.putAll(classification); return config; @@ -257,7 +253,8 @@ final class EmrTrino { * needs "unique for every node": that one is the coordinator's, and the entrypoint names a worker after its * node's host, as it does a node given no id. */ - static Map workerNode(Map classification, String host) { + @Override + public Map workerNode(Map classification, String host) { Map node = new LinkedHashMap<>(); node.put("node.internal-address", host); node.putAll(classification); @@ -327,7 +324,8 @@ final class EmrTrino { * Trino's catalogs, by name: {@code hive}, then each that {@code connectors}, the cluster's * {@code trino-connector-} classifications' properties by catalog, name (see {@link #catalog}). */ - static Map> catalogs(Map> connectors, + @Override + public Map> catalogs(Map> connectors, String metastoreHost, String endpoint, String region) { Map> catalogs = new LinkedHashMap<>(); catalogs.put(HIVE, catalog(HIVE, connectors.getOrDefault(HIVE, Map.of()), metastoreHost, endpoint, region)); @@ -380,14 +378,9 @@ final class EmrTrino { * once, in their order: those whose path is absolute, as Trino's container has no folder of the cluster's own a * relative one would be in. */ - static List authenticatorFiles(Map passwordAuthenticator) { + @Override + public List authenticatorFiles(Map passwordAuthenticator) { return AUTHENTICATOR_FILES.stream().map(passwordAuthenticator::get) .filter(path -> path != null && path.trim().startsWith("/")).map(String::trim).distinct().toList(); } - - /** {@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/EmrTrinoRoutes.java b/src/main/java/io/floci/aws/services/emr/EmrTrinoRoutes.java index 0e40ece480..3f77d44554 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrTrinoRoutes.java +++ b/src/main/java/io/floci/aws/services/emr/EmrTrinoRoutes.java @@ -2,47 +2,21 @@ package io.floci.aws.services.emr; import io.floci.aws.core.common.AppUiRoute; import io.floci.aws.core.common.AppUiRoutes; -import io.floci.aws.core.common.RequestScopes; -import io.floci.aws.core.common.docker.ContainerLifecycleManager; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.regex.Pattern; /** * A cluster's Trino as clients outside the cluster reach it, through Floci, on a host of the cluster's own, - * {@code .}{@value EmrTrino#HOST_LABEL}{@code .} ({@link EmrTrino#address}), as - * EMR's clients reach Trino on the primary node: no AWS API gives an address for it. The host asks for no credentials - * of its own: the cluster's Trino asks for those its {@code trino-config} and {@code trino-password-authenticator} - * configure, and where they configure none, whoever reaches Floci's port reaches the cluster's Trino. Trino names a - * query's next pages by the host it was asked on, which the request keeps, and by the scheme it was reached over, which - * goes on as {@code X-Forwarded-Proto}, and takes a password only where that scheme is HTTPS, through Floci with its - * TLS on. A cluster whose Trino is not running yet has its primary node started, as an application UI link does, and - * the request answered with a {@code 503}, which Trino's clients try again on. + * {@code .}{@value EmrTrino#HOST_LABEL}{@code .}, as + * {@link EmrQueryEngineRoutes} routes it. Trino takes a password only where the scheme a client reached it over is + * HTTPS, through Floci with its TLS on. */ @ApplicationScoped public class EmrTrinoRoutes implements AppUiRoutes { - // No source gives these, as no AWS API serves Trino; they are Floci's. - static final String NO_SUCH_CLUSTER = "No EMR cluster %s runs Floci's Trino."; - static final String CLUSTER_ENDED = "EMR cluster %s is no longer running, and its Trino is there only while it is" - + " RUNNING or WAITING."; - static final String NOT_READY = "The Trino of EMR cluster %s is starting. Try again in a moment."; - // How long a port found for a cluster's Trino is used before it is asked for again, as for the application UIs. - private static final Duration ENDPOINT_RECHECK = Duration.ofSeconds(10); - // A cluster's id, as a host name holds it, without case. - private static final Pattern CLUSTER_ID = Pattern.compile("j-[a-z0-9]+"); - - private final EmrService clusters; - private final Clock clock; - // Where Floci found each cluster's Trino, and when, by account and cluster. - private final Map endpoints = new ConcurrentHashMap<>(); + private final EmrQueryEngineRoutes routes; @Inject public EmrTrinoRoutes(EmrService clusters) { @@ -50,68 +24,21 @@ public class EmrTrinoRoutes implements AppUiRoutes { } EmrTrinoRoutes(EmrService clusters, Clock clock) { - this.clusters = clusters; - this.clock = clock; - } - - private record Found(ContainerLifecycleManager.EndpointInfo endpoint, Instant at) { + this.routes = new EmrQueryEngineRoutes(EmrTrino.ENGINE, clusters, clock); } @Override public String hostLabel() { - return EmrTrino.HOST_LABEL; + return routes.hostLabel(); } @Override public String service() { - return "emr"; + return routes.service(); } - /** - * The route of a request whose {@code Host} is {@code hostHeader}, over {@code scheme}: to the Trino of the - * cluster the host names, once it answers queries; null where the host is not one of a cluster's Trino. - */ @Override public AppUiRoute route(String hostHeader, String scheme) { - String host = hostHeader.toLowerCase(Locale.ROOT); - int dot = host.indexOf('.'); - if (dot <= 0 || !host.startsWith(EmrTrino.HOST_LABEL + ".", dot + 1) - || !CLUSTER_ID.matcher(host.substring(0, dot)).matches()) { - return null; - } - // A cluster's id is j- and capitals and digits, which the host holds in lower case. - String clusterId = "j-" + host.substring(2, dot).toUpperCase(Locale.ROOT); - EmrService.TrinoCluster cluster = clusters.trinoCluster(clusterId).orElse(null); - if (cluster == null) { - return AppUiRoute.refused(404, String.format(NO_SUCH_CLUSTER, clusterId)); - } - String key = cluster.accountId() + "/" + cluster.clusterId(); - if (!EmrClusterLifecycle.RUNNING.equals(cluster.state()) - && !EmrClusterLifecycle.WAITING.equals(cluster.state())) { - endpoints.remove(key); - return EmrClusterLifecycle.isTerminated(cluster.state()) - || EmrClusterLifecycle.TERMINATING.equals(cluster.state()) - ? AppUiRoute.refused(404, String.format(CLUSTER_ENDED, cluster.clusterId())) - : AppUiRoute.refused(503, String.format(NOT_READY, cluster.clusterId())); - } - Instant now = clock.instant(); - Found found = endpoints.get(key); - if (found == null || !now.isBefore(found.at().plus(ENDPOINT_RECHECK))) { - ContainerLifecycleManager.EndpointInfo endpoint = RequestScopes.callAs(cluster.accountId(), - cluster.region(), () -> clusters.trinoInterface(cluster.clusterId(), cluster.port())) - .orElse(null); - if (endpoint == null) { - endpoints.remove(key); - RequestScopes.runAs(cluster.accountId(), cluster.region(), - () -> clusters.startPrimaryNode(cluster.clusterId())); - return AppUiRoute.refused(503, String.format(NOT_READY, cluster.clusterId())); - } - found = new Found(endpoint, now); - endpoints.put(key, found); - } - Found routed = found; - return new AppUiRoute(found.endpoint().host(), found.endpoint().port(), Map.of(), - () -> endpoints.remove(key, routed), 0, null, 503, String.format(NOT_READY, cluster.clusterId())) - .withHeaders(Map.of("X-Forwarded-Proto", scheme)); + return routes.route(hostHeader, scheme); } } 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 d6d99ee088..3c876fe138 100644 --- a/src/main/java/io/floci/aws/services/emr/ReleaseImages.java +++ b/src/main/java/io/floci/aws/services/emr/ReleaseImages.java @@ -16,15 +16,15 @@ public interface ReleaseImages { */ default String image(String releaseLabel, String sparkImage, String hiveImage, boolean withHive, boolean withPig) { - return image(releaseLabel, sparkImage, hiveImage, withHive, withPig, null); + return image(releaseLabel, sparkImage, hiveImage, withHive, withPig, null, 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. + * {@link #image(String, String, String, boolean, boolean)}, with EMR's command for the CLI of {@code engine}, the + * query engine of {@code engineImage}, 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); + EmrQueryEngine engine, String engineImage); /** * 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/test/java/io/floci/aws/services/emr/EmrClusterStorageTest.java b/src/test/java/io/floci/aws/services/emr/EmrClusterStorageTest.java index 8ce154a698..0fb6a1322e 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrClusterStorageTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrClusterStorageTest.java @@ -138,8 +138,8 @@ class EmrClusterStorageTest { // 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(), Map.of(), Map.of(), Map.of(), - Map.of(), null, Map.of(), null, 0, 1024, null)); + new ClusterStorage.QueryEngine(EmrTrino.ENGINE, "trinodb/trino:446", 2048, Map.of(), Map.of(), + Map.of(), Map.of(), Map.of(), null, Map.of(), null, 0, 1024, null)); private final EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); private final DockerClient docker = mock(DockerClient.class); @@ -1848,7 +1848,8 @@ class EmrClusterStorageTest { String later = "application_1_0002/container_1_0002_01_000001/stdout"; List> listings = nodeLogs(Map.of(earlier, "one")); storage.archiveContainerLogs("j-1", "123456789012", "us-east-1", "s3://logs/j-1/containers/"); - // A primary node whose core nodes run the NodeManagers has no such folder, which is none to list and no failure. + // A primary node whose core nodes run the NodeManagers has no such folder, which is none to list and no + // failure. assertEquals(List.of(List.of("bash", "-c", "[ ! -d /mnt/yarn/logs ] || exec find /mnt/yarn/logs -mindepth 3" + " -maxdepth 3 -type f -printf '%s %P\\n'")), listings); @@ -2026,7 +2027,7 @@ class EmrClusterStorageTest { verify(trinoSpec).withEnv(EmrTrino.LOG_VARIABLE, ""); // No trino-exchange-manager, so no exchange manager, as on EMR. verify(trinoSpec, never()).withEnv(eq(EmrTrino.EXCHANGE_VARIABLE), anyString()); - verify(trinoSpec).withEnv(EmrTrino.CATALOG_PREFIX + "hive", EmrTrino.properties(EmrTrino.catalog("hive", + verify(trinoSpec).withEnv(EmrTrino.CATALOG_PREFIX + "hive", EmrQueryEngine.properties(EmrTrino.catalog("hive", Map.of(), "localhost", "http://host.docker.internal:4566", "us-east-1"))); verify(trinoSpec).withEntrypoint(List.of("/bin/bash", "-c", EmrTrino.ENTRYPOINT)); verify(trinoSpec).withJavaTrustStore(); @@ -2056,7 +2057,7 @@ class EmrClusterStorageTest { when(currentContainer.resolveContainerId()).thenReturn(Optional.empty()); // Not started yet. - assertTrue(ticking.trinoInterface("j-1", 8889).isEmpty()); + assertTrue(ticking.queryEngineInterface("j-1", 8889).isEmpty()); ticking.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", TRINO_METASTORE, null, NOT_STOPPED); @@ -2064,15 +2065,15 @@ class EmrClusterStorageTest { verify(spec).withLoopbackPortBinding(8889, 0); when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.RUNNING); ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", ""); - assertEquals(Optional.of(published), ticking.trinoInterface("j-1", 8889)); + assertEquals(Optional.of(published), ticking.queryEngineInterface("j-1", 8889)); // A Trino that has stopped is not reached. when(lifecycle.probeContainer(trinoName)).thenReturn(ContainerLiveness.NOT_RUNNING); - assertTrue(ticking.trinoInterface("j-1", 8889).isEmpty()); + assertTrue(ticking.queryEngineInterface("j-1", 8889).isEmpty()); when(lifecycle.probeContainer(trinoName)).thenReturn(ContainerLiveness.RUNNING); ticking.remove("j-1"); - assertTrue(ticking.trinoInterface("j-1", 8889).isEmpty()); + assertTrue(ticking.queryEngineInterface("j-1", 8889).isEmpty()); } @Test @@ -2085,8 +2086,8 @@ class EmrClusterStorageTest { authenticator.put("password-authenticator.name", "file"); authenticator.put("file.password-file", "/etc/trino/password.db"); ClusterStorage.HiveMetastore metastore = new ClusterStorage.HiveMetastore("arn:aws:iam::123456789012:role/r", - Map.of(), new ClusterStorage.Trino("trinodb/trino:446", 2048, Map.of(), Map.of(), - Map.of("node.environment", "production"), Map.of("io.trino", "DEBUG"), + Map.of(), new ClusterStorage.QueryEngine(EmrTrino.ENGINE, "trinodb/trino:446", 2048, Map.of(), + Map.of(), Map.of("node.environment", "production"), Map.of("io.trino", "DEBUG"), Map.of("DB_PASSWORD", "s3cret"), Map.of("exchange.base-directories", "s3://spool/exchange"), authenticator, null, 0, 1024, null)); @@ -2138,12 +2139,12 @@ class EmrClusterStorageTest { verify(trinoSpec, times(3)).withEnv(eq(EmrTrino.CONFIG_VARIABLE), configs.capture()); String coordinator = configs.getAllValues().get(0); assertTrue(coordinatorConfig(false, coordinator), coordinator); - String worker = EmrTrino.properties(EmrTrino.workerConfig(Map.of(), HOST, secretIn(coordinator))); + String worker = EmrQueryEngine.properties(EmrTrino.ENGINE.workerConfig(Map.of(), HOST, secretIn(coordinator))); assertEquals(List.of(worker, worker), configs.getAllValues().subList(1, 3)); // Each reached at its node's host, its catalogs' metastore on the primary node. verify(trinoSpec).withEnv(EmrTrino.NODE_VARIABLE, "node.internal-address=" + CORE_HOST); verify(trinoSpec).withEnv(EmrTrino.NODE_VARIABLE, "node.internal-address=" + TASK_HOST); - verify(trinoSpec, times(2)).withEnv(EmrTrino.CATALOG_PREFIX + "hive", EmrTrino.properties( + verify(trinoSpec, times(2)).withEnv(EmrTrino.CATALOG_PREFIX + "hive", EmrQueryEngine.properties( EmrTrino.catalog("hive", Map.of(), HOST, "http://host.docker.internal:4566", "us-east-1"))); // Each with a session of its own for the cluster's role, and waited for as the coordinator is. verify(trinoSpec).withEnv(List.of("AWS_ACCESS_KEY_ID=ASIACOREWORKER")); @@ -2273,7 +2274,7 @@ class EmrClusterStorageTest { verify(trinoSpec, times(3)).withEnv(eq(EmrTrino.CONFIG_VARIABLE), configs.capture()); String coordinator = configs.getAllValues().get(0); assertTrue(coordinatorConfig(false, coordinator), coordinator); - String worker = EmrTrino.properties(EmrTrino.workerConfig(Map.of(), HOST, secretIn(coordinator))); + String worker = EmrQueryEngine.properties(EmrTrino.ENGINE.workerConfig(Map.of(), HOST, secretIn(coordinator))); assertEquals(List.of(worker, worker), configs.getAllValues().subList(1, 3)); verify(trinoSpec).withEnv(EmrTrino.NODE_VARIABLE, "node.internal-address=" + CORE_HOST); assertFalse(stubs.asked().get(coreWorker).isEmpty()); @@ -2307,7 +2308,7 @@ class EmrClusterStorageTest { verify(trinoSpec).withLinkLocalIp("169.254.0.2"); nodes.set(List.of()); - storage.resizeTrino("j-1"); + storage.resizeQueryEngine("j-1"); verify(relays).release("169.254.0.2"); } @@ -2335,7 +2336,7 @@ class EmrClusterStorageTest { int before = removed.size(); nodes.set(List.of(TASK_NODE)); - ticking.resizeTrino("j-1"); + ticking.resizeQueryEngine("j-1"); // The new node's worker joins the coordinator as it becomes ready; the leaving node's goes. verify(trinoSpec).withName(taskWorker); @@ -2352,13 +2353,13 @@ class EmrClusterStorageTest { ticking.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", trinoAlone(4, nodes::get), null, NOT_STOPPED); runningOn(coreWorker, hdfsName); - ticking.resizeTrino("j-1"); + ticking.resizeQueryEngine("j-1"); verify(trinoSpec, times(1)).withName(coreWorker); List removed = stubs.trino().removed(); int before = removed.size(); nodes.set(List.of(new ClusterStorage.Node("1-1", CORE_HOST, true, "sha256:node"))); - ticking.resizeTrino("j-1"); + ticking.resizeQueryEngine("j-1"); // Kept while its node has the same image; started again once the node's own bootstrap has left one, so its // password authenticator's files are the node's. @@ -2368,7 +2369,7 @@ class EmrClusterStorageTest { @Test void aResizeBeforeAStepHasStartedTheClustersTrinoStartsNoWorker() { - storage.resizeTrino("j-1"); + storage.resizeQueryEngine("j-1"); verify(lifecycle, never()).createAndStart(any()); } @@ -2377,15 +2378,15 @@ class EmrClusterStorageTest { // workers on nodes of its own, as they are when read, each container getting 1024 MB. private static ClusterStorage.HiveMetastore trinoAlone(int maxWorkers, Supplier> nodes) { return new ClusterStorage.HiveMetastore("arn:aws:iam::123456789012:role/r", Map.of(), - new ClusterStorage.Trino("trinodb/trino:446", 2048, Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), - null, Map.of(), null, maxWorkers, 1024, nodes), false); + new ClusterStorage.QueryEngine(EmrTrino.ENGINE, "trinodb/trino:446", 2048, Map.of(), Map.of(), + Map.of(), Map.of(), Map.of(), null, Map.of(), null, maxWorkers, 1024, nodes), false); } // A cluster whose Trino runs up to maxWorkers workers, each container getting 1024 MB. private static ClusterStorage.HiveMetastore trinoWithWorkers(int maxWorkers) { return new ClusterStorage.HiveMetastore("arn:aws:iam::123456789012:role/r", Map.of(), - new ClusterStorage.Trino("trinodb/trino:446", 2048, Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), - null, Map.of(), null, maxWorkers, 1024, null)); + new ClusterStorage.QueryEngine(EmrTrino.ENGINE, "trinodb/trino:446", 2048, Map.of(), Map.of(), + Map.of(), Map.of(), Map.of(), null, Map.of(), null, maxWorkers, 1024, null)); } // Trino's coordinator as trinoStarts has it, and each node named so running in a container whose id is its name's @@ -2531,8 +2532,8 @@ class EmrClusterStorageTest { ldap.put("ldap.ssl.truststore.path", "/home/hadoop/ldap/truststore.pem"); ldap.put("ldap.ssl.keystore.path", "/home/hadoop/ldap/keystore.pem"); return new ClusterStorage.HiveMetastore("arn:aws:iam::123456789012:role/r", Map.of(), - new ClusterStorage.Trino("trinodb/trino:446", memoryMb, Map.of(), Map.of(), Map.of(), Map.of(), - Map.of(), null, ldap, "sha256:bootstrapped", 0, 1024, null)); + new ClusterStorage.QueryEngine(EmrTrino.ENGINE, "trinodb/trino:446", memoryMb, Map.of(), Map.of(), + Map.of(), Map.of(), Map.of(), null, ldap, "sha256:bootstrapped", 0, 1024, null)); } // An archive whose one file's header says it is size bytes, with none of its content after it. @@ -3787,7 +3788,7 @@ class EmrClusterStorageTest { // Whether config is the coordinator's configuration, running the queries too or not, with a shared secret Floci // made: 32 random bytes in Base64. private static boolean coordinatorConfig(boolean includesItself, String config) { - String expected = EmrTrino.properties(EmrTrino.config(Map.of(), !includesItself, "SECRET")); + String expected = EmrQueryEngine.properties(EmrTrino.ENGINE.config(Map.of(), !includesItself, "SECRET")); return Pattern.matches(Pattern.quote(expected).replace("SECRET", "\\E[A-Za-z0-9+/]{43}=\\Q"), config); } 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 c5d7470ef2..edd192a5a3 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrReleaseImagesTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrReleaseImagesTest.java @@ -188,8 +188,8 @@ class EmrReleaseImagesTest { .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()); + assertEquals("/usr/lib", EmrReleaseImages.engineCli(EmrTrino.ENGINE).into()); + assertEquals("trino/trino-cli", EmrReleaseImages.engineCli(EmrTrino.ENGINE).as()); verify(docker).removeContainerCmd("cli"); ArgumentCaptor tags = ArgumentCaptor.forClass(String.class); ArgumentCaptor> labels = mapCaptor(); @@ -571,7 +571,8 @@ class EmrReleaseImagesTest { when(listImages.exec()).thenAnswer(invocation -> listed); when(docker.listImagesCmd()).thenReturn(listImages); - assertEquals("sha256:made", images.image(release, SPARK, HIVE, withHive, withPig, trino)); + assertEquals("sha256:made", images.image(release, SPARK, HIVE, withHive, withPig, + trino != null ? EmrTrino.ENGINE : null, 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 416e05bf60..61a22de702 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java @@ -1128,12 +1128,13 @@ class EmrServiceContainerStepsTest { "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", Map.of("hive.metastore", - "glue"), "tpch", Map.of()), Map.of("http-server.http.port", "8890"), - Map.of("node.environment", "production"), Map.of("io.trino", "DEBUG"), + assertEquals(new ClusterStorage.QueryEngine(EmrTrino.ENGINE, "trinodb/trino:446", 2048, + Map.of("hive", Map.of("hive.metastore", "glue"), "tpch", Map.of()), + Map.of("http-server.http.port", "8890"), Map.of("node.environment", "production"), + Map.of("io.trino", "DEBUG"), Map.of("DB_PASSWORD", "s3cret"), Map.of(), Map.of("password-authenticator.name", "ldap", "ldap.url", "ldaps://ldap.example.com:636"), null, 4, 1024, null), - fixture.clusterStorage.metastores.get(0).trino()); + fixture.clusterStorage.metastores.get(0).queryEngine()); SparkJobRunner.Job job = runner.jobs.get(0); assertEquals(args, job.command()); String host = fixture.clusterStorage.hdfs.get(0).get(1); @@ -1156,8 +1157,9 @@ class EmrServiceContainerStepsTest { fixture.runStepThread(); fixture.runStepThread(); assertEquals(List.of("true"), runner.jobs.get(0).command()); - assertEquals(new ClusterStorage.Trino("trinodb/trino:446", 2048, Map.of(), Map.of(), Map.of(), Map.of(), - Map.of(), null, Map.of(), null, 4, 1024, null), fixture.clusterStorage.metastores.get(0).trino()); + assertEquals(new ClusterStorage.QueryEngine(EmrTrino.ENGINE, "trinodb/trino:446", 2048, Map.of(), Map.of(), + Map.of(), Map.of(), Map.of(), null, Map.of(), null, 4, 1024, null), + fixture.clusterStorage.metastores.get(0).queryEngine()); assertEquals(0, fixture.stepThreadsWaiting()); } @@ -1181,10 +1183,10 @@ class EmrServiceContainerStepsTest { } // What the actions wrote is in the image they left, the primary node's. - assertEquals(new ClusterStorage.Trino("trinodb/trino:446", 2048, Map.of(), + assertEquals(new ClusterStorage.QueryEngine(EmrTrino.ENGINE, "trinodb/trino:446", 2048, Map.of(), Map.of("http-server.authentication.type", "PASSWORD"), Map.of(), Map.of(), Map.of(), null, Map.of("password-authenticator.name", "file", "file.password-file", "/home/hadoop/password.db"), - "sha256:" + id, 4, 1024, null), bootstrapping.clusterStorage.metastores.get(0).trino()); + "sha256:" + id, 4, 1024, null), bootstrapping.clusterStorage.metastores.get(0).queryEngine()); } @Test @@ -1203,7 +1205,7 @@ class EmrServiceContainerStepsTest { // metastore EMR installs with Trino runs, and the release's Trino, 479. ClusterStorage.HiveMetastore metastore = fixture.clusterStorage.metastores.get(0); assertFalse(metastore.hdfs()); - assertEquals("trinodb/trino:479", metastore.trino().image()); + assertEquals("trinodb/trino:479", metastore.queryEngine().image()); assertEquals(List.of(), fixture.clusterStorage.yarns); // In the release's Hive image, as on a cluster without YARN. assertEquals("public.ecr.aws/emr-serverless/hive/emr-7.14.0:latest", fixture.clusterStorage.hdfs.get(0).get(2)); @@ -1233,7 +1235,7 @@ class EmrServiceContainerStepsTest { assertEquals(2, fixture.clusterStorage.yarns.size()); // Their Trino's workers run on YARN's nodes. assertTrue(fixture.clusterStorage.metastores.stream() - .allMatch(metastore -> metastore.trino().ownNodes() == null)); + .allMatch(metastore -> metastore.queryEngine().ownNodes() == null)); } @Test @@ -1249,7 +1251,7 @@ class EmrServiceContainerStepsTest { fixture.runStepThread(); // Its core and task nodes run Trino's workers, and no YARN. - ClusterStorage.Trino trino = fixture.clusterStorage.metastores.get(0).trino(); + ClusterStorage.QueryEngine trino = fixture.clusterStorage.metastores.get(0).queryEngine(); assertEquals(List.of("1-1", "2-1"), trino.ownNodes().get().stream().map(ClusterStorage.Node::id).toList()); assertEquals(List.of(), fixture.clusterStorage.yarns); String task = cluster.getInstanceGroups().get(2).getId(); @@ -1286,7 +1288,7 @@ class EmrServiceContainerStepsTest { bootstrap.bootstraps.forEach(ran -> roles.put(String.valueOf(ran.node()), ran.instanceRole())); assertEquals(Map.of("null", "MASTER", "1-1", "CORE", "2-1", "TASK"), roles); assertEquals(List.of("sha256:" + id + "-1-1", "sha256:" + id + "-2-1"), bootstrapping.clusterStorage.metastores - .get(0).trino().workers(null).stream().map(ClusterStorage.Node::image).toList()); + .get(0).queryEngine().workers(null).stream().map(ClusterStorage.Node::image).toList()); } @Test @@ -1355,14 +1357,15 @@ class EmrServiceContainerStepsTest { hive.setApplications("[{\"Name\": \"Hive\"}]"); String hiveId = withTrino.runJobFlow(hive, REGION).getId(); - assertEquals(Optional.of(new EmrService.TrinoCluster(ACCOUNT, REGION, trinoId, "WAITING", 8890)), - withTrino.trinoCluster(trinoId)); - assertEquals(Optional.empty(), withTrino.trinoCluster(hiveId)); - assertEquals(Optional.empty(), withTrino.trinoCluster("j-NOSUCHCLUSTER")); + assertEquals(Optional.of(new EmrService.QueryEngineCluster(ACCOUNT, REGION, trinoId, "WAITING", + EmrTrino.ENGINE, 8890)), + withTrino.queryEngineCluster(trinoId)); + assertEquals(Optional.empty(), withTrino.queryEngineCluster(hiveId)); + assertEquals(Optional.empty(), withTrino.queryEngineCluster("j-NOSUCHCLUSTER")); // With Floci's Trino off, or on a network its steps share, it runs none. - assertEquals(Optional.empty(), service.trinoCluster(trinoId)); + assertEquals(Optional.empty(), service.queryEngineCluster(trinoId)); fixture.clusterStorage.ownNetwork = false; - assertEquals(Optional.empty(), withTrino.trinoCluster(trinoId)); + assertEquals(Optional.empty(), withTrino.queryEngineCluster(trinoId)); } @Test diff --git a/src/test/java/io/floci/aws/services/emr/EmrServiceFixture.java b/src/test/java/io/floci/aws/services/emr/EmrServiceFixture.java index b0628c4357..821b458629 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrServiceFixture.java +++ b/src/test/java/io/floci/aws/services/emr/EmrServiceFixture.java @@ -213,7 +213,7 @@ final class EmrServiceFixture { } @Override - public void resizeTrino(String clusterId) { + public void resizeQueryEngine(String clusterId) { trinoResizes.add(clusterId); } @@ -271,7 +271,7 @@ final class EmrServiceFixture { @Override public String image(String releaseLabel, String sparkImage, String hiveImage, boolean withHive, - boolean withPig, String trinoImage) { + boolean withPig, EmrQueryEngine engine, String trinoImage) { asked.add(List.of(releaseLabel, sparkImage, hiveImage, String.valueOf(withHive), String.valueOf(withPig))); trinoImages.add(trinoImage); if (failure != null) { 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 eb3e8d3d53..371684b788 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrSparkStepsTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrSparkStepsTest.java @@ -28,6 +28,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; @ResourceLock(value = ParallelLocks.PORTS, mode = ResourceAccessMode.READ) class EmrSparkStepsTest { + private static final EmrQueryEngine TRINO = EmrTrino.ENGINE; + // A cluster's Applications, as RunJobFlow stores them, in a case of their own. private static final String HIVE_AND_SPARK = "[{\"Name\": \"Spark\"}, {\"Name\": \"hive\"}]"; private static final String RELEASE = "emr-7.5.0"; @@ -279,15 +281,17 @@ class EmrSparkStepsTest { "Configurations": [{"Classification": "export", "Properties": {"HADOOP_HEAPSIZE": "2048"}}]}] """; - assertEquals(Map.of("node.environment", "production"), EmrSparkSteps.trinoNode(configurations, objectMapper)); - assertEquals(Map.of("io.trino", "DEBUG"), EmrSparkSteps.trinoLog(configurations, objectMapper)); - // "If any classification ends in env, use the export sub-classification." - assertEquals(Map.of("DB_PASSWORD", "s3cret"), EmrSparkSteps.trinoEnvironment(configurations, objectMapper)); - assertEquals(Map.of(), EmrSparkSteps.trinoEnvironment(null, objectMapper)); - // An exchange manager only where the cluster names one, one with no properties at EMR's defaults. - assertNull(EmrSparkSteps.trinoExchangeManager(configurations, objectMapper)); - assertEquals(Map.of(), EmrSparkSteps.trinoExchangeManager("[{\"Classification\": \"trino-exchange-manager\"}]", + assertEquals(Map.of("node.environment", "production"), EmrSparkSteps.engineNode(TRINO, configurations, objectMapper)); + assertEquals(Map.of("io.trino", "DEBUG"), EmrSparkSteps.engineLog(TRINO, configurations, objectMapper)); + // "If any classification ends in env, use the export sub-classification." + assertEquals(Map.of("DB_PASSWORD", "s3cret"), EmrSparkSteps.engineEnvironment(TRINO, configurations, + objectMapper)); + assertEquals(Map.of(), EmrSparkSteps.engineEnvironment(TRINO, null, objectMapper)); + // An exchange manager only where the cluster names one, one with no properties at EMR's defaults. + assertNull(EmrSparkSteps.engineExchangeManager(TRINO, configurations, objectMapper)); + assertEquals(Map.of(), EmrSparkSteps.engineExchangeManager(TRINO, + "[{\"Classification\": \"trino-exchange-manager\"}]", objectMapper)); } @Test @@ -304,8 +308,8 @@ class EmrSparkStepsTest { assertEquals(Map.of("password-authenticator.name", "ldap", "ldap.url", "ldaps://ip-xxx-xxx-xxx-xxx.ec2.internal:636", "ldap.user-bind-pattern", "uid=${USER},ou=admins,dc=ec2,dc=internal"), - EmrSparkSteps.trinoPasswordAuthenticator(configurations, objectMapper)); - assertEquals(Map.of(), EmrSparkSteps.trinoPasswordAuthenticator("[]", objectMapper)); + EmrSparkSteps.enginePasswordAuthenticator(TRINO, configurations, objectMapper)); + assertEquals(Map.of(), EmrSparkSteps.enginePasswordAuthenticator(TRINO, "[]", objectMapper)); } @Test @@ -322,15 +326,16 @@ class EmrSparkStepsTest { {"Classification": "trino-config", "Properties": {"http-server.http.port": "8890"}}] """; - Map> connectors = EmrSparkSteps.trinoConnectors(configurations, objectMapper); + Map> connectors = EmrSparkSteps.engineConnectors(TRINO, configurations, + objectMapper); assertEquals(List.of("hive", "iceberg", "tpch"), List.copyOf(connectors.keySet())); assertEquals(Map.of("hive.metastore", "glue", "hive.metastore.glue.catalogid", "444455556666"), connectors.get("hive")); assertEquals(Map.of(), connectors.get("tpch")); - assertEquals(Map.of("http-server.http.port", "8890"), EmrSparkSteps.trinoConfig(configurations, + assertEquals(Map.of("http-server.http.port", "8890"), EmrSparkSteps.engineConfig(TRINO, configurations, objectMapper)); - assertEquals(Map.of(), EmrSparkSteps.trinoConnectors(null, objectMapper)); + assertEquals(Map.of(), EmrSparkSteps.engineConnectors(TRINO, null, objectMapper)); } @Test diff --git a/src/test/java/io/floci/aws/services/emr/EmrTrinoHttpsIntegrationTest.java b/src/test/java/io/floci/aws/services/emr/EmrTrinoHttpsIntegrationTest.java index 1179e6c6b7..5aa2d0045b 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrTrinoHttpsIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrTrinoHttpsIntegrationTest.java @@ -75,9 +75,9 @@ class EmrTrinoHttpsIntegrationTest { @BeforeEach void runningCluster() { EmrService clusters = mock(EmrService.class); - when(clusters.trinoCluster(CLUSTER)).thenReturn(Optional.of(new EmrService.TrinoCluster("000000000000", - "us-east-1", CLUSTER, EmrClusterLifecycle.WAITING, EmrTrino.PORT))); - when(clusters.trinoInterface(CLUSTER, EmrTrino.PORT)).thenReturn(Optional.of( + when(clusters.queryEngineCluster(CLUSTER)).thenReturn(Optional.of(new EmrService.QueryEngineCluster( + "000000000000", "us-east-1", CLUSTER, EmrClusterLifecycle.WAITING, EmrTrino.ENGINE, EmrTrino.PORT))); + when(clusters.queryEngineInterface(CLUSTER, EmrTrino.PORT)).thenReturn(Optional.of( new ContainerLifecycleManager.EndpointInfo("127.0.0.1", trino.getAddress().getPort()))); QuarkusMock.installMockForType(clusters, EmrService.class); schemes.clear(); diff --git a/src/test/java/io/floci/aws/services/emr/EmrTrinoRoutesTest.java b/src/test/java/io/floci/aws/services/emr/EmrTrinoRoutesTest.java index 4a5b2f8fbb..1cf94b2a39 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrTrinoRoutesTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrTrinoRoutesTest.java @@ -52,44 +52,45 @@ class EmrTrinoRoutesTest { @Test void aClusterWithNoTrinoOfFlocisIsNotFound() { - when(clusters.trinoCluster(CLUSTER)).thenReturn(Optional.empty()); + when(clusters.queryEngineCluster(CLUSTER)).thenReturn(Optional.empty()); AppUiRoute route = routes.route(HOST, "http"); assertEquals(404, route.status()); - assertEquals(String.format(EmrTrinoRoutes.NO_SUCH_CLUSTER, CLUSTER), route.refusal()); + assertEquals(String.format(EmrQueryEngineRoutes.NO_SUCH_CLUSTER, CLUSTER, "Trino"), route.refusal()); } @Test void aClusterStillStartingIsAskedAgainAndOneThatHasEndedIsGone() { - when(clusters.trinoCluster(CLUSTER)).thenReturn(Optional.of(cluster("STARTING"))); + when(clusters.queryEngineCluster(CLUSTER)).thenReturn(Optional.of(cluster("STARTING"))); assertEquals(503, routes.route(HOST, "http").status()); - when(clusters.trinoCluster(CLUSTER)).thenReturn(Optional.of(cluster("TERMINATED"))); + when(clusters.queryEngineCluster(CLUSTER)).thenReturn(Optional.of(cluster("TERMINATED"))); assertEquals(404, routes.route(HOST, "http").status()); - when(clusters.trinoCluster(CLUSTER)).thenReturn(Optional.of(cluster("TERMINATING"))); - assertEquals(String.format(EmrTrinoRoutes.CLUSTER_ENDED, CLUSTER), routes.route(HOST, "http").refusal()); + when(clusters.queryEngineCluster(CLUSTER)).thenReturn(Optional.of(cluster("TERMINATING"))); + assertEquals(String.format(EmrQueryEngineRoutes.CLUSTER_ENDED, CLUSTER, "Trino"), + routes.route(HOST, "http").refusal()); verify(clusters, never()).startPrimaryNode(anyString()); - verify(clusters, never()).trinoInterface(anyString(), anyInt()); + verify(clusters, never()).queryEngineInterface(anyString(), anyInt()); } @Test void aTrinoNotAnsweringYetHasItsPrimaryNodeStartedAndTheClientAskedAgain() { - when(clusters.trinoCluster(CLUSTER)).thenReturn(Optional.of(cluster("WAITING"))); - when(clusters.trinoInterface(CLUSTER, 8890)).thenReturn(Optional.empty()); + when(clusters.queryEngineCluster(CLUSTER)).thenReturn(Optional.of(cluster("WAITING"))); + when(clusters.queryEngineInterface(CLUSTER, 8890)).thenReturn(Optional.empty()); AppUiRoute route = routes.route(HOST, "http"); assertEquals(503, route.status()); - assertEquals(String.format(EmrTrinoRoutes.NOT_READY, CLUSTER), route.refusal()); + assertEquals(String.format(EmrQueryEngineRoutes.NOT_READY, CLUSTER, "Trino"), route.refusal()); verify(clusters).startPrimaryNode(CLUSTER); } @Test void aRunningTrinoIsReachedWithTheSchemeTheClientUsedItsPortFoundOnceInTenSeconds() { - when(clusters.trinoCluster(CLUSTER)).thenReturn(Optional.of(cluster("RUNNING"))); - when(clusters.trinoInterface(CLUSTER, 8890)).thenReturn(Optional.of(ENDPOINT)); + when(clusters.queryEngineCluster(CLUSTER)).thenReturn(Optional.of(cluster("RUNNING"))); + when(clusters.queryEngineInterface(CLUSTER, 8890)).thenReturn(Optional.of(ENDPOINT)); // A host name is read without case. AppUiRoute route = routes.route(HOST.toUpperCase(), "https"); @@ -101,20 +102,20 @@ class EmrTrinoRoutesTest { assertEquals(Map.of(), route.rewrites()); assertEquals(503, route.unansweredStatus()); assertEquals(Map.of("X-Forwarded-Proto", "http"), routes.route(HOST, "http").headers()); - verify(clusters, times(1)).trinoInterface(CLUSTER, 8890); + verify(clusters, times(1)).queryEngineInterface(CLUSTER, 8890); clock.advance(Duration.ofSeconds(10)); routes.route(HOST, "http"); - verify(clusters, times(2)).trinoInterface(CLUSTER, 8890); + verify(clusters, times(2)).queryEngineInterface(CLUSTER, 8890); // One that does not answer is looked for again. routes.route(HOST, "http").unreachable().run(); routes.route(HOST, "http"); - verify(clusters, times(3)).trinoInterface(CLUSTER, 8890); + verify(clusters, times(3)).queryEngineInterface(CLUSTER, 8890); verify(clusters, never()).startPrimaryNode(anyString()); } - private static EmrService.TrinoCluster cluster(String state) { - return new EmrService.TrinoCluster("000000000000", "us-east-1", CLUSTER, state, 8890); + private static EmrService.QueryEngineCluster cluster(String state) { + return new EmrService.QueryEngineCluster("000000000000", "us-east-1", CLUSTER, state, EmrTrino.ENGINE, 8890); } } diff --git a/src/test/java/io/floci/aws/services/emr/EmrTrinoTest.java b/src/test/java/io/floci/aws/services/emr/EmrTrinoTest.java index 714c668d3b..e23af514dc 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrTrinoTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrTrinoTest.java @@ -27,6 +27,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; @ResourceLock(value = ParallelLocks.PORTS, mode = ResourceAccessMode.READ) class EmrTrinoTest { + private static final EmrQueryEngine TRINO = EmrTrino.ENGINE; + private static final String ENDPOINT = "http://floci:4566"; private static final String SERVER = "http://ip-10-0-0-1.ec2.internal:8889"; private static final String PRIMARY = "ip-10-0-0-1.ec2.internal"; @@ -34,13 +36,13 @@ class EmrTrinoTest { @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")); + assertEquals("trinodb/trino:446", TRINO.image("trinodb/trino:%s", "emr-7.5.0")); + assertEquals("trinodb/trino:479", TRINO.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")); + assertNull(TRINO.image("trinodb/trino:%s", "emr-spark-8.0.0")); + assertNull(TRINO.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")); + assertEquals("registry.internal/trino:446", TRINO.image("registry.internal/trino:446", "emr-9.9.9")); } @Test @@ -50,7 +52,7 @@ class EmrTrinoTest { 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"))); + List.of(EmrQueryEngine.properties(catalog).split("\n"))); } @Test @@ -66,7 +68,7 @@ class EmrTrinoTest { "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"))); + List.of(EmrQueryEngine.properties(catalog).split("\n"))); } @Test @@ -123,12 +125,12 @@ class EmrTrinoTest { connectors.put("tpch", Map.of()); connectors.put("hive", Map.of("hive.metastore", "glue")); - Map> catalogs = EmrTrino.catalogs(connectors, "localhost", ENDPOINT, "us-east-1"); + Map> catalogs = TRINO.catalogs(connectors, "localhost", ENDPOINT, "us-east-1"); assertEquals(List.of("hive", "tpch"), List.copyOf(catalogs.keySet())); assertEquals("glue", catalogs.get("hive").get("hive.metastore")); assertEquals(List.of("hive"), - List.copyOf(EmrTrino.catalogs(Map.of(), "localhost", ENDPOINT, "us-east-1").keySet())); + List.copyOf(TRINO.catalogs(Map.of(), "localhost", ENDPOINT, "us-east-1").keySet())); } @Test @@ -138,19 +140,19 @@ class EmrTrinoTest { assertEquals(List.of("coordinator=true", "node-scheduler.include-coordinator=true", "http-server.http.port=8889", "discovery.uri=http://localhost:8889", "http-server.process-forwarded=true", "internal-communication.shared-secret=s3cret"), - List.of(EmrTrino.properties(EmrTrino.config(Map.of(), false, "s3cret")).split("\n"))); + List.of(EmrQueryEngine.properties(TRINO.config(Map.of(), false, "s3cret")).split("\n"))); // "To change the port, use the presto-config configuration classification to set the http-server.http.port // property", trino-config for Trino: its discovery follows. - Map moved = EmrTrino.config(Map.of("http-server.http.port", "8890", + Map moved = TRINO.config(Map.of("http-server.http.port", "8890", "query.max-memory", "1GB"), false, "s3cret"); assertEquals(List.of("coordinator=true", "node-scheduler.include-coordinator=true", "http-server.http.port=8890", "discovery.uri=http://localhost:8890", "http-server.process-forwarded=true", "internal-communication.shared-secret=s3cret", "query.max-memory=1GB"), - List.of(EmrTrino.properties(moved).split("\n"))); - assertEquals(8890, EmrTrino.port(moved)); - assertEquals(8889, EmrTrino.port(Map.of("http-server.http.port", "eighty"))); - assertEquals("http://ip-10-0-0-1.ec2.internal:8890", EmrTrino.server("ip-10-0-0-1.ec2.internal", 8890)); + List.of(EmrQueryEngine.properties(moved).split("\n"))); + assertEquals(8890, EmrQueryEngine.port(moved)); + assertEquals(8889, EmrQueryEngine.port(Map.of("http-server.http.port", "eighty"))); + assertEquals("http://ip-10-0-0-1.ec2.internal:8890", EmrQueryEngine.server("ip-10-0-0-1.ec2.internal", 8890)); // Its image's own health check, which asks the port config.properties names, without credentials. assertEquals(List.of("/usr/lib/trino/bin/health-check"), EmrTrino.READY_CHECK); } @@ -159,9 +161,9 @@ class EmrTrinoTest { void aCoordinatorWithWorkersLeavesTheQueriesToThem() { // Trino's deployment guide: a coordinator of a cluster with workers runs none of their work, as AWS's // "coordinator-worker model, where each component has a specialized role in query execution" has it. - assertEquals("false", EmrTrino.config(Map.of(), true, "s3cret").get("node-scheduler.include-coordinator")); + assertEquals("false", TRINO.config(Map.of(), true, "s3cret").get("node-scheduler.include-coordinator")); // The cluster's trino-config says otherwise, if it does. - assertEquals("true", EmrTrino.config(Map.of("node-scheduler.include-coordinator", "true"), true, "s3cret") + assertEquals("true", TRINO.config(Map.of("node-scheduler.include-coordinator", "true"), true, "s3cret") .get("node-scheduler.include-coordinator")); } @@ -170,15 +172,15 @@ class EmrTrinoTest { // "you can override the configuration with your own secret key", on every node. Map own = Map.of("internal-communication.shared-secret", "mine"); - assertEquals("mine", EmrTrino.config(own, true, "s3cret").get(EmrTrino.SHARED_SECRET)); - assertEquals("mine", EmrTrino.workerConfig(own, PRIMARY, "s3cret").get(EmrTrino.SHARED_SECRET)); + assertEquals("mine", TRINO.config(own, true, "s3cret").get(EmrTrino.SHARED_SECRET)); + assertEquals("mine", TRINO.workerConfig(own, PRIMARY, "s3cret").get(EmrTrino.SHARED_SECRET)); } @Test void aWorkerFindsTheCoordinatorOnThePrimaryNodeAndTakesTheClustersTrinoConfig() { assertEquals(List.of("coordinator=false", "http-server.http.port=8889", "discovery.uri=http://ip-10-0-0-1.ec2.internal:8889", "internal-communication.shared-secret=s3cret"), - List.of(EmrTrino.properties(EmrTrino.workerConfig(Map.of(), PRIMARY, "s3cret")).split("\n"))); + List.of(EmrQueryEngine.properties(TRINO.workerConfig(Map.of(), PRIMARY, "s3cret")).split("\n"))); // "configuration properties must be set on the coordinator and all worker nodes": a port of the cluster's own // is every node's, the coordinator's discovery with it. Map classification = new LinkedHashMap<>(); @@ -187,14 +189,14 @@ class EmrTrinoTest { assertEquals(List.of("coordinator=false", "http-server.http.port=8890", "discovery.uri=http://ip-10-0-0-1.ec2.internal:8890", "internal-communication.shared-secret=s3cret", "query.max-memory-per-node=512MB"), - List.of(EmrTrino.properties(EmrTrino.workerConfig(classification, PRIMARY, "s3cret")).split("\n"))); + List.of(EmrQueryEngine.properties(TRINO.workerConfig(classification, PRIMARY, "s3cret")).split("\n"))); } @Test void aWorkerIsReachedAtItsNodesHostTheClustersTrinoNodeAfter() { // Not at whichever of the node's addresses Trino would pick, a link-local one among them. assertEquals(List.of("node.internal-address=ip-10-0-0-2.ec2.internal", "node.environment=production"), - List.of(EmrTrino.properties(EmrTrino.workerNode(Map.of("node.environment", "production"), + List.of(EmrQueryEngine.properties(TRINO.workerNode(Map.of("node.environment", "production"), "ip-10-0-0-2.ec2.internal")).split("\n"))); } @@ -206,14 +208,14 @@ class EmrTrinoTest { // Each worker is then named after its node's host by the entrypoint, as a node given no id is. assertEquals(List.of("node.internal-address=ip-10-0-0-2.ec2.internal", "node.environment=production"), - List.of(EmrTrino.properties(EmrTrino.workerNode(classification, "ip-10-0-0-2.ec2.internal")) + List.of(EmrQueryEngine.properties(TRINO.workerNode(classification, "ip-10-0-0-2.ec2.internal")) .split("\n"))); } @Test void aWorkersCatalogsReachTheMetastoreOnThePrimaryNode() { assertEquals("thrift://ip-10-0-0-1.ec2.internal:9083", - EmrTrino.catalogs(Map.of(), PRIMARY, ENDPOINT, "us-east-1").get("hive").get("hive.metastore.uri")); + TRINO.catalogs(Map.of(), PRIMARY, ENDPOINT, "us-east-1").get("hive").get("hive.metastore.uri")); } @Test @@ -226,10 +228,10 @@ class EmrTrinoTest { ldap.put("ldap.ssl.keystore.path", "keys/ldap-key.pem"); // The key store's path is relative, and the trust store named twice is one file. - assertEquals(List.of("/etc/trino/ldap-truststore.pem"), EmrTrino.authenticatorFiles(ldap)); - assertEquals(List.of("/home/hadoop/password.db"), EmrTrino.authenticatorFiles(Map.of( + assertEquals(List.of("/etc/trino/ldap-truststore.pem"), TRINO.authenticatorFiles(ldap)); + assertEquals(List.of("/home/hadoop/password.db"), TRINO.authenticatorFiles(Map.of( "password-authenticator.name", "file", "file.password-file", "/home/hadoop/password.db"))); - assertEquals(List.of(), EmrTrino.authenticatorFiles(Map.of())); + assertEquals(List.of(), TRINO.authenticatorFiles(Map.of())); } @Test @@ -239,7 +241,7 @@ class EmrTrinoTest { assertEquals(List.of("exchange-manager.name=hdfs", "exchange.base-directories=hdfs://ip-10-0-0-1.ec2.internal:8020/user/trino/trino-exchange/", "hdfs.config.resources=/etc/trino/exchange-core-site.xml"), - List.of(EmrTrino.properties(EmrTrino.exchangeManager(Map.of(), NAMENODE, ENDPOINT, "us-east-1")) + List.of(EmrQueryEngine.properties(EmrTrino.exchangeManager(Map.of(), NAMENODE, ENDPOINT, "us-east-1")) .split("\n"))); // "Set exchange.use-local-hdfs to true. Set exchange.base-directories to the custom directory location in // HDFS", a property the Trino project's Trino does not take; the HDFS settings EMR lists go on. @@ -250,7 +252,7 @@ class EmrTrinoTest { assertEquals(List.of("exchange-manager.name=hdfs", "exchange.base-directories=hdfs://ip-10-0-0-1.ec2.internal:8020/exchange", "hdfs.config.resources=/etc/trino/exchange-core-site.xml", "exchange.hdfs.block-size=8MB"), - List.of(EmrTrino.properties(EmrTrino.exchangeManager(custom, NAMENODE, ENDPOINT, "us-east-1")) + List.of(EmrQueryEngine.properties(EmrTrino.exchangeManager(custom, NAMENODE, ENDPOINT, "us-east-1")) .split("\n"))); } @@ -265,22 +267,22 @@ class EmrTrinoTest { "exchange.base-directories=s3://spool-a/exchange,s3://spool-b/exchange", "exchange.s3.endpoint=" + ENDPOINT, "exchange.s3.region=eu-west-1", "exchange.s3.path-style-access=false", "exchange.sink-buffers-per-partition=4"), - List.of(EmrTrino.properties(EmrTrino.exchangeManager(s3, NAMENODE, ENDPOINT, "eu-west-1")) + List.of(EmrQueryEngine.properties(EmrTrino.exchangeManager(s3, NAMENODE, ENDPOINT, "eu-west-1")) .split("\n"))); } @Test void clientsOutsideTheClusterReachItsTrinoOnAHostOfTheClustersOwnUnderFlocis() { assertEquals("http://j-2axxxxxxgaplf.emr-trino.localhost:4566", - EmrTrino.address("http://localhost:4566", "j-2AXXXXXXGAPLF")); + TRINO.address("http://localhost:4566", "j-2AXXXXXXGAPLF")); assertEquals("https://j-2axxxxxxgaplf.emr-trino.localhost.floci.io:4566", - EmrTrino.address("https://localhost.floci.io:4566/", "j-2AXXXXXXGAPLF")); + TRINO.address("https://localhost.floci.io:4566/", "j-2AXXXXXXGAPLF")); } @Test void theEntrypointWritesTheConfigurationNodeLogAndCatalogsFlociGivesAloneAndANodeIdTrinoTakes(@TempDir Path etc) throws Exception { - String config = EmrTrino.properties(EmrTrino.config(Map.of(), false, "s3cret")); + String config = EmrQueryEngine.properties(TRINO.config(Map.of(), false, "s3cret")); Map environment = new LinkedHashMap<>(); environment.put(EmrTrino.CONFIG_VARIABLE, config); environment.put(EmrTrino.NODE_VARIABLE, "node.environment=production"); @@ -331,7 +333,8 @@ class EmrTrinoTest { @Test void theEntrypointWritesTheExchangeManagerTheClusterGives(@TempDir Path etc) throws Exception { - String exchange = EmrTrino.properties(EmrTrino.exchangeManager(Map.of(), NAMENODE, ENDPOINT, "us-east-1")); + String exchange = EmrQueryEngine.properties(EmrTrino.exchangeManager(Map.of(), NAMENODE, ENDPOINT, + "us-east-1")); runEntrypoint(etc, Map.of(EmrTrino.EXCHANGE_VARIABLE, exchange, EmrTrino.EXCHANGE_SITE_VARIABLE, EmrTrino.exchangeSite(NAMENODE)));