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

@@ -30,10 +30,13 @@ import static io.github.hectorvent.floci.services.emr.EmrServiceFixture.ACCOUNT;
import static io.github.hectorvent.floci.services.emr.EmrServiceFixture.REGION;
import static io.github.hectorvent.floci.services.emr.EmrServiceFixture.cluster;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@@ -97,6 +100,8 @@ class EmrServiceContainerStepsTest {
assertNull(job.logFolder());
assertNull(job.cloudWatchLogs());
assertEquals(Map.of("PYSPARK_PYTHON", "/usr/bin/python3.11"), job.environment());
assertEquals(new SparkJobRunner.Storage(cluster.getId() + "-home", cluster.getId() + "-mnt"), job.storage());
assertEquals(List.of(cluster.getId()), fixture.clusterStorage.created);
}
@Test
@@ -446,21 +451,23 @@ class EmrServiceContainerStepsTest {
}
@Test
void leftoverDriversAndBootstrapImagesAreRemovedWhenTheServiceStartsUnlessReconcilingIsOff() {
void leftoverDriversBootstrapImagesAndStorageAreRemovedWhenTheServiceStartsUnlessReconcilingIsOff() {
for (boolean reconcile : List.of(true, false)) {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().emr().runnerMode()).thenReturn("docker");
when(config.services().emr().reconcileContainersOnStartup()).thenReturn(reconcile);
EmrServerlessSparkRunner sparkRunner = mock(EmrServerlessSparkRunner.class);
EmrBootstrapRunner bootstrapRunner = mock(EmrBootstrapRunner.class);
EmrClusterStorage clusterStorage = mock(EmrClusterStorage.class);
RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT);
new EmrService(new InMemoryStorageFactory(ACCOUNT), config, regionResolver,
new EmrEventPublisher(mock(EventBridgeService.class), new ObjectMapper(), regionResolver),
sparkRunner, bootstrapRunner, mock(IamService.class)).shutdown();
sparkRunner, bootstrapRunner, clusterStorage, mock(IamService.class)).shutdown();
verify(sparkRunner, times(reconcile ? 1 : 0)).removeLeftoverDrivers("emr");
verify(bootstrapRunner, times(reconcile ? 1 : 0)).removeImages(Set.of());
verify(clusterStorage, times(reconcile ? 1 : 0)).removeAllBut(Set.of());
}
}
@@ -621,6 +628,122 @@ class EmrServiceContainerStepsTest {
assertEquals(0, bootstrapping.stepThreadsWaiting());
}
@Test
void aClustersStepsShareItsStorageWhichGoesOnceItHasEndedAndItsLastStepIsDone() {
EmrCluster cluster = service.runJobFlow(cluster("shared", false, sparkStep("load", "CONTINUE"),
sparkStep("report", "CONTINUE")), REGION);
fixture.runStepThread();
// The second step's driver, still running as its cluster ends, still needs the storage, however often
// the cluster is read meanwhile.
List<Integer> threadsAsTheClusterEnded = new ArrayList<>();
runner.whileRunning = () -> {
service.terminateJobFlows(List.of(cluster.getId()));
service.describeCluster(cluster.getId());
threadsAsTheClusterEnded.add(fixture.stepThreadsWaiting());
};
fixture.runStepThread();
assertEquals(List.of(0), threadsAsTheClusterEnded);
assertTrue(service.describeCluster(cluster.getId()).isStorageCreated());
fixture.runStepThread();
SparkJobRunner.Storage storage = new SparkJobRunner.Storage(cluster.getId() + "-home",
cluster.getId() + "-mnt");
assertEquals(List.of(storage, storage), runner.jobs.stream().map(SparkJobRunner.Job::storage).toList());
assertEquals(List.of(cluster.getId()), fixture.clusterStorage.removed);
assertFalse(service.describeCluster(cluster.getId()).isStorageCreated());
assertEquals(0, fixture.stepThreadsWaiting());
}
@Test
void theStorageOfAClusterItsLastStepEndedGoesWithoutTheClusterBeingReadAgain() {
EmrCluster cluster = service.runJobFlow(cluster("finished", false, sparkStep("report", "CONTINUE")), REGION);
fixture.runStepThread();
// The step's end ended the cluster, and its storage's removal is on a thread of its own already.
assertEquals(1, fixture.stepThreadsWaiting());
fixture.runStepThread();
assertEquals(List.of(cluster.getId()), fixture.clusterStorage.removed);
EmrCluster ended = service.describeCluster(cluster.getId());
assertEquals("TERMINATED", ended.getState());
assertFalse(ended.isStorageCreated());
}
@Test
void storageMadeAsAResetSweptGoesOnceItsStepsThreadIsDone() {
EmrCluster cluster = service.runJobFlow(cluster("reset", true, sparkStep("load", "CONTINUE")), REGION);
// The reset sweeps every cluster's storage while the step's thread is making it.
fixture.clusterStorage.whileCreating = service::beforeReset;
fixture.runStepThread();
assertEquals(List.of(Set.of()), fixture.clusterStorage.kept);
assertEquals(List.of(cluster.getId()), fixture.clusterStorage.removed);
assertEquals(List.of(), runner.driversStarted);
}
@Test
void storageDockerRefusesToRemoveIsTriedAgainTheNextTimeItsClusterIsRead() {
EmrCluster cluster = service.runJobFlow(cluster("refused", true, sparkStep("load", "CONTINUE")), REGION);
fixture.runStepThread();
fixture.clusterStorage.refuse = true;
service.terminateJobFlows(List.of(cluster.getId()));
// One removal at a time, however often the cluster is read meanwhile.
service.describeCluster(cluster.getId());
assertEquals(1, fixture.stepThreadsWaiting());
fixture.runStepThread();
// Refused: the cluster still keeps its storage, and reading it tries again.
assertTrue(service.describeCluster(cluster.getId()).isStorageCreated());
fixture.clusterStorage.refuse = false;
fixture.runStepThread();
assertEquals(List.of(cluster.getId(), cluster.getId()), fixture.clusterStorage.removed);
assertFalse(service.describeCluster(cluster.getId()).isStorageCreated());
assertEquals(0, fixture.stepThreadsWaiting());
}
@Test
void aClusterWhoseStepsNoContainerRanHasNoStorage() {
EmrStep copy = sparkStep("copy", "CONTINUE");
copy.setArgs(new ArrayList<>(List.of("s3-dist-cp", "--src=s3://bucket/in/", "--dest=hdfs:///in/")));
EmrCluster cluster = service.runJobFlow(cluster("unrun", true, copy), REGION);
fixture.runStepThread();
service.terminateJobFlows(List.of(cluster.getId()));
assertFalse(service.describeCluster(cluster.getId()).isStorageCreated());
assertEquals(List.of(), fixture.clusterStorage.created);
assertEquals(List.of(), fixture.clusterStorage.removed);
assertEquals(0, fixture.stepThreadsWaiting());
}
@Test
void theStorageOfClustersThatAreGoneOrHaveEndedIsRemovedBeforeARestartedClusterCanMoveOn() {
// Its step was running as Floci stopped: the wakeup that fails it could start another step.
EmrCluster up = service.runJobFlow(cluster("up", true, sparkStep("cut", "CONTINUE")), REGION);
EmrCluster ended = service.runJobFlow(cluster("ended", true), REGION);
service.terminateJobFlows(List.of(ended.getId()));
EmrService.Wakeups wakeups = mock(EmrService.Wakeups.class);
doAnswer(invocation -> {
assertEquals(List.of(Set.of(up.getId())), fixture.clusterStorage.kept);
return null;
}).when(wakeups).at(any(), any());
fixture.restartReconciling(mock(SparkJobRunner.class), wakeups);
verify(wakeups, atLeastOnce()).at(any(), any());
assertEquals(List.of(Set.of(up.getId())), fixture.clusterStorage.kept);
}
@Test
void aResetRemovesTheStorageOfEveryCluster() {
service.beforeReset();
assertEquals(List.of(Set.of()), fixture.clusterStorage.kept);
}
@Test
void aClusterARestartLeftBootstrappingEndsWithErrors() {
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
@@ -17,6 +17,7 @@ import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.ArgumentMatchers.anyString;
@@ -47,6 +48,40 @@ final class EmrServiceFixture {
private record Wakeup(Instant due, Runnable task) {}
/**
* A cluster's storage as what the service asked of it, each removal refused while {@link #refuse} is set, and
* {@link #whileCreating} run as each is made.
*/
static final class RecordingStorage implements ClusterStorage {
final List<String> created = new ArrayList<>();
final List<String> removed = new ArrayList<>();
final List<Set<String>> kept = new ArrayList<>();
boolean refuse;
Runnable whileCreating = () -> { };
@Override
public SparkJobRunner.Storage volumes(String clusterId) {
return new SparkJobRunner.Storage(clusterId + "-home", clusterId + "-mnt");
}
@Override
public void create(String clusterId, String accountId, String region) {
created.add(clusterId);
whileCreating.run();
}
@Override
public boolean remove(String clusterId) {
removed.add(clusterId);
return !refuse;
}
@Override
public void removeAllBut(Set<String> kept) {
this.kept.add(kept);
}
}
final ObjectMapper objectMapper = new ObjectMapper();
final List<JsonNode> published = new ArrayList<>();
final MutableClock clock;
@@ -62,6 +97,8 @@ final class EmrServiceFixture {
private final InMemoryStorageFactory storage;
private final SparkJobRunner runner;
private final BootstrapRunner bootstrap;
// The docker runner mode's; null in the immediate one.
final RecordingStorage clusterStorage;
private final IamService iam;
private final int[] durations;
@@ -71,7 +108,7 @@ final class EmrServiceFixture {
}
EmrServiceFixture(int startupDelaySeconds, int stepDurationSeconds, int terminationDelaySeconds) {
this(new InMemoryStorageFactory(ACCOUNT), new MutableClock(), null, null, null,
this(new InMemoryStorageFactory(ACCOUNT), new MutableClock(), null, null, null, null,
startupDelaySeconds, stepDurationSeconds, terminationDelaySeconds);
}
@@ -82,16 +119,18 @@ final class EmrServiceFixture {
/** As {@link #docker(SparkJobRunner, IamService)}, its clusters' bootstrap actions run by {@code bootstrap}. */
static EmrServiceFixture docker(SparkJobRunner runner, BootstrapRunner bootstrap, IamService iam) {
return new EmrServiceFixture(new InMemoryStorageFactory(ACCOUNT), new MutableClock(), runner, bootstrap, iam,
0, 0, 0);
return new EmrServiceFixture(new InMemoryStorageFactory(ACCOUNT), new MutableClock(), runner, bootstrap,
new RecordingStorage(), iam, 0, 0, 0);
}
private EmrServiceFixture(InMemoryStorageFactory storage, MutableClock clock, SparkJobRunner runner,
BootstrapRunner bootstrap, IamService iam, int... durations) {
BootstrapRunner bootstrap, RecordingStorage clusterStorage, IamService iam,
int... durations) {
this.storage = storage;
this.clock = clock;
this.runner = runner;
this.bootstrap = bootstrap;
this.clusterStorage = clusterStorage;
this.iam = iam;
this.durations = durations;
EventBridgeService eventBridge = mock(EventBridgeService.class);
@@ -118,12 +157,12 @@ final class EmrServiceFixture {
public void deliver(Runnable delivery) {
deliveries.add(delivery);
}
}, runner, bootstrap, stepThreads::add, iam);
}, runner, bootstrap, clusterStorage, stepThreads::add, iam);
}
/** A new service on the same storage and clock, as after a restart of Floci with persistent storage. */
EmrServiceFixture restart() {
return new EmrServiceFixture(storage, clock, runner, bootstrap, iam, durations);
return new EmrServiceFixture(storage, clock, runner, bootstrap, clusterStorage, iam, durations);
}
/**
@@ -132,7 +171,7 @@ final class EmrServiceFixture {
*/
EmrService restartReconciling(SparkJobRunner runner, EmrService.Wakeups wakeups) {
return new EmrService(storage, config(true), new RegionResolver(REGION, ACCOUNT), publisher, clock, wakeups,
runner, bootstrap, stepThreads::add, iam);
runner, bootstrap, clusterStorage, stepThreads::add, iam);
}
private EmulatorConfig config(boolean reconcile) {
@@ -265,6 +265,8 @@ class EmrServerlessJobRunServiceTest {
assertNull(job.cloudWatchLogs());
assertEquals(Map.of(), job.environment());
assertEquals(List.of(), job.archives());
// An EMR Serverless application has no cluster, nor its storage.
assertNull(job.storage());
}
@Test
@@ -77,6 +77,8 @@ import static org.mockito.Mockito.when;
class EmrServerlessSparkRunnerTest {
private static final String ENDPOINT = "http://floci:4566";
private static final SparkJobRunner.Storage STORAGE = new SparkJobRunner.Storage(
"floci-aws-emr-j-2AXXXXXXGAPLF-home", "floci-aws-emr-j-2AXXXXXXGAPLF-mnt");
private final EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
private final ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
@@ -169,6 +171,8 @@ class EmrServerlessSparkRunnerTest {
verify(lifecycle, never()).copyJavaTrustStore(anyString());
// The release's image is not in an ECR repository, so it is pulled once, as the container is created.
verify(lifecycle, never()).resolveImageForLaunch(anyString(), any(), any());
// An EMR Serverless run has no cluster, nor its storage.
verify(spec, never()).withNamedVolume(anyString(), anyString());
}
@Test
@@ -216,6 +220,7 @@ class EmrServerlessSparkRunnerTest {
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"));
verify(spec, never()).withEnv(eq("FLOCI_HADOOP_SITE"), anyString());
}
@Test
@@ -396,6 +401,62 @@ class EmrServerlessSparkRunnerTest {
assertFalse(ended.output().contains("started"));
}
@Test
void aStepMountsItsClustersStorageWhoseHdfsIsWherePathsWithoutASchemeLead() {
ContainerBuilder builder = mock(ContainerBuilder.class);
ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(builder.newContainer(anyString())).thenReturn(spec);
SparkJobRunner.Job job = stepJob(Map.of("spark.hadoop.fs.defaultFS", "file:///"));
runner(builder).run(job, progress);
List<String> arguments = EmrServerlessSparkRunner.sparkSubmitArguments(job, ENDPOINT);
verify(spec).withNamedVolume(STORAGE.home(), "/home/hadoop");
verify(spec).withNamedVolume(STORAGE.mnt(), "/mnt");
// After Floci's S3 settings, before the cluster's spark-defaults, which win.
assertEquals("spark.hadoop.aws.region=eu-west-1", arguments.get(17));
assertEquals(List.of(
"--conf", "spark.hadoop.fs.defaultFS=hdfs:///",
"--conf", "spark.hadoop.fs.hdfs.impl=org.apache.hadoop.fs.viewfs.ViewFileSystemOverloadScheme",
"--conf", "spark.hadoop.fs.viewfs.mounttable.default.linkFallback=file:///mnt/hdfs",
"--conf", "spark.sql.streaming.checkpointFileManagerClass="
+ "org.apache.spark.sql.execution.streaming.FileSystemBasedCheckpointFileManager",
"--conf", "spark.hadoop.fs.defaultFS=file:///",
"s3://bucket/jobs/report.py"), arguments.subList(18, arguments.size()));
}
@Test
void aCommandOnAClusterGivesItsHadoopCommandTheClustersHdfsToo() {
ContainerBuilder builder = mock(ContainerBuilder.class);
ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(builder.newContainer(anyString())).thenReturn(spec);
List<String> command = List.of("bash", "-c", "hadoop fs -put data.csv /input/");
runner(builder).run(commandJob(command, Map.of(), STORAGE), progress);
verify(spec).withNamedVolume(STORAGE.home(), "/home/hadoop");
verify(spec).withNamedVolume(STORAGE.mnt(), "/mnt");
verify(spec).withEnv("FLOCI_HADOOP_SITE", String.join("\n",
"<property><name>fs.defaultFS</name><value>hdfs:///</value></property>",
"<property><name>fs.hdfs.impl</name><value>org.apache.hadoop.fs.viewfs.ViewFileSystemOverloadScheme"
+ "</value></property>",
"<property><name>fs.viewfs.mounttable.default.linkFallback</name><value>file:///mnt/hdfs</value>"
+ "</property>"));
verify(spec).withEnv(eq("FLOCI_SPARK_DEFAULTS"), argThat(file -> file.contains(
"\nspark.hadoop.fs.defaultFS hdfs:///\n")));
// A copy of the Hadoop configuration a spark-env export of HADOOP_CONF_DIR names, else of the image's, links
// followed, its core-site.xml taking in the original's whole, whatever its XML, then the cluster's HDFS.
verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains(
"source_conf=\"${HADOOP_CONF_DIR:-/etc/hadoop/conf}\"\n")
&& entrypoint.get(2).contains("cp -rL \"$source_conf/.\" \"$hadoop_conf\"")
&& entrypoint.get(2).contains(
"include='<xi:include href=\"/tmp/floci-hadoop-conf/floci-original-core-site.xml\"/>'")
&& entrypoint.get(2).contains("'<configuration xmlns:xi=\"http://www.w3.org/2001/XInclude\">'"
+ " \"$include\" \"$FLOCI_HADOOP_SITE\" '</configuration>' > \"$hadoop_conf/core-site.xml\"")
&& entrypoint.get(2).contains(
"export HADOOP_CONF_DIR=\"$hadoop_conf\" PATH=\"/tmp/floci-bin:$PATH\"")));
}
@Test
void aCommandsOwnSparkSubmitRunsLocallyOnFlocisS3WithTheJobsSparkDefaults() {
assertEquals(String.join("\n",
@@ -835,24 +896,37 @@ 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());
application, null, timeout, logFolder, cloudWatchLogs, Map.of(), List.of(), null);
}
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());
List.of("s3://bucket/jobs/app.jar"), null, Duration.ZERO, null, null, Map.of(), List.of(), null);
}
private static SparkJobRunner.Job archiveJob(List<String> archives) {
return new SparkJobRunner.Job("emr-serverless", "00f0000000000001", "123456789012", "eu-west-1", "emr-7.5.0",
null, null, "floci-network", "arn:aws:iam::123456789012:role/job", Map.of(),
List.of("s3://bucket/jobs/app.jar"), null, Duration.ZERO, null, null, Map.of(), archives);
List.of("s3://bucket/jobs/app.jar"), null, Duration.ZERO, null, null, Map.of(), archives, null);
}
private static SparkJobRunner.Job commandJob(List<String> command, Map<String, String> sparkDefaults) {
return commandJob(command, sparkDefaults, null);
}
private static SparkJobRunner.Job commandJob(List<String> command, Map<String, String> sparkDefaults,
SparkJobRunner.Storage storage) {
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());
Duration.ZERO, null, null, Map.of("PYSPARK_PYTHON", "/usr/bin/python3.11"), List.of(),
storage);
}
// A Spark step on a cluster, which has storage.
private static SparkJobRunner.Job stepJob(Map<String, String> sparkDefaults) {
return new SparkJobRunner.Job("emr", "s-1A2B3C4D5E6F7", "123456789012", "eu-west-1", "emr-7.5.0", null,
null, "floci-network", "arn:aws:iam::123456789012:role/job", sparkDefaults,
List.of("s3://bucket/jobs/report.py"), null, Duration.ZERO, null, null, Map.of(), List.of(), STORAGE);
}
}