feat(emr): run Spark steps in containers in a docker runner mode (#6578)

Classic EMR steps never ran: each one completed after
step-duration-seconds, so a step could not fail, a failed step's
ActionOnFailure never applied, and no cluster ever ended
TERMINATED_WITH_ERRORS. A new floci.services.emr.runner-mode, immediate
by default (today's timed lifecycle), runs each step in docker mode:

- One container per step, from when the step goes RUNNING until its
  Spark driver exits, through the runner EMR Serverless's docker mode
  uses: spark-submit in local mode in the release's EMR Serverless image,
  with S3A and Glue pointed at Floci. The cluster gets no container.
- command-runner.jar running spark-submit gets the arguments after it,
  without --master and --deploy-mode; a custom JAR runs its MainClass,
  or its manifest's, with the JAR and its Args. Other steps (Hive, Pig,
  script-runner.jar, other commands) fail without running.
- The step is COMPLETED on exit code 0 and FAILED otherwise, with
  FailureDetails: Reason "Unknown Error", which the API reference says
  EMR gives when it cannot find the root cause, and Floci's message.
- ActionOnFailure as the API reference and the Management Guide give
  it: TERMINATE_CLUSTER ends the cluster unless it waits after its steps
  and is protected; CANCEL_AND_WAIT cancels the pending steps and waits,
  or ends a cluster set to end after its steps; CONTINUE goes on; none
  applies above concurrency level 1, nor CANCEL_AND_WAIT with other
  steps running. A cluster a failure ends is TERMINATED_WITH_ERRORS with
  STEP_FAILURE and "Shut down as step failed".
- Step FAILED (ERROR) and cluster TERMINATED_WITH_ERRORS (CRITICAL)
  events, with the messages of the guide's event tables.
- CancelSteps and TerminateJobFlows stop a running step's driver. A
  driver Floci's shutdown or a reset stops leaves its step as it is, so
  no other step starts once the teardown has passed: a step Floci was
  running is FAILED once Floci is back, and a reset's threads write
  nothing after it. Leftover drivers are removed when the service
  starts, before any step can, unless reconcile-containers-on-startup is
  off.
- The driver runs as the step's ExecutionRoleArn, or else the role of
  the cluster's JobFlowRole instance profile, and gets the spark-defaults
  of the cluster's Configurations.

New settings: runner-mode, docker-network, image-template and
reconcile-containers-on-startup, as EMR Serverless has.

The shared runner now reads Progress.cancelled() at every look at a
running driver, so a driver whose run a reset removed is stopped, and
removeLeftoverDrivers is on SparkJobRunner. EMR Serverless's job run
service counts a RUNNING run as not cancelled accordingly.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-25 22:30:25 -05:00
1 parent 5c7c84374b
commit 4b33002784
18 files changed
+1236 -56

No files matched your search

@@ -0,0 +1,437 @@
package io.github.hectorvent.floci.services.emr;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.emr.model.EmrCluster;
import io.github.hectorvent.floci.services.emr.model.EmrStep;
import io.github.hectorvent.floci.services.emrserverless.EmrServerlessSparkRunner;
import io.github.hectorvent.floci.services.emrserverless.SparkJobRunner;
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.IamRole;
import io.github.hectorvent.floci.services.iam.model.InstanceProfile;
import io.github.hectorvent.floci.testing.InMemoryStorageFactory;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import java.time.Duration;
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 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.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* The {@code docker} runner mode: each step runs in a container from when it goes RUNNING until its Spark
* driver ends, and then is COMPLETED, or FAILED with its ActionOnFailure taken, as the API reference and
* the Management Guide give it.
*/
class EmrServiceContainerStepsTest {
private static final String REPORT = "s3://bucket/jobs/report.py";
private static final String DRIVER_FAILED = "The Spark driver exited with code 1.";
private final FakeRunner runner = new FakeRunner();
private final EmrServiceFixture fixture = EmrServiceFixture.docker(runner, null);
private final EmrService service = fixture.service;
@Test
void aStepRunsInAContainerFromWhenItStartsUntilItsDriverExits() {
EmrCluster requested = cluster("real", true, sparkStep("report", "CONTINUE"));
requested.setConfigurations("""
[{"Classification": "spark-defaults", "Properties": {"spark.executor.cores": "2"}}]""");
EmrCluster cluster = service.runJobFlow(requested, REGION);
String stepId = cluster.getSteps().get(0).getId();
assertEquals("RUNNING", service.describeStep(cluster.getId(), stepId).getState());
assertEquals("RUNNING", service.describeCluster(cluster.getId()).getState());
fixture.clock.advance(Duration.ofSeconds(30));
fixture.runStepThread();
EmrStep completed = service.describeStep(cluster.getId(), stepId);
assertEquals("COMPLETED", completed.getState());
assertEquals(30, Duration.between(completed.getStartDateTime(), completed.getEndDateTime()).toSeconds());
assertEquals("WAITING", service.describeCluster(cluster.getId()).getState());
assertEquals(List.of("STARTING", "PENDING report", "RUNNING report", "COMPLETED report", "WAITING"),
fixture.states());
SparkJobRunner.Job job = runner.jobs.get(0);
assertEquals("emr", job.service());
assertEquals(stepId, job.runId());
assertEquals(ACCOUNT, job.accountId());
assertEquals(REGION, job.region());
assertEquals("emr-7.5.0", job.releaseLabel());
assertNull(job.imageTemplate());
assertNull(job.dockerNetwork());
assertEquals(List.of(REPORT, "s3://bucket/out/"), job.application());
assertEquals(Map.of("spark.executor.cores", "2"), job.sparkDefaults());
assertEquals(Duration.ZERO, job.timeout());
}
@Test
void aStepWhoseDriverFailsIsFailedAndOnContinueTheNextOneRuns() {
EmrCluster cluster = service.runJobFlow(cluster("continuing", true,
sparkStep("breaks", "CONTINUE"), sparkStep("next", "CONTINUE")), REGION);
String failedId = cluster.getSteps().get(0).getId();
runner.outcome = SparkJobRunner.Outcome.exitedWith(1);
fixture.runStepThread();
EmrStep failed = service.describeStep(cluster.getId(), failedId);
assertEquals("FAILED", failed.getState());
assertEquals("Unknown Error", failed.getFailureReason());
assertEquals(DRIVER_FAILED, failed.getFailureMessage());
assertEquals("RUNNING", service.describeStep(cluster.getId(), cluster.getSteps().get(1).getId()).getState());
// The step's FAILED, then the next one's RUNNING.
JsonNode event = fixture.published.get(fixture.published.size() - 2).path("detail");
assertEquals("FAILED", event.path("state").asText());
assertEquals("ERROR", event.path("severity").asText());
assertEquals("Step " + failedId + " (breaks) in Amazon EMR cluster " + cluster.getId() + " (continuing) failed"
+ " at 2026-01-01 00:00 UTC.", event.path("message").asText());
runner.outcome = SparkJobRunner.Outcome.exitedWith(0);
fixture.runStepThread();
assertEquals("WAITING", service.describeCluster(cluster.getId()).getState());
}
@Test
void terminateClusterEndsTheClusterWithErrorsAndCancelsTheStepsLeft() {
EmrCluster cluster = service.runJobFlow(cluster("doomed", true,
sparkStep("breaks", "TERMINATE_CLUSTER"), sparkStep("never", "CONTINUE")), REGION);
runner.outcome = SparkJobRunner.Outcome.exitedWith(1);
fixture.runStepThread();
EmrCluster ended = service.describeCluster(cluster.getId());
assertEquals("TERMINATED_WITH_ERRORS", ended.getState());
assertEquals("STEP_FAILURE", ended.getStateChangeReasonCode());
assertEquals("Shut down as step failed", ended.getStateChangeMessage());
assertEquals("CANCELLED", service.describeStep(cluster.getId(), cluster.getSteps().get(1).getId()).getState());
assertEquals(1, runner.jobs.size());
assertEquals(List.of("STARTING", "PENDING breaks", "PENDING never", "RUNNING breaks", "FAILED breaks",
"CANCELLED never", "TERMINATED_WITH_ERRORS"), fixture.states());
JsonNode event = fixture.published.get(fixture.published.size() - 1).path("detail");
assertEquals("CRITICAL", event.path("severity").asText());
assertEquals("{\"code\":\"STEP_FAILURE\",\"message\":\"Shut down as step failed\"}",
event.path("stateChangeReason").asText());
assertEquals("Amazon EMR Cluster " + cluster.getId() + " (doomed) has terminated with errors at"
+ " 2026-01-01 00:00 UTC with a reason of STEP_FAILURE.", event.path("message").asText());
}
@Test
void terminateClusterLeavesAProtectedClusterThatWaitsAfterItsStepsRunning() {
EmrCluster requested = cluster("protected", true, sparkStep("breaks", "TERMINATE_CLUSTER"),
sparkStep("next", "CONTINUE"));
requested.setTerminationProtected(true);
EmrCluster cluster = service.runJobFlow(requested, REGION);
runner.outcome = SparkJobRunner.Outcome.exitedWith(1);
fixture.runStepThread();
assertEquals("RUNNING", service.describeCluster(cluster.getId()).getState());
assertEquals("RUNNING", service.describeStep(cluster.getId(), cluster.getSteps().get(1).getId()).getState());
}
@Test
void terminateClusterEndsAProtectedClusterSetToEndAfterItsSteps() {
EmrCluster requested = cluster("transient", false, sparkStep("breaks", "TERMINATE_CLUSTER"));
requested.setTerminationProtected(true);
EmrCluster cluster = service.runJobFlow(requested, REGION);
runner.outcome = SparkJobRunner.Outcome.exitedWith(1);
fixture.runStepThread();
assertEquals("TERMINATED_WITH_ERRORS", service.describeCluster(cluster.getId()).getState());
}
@Test
void cancelAndWaitCancelsThePendingStepsAndWaits() {
EmrCluster cluster = service.runJobFlow(cluster("waits", true,
sparkStep("breaks", "CANCEL_AND_WAIT"), sparkStep("cancelled", "CONTINUE")), REGION);
runner.outcome = SparkJobRunner.Outcome.exitedWith(1);
fixture.runStepThread();
EmrCluster waiting = service.describeCluster(cluster.getId());
assertEquals("WAITING", waiting.getState());
assertEquals("CANCELLED", waiting.getSteps().get(1).getState());
assertEquals(1, runner.jobs.size());
}
@Test
void cancelAndWaitEndsAClusterSetToEndAfterItsSteps() {
EmrCluster cluster = service.runJobFlow(cluster("transient", false,
sparkStep("breaks", "CANCEL_AND_WAIT"), sparkStep("never", "CONTINUE")), REGION);
runner.outcome = SparkJobRunner.Outcome.exitedWith(1);
fixture.runStepThread();
EmrCluster ended = service.describeCluster(cluster.getId());
assertEquals("TERMINATED_WITH_ERRORS", ended.getState());
assertEquals("STEP_FAILURE", ended.getStateChangeReasonCode());
assertEquals("CANCELLED", ended.getSteps().get(1).getState());
}
@Test
void actionOnFailureDoesNotActivateWhileTheConcurrencyLevelIsAboveOne() {
EmrCluster requested = cluster("parallel", true, sparkStep("breaks", "TERMINATE_CLUSTER"),
sparkStep("alongside", "CONTINUE"));
requested.setStepConcurrencyLevel(2);
EmrCluster cluster = service.runJobFlow(requested, REGION);
runner.outcome = SparkJobRunner.Outcome.exitedWith(1);
fixture.runStepThread();
assertEquals("RUNNING", service.describeCluster(cluster.getId()).getState());
assertEquals("RUNNING", service.describeStep(cluster.getId(), cluster.getSteps().get(1).getId()).getState());
}
@Test
void aStepFlociDoesNotRunFailsWithoutRunning() {
EmrStep hive = sparkStep("query", "CONTINUE");
hive.setArgs(List.of("hive-script", "--run-hive-script", "--args", "-f", "s3://bucket/query.q"));
EmrCluster cluster = service.runJobFlow(cluster("hive", true, hive), REGION);
fixture.runStepThread();
EmrStep failed = service.describeStep(cluster.getId(), cluster.getSteps().get(0).getId());
assertEquals("FAILED", failed.getState());
assertEquals(EmrSparkSteps.NOT_RUN, failed.getFailureMessage());
assertEquals(List.of(), runner.jobs);
}
@Test
void describeStepAnswersAFailedStepsFailureDetails() {
EmrCluster cluster = service.runJobFlow(cluster("described", true, sparkStep("breaks", "CONTINUE")), REGION);
runner.outcome = SparkJobRunner.Outcome.couldNotStart("Could not pull image: Downloading");
fixture.runStepThread();
ObjectMapper objectMapper = new ObjectMapper();
JsonNode answer = (JsonNode) new EmrHandler(service, objectMapper).handle("DescribeStep",
objectMapper.createObjectNode().put("ClusterId", cluster.getId())
.put("StepId", cluster.getSteps().get(0).getId()), REGION).getEntity();
JsonNode status = answer.path("Step").path("Status");
assertEquals("FAILED", status.path("State").asText());
assertEquals("Unknown Error", status.path("FailureDetails").path("Reason").asText());
assertEquals("The step could not start: Could not pull image: Downloading",
status.path("FailureDetails").path("Message").asText());
}
@Test
void cancellingARunningStepStopsItsDriverAndStartsTheNext() {
EmrCluster cluster = service.runJobFlow(cluster("cancelling", true,
sparkStep("stopped", "TERMINATE_CLUSTER"), sparkStep("next", "CONTINUE")), REGION);
String stoppedId = cluster.getSteps().get(0).getId();
runner.whileRunning = () -> service.cancelSteps(cluster.getId(), List.of(stoppedId));
fixture.runStepThread();
assertEquals(Set.of(stoppedId), runner.stopped);
EmrCluster running = service.describeCluster(cluster.getId());
assertEquals("CANCELLED", running.getSteps().get(0).getState());
// "Canceling a running step does not trigger the step ActionOnFailure."
assertEquals("RUNNING", running.getState());
assertEquals("RUNNING", running.getSteps().get(1).getState());
}
@Test
void aStepCancelledBeforeItsDriverStartsNeverStartsIt() {
EmrCluster cluster = service.runJobFlow(cluster("early", true, sparkStep("never", "CONTINUE")), REGION);
service.cancelSteps(cluster.getId(), List.of(cluster.getSteps().get(0).getId()));
fixture.runStepThread();
assertEquals(List.of(), runner.driversStarted);
assertEquals("CANCELLED", service.describeCluster(cluster.getId()).getSteps().get(0).getState());
}
@Test
void terminatingTheClusterStopsTheDriversOfItsRunningSteps() {
EmrCluster cluster = service.runJobFlow(cluster("ended", true, sparkStep("stopped", "CONTINUE")), REGION);
String stepId = cluster.getSteps().get(0).getId();
runner.whileRunning = () -> service.terminateJobFlows(List.of(cluster.getId()));
fixture.runStepThread();
assertEquals(Set.of(stepId), runner.stopped);
EmrCluster ended = service.describeCluster(cluster.getId());
assertEquals("TERMINATED", ended.getState());
assertEquals("USER_REQUEST", ended.getStateChangeReasonCode());
assertEquals("CANCELLED", ended.getSteps().get(0).getState());
}
@Test
void aStepRunningWhenFlociStoppedFailsOnceFlociIsBack() {
EmrCluster cluster = service.runJobFlow(cluster("restarted", true, sparkStep("cut", "CONTINUE")), REGION);
String stepId = cluster.getSteps().get(0).getId();
EmrServiceFixture restarted = fixture.restart();
restarted.pass(Duration.ZERO);
EmrStep failed = restarted.service.describeStep(cluster.getId(), stepId);
assertEquals("FAILED", failed.getState());
assertEquals(EmrSparkSteps.INTERRUPTED, failed.getFailureMessage());
assertEquals(List.of("FAILED cut", "WAITING"), restarted.states());
}
@Test
void aStepsThreadWritesNothingOnceAResetHasBegun() {
service.runJobFlow(cluster("reset", true, sparkStep("cut", "CONTINUE")), REGION);
// The reset's teardown stops the driver while it runs; beforeReset() comes before the storage wipe.
runner.whileRunning = service::beforeReset;
fixture.runStepThread();
assertEquals(List.of("STARTING", "PENDING cut", "RUNNING cut"), fixture.states());
// The runner stops a running driver whose step the reset removed.
assertEquals(List.of(false, true), runner.cancelledAsRunning);
}
@Test
void aDriverFlociStoppedLeavesItsStepForTheResetOrTheRestartToEnd() {
EmrCluster cluster = service.runJobFlow(
cluster("stopped", true, sparkStep("cut", "CONTINUE"), sparkStep("next", "CONTINUE")), REGION);
String stepId = cluster.getSteps().get(0).getId();
// A reset's teardown, or Floci's shutdown, stops the driver; the step asked for no stop.
runner.outcome = SparkJobRunner.Outcome.halted();
fixture.runStepThread();
// Taking CONTINUE now would start the next step's driver after the teardown has passed.
assertEquals("RUNNING", service.describeStep(cluster.getId(), stepId).getState());
assertEquals(0, fixture.stepThreadsWaiting());
assertEquals(List.of("STARTING", "PENDING cut", "PENDING next", "RUNNING cut"), fixture.states());
EmrServiceFixture restarted = fixture.restart();
restarted.pass(Duration.ZERO);
assertEquals("FAILED", restarted.service.describeStep(cluster.getId(), stepId).getState());
assertEquals(List.of("FAILED cut", "RUNNING next"), restarted.states());
}
@Test
void leftoverDriversAreRemovedBeforeARestartedClusterCanStartAStep() {
service.runJobFlow(cluster("restarted", true, sparkStep("cut", "CONTINUE"), sparkStep("next", "CONTINUE")),
REGION);
SparkJobRunner restartedRunner = mock(SparkJobRunner.class);
EmrService.Wakeups wakeups = mock(EmrService.Wakeups.class);
fixture.restartReconciling(restartedRunner, wakeups);
// The wakeup that fails the step Floci was running starts the next one, whose driver the sweep would remove.
InOrder order = inOrder(restartedRunner, wakeups);
order.verify(restartedRunner).removeLeftoverDrivers("emr");
order.verify(wakeups).at(any(), any());
}
@Test
void aStepRunsAsItsRuntimeRoleOrElseAsTheClustersInstanceProfileRole() {
IamService iam = mock(IamService.class);
InstanceProfile profile = new InstanceProfile();
profile.setRoleNames(List.of("emr-ec2"));
IamRole role = new IamRole();
role.setArn("arn:aws:iam::" + ACCOUNT + ":role/emr-ec2");
when(iam.findInstanceProfile(ACCOUNT, "EMR_EC2_DefaultRole")).thenReturn(Optional.of(profile));
when(iam.findRole(ACCOUNT, "emr-ec2")).thenReturn(Optional.of(role));
EmrServiceFixture withIam = EmrServiceFixture.docker(runner, iam);
EmrStep runtime = sparkStep("runtime", "CONTINUE");
runtime.setExecutionRoleArn("arn:aws:iam::" + ACCOUNT + ":role/step");
EmrCluster requested = cluster("roles", true, sparkStep("profile", "CONTINUE"), runtime);
requested.setJobFlowRole("EMR_EC2_DefaultRole");
withIam.service.runJobFlow(requested, REGION);
withIam.runStepThread();
withIam.runStepThread();
assertEquals("arn:aws:iam::" + ACCOUNT + ":role/emr-ec2", runner.jobs.get(0).executionRole());
assertEquals("arn:aws:iam::" + ACCOUNT + ":role/step", runner.jobs.get(1).executionRole());
}
@Test
void aStepRunsWithoutARoleWhenIamKnowsNone() {
service.runJobFlow(cluster("roleless", true, sparkStep("plain", "CONTINUE")), REGION);
fixture.runStepThread();
assertNull(runner.jobs.get(0).executionRole());
}
@Test
void leftoverDriversAreRemovedWhenTheServiceStartsUnlessReconcilingIsOff() {
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);
RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT);
new EmrService(new InMemoryStorageFactory(ACCOUNT), config, regionResolver,
new EmrEventPublisher(mock(EventBridgeService.class), new ObjectMapper(), regionResolver),
sparkRunner, mock(IamService.class)).shutdown();
verify(sparkRunner, times(reconcile ? 1 : 0)).removeLeftoverDrivers("emr");
}
}
// A spark-submit step through command-runner.jar, written for a cluster with YARN.
private static EmrStep sparkStep(String name, String actionOnFailure) {
EmrStep step = new EmrStep();
step.setName(name);
step.setActionOnFailure(actionOnFailure);
step.setJar("command-runner.jar");
step.setArgs(new ArrayList<>(List.of("spark-submit", "--deploy-mode", "cluster", REPORT, "s3://bucket/out/")));
return step;
}
/**
* Runs a step's driver on the test's thread: it 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<>();
// What progress.cancelled() said once the driver ran, and again after whileRunning.
final List<Boolean> cancelledAsRunning = new ArrayList<>();
Outcome outcome = Outcome.exitedWith(0);
Runnable whileRunning = () -> { };
@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.runId());
progress.started();
cancelledAsRunning.add(progress.cancelled());
whileRunning.run();
cancelledAsRunning.add(progress.cancelled());
return stopped.contains(job.runId()) ? Outcome.halted() : outcome;
}
@Override
public void stop(String runId) {
stopped.add(runId);
}
@Override
public void removeLeftoverDrivers(String service) {
// A test's drivers live no longer than its runs.
}
}
}
@@ -6,7 +6,9 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.emr.model.EmrCluster;
import io.github.hectorvent.floci.services.emr.model.EmrStep;
import io.github.hectorvent.floci.services.emrserverless.SparkJobRunner;
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.testing.InMemoryStorageFactory;
import io.github.hectorvent.floci.testing.MutableClock;
@@ -14,6 +16,7 @@ import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.ArgumentMatchers.anyString;
@@ -28,7 +31,8 @@ import static org.mockito.Mockito.when;
* An {@link EmrService} on in-memory storage, with a clock the test moves and wakeups the test runs,
* recording the {@code aws.emr} events it publishes. Each event is handed to {@link #target} as it is
* published, as EventBridge's first delivery is, and checked to be published once the service is let go,
* and, for a wakeup's, after it, as the timer's own thread never sends them.
* and, for a wakeup's, after it, as the timer's own thread never sends them. In the {@code docker} runner
* mode a step's thread is one the test runs, with {@link #runStepThread}.
*/
final class EmrServiceFixture {
@@ -52,8 +56,12 @@ final class EmrServiceFixture {
Target target = event -> { };
private final List<Wakeup> wakeups = new ArrayList<>();
private final List<Runnable> deliveries = new ArrayList<>();
// The docker runner mode's step threads, not yet run.
private final List<Runnable> stepThreads = new ArrayList<>();
private boolean waking;
private final InMemoryStorageFactory storage;
private final SparkJobRunner runner;
private final IamService iam;
private final int[] durations;
/** The service as configured by default, every duration 0. */
@@ -62,13 +70,21 @@ final class EmrServiceFixture {
}
EmrServiceFixture(int startupDelaySeconds, int stepDurationSeconds, int terminationDelaySeconds) {
this(new InMemoryStorageFactory(ACCOUNT), new MutableClock(),
this(new InMemoryStorageFactory(ACCOUNT), new MutableClock(), null, null,
startupDelaySeconds, stepDurationSeconds, terminationDelaySeconds);
}
private EmrServiceFixture(InMemoryStorageFactory storage, MutableClock clock, int... durations) {
/** The service in the {@code docker} runner mode, every duration 0, its steps run by {@code runner}. */
static EmrServiceFixture docker(SparkJobRunner runner, IamService iam) {
return new EmrServiceFixture(new InMemoryStorageFactory(ACCOUNT), new MutableClock(), runner, iam, 0, 0, 0);
}
private EmrServiceFixture(InMemoryStorageFactory storage, MutableClock clock, SparkJobRunner runner,
IamService iam, int... durations) {
this.storage = storage;
this.clock = clock;
this.runner = runner;
this.iam = iam;
this.durations = durations;
EventBridgeService eventBridge = mock(EventBridgeService.class);
doAnswer(invocation -> {
@@ -82,14 +98,9 @@ final class EmrServiceFixture {
target.deliver(event);
return null;
}).when(eventBridge).publishServiceEvent(eq("aws.emr"), anyString(), anyString(), isNull(), eq(REGION));
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().emr().defaultReleaseLabel()).thenReturn("emr-7.5.0");
when(config.services().emr().clusterStartupDelaySeconds()).thenReturn(durations[0]);
when(config.services().emr().stepDurationSeconds()).thenReturn(durations[1]);
when(config.services().emr().clusterTerminationDelaySeconds()).thenReturn(durations[2]);
RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT);
publisher = new EmrEventPublisher(eventBridge, objectMapper, regionResolver);
service = new EmrService(storage, config, regionResolver, publisher, clock, new EmrService.Wakeups() {
service = new EmrService(storage, config(false), regionResolver, publisher, clock, new EmrService.Wakeups() {
@Override
public void at(Instant due, Runnable task) {
wakeups.add(new Wakeup(due, task));
@@ -99,12 +110,43 @@ final class EmrServiceFixture {
public void deliver(Runnable delivery) {
deliveries.add(delivery);
}
});
}, runner, 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, durations);
return new EmrServiceFixture(storage, clock, runner, iam, durations);
}
/**
* A new service on the same storage and clock, as {@link #restart} builds, but with {@code runner},
* its wakeups set on {@code wakeups}, and leftover drivers removed when it starts.
*/
EmrService restartReconciling(SparkJobRunner runner, EmrService.Wakeups wakeups) {
return new EmrService(storage, config(true), new RegionResolver(REGION, ACCOUNT), publisher, clock, wakeups,
runner, stepThreads::add, iam);
}
private EmulatorConfig config(boolean reconcile) {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().emr().defaultReleaseLabel()).thenReturn("emr-7.5.0");
when(config.services().emr().clusterStartupDelaySeconds()).thenReturn(durations[0]);
when(config.services().emr().stepDurationSeconds()).thenReturn(durations[1]);
when(config.services().emr().clusterTerminationDelaySeconds()).thenReturn(durations[2]);
when(config.services().emr().imageTemplate()).thenReturn(Optional.empty());
when(config.services().emr().dockerNetwork()).thenReturn(Optional.empty());
when(config.services().emr().reconcileContainersOnStartup()).thenReturn(reconcile);
return config;
}
/** Runs the oldest step thread not yet run, as the docker runner mode's pool would. */
void runStepThread() {
stepThreads.remove(0).run();
}
/** How many step threads have been started and not yet run. */
int stepThreadsWaiting() {
return stepThreads.size();
}
/**
@@ -0,0 +1,72 @@
package io.github.hectorvent.floci.services.emr;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.emr.model.EmrStep;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
class EmrSparkStepsTest {
private final ObjectMapper objectMapper = new ObjectMapper();
@Test
void aCommandRunnerSparkSubmitStepRunsLocallyWithoutItsMasterOrDeployMode() {
EmrStep step = step("command-runner.jar", null, "spark-submit", "--deploy-mode", "cluster",
"--master=yarn", "--verbose", "--conf", "spark.executor.cores=2", "--class", "com.example.Report",
"s3://bucket/jobs/report.jar", "--master", "kept");
// Options come before the application, so --master after it is the application's own argument.
assertEquals(List.of("--verbose", "--conf", "spark.executor.cores=2", "--class", "com.example.Report",
"s3://bucket/jobs/report.jar", "--master", "kept"), EmrSparkSteps.application(step));
}
@Test
void sparkSubmitMayBeNamedByItsPath() {
assertEquals(List.of("s3://bucket/jobs/report.py"), EmrSparkSteps.application(
step("command-runner.jar", null, "/usr/bin/spark-submit", "s3://bucket/jobs/report.py")));
}
@Test
void aCustomJarRunsItsMainClassOrElseItsManifests() {
assertEquals(List.of("--class", "com.example.Report", "s3://bucket/jobs/report.jar", "2026-10-25"),
EmrSparkSteps.application(step("s3://bucket/jobs/report.jar", "com.example.Report", "2026-10-25")));
assertEquals(List.of("s3://bucket/jobs/report.jar"),
EmrSparkSteps.application(step("s3://bucket/jobs/report.jar", null)));
}
@Test
void stepsOtherThanSparkAreNotRun() {
assertNull(EmrSparkSteps.application(step("command-runner.jar", null, "hive-script", "--run-hive-script")));
assertNull(EmrSparkSteps.application(step("command-runner.jar", null)));
assertNull(EmrSparkSteps.application(
step("s3://us-east-1.elasticmapreduce/libs/script-runner/script-runner.jar", null, "s3://b/x.sh")));
assertNull(EmrSparkSteps.application(step(null, null)));
}
@Test
void theClustersSparkDefaultsComeFromItsConfigurations() {
String configurations = """
[{"Classification": "spark-env", "Properties": {"JAVA_HOME": "/usr/lib/jvm"}},
{"Classification": "spark-defaults", "Properties": {"spark.executor.cores": "2",
"spark.sql.shuffle.partitions": "8"}}]
""";
assertEquals(Map.of("spark.executor.cores", "2", "spark.sql.shuffle.partitions", "8"),
EmrSparkSteps.sparkDefaults(configurations, objectMapper));
assertEquals(Map.of(), EmrSparkSteps.sparkDefaults(null, objectMapper));
assertEquals(Map.of(), EmrSparkSteps.sparkDefaults("[{", objectMapper));
}
private static EmrStep step(String jar, String mainClass, String... args) {
EmrStep step = new EmrStep();
step.setJar(jar);
step.setMainClass(mainClass);
step.setArgs(List.of(args));
return step;
}
}
@@ -446,6 +446,8 @@ class EmrServerlessJobRunServiceTest {
String afterReset = service.startJobRun(applicationId, request(null, null)).getJobRunId();
runNext();
assertEquals("SUCCESS", store.get(afterReset).orElseThrow().getJobRun().getState());
// A running driver goes on, and the runner stops one whose run the reset removed.
assertEquals(List.of(false, true, false, false), runner.cancelledAsRunning);
}
@Test
@@ -471,6 +473,8 @@ class EmrServerlessJobRunServiceTest {
final List<Job> jobs = new ArrayList<>();
final Set<String> stopped = new HashSet<>();
final List<String> driversStarted = new ArrayList<>();
// What progress.cancelled() said once the driver ran, and again after whileRunning.
final List<Boolean> cancelledAsRunning = new ArrayList<>();
Outcome outcome = Outcome.exitedWith(0);
Runnable whileRunning = () -> { };
Runnable whileTimingOut = () -> { };
@@ -484,7 +488,9 @@ class EmrServerlessJobRunServiceTest {
}
driversStarted.add(job.runId());
progress.started();
cancelledAsRunning.add(progress.cancelled());
whileRunning.run();
cancelledAsRunning.add(progress.cancelled());
if (outcome.timedOut()) {
progress.timedOut();
whileTimingOut.run();
@@ -496,5 +502,10 @@ class EmrServerlessJobRunServiceTest {
public void stop(String runId) {
stopped.add(runId);
}
@Override
public void removeLeftoverDrivers(String service) {
// A test's drivers live no longer than its runs.
}
}
}
@@ -189,6 +189,21 @@ class EmrServerlessSparkRunnerTest {
verify(lifecycle).stopAndRemove("driver", null, 0);
}
@Test
void aRunningDriverWhoseRunIsGoneIsStoppedAtTheNextLook() {
EmrServerlessSparkRunner runner = runner();
// A reset removes the run while its driver runs: not cancelled before the driver starts, nor at the
// first look at it, then gone. Left to itself, the driver would run on for four more looks, then exit.
when(progress.cancelled()).thenReturn(false, false, false, true);
when(docker.inspectContainerCmd("driver").exec().getState().getRunning())
.thenReturn(true, true, true, true, true, false);
SparkJobRunner.Outcome outcome = runner.run(job(Duration.ZERO), progress);
assertTrue(outcome.stopped());
verify(lifecycle).stopAndRemove("driver", null, 0);
}
@Test
void aStopAfterTheRunHasEndedIsDropped() {
EmrServerlessSparkRunner runner = runner();