feat(emr-serverless): run Spark job runs in a container (#6469)

A new runner mode, floci.services.emrserverless.runner-mode=docker,
runs each Spark job run. Floci starts one container per run from the
release's EMR Serverless base image on Amazon ECR Public, and starts
spark-submit in local mode in it itself, since the image's own
entrypoint hands over to a script only EMR Serverless supplies. The
default, immediate, keeps today's behaviour.

A docker run is SCHEDULED while its image is pulled and its container
starts, RUNNING once the Spark driver runs, then SUCCESS when it exits
0 and FAILED otherwise, with the exit code in stateDetails, as the
user guide's job run states describe. CancelJobRun, or a BATCH run
passing its executionTimeoutMinutes, makes it CANCELLING until the
driver is stopped, then CANCELLED. A run left by a Floci restart is
FAILED once read.

Floci's shutdown and a state reset stop every driver, one whose image
is still being pulled as soon as its container is up, and a reset
raises a generation the runs' threads check, so none writes its run
back after the storage wipe. A driver a hard stop left running is
removed before this process starts one: driver containers carry the
deployment's owner label, as EC2's and ECS's do, and
reconcile-containers-on-startup turns the removal off, as theirs does,
for two Flocis sharing a daemon. A stop that comes after its run has
ended is dropped, and a cancel before a run starts is read from the
run's state. A driver is watched with a look at its container every
250 ms, as Batch's runner watches its jobs, so a run holds no Docker
connection while its driver runs; a run past its timeout is
CANCELLING while its driver is stopped.

spark-submit gets the entry point, its arguments and the
sparkSubmitParameters (split as a POSIX shell would), after the
spark-defaults of the application's runtimeConfiguration, or the
run's own in its applicationConfiguration, which replace the
application's whole classification ("Only the properties included in
StartJobRun is considered for this classification"); from
emr-spark-8.1.0 the two merge by property, the run's winning, as its
release notes say. S3A takes s3:// and s3a:// paths to Floci's S3 on
every release, with in-memory commit tracking, without which EMR's
committer loses every write; the Glue Data Catalog client goes to
Floci's Glue. The container gets a session for the run's execution
role and AWS_ENDPOINT_URL, as the other containers Floci launches do.
The image is public.ecr.aws/emr-serverless/spark/<release>:latest, or
spark4/ in place of spark/ for an emr-spark-* release, where ECR
Public keeps the AWS runtime for Apache Spark images. image-template
names another image, and docker-network the network.

Docker answers a stop of a container that has already exited with
HTTP 304, which ContainerLifecycleManager logged as a failed stop
after every run that ended by itself. It now counts as stopped, as a
304 on start already counts as started, and so does the runner's stop
for a cancel that finds the driver already exited.

A Hive run fails without running. Log destinations, retries and the
cancellation grace period are not emulated; the driver's output goes
to Floci's log.

Part of #6046 (REAL-2).
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-24 23:03:37 -05:00
1 parent 68e7b313a8
commit edbcac33c7
12 files changed
+1359 -25

No files matched your search

@@ -3,8 +3,10 @@ package io.github.hectorvent.floci.core.common.docker;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.RemoveContainerCmd;
import com.github.dockerjava.api.command.StopContainerCmd;
import com.github.dockerjava.api.exception.NotModifiedException;
import org.junit.jupiter.api.Test;
import java.io.Closeable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
@@ -15,6 +17,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import static io.github.hectorvent.floci.testing.ThreadStates.awaitBlockedOrDone;
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.assertThrows;
@@ -142,4 +145,27 @@ class ContainerLifecycleManagerTeardownTest {
}
}
@Test
void aContainerThatHadAlreadyExitedCountsAsStopped() throws Exception {
DockerClient docker = mock(DockerClient.class);
ContainerLifecycleManager manager = new ContainerLifecycleManager(docker, null, null, null);
StopContainerCmd stop = mock(StopContainerCmd.class);
when(docker.stopContainerCmd(anyString())).thenReturn(stop);
when(stop.withTimeout(anyInt())).thenReturn(stop);
// Docker answers a stop of an exited container with HTTP 304.
when(stop.exec()).thenThrow(new NotModifiedException("Container already stopped"));
RemoveContainerCmd remove = mock(RemoveContainerCmd.class);
when(docker.removeContainerCmd(anyString())).thenReturn(remove);
when(remove.withForce(true)).thenReturn(remove);
when(remove.exec()).thenThrow(new IllegalStateException("daemon refused removal"));
Closeable logStream = mock(Closeable.class);
manager.stopAndRemove("exited", logStream, 0);
verify(logStream).close();
IllegalStateException failure = assertThrows(IllegalStateException.class,
() -> manager.stopAndRemoveStrict("exited-strict", null));
assertEquals(0, failure.getSuppressed().length);
}
}
@@ -6,10 +6,12 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.emrserverless.model.CreateApplicationRequest;
import io.github.hectorvent.floci.services.emrserverless.model.JobDriver;
import io.github.hectorvent.floci.services.emrserverless.model.JobRun;
import io.github.hectorvent.floci.services.emrserverless.model.JobRunRecord;
import io.github.hectorvent.floci.services.emrserverless.model.RuntimeConfiguration;
import io.github.hectorvent.floci.services.emrserverless.model.StartJobRunRequest;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.testing.InMemoryStorageFactory;
@@ -19,15 +21,22 @@ import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class EmrServerlessJobRunServiceTest {
@@ -42,6 +51,8 @@ class EmrServerlessJobRunServiceTest {
private AccountAwareStorageBackend<JobRunRecord> store;
private MutableClock clock;
private String applicationId;
// The docker runner mode's thread pool, run by hand: a container run's thread is the test's.
private final List<Runnable> tasks = new ArrayList<>();
@BeforeEach
void setUp() {
@@ -203,4 +214,273 @@ class EmrServerlessJobRunServiceTest {
() -> EmrServerlessJobRunService.parseTimestamp("yesterday", "createdAtAfter"));
assertEquals("ValidationException", invalid.getErrorCode());
}
@Test
void aContainerRunIsScheduledUntilItsDriverRunsThenSucceedsWhenItExitsZero() {
FakeRunner runner = new FakeRunner();
EmrServerlessJobRunService service = dockerService(runner);
JobRun submitted = service.startJobRun(applicationId, request(null, null));
String jobRunId = submitted.getJobRunId();
List<JobRun> whileRunning = new ArrayList<>();
runner.whileRunning = () -> {
whileRunning.add(service.getJobRun(applicationId, jobRunId, null));
clock.advance(Duration.ofSeconds(42));
};
assertEquals("SCHEDULED", service.getJobRun(applicationId, jobRunId, null).getState());
assertNull(service.getJobRun(applicationId, jobRunId, null).getStartedAt());
clock.advance(Duration.ofSeconds(3));
runNext();
assertEquals("RUNNING", whileRunning.get(0).getState());
assertEquals(3, Duration.between(submitted.getCreatedAt(), whileRunning.get(0).getStartedAt()).toSeconds());
JobRun finished = service.getJobRun(applicationId, jobRunId, null);
assertEquals("SUCCESS", finished.getState());
assertEquals(42, Duration.between(finished.getStartedAt(), finished.getEndedAt()).toSeconds());
assertEquals(42, finished.getTotalExecutionDurationSeconds());
}
@Test
void theRunnerGetsTheRunsAccountReleaseRoleAndBatchTimeout() {
FakeRunner runner = new FakeRunner();
EmrServerlessJobRunService service = dockerService(runner);
String batch = service.startJobRun(applicationId, request(null, 30L)).getJobRunId();
service.startJobRun(applicationId, request("STREAMING", 30L));
runNext();
runNext();
SparkJobRunner.Job job = runner.jobs.get(0);
assertEquals(batch, job.jobRunId());
assertEquals(applicationId, job.applicationId());
assertEquals(ACCOUNT_ID, job.accountId());
assertEquals(REGION, job.region());
assertEquals("emr-7.5.0", job.releaseLabel());
assertEquals(ROLE, job.executionRole());
assertEquals("s3://bucket/jobs/app.jar", job.sparkSubmit().getEntryPoint());
assertEquals(Duration.ofMinutes(30), job.timeout());
assertEquals(Duration.ZERO, runner.jobs.get(1).timeout());
}
@Test
void aRunsSparkDefaultsReplaceTheApplicationsUntilEmrSpark810MergesThem() {
FakeRunner runner = new FakeRunner();
EmrServerlessJobRunService service = dockerService(runner);
for (String release : List.of("emr-7.10.0", "emr-spark-8.0.0", "emr-spark-8.1.0")) {
String configured = applicationWithSparkDefaults(release);
StartJobRunRequest overriding = request(null, null);
overriding.setConfigurationOverrides(Map.of("applicationConfiguration", List.of(Map.of(
"classification", "spark-defaults", "properties", Map.of("spark.executor.cores", "2")))));
service.startJobRun(configured, request(null, null));
service.startJobRun(configured, overriding);
runNext();
runNext();
}
Map<String, String> fromApp = Map.of("spark.executor.cores", "4", "spark.app.name", "from-app");
List<Map<String, String>> sparkDefaults = runner.jobs.stream().map(SparkJobRunner.Job::sparkDefaults).toList();
assertEquals(List.of(fromApp, Map.of("spark.executor.cores", "2"), fromApp, Map.of("spark.executor.cores", "2"),
fromApp, Map.of("spark.executor.cores", "2", "spark.app.name", "from-app")), sparkDefaults);
assertEquals("emr-spark-8.1.0", runner.jobs.get(5).releaseLabel());
}
private String applicationWithSparkDefaults(String releaseLabel) {
RuntimeConfiguration defaults = new RuntimeConfiguration();
defaults.setMember("classification", "spark-defaults");
defaults.setMember("properties", Map.of("spark.executor.cores", "4", "spark.app.name", "from-app"));
CreateApplicationRequest create = new CreateApplicationRequest();
create.setName("configured-" + releaseLabel);
create.setReleaseLabel(releaseLabel);
create.setType("SPARK");
create.setClientToken(UUID.randomUUID().toString());
create.setRuntimeConfiguration(List.of(defaults));
return applications.createApplication(create).getApplicationId();
}
@Test
void aDriverThatExitsNonZeroOrNeverStartsFailsTheRun() {
FakeRunner runner = new FakeRunner();
EmrServerlessJobRunService service = dockerService(runner);
String exited = service.startJobRun(applicationId, request(null, null)).getJobRunId();
String unstarted = service.startJobRun(applicationId, request(null, null)).getJobRunId();
runner.outcome = SparkJobRunner.Outcome.exitedWith(1);
runNext();
runner.outcome = SparkJobRunner.Outcome.couldNotStart("no such image");
runNext();
JobRun failed = service.getJobRun(applicationId, exited, null);
assertEquals("FAILED", failed.getState());
assertEquals("Job run failed: the Spark driver exited with code 1.", failed.getStateDetails());
assertEquals("FAILED", service.getJobRun(applicationId, unstarted, null).getState());
assertEquals("Job run could not start: no such image",
service.getJobRun(applicationId, unstarted, null).getStateDetails());
}
@Test
void cancellingARunningContainerRunStopsItsDriver() {
FakeRunner runner = new FakeRunner();
EmrServerlessJobRunService service = dockerService(runner);
String jobRunId = service.startJobRun(applicationId, request(null, null)).getJobRunId();
List<String> whileStopping = new ArrayList<>();
runner.whileRunning = () -> {
clock.advance(Duration.ofSeconds(10));
service.cancelJobRun(applicationId, jobRunId);
whileStopping.add(service.getJobRun(applicationId, jobRunId, null).getState());
runNext();
};
runNext();
assertEquals(List.of("CANCELLING"), whileStopping);
assertEquals(Set.of(jobRunId), runner.stopped);
JobRun cancelled = service.getJobRun(applicationId, jobRunId, null);
assertEquals("CANCELLED", cancelled.getState());
assertEquals(10, cancelled.getTotalExecutionDurationSeconds());
}
@Test
void aRunCancelledBeforeItsDriverRunsNeverStarts() {
FakeRunner runner = new FakeRunner();
EmrServerlessJobRunService service = dockerService(runner);
String jobRunId = service.startJobRun(applicationId, request(null, null)).getJobRunId();
service.cancelJobRun(applicationId, jobRunId);
tasks.remove(1).run();
runNext();
JobRun cancelled = service.getJobRun(applicationId, jobRunId, null);
assertEquals("CANCELLED", cancelled.getState());
assertNull(cancelled.getStartedAt());
assertEquals(0, cancelled.getTotalExecutionDurationSeconds());
assertEquals(List.of(), runner.driversStarted);
}
@Test
void aContainerRunPastItsTimeoutIsCancelled() {
FakeRunner runner = new FakeRunner();
runner.outcome = SparkJobRunner.Outcome.outOfTime();
EmrServerlessJobRunService service = dockerService(runner);
String jobRunId = service.startJobRun(applicationId, request(null, 5L)).getJobRunId();
List<String> whileStopping = new ArrayList<>();
runner.whileTimingOut = () -> whileStopping.add(service.getJobRun(applicationId, jobRunId, null).getState());
runNext();
assertEquals(List.of("CANCELLING"), whileStopping);
assertEquals("CANCELLED", service.getJobRun(applicationId, jobRunId, null).getState());
}
@Test
void aHiveRunFailsWithoutRunning() {
CreateApplicationRequest create = new CreateApplicationRequest();
create.setName("hive");
create.setReleaseLabel("emr-7.5.0");
create.setType("HIVE");
create.setClientToken(UUID.randomUUID().toString());
String hive = applications.createApplication(create).getApplicationId();
JobDriver.Hive query = new JobDriver.Hive();
query.setQuery("s3://bucket/queries/report.sql");
StartJobRunRequest request = request(null, null);
request.getJobDriver().setSparkSubmit(null);
request.getJobDriver().setHive(query);
JobRun run = dockerService(new FakeRunner()).startJobRun(hive, request);
assertEquals("FAILED", run.getState());
assertEquals(EmrServerlessJobRunService.HIVE_NOT_RUN, run.getStateDetails());
assertEquals(List.of(), tasks);
}
@Test
void aContainerRunNothingRunsAnyMoreFails() {
FakeRunner runner = new FakeRunner();
String leftByRestart = dockerService(runner).startJobRun(applicationId, request(null, null)).getJobRunId();
EmrServerlessJobRunService service = dockerService(runner);
String stoppedByShutdown = service.startJobRun(applicationId, request(null, null)).getJobRunId();
runner.whileRunning = () -> runner.stop(stoppedByShutdown);
tasks.remove(1).run();
for (String jobRunId : List.of(leftByRestart, stoppedByShutdown)) {
JobRun run = service.getJobRun(applicationId, jobRunId, null);
assertEquals("FAILED", run.getState());
assertEquals(EmrServerlessJobRunService.INTERRUPTED, run.getStateDetails());
}
}
private EmrServerlessJobRunService dockerService(SparkJobRunner runner) {
return new EmrServerlessJobRunService(store, applications, iamService, new RegionResolver(REGION, ACCOUNT_ID),
null, objectMapper, 0, clock, runner, tasks::add);
}
private void runNext() {
tasks.remove(0).run();
}
@Test
void aRunsThreadWritesNothingOnceAResetHasBegun() {
FakeRunner runner = new FakeRunner();
EmrServerlessJobRunService service = dockerService(runner);
String beforeReset = service.startJobRun(applicationId, request(null, null)).getJobRunId();
// The reset's teardown stops the driver while it runs; beforeReset() comes before the storage wipe.
runner.whileRunning = service::beforeReset;
runNext();
assertEquals("RUNNING", store.get(beforeReset).orElseThrow().getJobRun().getState());
runner.whileRunning = () -> { };
String afterReset = service.startJobRun(applicationId, request(null, null)).getJobRunId();
runNext();
assertEquals("SUCCESS", store.get(afterReset).orElseThrow().getJobRun().getState());
}
@Test
void leftoverDriversAreRemovedWhenTheServiceStartsUnlessReconcilingIsOff() {
for (boolean reconcile : List.of(true, false)) {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().emrserverless().runnerMode()).thenReturn("docker");
when(config.services().emrserverless().reconcileContainersOnStartup()).thenReturn(reconcile);
EmrServerlessSparkRunner sparkRunner = mock(EmrServerlessSparkRunner.class);
new EmrServerlessJobRunService(mock(StorageFactory.class), applications, iamService,
new RegionResolver(REGION, ACCOUNT_ID), null, objectMapper, config, clock, sparkRunner).shutdown();
verify(sparkRunner, times(reconcile ? 1 : 0)).removeLeftoverDrivers();
}
}
/**
* Runs a container run on the test's thread: its driver starts, does what the test asks, and ends
* with {@code outcome}, or stopped once {@link #stop} has been called for it.
*/
private static final class FakeRunner implements SparkJobRunner {
final List<Job> jobs = new ArrayList<>();
final Set<String> stopped = new HashSet<>();
final List<String> driversStarted = new ArrayList<>();
Outcome outcome = Outcome.exitedWith(0);
Runnable whileRunning = () -> { };
Runnable whileTimingOut = () -> { };
@Override
public Outcome run(Job job, Progress progress) {
jobs.add(job);
// As the Docker runner, a stop counts only for a run in progress, so a cancel before then is read here.
if (progress.cancelled()) {
return Outcome.halted();
}
driversStarted.add(job.jobRunId());
progress.started();
whileRunning.run();
if (outcome.timedOut()) {
progress.timedOut();
whileTimingOut.run();
}
return stopped.contains(job.jobRunId()) ? Outcome.halted() : outcome;
}
@Override
public void stop(String jobRunId) {
stopped.add(jobRunId);
}
}
}
@@ -0,0 +1,242 @@
package io.github.hectorvent.floci.services.emrserverless;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.exception.NotModifiedException;
import com.github.dockerjava.api.model.Container;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
import io.github.hectorvent.floci.core.common.docker.LaunchedContainerAwsEnv;
import io.github.hectorvent.floci.services.emrserverless.model.JobDriver;
import io.github.hectorvent.floci.services.lambda.launcher.LambdaExecutionRoleCredentials;
import io.github.hectorvent.floci.testing.MutableClock;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anyString;
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.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class EmrServerlessSparkRunnerTest {
private static final String ENDPOINT = "http://floci:4566";
private final EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
private final ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
private final DockerClient docker = mock(DockerClient.class, RETURNS_DEEP_STUBS);
private final SparkJobRunner.Progress progress = mock(SparkJobRunner.Progress.class);
@Test
void sparkSubmitRunsLocallyOnFlocisS3ThenTheRunsOwnSettings() {
JobDriver.SparkSubmit sparkSubmit = new JobDriver.SparkSubmit();
sparkSubmit.setEntryPoint("s3://bucket/jobs/report.py");
sparkSubmit.setEntryPointArguments(List.of("s3://bucket/input/", "s3://bucket/output/"));
sparkSubmit.setSparkSubmitParameters("--conf spark.executor.cores=2 --py-files s3://bucket/jobs/lib.zip");
Map<String, String> defaults = new LinkedHashMap<>();
defaults.put("spark.executor.cores", "4");
defaults.put("spark.sql.shuffle.partitions", "8");
List<String> arguments = EmrServerlessSparkRunner.sparkSubmitArguments(job(sparkSubmit, defaults), ENDPOINT);
assertEquals(List.of("--master", "local[*]",
"--conf", "spark.hadoop.fs.s3a.endpoint=http://floci:4566",
"--conf", "spark.hadoop.fs.s3a.endpoint.region=eu-west-1",
"--conf", "spark.hadoop.fs.s3a.path.style.access=true",
"--conf", "spark.hadoop.fs.s3a.committer.magic.track.commits.in.memory.enabled=true",
"--conf", "spark.hadoop.fs.s3.impl=org.apache.hadoop.fs.s3a.S3AFileSystem",
"--conf", "spark.hadoop.fs.AbstractFileSystem.s3.impl=org.apache.hadoop.fs.s3a.S3A",
"--conf", "spark.hadoop.aws.glue.endpoint=http://floci:4566",
"--conf", "spark.hadoop.aws.region=eu-west-1",
"--conf", "spark.executor.cores=4",
"--conf", "spark.sql.shuffle.partitions=8",
"--conf", "spark.executor.cores=2",
"--py-files", "s3://bucket/jobs/lib.zip",
"s3://bucket/jobs/report.py", "s3://bucket/input/", "s3://bucket/output/"), arguments);
}
@Test
void anEntryPointWithoutParametersOrArgumentsFollowsFlocisSettings() {
JobDriver.SparkSubmit sparkSubmit = new JobDriver.SparkSubmit();
sparkSubmit.setEntryPoint("s3://bucket/jobs/app.jar");
List<String> arguments = EmrServerlessSparkRunner.sparkSubmitArguments(job(sparkSubmit, Map.of()), ENDPOINT);
assertEquals("--conf", arguments.get(arguments.size() - 3));
assertEquals("spark.hadoop.aws.region=eu-west-1", arguments.get(arguments.size() - 2));
assertEquals("s3://bucket/jobs/app.jar", arguments.get(arguments.size() - 1));
}
@Test
void sparkSubmitParametersSplitAsAShellWould() {
assertEquals(List.of("--conf", "spark.driver.extraJavaOptions=-Da=1 -Db=2", "--conf", "x=it's", "a b", ""),
EmrServerlessSparkRunner.splitParameters(
" --conf \"spark.driver.extraJavaOptions=-Da=1 -Db=2\"\t--conf 'x=it'\\''s' a\\ b '' "));
// Inside double quotes a backslash escapes only ", \, $, ` and a newline, and is kept before anything else.
assertEquals(List.of("--conf", "spark.driver.extraJavaOptions=-Dpattern=\\d+ -Dq=\"x\" -Dp=\\ $HOME", "onetwo"),
EmrServerlessSparkRunner.splitParameters(
"--conf \"spark.driver.extraJavaOptions=-Dpattern=\\d+ -Dq=\\\"x\\\" -Dp=\\\\ \\$HOME\" one\\\ntwo"));
assertEquals(List.of(), EmrServerlessSparkRunner.splitParameters(null));
assertEquals(List.of(), EmrServerlessSparkRunner.splitParameters(" "));
}
@Test
void theImageIsTheReleasesPublicImageUnlessATemplateNamesAnother() {
EmrServerlessSparkRunner runner = runner();
assertEquals("public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest", runner.image("emr-7.5.0"));
assertEquals("public.ecr.aws/emr-serverless/spark4/emr-spark-8.1.0:latest", runner.image("emr-spark-8.1.0"));
when(config.services().emrserverless().imageTemplate())
.thenReturn(Optional.of("registry.internal/emr-serverless/spark/%s:20250425"));
assertEquals("registry.internal/emr-serverless/spark/emr-7.5.0:20250425", runner.image("emr-7.5.0"));
}
@Test
void aCancelThatFindsTheDriverAlreadyExitedStillStopsTheRun() {
EmrServerlessSparkRunner runner = runner();
// Docker answers a stop of an exited container with HTTP 304.
when(docker.stopContainerCmd("driver").withTimeout(0).exec())
.thenThrow(new NotModifiedException("Container already stopped"));
SparkJobRunner.Job job = job(Duration.ZERO);
doAnswer(started -> {
runner.stop(job.jobRunId());
return null;
}).when(progress).started();
SparkJobRunner.Outcome outcome = runner.run(job, progress);
assertTrue(outcome.stopped());
verify(lifecycle).stopAndRemove("driver", null, 0);
}
@Test
void aResetWhileTheImageIsPulledStopsTheRunOnceItsContainerIsUp() {
EmrServerlessSparkRunner runner = runner();
when(lifecycle.createAndStart(any())).thenAnswer(pulling -> {
runner.stopManagedContainers();
return new ContainerLifecycleManager.ContainerInfo("driver", Map.of());
});
SparkJobRunner.Outcome outcome = runner.run(job(Duration.ZERO), progress);
assertTrue(outcome.stopped());
verify(progress, never()).started();
verify(lifecycle).stopAndRemove("driver", null, 0);
}
@Test
void aRunCancelledWhileItsImageIsPulledNeverStartsItsDriver() {
EmrServerlessSparkRunner runner = runner();
// Not cancelled when the run begins, cancelled by the time its container is up.
when(progress.cancelled()).thenReturn(false, true);
SparkJobRunner.Outcome outcome = runner.run(job(Duration.ZERO), progress);
assertTrue(outcome.stopped());
verify(progress, never()).started();
verify(lifecycle).stopAndRemove("driver", null, 0);
}
@Test
void aStopAfterTheRunHasEndedIsDropped() {
EmrServerlessSparkRunner runner = runner();
SparkJobRunner.Job job = job(Duration.ZERO);
assertEquals(0, runner.run(job, progress).exitCode());
runner.stop(job.jobRunId());
// A stop kept past its run would halt the next run of this id before it started.
assertEquals(0, runner.run(job, progress).exitCode());
verify(docker, never()).stopContainerCmd(anyString());
}
@Test
void aRunPastItsTimeoutIsToldSoBeforeItsDriverIsRemoved() {
EmrServerlessSparkRunner runner = runner();
when(docker.inspectContainerCmd("driver").exec().getState().getRunning()).thenReturn(true);
SparkJobRunner.Outcome outcome = runner.run(job(Duration.ofMillis(5)), progress);
assertTrue(outcome.timedOut());
InOrder order = inOrder(progress, lifecycle);
order.verify(progress).timedOut();
order.verify(lifecycle).stopAndRemove("driver", null, 0);
}
@Test
void theDriverIsWatchedWithoutHoldingADockerConnection() {
EmrServerlessSparkRunner runner = runner();
runner.run(job(Duration.ZERO), progress);
// A look at the container is one short call; no wait or other stream is held while the driver runs.
verify(docker, atLeastOnce()).inspectContainerCmd("driver");
verify(docker, never()).waitContainerCmd(anyString());
}
@Test
void driversAnEarlierProcessOfThisDeploymentLeftAreRemoved() {
EmrServerlessSparkRunner runner = runner();
when(config.port()).thenReturn(4566);
List<Container> drivers = List.of(driver("left-behind", "4566"), driver("another-deployments", "4567"));
when(docker.listContainersCmd().withShowAll(true).withLabelFilter(anyMap()).exec()).thenReturn(drivers);
runner.removeLeftoverDrivers();
verify(lifecycle).removeIfExists("left-behind");
verify(lifecycle, never()).removeIfExists("another-deployments");
}
// A runner whose driver container, "driver", starts at once and exits with code 0 unless a test says otherwise.
private EmrServerlessSparkRunner runner() {
when(config.services().emrserverless().imageTemplate()).thenReturn(Optional.empty());
when(lifecycle.getDockerClient()).thenReturn(docker);
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("driver", Map.of()));
when(docker.inspectContainerCmd("driver").exec().getState().getRunning()).thenReturn(false);
when(docker.inspectContainerCmd("driver").exec().getState().getExitCodeLong()).thenReturn(0L);
return new EmrServerlessSparkRunner(mock(ContainerBuilder.class, RETURNS_DEEP_STUBS), lifecycle,
mock(ContainerLogStreamer.class), mock(LaunchedContainerAwsEnv.class),
mock(LambdaExecutionRoleCredentials.class), config, new MutableClock(), Duration.ZERO);
}
private static Container driver(String id, String owner) {
Container container = mock(Container.class);
when(container.getId()).thenReturn(id);
when(container.getLabels()).thenReturn(Map.of(ContainerStorageHelper.SERVICE_LABEL, "emr-serverless",
ContainerStorageHelper.OWNER_LABEL, owner));
return container;
}
private static SparkJobRunner.Job job(Duration timeout) {
JobDriver.SparkSubmit sparkSubmit = new JobDriver.SparkSubmit();
sparkSubmit.setEntryPoint("s3://bucket/jobs/app.jar");
return job(sparkSubmit, Map.of(), timeout);
}
private static SparkJobRunner.Job job(JobDriver.SparkSubmit sparkSubmit, Map<String, String> sparkDefaults) {
return job(sparkSubmit, sparkDefaults, Duration.ZERO);
}
private static SparkJobRunner.Job job(JobDriver.SparkSubmit sparkSubmit, Map<String, String> sparkDefaults,
Duration timeout) {
return new SparkJobRunner.Job("00f0000000000001", "00f0000000000000", "123456789012", "eu-west-1",
"emr-7.5.0", "arn:aws:iam::123456789012:role/job", sparkSubmit, sparkDefaults, timeout);
}
}