feat(emr): run a custom JAR's MapReduce and apply Hadoop classifications (#7294)

In the docker runner mode a custom JAR step whose main class starts a
MapReduce job, such as the Management Guide's wordcount of Hadoop's
examples JAR, never ended: its spark-submit read the image's
mapred-site.xml, which names YARN, and the job kept retrying a
ResourceManager at 0.0.0.0:8032. A Jar of
/usr/lib/hadoop-mapreduce/hadoop-streaming.jar, where EMR has it, named
a file the image lacks. And a cluster's mapred-site, hadoop-log4j and
hadoop-env classifications reached none of its steps.

Now, on a cluster:

- a custom JAR or Spark step's spark-submit runs after the Hadoop setup
  a command gets, so its HADOOP_CONF_DIR is the copy with Floci's S3,
  the cluster's HDFS and MapReduce in local mode, which spark-submit
  puts on its class path; a MapReduce job its main class starts runs in
  the driver's JVM.
- a Jar of /usr/lib/hadoop-mapreduce/hadoop-streaming.jar runs the
  image's /usr/lib/hadoop/hadoop-streaming.jar.
- mapred-site, which will "Change values in the MapReduce application's
  mapred-site.xml file", goes in the copied mapred-site.xml ahead of
  Floci's local mode and staging folder, which win.
- hadoop-log4j, which will "Change values in Hadoop's log4j.properties
  file", follows the copied log4j.properties, a later key winning.
- hadoop-env's export classification starts the copied hadoop-env.sh,
  which the hadoop command reads, each value as given, single-quoted,
  as spark-env's exports are set without shell expansion; a name a
  shell cannot export is left out. The image's own lines come after
  and add to HADOOP_CLASSPATH rather than set it, so the Release
  Guide's HADOOP_CLASSPATH of /path/to/my.jar keeps the LZO codec the
  image's core-site.xml names, without which every job fails.
- a jar the MapReduce home links that the image lacks is named on the
  step's standard error, as a job that needs it fails later, on its
  class path, and emr.md says which releases this has run on (emr-7.5.0
  and emr-7.10.0).

An EMR Serverless run still starts spark-submit as it is. A custom JAR
step's spark-submit reads neither hadoop-env.sh nor Hadoop's
log4j.properties, so those two do not reach it.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-02 07:53:24 -06:00
1 parent b4c539d009
commit db3efe8186
9 files changed
+429 -80

No files matched your search

+38 -17
View File
@@ -117,7 +117,10 @@ but for its bootstrap actions and its storage.
* **Which steps run**: a `command-runner.jar` step whose first argument is `spark-submit`, the way the
Management Guide writes Spark steps, runs the arguments after it, without its `--master` and
`--deploy-mode`. A custom JAR step runs its `MainClass`, or else the one its manifest names, through
`spark-submit`, with the JAR and the step's `Args`. Any other `command-runner.jar` step runs its
`spark-submit`, with the JAR and the step's `Args`; a MapReduce job it starts, such as the Management
Guide's `wordcount` of Hadoop's examples JAR, runs in local mode (see **Hadoop streaming and MapReduce**).
A `Jar` of `/usr/lib/hadoop-mapreduce/hadoop-streaming.jar`, where EMR has it, runs the image's
`/usr/lib/hadoop/hadoop-streaming.jar`. Any other `command-runner.jar` step runs its
command, its first argument, with the rest, and a `script-runner.jar` step (by name, or by its
`s3://<region>.elasticmapreduce/libs/script-runner/script-runner.jar` URI) its script, as the Release
Guide's "Run commands and scripts on an Amazon EMR cluster" describes them. An `s3-dist-cp` step runs
@@ -157,20 +160,36 @@ but for its bootstrap actions and its storage.
as there is no YARN: the image has MapReduce only in Spark's shaded Hadoop client, which Floci makes the
command's MapReduce home (`HADOOP_MAPRED_HOME`, unless a `spark-env` export names one), so it is on the
command's class path whatever `HADOOP_CLASSPATH` a command sets, and a copy of its `mapred-site.xml` sets
`mapreduce.framework.name` to `local`. So a `command-runner.jar` step whose first argument is
`hadoop-streaming`, which "Submits an Hadoop streaming program. In the console and some SDKs, this is a
streaming step", as the Release Guide's tools table puts it (the AWS CLI's `Type=STREAMING` becomes one),
runs the image's `hadoop-streaming.jar` with the step's other arguments: its mapper and reducer can come
from Floci's S3 through `-files`, `-cacheFile` or `-cacheArchive`, and its `-input` and `-output` can be in
Floci's S3 or the cluster's HDFS, where a job's staging folder, `/tmp/hadoop/mapred/staging`, is too. A
`hadoop-lzo` step runs the image's LZO indexer the same way, as does a `hadoop jar` a command or script
runs. `s3://` and `s3a://` paths reach Floci's S3 through S3A, with the AWS SDK Spark's own S3A finds, in
place of the image's EMRFS, which is not pointed at Floci. The image's `log4j.properties` for Hadoop is
empty, so Hadoop logs to the step's standard error, from `INFO` up, in the layout of the Management Guide's
step log lines, and `stderr.gz` holds a failed job's reason ("ERROR org.apache.hadoop.streaming.StreamJob
(main): Error Launching job : Output directory ... already exists"), which EMR writes to the step's
`syslog`. The cluster's `mapred-site`, `hadoop-log4j` and `hadoop-env` classifications are not applied, and
a job's own `-D mapreduce.framework.name=yarn` fails.
`mapreduce.framework.name` to `local`. This has run on the `emr-7.5.0` and `emr-7.10.0` images; on another,
whose Spark jars may be named otherwise, the step's standard error names each jar of the three the MapReduce
home links that the image lacks, as a job that needs it fails later, on its class path. So a
`command-runner.jar` step whose first argument is `hadoop-streaming`, which "Submits an Hadoop streaming
program. In the console and some SDKs, this is a streaming step", as the Release Guide's tools table puts it
(the AWS CLI's `Type=STREAMING` becomes one), runs the image's `hadoop-streaming.jar` with the step's other
arguments: its mapper and reducer can come from Floci's S3 through `-files`, `-cacheFile` or
`-cacheArchive`, and its `-input` and `-output` can be in Floci's S3 or the cluster's HDFS, where a job's
staging folder, `/tmp/hadoop/mapred/staging`, is too. A `hadoop-lzo` step runs the image's LZO indexer the
same way, as does a `hadoop jar` a command or script runs. `s3://` and `s3a://` paths reach Floci's S3
through S3A, with the AWS SDK Spark's own S3A finds, in place of the image's EMRFS, which is not pointed at
Floci. The image's `log4j.properties` for Hadoop is empty, so Hadoop logs to the step's standard error, from
`INFO` up, in the layout of the Management Guide's step log lines, and `stderr.gz` holds a failed job's
reason ("ERROR org.apache.hadoop.streaming.StreamJob (main): Error Launching job : Output directory ...
already exists"), which EMR writes to the step's `syslog`. A MapReduce job a custom JAR step's
`spark-submit` starts runs in local mode the same way, in the driver's JVM, as `spark-submit` puts the
copied Hadoop configuration (`HADOOP_CONF_DIR`) on its class path; with the image's, whose `mapred-site.xml`
names YARN, the job would wait for it without end. The cluster's `mapred-site` properties, which "Change
values in the MapReduce application's mapred-site.xml file", come before Floci's `mapreduce.framework.name`
and staging folder, which win, so a job's own `-D mapreduce.framework.name=yarn` still fails, and
`mapreduce.application.classpath`, which the Release Guide gives for a custom JAR's dependencies, changes
nothing, as a job's tasks run in its own JVM. The cluster's `hadoop-log4j` properties, which "Change values
in Hadoop's log4j.properties file", follow the `log4j.properties` lines, a later key winning, and its
`hadoop-env` exports, which "Change values in the Hadoop environment for all Hadoop components", start the
`hadoop-env.sh` the `hadoop` command reads, as given, with no shell expansion, as `spark-env`'s are, ahead
of the image's own lines, which add to `HADOOP_CLASSPATH` rather than set it, so the Release Guide's
`HADOOP_CLASSPATH` of `/path/to/my.jar` keeps the LZO codec the image's `core-site.xml` names; a name a
shell cannot export is left out. A custom JAR step's `spark-submit` reads neither `hadoop-env.sh` nor
Hadoop's `log4j.properties`, so those two do not reach it: a `hadoop-env` `HADOOP_CLASSPATH`, say, is not on
its class path, and it logs as Spark does.
* **S3DistCp**: the image has no `s3-dist-cp`, so a `command-runner.jar` step whose
first argument is `s3-dist-cp`, the Release Guide's form, runs Floci's own program instead, through
`spark-submit` in the step's container, copying through Hadoop's file systems: `--src` and `--dest` take
@@ -264,8 +283,10 @@ but for its bootstrap actions and its storage.
without a scheme, at the cluster's HDFS. The cluster's `spark-log4j2` properties, which "Change values in
Spark's log4j2.properties file", follow the `log4j2.properties` of the folder a `spark-env` export of
`SPARK_CONF_DIR` names, else of the image's, in a copy of the step's own, a later key winning, so
`rootLogger.level` set to `warn` quiets Spark's `INFO` lines. Other classifications (`hadoop-env`,
`spark-metrics`, `spark-log4j` for releases before 6.8.0 and the rest) are not applied.
`rootLogger.level` set to `warn` quiets Spark's `INFO` lines. Its `HADOOP_CONF_DIR` is the copy of the
cluster's Hadoop configuration a command's `hadoop` gets, `mapred-site` included (see **Hadoop streaming
and MapReduce**). Other classifications (`spark-metrics`, `spark-log4j` for releases before 6.8.0,
`mapred-env` and the rest) are not applied.
* **A step's `Properties`**: "Java properties that are set when the step runs. You can use these properties
to pass key-value pairs to your main function", as the API Reference puts it. A custom JAR step's are
system properties of the JVM its main class runs in, which `System.getProperty` reads, passed to
@@ -1395,7 +1395,10 @@ public class EmrService implements Resettable {
EmrSparkSteps.logFolder(cluster, step), null,
EmrSparkSteps.environment(step, cluster.getConfigurations(), SNAPSHOT_MAPPER), List.of(),
storage, EmrSparkSteps.coreSite(cluster.getConfigurations(), SNAPSHOT_MAPPER),
EmrSparkSteps.sparkLog4j2(cluster.getConfigurations(), SNAPSHOT_MAPPER));
EmrSparkSteps.sparkLog4j2(cluster.getConfigurations(), SNAPSHOT_MAPPER),
EmrSparkSteps.mapredSite(cluster.getConfigurations(), SNAPSHOT_MAPPER),
EmrSparkSteps.hadoopLog4j(cluster.getConfigurations(), SNAPSHOT_MAPPER),
EmrSparkSteps.hadoopEnvironment(cluster.getConfigurations(), SNAPSHOT_MAPPER));
StepLaunch launch = new StepLaunch(accountId, region, cluster.getId(), step.getId(), generation);
executing.add(stepKey(accountId, step.getId()));
stepExecutor.execute(() -> runStep(job, launch));
@@ -21,11 +21,11 @@ import java.util.Set;
* What a step runs in the {@code docker} runner mode, in a container of the release's EMR Serverless image.
* A Spark step runs through {@code spark-submit} in local mode: a {@code command-runner.jar} step running
* {@code spark-submit}, as the Management Guide's Spark steps are written, and a custom JAR step, whose main
* class {@code spark-submit} runs with the JAR on its class path. Any other {@code command-runner.jar} step
* runs its command, and a {@code script-runner.jar} step its script, as the Release Guide's "Run commands
* and scripts on an Amazon EMR cluster" describes them, a {@code hadoop-streaming} or {@code hadoop-lzo} one
* through the image's {@code hadoop}, with MapReduce in local mode; an {@code s3-dist-cp} one runs Floci's own
* S3DistCp.
* class {@code spark-submit} runs with the JAR on its class path, a MapReduce job's in local mode. Any other
* {@code command-runner.jar} step runs its command, and a {@code script-runner.jar} step its script, as the
* Release Guide's "Run commands and scripts on an Amazon EMR cluster" describes them, a
* {@code hadoop-streaming} or {@code hadoop-lzo} one through the image's {@code hadoop}, with MapReduce in local
* mode; an {@code s3-dist-cp} one runs Floci's own S3DistCp.
*/
final class EmrSparkSteps {
@@ -53,12 +53,22 @@ final class EmrSparkSteps {
// which will "Change values in Spark's log4j2.properties file".
private static final String CORE_SITE = "core-site";
private static final String SPARK_LOG4J2 = "spark-log4j2";
// And mapred-site, which will "Change values in the MapReduce application's mapred-site.xml file", hadoop-log4j
// "Change values in Hadoop's log4j.properties file", and hadoop-env "Change values in the Hadoop environment for
// all Hadoop components", through its export classification.
private static final String MAPRED_SITE = "mapred-site";
private static final String HADOOP_LOG4J = "hadoop-log4j";
private static final String HADOOP_ENV = "hadoop-env";
// Spark puts a spark.hadoop. setting in its Hadoop configuration, ahead of core-site.xml and hive-site.xml.
private static final String SPARK_HADOOP_PREFIX = "spark.hadoop.";
// spark-submit gives the JVM it runs an application's main class in the Java options of this variable.
private static final String SPARK_SUBMIT_OPTS = "SPARK_SUBMIT_OPTS";
// The Release Guide's command-runner.jar tools that the EMR Serverless image does not have.
private static final Set<String> UNAVAILABLE_TOOLS = Set.of("hive-script", "pig-script");
// EMR's MapReduce jars are in /usr/lib/hadoop-mapreduce, as the image's own hadoop-streaming script has it,
// which the image does not have; its streaming jar is in /usr/lib/hadoop.
private static final Map<String, String> IMAGE_JARS = Map.of(
"/usr/lib/hadoop-mapreduce/hadoop-streaming.jar", "/usr/lib/hadoop/hadoop-streaming.jar");
private static final String S3_DIST_CP = "s3-dist-cp";
static final String S3_DIST_CP_RESOURCE = "emr/s3-dist-cp.py";
// The line that ends the program where the command writes it out.
@@ -94,7 +104,7 @@ final class EmrSparkSteps {
* {@code spark-submit}, without its {@code --master} and {@code --deploy-mode}: options come before the
* application, so one after it is the application's own and kept. For a custom JAR, its main class, if
* the step names one (otherwise {@code spark-submit} reads the JAR's manifest), the JAR and the step's
* arguments.
* arguments. A JAR EMR has in {@code /usr/lib/hadoop-mapreduce} is the image's copy of it.
*/
static List<String> application(EmrStep step) {
String jar = step.getJar();
@@ -111,7 +121,7 @@ final class EmrSparkSteps {
application.add("--class");
application.add(step.getMainClass());
}
application.add(jar);
application.add(IMAGE_JARS.getOrDefault(jar, jar));
application.addAll(args);
return application;
}
@@ -183,6 +193,21 @@ final class EmrSparkSteps {
return properties(configurations, objectMapper, SPARK_LOG4J2);
}
/** The properties of a cluster's {@code mapred-site}, which its steps' MapReduce gets in its mapred-site.xml. */
static Map<String, String> mapredSite(String configurations, ObjectMapper objectMapper) {
return properties(configurations, objectMapper, MAPRED_SITE);
}
/** The properties of a cluster's {@code hadoop-log4j}, which its steps' {@code hadoop} command logs with. */
static Map<String, String> hadoopLog4j(String configurations, ObjectMapper objectMapper) {
return properties(configurations, objectMapper, HADOOP_LOG4J);
}
/** The variables a cluster's {@code hadoop-env} exports, which its steps' {@code hadoop} command gets. */
static Map<String, String> hadoopEnvironment(String configurations, ObjectMapper objectMapper) {
return exports(configurations, objectMapper, HADOOP_ENV);
}
/**
* The environment variables a step's container gets: its cluster's {@code spark-env} exports and, for a
* custom JAR step, its {@code Properties}, "Java properties that are set when the step runs. You can use
@@ -207,8 +232,14 @@ final class EmrSparkSteps {
* classification's properties, or none.
*/
static Map<String, String> sparkEnvironment(String configurations, ObjectMapper objectMapper) {
return exports(configurations, objectMapper, SPARK_ENV);
}
// The properties of the export classification nested in one classification, a later configuration's winning.
private static Map<String, String> exports(String configurations, ObjectMapper objectMapper,
String classification) {
Map<String, String> variables = new LinkedHashMap<>();
for (JsonNode configuration : classified(configurations, objectMapper, SPARK_ENV)) {
for (JsonNode configuration : classified(configurations, objectMapper, classification)) {
for (JsonNode nested : configuration.path("Configurations")) {
if (EXPORT.equals(nested.path("Classification").asText())) {
nested.path("Properties").properties()
@@ -495,7 +495,7 @@ public class EmrServerlessJobRunService implements Resettable {
run.getReleaseLabel(), imageTemplate, customImage(app), dockerNetwork, run.getExecutionRole(),
sparkDefaults, application(sparkSubmit), null, timeout, driverLogFolder(app, run),
driverCloudWatchLogs(app, run), driverEnvironment(sparkProperties), archives(sparkProperties),
null, Map.of(), Map.of());
null, Map.of(), Map.of(), Map.of(), Map.of(), Map.of());
executing.add(run.getJobRunId());
long launchedIn = generation;
runExecutor.execute(() -> execute(job, launchedIn));
@@ -46,6 +46,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.function.BooleanSupplier;
import java.util.regex.Pattern;
import java.util.zip.GZIPOutputStream;
/**
@@ -60,7 +61,8 @@ import java.util.zip.GZIPOutputStream;
* Floci's log and, while it runs, to the run's CloudWatch log streams, when it has some; once it ends, its
* standard output and error go, gzipped, to the run's log folder in Floci's S3, when it has one. An EMR step's
* container mounts its cluster's storage, where {@code hdfs://} paths, and paths without a scheme, lead, and a
* step's {@code hadoop} command reaches Floci's S3 and runs MapReduce in local mode.
* step's {@code hadoop} command, and a MapReduce job its {@code spark-submit} starts, reach Floci's S3 and run
* MapReduce in local mode, with the cluster's Hadoop configuration.
*/
@ApplicationScoped
public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardown {
@@ -70,6 +72,10 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
private static final String SPARK_DEFAULTS_VARIABLE = "FLOCI_SPARK_DEFAULTS";
private static final String HADOOP_SITE_VARIABLE = "FLOCI_HADOOP_SITE";
private static final String SPARK_LOG4J2_VARIABLE = "FLOCI_SPARK_LOG4J2";
private static final String MAPRED_SITE_VARIABLE = "FLOCI_MAPRED_SITE";
private static final String HADOOP_LOG4J_VARIABLE = "FLOCI_HADOOP_LOG4J";
private static final String HADOOP_ENV_VARIABLE = "FLOCI_HADOOP_ENV";
private static final Pattern SHELL_NAME = Pattern.compile("[A-Za-z_][A-Za-z0-9_]*");
// A cluster's HDFS, as Hadoop settings: hdfs:// paths, and those without a scheme ("hdfs:// (or no prefix)"),
// lead to the HDFS folder of the cluster's /mnt volume, through a view of it under the hdfs scheme, as the
// image has no HDFS of its own.
@@ -86,7 +92,7 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
// Where Hadoop's local job runner puts a job's files, -files and -archives among them: a folder of the local
// file system, whose files it then names by their path alone, which leads to the cluster's HDFS.
private static final String MAPRED_STAGING = "/tmp/hadoop/mapred/staging";
// A command's MapReduce runs in the hadoop command's own JVM, as there is no YARN to run it on.
// A step's MapReduce runs in the JVM that starts it, as there is no YARN to run it on.
private static final String MAPRED_SITE = "<property><name>mapreduce.framework.name</name><value>local</value>"
+ "</property><property><name>mapreduce.jobtracker.staging.root.dir</name><value>" + MAPRED_STAGING
+ "</value></property>";
@@ -102,8 +108,13 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
"log4j.appender.console.layout.ConversionPattern=%d{ISO8601} %p %c (%t): %m%n");
// MapReduce, which a streaming job, the LZO indexer and any other hadoop jar run in, is only in Spark's shaded
// Hadoop client, and S3A's AWS SDK only in the jar Spark's own S3A finds it in; links to them make up the hadoop
// command's MapReduce home, whose jars it puts after its own, whatever HADOOP_CLASSPATH a command sets.
// command's MapReduce home, whose jars it puts after its own, whatever HADOOP_CLASSPATH a command sets. The names
// are those of the emr-7.5.0 and emr-7.10.0 images; one another image lacks is named on standard error, as a job
// that needs it fails later, on its class path.
private static final String MAPRED_HOME = "/tmp/floci-mapreduce";
// No source gives AWS's wording for this; it is Floci's.
private static final String MISSING_JAR = "Floci: this image has no $jar, so the hadoop command may not find"
+ " MapReduce or S3A's AWS SDK.";
private static final List<String> MAPRED_JARS = List.of(
"/usr/lib/spark/jars/hadoop-client-api-*.jar",
"/usr/lib/spark/jars/hadoop-client-runtime-*.jar",
@@ -120,25 +131,18 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
" printf '\\n%s\\n' \"$" + SPARK_LOG4J2_VARIABLE + "\" >> \"$conf/log4j2.properties\"",
"fi",
"export SPARK_CONF_DIR=\"$conf\"");
// A Spark step whose job has log4j2.properties lines runs spark-submit after this.
private static final String SPARK_CONF_WRAPPER = String.join("\n", concat(SPARK_CONF_COPY, "exec \"$@\""));
// A command runs after this sets up a Spark configuration of its own, so a spark-submit it starts runs
// locally on Floci's S3: the image's spark-defaults.conf names EMR Serverless's resource manager as its
// master, which a system property cannot override, so its master and that manager's lines give way to
// local mode, Floci's settings and the job's spark-defaults, passed in SPARK_DEFAULTS_VARIABLE.
private static final String COMMAND_WRAPPER = String.join("\n", concat(SPARK_CONF_COPY,
"touch \"$conf/spark-defaults.conf\"",
"sed -i -e '/^spark\\.master[[:space:]]/d' -e '/^spark\\.submit\\.deployMode[[:space:]]/d'"
+ " -e '/^spark\\.submit\\.customResourceManager/d' \"$conf/spark-defaults.conf\"",
"printf '\\n%s\\n' \"$" + SPARK_DEFAULTS_VARIABLE + "\" >> \"$conf/spark-defaults.conf\"",
// On a cluster, the hadoop command gets its HDFS and Floci's S3 too, through a copy of its Hadoop
// configuration (the image's, or the folder a spark-env export names), links followed, whose
// core-site.xml takes in the original's through Hadoop's XInclude, whatever its XML, then
// HADOOP_SITE_VARIABLE's properties, which win (see hadoopSite), and whose mapred-site.xml runs
// MapReduce in local mode the same way. Its script runs only once its HDFS, MapReduce and YARN homes
// name folders that are there, and the image has /usr/lib/hadoop alone, without MapReduce, so the
// MapReduce home is Floci's (see MAPRED_HOME). The image's hdfs command cannot run, so hdfs dfs runs
// as hadoop fs, and its hadoop-streaming names a jar it does not have, so the one it has runs.
// On a cluster, the hadoop command, and MapReduce in a step's spark-submit, get its HDFS and Floci's S3 too,
// through a copy of its Hadoop configuration (the image's, or the folder a spark-env export names), links
// followed, whose core-site.xml takes in the original's through Hadoop's XInclude, whatever its XML, then
// HADOOP_SITE_VARIABLE's properties, which win (see hadoopSite), and whose mapred-site.xml runs MapReduce in local
// mode the same way (see mapredSite). The cluster's hadoop-log4j lines follow the log4j.properties, on a line of
// their own, a later key winning, and its hadoop-env exports start the hadoop-env.sh the hadoop command reads,
// ahead of the image's own lines, which add to HADOOP_CLASSPATH rather than set it, so a HADOOP_CLASSPATH the
// cluster sets keeps the LZO codec the image's core-site.xml names. The hadoop script runs only once its HDFS,
// MapReduce and YARN homes name folders that are there, and the image has /usr/lib/hadoop alone, without
// MapReduce, so the MapReduce home is Floci's (see MAPRED_HOME). The image's hdfs command cannot run, so hdfs dfs
// runs as hadoop fs, and its hadoop-streaming names a jar it does not have, so the one it has runs.
private static final List<String> HADOOP_CONF_SETUP = List.of(
"if [ -n \"${" + HADOOP_SITE_VARIABLE + ":-}\" ]; then",
" hadoop_conf=/tmp/floci-hadoop-conf source_conf=\"${HADOOP_CONF_DIR:-/etc/hadoop/conf}\"",
" mkdir -p \"$hadoop_conf\" /tmp/floci-bin " + MAPRED_HOME,
@@ -153,7 +157,7 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
+ " '</configuration>' > \"$hadoop_conf/$1\"",
" }",
" site core-site.xml \"$" + HADOOP_SITE_VARIABLE + "\"",
" site mapred-site.xml '" + MAPRED_SITE + "'",
" site mapred-site.xml \"$" + MAPRED_SITE_VARIABLE + "\"",
// The local staging folder is a link to the same path in the HDFS folder, so a job's files are where
// their path leads.
" mkdir -p \"" + HDFS_FOLDER + MAPRED_STAGING + "\" \"$(dirname " + MAPRED_STAGING + ")\"",
@@ -161,20 +165,40 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
" if [ ! -s \"$hadoop_conf/log4j.properties\" ]; then",
" printf '%s\\n' '" + String.join("' '", HADOOP_CONSOLE_LOG) + "' > \"$hadoop_conf/log4j.properties\"",
" fi",
" if [ -n \"${" + HADOOP_LOG4J_VARIABLE + ":-}\" ]; then",
" printf '\\n%s\\n' \"$" + HADOOP_LOG4J_VARIABLE + "\" >> \"$hadoop_conf/log4j.properties\"",
" fi",
" if [ -n \"${" + HADOOP_ENV_VARIABLE + ":-}\" ]; then",
" { printf '%s\\n' \"$" + HADOOP_ENV_VARIABLE + "\"; cat \"$hadoop_conf/hadoop-env.sh\" 2>/dev/null; }"
+ " > \"$hadoop_conf/floci-hadoop-env.sh\"",
" mv \"$hadoop_conf/floci-hadoop-env.sh\" \"$hadoop_conf/hadoop-env.sh\"",
" fi",
" printf '%s\\n' '#!/bin/bash' 'if [ \"$1\" = dfs ]; then shift; exec hadoop fs \"$@\"; fi'"
+ " 'echo \"hdfs $1: only hdfs dfs runs here, as hadoop fs\" >&2' 'exit 1' > /tmp/floci-bin/hdfs",
" printf '%s\\n' '#!/bin/bash' 'exec hadoop jar /usr/lib/hadoop/hadoop-streaming.jar \"$@\"'"
+ " > /tmp/floci-bin/hadoop-streaming",
" chmod +x /tmp/floci-bin/hdfs /tmp/floci-bin/hadoop-streaming",
" for jar in " + String.join(" ", MAPRED_JARS) + "; do",
" if [ -f \"$jar\" ]; then ln -sf \"$jar\" " + MAPRED_HOME + "/; fi",
" if [ -f \"$jar\" ]; then ln -sf \"$jar\" " + MAPRED_HOME + "/;",
" else echo \"" + MISSING_JAR + "\" >&2; fi",
" done",
" export HADOOP_CONF_DIR=\"$hadoop_conf\" PATH=\"/tmp/floci-bin:$PATH\"",
" export HADOOP_HDFS_HOME=\"${HADOOP_HDFS_HOME:-/usr/lib/hadoop}\"",
" export HADOOP_MAPRED_HOME=\"${HADOOP_MAPRED_HOME:-" + MAPRED_HOME + "}\"",
" export HADOOP_YARN_HOME=\"${HADOOP_YARN_HOME:-/usr/lib/hadoop}\"",
"fi",
"exec \"$@\""));
"fi");
// A step on a cluster, or one whose job has log4j2.properties lines, runs spark-submit after this.
private static final String SPARK_CONF_WRAPPER = wrapper(SPARK_CONF_COPY, HADOOP_CONF_SETUP);
// A command runs after this sets up a Spark configuration of its own, so a spark-submit it starts runs
// locally on Floci's S3: the image's spark-defaults.conf names EMR Serverless's resource manager as its
// master, which a system property cannot override, so its master and that manager's lines give way to
// local mode, Floci's settings and the job's spark-defaults, passed in SPARK_DEFAULTS_VARIABLE.
private static final String COMMAND_WRAPPER = wrapper(SPARK_CONF_COPY, List.of(
"touch \"$conf/spark-defaults.conf\"",
"sed -i -e '/^spark\\.master[[:space:]]/d' -e '/^spark\\.submit\\.deployMode[[:space:]]/d'"
+ " -e '/^spark\\.submit\\.customResourceManager/d' \"$conf/spark-defaults.conf\"",
"printf '\\n%s\\n' \"$" + SPARK_DEFAULTS_VARIABLE + "\" >> \"$conf/spark-defaults.conf\""),
HADOOP_CONF_SETUP);
// The archives a driver needs in its working directory are put in this folder of its container, each in a
// numbered folder of its own, which the copy creates.
private static final String ARCHIVES_FOLDER = "/tmp/floci-archives";
@@ -276,24 +300,29 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
job.environment()));
// bash -c's script gets "floci" as its $0, and what runs after it as its arguments, "$@".
if (job.command() == null) {
List<String> sparkSubmit = job.sparkLog4j2().isEmpty() ? List.of(SPARK_SUBMIT)
: List.of("/bin/bash", "-c", SPARK_CONF_WRAPPER, "floci", SPARK_SUBMIT);
List<String> sparkSubmit = job.sparkLog4j2().isEmpty() && job.storage() == null
? List.of(SPARK_SUBMIT) : List.of("/bin/bash", "-c", SPARK_CONF_WRAPPER, "floci", SPARK_SUBMIT);
container.withEntrypoint(unpackingFirst(archives, sparkSubmit))
.withCmd(sparkSubmitArguments(job, endpoint));
} else {
container.withEntrypoint(unpackingFirst(archives, List.of("/bin/bash", "-c", COMMAND_WRAPPER, "floci")))
.withCmd(job.command())
.withEnv(SPARK_DEFAULTS_VARIABLE, sparkDefaultsFile(job, endpoint));
if (job.storage() != null) {
container.withEnv(HADOOP_SITE_VARIABLE, hadoopSite(job, endpoint));
}
}
if (!job.sparkLog4j2().isEmpty()) {
container.withEnv(SPARK_LOG4J2_VARIABLE, sparkLog4j2File(job));
}
if (job.storage() != null) {
container.withNamedVolume(job.storage().home(), "/home/hadoop")
.withNamedVolume(job.storage().mnt(), "/mnt");
.withNamedVolume(job.storage().mnt(), "/mnt")
.withEnv(HADOOP_SITE_VARIABLE, hadoopSite(job, endpoint))
.withEnv(MAPRED_SITE_VARIABLE, mapredSite(job));
if (!job.hadoopLog4j().isEmpty()) {
container.withEnv(HADOOP_LOG4J_VARIABLE, hadoopLog4jFile(job));
}
if (!job.hadoopEnvironment().isEmpty()) {
container.withEnv(HADOOP_ENV_VARIABLE, hadoopEnvFile(job));
}
}
ContainerSpec spec = container
.withDockerNetwork(Optional.ofNullable(job.dockerNetwork()))
@@ -633,8 +662,44 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
* reads as a {@code Properties} file, so each key and value is escaped for it.
*/
static String sparkLog4j2File(Job job) {
return propertiesLines(job.sparkLog4j2());
}
/**
* The {@code mapred-site.xml} properties a step's MapReduce gets: its cluster's {@code mapred-site}, then
* Floci's local mode and staging folder, which win, as there is no YARN to run a job on.
*/
static String mapredSite(Job job) {
List<String> properties = new ArrayList<>();
job.mapredSite().forEach((name, value) -> properties.add(siteProperty(name, value)));
properties.add(MAPRED_SITE);
return String.join("\n", properties);
}
/** The lines a step's {@code hadoop} command gets after those of its {@code log4j.properties}. */
static String hadoopLog4jFile(Job job) {
return propertiesLines(job.hadoopLog4j());
}
/**
* The lines that start a step's {@code hadoop-env.sh}: an export of each {@code hadoop-env} variable, as given,
* in single quotes, with no shell expansion, as its {@code spark-env} ones are. A name a shell cannot export
* is left out, as its line would run what it holds.
*/
static String hadoopEnvFile(Job job) {
List<String> lines = new ArrayList<>();
job.sparkLog4j2().forEach((key, value) ->
job.hadoopEnvironment().forEach((name, value) -> {
if (SHELL_NAME.matcher(name).matches()) {
lines.add("export " + name + "='" + value.replace("'", "'\\''") + "'");
}
});
return String.join("\n", lines);
}
// Each property as a line Properties.load reads back as it is.
private static String propertiesLines(Map<String, String> properties) {
List<String> lines = new ArrayList<>();
properties.forEach((key, value) ->
lines.add(propertiesEscaped(key, true) + " = " + propertiesEscaped(value, false)));
return String.join("\n", lines);
}
@@ -644,10 +709,15 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
+ "</value></property>";
}
private static List<String> concat(List<String> lines, String... more) {
List<String> all = new ArrayList<>(lines);
all.addAll(List.of(more));
return all;
// A wrapper's script: the lines of each part, in order, then what it runs.
@SafeVarargs
private static String wrapper(List<String>... parts) {
List<String> lines = new ArrayList<>();
for (List<String> part : parts) {
lines.addAll(part);
}
lines.add("exec \"$@\"");
return String.join("\n", lines);
}
// A backslash starts an escape and a line break ends a setting; in a key, whitespace, '=' and ':' end it,
@@ -67,16 +67,19 @@ public interface SparkJobRunner {
* which those in S3 are unpacked into the container's working directory before the driver starts (empty
* for none); the storage of the cluster it runs on (null for none, as for an EMR Serverless run); the
* {@code core-site.xml} properties its {@code hadoop} command gets, on a cluster, after those of the
* cluster's storage, which they replace where a name is the same (empty for none); and the
* cluster's storage, which they replace where a name is the same (empty for none); the
* {@code log4j2.properties} lines its Spark gets after those of its configuration, which they replace where
* a key is the same (empty for none).
* a key is the same (empty for none); and, on a cluster, the {@code mapred-site.xml} properties its
* MapReduce gets, the {@code log4j.properties} lines and the {@code hadoop-env.sh} exports its {@code hadoop}
* command gets (each empty for none).
*/
record Job(String service, String runId, String accountId, String region, String releaseLabel,
String imageTemplate, String customImage, String dockerNetwork, String executionRole,
Map<String, String> sparkDefaults, List<String> application, List<String> command, Duration timeout,
String logFolder, CloudWatchLogs cloudWatchLogs, Map<String, String> environment,
List<String> archives, Storage storage, Map<String, String> coreSite,
Map<String, String> sparkLog4j2) {
Map<String, String> sparkLog4j2, Map<String, String> mapredSite, Map<String, String> hadoopLog4j,
Map<String, String> hadoopEnvironment) {
}
/**
@@ -128,6 +128,31 @@ class EmrServiceContainerStepsTest {
assertEquals(Map.of("rootLogger.level", "warn"), job.sparkLog4j2());
}
@Test
void aMapReduceCustomJarStepGetsItsClustersMapredSiteHadoopLog4jAndHadoopEnv() {
// The Management Guide's custom JAR step, the word count of Hadoop's MapReduce examples.
EmrStep wordCount = sparkStep("word-count", "CONTINUE");
wordCount.setJar("s3://bucket/jars/hadoop-mapreduce-examples-3.4.0-amzn-1.jar");
wordCount.setArgs(List.of("wordcount", "s3://bucket/input/input.txt", "s3://bucket/output/"));
EmrCluster requested = cluster("mapreduce", true, wordCount);
requested.setConfigurations("""
[{"Classification": "mapred-site", "Properties": {"mapreduce.job.reduces": "1"}},
{"Classification": "hadoop-log4j", "Properties": {"log4j.logger.org.apache.hadoop": "WARN"}},
{"Classification": "hadoop-env", "Configurations": [
{"Classification": "export", "Properties": {"HADOOP_CLASSPATH": "/path/to/my.jar"}}]}]""");
service.runJobFlow(requested, REGION);
fixture.runStepThread();
SparkJobRunner.Job job = runner.jobs.get(0);
assertEquals(List.of("s3://bucket/jars/hadoop-mapreduce-examples-3.4.0-amzn-1.jar", "wordcount",
"s3://bucket/input/input.txt", "s3://bucket/output/"), job.application());
assertEquals(Map.of("mapreduce.job.reduces", "1"), job.mapredSite());
assertEquals(Map.of("log4j.logger.org.apache.hadoop", "WARN"), job.hadoopLog4j());
assertEquals(Map.of("HADOOP_CLASSPATH", "/path/to/my.jar"), job.hadoopEnvironment());
assertEquals(Map.of(), job.environment());
}
@Test
void aStepsLogsGoUnderItsClustersLogUri() {
EmrCluster requested = cluster("logged", true, sparkStep("report", "CONTINUE"));
@@ -48,6 +48,15 @@ class EmrSparkStepsTest {
EmrSparkSteps.application(step("s3://bucket/jobs/report.jar", null)));
}
@Test
void aCustomJarAtEmrsStreamingJarPathRunsTheImagesCopy() {
assertEquals(List.of("/usr/lib/hadoop/hadoop-streaming.jar", "-input", "s3://bucket/in/"),
EmrSparkSteps.application(step("/usr/lib/hadoop-mapreduce/hadoop-streaming.jar", null, "-input",
"s3://bucket/in/")));
assertEquals(List.of("/home/hadoop/hadoop-streaming.jar"),
EmrSparkSteps.application(step("/home/hadoop/hadoop-streaming.jar", null)));
}
@Test
void stepsOtherThanSparkAreNotRun() {
assertNull(EmrSparkSteps.application(step("command-runner.jar", null, "hive-script", "--run-hive-script")));
@@ -231,6 +240,32 @@ class EmrSparkStepsTest {
assertEquals(Map.of(), EmrSparkSteps.sparkLog4j2(null, objectMapper));
}
@Test
void theClustersHadoopClassificationsComeFromItsConfigurations() {
// The Release Guide's mapred-site and hadoop-env examples, the later configuration winning.
String configurations = """
[{"Classification": "mapred-site", "Properties": {"mapred.tasktracker.map.tasks.maximum": "2",
"mapreduce.map.sort.spill.percent": "0.90"}},
{"Classification": "hadoop-log4j", "Properties": {"log4j.logger.org.apache.hadoop": "WARN"}},
{"Classification": "hadoop-env", "Properties": {"IGNORED": "1"}, "Configurations": [
{"Classification": "export", "Properties": {"HADOOP_USER_CLASSPATH_FIRST": "true",
"HADOOP_CLASSPATH": "/path/to/my.jar"}}]},
{"Classification": "mapred-site", "Properties": {"mapreduce.map.sort.spill.percent": "0.80"}},
{"Classification": "spark-env", "Configurations": [
{"Classification": "export", "Properties": {"PYSPARK_PYTHON": "/usr/bin/python3.11"}}]}]
""";
assertEquals(Map.of("mapred.tasktracker.map.tasks.maximum", "2", "mapreduce.map.sort.spill.percent", "0.80"),
EmrSparkSteps.mapredSite(configurations, objectMapper));
assertEquals(Map.of("log4j.logger.org.apache.hadoop", "WARN"),
EmrSparkSteps.hadoopLog4j(configurations, objectMapper));
assertEquals(Map.of("HADOOP_USER_CLASSPATH_FIRST", "true", "HADOOP_CLASSPATH", "/path/to/my.jar"),
EmrSparkSteps.hadoopEnvironment(configurations, objectMapper));
assertEquals(Map.of(), EmrSparkSteps.mapredSite(null, objectMapper));
assertEquals(Map.of(), EmrSparkSteps.hadoopLog4j(null, objectMapper));
assertEquals(Map.of(), EmrSparkSteps.hadoopEnvironment(null, objectMapper));
}
@Test
void aCustomJarStepsPropertiesAreJavaSystemPropertiesOfTheJvmItsMainClassRunsIn() {
EmrStep step = step("s3://bucket/jobs/app.jar", "com.example.Report", "2026-11-01");
@@ -478,10 +478,11 @@ class EmrServerlessSparkRunnerTest {
verify(spec).withEnv(eq("FLOCI_HADOOP_SITE"), argThat(site -> site.startsWith(
"<property><name>fs.s3a.endpoint</name><value>http://floci:4566</value></property>\n")));
verify(spec).withCmd(command);
verify(spec).withEnv("FLOCI_MAPRED_SITE", "<property><name>mapreduce.framework.name</name><value>local"
+ "</value></property><property><name>mapreduce.jobtracker.staging.root.dir</name>"
+ "<value>/tmp/hadoop/mapred/staging</value></property>");
verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains(String.join("\n",
" site mapred-site.xml '<property><name>mapreduce.framework.name</name><value>local</value>"
+ "</property><property><name>mapreduce.jobtracker.staging.root.dir</name>"
+ "<value>/tmp/hadoop/mapred/staging</value></property>'",
" site mapred-site.xml \"$FLOCI_MAPRED_SITE\"",
// The local job runner names a job's files by their path alone, which leads to the cluster's HDFS.
" mkdir -p \"/mnt/hdfs/tmp/hadoop/mapred/staging\" \"$(dirname /tmp/hadoop/mapred/staging)\"",
" ln -sfn \"/mnt/hdfs/tmp/hadoop/mapred/staging\" /tmp/hadoop/mapred/staging\n"))
@@ -492,7 +493,9 @@ class EmrServerlessSparkRunnerTest {
" for jar in /usr/lib/spark/jars/hadoop-client-api-*.jar"
+ " /usr/lib/spark/jars/hadoop-client-runtime-*.jar"
+ " /usr/lib/spark/jars/emr-serverless-spark-goodies.jar; do",
" if [ -f \"$jar\" ]; then ln -sf \"$jar\" /tmp/floci-mapreduce/; fi",
" if [ -f \"$jar\" ]; then ln -sf \"$jar\" /tmp/floci-mapreduce/;",
" else echo \"Floci: this image has no $jar, so the hadoop command may not find MapReduce"
+ " or S3A's AWS SDK.\" >&2; fi",
" done"))
&& entrypoint.get(2).contains(
"\n export HADOOP_MAPRED_HOME=\"${HADOOP_MAPRED_HOME:-/tmp/floci-mapreduce}\"\n")
@@ -503,6 +506,36 @@ class EmrServerlessSparkRunnerTest {
&& entrypoint.get(2).contains("chmod +x /tmp/floci-bin/hdfs /tmp/floci-bin/hadoop-streaming")));
}
@Test
void aJarTheMapReduceHomeLinksThatTheImageLacksIsNamedOnStandardError(@TempDir Path folder) throws Exception {
ContainerBuilder builder = mock(ContainerBuilder.class);
ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(builder.newContainer(anyString())).thenReturn(spec);
runner(builder).run(commandJob(List.of("hadoop", "fs", "-ls", "/"), Map.of(), STORAGE), progress);
ArgumentCaptor<List<String>> entrypoint = ArgumentCaptor.captor();
verify(spec).withEntrypoint(entrypoint.capture());
String script = entrypoint.getValue().get(2);
int start = script.indexOf(" for jar in ");
// The wrapper's loop, on a Spark jars folder of the test's with one of the three jars in it.
Path jars = Files.createDirectory(folder.resolve("jars"));
Path home = Files.createDirectory(folder.resolve("home"));
Files.writeString(jars.resolve("hadoop-client-api-3.4.0-amzn-1.jar"), "");
String loop = script.substring(start, script.indexOf("\n done\n", start) + 7)
.replace("/usr/lib/spark/jars/", jars + "/").replace("/tmp/floci-mapreduce/", home + "/");
BootstrapProcess.Result ended = BootstrapProcess.run(new ProcessBuilder("bash", "-c", loop)
.directory(folder.toFile()));
assertEquals(0, ended.exit(), ended.output());
assertTrue(Files.isSymbolicLink(home.resolve("hadoop-client-api-3.4.0-amzn-1.jar")));
assertTrue(ended.output().contains("Floci: this image has no " + jars + "/hadoop-client-runtime-*.jar, so the"
+ " hadoop command may not find MapReduce or S3A's AWS SDK."), ended.output());
assertTrue(ended.output().contains("Floci: this image has no " + jars + "/emr-serverless-spark-goodies.jar"),
ended.output());
assertFalse(ended.output().contains("hadoop-client-api"), ended.output());
}
@Test
void aStepsHadoopCommandLogsToStandardErrorWhenItsLog4jPropertiesIsEmpty() {
ContainerBuilder builder = mock(ContainerBuilder.class);
@@ -574,7 +607,8 @@ class EmrServerlessSparkRunnerTest {
" printf '\\n%s\\n' \"$FLOCI_SPARK_LOG4J2\" >> \"$conf/log4j2.properties\"",
"fi",
"export SPARK_CONF_DIR=\"$conf\"",
"exec \"$@\""))
"if [ -n \"${FLOCI_HADOOP_SITE:-}\" ]; then"))
&& entrypoint.get(2).endsWith("\nfi\nexec \"$@\"")
&& entrypoint.subList(3, 5).equals(List.of("floci", "/usr/lib/spark/bin/spark-submit"))));
ArgumentMatcher<List<String>> theStepsApplication =
arguments -> arguments.getLast().equals("s3://bucket/jobs/report.py");
@@ -615,15 +649,131 @@ class EmrServerlessSparkRunnerTest {
}
@Test
void aStepWithoutLog4j2LinesRunsSparkSubmitAsItIs() {
void anEmrServerlessRunRunsSparkSubmitAsItIs() {
ContainerBuilder builder = mock(ContainerBuilder.class);
ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(builder.newContainer(anyString())).thenReturn(spec);
runner(builder).run(stepJob(Map.of()), progress);
runner(builder).run(job(null, List.of("s3://bucket/jobs/report.py"), Map.of(), Duration.ZERO), progress);
verify(spec).withEntrypoint(List.of("/usr/lib/spark/bin/spark-submit"));
verify(spec, never()).withEnv(eq("FLOCI_SPARK_LOG4J2"), anyString());
verify(spec, never()).withEnv(eq("FLOCI_HADOOP_SITE"), anyString());
verify(spec, never()).withEnv(eq("FLOCI_MAPRED_SITE"), anyString());
}
@Test
void aCustomJarOrSparkStepsMapReduceRunsLocallyOnTheClustersHadoopConfiguration() {
ContainerBuilder builder = mock(ContainerBuilder.class);
ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(builder.newContainer(anyString())).thenReturn(spec);
SparkJobRunner.Job job = hadoopJob(null, Map.of("mapreduce.job.reduces", "1"), Map.of(), Map.of());
runner(builder).run(job, progress);
// A MapReduce job its main class starts reads mapred-site.xml from HADOOP_CONF_DIR, which spark-submit puts
// on its class path: the image's names YARN, which the job would wait for without end.
verify(spec).withEnv("FLOCI_HADOOP_SITE", EmrServerlessSparkRunner.hadoopSite(job, ENDPOINT));
verify(spec).withEnv("FLOCI_MAPRED_SITE", EmrServerlessSparkRunner.mapredSite(job));
verify(spec, never()).withEnv(eq("FLOCI_SPARK_LOG4J2"), anyString());
verify(spec, never()).withEnv(eq("FLOCI_HADOOP_LOG4J"), anyString());
verify(spec, never()).withEnv(eq("FLOCI_HADOOP_ENV"), anyString());
verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.size() == 5
&& entrypoint.subList(0, 2).equals(List.of("/bin/bash", "-c"))
&& entrypoint.get(2).contains("\n site mapred-site.xml \"$FLOCI_MAPRED_SITE\"\n")
&& entrypoint.get(2).contains(
"\n export HADOOP_CONF_DIR=\"$hadoop_conf\" PATH=\"/tmp/floci-bin:$PATH\"\n")
&& entrypoint.get(2).endsWith("\nfi\nexec \"$@\"")
&& entrypoint.subList(3, 5).equals(List.of("floci", "/usr/lib/spark/bin/spark-submit"))));
ArgumentMatcher<List<String>> theStepsJar =
arguments -> arguments.getLast().equals("s3://bucket/jobs/report.jar");
verify(spec).withCmd(argThat(theStepsJar));
}
@Test
void theClustersMapredSiteComesBeforeFlocisLocalModeAndStagingFolderEscapedForXml() {
Map<String, String> mapredSite = new LinkedHashMap<>();
mapredSite.put("mapreduce.framework.name", "yarn");
mapredSite.put("mapreduce.map.sort.spill.percent", "0.90");
mapredSite.put("floci.note", "a<b & \"c\"");
// A later property wins over an earlier one in the same file, so a job never waits for YARN.
assertEquals(String.join("\n",
"<property><name>mapreduce.framework.name</name><value>yarn</value></property>",
"<property><name>mapreduce.map.sort.spill.percent</name><value>0.90</value></property>",
"<property><name>floci.note</name><value>a&lt;b &amp; &quot;c&quot;</value></property>",
"<property><name>mapreduce.framework.name</name><value>local</value></property>"
+ "<property><name>mapreduce.jobtracker.staging.root.dir</name>"
+ "<value>/tmp/hadoop/mapred/staging</value></property>"),
EmrServerlessSparkRunner.mapredSite(hadoopJob(null, mapredSite, Map.of(), Map.of())));
}
@Test
void aStepsHadoopCommandGetsTheClustersHadoopLog4jLinesAfterItsOwn() throws IOException {
ContainerBuilder builder = mock(ContainerBuilder.class);
ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(builder.newContainer(anyString())).thenReturn(spec);
Map<String, String> hadoopLog4j = new LinkedHashMap<>();
hadoopLog4j.put("log4j.logger.org.apache.hadoop", "WARN");
hadoopLog4j.put("log4j.appender.console.layout.ConversionPattern", " %p %m%n");
SparkJobRunner.Job job = hadoopJob(List.of("hadoop", "fs", "-ls", "/"), Map.of(), hadoopLog4j, Map.of());
runner(builder).run(job, progress);
verify(spec).withEnv("FLOCI_HADOOP_LOG4J", EmrServerlessSparkRunner.hadoopLog4jFile(job));
// After the console logger an empty log4j.properties gets, each on a line of its own.
verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains(String.join("\n",
" fi",
" if [ -n \"${FLOCI_HADOOP_LOG4J:-}\" ]; then",
" printf '\\n%s\\n' \"$FLOCI_HADOOP_LOG4J\" >> \"$hadoop_conf/log4j.properties\"",
" fi\n"))));
// Log4j 1 loads log4j.properties with Properties.load, a later key winning.
Properties loaded = new Properties();
loaded.load(new StringReader(EmrServerlessSparkRunner.hadoopLog4jFile(job)));
assertEquals(2, loaded.size());
assertEquals("WARN", loaded.getProperty("log4j.logger.org.apache.hadoop"));
assertEquals(" %p %m%n", loaded.getProperty("log4j.appender.console.layout.ConversionPattern"));
}
@Test
void aStepsHadoopCommandGetsTheClustersHadoopEnvExportsAsGiven(@TempDir Path folder) throws Exception {
ContainerBuilder builder = mock(ContainerBuilder.class);
ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(builder.newContainer(anyString())).thenReturn(spec);
Map<String, String> hadoopEnvironment = new LinkedHashMap<>();
hadoopEnvironment.put("HADOOP_USER_CLASSPATH_FIRST", "true");
hadoopEnvironment.put("HADOOP_CLASSPATH", "/path/to/my.jar");
hadoopEnvironment.put("HADOOP_OPTS", "-Dnote='it''s' $HOME `id`");
hadoopEnvironment.put("NOT-A-NAME", "left out");
hadoopEnvironment.put("X=1; touch " + folder.resolve("ran") + "; Y", "left out");
SparkJobRunner.Job job = hadoopJob(List.of("hadoop", "fs", "-ls", "/"), Map.of(), Map.of(),
hadoopEnvironment);
runner(builder).run(job, progress);
verify(spec).withEnv("FLOCI_HADOOP_ENV", EmrServerlessSparkRunner.hadoopEnvFile(job));
ArgumentCaptor<List<String>> entrypoint = ArgumentCaptor.captor();
verify(spec).withEntrypoint(entrypoint.capture());
String script = entrypoint.getValue().get(2);
String start = " if [ -n \"${FLOCI_HADOOP_ENV:-}\" ]; then\n";
String lines = script.substring(script.indexOf(start), script.indexOf("\n fi\n", script.indexOf(start)) + 6);
// The wrapper's lines on a hadoop-env.sh that adds to HADOOP_CLASSPATH, as the image's does, then the file
// sourced as the hadoop command sources it: the exports come first, so the image's line keeps them, each
// value as given, with no expansion, and a name a shell cannot export runs nothing.
Files.writeString(folder.resolve("hadoop-env.sh"),
"export HADOOP_CLASSPATH=\"$HADOOP_CLASSPATH:/usr/lib/hadoop-lzo/lib/*\"\n");
Path printed = folder.resolve("printed");
List<String> command = List.of("bash", "-c", "hadoop_conf=" + folder + "\n" + lines
+ ". \"$hadoop_conf/hadoop-env.sh\"\n"
+ "printf '%s\\n' \"$HADOOP_USER_CLASSPATH_FIRST\" \"$HADOOP_CLASSPATH\" \"$HADOOP_OPTS\" > "
+ printed);
ProcessBuilder process = new ProcessBuilder(command).directory(folder.toFile());
process.environment().put("FLOCI_HADOOP_ENV", EmrServerlessSparkRunner.hadoopEnvFile(job));
BootstrapProcess.Result ended = BootstrapProcess.run(process);
assertEquals(0, ended.exit(), ended.output());
assertEquals(List.of("true", "/path/to/my.jar:/usr/lib/hadoop-lzo/lib/*", "-Dnote='it''s' $HOME `id`"),
Files.readAllLines(printed));
assertFalse(Files.exists(folder.resolve("ran")));
}
@Test
@@ -1084,21 +1234,22 @@ class EmrServerlessSparkRunnerTest {
SparkJobRunner.CloudWatchLogs cloudWatchLogs) {
return new SparkJobRunner.Job("emr-serverless", "00f0000000000001", "123456789012", "eu-west-1", "emr-7.5.0",
imageTemplate, null, "floci-network", "arn:aws:iam::123456789012:role/job", sparkDefaults,
application, null, timeout, logFolder, cloudWatchLogs, Map.of(), List.of(), null, Map.of(), Map.of());
application, null, timeout, logFolder, cloudWatchLogs, Map.of(), List.of(), null, Map.of(), Map.of(),
Map.of(), Map.of(), Map.of());
}
private static SparkJobRunner.Job customImageJob(String customImage) {
return new SparkJobRunner.Job("emr-serverless", "00f0000000000001", "123456789012", "eu-west-1", "emr-7.5.0",
null, customImage, "floci-network", "arn:aws:iam::123456789012:role/job", Map.of(),
List.of("s3://bucket/jobs/app.jar"), null, Duration.ZERO, null, null, Map.of(), List.of(), null,
Map.of(), Map.of());
Map.of(), Map.of(), Map.of(), Map.of(), Map.of());
}
private static SparkJobRunner.Job archiveJob(List<String> archives) {
return new SparkJobRunner.Job("emr-serverless", "00f0000000000001", "123456789012", "eu-west-1", "emr-7.5.0",
null, null, "floci-network", "arn:aws:iam::123456789012:role/job", Map.of(),
List.of("s3://bucket/jobs/app.jar"), null, Duration.ZERO, null, null, Map.of(), archives, null,
Map.of(), Map.of());
Map.of(), Map.of(), Map.of(), Map.of(), Map.of());
}
private static SparkJobRunner.Job commandJob(List<String> command, Map<String, String> sparkDefaults) {
@@ -1110,7 +1261,7 @@ class EmrServerlessSparkRunnerTest {
return new SparkJobRunner.Job("emr", "s-1A2B3C4D5E6F7", "123456789012", "eu-west-1", "emr-7.5.0", null,
null, "floci-network", "arn:aws:iam::123456789012:role/job", sparkDefaults, List.of(), command,
Duration.ZERO, null, null, Map.of("PYSPARK_PYTHON", "/usr/bin/python3.11"), List.of(),
storage, Map.of(), Map.of());
storage, Map.of(), Map.of(), Map.of(), Map.of(), Map.of());
}
// A step on a cluster with core-site and spark-log4j2 properties: a command, or a Spark step for a null one.
@@ -1119,7 +1270,17 @@ class EmrServerlessSparkRunnerTest {
return new SparkJobRunner.Job("emr", "s-1A2B3C4D5E6F7", "123456789012", "eu-west-1", "emr-7.5.0", null,
null, "floci-network", "arn:aws:iam::123456789012:role/job", Map.of(),
command == null ? List.of("s3://bucket/jobs/report.py") : List.of(), command, Duration.ZERO, null,
null, Map.of(), List.of(), STORAGE, coreSite, sparkLog4j2);
null, Map.of(), List.of(), STORAGE, coreSite, sparkLog4j2, Map.of(), Map.of(), Map.of());
}
// A step on a cluster with mapred-site, hadoop-log4j and hadoop-env: a command, or a custom JAR for a null one.
private static SparkJobRunner.Job hadoopJob(List<String> command, Map<String, String> mapredSite,
Map<String, String> hadoopLog4j,
Map<String, String> hadoopEnvironment) {
return new SparkJobRunner.Job("emr", "s-1A2B3C4D5E6F7", "123456789012", "eu-west-1", "emr-7.5.0", null,
null, "floci-network", "arn:aws:iam::123456789012:role/job", Map.of(),
command == null ? List.of("s3://bucket/jobs/report.jar") : List.of(), command, Duration.ZERO, null,
null, Map.of(), List.of(), STORAGE, Map.of(), Map.of(), mapredSite, hadoopLog4j, hadoopEnvironment);
}
// A Spark step on a cluster, which has storage.
@@ -1127,6 +1288,6 @@ class EmrServerlessSparkRunnerTest {
return new SparkJobRunner.Job("emr", "s-1A2B3C4D5E6F7", "123456789012", "eu-west-1", "emr-7.5.0", null,
null, "floci-network", "arn:aws:iam::123456789012:role/job", sparkDefaults,
List.of("s3://bucket/jobs/report.py"), null, Duration.ZERO, null, null, Map.of(), List.of(), STORAGE,
Map.of(), Map.of());
Map.of(), Map.of(), Map.of(), Map.of(), Map.of());
}
}