feat(emr): apply a cluster's spark-env and spark-hive-site to its steps (#7047)

In the docker runner mode a step's spark-submit got the spark-defaults
of the cluster's Configurations, and nothing else from them. The
Release Guide's other two Spark classifications that change what a job
does were ignored:

- spark-env "Sets values in the spark-env.sh file", through its nested
  export classification ("If any classification ends in env, use the
  export sub-classification"). It is how a cluster picks the Python
  PySpark runs (PYSPARK_PYTHON) or the JVM (JAVA_HOME). Its exports are
  now the step container's environment variables, replacing any of
  Floci's own with the same name. The image's spark-env.sh only
  defaults PYSPARK_PYTHON, PYSPARK_DRIVER_PYTHON, SPARK_HOME and
  HADOOP_CONF_DIR, so the exports win there.
- spark-hive-site "Sets values in the hive-site.xml for Spark", as the
  Management Guide uses it to put Spark's tables in the Glue Data
  Catalog (hive.metastore.client.factory.class). Its properties now
  reach spark-submit as spark.hadoop. settings, which Spark's Hive
  client reads as it would hive-site.xml; a spark.hadoop. setting in
  spark-defaults wins over them, as it would over hive-site.xml.

SparkJobRunner.Job carries the environment, which an EMR Serverless run
leaves empty. The exports are set as given, with no shell expansion,
and a command or script step sees them too; emr.md says so.

Separately, the pattern EcrRegistryManager reads an ECR image's Region
with, which EMR Serverless checks an application's custom image
against, now names the hosts it takes: AwsPartitions.dnsSuffixRegex()
for AWS's, as AWS_ECR_URI does, and localhost or localhost.floci.io
with a port for the repositoryUri Floci's ECR hands out. It took any
host after the Region before, so an image on a registry that only
looks like ECR's (<account>.dkr.ecr.<region>.registry.internal/...)
was refused for being in another Region.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-31 10:27:25 -05:00
1 parent bfd3bcbbce
commit 264513650c
12 files changed
+159 -28

No files matched your search

+13 -3
View File
@@ -129,7 +129,7 @@ but for its bootstrap actions.
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, though nothing a former step wrote is there, each step having a container of
its own. A `spark-submit` they start runs in local mode on Floci's S3 with the cluster's
`spark-defaults`, which Floci puts in a Spark configuration of its own, ahead of the image's EMR
`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.
* **HTTPS**: with [TLS](../configuration/tls.md) on, each step's container, and the bootstrap actions'
one, also gets Floci's CA bundle as a Java trust store, which every JVM in it uses, as an
@@ -178,10 +178,20 @@ but for its bootstrap actions.
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`. `s3://` and `s3a://` paths reach Floci's S3 through S3A, on releases
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
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. A step's `Properties` are not
applied.
applied, nor are the other classifications (`core-site`, `hadoop-env`, `spark-log4j2` and the rest).
* **`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
them, and a command or script sees them too, where EMR writes them in `spark-env.sh`, which only Spark's
own scripts read. The image's `spark-env.sh` gives `PYSPARK_PYTHON`, `PYSPARK_DRIVER_PYTHON`,
`SPARK_HOME` and `HADOOP_CONF_DIR` only a default, so the exports win there, but a variable it sets
outright, such as `AWS_STS_REGIONAL_ENDPOINTS`, keeps the image's value in `spark-submit`.
* **Credentials**: the container gets a session for the step's `ExecutionRoleArn`, or else for the role
of the cluster's `JobFlowRole` instance profile, when IAM knows it and the profile holds one role,
and otherwise the account's placeholder credentials, with `AWS_ENDPOINT_URL` pointing at Floci.
@@ -68,13 +68,18 @@ public class EcrRegistryManager {
private static final Pattern AWS_ECR_URI = Pattern.compile(
"^([0-9]{12})\\.dkr\\.ecr\\.([a-z0-9-]+)\\." + AwsPartitions.dnsSuffixRegex() + "/(.+)$");
/** The host and port of a {@code repositoryUri} Floci's ECR hands out. */
private static final String FLOCI_REGISTRY_HOST = "localhost(?:\\.floci\\.io)?:[0-9]+";
/**
* The Region of an image in an ECR repository: in {@code <account>.dkr.ecr.<region>.<host>/<repo>}, AWS's
* form and Floci's {@code repositoryUri} in the default URI style, or in
* {@code localhost:<port>/<account>/<region>/<repo>}, Floci's in the path style.
* The Region of an image in an ECR repository: in {@code <account>.dkr.ecr.<region>.<dnsSuffix>/<repo>}, AWS's
* form in any partition, or in {@code <account>.dkr.ecr.<region>.localhost:<port>/<repo>}, Floci's
* {@code repositoryUri} in the default URI style, or in {@code localhost:<port>/<account>/<region>/<repo>},
* Floci's in the path style.
*/
private static final Pattern ECR_IMAGE_REGION = Pattern.compile("^(?:[0-9]{12}\\.dkr\\.ecr\\.([a-z0-9-]+)\\.[^/]+"
+ "|localhost(?:\\.floci\\.io)?:[0-9]+/[0-9]{12}/([a-z0-9-]+))/.+$");
private static final Pattern ECR_IMAGE_REGION = Pattern.compile("^(?:[0-9]{12}\\.dkr\\.ecr\\.([a-z0-9-]+)\\.(?:"
+ AwsPartitions.dnsSuffixRegex() + "|" + FLOCI_REGISTRY_HOST + ")"
+ "|" + FLOCI_REGISTRY_HOST + "/[0-9]{12}/([a-z0-9-]+))/.+$");
/**
* The container name actually in use. Differs from {@link #registryContainerName()} only when
@@ -1321,7 +1321,8 @@ public class EmrService implements Resettable {
dockerNetwork, executionRole(cluster, step, accountId),
EmrSparkSteps.sparkDefaults(cluster.getConfigurations(), SNAPSHOT_MAPPER),
application != null ? application : List.of(), command, Duration.ZERO,
EmrSparkSteps.logFolder(cluster, step), null);
EmrSparkSteps.logFolder(cluster, step), null,
EmrSparkSteps.sparkEnvironment(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));
@@ -37,6 +37,14 @@ final class EmrSparkSteps {
private static final Set<String> SWITCHES = Set.of("--help", "-h", "--supervise", "--usage-error", "--verbose",
"-v", "--version");
private static final String SPARK_DEFAULTS = "spark-defaults";
// The Release Guide's Spark classifications: spark-env "Sets values in the spark-env.sh file", through its
// export classification ("If any classification ends in env, use the export sub-classification"), and
// spark-hive-site "Sets values in the hive-site.xml for Spark".
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.
private static final String SPARK_HADOOP_PREFIX = "spark.hadoop.";
// The Release Guide's command-runner.jar tools that the EMR Serverless image does not have; its hadoop
// has no HDFS to run streaming or the LZO indexer against.
private static final Set<String> UNAVAILABLE_TOOLS = Set.of("hive-script", "pig-script", "hadoop-streaming",
@@ -128,26 +136,60 @@ final class EmrSparkSteps {
}
/**
* The {@code spark-defaults} properties of a cluster's {@code Configurations}, the JSON array
* {@code RunJobFlow} was given, or none.
* 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}.
*/
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()));
}
return properties;
}
/**
* The environment variables a cluster's {@code spark-env} exports, its nested {@code export}
* classification's properties, or none.
*/
static Map<String, String> sparkEnvironment(String configurations, ObjectMapper objectMapper) {
Map<String, String> variables = new LinkedHashMap<>();
for (JsonNode configuration : classified(configurations, objectMapper, SPARK_ENV)) {
for (JsonNode nested : configuration.path("Configurations")) {
if (EXPORT.equals(nested.path("Classification").asText())) {
nested.path("Properties").properties()
.forEach(property -> variables.put(property.getKey(), property.getValue().asText()));
}
}
}
return variables;
}
// The configurations of one classification in a cluster's Configurations, in their order.
private static List<JsonNode> classified(String configurations, ObjectMapper objectMapper,
String classification) {
List<JsonNode> matching = new ArrayList<>();
if (configurations == null) {
return properties;
return matching;
}
try {
for (JsonNode configuration : objectMapper.readTree(configurations)) {
if (SPARK_DEFAULTS.equals(configuration.path("Classification").asText())) {
configuration.path("Properties").properties()
.forEach(property -> properties.put(property.getKey(), property.getValue().asText()));
if (classification.equals(configuration.path("Classification").asText())) {
matching.add(configuration);
}
}
} catch (JsonProcessingException ignored) {
// RunJobFlow stored the array as it came; one that does not parse holds no properties to apply.
return properties;
return matching;
}
return properties;
return matching;
}
private static List<String> withoutMasterOrDeployMode(List<String> arguments) {
@@ -483,7 +483,7 @@ public class EmrServerlessJobRunService implements Resettable {
SparkJobRunner.Job job = new SparkJobRunner.Job(SERVICE, run.getJobRunId(), arn.accountId(), arn.region(),
run.getReleaseLabel(), imageTemplate, customImage(app), dockerNetwork, run.getExecutionRole(),
sparkDefaults(app, run), application(run.getJobDriver().getSparkSubmit()), null, timeout,
driverLogFolder(app, run), driverCloudWatchLogs(app, run));
driverLogFolder(app, run), driverCloudWatchLogs(app, run), Map.of());
executing.add(run.getJobRunId());
long launchedIn = generation;
runExecutor.execute(() -> execute(job, launchedIn));
@@ -145,7 +145,9 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
String endpoint = awsEnv.flociEndpoint();
ContainerBuilder.Builder container = containerBuilder.newContainer(launchImage(job))
.withName(ContainerStorageHelper.dockerName(config, job.service() + "-" + job.runId()))
.withEnv(awsEnv.sdkBaselineEnv(job.region(), Optional.empty(), credentials, job.accountId()));
.withEnv(environment(
awsEnv.sdkBaselineEnv(job.region(), Optional.empty(), credentials, job.accountId()),
job.environment()));
if (job.command() == null) {
container.withEntrypoint(List.of(SPARK_SUBMIT)).withCmd(sparkSubmitArguments(job, endpoint));
} else {
@@ -308,6 +310,17 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
return template.formatted(releaseLabel);
}
/** A driver's environment: Floci's own variables, then the job's, one of which replaces Floci's of its name. */
static List<String> environment(List<String> flocis, Map<String, String> jobs) {
Map<String, String> byName = new LinkedHashMap<>();
for (String variable : flocis) {
int equals = variable.indexOf('=');
byName.put(equals < 0 ? variable : variable.substring(0, equals), variable);
}
jobs.forEach((name, value) -> byName.put(name, name + "=" + value));
return new ArrayList<>(byName.values());
}
/**
* The image a run's driver starts from: the release's, or the template's, or the application's custom
* image. A custom image's ECR URI leads to Floci's own registry, as a Lambda function's or an ECS task's
@@ -60,13 +60,14 @@ public interface SparkJobRunner {
* gets Floci's settings and the {@code spark-defaults} as defaults (its {@code application} is then
* empty); how long it may run
* ({@link Duration#ZERO} for no limit); the S3 folder its driver's {@code stdout.gz} and
* {@code stderr.gz} go to once it ends, ending in a slash (null for none); and where in CloudWatch Logs
* its driver's output goes while it runs (null for nowhere but Floci's log).
* {@code stderr.gz} go to once it ends, ending in a slash (null for none); where in CloudWatch Logs
* its driver's output goes while it runs (null for nowhere but Floci's log); and the environment variables
* its container gets besides Floci's own, which they replace where a name 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) {
String logFolder, CloudWatchLogs cloudWatchLogs, Map<String, String> environment) {
}
/**
@@ -742,7 +742,9 @@ class EcrRegistryManagerTest {
@Test
void anImageOutsideEcrHasNoRegion() {
for (String image : List.of("public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest", "python:3.12",
"localhost:5000/spark/custom:7.5.0", "registry.internal/123456789012/us-east-1/spark:7.5.0")) {
"localhost:5000/spark/custom:7.5.0", "registry.internal/123456789012/us-east-1/spark:7.5.0",
"123456789012.dkr.ecr.us-east-1.registry.internal/spark/custom:7.5.0",
"123456789012.dkr.ecr.us-east-1.amazonaws.com.example.com/spark/custom:7.5.0")) {
assertEquals(Optional.empty(), EcrRegistryManager.imageRegion(image), image);
}
assertEquals(Optional.empty(), EcrRegistryManager.imageRegion(null));
@@ -63,7 +63,10 @@ class EmrServiceContainerStepsTest {
void aStepRunsInAContainerFromWhenItStartsUntilItsDriverExits() {
EmrCluster requested = cluster("real", true, sparkStep("report", "CONTINUE"));
requested.setConfigurations("""
[{"Classification": "spark-defaults", "Properties": {"spark.executor.cores": "2"}}]""");
[{"Classification": "spark-defaults", "Properties": {"spark.executor.cores": "2"}},
{"Classification": "spark-hive-site", "Properties": {"hive.metastore.glue.catalogid": "111122223333"}},
{"Classification": "spark-env", "Configurations": [
{"Classification": "export", "Properties": {"PYSPARK_PYTHON": "/usr/bin/python3.11"}}]}]""");
EmrCluster cluster = service.runJobFlow(requested, REGION);
String stepId = cluster.getSteps().get(0).getId();
@@ -88,10 +91,12 @@ class EmrServiceContainerStepsTest {
assertNull(job.dockerNetwork());
assertEquals(List.of(REPORT, "s3://bucket/out/"), job.application());
assertNull(job.command());
assertEquals(Map.of("spark.executor.cores", "2"), job.sparkDefaults());
assertEquals(Map.of("spark.executor.cores", "2", "spark.hadoop.hive.metastore.glue.catalogid", "111122223333"),
job.sparkDefaults());
assertEquals(Duration.ZERO, job.timeout());
assertNull(job.logFolder());
assertNull(job.cloudWatchLogs());
assertEquals(Map.of("PYSPARK_PYTHON", "/usr/bin/python3.11"), job.environment());
}
@Test
@@ -117,6 +117,41 @@ class EmrSparkStepsTest {
assertEquals(Map.of(), EmrSparkSteps.sparkDefaults("[{", objectMapper));
}
@Test
void sparkHiveSitePropertiesReachSparkAsHadoopSettingsThatSparkDefaultsOverride() {
// The Management Guide's Glue Data Catalog setting for Spark, and one spark-defaults overrides.
String configurations = """
[{"Classification": "spark-hive-site", "Properties": {
"hive.metastore.client.factory.class":
"com.amazonaws.glue.catalog.metastore.AWSGlueDataCatalogHiveClientFactory",
"hive.metastore.glue.catalogid": "111122223333"}},
{"Classification": "spark-defaults", "Properties": {
"spark.hadoop.hive.metastore.glue.catalogid": "444455556666"}}]
""";
assertEquals(Map.of("spark.hadoop.hive.metastore.client.factory.class",
"com.amazonaws.glue.catalog.metastore.AWSGlueDataCatalogHiveClientFactory",
"spark.hadoop.hive.metastore.glue.catalogid", "444455556666"),
EmrSparkSteps.sparkDefaults(configurations, objectMapper));
}
@Test
void theClustersSparkEnvExportsAreItsStepsEnvironment() {
// The Release Guide's spark-env example, with a property outside export, which sets nothing.
String configurations = """
[{"Classification": "spark-env", "Properties": {"IGNORED": "1"}, "Configurations": [
{"Classification": "export", "Properties": {"JAVA_HOME": "/usr/lib/jvm/java-1.8.0",
"PYSPARK_PYTHON": "/usr/bin/python3.11"}, "Configurations": []}]},
{"Classification": "hadoop-env", "Properties": {}, "Configurations": [
{"Classification": "export", "Properties": {"HADOOP_HEAPSIZE": "2048"}}]}]
""";
assertEquals(Map.of("JAVA_HOME", "/usr/lib/jvm/java-1.8.0", "PYSPARK_PYTHON", "/usr/bin/python3.11"),
EmrSparkSteps.sparkEnvironment(configurations, objectMapper));
assertEquals(Map.of(), EmrSparkSteps.sparkEnvironment(null, objectMapper));
assertEquals(Map.of(), EmrSparkSteps.sparkEnvironment("[{", objectMapper));
}
private static EmrStep step(String jar, String mainClass, String... args) {
EmrStep step = new EmrStep();
step.setJar(jar);
@@ -263,6 +263,7 @@ class EmrServerlessJobRunServiceTest {
assertEquals(Duration.ZERO, runner.jobs.get(1).timeout());
assertNull(job.logFolder());
assertNull(job.cloudWatchLogs());
assertEquals(Map.of(), job.environment());
}
@Test
@@ -197,6 +197,22 @@ class EmrServerlessSparkRunnerTest {
&& file.endsWith("\nspark.executor.cores 4")));
verify(spec, never()).withEntrypoint(List.of("/usr/lib/spark/bin/spark-submit"));
verify(spec).withJavaTrustStore();
// The job's own variables, a cluster's spark-env exports, beside Floci's (none from this test's mock).
verify(spec).withEnv(List.of("PYSPARK_PYTHON=/usr/bin/python3.11"));
}
@Test
void aJobsVariablesFollowFlocisAndReplaceOneOfTheSameName() {
Map<String, String> jobs = new LinkedHashMap<>();
jobs.put("AWS_REGION", "us-east-1");
jobs.put("SPARK_DAEMON_JAVA_OPTS", "-Dkey=value -Xmx1g");
assertEquals(List.of("AWS_REGION=us-east-1", "AWS_ENDPOINT_URL=http://floci:4566",
"SPARK_DAEMON_JAVA_OPTS=-Dkey=value -Xmx1g"),
EmrServerlessSparkRunner.environment(
List.of("AWS_REGION=eu-west-1", "AWS_ENDPOINT_URL=http://floci:4566"), jobs));
assertEquals(List.of("AWS_REGION=eu-west-1"),
EmrServerlessSparkRunner.environment(List.of("AWS_REGION=eu-west-1"), Map.of()));
}
@Test
@@ -610,18 +626,18 @@ 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);
application, null, timeout, logFolder, cloudWatchLogs, 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);
List.of("s3://bucket/jobs/app.jar"), null, Duration.ZERO, null, null, Map.of());
}
private static SparkJobRunner.Job commandJob(List<String> command, 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(), command,
Duration.ZERO, null, null);
Duration.ZERO, null, null, Map.of("PYSPARK_PYTHON", "/usr/bin/python3.11"));
}
}