feat(emr): apply a step's Properties, core-site and spark-log4j2 (#7226)

In the docker runner mode a step's HadoopJarStep.Properties, "A list of
Java properties that are set when the step runs. You can use these
properties to pass key-value pairs to your main function", were kept
but never applied, and of a cluster's classifications only
spark-defaults, spark-hive-site and spark-env reached its steps.

Now:

- A custom JAR step's Properties are system properties of the JVM its
  main class runs in, through SPARK_SUBMIT_OPTS, each -Dkey=value in
  single quotes as spark-submit's launcher reads them, after any Java
  options a spark-env export puts there, so a step's own win. A
  command-runner.jar or script-runner.jar step's would be its runner's
  own JVM's, which Floci has none of, and a JVM's system properties do
  not pass to a process it starts, so they go nowhere. The API sentence
  is the only source; emr.md calls this Floci's reading.
- core-site, which will "Change values in Hadoop's core-site.xml file",
  reaches Spark as spark.hadoop. settings ahead of spark-hive-site's,
  as core-site.xml comes ahead of hive-site.xml, with spark-defaults
  winning over both; a command's hadoop command gets it too, after the
  cluster's HDFS settings in its core-site.xml copy, escaped for XML.
- spark-log4j2, which will "Change values in Spark's log4j2.properties
  file", follows the log4j2.properties of the Spark configuration a
  spark-env export of SPARK_CONF_DIR names, else the image's, in a copy
  of the step's own, a later key winning: a Spark step with some runs
  spark-submit after a wrapper that makes the copy, and a command's
  wrapper does the same before its own changes, now from that exported
  folder too, links followed. What is added starts on a line of its
  own, as the image's log4j2.properties has no line break at its end,
  and a value's leading spaces are escaped, as Properties.load would
  skip them.

SparkJobRunner.Job gets coreSite and sparkLog4j2 components, which an
EMR Serverless run leaves empty.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-01 17:17:26 -06:00
1 parent b3bee2d407
commit b4ae0ce9e0
9 files changed
+399 -54

No files matched your search

@@ -1393,8 +1393,9 @@ public class EmrService implements Resettable {
EmrSparkSteps.sparkDefaults(cluster.getConfigurations(), SNAPSHOT_MAPPER),
application != null ? application : List.of(), command, Duration.ZERO,
EmrSparkSteps.logFolder(cluster, step), null,
EmrSparkSteps.sparkEnvironment(cluster.getConfigurations(), SNAPSHOT_MAPPER), List.of(),
storage);
EmrSparkSteps.environment(step, cluster.getConfigurations(), SNAPSHOT_MAPPER), List.of(),
storage, EmrSparkSteps.coreSite(cluster.getConfigurations(), SNAPSHOT_MAPPER),
EmrSparkSteps.sparkLog4j2(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));
@@ -47,8 +47,14 @@ final class EmrSparkSteps {
private static final String SPARK_ENV = "spark-env";
private static final String EXPORT = "export";
private static final String SPARK_HIVE_SITE = "spark-hive-site";
// Spark puts a spark.hadoop. setting in the Hadoop configuration its Hive client reads, ahead of hive-site.xml.
// The release pages' core-site, which will "Change values in Hadoop's core-site.xml file", and spark-log4j2,
// 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";
// 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; its hadoop
// has no MapReduce to run streaming or the LZO indexer.
private static final Set<String> UNAVAILABLE_TOOLS = Set.of("hive-script", "pig-script", "hadoop-streaming",
@@ -151,24 +157,51 @@ final class EmrSparkSteps {
/**
* The Spark properties of a cluster's {@code Configurations}, the JSON array {@code RunJobFlow} was given,
* that a step's {@code spark-submit} gets as defaults: {@code spark-defaults}'s, and {@code spark-hive-site}'s
* as {@code spark.hadoop.} settings, which Spark's Hive client reads as it would {@code hive-site.xml}. A
* {@code spark.hadoop.} setting in {@code spark-defaults} wins over the same one in {@code spark-hive-site},
* as it would over {@code hive-site.xml}.
* that a step's {@code spark-submit} gets as defaults: {@code spark-defaults}'s, and {@code core-site}'s and
* {@code spark-hive-site}'s as {@code spark.hadoop.} settings, which Spark's Hadoop configuration, and its
* Hive client's, take as they would {@code core-site.xml} and {@code hive-site.xml}. A setting in
* {@code spark-hive-site} wins over the same one in {@code core-site}, as {@code hive-site.xml} does, and a
* {@code spark.hadoop.} setting in {@code spark-defaults} over both.
*/
static Map<String, String> sparkDefaults(String configurations, ObjectMapper objectMapper) {
Map<String, String> properties = new LinkedHashMap<>();
for (JsonNode configuration : classified(configurations, objectMapper, SPARK_HIVE_SITE)) {
configuration.path("Properties").properties().forEach(property ->
properties.put(SPARK_HADOOP_PREFIX + property.getKey(), property.getValue().asText()));
}
for (JsonNode configuration : classified(configurations, objectMapper, SPARK_DEFAULTS)) {
configuration.path("Properties").properties()
.forEach(property -> properties.put(property.getKey(), property.getValue().asText()));
}
coreSite(configurations, objectMapper)
.forEach((key, value) -> properties.put(SPARK_HADOOP_PREFIX + key, value));
properties(configurations, objectMapper, SPARK_HIVE_SITE)
.forEach((key, value) -> properties.put(SPARK_HADOOP_PREFIX + key, value));
properties.putAll(properties(configurations, objectMapper, SPARK_DEFAULTS));
return properties;
}
/** The properties of a cluster's {@code core-site}, which its steps' {@code hadoop} command gets too. */
static Map<String, String> coreSite(String configurations, ObjectMapper objectMapper) {
return properties(configurations, objectMapper, CORE_SITE);
}
/** The properties of a cluster's {@code spark-log4j2}, which its steps' Spark gets in its log4j2.properties. */
static Map<String, String> sparkLog4j2(String configurations, ObjectMapper objectMapper) {
return properties(configurations, objectMapper, SPARK_LOG4J2);
}
/**
* 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
* these properties to pass key-value pairs to your main function", as system properties of the JVM its main
* class runs in, after any Java options the cluster exports to {@code spark-submit}, so that a step's own
* win. A {@code command-runner.jar} or {@code script-runner.jar} step's would be those of its runner's JVM,
* which Floci has none of, so they go nowhere.
*/
static Map<String, String> environment(EmrStep step, String configurations, ObjectMapper objectMapper) {
Map<String, String> variables = sparkEnvironment(configurations, objectMapper);
String jar = step.getJar();
if (step.getProperties() != null && !step.getProperties().isEmpty() && jar != null && !jar.isBlank()
&& !named(jar, COMMAND_RUNNER) && !named(jar, SCRIPT_RUNNER)) {
variables.merge(SPARK_SUBMIT_OPTS, javaOptions(step.getProperties()),
(exported, own) -> exported + " " + own);
}
return variables;
}
/**
* The environment variables a cluster's {@code spark-env} exports, its nested {@code export}
* classification's properties, or none.
@@ -186,6 +219,25 @@ final class EmrSparkSteps {
return variables;
}
// The properties of one classification in a cluster's Configurations, a later configuration's winning.
private static Map<String, String> properties(String configurations, ObjectMapper objectMapper,
String classification) {
Map<String, String> properties = new LinkedHashMap<>();
for (JsonNode configuration : classified(configurations, objectMapper, classification)) {
configuration.path("Properties").properties()
.forEach(property -> properties.put(property.getKey(), property.getValue().asText()));
}
return properties;
}
// Each property as a -D option, in single quotes, which spark-submit's launcher reads as a shell would,
// keeping what they hold, a quote itself written '\''.
private static String javaOptions(Map<String, String> properties) {
List<String> options = new ArrayList<>();
properties.forEach((key, value) -> options.add("'" + ("-D" + key + "=" + value).replace("'", "'\\''") + "'"));
return String.join(" ", options);
}
// The configurations of one classification in a cluster's Configurations, in their order.
private static List<JsonNode> classified(String configurations, ObjectMapper objectMapper,
String classification) {
@@ -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);
null, Map.of(), Map.of());
executing.add(run.getJobRunId());
long launchedIn = generation;
runExecutor.execute(() -> execute(job, launchedIn));
@@ -11,6 +11,7 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.ContainerTeardown;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.common.S3Uri;
import io.github.hectorvent.floci.core.common.XmlBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerLaunches;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
@@ -67,6 +68,7 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
private static final String SPARK_SUBMIT = "/usr/lib/spark/bin/spark-submit";
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";
// 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.
@@ -79,29 +81,35 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
private static final SparkSetting FILE_SYSTEM_CHECKPOINTS = new SparkSetting(
"spark.sql.streaming.checkpointFileManagerClass",
"org.apache.spark.sql.execution.streaming.FileSystemBasedCheckpointFileManager");
// HDFS_SETTINGS as core-site.xml properties, for the hadoop command; none needs escaping.
private static final String HADOOP_SITE = String.join("\n", HDFS_SETTINGS.stream()
.map(setting -> "<property><name>" + setting.key() + "</name><value>" + setting.value()
+ "</value></property>")
.toList());
// A Spark configuration of the container's own: a copy of the folder a spark-env export of SPARK_CONF_DIR names,
// else of the image's, links followed, whose log4j2.properties ends with the job's lines, passed in
// SPARK_LOG4J2_VARIABLE, a later line winning. What is added to a file starts on a line of its own, as the
// image's log4j2.properties has no line break at its end.
private static final List<String> SPARK_CONF_COPY = List.of(
"conf=/tmp/floci-spark-conf",
"mkdir -p \"$conf\"",
"cp -rL \"${SPARK_CONF_DIR:-/usr/lib/spark/conf}/.\" \"$conf\" 2>/dev/null",
"if [ -n \"${" + SPARK_LOG4J2_VARIABLE + ":-}\" ]; then",
" 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",
"conf=/tmp/floci-spark-conf",
"mkdir -p \"$conf\"",
"cp -r /usr/lib/spark/conf/. \"$conf\" 2>/dev/null",
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 '%s\\n' \"$" + SPARK_DEFAULTS_VARIABLE + "\" >> \"$conf/spark-defaults.conf\"",
"export SPARK_CONF_DIR=\"$conf\"",
"printf '\\n%s\\n' \"$" + SPARK_DEFAULTS_VARIABLE + "\" >> \"$conf/spark-defaults.conf\"",
// On a cluster, the hadoop command gets its HDFS 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. Its script runs only once its HDFS, MapReduce and YARN homes name folders that are there, and the
// image has /usr/lib/hadoop alone. The image's hdfs command cannot run, so hdfs dfs runs as hadoop fs.
// win (see hadoopSite). Its script runs only once its HDFS, MapReduce and YARN homes name folders that
// are there, and the image has /usr/lib/hadoop alone. The image's hdfs command cannot run, so hdfs dfs
// runs as hadoop fs.
"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",
@@ -121,7 +129,7 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
" export HADOOP_MAPRED_HOME=\"${HADOOP_MAPRED_HOME:-/usr/lib/hadoop}\"",
" export HADOOP_YARN_HOME=\"${HADOOP_YARN_HOME:-/usr/lib/hadoop}\"",
"fi",
"exec \"$@\"");
"exec \"$@\""));
// 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";
@@ -221,18 +229,23 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
.withEnv(environment(
awsEnv.sdkBaselineEnv(job.region(), Optional.empty(), credentials, job.accountId()),
job.environment()));
// bash -c's script gets "floci" as its $0, and what runs after it as its arguments, "$@".
if (job.command() == null) {
container.withEntrypoint(unpackingFirst(archives, List.of(SPARK_SUBMIT)))
List<String> sparkSubmit = job.sparkLog4j2().isEmpty() ? 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 {
// bash -c's script gets "floci" as its $0, and the command as its arguments, "$@".
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, HADOOP_SITE);
container.withEnv(HADOOP_SITE_VARIABLE, hadoopSite(job));
}
}
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");
@@ -554,10 +567,46 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
return file.toString();
}
/**
* The {@code core-site.xml} properties a step's {@code hadoop} command gets: its cluster's HDFS, then the
* job's {@code core-site}, which wins, as a later property does in one file.
*/
static String hadoopSite(Job job) {
List<String> properties = new ArrayList<>();
for (SparkSetting setting : HDFS_SETTINGS) {
properties.add(siteProperty(setting.key(), setting.value()));
}
job.coreSite().forEach((name, value) -> properties.add(siteProperty(name, value)));
return String.join("\n", properties);
}
/**
* The lines a job's Spark gets after those of its configuration's {@code log4j2.properties}, which Log4j
* reads as a {@code Properties} file, so each key and value is escaped for it.
*/
static String sparkLog4j2File(Job job) {
List<String> lines = new ArrayList<>();
job.sparkLog4j2().forEach((key, value) ->
lines.add(propertiesEscaped(key, true) + " = " + propertiesEscaped(value, false)));
return String.join("\n", lines);
}
private static String siteProperty(String name, String value) {
return "<property><name>" + XmlBuilder.escape(name) + "</name><value>" + XmlBuilder.escape(value)
+ "</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 backslash starts an escape and a line break ends a setting; in a key, whitespace, '=' and ':' end it,
// and a leading '#' or '!' makes the line a comment.
// and a leading '#' or '!' makes the line a comment; the spaces a value starts with are skipped.
private static String propertiesEscaped(String text, boolean key) {
StringBuilder escaped = new StringBuilder();
boolean leading = true;
for (char c : text.toCharArray()) {
switch (c) {
case '\\' -> escaped.append("\\\\");
@@ -565,9 +614,11 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
case '\r' -> escaped.append("\\r");
case '\t' -> escaped.append("\\t");
case '\f' -> escaped.append("\\f");
case ' ', '=', ':', '#', '!' -> escaped.append(key ? "\\" : "").append(c);
case ' ' -> escaped.append(key || leading ? "\\ " : " ");
case '=', ':', '#', '!' -> escaped.append(key ? "\\" : "").append(c);
default -> escaped.append(c);
}
leading = leading && c == ' ';
}
return escaped.toString();
}
@@ -65,13 +65,18 @@ public interface SparkJobRunner {
* its container gets besides Floci's own, which they replace where a name is the same (empty for none);
* its {@code spark.archives}, each a path with, after a {@code #}, the directory it is unpacked to, of
* which those in S3 are unpacked into the container's working directory before the driver starts (empty
* for none); and the storage of the cluster it runs on (null for none, as for an EMR Serverless run).
* 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
* {@code log4j2.properties} lines its Spark gets after those of its configuration, which they replace where
* a key is the same (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) {
List<String> archives, Storage storage, Map<String, String> coreSite,
Map<String, String> sparkLog4j2) {
}
/**