mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
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:
1 parent
5c7c84374b
commit
4b33002784
18 files changed
+1236
-56
No files matched your search
+58
-6
@@ -4,7 +4,7 @@
|
||||
**Endpoint:** `http://localhost:4566/`
|
||||
**Target prefix:** `X-Amz-Target: ElasticMapReduce.*`
|
||||
|
||||
Floci emulates the Amazon EMR (Elastic MapReduce) management API. Clusters (job flows), instance groups and fleets, steps, security configurations, and tags are tracked in Floci's storage backend so the AWS CLI and SDK clients can drive the full cluster lifecycle locally. EMR does not launch real Hadoop/Spark clusters — clusters transition through their lifecycle states as a state machine.
|
||||
Floci emulates the Amazon EMR (Elastic MapReduce) management API. Clusters (job flows), instance groups and fleets, steps, security configurations, and tags are tracked in Floci's storage backend so the AWS CLI and SDK clients can drive the full cluster lifecycle locally. EMR does not launch real Hadoop/Spark clusters. Clusters transition through their lifecycle states as a state machine. In the `docker` runner mode Spark steps run for real, each in a container of its own (see [Running Spark steps](#running-spark-steps)).
|
||||
|
||||
## Supported Actions
|
||||
|
||||
@@ -55,8 +55,8 @@ Floci emulates the Amazon EMR (Elastic MapReduce) management API. Clusters (job
|
||||
|
||||
## Cluster lifecycle
|
||||
|
||||
Nothing runs in this metadata-only emulator, but a cluster and its steps go through the states of the
|
||||
Management Guide's cluster lifecycle, each held for as long as the [configuration](#configuration)
|
||||
In the default `immediate` runner mode nothing runs, but a cluster and its steps go through the states
|
||||
of the Management Guide's cluster lifecycle, each held for as long as the [configuration](#configuration)
|
||||
says. A cluster is `STARTING` for the first half of `cluster-startup-delay-seconds` and `BOOTSTRAPPING`
|
||||
for the second, then `RUNNING` while it runs steps and `WAITING` once it has none left. A request's
|
||||
steps are all created `PENDING`, then start in the order they were added, at most `StepConcurrencyLevel`
|
||||
@@ -105,6 +105,53 @@ still accepted.
|
||||
A state machine drives clusters and steps through the `elasticmapreduce:` integrations, `.sync`
|
||||
included; see [Step Functions: Amazon EMR tasks](step-functions.md#amazon-emr-tasks).
|
||||
|
||||
## Running Spark steps
|
||||
|
||||
With `runner-mode` set to `docker` (`FLOCI_SERVICES_EMR_RUNNER_MODE=docker`), a Spark step runs. Floci
|
||||
starts one container per step from the cluster's release image, the one EMR Serverless's `docker` mode
|
||||
uses (`public.ecr.aws/emr-serverless/spark/<release>`), and runs `spark-submit` in local mode in it: the
|
||||
container holds the driver and its executors. The cluster itself gets no container, and goes through
|
||||
its lifecycle as in the `immediate` mode.
|
||||
|
||||
* **Which steps run**: a `command-runner.jar` step whose first argument is `spark-submit`, the way the
|
||||
Management Guide writes Spark steps, runs the arguments after it, without its `--master` and
|
||||
`--deploy-mode`. A custom JAR step runs its `MainClass`, or else the one its manifest names, through
|
||||
`spark-submit`, with the JAR and the step's `Args`. Any other step, such as Hive, Pig,
|
||||
`script-runner.jar` or another `command-runner.jar` command, is `FAILED` without running.
|
||||
* **States**: a step is `RUNNING` from when it starts until its driver exits; `step-duration-seconds`
|
||||
does not apply. The first step of a release also waits while its image is pulled (3.5 to 4.3 GB
|
||||
unpacked; see [`floci.docker.image-pull-timeout-seconds`](../configuration/docker.md)). It is then
|
||||
`COMPLETED` on exit code 0, and `FAILED` otherwise. A `FAILED` step's `Status.FailureDetails` has the `Reason`
|
||||
"Unknown Error", which the API reference says EMR gives when it cannot find the root cause, and a
|
||||
`Message` in Floci's own words, such as "The Spark driver exited with code 1.".
|
||||
* **ActionOnFailure**: a failed step's action is taken as the API reference and the Management Guide's
|
||||
termination protection table give it. `CONTINUE` runs the next step. `TERMINATE_CLUSTER` (or
|
||||
`TERMINATE_JOB_FLOW`) ends the cluster, unless it waits after its steps
|
||||
(`KeepJobFlowAliveWhenNoSteps`) and is termination protected, when it goes on. `CANCEL_AND_WAIT`
|
||||
cancels the `PENDING` steps and leaves the cluster `WAITING`, or ends it when it is set to end after
|
||||
its steps. A cluster a step failure ends cancels its other steps and goes `TERMINATING`, then
|
||||
`TERMINATED_WITH_ERRORS`, with the reason `STEP_FAILURE` and the message "Shut down as step failed".
|
||||
While `StepConcurrencyLevel` is above 1 no action is taken, and with level 1 and other steps still
|
||||
running `CANCEL_AND_WAIT` is not either, as the guide says.
|
||||
* **Cancelling**: `CancelSteps` on a `RUNNING` step, and `TerminateJobFlows`, stop its driver at once; a
|
||||
cancelled step takes no `ActionOnFailure`. A step Floci was running when it stopped is `FAILED` once
|
||||
Floci is back, and its `ActionOnFailure` is taken then. Floci's shutdown and a state reset stop every
|
||||
driver, and start no other step; a driver a hard stop left running is removed when the EMR service
|
||||
starts, before any step can start, unless `reconcile-containers-on-startup` is off.
|
||||
* **What `spark-submit` gets**: the step's arguments, after the `spark-defaults` properties of the
|
||||
cluster's `Configurations`. `s3://` and `s3a://` paths reach Floci's S3 through S3A, on releases
|
||||
before 7.10.0 too, where `s3://` would otherwise be EMRFS, so the application and its files can be read
|
||||
from there; the Glue Data Catalog client is pointed at Floci's Glue. A step's `Properties` are not
|
||||
applied.
|
||||
* **Credentials**: the container gets a session for the step's `ExecutionRoleArn`, or else for the role
|
||||
of the cluster's `JobFlowRole` instance profile, when IAM knows it and the profile holds one role,
|
||||
and otherwise the account's placeholder credentials, with `AWS_ENDPOINT_URL` pointing at Floci.
|
||||
* **Output**: the driver's output goes to Floci's log, prefixed `emr:<stepId>`. Nothing is written
|
||||
under `LogUri`.
|
||||
* **Image**: `image-template` names another image, such as a mirror or a dated tag of the release's
|
||||
image: `registry.internal/emr-serverless/spark/%s:20250425`. A release with no EMR Serverless image
|
||||
fails its steps with "The step could not start: Could not pull image".
|
||||
|
||||
## EventBridge events
|
||||
|
||||
Every state a cluster or a step enters is sent to the default EventBridge bus of its Region, in the
|
||||
@@ -122,6 +169,7 @@ Each change sends its events:
|
||||
| `RunJobFlow` | the cluster `STARTING`, then each step `PENDING` |
|
||||
| `AddJobFlowSteps` | each step `PENDING` |
|
||||
| The cluster is ready, or a step completes | the step `COMPLETED`; each step it makes room for `RUNNING`; once none is left, the cluster `WAITING`, or `TERMINATED` with `ALL_STEPS_COMPLETED` when it ends after its steps |
|
||||
| A step fails (`docker` runner mode) | the step `FAILED`; then as its `ActionOnFailure` goes: as a completed step, or `CANCELLED` for each step it cancels and the cluster `WAITING`, or `CANCELLED` for each step not yet completed and the cluster `TERMINATED_WITH_ERRORS` with `STEP_FAILURE` |
|
||||
| `TerminateJobFlows` | `CANCELLED` for each step not yet completed; the cluster `TERMINATED` with `USER_REQUEST` once it has been `TERMINATING` for the delay, also when a protected cluster fails the call |
|
||||
| `CancelSteps` | `CANCELLED` for each step it cancels, and `RUNNING` for the step a cancelled `RUNNING` one makes room for |
|
||||
|
||||
@@ -129,10 +177,10 @@ A change that falls due between calls, such as a step completing after `step-dur
|
||||
made at that time and its events sent then, whether or not anything reads the cluster.
|
||||
|
||||
A `STARTING` or `WAITING` cluster's `stateChangeReason` is `{"code":""}`, as in the guide's example,
|
||||
and a `TERMINATED` one's carries the reason's code and message, such as
|
||||
and a terminated one's carries the reason's code and message, such as
|
||||
`{"code":"USER_REQUEST","message":"Terminated by user request"}`. `TERMINATED` is `INFO` for
|
||||
`USER_REQUEST` and `ALL_STEPS_COMPLETED` and `CRITICAL` for any other reason; a cancelled step is
|
||||
`WARN`. The tables have no row for a cluster's `BOOTSTRAPPING`, `RUNNING` or `TERMINATING`, which
|
||||
`USER_REQUEST` and `ALL_STEPS_COMPLETED` and `CRITICAL` for any other reason, and
|
||||
`TERMINATED_WITH_ERRORS` is `CRITICAL`; a cancelled step is `WARN` and a failed one `ERROR`. The tables have no row for a cluster's `BOOTSTRAPPING`, `RUNNING` or `TERMINATING`, which
|
||||
send nothing, so a `WAITING` cluster that runs added steps sends `WAITING` again when they are done.
|
||||
The guide gives two `WAITING` messages without saying when each applies: a cluster that ran steps
|
||||
reports it "finished running all pending steps", one that did not that it "was created ... and is
|
||||
@@ -151,6 +199,10 @@ its `STARTING` event, has its events sent after the rest of that call's.
|
||||
| `FLOCI_SERVICES_EMR_CLUSTER_STARTUP_DELAY_SECONDS` | `0` | Seconds a new cluster takes to be ready to run steps, the first half `STARTING` and the second `BOOTSTRAPPING`; `0` makes it ready as soon as it is created |
|
||||
| `FLOCI_SERVICES_EMR_STEP_DURATION_SECONDS` | `0` | Seconds a step stays `RUNNING` before it completes; `0` completes it as soon as it starts |
|
||||
| `FLOCI_SERVICES_EMR_CLUSTER_TERMINATION_DELAY_SECONDS` | `0` | Seconds a cluster stays `TERMINATING` before it is `TERMINATED`; `0` ends it at once |
|
||||
| `FLOCI_SERVICES_EMR_RUNNER_MODE` | `immediate` | `immediate` completes steps by time without running anything; `docker` runs each Spark step in a container (see [Running Spark steps](#running-spark-steps)) |
|
||||
| `FLOCI_SERVICES_EMR_DOCKER_NETWORK` | the global default | Docker network for step containers |
|
||||
| `FLOCI_SERVICES_EMR_IMAGE_TEMPLATE` | `public.ecr.aws/emr-serverless/spark/%s:latest`, or `spark4/` in place of `spark/` for an `emr-spark-*` release | Image for a `docker` step, `%s` standing for the cluster's release label |
|
||||
| `FLOCI_SERVICES_EMR_RECONCILE_CONTAINERS_ON_STARTUP` | `true` | Remove the step drivers a previous run of this Floci left on the Docker daemon when the EMR service starts; turn it off when two Floci instances share a daemon with the same port and no resource namespace |
|
||||
|
||||
## Release catalogue
|
||||
|
||||
|
||||
@@ -1979,6 +1979,33 @@ public interface EmulatorConfig {
|
||||
/** How long a cluster stays TERMINATING before it is TERMINATED; 0 ends it at once. */
|
||||
@WithDefault("0")
|
||||
int clusterTerminationDelaySeconds();
|
||||
|
||||
/**
|
||||
* {@code immediate} completes each step by time without running anything; {@code docker} runs each
|
||||
* Spark step's {@code spark-submit} in a container of the release's EMR Serverless image.
|
||||
*/
|
||||
@WithDefault("immediate")
|
||||
String runnerMode();
|
||||
|
||||
Optional<String> dockerNetwork();
|
||||
|
||||
/**
|
||||
* The image a {@code docker} step uses, with {@code %s} standing for the cluster's release label,
|
||||
* for example "registry.internal/emr-serverless/spark/%s:20250425". If omitted, Floci uses the
|
||||
* release's public EMR Serverless image on Amazon ECR Public.
|
||||
*/
|
||||
Optional<String> imageTemplate();
|
||||
|
||||
/**
|
||||
* When true, Floci removes, in the {@code docker} runner mode, every EMR step driver a previous run
|
||||
* of <em>this same</em> Floci left on the daemon (matched by the {@code io.floci.owner} label) when
|
||||
* the EMR service starts. Turn it off when two Floci instances share a daemon with the same port
|
||||
* and no resource namespace, so one does not remove the other's drivers.
|
||||
*
|
||||
* Env var: FLOCI_SERVICES_EMR_RECONCILE_CONTAINERS_ON_STARTUP
|
||||
*/
|
||||
@WithDefault("true")
|
||||
boolean reconcileContainersOnStartup();
|
||||
}
|
||||
|
||||
interface WafV2ServiceConfig {
|
||||
|
||||
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.services.emr.model.EmrStep;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
@@ -16,11 +17,12 @@ import java.util.regex.Pattern;
|
||||
* A cluster's and its steps' lifecycle, as the Management Guide gives it in "Understanding the cluster
|
||||
* lifecycle" and "Running steps to process data". A cluster is STARTING, then BOOTSTRAPPING, then
|
||||
* RUNNING while it runs its steps, in the order they were added and at most its StepConcurrencyLevel
|
||||
* at a time, then WAITING, or TERMINATING and TERMINATED when it ends after them. Nothing runs: each
|
||||
* change falls due at a time worked out from three durations and the times already recorded, and
|
||||
* {@link #advance} makes every change due by a given time, in the order they fall due, queuing the
|
||||
* event of each state the guide's event tables report. With the durations at 0, every change falls
|
||||
* due at the time of the call that leads to it.
|
||||
* at a time, then WAITING, or TERMINATING and TERMINATED when it ends after them. Each change falls due
|
||||
* at a time worked out from three durations and the times already recorded, and {@link #advance} makes
|
||||
* every change due by a given time, in the order they fall due, queuing the event of each state the
|
||||
* guide's event tables report. With the durations at 0, every change falls due at the time of the call
|
||||
* that leads to it. Without a {@link StepExecution} nothing runs and a step completes by time; with one,
|
||||
* a step runs for real, and ends, COMPLETED or FAILED, when {@link #stepEnded} says so.
|
||||
*/
|
||||
final class EmrClusterLifecycle {
|
||||
|
||||
@@ -33,19 +35,44 @@ final class EmrClusterLifecycle {
|
||||
static final String PENDING = "PENDING";
|
||||
static final String COMPLETED = "COMPLETED";
|
||||
static final String CANCELLED = "CANCELLED";
|
||||
static final String FAILED = "FAILED";
|
||||
static final String TERMINATED_WITH_ERRORS = "TERMINATED_WITH_ERRORS";
|
||||
// FailureDetails.Reason: "In the case where the service cannot successfully determine the root cause of
|
||||
// the failure, it returns "Unknown Error" as a reason." Floci never determines it.
|
||||
private static final String UNKNOWN_ERROR = "Unknown Error";
|
||||
private static final String STEP_FAILURE = "STEP_FAILURE";
|
||||
// The reason a cluster a failed step ends gives: the console's for a Snowplow cluster on its forum, and
|
||||
// mrjob's mock EMR.
|
||||
private static final String SHUT_DOWN_AS_STEP_FAILED = "Shut down as step failed";
|
||||
private static final Pattern RELEASE_LABEL = Pattern.compile("emr-(\\d{1,6})\\.(\\d{1,6})(?:\\..*)?");
|
||||
|
||||
private final Duration startup;
|
||||
private final Duration stepRun;
|
||||
private final Duration termination;
|
||||
private final EmrEventPublisher events;
|
||||
// Null when steps complete by time.
|
||||
private final StepExecution execution;
|
||||
|
||||
/**
|
||||
* Runs the steps a cluster starts, in the {@code docker} runner mode. Each call only sets work going
|
||||
* and returns: a step's end comes back later through {@link #stepEnded}, never from inside the call.
|
||||
*/
|
||||
interface StepExecution {
|
||||
|
||||
/** {@code step} of {@code cluster} has just gone RUNNING. */
|
||||
void start(EmrCluster cluster, EmrStep step, String region);
|
||||
|
||||
/** {@code step}, which was RUNNING, has just been cancelled. */
|
||||
void stop(EmrStep step);
|
||||
}
|
||||
|
||||
EmrClusterLifecycle(int startupDelaySeconds, int stepDurationSeconds, int terminationDelaySeconds,
|
||||
EmrEventPublisher events) {
|
||||
EmrEventPublisher events, StepExecution execution) {
|
||||
this.startup = seconds("cluster-startup-delay-seconds", startupDelaySeconds);
|
||||
this.stepRun = seconds("step-duration-seconds", stepDurationSeconds);
|
||||
this.termination = seconds("cluster-termination-delay-seconds", terminationDelaySeconds);
|
||||
this.events = events;
|
||||
this.execution = execution;
|
||||
}
|
||||
|
||||
private static Duration seconds(String setting, int value) {
|
||||
@@ -144,7 +171,7 @@ final class EmrClusterLifecycle {
|
||||
case STARTING -> cluster.getCreationDateTime().plus(startup.dividedBy(2));
|
||||
case BOOTSTRAPPING -> cluster.getCreationDateTime().plus(startup);
|
||||
case RUNNING -> cluster.getSteps().stream()
|
||||
.filter(step -> RUNNING.equals(step.getState()))
|
||||
.filter(step -> RUNNING.equals(step.getState()) && timed(step))
|
||||
.map(step -> step.getStartDateTime().plus(stepRun))
|
||||
.min(Comparator.naturalOrder())
|
||||
.orElse(null);
|
||||
@@ -163,7 +190,8 @@ final class EmrClusterLifecycle {
|
||||
}
|
||||
case RUNNING -> {
|
||||
for (EmrStep step : cluster.getSteps()) {
|
||||
if (RUNNING.equals(step.getState()) && !step.getStartDateTime().plus(stepRun).isAfter(at)) {
|
||||
if (RUNNING.equals(step.getState()) && timed(step)
|
||||
&& !step.getStartDateTime().plus(stepRun).isAfter(at)) {
|
||||
step.setState(COMPLETED);
|
||||
step.setEndDateTime(at);
|
||||
events.queue(events.stepStatusChange(cluster, step, COMPLETED), region);
|
||||
@@ -172,10 +200,14 @@ final class EmrClusterLifecycle {
|
||||
runSteps(cluster, at, region);
|
||||
}
|
||||
case TERMINATING -> {
|
||||
cluster.setState(TERMINATED);
|
||||
// "If a cluster terminates because of a failure, ... the cluster state is set to
|
||||
// TERMINATED_WITH_ERRORS."
|
||||
String ended = STEP_FAILURE.equals(cluster.getStateChangeReasonCode())
|
||||
? TERMINATED_WITH_ERRORS : TERMINATED;
|
||||
cluster.setState(ended);
|
||||
cluster.setEndDateTime(at);
|
||||
releaseInstanceCapacity(cluster);
|
||||
events.queue(events.clusterStateChange(cluster, TERMINATED, at), region);
|
||||
events.queue(events.clusterStateChange(cluster, ended, at), region);
|
||||
}
|
||||
default -> throw new IllegalStateException("Nothing falls due for a " + cluster.getState() + " cluster");
|
||||
}
|
||||
@@ -190,6 +222,7 @@ final class EmrClusterLifecycle {
|
||||
long running = cluster.getSteps().stream().filter(step -> RUNNING.equals(step.getState())).count();
|
||||
// The model allows 1 to 256; Floci stores any level it is given, and a lower one would never start a step.
|
||||
int level = Math.max(1, cluster.getStepConcurrencyLevel());
|
||||
List<EmrStep> started = new ArrayList<>();
|
||||
for (EmrStep step : cluster.getSteps()) {
|
||||
if (running >= level) {
|
||||
break;
|
||||
@@ -197,7 +230,9 @@ final class EmrClusterLifecycle {
|
||||
if (PENDING.equals(step.getState())) {
|
||||
step.setState(RUNNING);
|
||||
step.setStartDateTime(at);
|
||||
step.setRunInContainer(execution != null);
|
||||
events.queue(events.stepStatusChange(cluster, step, RUNNING), region);
|
||||
started.add(step);
|
||||
running++;
|
||||
}
|
||||
}
|
||||
@@ -209,6 +244,63 @@ final class EmrClusterLifecycle {
|
||||
} else {
|
||||
finish(cluster, at, region);
|
||||
}
|
||||
if (execution != null) {
|
||||
started.forEach(step -> execution.start(cluster, step, region));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A step run for real has ended: COMPLETED when {@code failure} is null, otherwise FAILED, with
|
||||
* {@code failure} as its FailureDetails message, and its ActionOnFailure taken. Either way the
|
||||
* cluster goes on as it would once a step is done.
|
||||
*/
|
||||
void stepEnded(EmrCluster cluster, EmrStep step, String failure, Instant at, String region) {
|
||||
step.setEndDateTime(at);
|
||||
if (failure == null) {
|
||||
step.setState(COMPLETED);
|
||||
events.queue(events.stepStatusChange(cluster, step, COMPLETED), region);
|
||||
runSteps(cluster, at, region);
|
||||
return;
|
||||
}
|
||||
step.setState(FAILED);
|
||||
step.setFailureReason(UNKNOWN_ERROR);
|
||||
step.setFailureMessage(failure);
|
||||
events.queue(events.stepStatusChange(cluster, step, FAILED), region);
|
||||
actOnFailure(cluster, step, at, region);
|
||||
}
|
||||
|
||||
/**
|
||||
* A failed step's ActionOnFailure, as the API reference's Step and the Management Guide give it.
|
||||
* TERMINATE_CLUSTER (TERMINATE_JOB_FLOW before it) ends the cluster, unless it is set to wait after
|
||||
* its steps and protected from termination: then it "continues". CANCEL_AND_WAIT "Cancels any pending
|
||||
* steps and returns the cluster to the WAITING state", and on a cluster set to end after its steps
|
||||
* "the cluster terminates without executing subsequent steps". CONTINUE "Continues to the next step in
|
||||
* the queue". "If the step concurrency level of a cluster is greater than one, step ActionOnFailure
|
||||
* feature will not activate", and with level 1 but other steps still running (the level was lowered
|
||||
* while they ran) "TERMINATE_CLUSTER ActionOnFailure may activate, but CANCEL_AND_WAIT ActionOnFailure
|
||||
* will not".
|
||||
*/
|
||||
private void actOnFailure(EmrCluster cluster, EmrStep step, Instant at, String region) {
|
||||
String action = step.getActionOnFailure();
|
||||
boolean activates = cluster.getStepConcurrencyLevel() <= 1;
|
||||
boolean terminates = "TERMINATE_CLUSTER".equals(action) || "TERMINATE_JOB_FLOW".equals(action);
|
||||
if (activates && terminates && (cluster.isAutoTerminate() || !cluster.isTerminationProtected())) {
|
||||
terminate(cluster, STEP_FAILURE, SHUT_DOWN_AS_STEP_FAILED, at, region);
|
||||
return;
|
||||
}
|
||||
boolean othersRunning = cluster.getSteps().stream().anyMatch(other -> RUNNING.equals(other.getState()));
|
||||
if (activates && "CANCEL_AND_WAIT".equals(action) && !othersRunning) {
|
||||
if (cluster.isAutoTerminate()) {
|
||||
terminate(cluster, STEP_FAILURE, SHUT_DOWN_AS_STEP_FAILED, at, region);
|
||||
return;
|
||||
}
|
||||
for (EmrStep pending : cluster.getSteps()) {
|
||||
if (PENDING.equals(pending.getState())) {
|
||||
cancelStep(cluster, pending, at, region);
|
||||
}
|
||||
}
|
||||
}
|
||||
runSteps(cluster, at, region);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -227,9 +319,26 @@ final class EmrClusterLifecycle {
|
||||
}
|
||||
|
||||
private void cancelStep(EmrCluster cluster, EmrStep step, Instant at, String region) {
|
||||
boolean running = RUNNING.equals(step.getState());
|
||||
step.setState(CANCELLED);
|
||||
step.setEndDateTime(at);
|
||||
events.queue(events.stepStatusChange(cluster, step, CANCELLED), region);
|
||||
if (running && !timed(step)) {
|
||||
execution.stop(step);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a RUNNING step completes by time: every step without a {@link StepExecution}, including one
|
||||
* a {@code docker} runner mode started before a restart into the {@code immediate} one.
|
||||
*/
|
||||
private boolean timed(EmrStep step) {
|
||||
return execution == null || !step.isRunInContainer();
|
||||
}
|
||||
|
||||
/** TERMINATED, or TERMINATED_WITH_ERRORS: the cluster has ended. */
|
||||
static boolean isTerminated(String state) {
|
||||
return TERMINATED.equals(state) || TERMINATED_WITH_ERRORS.equals(state);
|
||||
}
|
||||
|
||||
private static void releaseInstanceCapacity(EmrCluster cluster) {
|
||||
|
||||
@@ -59,12 +59,15 @@ public class EmrEventPublisher {
|
||||
this.regionResolver = regionResolver;
|
||||
}
|
||||
|
||||
/** {@code cluster} entering {@code state} at {@code at}: STARTING, WAITING or TERMINATED. */
|
||||
/**
|
||||
* {@code cluster} entering {@code state} at {@code at}: STARTING, WAITING, TERMINATED or
|
||||
* TERMINATED_WITH_ERRORS.
|
||||
*/
|
||||
Event clusterStateChange(EmrCluster cluster, String state, Instant at) {
|
||||
boolean terminated = "TERMINATED".equals(state);
|
||||
boolean terminated = EmrClusterLifecycle.isTerminated(state);
|
||||
String code = cluster.getStateChangeReasonCode();
|
||||
// The examples' reason is a JSON string: {"code":""} for a WAITING cluster, and the reason's code
|
||||
// and message for a TERMINATED one.
|
||||
// and message for a terminated one.
|
||||
ObjectNode reason = objectMapper.createObjectNode().put("code", terminated && code != null ? code : "");
|
||||
if (terminated && cluster.getStateChangeMessage() != null) {
|
||||
reason.put("message", cluster.getStateChangeMessage());
|
||||
@@ -80,10 +83,17 @@ public class EmrEventPublisher {
|
||||
return new Event(CLUSTER_STATE_CHANGE, detail.toString());
|
||||
}
|
||||
|
||||
/** {@code step} of {@code cluster} entering {@code state}: PENDING, RUNNING, COMPLETED or CANCELLED. */
|
||||
/**
|
||||
* {@code step} of {@code cluster} entering {@code state}: PENDING, RUNNING, COMPLETED, CANCELLED or
|
||||
* FAILED.
|
||||
*/
|
||||
Event stepStatusChange(EmrCluster cluster, EmrStep step, String state) {
|
||||
ObjectNode detail = objectMapper.createObjectNode();
|
||||
detail.put("severity", "CANCELLED".equals(state) ? "WARN" : "INFO");
|
||||
detail.put("severity", switch (state) {
|
||||
case "CANCELLED" -> "WARN";
|
||||
case "FAILED" -> "ERROR";
|
||||
default -> "INFO";
|
||||
});
|
||||
detail.put("actionOnFailure", step.getActionOnFailure());
|
||||
detail.put("stepId", step.getId());
|
||||
detail.put("name", step.getName());
|
||||
@@ -136,6 +146,8 @@ public class EmrEventPublisher {
|
||||
: "Amazon EMR cluster " + named + " finished running all pending steps at " + time(at) + ".";
|
||||
case "TERMINATED" -> "Amazon EMR Cluster " + named + " has terminated at " + time(at)
|
||||
+ " with a reason of " + cluster.getStateChangeReasonCode() + ".";
|
||||
case "TERMINATED_WITH_ERRORS" -> "Amazon EMR Cluster " + named + " has terminated with errors at "
|
||||
+ time(at) + " with a reason of " + cluster.getStateChangeReasonCode() + ".";
|
||||
default -> throw new IllegalArgumentException("No cluster event for state " + state);
|
||||
};
|
||||
}
|
||||
@@ -156,6 +168,8 @@ public class EmrEventPublisher {
|
||||
case "CANCELLED" -> "Cancellation request has succeeded for cluster step " + stepNamed
|
||||
+ " in Amazon EMR cluster " + clusterNamed + " at " + time(step.getEndDateTime())
|
||||
+ ", and the step is now cancelled.";
|
||||
case "FAILED" -> "Step " + stepNamed + " in Amazon EMR cluster " + clusterNamed + " failed at "
|
||||
+ time(step.getEndDateTime()) + ".";
|
||||
default -> throw new IllegalArgumentException("No step event for state " + state);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -317,7 +317,7 @@ public class EmrHandler {
|
||||
EmrCluster cluster = service.getClusterForInstances(text(request, "ClusterId"));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode arr = response.putArray("Instances");
|
||||
boolean terminated = "TERMINATED".equals(cluster.getState());
|
||||
boolean terminated = EmrClusterLifecycle.isTerminated(cluster.getState());
|
||||
List<String> states = stringList(request.path("InstanceStates"));
|
||||
if ((!states.isEmpty() && !states.contains(terminated ? "TERMINATED" : "RUNNING"))
|
||||
|| (terminated && !withinTerminatedInstanceRetention(cluster.getEndDateTime(), Instant.now()))) {
|
||||
@@ -666,6 +666,12 @@ public class EmrHandler {
|
||||
if (step.getStateChangeReason() != null) {
|
||||
status.putObject("StateChangeReason").put("Message", step.getStateChangeReason());
|
||||
}
|
||||
if (step.getFailureReason() != null) {
|
||||
ObjectNode failure = status.putObject("FailureDetails").put("Reason", step.getFailureReason());
|
||||
if (step.getFailureMessage() != null) {
|
||||
failure.put("Message", step.getFailureMessage());
|
||||
}
|
||||
}
|
||||
ObjectNode timeline = status.putObject("Timeline");
|
||||
putEpoch(timeline, "CreationDateTime", step.getCreationDateTime());
|
||||
putEpoch(timeline, "StartDateTime", step.getStartDateTime());
|
||||
|
||||
@@ -11,6 +11,7 @@ import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
import io.github.hectorvent.floci.core.common.Pagination;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
@@ -21,6 +22,10 @@ import io.github.hectorvent.floci.services.emr.model.EmrInstanceFleet;
|
||||
import io.github.hectorvent.floci.services.emr.model.EmrInstanceGroup;
|
||||
import io.github.hectorvent.floci.services.emr.model.EmrStep;
|
||||
import io.github.hectorvent.floci.services.emr.model.SecurityConfiguration;
|
||||
import io.github.hectorvent.floci.services.emrserverless.EmrServerlessSparkRunner;
|
||||
import io.github.hectorvent.floci.services.emrserverless.SparkJobRunner;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamRole;
|
||||
import io.quarkus.runtime.StartupEvent;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
@@ -35,6 +40,7 @@ import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -42,6 +48,7 @@ import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
@@ -50,16 +57,21 @@ import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* EMR management-plane business logic. Nothing runs: clusters and steps go through the states of
|
||||
* EMR management-plane business logic. Clusters and steps go through the states of
|
||||
* {@link EmrClusterLifecycle}, timed by {@code cluster-startup-delay-seconds},
|
||||
* {@code step-duration-seconds} and {@code cluster-termination-delay-seconds}, all 0 by default, which
|
||||
* makes a cluster ready, and a step complete, before the call that started it returns. A call brings
|
||||
* each cluster it reads up to the time it is made, and the service wakes at each cluster's next
|
||||
* change, so the change's event goes out without anyone asking. Events are published once the call
|
||||
* that made the change no longer holds the service.
|
||||
*
|
||||
* <p>In the default {@code immediate} runner mode nothing runs. In the {@code docker} one each step
|
||||
* runs, in a container of its own, from when it goes RUNNING until its Spark driver exits, on a thread
|
||||
* of its own that ends the step under the service's lock: COMPLETED on exit code 0, FAILED otherwise,
|
||||
* with its ActionOnFailure taken.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class EmrService {
|
||||
public class EmrService implements Resettable {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(EmrService.class);
|
||||
private static final String UPPER_ALNUM = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||
@@ -69,6 +81,9 @@ public class EmrService {
|
||||
private static final String JOB_FLOW_SHUT_DOWN =
|
||||
"A job flow that is shutting down, terminated, or finished may not be modified.";
|
||||
private static final ObjectMapper SNAPSHOT_MAPPER = new ObjectMapper().registerModule(new JavaTimeModule());
|
||||
private static final String RUNNER_DOCKER = "docker";
|
||||
// The service a step's driver belongs to, which names it and labels it.
|
||||
private static final String SERVICE = "emr";
|
||||
|
||||
private final AccountAwareStorageBackend<EmrCluster> clusterStore;
|
||||
private final StorageBackend<String, SecurityConfiguration> secConfigStore;
|
||||
@@ -81,6 +96,18 @@ public class EmrService {
|
||||
private final Wakeups wakeups;
|
||||
// Each cluster's next wakeup, by account and id, so a call that reads a cluster does not add another.
|
||||
private final Map<String, Instant> wakeupsDue = new ConcurrentHashMap<>();
|
||||
// The docker runner mode's; null in the immediate one.
|
||||
private final SparkJobRunner sparkRunner;
|
||||
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
|
||||
// not set.
|
||||
private final String imageTemplate;
|
||||
private final String dockerNetwork;
|
||||
// The steps a thread is running, by account and id; a RUNNING container step not here was left by a restart.
|
||||
private final Set<String> executing = new HashSet<>();
|
||||
// Raised by each reset, so a step's thread from before it writes nothing back after the wipe.
|
||||
private long generation;
|
||||
|
||||
private static final Set<String> COMPUTE_LIMITS_UNIT_TYPES = Set.of("InstanceFleetUnits", "Instances", "VCPU");
|
||||
private static final Set<String> SCALING_STRATEGIES = Set.of("DEFAULT", "ADVANCED");
|
||||
@@ -142,13 +169,22 @@ public class EmrService {
|
||||
|
||||
@Inject
|
||||
public EmrService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver,
|
||||
EmrEventPublisher eventPublisher) {
|
||||
EmrEventPublisher eventPublisher, EmrServerlessSparkRunner sparkRunner, IamService iamService) {
|
||||
this(storageFactory, config, regionResolver, eventPublisher, Clock.systemUTC(),
|
||||
Wakeups.timer(Clock.systemUTC()));
|
||||
Wakeups.timer(Clock.systemUTC()),
|
||||
RUNNER_DOCKER.equalsIgnoreCase(config.services().emr().runnerMode()) ? sparkRunner : 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, Runnable::run, null);
|
||||
}
|
||||
|
||||
EmrService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver,
|
||||
EmrEventPublisher eventPublisher, Clock clock, Wakeups wakeups, SparkJobRunner sparkRunner,
|
||||
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",
|
||||
@@ -158,15 +194,29 @@ public class EmrService {
|
||||
this.regionResolver = regionResolver;
|
||||
this.eventPublisher = eventPublisher;
|
||||
this.defaultReleaseLabel = config.services().emr().defaultReleaseLabel();
|
||||
this.sparkRunner = sparkRunner;
|
||||
this.stepExecutor = stepExecutor;
|
||||
this.iamService = iamService;
|
||||
this.imageTemplate = config.services().emr().imageTemplate().orElse(null);
|
||||
this.dockerNetwork = config.services().emr().dockerNetwork().orElse(null);
|
||||
this.lifecycle = new EmrClusterLifecycle(config.services().emr().clusterStartupDelaySeconds(),
|
||||
config.services().emr().stepDurationSeconds(),
|
||||
config.services().emr().clusterTerminationDelaySeconds(), eventPublisher);
|
||||
config.services().emr().clusterTerminationDelaySeconds(), eventPublisher,
|
||||
sparkRunner != null ? new ContainerSteps() : null);
|
||||
this.clock = clock;
|
||||
this.wakeups = wakeups;
|
||||
// After a restart, a stored cluster with a change still to come wakes the service as before.
|
||||
// Before any step of this process can start, the next step a restarted cluster's wakeup below starts
|
||||
// included: a driver an earlier process left belongs to a step read as FAILED, and the sweep removes
|
||||
// every driver of this deployment it finds.
|
||||
if (sparkRunner != null && config.services().emr().reconcileContainersOnStartup()) {
|
||||
sparkRunner.removeLeftoverDrivers(SERVICE);
|
||||
}
|
||||
// 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, which no thread runs any more, wakes it at once to fail that step.
|
||||
for (AccountAwareStorageBackend.AccountEntry<EmrCluster> entry
|
||||
: clusterStore.scanAllAccountEntries(k -> true)) {
|
||||
Instant due = lifecycle.nextChange(entry.value());
|
||||
Instant due = sparkRunner != null && hasContainerStepRunning(entry.value())
|
||||
? clock.instant() : lifecycle.nextChange(entry.value());
|
||||
if (due != null) {
|
||||
wakeAt(entry.accountId(), entry.value(), due);
|
||||
}
|
||||
@@ -182,6 +232,24 @@ public class EmrService {
|
||||
@PreDestroy
|
||||
void shutdown() {
|
||||
wakeups.close();
|
||||
if (stepExecutor instanceof ExecutorService executor) {
|
||||
executor.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A reset has begun: the steps' threads from before it write nothing more, so the storage wipe that
|
||||
* follows leaves none of their clusters behind. Its teardown has already stopped their drivers.
|
||||
*/
|
||||
@Override
|
||||
public synchronized void beforeReset() {
|
||||
generation++;
|
||||
executing.clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
// The clusters live in storage, which the reset has already wiped.
|
||||
}
|
||||
|
||||
// ──────────────────────────── Cluster lifecycle ────────────────────────────
|
||||
@@ -933,7 +1001,7 @@ public class EmrService {
|
||||
if (EmrClusterLifecycle.TERMINATING.equals(cluster.getState())) {
|
||||
throw shuttingDown.get();
|
||||
}
|
||||
if (EmrClusterLifecycle.TERMINATED.equals(cluster.getState())) {
|
||||
if (EmrClusterLifecycle.isTerminated(cluster.getState())) {
|
||||
throw invalid("Cluster " + cluster.getId() + " is terminated.");
|
||||
}
|
||||
}
|
||||
@@ -978,7 +1046,7 @@ public class EmrService {
|
||||
/** Shutting down or ended: "A job flow that is shutting down, terminated, or finished may not be modified." */
|
||||
private static boolean isShutDown(EmrCluster cluster) {
|
||||
return EmrClusterLifecycle.TERMINATING.equals(cluster.getState())
|
||||
|| EmrClusterLifecycle.TERMINATED.equals(cluster.getState());
|
||||
|| EmrClusterLifecycle.isTerminated(cluster.getState());
|
||||
}
|
||||
|
||||
/** The only states in which a cluster's instance groups and fleets may be modified. */
|
||||
@@ -1017,15 +1085,194 @@ public class EmrService {
|
||||
return SNAPSHOT_MAPPER.convertValue(cluster, EmrCluster.class);
|
||||
}
|
||||
|
||||
/** The cluster as it stands now: every change due by now made, stored if there was one. */
|
||||
/**
|
||||
* The cluster as it stands now: every change due by now made, stored if there was one. A step a
|
||||
* container ran that no thread runs any more, since Floci stopped while it ran, is FAILED.
|
||||
*/
|
||||
private EmrCluster settle(EmrCluster cluster) {
|
||||
if (lifecycle.advance(cluster, now(), regionOf(cluster))) {
|
||||
boolean interrupted = failInterruptedSteps(cluster);
|
||||
if (lifecycle.advance(cluster, now(), regionOf(cluster)) || interrupted) {
|
||||
clusterStore.put(cluster.getId(), cluster);
|
||||
}
|
||||
wakeForNextChange(cluster);
|
||||
return cluster;
|
||||
}
|
||||
|
||||
private boolean failInterruptedSteps(EmrCluster cluster) {
|
||||
if (sparkRunner == null) {
|
||||
return false;
|
||||
}
|
||||
boolean failed = false;
|
||||
for (EmrStep step : List.copyOf(cluster.getSteps())) {
|
||||
if (runsInContainer(step) && !executing.contains(stepKey(regionResolver.getAccountId(), step.getId()))) {
|
||||
lifecycle.stepEnded(cluster, step, EmrSparkSteps.INTERRUPTED, now(), regionOf(cluster));
|
||||
failed = true;
|
||||
}
|
||||
}
|
||||
return failed;
|
||||
}
|
||||
|
||||
private static boolean hasContainerStepRunning(EmrCluster cluster) {
|
||||
return cluster.getSteps().stream().anyMatch(EmrService::runsInContainer);
|
||||
}
|
||||
|
||||
private static boolean runsInContainer(EmrStep step) {
|
||||
return EmrClusterLifecycle.RUNNING.equals(step.getState()) && step.isRunInContainer();
|
||||
}
|
||||
|
||||
private static String stepKey(String accountId, String stepId) {
|
||||
return accountId + "/" + stepId;
|
||||
}
|
||||
|
||||
/**
|
||||
* The role a step's driver runs as: the step's runtime role, or else the role of the cluster's EC2
|
||||
* instance profile, its {@code JobFlowRole}, given by name or ARN; null when IAM knows neither, and the
|
||||
* driver then has the account's placeholder credentials. The guide's "Runtime roles for Amazon EMR
|
||||
* steps": without them, clusters "ran Amazon EMR jobs or queries with permissions based on the IAM
|
||||
* policy attached to the instance profile that you used to launch the cluster".
|
||||
*/
|
||||
private String executionRole(EmrCluster cluster, EmrStep step, String accountId) {
|
||||
if (step.getExecutionRoleArn() != null) {
|
||||
return step.getExecutionRoleArn();
|
||||
}
|
||||
String profile = cluster.getJobFlowRole();
|
||||
if (profile == null || iamService == null) {
|
||||
return null;
|
||||
}
|
||||
return iamService.findInstanceProfile(accountId, profile.substring(profile.lastIndexOf('/') + 1))
|
||||
.filter(found -> found.getRoleNames() != null && found.getRoleNames().size() == 1)
|
||||
.flatMap(found -> iamService.findRole(accountId, found.getRoleNames().getFirst()))
|
||||
.map(IamRole::getArn)
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ends a step its thread ran, COMPLETED when {@code failure} is null and FAILED otherwise, unless a
|
||||
* reset came since it started or the step is no longer RUNNING: cancelled, or on a cluster that ended.
|
||||
*/
|
||||
private void stepEnded(StepLaunch launch, String failure) {
|
||||
if (launch.launchedIn() != generation) {
|
||||
return;
|
||||
}
|
||||
// Read while the step still counts as running, so it is not taken for one a restart left.
|
||||
Optional<EmrCluster> found = findCluster(launch.clusterId());
|
||||
executing.remove(stepKey(launch.accountId(), launch.stepId()));
|
||||
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())) {
|
||||
return;
|
||||
}
|
||||
EmrCluster cluster = found.get();
|
||||
lifecycle.stepEnded(cluster, step, failure, now(), regionOf(cluster));
|
||||
store(cluster);
|
||||
LOG.infov("EMR step {0} of cluster {1} ended {2}", step.getId(), cluster.getId(), step.getState());
|
||||
}
|
||||
|
||||
/**
|
||||
* A step's driver was stopped. A cancel, or its cluster's end, has ended the step already. One still
|
||||
* RUNNING was stopped by Floci itself, by a reset's teardown or its shutdown, and is left as it is, still
|
||||
* counted as running: the reset wipes it, a restart fails it, and its ActionOnFailure, which could start
|
||||
* the next step after the teardown has passed, is not taken now.
|
||||
*/
|
||||
private void driverStopped(StepLaunch launch) {
|
||||
if (!stillRunning(launch)) {
|
||||
executing.remove(stepKey(launch.accountId(), launch.stepId()));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Why a step whose driver ended this way, by itself or before it could start, failed, or null when it
|
||||
* did not. No source gives AWS's wording for these; they are Floci's.
|
||||
*/
|
||||
private static String failureOf(SparkJobRunner.Outcome outcome) {
|
||||
if (outcome.exitCode() != null) {
|
||||
return outcome.exitCode() == 0 ? null : "The Spark driver exited with code " + outcome.exitCode() + ".";
|
||||
}
|
||||
return "The step could not start: " + outcome.failure();
|
||||
}
|
||||
|
||||
// Whether a step's driver may still start, or go on: one cancelled, on a cluster that ended, or a reset
|
||||
// removed, is past it.
|
||||
private synchronized boolean stillRunning(StepLaunch launch) {
|
||||
return launch.launchedIn() == generation && clusterStore.get(launch.clusterId()).stream()
|
||||
.flatMap(cluster -> cluster.getSteps().stream())
|
||||
.anyMatch(step -> launch.stepId().equals(step.getId())
|
||||
&& EmrClusterLifecycle.RUNNING.equals(step.getState()));
|
||||
}
|
||||
|
||||
/** 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) {}
|
||||
|
||||
/** Starts each step a cluster runs on a thread of its own, which ends the step once it is done. */
|
||||
private final class ContainerSteps implements EmrClusterLifecycle.StepExecution {
|
||||
|
||||
@Override
|
||||
public void start(EmrCluster cluster, EmrStep step, String region) {
|
||||
String accountId = regionResolver.getAccountId();
|
||||
List<String> application = EmrSparkSteps.application(step);
|
||||
SparkJobRunner.Job job = application == null ? null : new SparkJobRunner.Job(SERVICE, step.getId(),
|
||||
accountId, region, cluster.getReleaseLabel(), imageTemplate, dockerNetwork,
|
||||
executionRole(cluster, step, accountId),
|
||||
EmrSparkSteps.sparkDefaults(cluster.getConfigurations(), SNAPSHOT_MAPPER), application,
|
||||
Duration.ZERO);
|
||||
StepLaunch launch = new StepLaunch(accountId, region, cluster.getId(), step.getId(), generation);
|
||||
executing.add(stepKey(accountId, step.getId()));
|
||||
stepExecutor.execute(() -> runStep(job, launch));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop(EmrStep step) {
|
||||
sparkRunner.stop(step.getId());
|
||||
}
|
||||
}
|
||||
|
||||
// A step's thread: its driver runs to its end, or the step fails at once when Floci does not run its kind.
|
||||
private void runStep(SparkJobRunner.Job job, StepLaunch launch) {
|
||||
String failure;
|
||||
if (job == null) {
|
||||
failure = EmrSparkSteps.NOT_RUN;
|
||||
} else {
|
||||
SparkJobRunner.Outcome outcome;
|
||||
try {
|
||||
outcome = sparkRunner.run(job, new StepProgress(launch));
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "EMR step {0} could not run", launch.stepId());
|
||||
outcome = SparkJobRunner.Outcome.couldNotStart(e.getMessage());
|
||||
}
|
||||
if (outcome.stopped()) {
|
||||
RequestScopes.runAs(launch.accountId(), launch.region(), () -> run(() -> driverStopped(launch)));
|
||||
return;
|
||||
}
|
||||
failure = failureOf(outcome);
|
||||
}
|
||||
RequestScopes.runAs(launch.accountId(), launch.region(), () -> run(() -> stepEnded(launch, failure)));
|
||||
}
|
||||
|
||||
/** What a step's thread asks the service while its driver goes: a step has no timeout to report. */
|
||||
private final class StepProgress implements SparkJobRunner.Progress {
|
||||
|
||||
private final StepLaunch launch;
|
||||
|
||||
StepProgress(StepLaunch launch) {
|
||||
this.launch = launch;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void started() {
|
||||
// The step has been RUNNING since it started; the driver's start changes nothing a caller sees.
|
||||
}
|
||||
|
||||
@Override
|
||||
public void timedOut() {
|
||||
// A step runs until its driver ends.
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean cancelled() {
|
||||
return !RequestScopes.callAs(launch.accountId(), launch.region(), () -> stillRunning(launch));
|
||||
}
|
||||
}
|
||||
|
||||
/** 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));
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
package io.github.hectorvent.floci.services.emr;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.services.emr.model.EmrStep;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* What a step runs in the {@code docker} runner mode, which runs Spark steps only, each through
|
||||
* {@code spark-submit} in local mode: a {@code command-runner.jar} step running {@code spark-submit}, as
|
||||
* the Management Guide's Spark steps are written, and a custom JAR step, whose main class
|
||||
* {@code spark-submit} runs with the JAR on its class path.
|
||||
*/
|
||||
final class EmrSparkSteps {
|
||||
|
||||
// No source gives AWS's wording for these; they are Floci's.
|
||||
static final String NOT_RUN = "Floci runs Spark steps only: spark-submit through command-runner.jar, or a"
|
||||
+ " custom JAR.";
|
||||
static final String INTERRUPTED = "Floci stopped while the step was running.";
|
||||
|
||||
private static final String COMMAND_RUNNER = "command-runner.jar";
|
||||
private static final String SCRIPT_RUNNER = "script-runner.jar";
|
||||
private static final String SPARK_SUBMIT = "spark-submit";
|
||||
// Local mode is Floci's, so a step's own master and deploy mode are dropped.
|
||||
private static final Set<String> DROPPED_OPTIONS = Set.of("--master", "--deploy-mode");
|
||||
// spark-submit's options that take no value (SparkSubmitOptionParser's switches); every other takes one.
|
||||
private static final Set<String> SWITCHES = Set.of("--help", "-h", "--supervise", "--usage-error", "--verbose",
|
||||
"-v", "--version");
|
||||
private static final String SPARK_DEFAULTS = "spark-defaults";
|
||||
|
||||
private EmrSparkSteps() {
|
||||
}
|
||||
|
||||
/**
|
||||
* What follows Floci's own settings on {@code spark-submit}'s command line for {@code step}, or null for
|
||||
* a step Floci does not run. For {@code command-runner.jar spark-submit ...}, the arguments after
|
||||
* {@code spark-submit}, without its {@code --master} and {@code --deploy-mode}: options come before the
|
||||
* application, so one after it is the application's own and kept. For a custom JAR, its main class, if
|
||||
* the step names one (otherwise {@code spark-submit} reads the JAR's manifest), the JAR and the step's
|
||||
* arguments.
|
||||
*/
|
||||
static List<String> application(EmrStep step) {
|
||||
String jar = step.getJar();
|
||||
if (jar == null || jar.isBlank() || named(jar, SCRIPT_RUNNER)) {
|
||||
return null;
|
||||
}
|
||||
List<String> args = step.getArgs() != null ? step.getArgs() : List.of();
|
||||
if (named(jar, COMMAND_RUNNER)) {
|
||||
return !args.isEmpty() && named(args.getFirst(), SPARK_SUBMIT)
|
||||
? withoutMasterOrDeployMode(args.subList(1, args.size())) : null;
|
||||
}
|
||||
List<String> application = new ArrayList<>();
|
||||
if (step.getMainClass() != null && !step.getMainClass().isBlank()) {
|
||||
application.add("--class");
|
||||
application.add(step.getMainClass());
|
||||
}
|
||||
application.add(jar);
|
||||
application.addAll(args);
|
||||
return application;
|
||||
}
|
||||
|
||||
/**
|
||||
* The {@code spark-defaults} properties of a cluster's {@code Configurations}, the JSON array
|
||||
* {@code RunJobFlow} was given, or none.
|
||||
*/
|
||||
static Map<String, String> sparkDefaults(String configurations, ObjectMapper objectMapper) {
|
||||
Map<String, String> properties = new LinkedHashMap<>();
|
||||
if (configurations == null) {
|
||||
return properties;
|
||||
}
|
||||
try {
|
||||
for (JsonNode configuration : objectMapper.readTree(configurations)) {
|
||||
if (SPARK_DEFAULTS.equals(configuration.path("Classification").asText())) {
|
||||
configuration.path("Properties").properties()
|
||||
.forEach(property -> properties.put(property.getKey(), property.getValue().asText()));
|
||||
}
|
||||
}
|
||||
} catch (JsonProcessingException ignored) {
|
||||
// RunJobFlow stored the array as it came; one that does not parse holds no properties to apply.
|
||||
return properties;
|
||||
}
|
||||
return properties;
|
||||
}
|
||||
|
||||
private static List<String> withoutMasterOrDeployMode(List<String> arguments) {
|
||||
List<String> kept = new ArrayList<>();
|
||||
int i = 0;
|
||||
while (i < arguments.size() && arguments.get(i).startsWith("-")) {
|
||||
String option = arguments.get(i);
|
||||
int equals = option.indexOf('=');
|
||||
String name = option.startsWith("--") && equals > 0 ? option.substring(0, equals) : option;
|
||||
// A switch, or an option written --name=value, is one argument; any other option takes the next.
|
||||
int length = SWITCHES.contains(option) || !name.equals(option) ? 1 : 2;
|
||||
List<String> words = arguments.subList(i, Math.min(i + length, arguments.size()));
|
||||
if (!DROPPED_OPTIONS.contains(name)) {
|
||||
kept.addAll(words);
|
||||
}
|
||||
i += words.size();
|
||||
}
|
||||
kept.addAll(arguments.subList(i, arguments.size()));
|
||||
return kept;
|
||||
}
|
||||
|
||||
// command-runner.jar is named alone; a path such as /usr/bin/spark-submit names spark-submit too.
|
||||
private static boolean named(String path, String name) {
|
||||
return path.equals(name) || path.endsWith("/" + name);
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import java.util.Map;
|
||||
/**
|
||||
* An EMR cluster (job flow). State machine:
|
||||
* STARTING → BOOTSTRAPPING → RUNNING → WAITING (and back to RUNNING for added steps), then
|
||||
* → TERMINATING → TERMINATED.
|
||||
* → TERMINATING → TERMINATED, or TERMINATED_WITH_ERRORS when a failed step ended it.
|
||||
* Steps, instance groups and fleets are stored as nested lists. Complex sub-structures
|
||||
* (ec2 attributes, applications, configurations) are stored as raw JSON strings.
|
||||
*/
|
||||
|
||||
@@ -8,7 +8,10 @@ import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** An EMR job-flow step. State machine: PENDING → RUNNING → COMPLETED (or CANCELLED/FAILED). */
|
||||
/**
|
||||
* An EMR job-flow step. State machine: PENDING → RUNNING → COMPLETED (or CANCELLED/FAILED). A step the
|
||||
* {@code docker} runner mode started runs in a container, and a FAILED one carries its FailureDetails.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
public class EmrStep {
|
||||
|
||||
@@ -22,6 +25,9 @@ public class EmrStep {
|
||||
private String state;
|
||||
private String stateChangeReason;
|
||||
private String executionRoleArn;
|
||||
private boolean runInContainer;
|
||||
private String failureReason;
|
||||
private String failureMessage;
|
||||
private Instant creationDateTime;
|
||||
private Instant startDateTime;
|
||||
private Instant endDateTime;
|
||||
@@ -58,6 +64,15 @@ public class EmrStep {
|
||||
public String getExecutionRoleArn() { return executionRoleArn; }
|
||||
public void setExecutionRoleArn(String executionRoleArn) { this.executionRoleArn = executionRoleArn; }
|
||||
|
||||
public boolean isRunInContainer() { return runInContainer; }
|
||||
public void setRunInContainer(boolean runInContainer) { this.runInContainer = runInContainer; }
|
||||
|
||||
public String getFailureReason() { return failureReason; }
|
||||
public void setFailureReason(String failureReason) { this.failureReason = failureReason; }
|
||||
|
||||
public String getFailureMessage() { return failureMessage; }
|
||||
public void setFailureMessage(String failureMessage) { this.failureMessage = failureMessage; }
|
||||
|
||||
public Instant getCreationDateTime() { return creationDateTime; }
|
||||
public void setCreationDateTime(Instant creationDateTime) { this.creationDateTime = creationDateTime; }
|
||||
|
||||
|
||||
+6
-4
@@ -507,10 +507,12 @@ public class EmrServerlessJobRunService implements Resettable {
|
||||
// The runs live in storage, which the reset has already wiped.
|
||||
}
|
||||
|
||||
// Whether a run's driver may still start: a cancelled run is past it, and so is one a reset removed.
|
||||
private synchronized boolean waitingToStart(String jobRunId, long launchedIn) {
|
||||
// Whether a run's driver may still start, or go on: a cancelled run is past it, and so is one a reset removed.
|
||||
private synchronized boolean stillGoing(String jobRunId, long launchedIn) {
|
||||
return launchedIn == generation && store.get(jobRunId)
|
||||
.map(record -> STATE_SCHEDULED.equals(record.getJobRun().getState())).orElse(false);
|
||||
.map(record -> STATE_SCHEDULED.equals(record.getJobRun().getState())
|
||||
|| STATE_RUNNING.equals(record.getJobRun().getState()))
|
||||
.orElse(false);
|
||||
}
|
||||
|
||||
private synchronized void driverStarted(String jobRunId, long launchedIn) {
|
||||
@@ -859,7 +861,7 @@ public class EmrServerlessJobRunService implements Resettable {
|
||||
@Override
|
||||
public boolean cancelled() {
|
||||
return !RequestScopes.callAs(job.accountId(), job.region(),
|
||||
() -> waitingToStart(job.runId(), launchedIn));
|
||||
() -> stillGoing(job.runId(), launchedIn));
|
||||
}
|
||||
}
|
||||
}
|
||||
+7
-5
@@ -179,6 +179,7 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
|
||||
* service calls this before it hands a run to {@link #run}, so every driver of this deployment it
|
||||
* finds is a leftover.
|
||||
*/
|
||||
@Override
|
||||
public void removeLeftoverDrivers(String service) {
|
||||
String owner = ContainerStorageHelper.ownerIdentity(config);
|
||||
ContainerStorageHelper.LabelAliases aliases = ContainerStorageHelper.CONTAINER_LABEL_ALIASES;
|
||||
@@ -301,15 +302,16 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
|
||||
|
||||
/**
|
||||
* How the running driver ends: with its exit code, by a stop, or at the run's timeout, which
|
||||
* {@code progress} hears before the driver is stopped. A stop is read at every look, so it ends the
|
||||
* run whether or not the driver would ever exit by itself, as a STREAMING run's does not, and run()
|
||||
* then removes the driver. Each look at the container is one short control-plane call, so a run
|
||||
* holds no Docker connection while its driver runs.
|
||||
* {@code progress} hears before the driver is stopped. A stop, and a run {@code progress} reports
|
||||
* cancelled or gone, are read at every look, so they end the run whether or not the driver would ever
|
||||
* exit by itself, as a STREAMING run's does not, and run() then removes the driver: one a run started
|
||||
* while a reset's teardown was passing is stopped once the reset has removed its run. Each look at the
|
||||
* container is one short control-plane call, so a run holds no Docker connection while its driver runs.
|
||||
*/
|
||||
private Outcome awaitEnd(String containerId, Job job, Launch launch, Progress progress)
|
||||
throws InterruptedException {
|
||||
Instant deadline = job.timeout().isZero() ? null : clock.instant().plus(job.timeout());
|
||||
while (!launch.stopRequested) {
|
||||
while (!launch.stopRequested && !progress.cancelled()) {
|
||||
InspectContainerResponse.ContainerState state =
|
||||
lifecycleManager.getDockerClient().inspectContainerCmd(containerId).exec().getState();
|
||||
if (!Boolean.TRUE.equals(state.getRunning())) {
|
||||
|
||||
+10
-1
@@ -25,6 +25,12 @@ public interface SparkJobRunner {
|
||||
*/
|
||||
void stop(String runId);
|
||||
|
||||
/**
|
||||
* Removes the drivers of {@code service}'s runs an earlier Floci process left running, which no thread
|
||||
* follows any more. The service calls it before any run of its own can start.
|
||||
*/
|
||||
void removeLeftoverDrivers(String service);
|
||||
|
||||
/** What a run tells the service, and asks it, while it goes. */
|
||||
interface Progress {
|
||||
|
||||
@@ -34,7 +40,10 @@ public interface SparkJobRunner {
|
||||
/** The run has passed its timeout, and its driver is about to be stopped. */
|
||||
void timedOut();
|
||||
|
||||
/** Whether the run was cancelled, or is gone, so that its driver must not start. */
|
||||
/**
|
||||
* Whether the run was cancelled, or is gone, as after a reset: its driver must not start, and one
|
||||
* that runs is stopped.
|
||||
*/
|
||||
boolean cancelled();
|
||||
}
|
||||
|
||||
|
||||
@@ -590,6 +590,12 @@ floci:
|
||||
cluster-startup-delay-seconds: 0 # 0 = a cluster is ready as soon as it is created
|
||||
step-duration-seconds: 0 # 0 = a step completes as soon as it starts
|
||||
cluster-termination-delay-seconds: 0 # 0 = a cluster is TERMINATED as soon as it is TERMINATING
|
||||
runner-mode: immediate # docker = run each Spark step's spark-submit in a container
|
||||
# docker-network: floci-network
|
||||
# image-template: "registry.internal/emr-serverless/spark/%s:20250425" # %s = the release label
|
||||
# Remove the step drivers a previous run of this deployment left on the daemon when the EMR
|
||||
# service starts. Scoped to this deployment's own containers.
|
||||
reconcile-containers-on-startup: true
|
||||
wafv2:
|
||||
enabled: true
|
||||
scheduler:
|
||||
|
||||
+437
@@ -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;
|
||||
}
|
||||
}
|
||||
+11
@@ -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.
|
||||
}
|
||||
}
|
||||
}
|
||||
+15
@@ -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();
|
||||
|
||||
Reference in new issue
Block a user