From 0475f96d85fc745520a92254afb2e09805842b0e Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:06:32 -0400 Subject: [PATCH] feat(emr): run a Spark History Server on a cluster's primary node in the docker runner mode (#8796) With runner-mode docker, a cluster with Spark now runs a Spark History Server on its primary node, as EMR's does ("Spark HistoryServer | http://master-public-dns-name:18080/"), and GetOnClusterAppUIPresignedURL opens it for real, on its own host, as the cluster's other interfaces open. Where the primary node runs the server, a step's Spark on the cluster's YARN keeps its event logs where "By default, Amazon EMR stores event logs in the /var/log/spark/apps directory of HDFS" (spark.eventLog.dir hdfs:///var/log/spark/apps, which the cluster's spark-defaults may replace), and names the server as spark.yarn.historyServer.address, so an ended application's tracking URL leads to its page there. The primary node makes that folder with the others in its HDFS, starts the server once it is there, reading it and listening where HDFS does, as one of the node's daemons, and is ready once it answers. Its port is published on the host's loopback interface as the other interfaces' are. With an ApplicationId, the server's link lands on the application's page. EmrAppUiNightlyIntegrationTest runs it for real: after a SparkPi step, the ResourceManager's proxy sends the application's tracking URL on to its page on the server's own host, the server lists it from its event logs, and the server's own link lands on it. --- docs/services/emr.md | 21 +++++--- .../aws/services/emr/ClusterStorage.java | 20 +++++--- .../aws/services/emr/EmrAppUiService.java | 14 ++++-- .../aws/services/emr/EmrClusterStorage.java | 36 ++++++++++++-- .../io/floci/aws/services/emr/EmrService.java | 13 +++-- .../EmrServerlessSparkRunner.java | 19 ++++++- .../emrserverless/SparkJobRunner.java | 27 ++++++---- .../emr/EmrAppUiNightlyIntegrationTest.java | 49 ++++++++++++++++++- .../services/emr/EmrClusterStorageTest.java | 45 +++++++++++++++-- .../services/emr/EmrOnClusterAppUiTest.java | 8 ++- .../EmrServerlessSparkRunnerTest.java | 24 +++++++++ 11 files changed, 232 insertions(+), 44 deletions(-) diff --git a/docs/services/emr.md b/docs/services/emr.md index a363887cbf..41fd8db96b 100644 --- a/docs/services/emr.md +++ b/docs/services/emr.md @@ -373,8 +373,8 @@ not Jupyter: ## Application UIs -Floci keeps a cluster's persistent application UIs, but serves no Spark History Server, Tez UI or YARN timeline -server: a presigned URL to one of those opens a page Floci serves at `/_aws/emr/app-ui` on its own address +Floci keeps a cluster's persistent application UIs, but serves no persistent UI, Tez UI or YARN timeline server: a +presigned URL to one of those opens a page Floci serves at `/_aws/emr/app-ui` on its own address (`base-url`, or `hostname`), with the cluster as `DescribeCluster` gives it and the interface asked for, and so does one to an on-cluster UI in the `immediate` mode. The link is signed with a key Floci makes as it starts and lasts an hour, as no source gives AWS's; one changed, past its hour or given before Floci restarted opens a `403` page, and one @@ -382,7 +382,13 @@ whose cluster has gone a `404`. In the `docker` mode, an on-cluster UI that runs on the cluster's primary node opens for real: the `ResourceManager` ("YARN ResourceManager | http://master-public-dns-name:8088/"), an `ApplicationMaster` through the ResourceManager's -web proxy, and the `JobHistoryServer`, on a cluster whose primary node runs YARN (see **YARN**). Each opens on a host of +web proxy, and the `JobHistoryServer`, on a cluster whose primary node runs YARN (see **YARN**), and on one with Spark +its `SparkHistoryServer` ("Spark HistoryServer | http://master-public-dns-name:18080/"). A step's Spark on the +cluster's YARN keeps its event logs where "By default, Amazon EMR stores event logs", "the /var/log/spark/apps directory +of HDFS" (`spark.eventLog.dir`, unless the cluster's `spark-defaults` give another, which the server then does not +read), and gives the server's address as `spark.yarn.historyServer.address`, so an ended application's tracking URL +leads to its page there; the server reads that folder only, whatever the cluster's `spark.history.*` settings say. +Each opens on a host of its own, as AWS's application UIs are on hosts of their own under "emrappui-prod.us-east-1.amazonaws.com", which "are registered in the Public Suffix List": `http://-.emrappui./`, the secret 26 random letters and digits that only this link holds, so the host itself is the link's authority, as the interface @@ -416,8 +422,9 @@ arrives, and an interface that sends nothing for a minute has the request given refused, and the URL is `PresignedURLReady` at once. **GetOnClusterAppUIPresignedURL** gives one to an on-cluster UI, the `ResourceManager` by default, while the cluster is `RUNNING` or `WAITING`, and none for a `DryRun`. With an `ApplicationId`, the ResourceManager's link lands on the application's page, an application master's on its UI - through the web proxy, and the JobHistory server's on the job of that id (`job_` in place of `application_`); without - one, on the cluster's applications, its running ones, and its jobs. A link Floci opens for real is + through the web proxy, the JobHistory server's on the job of that id (`job_` in place of `application_`), and the + Spark History Server's on the application's; without one, on the cluster's applications, its running ones, its jobs, + and its Spark applications. A link Floci opens for real is `PresignedURLReady` once the primary node is: until then, as on a cluster no step has run on yet, the node starts as a step's would ("Used to determine if the presigned URL is ready"), and its host answers with a `503` page meanwhile. Any other is ready at once. @@ -541,7 +548,9 @@ holding the driver and its executors, or a command or a script. The cluster itse reach, and the cluster's Spark, MapReduce (see **Hadoop streaming and MapReduce**) and Hive's Tez (see **Hive steps**) run on them. Beside them runs the MapReduce JobHistory server EMR's primary node runs too (a release's `mapred-site` classification "Restarts Hadoop MapReduce-HistoryServer"), on Hadoop's own ports, 10020 and 19888 for its web - pages, from the jobs' history in the cluster's HDFS, and the node is ready once it answers. A + pages, from the jobs' history in the cluster's HDFS, and, on a cluster with Spark, a Spark History Server on 18080, + from the Spark applications' event logs in `/var/log/spark/apps` of the cluster's HDFS (see + [Application UIs](#application-uis)); the node is ready once both answer. A Spark step or custom JAR step submits to it, with `--master yarn` unless it names another master, and in the deploy mode it asks for, `client` when it names none, and so does a `spark-submit` a command or script starts. In client mode the driver stays in the step's container and its output in the step's logs, and the executors run in YARN's 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 889b04a8f1..218f9a67d2 100644 --- a/src/main/java/io/floci/aws/services/emr/ClusterStorage.java +++ b/src/main/java/io/floci/aws/services/emr/ClusterStorage.java @@ -117,19 +117,20 @@ public interface ClusterStorage { * YARN on a cluster: a ResourceManager on its primary node, and a NodeManager on each of its {@code nodes}, and on * the primary node too when it {@code primaryWorks}, each offering its containers {@code memoryMb} of memory and * {@code vcores} virtual cores, which run its steps' Spark executors; the folder of the nodes' image holding the - * Hadoop their daemons run from, or null for the image's own; the copies of a block its HDFS keeps; and the S3 - * folder its applications' logs go in, or null. A primary node that works runs a DataNode as well. + * Hadoop their daemons run from, or null for the image's own; the copies of a block its HDFS keeps; the S3 + * folder its applications' logs go in, or null; and whether its primary node runs a Spark History Server, as on a + * cluster with Spark. A primary node that works runs a DataNode as well. */ record Yarn(int memoryMb, int vcores, String hadoopFolder, List nodes, int replication, String logFolder, - boolean primaryWorks) { + boolean primaryWorks, boolean sparkHistory) { Yarn(int memoryMb, int vcores) { - this(memoryMb, vcores, null, List.of(), 1, null, true); + this(memoryMb, vcores, null, List.of(), 1, null, true, false); } /** This YARN with its daemons run from the Hadoop in {@code folder}. */ Yarn withHadoopFolder(String folder) { - return new Yarn(memoryMb, vcores, folder, nodes, replication, logFolder, primaryWorks); + return new Yarn(memoryMb, vcores, folder, nodes, replication, logFolder, primaryWorks, sparkHistory); } /** @@ -138,12 +139,17 @@ public interface ClusterStorage { */ Yarn onNodes(List workers, int copies, String folder) { return new Yarn(memoryMb, vcores, hadoopFolder, List.copyOf(workers), copies, folder, - workers.stream().noneMatch(Node::core)); + workers.stream().noneMatch(Node::core), sparkHistory); } /** This YARN with its primary node running a DataNode and a NodeManager, or not. */ Yarn withPrimaryWorking(boolean works) { - return new Yarn(memoryMb, vcores, hadoopFolder, nodes, replication, logFolder, works); + return new Yarn(memoryMb, vcores, hadoopFolder, nodes, replication, logFolder, works, sparkHistory); + } + + /** This YARN with its primary node running a Spark History Server, or not. */ + Yarn withSparkHistory(boolean runs) { + return new Yarn(memoryMb, vcores, hadoopFolder, nodes, replication, logFolder, primaryWorks, runs); } } diff --git a/src/main/java/io/floci/aws/services/emr/EmrAppUiService.java b/src/main/java/io/floci/aws/services/emr/EmrAppUiService.java index 22646fb765..36fad0ef45 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrAppUiService.java +++ b/src/main/java/io/floci/aws/services/emr/EmrAppUiService.java @@ -39,11 +39,12 @@ import java.util.regex.Pattern; * A cluster's application user interfaces: the persistent ones "hosted off-cluster" (Amazon EMR Management Guide, "View * persistent application user interfaces in Amazon EMR") and the on-cluster ones, both reached through presigned URLs. * In the docker runner mode, an on-cluster UI that runs on the cluster's primary node, its ResourceManager, an - * application master through it, its MapReduce JobHistory server, or the NodeManager of a primary node that works, - * opens for real through {@link EmrAppUiProxy}, on a host of its own under {@link #UI_HOST}, as AWS's are under - * "emrappui-prod.us-east-1.amazonaws.com" (Management Guide, "View Amazon EMR application history"). Floci keeps a - * persistent application UI's record, but serves no Spark History Server, Tez UI or YARN timeline server: a link to - * one of those, and to any on-cluster UI elsewhere, opens a page of Floci's own about the cluster + * application master through it, its MapReduce JobHistory server, the NodeManager of a primary node that works, or the + * Spark History Server of a cluster with Spark, opens for real through {@link EmrAppUiProxy}, on a host of its own + * under {@link #UI_HOST}, as AWS's are under "emrappui-prod.us-east-1.amazonaws.com" (Management Guide, "View Amazon + * EMR application history"). Floci keeps a persistent application UI's record, but serves no persistent UI, Tez UI or + * YARN timeline server: a link to one of those, and to any on-cluster UI elsewhere, opens a page of Floci's own about + * the cluster * ({@link EmrAppUiController}). Either link is valid for {@link #VALIDITY}: the page's is signed with a key of this * process, and a proxied interface's host holds a secret this process gave it. */ @@ -72,6 +73,7 @@ public class EmrAppUiService { static final String RESOURCE_MANAGER = "ResourceManager"; static final String APPLICATION_MASTER = "ApplicationMaster"; static final String JOB_HISTORY_SERVER = "JobHistoryServer"; + static final String SPARK_HISTORY_SERVER = "SparkHistoryServer"; // No source gives AWS's wording for these; they are Floci's. static final String NO_SUCH_INTERFACE = "This link opens none of the cluster's interfaces on that port."; static final String CLUSTER_ENDED = "Cluster %s is no longer running, and its on-cluster application UIs are" @@ -267,6 +269,7 @@ public class EmrAppUiService { int port = switch (type) { case RESOURCE_MANAGER, APPLICATION_MASTER -> EmrClusterStorage.RESOURCE_MANAGER_WEB_PORT; case JOB_HISTORY_SERVER -> EmrServerlessSparkRunner.JOB_HISTORY_WEB_PORT; + case SPARK_HISTORY_SERVER -> EmrServerlessSparkRunner.SPARK_HISTORY_WEB_PORT; default -> 0; }; return interfaces.ports().contains(port) ? port : null; @@ -282,6 +285,7 @@ public class EmrAppUiService { Matcher matcher = applicationId != null ? APPLICATION_ID.matcher(applicationId) : null; yield matcher != null && matcher.matches() ? "/jobhistory/job/job_" + matcher.group(1) : "/jobhistory"; } + case SPARK_HISTORY_SERVER -> application != null ? "/history/" + application + "/" : "/"; default -> application != null ? "/cluster/app/" + application : "/cluster"; }; } 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 f9e0d58998..3f8a6481dd 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrClusterStorage.java +++ b/src/main/java/io/floci/aws/services/emr/EmrClusterStorage.java @@ -143,6 +143,11 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { // The MapReduce JobHistory server's information on its web port, which says it has started. private static final String JOB_HISTORY_INFO = "http://" + BIND + ":" + EmrServerlessSparkRunner.JOB_HISTORY_WEB_PORT + "/ws/v1/history/info"; + // Set on a primary node that runs a Spark History Server, as on a cluster with Spark; its version on its web port + // says it has started. + private static final String SPARK_HISTORY_VARIABLE = "FLOCI_SPARK_HISTORY"; + private static final String SPARK_HISTORY_VERSION = "http://" + BIND + ":" + + EmrServerlessSparkRunner.SPARK_HISTORY_WEB_PORT + "/api/v1/version"; // Where a NodeManager keeps its containers' logs, on the node's volume, as //. private static final String YARN_LOGS = "/mnt/yarn/logs"; private static final int LOG_LISTING_SECONDS = 30; @@ -274,10 +279,13 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { // ClusterId the one its format gave it, rather than another cluster's in that namespace, the DataNode has joined // and the NameNode has left safe mode, which on a restart waits for the blocks the volume holds, the folders EMR's // HDFS has for steps, /tmp and the hadoop user's home, are made, and the metastore's warehouse and HIVE_JARS, which - // Hive's exec jar goes in. HDFS_READY then says the node is ready, once the metastore takes connections, the - // NodeManager has registered and the JobHistory server answers. 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. + // Hive's exec jar goes in, and, with YARN, the folder its Spark applications' event logs go in + // (EmrServerlessSparkRunner.SPARK_EVENT_LOGS). With SPARK_HISTORY_VARIABLE set, a Spark History Server starts then, + // as EMR's primary node runs one on a cluster with Spark, reading that folder, listening on its port where HDFS + // 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. // 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. @@ -308,6 +316,8 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { + "if [ -z \"$" + NODE_WORKERS_VARIABLE + "\" ] || [ -d /mnt/datanode/current ]; then " + "hdfs datanode & n=2; fi; " + "dirs=\"/tmp /user/hadoop\"; " + + "[ -z \"$" + YARN_MEMORY_VARIABLE + "\" ] || dirs=\"$dirs " + + EmrServerlessSparkRunner.SPARK_EVENT_LOGS + "\"; " + "if [ -n \"$" + HIVE_METASTORE_VARIABLE + "\" ]; then " + "dirs=\"$dirs /user/hive/warehouse " + HIVE_JARS + "\"; " + "[ -z \"$" + HIVE_METASTORE_SITE_VARIABLE + "\" ] || mapfile -t site <<< \"$" @@ -337,6 +347,12 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { + untilReady("curl -sf -m 5 \"" + NAMENODE_JMX + "NameNodeInfo\"" + " | grep -q \"\\\"Safemode\\\" : \\\"\\\"\"") + "hdfs dfs -mkdir -p $dirs || exit 1; " + + "if [ -n \"$" + SPARK_HISTORY_VARIABLE + "\" ]; then " + + "SPARK_LOCAL_IP=$FLOCI_HDFS_BIND SPARK_HISTORY_OPTS=\"-Dspark.history.fs.logDirectory=" + + "hdfs://$FLOCI_HDFS_HOST:8020" + EmrServerlessSparkRunner.SPARK_EVENT_LOGS + + " -Dspark.history.ui.port=" + EmrServerlessSparkRunner.SPARK_HISTORY_WEB_PORT + "\"" + + " /usr/lib/spark/bin/spark-class org.apache.spark.deploy.history.HistoryServer & n=$((n + 1)); " + + "fi; " + "if [ -n \"$" + HIVE_METASTORE_VARIABLE + "\" ]; then " + "jar=$(ls /usr/lib/hive/lib/hive-exec-[0-9]*.jar | head -1); " + "hdfs dfs -put -f \"$jar\" " + HIVE_JARS @@ -348,6 +364,9 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { + " | grep -q \"\\\"activeNodes\\\":[1-9]\"") + untilReady("curl -sf -m 5 " + JOB_HISTORY_INFO + " | grep -q historyInfo") + "fi; " + + "if [ -n \"$" + SPARK_HISTORY_VARIABLE + "\" ]; then " + + untilReady("curl -sf -m 5 " + SPARK_HISTORY_VERSION + " > /dev/null") + + "fi; " + "touch " + HDFS_READY + "; " // Not wait -n: an emr-6.x image's bash, 4.2, does not have it. + "while [ \"$(jobs -rp | wc -l)\" = $n ]; do sleep 1; done; rm -f " + HDFS_READY @@ -743,6 +762,9 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { boolean everyWorkerJoined = network != null && clusterSubnet(clusterId) != null && (hiveMetastore == null || !yarn.primaryWorks()); storage = storage.withYarn(host, everyWorkerJoined ? awsEnv.flociEndpoint() : flociEndpointOn(name)); + if (yarn.sparkHistory()) { + storage = storage.withSparkHistoryServer(host); + } return yarn.nodes().stream().anyMatch(Node::core) ? storage.withReplication(yarn.replication()) : storage; } } @@ -1312,6 +1334,9 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { if (yarn.primaryWorks()) { spec.withLoopbackPortBinding(NODE_MANAGER_WEB_PORT, 0); } + if (yarn.sparkHistory()) { + spec.withLoopbackPortBinding(EmrServerlessSparkRunner.SPARK_HISTORY_WEB_PORT, 0); + } } if (yarn != null) { spec.withEnv(YARN_MEMORY_VARIABLE, String.valueOf(yarn.memoryMb())) @@ -1323,6 +1348,9 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown { if (yarn.hadoopFolder() != null) { spec.withEnv(HADOOP_FOLDER_VARIABLE, yarn.hadoopFolder()); } + if (yarn.sparkHistory()) { + spec.withEnv(SPARK_HISTORY_VARIABLE, "1"); + } } // The metastore and the executors YARN runs reach Floci, Floci on the host by its address, Floci's own // certificate trusted when it serves TLS. 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 8c3254ae39..a97e806489 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrService.java +++ b/src/main/java/io/floci/aws/services/emr/EmrService.java @@ -977,8 +977,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear /** * The web interfaces Floci serves of a cluster's primary node, where it runs YARN there, in the docker runner - * mode: its ResourceManager, its MapReduce JobHistory server, and, where the node works, its NodeManager; empty - * elsewhere. + * mode: its ResourceManager, its MapReduce JobHistory server, where the node works its NodeManager, and on a + * cluster with Spark its Spark History Server; empty elsewhere. */ public Optional webInterfaces(EmrCluster cluster) { if (!runsOnClusters() || !runsYarn(cluster)) { @@ -986,9 +986,13 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear } Set ports = new LinkedHashSet<>(List.of(EmrClusterStorage.RESOURCE_MANAGER_WEB_PORT, EmrServerlessSparkRunner.JOB_HISTORY_WEB_PORT)); - if (yarnOf(cluster).primaryWorks()) { + ClusterStorage.Yarn yarn = yarnOf(cluster); + if (yarn.primaryWorks()) { ports.add(EmrClusterStorage.NODE_MANAGER_WEB_PORT); } + if (yarn.sparkHistory()) { + ports.add(EmrServerlessSparkRunner.SPARK_HISTORY_WEB_PORT); + } return Optional.of(new WebInterfaces(masterPrivateDnsName(cluster), Set.copyOf(ports))); } @@ -2878,7 +2882,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear return nodeManager.withHadoopFolder(EmrReleaseImages.hadoopFolder(cluster.getReleaseLabel())) .onNodes(nodes, (int) Math.max(1, Math.min(replication(cluster), coreNodes)), EmrSparkSteps.containerLogFolder(cluster)) - .withPrimaryWorking(cluster.getProvisionedCoreNodes() == 0 || coreNodes == 0); + .withPrimaryWorking(cluster.getProvisionedCoreNodes() == 0 || coreNodes == 0) + .withSparkHistory(EmrSparkSteps.names(cluster.getApplications(), SNAPSHOT_MAPPER, "Spark")); } // 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. diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java index a20b68ac2e..b0b532379c 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java @@ -125,6 +125,13 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo /** The ports of a cluster's MapReduce JobHistory server on its primary node, Hadoop's own defaults. */ public static final int JOB_HISTORY_PORT = 10020; public static final int JOB_HISTORY_WEB_PORT = 19888; + /** A cluster's Spark History Server's port, "Spark HistoryServer | http://master-public-dns-name:18080/". */ + public static final int SPARK_HISTORY_WEB_PORT = 18080; + /** + * Where a cluster's Spark applications keep their event logs, which its Spark History Server reads: "By default, + * Amazon EMR stores event logs in the /var/log/spark/apps directory of HDFS". + */ + public static final String SPARK_EVENT_LOGS = "/var/log/spark/apps"; // Spark's default checkpoint manager goes through Hadoop's FileContext, which refuses an hdfs:// path without a // host, though "hdfs:///path-to-data" and "/path-to-data" "would resolve to the same location in HDFS", as the // Management Guide puts it; so a streaming query keeps its checkpoints through the file system instead. @@ -1625,8 +1632,10 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo // A step's Spark on its cluster's YARN: the ResourceManager on the primary node; Spark's jars from the node's image, // which is the step's; executors and a cluster-mode driver sized for the NodeManager rather than the image's 14 GB // ("determined by the core and task instance types" on EMR), which the cluster's spark-defaults and the step's own - // options replace; a client-mode driver reached at the container's name on the cluster's network; and the step's - // AWS environment for each executor and a cluster-mode driver, as its container has it. + // options replace; a client-mode driver reached at the container's name on the cluster's network; where the + // primary node runs a Spark History Server, as on a cluster with Spark, its event logs in the cluster's HDFS, where + // the server reads them, which the application's tracking URL leads to once it has ended; and the step's AWS + // environment for each executor and a cluster-mode driver, as its container has it. private static List yarnSettings(Job job, List executorEnvironment) { List settings = new ArrayList<>(List.of( new SparkSetting("spark.hadoop.yarn.resourcemanager.hostname", job.storage().resourceManager()), @@ -1637,6 +1646,12 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo new SparkSetting("spark.driver.cores", "1"), new SparkSetting("spark.driver.host", driverHost(job)), new SparkSetting("spark.driver.bindAddress", "0.0.0.0"))); + String history = job.storage().sparkHistoryServer(); + if (history != null) { + settings.add(new SparkSetting("spark.eventLog.enabled", "true")); + settings.add(new SparkSetting("spark.eventLog.dir", "hdfs://" + SPARK_EVENT_LOGS)); + settings.add(new SparkSetting("spark.yarn.historyServer.address", history + ":" + SPARK_HISTORY_WEB_PORT)); + } for (String variable : executorEnvironment) { int equals = variable.indexOf('='); String name = variable.substring(0, equals); diff --git a/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java b/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java index 6e2fa62362..9802c76654 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java +++ b/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java @@ -211,12 +211,13 @@ public interface SparkJobRunner { * node, named {@code hdfsHost}, which a step's container reaches at {@code hdfsAddress} on the Docker network * {@code hdfsNetwork}, the cluster's own, which the container joins (all three null until it runs, the network * also on the host's own network, which steps share with it); and, on a cluster with Hive or HCatalog, the URI of - * the Hive metastore service on that node, or null; and how many copies of a block its HDFS keeps, when its core - * nodes hold it, else 0. + * the Hive metastore service on that node, or null; how many copies of a block its HDFS keeps, when its core + * nodes hold it, else 0; and the host of the Spark History Server on that node, which reads its Spark applications' + * event logs, or null where it runs none. */ record Storage(String home, String mnt, String hdfsHost, String hdfsAddress, String hdfsNetwork, String hiveMetastore, String resourceManager, String flociEndpoint, int replication, - String metadataAddress) { + String metadataAddress, String sparkHistoryServer) { /** * The component label of an EMR cluster's HDFS container, which carries its service's labels as a driver @@ -229,19 +230,19 @@ public interface SparkJobRunner { /** A cluster's volumes, before its HDFS runs. */ public Storage(String home, String mnt) { - this(home, mnt, null, null, null, null, null, null, 0, null); + this(home, mnt, null, null, null, null, null, null, 0, null, null); } /** This storage, its HDFS's NameNode on {@code host}, at {@code address} on {@code network}. */ public Storage withHdfs(String host, String address, String network) { return new Storage(home, mnt, host, address, network, hiveMetastore, resourceManager, flociEndpoint, - replication, metadataAddress); + replication, metadataAddress, sparkHistoryServer); } /** This storage, its Hive metastore service at {@code uri}. */ public Storage withHiveMetastore(String uri) { return new Storage(home, mnt, hdfsHost, hdfsAddress, hdfsNetwork, uri, resourceManager, flociEndpoint, - replication, metadataAddress); + replication, metadataAddress, sparkHistoryServer); } /** @@ -250,13 +251,21 @@ public interface SparkJobRunner { */ public Storage withYarn(String host, String flociEndpoint) { return new Storage(home, mnt, hdfsHost, hdfsAddress, hdfsNetwork, hiveMetastore, host, flociEndpoint, - replication, metadataAddress); + replication, metadataAddress, sparkHistoryServer); } /** This storage, its HDFS keeping {@code copies} copies of a block on its core nodes. */ public Storage withReplication(int copies) { return new Storage(home, mnt, hdfsHost, hdfsAddress, hdfsNetwork, hiveMetastore, resourceManager, - flociEndpoint, copies, metadataAddress); + flociEndpoint, copies, metadataAddress, sparkHistoryServer); + } + + /** + * This storage, a Spark History Server on {@code host}, the primary node, reading its applications' event logs. + */ + public Storage withSparkHistoryServer(String host) { + return new Storage(home, mnt, hdfsHost, hdfsAddress, hdfsNetwork, hiveMetastore, resourceManager, + flociEndpoint, replication, metadataAddress, host); } /** @@ -265,7 +274,7 @@ public interface SparkJobRunner { */ public Storage withMetadataAddress(String address) { return new Storage(home, mnt, hdfsHost, hdfsAddress, hdfsNetwork, hiveMetastore, resourceManager, - flociEndpoint, replication, address); + flociEndpoint, replication, address, sparkHistoryServer); } } diff --git a/src/test/java/io/floci/aws/services/emr/EmrAppUiNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/emr/EmrAppUiNightlyIntegrationTest.java index e45c4e5fd5..e129f9b06c 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrAppUiNightlyIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrAppUiNightlyIntegrationTest.java @@ -37,9 +37,12 @@ import static org.junit.jupiter.api.Assertions.fail; * On-cluster application UIs open for real: on an emr-7.5.0 cluster no step has run on yet, the ResourceManager's link * starts the primary node and is ready once the node is, then opens the ResourceManager through Floci on a host of its * own; after a MapReduce step, the ResourceManager's answer links to the job on the JobHistory server's own host, which - * opens it, as the JobHistory server's link does. + * opens it, as the JobHistory server's link does; after a Spark step, whose event logs are in the cluster's HDFS, the + * ResourceManager's answer links to the application on the Spark History Server's own host, which lists and opens it, + * as the Spark History Server's link does. * - *

A nightly check: the cluster's image, its HDFS and YARN, and a MapReduce job take minutes and gigabytes. + *

A nightly check: the cluster's image, its HDFS and YARN, and a MapReduce job and a Spark one take minutes and + * gigabytes. */ @QuarkusTest @TestProfile(EmrAppUiNightlyIntegrationTest.Profile.class) @@ -63,6 +66,7 @@ class EmrAppUiNightlyIntegrationTest { private static final int PORT = 4598; private static final String EXAMPLES = "/usr/lib/hadoop-mapreduce/hadoop-mapreduce-examples.jar"; + private static final String SPARK_EXAMPLES = "/usr/lib/spark/examples/jars/spark-examples.jar"; @RegisterExtension final PartitionCleanup cleanup = new PartitionCleanup(); @@ -133,6 +137,47 @@ class EmrAppUiNightlyIntegrationTest { String jobLink = readyLink(clusterId, "JobHistoryServer", applicationId); assertEquals(jobPath, URI.create(jobLink).getPath()); assertTrue(open(jobLink).asString().contains("QuasiMonteCarlo")); + + String sparkStep = EmrRequests.addStep(clusterId, "spark-pi", "command-runner.jar", "spark-submit", + "--class", "org.apache.spark.examples.SparkPi", SPARK_EXAMPLES, "10"); + assertEquals("COMPLETED", awaitStep(clusterId, sparkStep).jsonPath().getString("Step.Status.State")); + // Its tracking URL, the ResourceManager's proxy, sends the browser on, once it has ended, to its page on the + // Spark History Server's own host. + JsonPath sparkApps = open(linked.getScheme() + "://" + linked.getRawAuthority() + "/ws/v1/cluster/apps") + .jsonPath(); + String spark = "apps.app.find { it.applicationType == 'SPARK' }"; + String sparkId = sparkApps.getString(spark + ".id"); + String sparkTracking = sparkApps.getString(spark + ".trackingUrl"); + assertEquals(String.format(origin, EmrClusterStorage.RESOURCE_MANAGER_WEB_PORT) + "/proxy/" + sparkId + "/", + sparkTracking); + Response sparkProxied = open(sparkTracking); + assertTrue(sparkProxied.statusCode() / 100 == 3, sparkProxied.statusCode() + " " + sparkProxied.asString()); + String historyOrigin = String.format(origin, EmrServerlessSparkRunner.SPARK_HISTORY_WEB_PORT); + assertTrue(sparkProxied.getHeader("Location").startsWith(historyOrigin + "/history/" + sparkId), + sparkProxied.getHeader("Location")); + // The Spark History Server's own link lists it from its event logs, read as they come, and lands on it, once + // the server has read its finished log: one it listed while the application ran is renamed as it ends, and is + // found again at the server's next look. + String historyLink = readyLink(clusterId, "SparkHistoryServer", null); + await(() -> open(historyLink.replaceFirst("/$", "") + "/api/v1/applications?status=completed").asString() + .contains(sparkId), Duration.ofMinutes(2)); + String applicationLink = readyLink(clusterId, "SparkHistoryServer", sparkId); + assertEquals("/history/" + sparkId + "/", URI.create(applicationLink).getPath()); + Response application = follow(applicationLink); + assertEquals(200, application.statusCode(), application.asString()); + assertTrue(application.asString().contains("Spark Pi"), application.asString()); + assertTrue(follow(sparkTracking).asString().contains("Spark Pi")); + } + + // A browser's request to the link, following the redirects it is sent, each to a link's host. + private static Response follow(String url) { + String at = url; + Response response = open(at); + for (int hop = 0; hop < 5 && response.statusCode() / 100 == 3; hop++) { + at = URI.create(at).resolve(response.getHeader("Location")).toString(); + response = open(at); + } + return response; } private static JsonPath link(String clusterId, String type, String applicationId) { 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 f4656d45be..062f8edd92 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrClusterStorageTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrClusterStorageTest.java @@ -1366,7 +1366,46 @@ class EmrClusterStorageTest { + " | grep -q \"\\\"activeNodes\\\":[1-9]\"") + waitUntil("curl -sf -m 5 http://$(cat /tmp/floci-hdfs-bind):19888/ws/v1/history/info" + " | grep -q historyInfo") - + "fi; touch /tmp/floci-hdfs-ready"))); + + "fi; if [ -n \"$FLOCI_SPARK_HISTORY\" ]; then ") + && entrypoint.get(2).contains("> /dev/null; do [ \"$(jobs -rp | wc -l)\" = $n ] || exit 1; sleep 0.2;" + + " done; fi; touch /tmp/floci-hdfs-ready"))); + // A cluster without Spark runs no Spark History Server. + assertNull(started.sparkHistoryServer()); + verify(spec, never()).withEnv(eq("FLOCI_SPARK_HISTORY"), anyString()); + verify(spec, never()).withLoopbackPortBinding(EmrServerlessSparkRunner.SPARK_HISTORY_WEB_PORT, 0); + } + + @Test + void aClusterWithSparkHasItsPrimaryNodeRunASparkHistoryServerOnItsApplicationsEventLogs() { + when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING); + when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-7", Map.of())); + when(lifecycle.probeContainer("c-7")).thenReturn(ContainerLiveness.RUNNING); + when(lifecycle.resolveContainerNetworkIp("c-7", hdfsName)).thenReturn("172.18.0.8"); + ContainerExecStubs.completeEveryExec(docker, "c-7", 0L, "", ""); + + SparkJobRunner.Storage started = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, + "floci-network", null, () -> new ClusterStorage.Yarn(4096, 4).withSparkHistory(true), NOT_STOPPED); + + // The cluster's Spark applications keep their event logs where it reads them. + assertEquals(HOST, started.sparkHistoryServer()); + verify(spec).withEnv("FLOCI_SPARK_HISTORY", "1"); + verify(spec).withLoopbackPortBinding(EmrServerlessSparkRunner.SPARK_HISTORY_WEB_PORT, 0); + // The event logs' folder, "/var/log/spark/apps", made in the HDFS with the others; the server started once it + // is there, reading it, listening where HDFS does, one of the node's daemons, and waited for before the node is + // ready. + verify(spec).withEntrypoint(argThat(entrypoint -> { + String script = entrypoint.get(2); + int folders = script.indexOf("[ -z \"$FLOCI_YARN_MEMORY_MB\" ] || dirs=\"$dirs /var/log/spark/apps\"; "); + int made = script.indexOf("hdfs dfs -mkdir -p $dirs || exit 1; "); + int launched = script.indexOf("if [ -n \"$FLOCI_SPARK_HISTORY\" ]; then SPARK_LOCAL_IP=$FLOCI_HDFS_BIND" + + " SPARK_HISTORY_OPTS=\"-Dspark.history.fs.logDirectory=hdfs://$FLOCI_HDFS_HOST:8020" + + "/var/log/spark/apps -Dspark.history.ui.port=18080\" /usr/lib/spark/bin/spark-class" + + " org.apache.spark.deploy.history.HistoryServer & n=$((n + 1)); fi; "); + int answered = script.indexOf( + "until curl -sf -m 5 http://$(cat /tmp/floci-hdfs-bind):18080/api/v1/version"); + int ready = script.indexOf("touch /tmp/floci-hdfs-ready"); + return folders >= 0 && folders < made && made < launched && launched < answered && answered < ready; + })); } @Test @@ -1650,8 +1689,8 @@ class EmrClusterStorageTest { // the others in one go. verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains( "if [ -n \"$FLOCI_HIVE_METASTORE\" ]; then dirs=\"$dirs /user/hive/warehouse /tmp/hadoop/.hiveJars\";") - && entrypoint.get(2).contains("hdfs dfs -mkdir -p $dirs || exit 1; " - + "if [ -n \"$FLOCI_HIVE_METASTORE\" ]; then " + && entrypoint.get(2).indexOf("hdfs dfs -mkdir -p $dirs || exit 1; ") < entrypoint.get(2).indexOf( + "fi; if [ -n \"$FLOCI_HIVE_METASTORE\" ]; then " + "jar=$(ls /usr/lib/hive/lib/hive-exec-[0-9]*.jar | head -1); hdfs dfs -put -f \"$jar\" " + "/tmp/hadoop/.hiveJars/$(basename \"$jar\" .jar)" + "-$(sha256sum \"$jar\" | cut -d\" \" -f1).jar || exit 1; until (exec 3<>/dev/tcp"))); diff --git a/src/test/java/io/floci/aws/services/emr/EmrOnClusterAppUiTest.java b/src/test/java/io/floci/aws/services/emr/EmrOnClusterAppUiTest.java index 16774bf8c8..797fc2942b 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrOnClusterAppUiTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrOnClusterAppUiTest.java @@ -82,6 +82,11 @@ class EmrOnClusterAppUiTest { assertEquals("/jobhistory/job/job_1763395200000_0002", path(appUis.onClusterUrl(clusterId, "JobHistoryServer", application, false))); assertTrue(appUis.onClusterUrl(clusterId, "JobHistoryServer", null, false).url().contains("-19888.")); + // A cluster with Spark: its Spark History Server, on the primary node. + EmrAppUiService.Presigned history = appUis.onClusterUrl(clusterId, "SparkHistoryServer", application, false); + assertTrue(history.url().contains("-18080.emrappui."), history.url()); + assertEquals("/history/" + application + "/", path(history)); + assertEquals("/", path(appUis.onClusterUrl(clusterId, "SparkHistoryServer", null, false))); } @Test @@ -156,8 +161,7 @@ class EmrOnClusterAppUiTest { void anInterfaceFlociDoesNotRunOpensFlocisOwnPage() { fixture.clusterStorage.webInterfaces.put(RESOURCE_MANAGER, RESOURCE_MANAGER_ON_HOST); - EmrAppUiService.Presigned link = appUis.onClusterUrl(yarnCluster().getId(), "SparkHistoryServer", null, - false); + EmrAppUiService.Presigned link = appUis.onClusterUrl(yarnCluster().getId(), "TezUI", null, false); assertTrue(link.ready()); assertTrue(link.url().startsWith("http://localhost:4566" + EmrAppUiService.PATH + "?"), link.url()); diff --git a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunnerTest.java b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunnerTest.java index 4f84f546fe..b14df37b1b 100644 --- a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunnerTest.java +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunnerTest.java @@ -1016,6 +1016,30 @@ class EmrServerlessSparkRunnerTest { .startsWith("spark.master yarn\n")); } + @Test + void aStepOnItsClustersYarnKeepsItsEventLogsInTheClustersHdfsUnlessItsClusterSaysOtherwise() { + SparkJobRunner.Job job = stepJob(Map.of("spark.eventLog.dir", "s3://logs/spark/")) + .onStorage(STORAGE.withYarn("ip-10-0-0-1.ec2.internal", "http://floci:4566") + .withSparkHistoryServer("ip-10-0-0-1.ec2.internal")); + + List arguments = EmrServerlessSparkRunner.sparkSubmitArguments(job, "http://floci:4566", List.of()); + + // "By default, Amazon EMR stores event logs in the /var/log/spark/apps directory of HDFS", which the primary + // node's Spark History Server reads, and which an ended application's tracking URL leads to. + assertTrue(arguments.contains("spark.eventLog.enabled=true"), arguments.toString()); + int hdfs = arguments.indexOf("spark.eventLog.dir=hdfs:///var/log/spark/apps"); + assertTrue(hdfs > 0 && arguments.indexOf("spark.eventLog.dir=s3://logs/spark/") > hdfs, arguments.toString()); + assertTrue(arguments.contains("spark.yarn.historyServer.address=ip-10-0-0-1.ec2.internal:18080")); + assertFalse(EmrServerlessSparkRunner.sparkSubmitArguments(stepJob(Map.of()), ENDPOINT).toString() + .contains("spark.eventLog.dir")); + // A cluster whose primary node runs no Spark History Server, one without Spark, keeps the image's. + String withoutServer = EmrServerlessSparkRunner.sparkSubmitArguments(stepJob(Map.of()) + .onStorage(STORAGE.withYarn("ip-10-0-0-1.ec2.internal", "http://floci:4566")), ENDPOINT, + List.of()).toString(); + assertFalse(withoutServer.contains("spark.eventLog") || withoutServer.contains("historyServer"), + withoutServer); + } + @Test void aStepNotOnYarnRunsInLocalModeWithNoneOfYarnsSettings() { List arguments = EmrServerlessSparkRunner.sparkSubmitArguments(stepJob(Map.of()), ENDPOINT);