diff --git a/docs/services/emr.md b/docs/services/emr.md index 2c7d2a6a8d..b6074701d0 100644 --- a/docs/services/emr.md +++ b/docs/services/emr.md @@ -129,9 +129,10 @@ but for its bootstrap actions and its storage. run with the step's other arguments; a path not in S3 is run as it is, a bare name from `/home/hadoop` when a file there has it, one a former step left there included. `hadoop fs` and `hdfs dfs` reach the cluster's HDFS (see **Storage**). A `spark-submit` they start runs in local mode on Floci's S3 with the - cluster's `spark-defaults` and `spark-hive-site`, which Floci puts in a Spark configuration of its own, - ahead of the image's EMR Serverless master; its own `--master yarn` or `--deploy-mode cluster` fails, as - there is no YARN. + cluster's `spark-defaults`, `core-site`, `spark-hive-site` and `spark-log4j2`, which Floci puts in a Spark + configuration of its own, a copy of the folder a `spark-env` export of `SPARK_CONF_DIR` names, else of the + image's, ahead of the image's EMR Serverless master; its own `--master yarn` or `--deploy-mode cluster` + fails, as there is no YARN. * **Storage**: a cluster's primary node keeps its disks while the cluster lives, and so does Floci: each step's container mounts the cluster's two Docker volumes, one at `/home/hadoop` and one at `/mnt`, so what a step leaves there is there for the steps after it, and for steps running at the same time. HDFS, "best @@ -139,9 +140,10 @@ but for its bootstrap actions and its storage. is the `hdfs` folder of `/mnt`. In Spark, `hdfs://` paths, and paths without a scheme ("hdfs:// (or no prefix)"), lead there through Hadoop's `ViewFileSystemOverloadScheme`, a relative path under `/user/hadoop` as in HDFS, and a structured streaming query keeps its checkpoints through Spark's file - system checkpoint manager; the cluster's `spark-defaults` can set any of these otherwise. A command's - `hadoop fs` gets the same, through a copy of the image's Hadoop configuration, or of the folder a - `spark-env` export of `HADOOP_CONF_DIR` names; the image's `hdfs` command cannot run, so `hdfs dfs` runs + system checkpoint manager; the cluster's `spark-defaults` and `core-site` can set any of these otherwise. + A command's `hadoop fs` gets the same, through a copy of the image's Hadoop configuration, or of the + folder a `spark-env` export of `HADOOP_CONF_DIR` names, with the cluster's `core-site` after it, which + wins; the image's `hdfs` command cannot run, so `hdfs dfs` runs as `hadoop fs`, and its other commands fail. What the bootstrap actions left in `/home/hadoop` or `/mnt` comes with the image the steps run in, and Docker copies it into the volumes when the first step starts. The volumes go once the cluster has ended and its last step is done @@ -234,14 +236,25 @@ but for its bootstrap actions and its storage. driver, and start no other step; a driver a hard stop left running is removed when the EMR service starts, before any step can start, unless `reconcile-containers-on-startup` is off. * **What `spark-submit` gets**: the step's arguments, after the `spark-defaults` properties of the - cluster's `Configurations` and its `spark-hive-site` ones as `spark.hadoop.` settings, which Spark's Hive - client reads as it would `hive-site.xml`, so the Management Guide's `hive.metastore.client.factory.class` - for the Glue Data Catalog applies; a `spark.hadoop.` setting in `spark-defaults` wins over the same one in - `spark-hive-site`. `s3://` and `s3a://` paths reach Floci's S3 through S3A, on releases + cluster's `Configurations` and its `core-site` and `spark-hive-site` ones as `spark.hadoop.` settings, + which Spark's Hadoop configuration, and its Hive client's, take as they would `core-site.xml` and + `hive-site.xml`, so the Management Guide's `hive.metastore.client.factory.class` for the Glue Data Catalog + applies; a `spark-hive-site` setting wins over the same one in `core-site`, and a `spark.hadoop.` setting + in `spark-defaults` over both. `s3://` and `s3a://` paths reach Floci's S3 through S3A, on releases before 7.10.0 too, where `s3://` would otherwise be EMRFS, so the application and its files can be read from there; the Glue Data Catalog client is pointed at Floci's Glue, and `hdfs://` paths, and those - without a scheme, at the cluster's HDFS. A step's `Properties` are not applied, nor are the other - classifications (`core-site`, `hadoop-env`, `spark-log4j2` and the rest). + 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. +* **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 + `spark-submit` in `SPARK_SUBMIT_OPTS` 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 those of the runner's own JVM, + which Floci has none of, and a JVM's system properties do not pass to a process it starts, so they go + nowhere. This is Floci's reading, as that sentence is the only source. * **`spark-env`**: the variables the cluster's `spark-env` exports, in its nested `export` classification, are in each step's container environment, `PYSPARK_PYTHON` or `JAVA_HOME` say, replacing any of Floci's own with the same name. They are set as given, with no shell expansion of a `$VARIABLE` in diff --git a/src/main/java/io/github/hectorvent/floci/services/emr/EmrService.java b/src/main/java/io/github/hectorvent/floci/services/emr/EmrService.java index 03330f2627..bed7b64828 100644 --- a/src/main/java/io/github/hectorvent/floci/services/emr/EmrService.java +++ b/src/main/java/io/github/hectorvent/floci/services/emr/EmrService.java @@ -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)); diff --git a/src/main/java/io/github/hectorvent/floci/services/emr/EmrSparkSteps.java b/src/main/java/io/github/hectorvent/floci/services/emr/EmrSparkSteps.java index 1aaef4f472..8173916aa6 100644 --- a/src/main/java/io/github/hectorvent/floci/services/emr/EmrSparkSteps.java +++ b/src/main/java/io/github/hectorvent/floci/services/emr/EmrSparkSteps.java @@ -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 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 sparkDefaults(String configurations, ObjectMapper objectMapper) { Map 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 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 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 environment(EmrStep step, String configurations, ObjectMapper objectMapper) { + Map 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 properties(String configurations, ObjectMapper objectMapper, + String classification) { + Map 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 properties) { + List 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 classified(String configurations, ObjectMapper objectMapper, String classification) { diff --git a/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessJobRunService.java b/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessJobRunService.java index 3c1d376027..d18574acf5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessJobRunService.java +++ b/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessJobRunService.java @@ -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)); diff --git a/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunner.java b/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunner.java index bd255affc8..990edab8c8 100644 --- a/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunner.java +++ b/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunner.java @@ -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 -> "" + setting.key() + "" + setting.value() - + "") - .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 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 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 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 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 "" + XmlBuilder.escape(name) + "" + XmlBuilder.escape(value) + + ""; + } + + private static List concat(List lines, String... more) { + List 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(); } diff --git a/src/main/java/io/github/hectorvent/floci/services/emrserverless/SparkJobRunner.java b/src/main/java/io/github/hectorvent/floci/services/emrserverless/SparkJobRunner.java index f3885996da..ffc3c0e1a3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/emrserverless/SparkJobRunner.java +++ b/src/main/java/io/github/hectorvent/floci/services/emrserverless/SparkJobRunner.java @@ -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 sparkDefaults, List application, List command, Duration timeout, String logFolder, CloudWatchLogs cloudWatchLogs, Map environment, - List archives, Storage storage) { + List archives, Storage storage, Map coreSite, + Map sparkLog4j2) { } /** diff --git a/src/test/java/io/github/hectorvent/floci/services/emr/EmrServiceContainerStepsTest.java b/src/test/java/io/github/hectorvent/floci/services/emr/EmrServiceContainerStepsTest.java index b6ba3ec839..bb235d260e 100644 --- a/src/test/java/io/github/hectorvent/floci/services/emr/EmrServiceContainerStepsTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/emr/EmrServiceContainerStepsTest.java @@ -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")); diff --git a/src/test/java/io/github/hectorvent/floci/services/emr/EmrSparkStepsTest.java b/src/test/java/io/github/hectorvent/floci/services/emr/EmrSparkStepsTest.java index c06107af5f..3f635404b3 100644 --- a/src/test/java/io/github/hectorvent/floci/services/emr/EmrSparkStepsTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/emr/EmrSparkStepsTest.java @@ -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 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 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); diff --git a/src/test/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunnerTest.java b/src/test/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunnerTest.java index a6fe10e4e2..f4d64c205d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunnerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunnerTest.java @@ -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 coreSite = new LinkedHashMap<>(); + coreSite.put("fs.permissions.umask-mode", "077"); + coreSite.put("floci.note", "afs.defaultFShdfs:///", + "fs.hdfs.implorg.apache.hadoop.fs.viewfs.ViewFileSystemOverloadScheme" + + "", + "fs.viewfs.mounttable.default.linkFallbackfile:///mnt/hdfs" + + "", + "fs.permissions.umask-mode077", + "floci.notea<b & "c" 'd'"), + 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 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> 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 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 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 command, Map 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 command, Map coreSite, + Map 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 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()); } }