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

@@ -104,6 +104,30 @@ class EmrServiceContainerStepsTest {
assertEquals(List.of(cluster.getId()), fixture.clusterStorage.created);
}
@Test
void aCustomJarStepGetsItsPropertiesAndItsClustersCoreSiteAndSparkLog4j2() {
EmrStep report = sparkStep("report", "CONTINUE");
report.setJar("s3://bucket/jobs/report.jar");
report.setMainClass("com.example.Report");
report.setArgs(List.of("2026-11-01"));
report.setProperties(Map.of("report.title", "Nightly"));
EmrCluster requested = cluster("configured", true, report);
requested.setConfigurations("""
[{"Classification": "core-site", "Properties": {"fs.s3a.connection.maximum": "50"}},
{"Classification": "spark-log4j2", "Properties": {"rootLogger.level": "warn"}}]""");
service.runJobFlow(requested, REGION);
fixture.runStepThread();
SparkJobRunner.Job job = runner.jobs.get(0);
assertEquals(List.of("--class", "com.example.Report", "s3://bucket/jobs/report.jar", "2026-11-01"),
job.application());
assertEquals(Map.of("SPARK_SUBMIT_OPTS", "'-Dreport.title=Nightly'"), job.environment());
assertEquals(Map.of("spark.hadoop.fs.s3a.connection.maximum", "50"), job.sparkDefaults());
assertEquals(Map.of("fs.s3a.connection.maximum", "50"), job.coreSite());
assertEquals(Map.of("rootLogger.level", "warn"), job.sparkLog4j2());
}
@Test
void aStepsLogsGoUnderItsClustersLogUri() {
EmrCluster requested = cluster("logged", true, sparkStep("report", "CONTINUE"));
@@ -10,6 +10,7 @@ import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -183,6 +184,80 @@ class EmrSparkStepsTest {
assertEquals(Map.of(), EmrSparkSteps.sparkEnvironment("[{", objectMapper));
}
@Test
void coreSitePropertiesReachSparkAsHadoopSettingsThatSparkHiveSiteAndSparkDefaultsOverride() {
// The Release Guide's core-site example, with two settings the later classifications set again.
String configurations = """
[{"Classification": "core-site", "Properties": {"hadoop.security.groups.cache.secs": "250",
"fs.s3a.connection.maximum": "50", "hive.exec.scratchdir": "/tmp/core"}},
{"Classification": "spark-hive-site", "Properties": {"hive.exec.scratchdir": "/tmp/hive"}},
{"Classification": "spark-defaults", "Properties": {
"spark.hadoop.fs.s3a.connection.maximum": "100"}}]
""";
assertEquals(Map.of("spark.hadoop.hadoop.security.groups.cache.secs", "250",
"spark.hadoop.fs.s3a.connection.maximum", "100",
"spark.hadoop.hive.exec.scratchdir", "/tmp/hive"),
EmrSparkSteps.sparkDefaults(configurations, objectMapper));
// The hadoop command gets core-site's alone, as they are.
assertEquals(Map.of("hadoop.security.groups.cache.secs", "250", "fs.s3a.connection.maximum", "50",
"hive.exec.scratchdir", "/tmp/core"), EmrSparkSteps.coreSite(configurations, objectMapper));
assertEquals(Map.of(), EmrSparkSteps.coreSite(null, objectMapper));
}
@Test
void theClustersSparkLog4j2PropertiesComeFromItsConfigurations() {
String configurations = """
[{"Classification": "spark-log4j2", "Properties": {"rootLogger.level": "warn",
"logger.app.name": "com.example.app", "logger.app.level": "debug"}},
{"Classification": "spark-defaults", "Properties": {"spark.executor.cores": "2"}}]
""";
assertEquals(Map.of("rootLogger.level", "warn", "logger.app.name", "com.example.app",
"logger.app.level", "debug"), EmrSparkSteps.sparkLog4j2(configurations, objectMapper));
assertEquals(Map.of(), EmrSparkSteps.sparkLog4j2(null, objectMapper));
}
@Test
void aCustomJarStepsPropertiesAreJavaSystemPropertiesOfTheJvmItsMainClassRunsIn() {
EmrStep step = step("s3://bucket/jobs/app.jar", "com.example.Report", "2026-11-01");
Map<String, String> properties = new LinkedHashMap<>();
properties.put("report.title", "Nightly report");
properties.put("report.owner", "it's the data team's");
step.setProperties(properties);
String configurations = """
[{"Classification": "spark-env", "Properties": {}, "Configurations": [
{"Classification": "export", "Properties": {"SPARK_SUBMIT_OPTS": "-Dreport.region=eu",
"PYSPARK_PYTHON": "/usr/bin/python3.11"}}]}]
""";
// After the cluster's own, which they win over as later options; each quoted, a quote written '\''.
String own = "'-Dreport.title=Nightly report' '-Dreport.owner=it'\\''s the data team'\\''s'";
assertEquals(Map.of("SPARK_SUBMIT_OPTS", "-Dreport.region=eu " + own, "PYSPARK_PYTHON", "/usr/bin/python3.11"),
EmrSparkSteps.environment(step, configurations, objectMapper));
assertEquals(Map.of("SPARK_SUBMIT_OPTS", own), EmrSparkSteps.environment(step, null, objectMapper));
}
@Test
void aRunnersPropertiesAreItsJvmsWhichFlociHasNoneOf() {
Map<String, String> properties = Map.of("report.title", "Nightly report");
EmrStep sparkSubmit = step("command-runner.jar", null, "spark-submit", "s3://bucket/jobs/report.py");
EmrStep script = step("s3://eu-west-1.elasticmapreduce/libs/script-runner/script-runner.jar", null,
"s3://bucket/scripts/prepare.sh");
sparkSubmit.setProperties(properties);
script.setProperties(properties);
String configurations = """
[{"Classification": "spark-env", "Configurations": [
{"Classification": "export", "Properties": {"PYSPARK_PYTHON": "/usr/bin/python3.11"}}]}]
""";
assertEquals(Map.of("PYSPARK_PYTHON", "/usr/bin/python3.11"),
EmrSparkSteps.environment(sparkSubmit, configurations, objectMapper));
assertEquals(Map.of("PYSPARK_PYTHON", "/usr/bin/python3.11"),
EmrSparkSteps.environment(script, configurations, objectMapper));
assertEquals(Map.of(), EmrSparkSteps.environment(step("s3://bucket/jobs/app.jar", null), null, objectMapper));
}
private static EmrStep step(String jar, String mainClass, String... args) {
EmrStep step = new EmrStep();
step.setJar(jar);
@@ -28,6 +28,7 @@ import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatcher;
import org.mockito.InOrder;
import java.io.ByteArrayInputStream;
@@ -457,6 +458,117 @@ class EmrServerlessSparkRunnerTest {
"export HADOOP_CONF_DIR=\"$hadoop_conf\" PATH=\"/tmp/floci-bin:$PATH\"")));
}
@Test
void aStepsHadoopCommandGetsItsClustersCoreSiteAfterItsHdfsEscapedForXml() {
Map<String, String> coreSite = new LinkedHashMap<>();
coreSite.put("fs.permissions.umask-mode", "077");
coreSite.put("floci.note", "a<b & \"c\" 'd'");
// A later property wins over an earlier one in the same file.
assertEquals(String.join("\n",
"<property><name>fs.defaultFS</name><value>hdfs:///</value></property>",
"<property><name>fs.hdfs.impl</name><value>org.apache.hadoop.fs.viewfs.ViewFileSystemOverloadScheme"
+ "</value></property>",
"<property><name>fs.viewfs.mounttable.default.linkFallback</name><value>file:///mnt/hdfs</value>"
+ "</property>",
"<property><name>fs.permissions.umask-mode</name><value>077</value></property>",
"<property><name>floci.note</name><value>a&lt;b &amp; &quot;c&quot; &apos;d&apos;</value></property>"),
EmrServerlessSparkRunner.hadoopSite(
clusterJob(List.of("hadoop", "fs", "-ls", "/"), coreSite, Map.of())));
}
@Test
void aSparkStepWithLog4j2LinesRunsSparkSubmitOnAConfigurationOfItsOwnThatEndsWithThem() {
ContainerBuilder builder = mock(ContainerBuilder.class);
ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(builder.newContainer(anyString())).thenReturn(spec);
Map<String, String> sparkLog4j2 = new LinkedHashMap<>();
sparkLog4j2.put("rootLogger.level", "warn");
sparkLog4j2.put("logger.app.name", "com.example.app");
runner(builder).run(clusterJob(null, Map.of(), sparkLog4j2), progress);
verify(spec).withEnv("FLOCI_SPARK_LOG4J2", "rootLogger.level = warn\nlogger.app.name = com.example.app");
verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.size() == 5
&& entrypoint.subList(0, 2).equals(List.of("/bin/bash", "-c"))
&& entrypoint.get(2).startsWith(String.join("\n",
"conf=/tmp/floci-spark-conf",
"mkdir -p \"$conf\"",
"cp -rL \"${SPARK_CONF_DIR:-/usr/lib/spark/conf}/.\" \"$conf\" 2>/dev/null",
"if [ -n \"${FLOCI_SPARK_LOG4J2:-}\" ]; then",
" printf '\\n%s\\n' \"$FLOCI_SPARK_LOG4J2\" >> \"$conf/log4j2.properties\"",
"fi",
"export SPARK_CONF_DIR=\"$conf\"",
"exec \"$@\""))
&& 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");
verify(spec).withCmd(argThat(theStepsApplication));
}
@Test
void aStepsSparkConfigurationIsACopyOfTheFolderASparkEnvExportNamesElseTheImages() {
ContainerBuilder builder = mock(ContainerBuilder.class);
ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(builder.newContainer(anyString())).thenReturn(spec);
String copy = "\ncp -rL \"${SPARK_CONF_DIR:-/usr/lib/spark/conf}/.\" \"$conf\" 2>/dev/null\n";
runner(builder).run(clusterJob(null, Map.of(), Map.of("rootLogger.level", "warn")), progress);
runner(builder).run(clusterJob(List.of("spark-submit", "s3://bucket/jobs/report.py"), Map.of(), Map.of()),
progress);
// A Spark step's wrapper, then a command's, links followed as a folder a bootstrap action wrote may hold them.
verify(spec, times(2)).withEntrypoint(argThat(entrypoint -> entrypoint.size() > 2
&& entrypoint.get(2).contains(copy)));
}
@Test
void aCommandsSparkGetsTheJobsLog4j2LinesToo() {
ContainerBuilder builder = mock(ContainerBuilder.class);
ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(builder.newContainer(anyString())).thenReturn(spec);
runner(builder).run(clusterJob(List.of("spark-submit", "s3://bucket/jobs/report.py"), Map.of(),
Map.of("rootLogger.level", "error")), progress);
verify(spec).withEnv("FLOCI_SPARK_LOG4J2", "rootLogger.level = error");
verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains(
" printf '\\n%s\\n' \"$FLOCI_SPARK_LOG4J2\" >> \"$conf/log4j2.properties\"\n")
&& entrypoint.get(2).contains(
"printf '\\n%s\\n' \"$FLOCI_SPARK_DEFAULTS\" >> \"$conf/spark-defaults.conf\"")
&& entrypoint.get(2).endsWith("exec \"$@\"")));
}
@Test
void aStepWithoutLog4j2LinesRunsSparkSubmitAsItIs() {
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);
verify(spec).withEntrypoint(List.of("/usr/lib/spark/bin/spark-submit"));
verify(spec, never()).withEnv(eq("FLOCI_SPARK_LOG4J2"), anyString());
}
@Test
void log4j2LinesReachLog4jAsTheClusterGaveThem() throws IOException {
Map<String, String> sparkLog4j2 = new LinkedHashMap<>();
sparkLog4j2.put("appender.file.fileName", "C:\\logs\\spark.log");
sparkLog4j2.put("odd key=with:separators", "#not a comment\nnor a second line");
sparkLog4j2.put("appender.console.layout.pattern", " %m%n");
// Log4j's PropertiesConfigurationFactory loads log4j2.properties with Properties.load.
Properties loaded = new Properties();
loaded.load(new StringReader(
EmrServerlessSparkRunner.sparkLog4j2File(clusterJob(null, Map.of(), sparkLog4j2))));
assertEquals("C:\\logs\\spark.log", loaded.getProperty("appender.file.fileName"));
assertEquals("#not a comment\nnor a second line", loaded.getProperty("odd key=with:separators"));
// Properties.load skips the spaces after the separator, so a value's own leading ones are escaped.
assertEquals(" %m%n", loaded.getProperty("appender.console.layout.pattern"));
}
@Test
void aCommandsOwnSparkSubmitRunsLocallyOnFlocisS3WithTheJobsSparkDefaults() {
assertEquals(String.join("\n",
@@ -896,19 +1008,21 @@ 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);
application, null, timeout, logFolder, cloudWatchLogs, Map.of(), List.of(), null, 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);
List.of("s3://bucket/jobs/app.jar"), null, Duration.ZERO, null, null, Map.of(), List.of(), null,
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);
List.of("s3://bucket/jobs/app.jar"), null, Duration.ZERO, null, null, Map.of(), archives, null,
Map.of(), Map.of());
}
private static SparkJobRunner.Job commandJob(List<String> command, Map<String, String> sparkDefaults) {
@@ -920,13 +1034,23 @@ 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);
storage, 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.
private static SparkJobRunner.Job clusterJob(List<String> command, Map<String, String> coreSite,
Map<String, String> sparkLog4j2) {
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);
}
// A Spark step on a cluster, which has storage.
private static SparkJobRunner.Job stepJob(Map<String, String> sparkDefaults) {
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);
List.of("s3://bucket/jobs/report.py"), null, Duration.ZERO, null, null, Map.of(), List.of(), STORAGE,
Map.of(), Map.of());
}
}