feat(emr): keep a cluster's storage, HDFS included, across its steps (#7137)

In the docker runner mode each step of a cluster ran in a container of its
own, so nothing a step left in /home/hadoop, or in HDFS, was there for the
next, and the image has no HDFS at all: an hdfs:// path failed, and a path
without a scheme, which EMR reads as HDFS, went to the container's own
disk. The Management Guide calls HDFS "best used for caching the results produced by
intermediate job-flow steps", the prefix "hdfs:// (or no prefix)", and
"ephemeral storage that is reclaimed when you terminate a cluster"; the
Release Guide's S3DistCp page copies data "into HDFS where it can be
processed by subsequent steps".

Now a cluster's storage outlives its steps:

- each step's container mounts the cluster's two Docker volumes, one at
  /home/hadoop and one at /mnt, both of which the image gives its hadoop
  user, so Docker gives an empty volume that owner, and what the cluster's
  bootstrap left there in the image its steps run in;
- HDFS is /mnt/hdfs: Spark gets fs.defaultFS hdfs:/// and the hdfs scheme
  through Hadoop's ViewFileSystemOverloadScheme with a fallback link to
  that folder, so hdfs:// paths and those without a scheme lead there, a
  relative one under /user/hadoop, and a streaming query keeps its
  checkpoints through Spark's file system checkpoint manager, as
  FileContext refuses an hdfs:// path without a host. The cluster's
  spark-defaults can set any of these otherwise;
- a command step'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, links followed, whose core-site.xml takes in
  the original's through Hadoop's XInclude and then those properties,
  with its HDFS, MapReduce and YARN homes set; hdfs dfs runs as hadoop
  fs, the image's hdfs command being unable to run;
- the volumes go once the cluster has ended and its last step is done,
  tried again while Docker refuses, as the bootstrap's image is; on a
  reset, a step's thread it overtook removing them again once its
  container is gone; and, for clusters that are gone or have ended, when
  the service starts, unless reconcile-containers-on-startup is off.

SparkJobRunner.Job carries the storage, which an EMR Serverless run leaves
null. ClusterStorage names, makes and removes the volumes;
EmrClusterStorage is its Docker side. A path without a scheme that a step
meant for its container's own disk now leads to HDFS, as on EMR. emr.md
says what HDFS lacks: no NameNode, no hdfs:// path with a host, no
hadoop fs -ls / and no S3 through hadoop fs.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-31 21:30:43 -05:00
1 parent f2a37c8792
commit ebf91d1a8e
12 files changed
+572 -43

No files matched your search

@@ -0,0 +1,32 @@
package io.github.hectorvent.floci.services.emr;
import io.github.hectorvent.floci.services.emrserverless.SparkJobRunner;
import java.util.Set;
/**
* A cluster's storage in the EMR {@code docker} runner mode: the disks of its primary node, which every one of
* its steps' containers mounts, so what a step leaves in {@code /home/hadoop}, or in HDFS, is there for the
* next, until the cluster ends ("HDFS is ephemeral storage that is reclaimed when you terminate a cluster").
* {@link EmrClusterStorage} is the Docker implementation, and a test supplies its own.
*/
public interface ClusterStorage {
/** The volumes holding {@code clusterId}'s storage, whether or not they are there yet. */
SparkJobRunner.Storage volumes(String clusterId);
/** Makes the volumes of {@code clusterId}'s storage, in its account and Region, when they are not there. */
void create(String clusterId, String accountId, String region);
/**
* Removes the volumes of {@code clusterId}'s storage once it no longer needs them: true when they are gone,
* false when Docker refused, so the caller can try again.
*/
boolean remove(String clusterId);
/**
* Removes the storage of every cluster of this deployment but those in {@code kept}, by id: after a
* restart, the storage of the clusters that are gone or have ended, and on a reset all of it.
*/
void removeAllBut(Set<String> kept);
}
@@ -0,0 +1,85 @@
package io.github.hectorvent.floci.services.emr;
import com.github.dockerjava.api.command.InspectVolumeResponse;
import com.github.dockerjava.api.command.ListVolumesResponse;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
import io.github.hectorvent.floci.services.emrserverless.SparkJobRunner;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Keeps each EMR cluster's storage in two Docker volumes, one for its primary node's {@code /home/hadoop} and one
* for its {@code /mnt}, where its HDFS is. Both paths belong to the image's {@code hadoop} user, and Docker gives
* an empty volume what the image has at the path it is first mounted on, owner included, so the steps, which
* run as that user, can write to both, and what the cluster's bootstrap left there comes with them.
*/
@ApplicationScoped
public class EmrClusterStorage implements ClusterStorage {
private static final Logger LOG = Logger.getLogger(EmrClusterStorage.class);
private static final String SERVICE = "emr";
private static final String COMPONENT = "emr-storage";
private final ContainerLifecycleManager lifecycleManager;
private final EmulatorConfig config;
@Inject
public EmrClusterStorage(ContainerLifecycleManager lifecycleManager, EmulatorConfig config) {
this.lifecycleManager = lifecycleManager;
this.config = config;
}
@Override
public SparkJobRunner.Storage volumes(String clusterId) {
return new SparkJobRunner.Storage(
ContainerStorageHelper.dockerName(config, SERVICE + "-" + clusterId + "-home"),
ContainerStorageHelper.dockerName(config, SERVICE + "-" + clusterId + "-mnt"));
}
@Override
public void create(String clusterId, String accountId, String region) {
Map<String, String> labels = new LinkedHashMap<>(ContainerStorageHelper.resourceIdentityLabels(SERVICE,
clusterId, accountId, region));
labels.put(ContainerStorageHelper.COMPONENT_LABEL, COMPONENT);
labels.put(ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config));
SparkJobRunner.Storage storage = volumes(clusterId);
lifecycleManager.ensureVolume(storage.home(), labels);
lifecycleManager.ensureVolume(storage.mnt(), labels);
}
@Override
public boolean remove(String clusterId) {
SparkJobRunner.Storage storage = volumes(clusterId);
// Both are tried, so one Docker refused does not keep the other.
boolean homeGone = lifecycleManager.removeVolume(storage.home());
return lifecycleManager.removeVolume(storage.mnt()) && homeGone;
}
@Override
public void removeAllBut(Set<String> kept) {
try {
ListVolumesResponse response = lifecycleManager.getDockerClient().listVolumesCmd()
.withFilter("label", List.of(ContainerStorageHelper.COMPONENT_LABEL + "=" + COMPONENT,
ContainerStorageHelper.OWNER_LABEL + "=" + ContainerStorageHelper.ownerIdentity(config)))
.exec();
List<InspectVolumeResponse> volumes = response != null && response.getVolumes() != null
? response.getVolumes() : List.of();
for (InspectVolumeResponse volume : volumes) {
Map<String, String> labels = volume.getLabels() != null ? volume.getLabels() : Map.of();
if (!kept.contains(labels.get(ContainerStorageHelper.RESOURCE_ID_LABEL))) {
lifecycleManager.removeVolume(volume.getName());
}
}
} catch (RuntimeException e) {
LOG.warnv("Could not remove the storage of EMR clusters that have ended: {0}", e.getMessage());
}
}
}
@@ -111,6 +111,7 @@ public class EmrService implements Resettable {
// The docker runner mode's; null in the immediate one.
private final SparkJobRunner sparkRunner;
private final BootstrapRunner bootstrapRunner;
private final ClusterStorage clusterStorage;
private final Executor stepExecutor;
private final IamService iamService;
// Where a step's driver runs: image-template, with the release label for %s, and docker-network; null when
@@ -124,6 +125,8 @@ public class EmrService implements Resettable {
// The images of ended clusters a thread is removing. A cluster names its image until it is gone, so one
// Docker refused to remove is tried again the next time the cluster is read or stored.
private final Set<String> imagesBeingRemoved = new HashSet<>();
// Likewise the clusters, by account and id, whose storage a thread is removing.
private final Set<String> storageBeingRemoved = new HashSet<>();
// Raised by each reset, so a step's thread from before it writes nothing back after the wipe.
private long generation;
@@ -188,24 +191,26 @@ public class EmrService implements Resettable {
@Inject
public EmrService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver,
EmrEventPublisher eventPublisher, EmrServerlessSparkRunner sparkRunner,
EmrBootstrapRunner bootstrapRunner, IamService iamService) {
EmrBootstrapRunner bootstrapRunner, EmrClusterStorage clusterStorage, IamService iamService) {
this(storageFactory, config, regionResolver, eventPublisher, Clock.systemUTC(),
Wakeups.timer(Clock.systemUTC()),
RUNNER_DOCKER.equalsIgnoreCase(config.services().emr().runnerMode()) ? sparkRunner : null,
RUNNER_DOCKER.equalsIgnoreCase(config.services().emr().runnerMode()) ? bootstrapRunner : null,
RUNNER_DOCKER.equalsIgnoreCase(config.services().emr().runnerMode()) ? clusterStorage : null,
Executors.newCachedThreadPool(Thread.ofPlatform().daemon().name("emr-step-", 0).factory()),
iamService);
}
EmrService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver,
EmrEventPublisher eventPublisher, Clock clock, Wakeups wakeups) {
this(storageFactory, config, regionResolver, eventPublisher, clock, wakeups, null, null, Runnable::run,
this(storageFactory, config, regionResolver, eventPublisher, clock, wakeups, null, null, null, Runnable::run,
null);
}
EmrService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver,
EmrEventPublisher eventPublisher, Clock clock, Wakeups wakeups, SparkJobRunner sparkRunner,
BootstrapRunner bootstrapRunner, Executor stepExecutor, IamService iamService) {
BootstrapRunner bootstrapRunner, ClusterStorage clusterStorage, Executor stepExecutor,
IamService iamService) {
this.clusterStore = storageFactory.create("emr", "emr-clusters.json",
new TypeReference<Map<String, EmrCluster>>() {});
this.secConfigStore = storageFactory.create("emr", "emr-security-configs.json",
@@ -217,6 +222,7 @@ public class EmrService implements Resettable {
this.defaultReleaseLabel = config.services().emr().defaultReleaseLabel();
this.sparkRunner = sparkRunner;
this.bootstrapRunner = bootstrapRunner;
this.clusterStorage = clusterStorage;
this.stepExecutor = stepExecutor;
this.iamService = iamService;
this.imageTemplate = config.services().emr().imageTemplate().orElse(null);
@@ -237,8 +243,10 @@ public class EmrService implements Resettable {
// After a restart, a stored cluster with a change still to come wakes the service as before, and one
// with a step a container ran, or bootstrap actions, which no thread runs any more, wakes it at once to
// fail them. The images bootstrap left for clusters that are gone, or have ended, go first: a wakeup
// runs on the timer's thread, and a cluster it moved on could keep an image the sweep never knew of.
// runs on the timer's thread, and a cluster it moved on could keep an image the sweep never knew of. The
// storage of the clusters that are gone, or have ended, goes then too.
Set<String> imagesInUse = new HashSet<>();
Set<String> clustersUp = new HashSet<>();
List<Runnable> wakeAtStart = new ArrayList<>();
for (AccountAwareStorageBackend.AccountEntry<EmrCluster> entry
: clusterStore.scanAllAccountEntries(k -> true)) {
@@ -252,10 +260,16 @@ public class EmrService implements Resettable {
if (cluster.getBootstrapImage() != null && !EmrClusterLifecycle.isTerminated(cluster.getState())) {
imagesInUse.add(cluster.getBootstrapImage());
}
if (!EmrClusterLifecycle.isTerminated(cluster.getState())) {
clustersUp.add(cluster.getId());
}
}
if (bootstrapRunner != null && config.services().emr().reconcileContainersOnStartup()) {
bootstrapRunner.removeImages(imagesInUse);
}
if (clusterStorage != null && config.services().emr().reconcileContainersOnStartup()) {
clusterStorage.removeAllBut(clustersUp);
}
wakeAtStart.forEach(Runnable::run);
}
@@ -275,8 +289,8 @@ public class EmrService implements Resettable {
/**
* A reset has begun: the steps' and bootstraps' threads from before it write nothing more, so the storage
* wipe that follows leaves none of their clusters behind, and the images bootstrap left go with them. Its
* teardown has already stopped their containers.
* wipe that follows leaves none of their clusters behind, and the images bootstrap left, and the clusters'
* own storage, go with them. Its teardown has already stopped their containers.
*/
@Override
public synchronized void beforeReset() {
@@ -286,6 +300,9 @@ public class EmrService implements Resettable {
if (bootstrapRunner != null) {
bootstrapRunner.removeImages(Set.of());
}
if (clusterStorage != null) {
clusterStorage.removeAllBut(Set.of());
}
}
@Override
@@ -1136,7 +1153,7 @@ public class EmrService implements Resettable {
if (changed) {
clusterStore.put(cluster.getId(), cluster);
}
releaseBootstrapImage(cluster);
releaseEnded(cluster);
wakeForNextChange(cluster);
return cluster;
}
@@ -1156,6 +1173,17 @@ public class EmrService implements Resettable {
return EmrClusterLifecycle.BOOTSTRAPPING.equals(cluster.getState()) && cluster.isBootstrapInContainer();
}
// What an ended cluster kept goes once no step of it still runs in a container: its bootstrap's image and
// its storage.
private void releaseEnded(EmrCluster cluster) {
releaseBootstrapImage(cluster);
releaseStorage(cluster);
}
private boolean stepsExecuting(EmrCluster cluster, String accountId) {
return cluster.getSteps().stream().anyMatch(step -> executing.contains(stepKey(accountId, step.getId())));
}
/**
* Once a cluster has ended and no step of it still runs in a container, the image its bootstrap left
* goes, off the service's lock. The cluster names it until it is gone, and while a thread removes it, it
@@ -1167,8 +1195,7 @@ public class EmrService implements Resettable {
return;
}
String accountId = regionResolver.getAccountId();
if (cluster.getSteps().stream().anyMatch(step -> executing.contains(stepKey(accountId, step.getId())))
|| !imagesBeingRemoved.add(image)) {
if (stepsExecuting(cluster, accountId) || !imagesBeingRemoved.add(image)) {
return;
}
String clusterId = cluster.getId();
@@ -1191,6 +1218,41 @@ public class EmrService implements Resettable {
});
}
/**
* Once a cluster has ended and no step of it still runs in a container, its storage goes, off the service's
* lock, as its bootstrap's image does: the cluster keeps it until it is gone, and while a thread removes it,
* it is not removed again.
*/
private void releaseStorage(EmrCluster cluster) {
if (!cluster.isStorageCreated() || clusterStorage == null
|| !EmrClusterLifecycle.isTerminated(cluster.getState())) {
return;
}
String accountId = regionResolver.getAccountId();
String key = clusterKey(accountId, cluster.getId());
if (stepsExecuting(cluster, accountId) || !storageBeingRemoved.add(key)) {
return;
}
String clusterId = cluster.getId();
String region = regionOf(cluster);
stepExecutor.execute(() -> {
boolean gone = clusterStorage.remove(clusterId);
RequestScopes.runAs(accountId, region, () -> run(() -> storageRemoved(clusterId, key, gone)));
});
}
// A thread's removal of a cluster's storage has ended: the cluster keeps it no more once it is gone.
private void storageRemoved(String clusterId, String key, boolean gone) {
storageBeingRemoved.remove(key);
if (!gone) {
return;
}
clusterStore.get(clusterId).filter(EmrCluster::isStorageCreated).ifPresent(cluster -> {
cluster.setStorageCreated(false);
clusterStore.put(clusterId, cluster);
});
}
private boolean failInterruptedSteps(EmrCluster cluster) {
if (sparkRunner == null) {
return false;
@@ -1260,8 +1322,8 @@ public class EmrService implements Resettable {
EmrStep step = found.flatMap(cluster -> cluster.getSteps().stream()
.filter(candidate -> launch.stepId().equals(candidate.getId())).findFirst()).orElse(null);
if (step == null || !EmrClusterLifecycle.RUNNING.equals(step.getState())) {
// A step of a cluster that has ended no longer runs: the cluster's image may go with it, its last one.
found.ifPresent(this::releaseBootstrapImage);
// A step of a cluster that has ended no longer runs: what the cluster kept may go with it, its last one.
found.ifPresent(this::releaseEnded);
return;
}
EmrCluster cluster = found.get();
@@ -1279,7 +1341,7 @@ public class EmrService implements Resettable {
private void driverStopped(StepLaunch launch) {
if (!stillRunning(launch)) {
executing.remove(stepKey(launch.accountId(), launch.stepId()));
clusterStore.get(launch.clusterId()).ifPresent(this::releaseBootstrapImage);
clusterStore.get(launch.clusterId()).ifPresent(this::releaseEnded);
}
}
@@ -1304,6 +1366,10 @@ public class EmrService implements Resettable {
&& EmrClusterLifecycle.RUNNING.equals(step.getState()));
}
private synchronized boolean resetSince(StepLaunch launch) {
return launch.launchedIn() != generation;
}
/** A step handed to a thread: whose it is, where, and under which reset. */
private record StepLaunch(String accountId, String region, String clusterId, String stepId, long launchedIn) {}
@@ -1315,6 +1381,11 @@ public class EmrService implements Resettable {
String accountId = regionResolver.getAccountId();
List<String> application = EmrSparkSteps.application(step);
List<String> command = application == null ? EmrSparkSteps.command(step) : null;
SparkJobRunner.Storage storage = null;
if ((application != null || command != null) && clusterStorage != null) {
storage = clusterStorage.volumes(cluster.getId());
cluster.setStorageCreated(true);
}
SparkJobRunner.Job job = application == null && command == null ? null
: new SparkJobRunner.Job(SERVICE, step.getId(), accountId, region, cluster.getReleaseLabel(),
cluster.getBootstrapImage() != null ? cluster.getBootstrapImage() : imageTemplate, null,
@@ -1322,7 +1393,8 @@ 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());
EmrSparkSteps.sparkEnvironment(cluster.getConfigurations(), SNAPSHOT_MAPPER), List.of(),
storage);
StepLaunch launch = new StepLaunch(accountId, region, cluster.getId(), step.getId(), generation);
executing.add(stepKey(accountId, step.getId()));
stepExecutor.execute(() -> runStep(job, launch));
@@ -1341,12 +1413,23 @@ public class EmrService implements Resettable {
failure = EmrSparkSteps.NOT_RUN;
} else {
SparkJobRunner.Outcome outcome;
StepProgress progress = new StepProgress(launch);
try {
outcome = sparkRunner.run(job, new StepProgress(launch));
// The cluster's storage is there before its first step's container mounts it. A step a cancel,
// its cluster's end or a reset has passed does not start, so it makes none.
if (job.storage() != null && !progress.cancelled()) {
clusterStorage.create(launch.clusterId(), launch.accountId(), launch.region());
}
outcome = sparkRunner.run(job, progress);
} catch (RuntimeException e) {
LOG.warnv(e, "EMR step {0} could not run", launch.stepId());
outcome = SparkJobRunner.Outcome.couldNotStart(e.getMessage());
}
// A reset since the step started has swept the storage and wiped its cluster, so nothing would remove
// volumes made, or mounted, after its sweep: they go now, the step's container being gone.
if (job.storage() != null && resetSince(launch)) {
clusterStorage.remove(launch.clusterId());
}
if (outcome.stopped()) {
RequestScopes.runAs(launch.accountId(), launch.region(), () -> run(() -> driverStopped(launch)));
return;
@@ -1514,7 +1597,7 @@ public class EmrService implements Resettable {
/** Stores a cluster a call changed, once every change that falls due by now is made. */
private void store(EmrCluster cluster) {
lifecycle.advance(cluster, now(), regionOf(cluster));
releaseBootstrapImage(cluster);
releaseEnded(cluster);
clusterStore.put(cluster.getId(), cluster);
wakeForNextChange(cluster);
}
@@ -51,6 +51,9 @@ public class EmrCluster {
// its steps run in; Floci's own, as the API has neither.
private boolean bootstrapInContainer;
private String bootstrapImage;
// Whether the docker runner mode has made the cluster's storage, which goes once the cluster has ended; Floci's
// own, as the API has none.
private boolean storageCreated;
// The cluster's ManagedScalingPolicy and AutoTerminationPolicy as given, raw JSON; null when none.
private String managedScalingPolicy;
private String autoTerminationPolicy;
@@ -177,6 +180,9 @@ public class EmrCluster {
public String getBootstrapImage() { return bootstrapImage; }
public void setBootstrapImage(String bootstrapImage) { this.bootstrapImage = bootstrapImage; }
public boolean isStorageCreated() { return storageCreated; }
public void setStorageCreated(boolean storageCreated) { this.storageCreated = storageCreated; }
public String getManagedScalingPolicy() { return managedScalingPolicy; }
public void setManagedScalingPolicy(String managedScalingPolicy) { this.managedScalingPolicy = managedScalingPolicy; }
@@ -494,7 +494,8 @@ 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, application(sparkSubmit), null, timeout, driverLogFolder(app, run),
driverCloudWatchLogs(app, run), driverEnvironment(sparkProperties), archives(sparkProperties));
driverCloudWatchLogs(app, run), driverEnvironment(sparkProperties), archives(sparkProperties),
null);
executing.add(run.getJobRunId());
long launchedIn = generation;
runExecutor.execute(() -> execute(job, launchedIn));
@@ -57,7 +57,8 @@ import java.util.zip.GZIPOutputStream;
* trusts Floci's CA, through the Java trust store copied in before it starts, and the run's archives in S3
* are unpacked into its working directory before the driver starts. The driver's output goes to
* Floci's log and, while it runs, to the run's CloudWatch log streams, when it has some; once it ends, its
* standard output and error go, gzipped, to the run's log folder in Floci's S3, when it has one.
* standard output and error go, gzipped, to the run's log folder in Floci's S3, when it has one. An EMR step's
* container mounts its cluster's storage, where {@code hdfs://} paths, and paths without a scheme, lead.
*/
@ApplicationScoped
public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardown {
@@ -65,6 +66,24 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
private static final Logger LOG = Logger.getLogger(EmrServerlessSparkRunner.class);
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";
// 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.
private static final List<SparkSetting> HDFS_SETTINGS = List.of(
new SparkSetting("fs.defaultFS", "hdfs:///"),
new SparkSetting("fs.hdfs.impl", "org.apache.hadoop.fs.viewfs.ViewFileSystemOverloadScheme"),
new SparkSetting("fs.viewfs.mounttable.default.linkFallback", "file:///mnt/hdfs"));
// Spark's default checkpoint manager goes through Hadoop's FileContext, which refuses an hdfs:// path
// without a host, so a streaming query keeps its checkpoints through the file system instead.
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 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
@@ -78,6 +97,30 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
+ " -e '/^spark\\.submit\\.customResourceManager/d' \"$conf/spark-defaults.conf\"",
"printf '%s\\n' \"$" + SPARK_DEFAULTS_VARIABLE + "\" >> \"$conf/spark-defaults.conf\"",
"export SPARK_CONF_DIR=\"$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.
"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",
" cp -rL \"$source_conf/.\" \"$hadoop_conf\" 2>/dev/null",
" include=",
" if [ -f \"$hadoop_conf/core-site.xml\" ]; then",
" mv \"$hadoop_conf/core-site.xml\" \"$hadoop_conf/floci-original-core-site.xml\"",
" include='<xi:include href=\"/tmp/floci-hadoop-conf/floci-original-core-site.xml\"/>'",
" fi",
" printf '%s\\n' '<configuration xmlns:xi=\"http://www.w3.org/2001/XInclude\">' \"$include\" \"$"
+ HADOOP_SITE_VARIABLE + "\" '</configuration>' > \"$hadoop_conf/core-site.xml\"",
" printf '%s\\n' '#!/bin/bash' 'if [ \"$1\" = dfs ]; then shift; exec hadoop fs \"$@\"; fi'"
+ " 'echo \"hdfs $1: only hdfs dfs runs here, as hadoop fs\" >&2' 'exit 1' > /tmp/floci-bin/hdfs",
" chmod +x /tmp/floci-bin/hdfs",
" export HADOOP_CONF_DIR=\"$hadoop_conf\" PATH=\"/tmp/floci-bin:$PATH\"",
" export HADOOP_HDFS_HOME=\"${HADOOP_HDFS_HOME:-/usr/lib/hadoop}\"",
" export HADOOP_MAPRED_HOME=\"${HADOOP_MAPRED_HOME:-/usr/lib/hadoop}\"",
" export HADOOP_YARN_HOME=\"${HADOOP_YARN_HOME:-/usr/lib/hadoop}\"",
"fi",
"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.
@@ -186,6 +229,13 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
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);
}
}
if (job.storage() != null) {
container.withNamedVolume(job.storage().home(), "/home/hadoop")
.withNamedVolume(job.storage().mnt(), "/mnt");
}
ContainerSpec spec = container
.withDockerNetwork(Optional.ofNullable(job.dockerNetwork()))
@@ -473,8 +523,9 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
/**
* {@code spark-submit}'s arguments: local mode, S3A on Floci's S3 for {@code s3://} and {@code s3a://}
* paths, then the run's {@code spark-defaults} and its own options, which win over what comes before
* them, then its application and that application's arguments. Before release 7.10.0
* paths, the cluster's HDFS for {@code hdfs://} paths and those without a scheme on a step, then the run's
* {@code spark-defaults} and its own options, which win over what comes before them, then its
* application and that application's arguments. Before release 7.10.0
* {@code s3://} is EMRFS, which ignores the endpoint setting, so it is switched to S3A. S3A writes
* are committed through commit data the writer keeps in memory, without which EMR's committer finds
* none and a write is silently lost.
@@ -532,6 +583,11 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
new SparkSetting("spark.hadoop.fs.AbstractFileSystem.s3.impl", "org.apache.hadoop.fs.s3a.S3A"),
new SparkSetting("spark.hadoop.aws.glue.endpoint", flociEndpoint),
new SparkSetting("spark.hadoop.aws.region", job.region())));
if (job.storage() != null) {
HDFS_SETTINGS.forEach(setting -> settings.add(new SparkSetting("spark.hadoop." + setting.key(),
setting.value())));
settings.add(FILE_SYSTEM_CHECKPOINTS);
}
job.sparkDefaults().forEach((key, value) -> settings.add(new SparkSetting(key, value)));
return settings;
}
@@ -63,15 +63,22 @@ public interface SparkJobRunner {
* {@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); the environment variables
* its container gets besides Floci's own, which they replace where a name is the same (empty for none);
* and 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).
* 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).
*/
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) {
List<String> archives, Storage storage) {
}
/**
* The Docker volumes holding an EMR cluster's storage, which every one of its steps' containers mounts:
* {@code home} at {@code /home/hadoop}, and {@code mnt} at {@code /mnt}, where its HDFS is.
*/
record Storage(String home, String mnt) {
}
/**