feat(emr): run a notebook execution's notebook on its cluster in the docker runner mode (#8764)

With runner-mode docker, StartNotebookExecution now runs the notebook on
its cluster as a step's command runs: a spark-submit there, a YARN
application with the cluster's Spark settings, as the execution's
ExecutionRoleArn, else the cluster's instance profile, with its
EnvironmentVariables (KERNEL_EXTRA_SPARK_OPTS, as AWS's example passes,
going to spark-submit as its options).

No source names AWS's kernel, so a program of Floci's own runs it,
needing only Python and PySpark, which every release's image has, not
Jupyter: it reads the notebook through the cluster's S3A, puts
NotebookParams in papermill's way (a cell tagged injected-parameters
after the one tagged parameters, else first, in place of any an earlier
run left; a name that is not a Python variable's fails the run), clears
every earlier output, runs the code cells in one namespace holding spark
and sc, keeping each one's output, its last expression's value and any
error, stops at the first cell that raises, and writes the notebook as
run as <name>.ipynb and <name>.html, then exits 3. A %%sql cell runs its
body with spark.sql, a %%local or %%spark one as Python, and other cell
magics are not run; % and ! lines are dropped only from a cell that is
not Python as it stands.

The notebook is the execution's NotebookS3Location; Floci keeps no EMR
Notebook's own S3 location, so an execution named by EditorId alone
fails at once. No source gives where AWS writes the notebook as run, so
Floci writes it under the OutputNotebookS3Location prefix, else beside
the notebook, in a folder named for the execution, and reports the one
OutputNotebookFormat names, the HTML one, else the notebook, as
OutputNotebookURI. The execution is START_PENDING until its container
runs, then RUNNING, and FINISHED, FAILED at the first raising cell (any
other failure giving the run's exit code), or STOPPED,
StopNotebookExecution going through STOPPING; its cluster's end stops
it, and one a restart left behind fails as interrupted.

EmrService.runOnCluster runs such a command on a cluster through the
cluster preparation steps and sessions share, its cluster's storage held
while it runs and its end stopping it. As a step's, its thread starts
nothing once its cluster has shut down or a reset's or a shutdown's
teardown has begun; one that cannot be handed to its thread ends at
once.

EmrNotebookExecutionNightlyIntegrationTest runs it for real on an
emr-7.5.0 cluster: a parameterized notebook's run, an earlier run's
parameters in it, written to S3 with its outputs, its %%sql cell's among
them, and HTML; a failing notebook's FAILED with its error kept and an
earlier run's later outputs gone; and a misnamed parameter's run failed
with its exit code.
The nightly job's timeout and image prefetch take the new check.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-17 15:08:32 -04:00
1 parent 45aeeb0652
commit 9821a919b6
12 files changed
+1082 -27

No files matched your search

+2 -1
View File
@@ -118,7 +118,7 @@ starts ElbV2LambdaTargetDataPlaneIntegrationTest && ecr public.ecr.aws/lambda/py
# EmrFlociContainerNightlyIntegrationTest runs a cluster's steps in it from Floci in a container, and
# EmrPigStepsNightlyIntegrationTest a cluster's Pig steps.
starts EmrDockerRunnerDockerIntegrationTest EmrHiveStepsDockerIntegrationTest EmrServerlessCustomImageNightlyIntegrationTest \
EmrFlociContainerNightlyIntegrationTest EmrPigStepsNightlyIntegrationTest \
EmrFlociContainerNightlyIntegrationTest EmrPigStepsNightlyIntegrationTest EmrNotebookExecutionNightlyIntegrationTest \
&& ecr public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest
# EmrServerlessHiveDockerIntegrationTest runs EMR Serverless Hive job runs, and EmrHiveStepsDockerIntegrationTest EMR
# Hive steps, in the emr-7.5.0 Hive image the runner's default Hive template names, 2.7 GB; every EMR cluster runs its
@@ -127,6 +127,7 @@ starts EmrDockerRunnerDockerIntegrationTest EmrHiveStepsDockerIntegrationTest Em
# Hadoop comes from it too).
starts EmrServerlessHiveDockerIntegrationTest EmrHiveStepsDockerIntegrationTest EmrDockerRunnerDockerIntegrationTest \
EmrFlociContainerNightlyIntegrationTest EmrPigStepsNightlyIntegrationTest EmrSessionServerNightlyIntegrationTest \
EmrNotebookExecutionNightlyIntegrationTest \
&& ecr public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest
# The nightly EmrServerlessSparkConnectNightlyIntegrationTest runs a session's Spark Connect server, and its client, in
# the emr-7.13.0 image, 3.7 GB, the first release with sessions.
+4 -4
View File
@@ -32,10 +32,10 @@ jobs:
# twenty minutes for the build, the image and the prefetch: EmrPigStepsNightlyIntegrationTest's 30,
# EmrFlociContainerNightlyIntegrationTest's 20 and 4 for its setup,
# EmrServerlessCustomImageNightlyIntegrationTest's 85 and 21 for its setup,
# EmrServerlessSparkConnectNightlyIntegrationTest's 30, and EmrSessionServerNightlyIntegrationTest's 40, 230 in all.
# A check added, or a bound raised, raises this with it, so a slow check fails with its own message rather than the
# job being cancelled with none.
timeout-minutes: 250
# EmrServerlessSparkConnectNightlyIntegrationTest's 30, EmrSessionServerNightlyIntegrationTest's 40, and
# EmrNotebookExecutionNightlyIntegrationTest's 40, 270 in all. A check added, or a bound raised, raises this with it,
# so a slow check fails with its own message rather than the job being cancelled with none.
timeout-minutes: 290
# A fork's schedule would spend its owner's minutes on checks it never asked for; a draft waits until it is
# ready for review, as the CI shards do.
if: >-
+43 -9
View File
@@ -311,8 +311,9 @@ nothing answers.
## Notebook executions
Floci keeps a notebook execution and its lifecycle, but runs no notebook, in either runner mode, and writes no output
notebook.
With `runner-mode` set to `docker`, a notebook execution runs its notebook on its cluster and writes it as run (see
[Running a notebook execution's notebook](#running-a-notebook-executions-notebook)). With the default `immediate`
mode, Floci keeps an execution and its lifecycle but runs no notebook and writes no output notebook.
* **StartNotebookExecution** refuses a request without `ExecutionEngine.Id` or `ServiceRole`, or with an
`ExecutionEngine.Type` or `OutputNotebookFormat` the model does not name, with `ValidationException`, and a member of
@@ -326,17 +327,50 @@ notebook.
`InvalidRequestException` in Floci's own wording. The editor, relative path, S3 locations and parameters are kept as
given. The execution's id is `ex-` and 29 letters and digits, and its `ExecutionEngine.Type` is `EMR` unless given.
IAM's `aws:ResourceTag` conditions read its tags.
* **States**: an execution is `START_PENDING` as it starts, `RUNNING` from then on, and `FINISHED` once the cluster's
`step-duration-seconds` has passed (at once by default), with AWS's "Execution is finished for cluster ...". It is
`FAILED` if its cluster shuts down first, or once it has run 30 days, as "An execution is terminated if it runs for
more than 30 days", in Floci's own wording.
* **StopNotebookExecution** stops one that has not ended at once, `STOPPED` with AWS's "Execution is stopped for
cluster ...". One that has ended is refused with `InvalidRequestException`, in Floci's own wording.
* **States**: in the `immediate` mode an execution is `START_PENDING` as it starts, `RUNNING` from then on, and
`FINISHED` once the cluster's `step-duration-seconds` has passed (at once by default), with AWS's "Execution is
finished for cluster ...". It is `FAILED` if its cluster shuts down first, or once it has run 30 days, as "An
execution is terminated if it runs for more than 30 days", in Floci's own wording. In the `docker` mode its run sets
them (below).
* **StopNotebookExecution** stops one that has not ended, `STOPPED` with AWS's "Execution is stopped for cluster ...":
at once with no notebook running, else `STOPPING` ("Execution is being stopped for cluster ...") until its run has
stopped. One that has ended is refused with `InvalidRequestException`, in Floci's own wording.
* **ListNotebookExecutions** lists the Region's executions that started from `From` (by default 30 days ago) to
`To` (by default now), filtered by `EditorId`, `Status` and `ExecutionEngineId`, newest first, at most 50 to a page
("Returns a maximum of 50 notebook executions") after a `Marker`, which resumes only the listing it came from: the
same account, Region and filters.
### Running a notebook execution's notebook
With `runner-mode` set to `docker`, an execution runs its notebook on its cluster as a step's command runs: a
`spark-submit` there, a YARN application with the cluster's Spark settings, as the execution's `ExecutionRoleArn`,
else the cluster's instance profile, with its `EnvironmentVariables`. No source names the kernel AWS runs a notebook
with, so Floci runs it with a program of its own, needing only Python and PySpark, which every release's image has,
not Jupyter:
* **The notebook** is the execution's `NotebookS3Location`, read through the cluster's S3A. AWS finds an EMR
Notebook named by `EditorId` and `RelativePath` under the notebook's own S3 location, which Floci keeps none of, so
such an execution fails at once, in Floci's own wording.
* **Its cells**: the code cells run in turn in one Python namespace that holds `spark` and `sc`, each keeping what it
printed, the value of its last expression, and any error, every output an earlier run left cleared first. Of
sparkmagic's cell commands, a `%%sql` cell runs its body with `spark.sql`, showing the result's first 20 rows, and a
`%%local` or `%%spark` one runs its body as Python; any other (`%%configure`, `%%info`, ...) is not run. A `%` or
`!` line of IPython's or sparkmagic's commands is not run either, where the cell is not Python as it stands.
`NotebookParams`, "Input parameters in JSON format", go in as papermill puts them, in a cell tagged
`injected-parameters` after the one tagged `parameters`, else first, as "You can pass different parameter values to
a notebook with a parameterized notebook cell", in place of any such cell an earlier run left; each parameter's name
must be a Python variable's, or the run fails before any cell. An environment variable `KERNEL_EXTRA_SPARK_OPTS`, as
AWS's example passes, goes to `spark-submit` as its options.
* **The notebook as run**: no source gives where AWS writes it, so Floci writes it under the
`OutputNotebookS3Location` prefix, else beside the notebook, in a folder named for the execution, as `<name>.ipynb`
and `<name>.html`, and reports the one `OutputNotebookFormat` names, the HTML one, else the notebook, as the
execution's `OutputNotebookURI`.
* **States**: `START_PENDING` until its container runs, then `RUNNING`; `FINISHED` once every cell has run; `FAILED`
at the first cell that raises (the notebook as run, written all the same, holds its error), where the run fails
otherwise (its reason giving the run's exit code, the notebook as run perhaps not written), where it could not
start, where its cluster shuts down, which stops the run, or after 30 days, in Floci's own wording. One Floci stopped
running when it restarted fails too.
## Application UIs
Floci keeps a cluster's persistent application UIs, but serves no Spark History Server, Tez UI, YARN timeline server
@@ -911,7 +945,7 @@ 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 step, and each session's Spark Connect server, in a container, after the cluster's bootstrap actions (see [Running steps](#running-steps) and [Running a session's Spark Connect server](#running-a-sessions-spark-connect-server)) |
| `FLOCI_SERVICES_EMR_RUNNER_MODE` | `immediate` | `immediate` completes steps by time without running anything; `docker` runs each step, each session's Spark Connect server and each notebook execution's notebook in a container, after the cluster's bootstrap actions (see [Running steps](#running-steps), [Running a session's Spark Connect server](#running-a-sessions-spark-connect-server) and [Running a notebook execution's notebook](#running-a-notebook-executions-notebook)) |
| `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; a mirror sets `FLOCI_SERVICES_EMR_HIVE_IMAGE_TEMPLATE` too |
| `FLOCI_SERVICES_EMR_HIVE_IMAGE_TEMPLATE` | `public.ecr.aws/emr-serverless/hive/%s:latest` | The EMR Serverless Hive image a `docker` cluster takes HDFS and YARN from, and a cluster with Hive takes Hive from, `%s` standing for the cluster's release label, or `emr-7.5.0` for the Hadoop of an `emr-spark-*` release; see [Storage and Hive steps](#running-steps) |
@@ -795,6 +795,7 @@ public class EmrHandler {
putS3Location(node, "OutputNotebookS3Location", execution.getOutputNotebookS3Bucket(),
execution.getOutputNotebookS3Key());
putIfSet(node, "OutputNotebookFormat", execution.getOutputNotebookFormat());
putIfSet(node, "OutputNotebookURI", execution.getOutputNotebookUri());
if (execution.getEnvironmentVariables() != null) {
ObjectNode variables = node.putObject("EnvironmentVariables");
execution.getEnvironmentVariables().forEach(variables::put);
@@ -12,6 +12,7 @@ import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.emr.model.EmrCluster;
import io.floci.aws.services.emr.model.EmrNotebookExecution;
import io.floci.aws.services.emrserverless.EmrServerlessSparkRunner;
import io.floci.aws.services.emrserverless.SparkJobRunner;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -20,6 +21,7 @@ import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -27,10 +29,11 @@ import java.util.Set;
/**
* Notebook executions on EMR clusters (Amazon EMR Management Guide, "Sample programmatic commands for EMR Notebooks").
* Floci keeps an execution and its lifecycle, but runs no notebook: in either runner mode an execution is RUNNING from
* the moment it starts and FINISHED once the cluster's step duration ({@code step-duration-seconds}) has passed, unless
* it is stopped first or its cluster shuts down; it writes no output notebook. Executions are kept apart from their
* clusters.
* In the immediate runner mode Floci keeps an execution and its lifecycle but runs no notebook: it is RUNNING from the
* moment it starts and FINISHED once the cluster's step duration ({@code step-duration-seconds}) has passed, unless it
* is stopped first or its cluster shuts down, and writes no output notebook. In the docker runner mode it runs the
* notebook on its cluster ({@link EmrNotebookRunner}, {@link EmrService#runOnCluster}) and writes it as run. Executions
* are kept apart from their clusters.
*/
@ApplicationScoped
public class EmrNotebookExecutionService {
@@ -40,6 +43,15 @@ public class EmrNotebookExecutionService {
static final String FINISHED = "FINISHED";
static final String FAILED = "FAILED";
static final String STOPPED = "STOPPED";
static final String STOPPING = "STOPPING";
static final String INTERRUPTED = "Floci stopped while the notebook execution was running.";
static final String NO_NOTEBOOK = "Execution failed for cluster %s: Floci keeps no EMR Notebook's S3 location, so"
+ " it runs a notebook only from its NotebookS3Location.";
static final String CELL_FAILED = "Execution failed for cluster %s: a cell of the notebook raised an error, which"
+ " the output notebook holds.";
// Its run failed otherwise, before a cell ran or as the notebook as run was written, which may then be missing.
static final String RUN_FAILED = "Execution failed for cluster %s: the notebook's run exited with code %s, as"
+ " Floci's log says.";
static final List<String> STATUSES = List.of(START_PENDING, "STARTING", RUNNING, "FINISHING", FINISHED,
"FAILING", FAILED, "STOP_PENDING", "STOPPING", STOPPED);
private static final Set<String> ENDED = Set.of(FINISHED, FAILED, STOPPED);
@@ -63,6 +75,9 @@ public class EmrNotebookExecutionService {
private final RegionResolver regionResolver;
private final Clock clock;
private final Duration runDuration;
// The executions whose notebook a thread of this process runs; one not here that has not ended was left by a
// restart.
private final Set<String> running = new HashSet<>();
@Inject
public EmrNotebookExecutionService(StorageFactory storageFactory, EmrService clusters,
@@ -136,8 +151,106 @@ public class EmrNotebookExecutionService {
: new LinkedHashMap<>());
execution.setSequence(store.scan(key -> true).stream().mapToLong(EmrNotebookExecution::getSequence)
.max().orElse(0) + 1);
execution.setContainerExecution(clusters.runsOnClusters());
store.put(id, execution);
return copy(execution);
if (execution.isContainerExecution()) {
runNotebook(execution);
}
// As stored: a run that could not be handed to its thread has ended it already.
return copy(store.get(id).orElse(execution));
}
/**
* Runs the execution's notebook on its cluster. The notebook is its {@code NotebookS3Location}: no source gives the
* S3 location of an EMR Notebook named by {@code EditorId} alone, which Floci keeps none of, so such an execution
* fails at once, in Floci's own wording. No source gives where AWS writes the notebook as run either: Floci writes
* it under the {@code OutputNotebookS3Location} prefix, else beside the notebook, in a folder named for the
* execution, as {@code <name>.ipynb} and {@code <name>.html}, and gives the one the {@code OutputNotebookFormat}
* names, the HTML one, else the notebook, as its {@code OutputNotebookURI}.
*/
private void runNotebook(EmrNotebookExecution execution) {
if (execution.getNotebookS3Bucket() == null || execution.getNotebookS3Key() == null) {
end(execution, FAILED, String.format(NO_NOTEBOOK, execution.getEngineId()), now());
return;
}
String key = execution.getNotebookS3Key();
String file = key.substring(key.lastIndexOf('/') + 1);
String name = file.endsWith(".ipynb") ? file.substring(0, file.length() - ".ipynb".length()) : file;
String base = execution.getOutputNotebookS3Bucket() != null
? join(execution.getOutputNotebookS3Bucket(), trimSlashes(execution.getOutputNotebookS3Key()))
: join(execution.getNotebookS3Bucket(), trimSlashes(key.substring(0, key.length() - file.length())));
String folder = "s3://" + join(base, execution.getId());
execution.setOutputNotebookUri(folder + "/" + name
+ ("HTML".equals(execution.getOutputNotebookFormat()) ? ".html" : ".ipynb"));
store.put(execution.getId(), execution);
Map<String, String> environment = new LinkedHashMap<>(execution.getEnvironmentVariables() != null
? execution.getEnvironmentVariables() : Map.of());
environment.put(EmrNotebookRunner.PROGRAM_VARIABLE, EmrNotebookRunner.PROGRAM);
running.add(execution.getId());
clusters.runOnCluster(execution.getEngineId(), execution.getId(), execution.getExecutionRoleArn(),
EmrNotebookRunner.command("s3://" + execution.getNotebookS3Bucket() + "/" + key, folder, name,
execution.getNotebookParams()), environment, MAX_RUN, new NotebookRun(execution.getId()));
}
private static String join(String first, String second) {
return second.isEmpty() ? first : first + "/" + second;
}
private static String trimSlashes(String key) {
String trimmed = key == null ? "" : key;
while (trimmed.startsWith("/")) {
trimmed = trimmed.substring(1);
}
while (trimmed.endsWith("/")) {
trimmed = trimmed.substring(0, trimmed.length() - 1);
}
return trimmed;
}
private synchronized void notebookStarted(String executionId) {
store.get(executionId).filter(execution -> START_PENDING.equals(execution.getStatus()))
.ifPresent(execution -> {
execution.setStatus(RUNNING);
store.put(executionId, execution);
});
}
/**
* The notebook's run has ended: FINISHED where every cell ran, "Execution is finished for cluster ...", as AWS's
* example puts it; STOPPED where StopNotebookExecution stopped it; FAILED where a cell raised (the program's
* {@link EmrNotebookRunner#CELL_RAISED}), where the run failed otherwise, where it could not start, where its
* cluster shut down, or after 30 days, in Floci's own wording.
*/
private synchronized void notebookEnded(String executionId, SparkJobRunner.Outcome outcome) {
running.remove(executionId);
store.get(executionId).filter(execution -> !ENDED.contains(execution.getStatus())).ifPresent(execution -> {
String cluster = execution.getEngineId();
Instant now = now();
if (STOPPING.equals(execution.getStatus())) {
end(execution, STOPPED, "Execution is stopped for cluster " + cluster + ".", now);
} else if (outcome.timedOut()) {
end(execution, FAILED, "Execution is terminated for cluster " + cluster
+ ", as it ran for more than 30 days.", now);
} else if (outcome.stopped()) {
end(execution, FAILED, "Execution failed for cluster " + cluster
+ ", as the cluster was terminated.", now);
} else if (outcome.failure() != null) {
end(execution, FAILED, "Execution failed for cluster " + cluster + ": " + outcome.failure(), now);
} else if (outcome.exitCode() != null && outcome.exitCode() == 0) {
end(execution, FINISHED, "Execution is finished for cluster " + cluster + ".", now);
} else if (outcome.exitCode() != null && outcome.exitCode() == EmrNotebookRunner.CELL_RAISED) {
end(execution, FAILED, String.format(CELL_FAILED, cluster), now);
} else {
end(execution, FAILED, String.format(RUN_FAILED, cluster, outcome.exitCode()), now);
}
});
}
private synchronized boolean notebookGoing(String executionId) {
return running.contains(executionId) && store.get(executionId)
.map(execution -> !ENDED.contains(execution.getStatus())
&& !STOPPING.equals(execution.getStatus()))
.orElse(false);
}
public synchronized EmrNotebookExecution describe(String executionId) {
@@ -154,6 +267,15 @@ public class EmrNotebookExecutionService {
if (ENDED.contains(execution.getStatus())) {
throw EmrService.invalid("Notebook execution " + executionId + " has already ended.");
}
if (running.contains(executionId)) {
// STOPPING until its run has stopped, as AWS's example has it: "Execution is being stopped for cluster".
execution.setStatus(STOPPING);
execution.setLastStateChangeReason("Execution is being stopped for cluster " + execution.getEngineId()
+ ".");
store.put(executionId, execution);
clusters.stopOnCluster(executionId);
return;
}
end(execution, STOPPED, "Execution is stopped for cluster " + execution.getEngineId() + ".", now());
}
@@ -246,6 +368,13 @@ public class EmrNotebookExecutionService {
if (ENDED.contains(execution.getStatus())) {
return execution;
}
// Its run ends it; without one, Floci stopped while it ran, and nothing is left to.
if (execution.isContainerExecution()) {
if (!running.contains(execution.getId())) {
end(execution, FAILED, INTERRUPTED, now());
}
return execution;
}
boolean changed = false;
if (START_PENDING.equals(execution.getStatus())) {
execution.setStatus(RUNNING);
@@ -291,6 +420,31 @@ public class EmrNotebookExecutionService {
store.put(execution.getId(), execution);
}
/** What a notebook's run on its cluster tells the service, as the execution's account. */
private final class NotebookRun implements EmrService.ClusterRun {
private final String executionId;
NotebookRun(String executionId) {
this.executionId = executionId;
}
@Override
public void started() {
notebookStarted(executionId);
}
@Override
public void ended(SparkJobRunner.Outcome outcome) {
notebookEnded(executionId, outcome);
}
@Override
public boolean cancelled() {
return !notebookGoing(executionId);
}
}
private EmrNotebookExecution require(String executionId) {
if (executionId == null) {
throw SmithyValidationErrors.validationException(SmithyValidationErrors.notNull("notebookExecutionId"));
@@ -0,0 +1,232 @@
package io.floci.aws.services.emr;
import java.util.List;
/**
* What runs a notebook execution's notebook on its cluster, in the docker runner mode: a Python program of Floci's own,
* in place of AWS's kernel, which no source names. It reads the notebook from S3 through the cluster's S3A, puts in the
* execution's parameters as papermill does, a cell tagged {@code injected-parameters} after the one tagged
* {@code parameters} (else first), as "You can pass different parameter values to a notebook with a parameterized
* notebook cell", in place of any an earlier run put in, each parameter's name a Python variable's. It runs each code
* cell in turn, every earlier output cleared first, in one namespace that holds {@code spark} and {@code sc}, keeping
* its output, the value of its last expression and any error. A {@code %%sql} cell runs its body with
* {@code spark.sql}, showing the result's first rows, and a {@code %%local} or {@code %%spark} one runs its body as
* Python; another cell of sparkmagic's or IPython's commands is not run, nor is a {@code %} or {@code !} line of a cell
* that is not Python as it stands. It stops at the first cell that raises, and writes the notebook as run, as
* {@code <name>.ipynb} and as {@code <name>.html}, under the output folder, then exits {@link #CELL_RAISED}; any other
* failure exits otherwise, the notebook perhaps not written.
*/
final class EmrNotebookRunner {
// Where the program goes in the container, from the variable it comes in.
static final String PROGRAM_PATH = "/tmp/floci-notebook-runner.py";
static final String PROGRAM_VARIABLE = "FLOCI_NOTEBOOK_RUNNER";
/** The program's exit code once a cell has raised and the notebook as run is written. */
static final int CELL_RAISED = 3;
// Python 3 and PySpark, which every EMR release's image has; no Jupyter, which they do not.
static final String PROGRAM = """
import ast
import contextlib
import html
import io
import json
import keyword
import sys
import traceback
from pyspark.sql import SparkSession
def filesystem(spark, uri):
jvm = spark.sparkContext._jvm
path = jvm.org.apache.hadoop.fs.Path(uri)
return path, path.getFileSystem(spark.sparkContext._jsc.hadoopConfiguration())
def read(spark, uri):
path, fs = filesystem(spark, uri)
stream = fs.open(path)
jvm = spark.sparkContext._jvm
data = jvm.org.apache.commons.io.IOUtils.toByteArray(stream)
stream.close()
return bytes(data).decode("utf-8")
def write(spark, uri, text):
path, fs = filesystem(spark, uri)
stream = fs.create(path, True)
stream.write(bytearray(text.encode("utf-8")))
stream.close()
def lines(source):
return source if isinstance(source, list) else str(source).splitlines(True)
def tags(cell):
return cell.get("metadata", {}).get("tags", [])
def inject(cells, params):
# A notebook an earlier run wrote has its parameters, which this run's replace.
cells[:] = [cell for cell in cells if "injected-parameters" not in tags(cell)]
if not params:
return
source = ["# Parameters\\n"] + ["%s = %r\\n" % (name, value) for name, value in params.items()]
cell = {"cell_type": "code", "execution_count": None, "metadata": {"tags": ["injected-parameters"]},
"outputs": [], "source": source}
at = 0
for index, existing in enumerate(cells):
if "parameters" in tags(existing):
at = index + 1
break
cells.insert(at, cell)
def cell_magic(text):
stripped = text.lstrip()
if not stripped.startswith("%%"):
return None, text
first, _, body = stripped.partition("\\n")
words = first[2:].split()
return (words[0] if words else ""), body
def python_source(text):
# A line of IPython's or sparkmagic's commands is dropped only from a cell that is not Python as it
# stands, so a line of a string or an expression that starts with % stays.
try:
ast.parse(text)
return text
except SyntaxError:
return "".join(line for line in text.splitlines(True)
if not line.lstrip().startswith(("%", "!")))
def run_cell(source, namespace, count):
magic, text = cell_magic("".join(lines(source)))
outputs = []
if magic not in (None, "sql", "local", "spark"):
return outputs, None
out, err = io.StringIO(), io.StringIO()
failure = None
value = None
try:
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
if magic == "sql":
frame = namespace["spark"].sql(text)
if frame.columns:
frame.show()
else:
tree = ast.parse(python_source(text), "<cell %d>" % count)
last = tree.body.pop() if tree.body and isinstance(tree.body[-1], ast.Expr) else None
exec(compile(tree, "<cell %d>" % count, "exec"), namespace)
if last is not None:
value = eval(compile(ast.Expression(last.value), "<cell %d>" % count, "eval"),
namespace)
except BaseException as e:
failure = e
value = None
if out.getvalue():
outputs.append({"output_type": "stream", "name": "stdout", "text": lines(out.getvalue())})
if err.getvalue():
outputs.append({"output_type": "stream", "name": "stderr", "text": lines(err.getvalue())})
if failure is None and value is not None:
outputs.append({"output_type": "execute_result", "execution_count": count, "metadata": {},
"data": {"text/plain": lines(repr(value))}})
if failure is not None:
outputs.append({"output_type": "error", "ename": type(failure).__name__,
"evalue": str(failure),
"traceback": traceback.format_exception(type(failure), failure,
failure.__traceback__)})
return outputs, failure
def page(name, cells):
parts = ["<!DOCTYPE html><html><head><meta charset=\\"utf-8\\"><title>%s</title></head><body>"
% html.escape(name), "<h1>%s</h1>" % html.escape(name)]
for cell in cells:
source = html.escape("".join(lines(cell.get("source", ""))))
if cell.get("cell_type") == "markdown":
parts.append("<div class=\\"markdown\\"><pre>%s</pre></div>" % source)
continue
if cell.get("cell_type") != "code":
continue
parts.append("<div class=\\"cell\\"><pre class=\\"source\\">%s</pre>" % source)
for output in cell.get("outputs", []):
if output["output_type"] == "error":
text = "".join(output["traceback"])
elif output["output_type"] == "stream":
text = "".join(output["text"])
else:
text = "".join(lines(output.get("data", {}).get("text/plain", "")))
parts.append("<pre class=\\"%s\\">%s</pre>" % (output["output_type"], html.escape(text)))
parts.append("</div>")
parts.append("</body></html>")
return "".join(parts)
def parameters(params):
values = json.loads(params) if params else {}
if not isinstance(values, dict):
raise ValueError("NotebookParams is not a JSON object")
for name in values:
if not name.isidentifier() or keyword.iskeyword(name):
raise ValueError("NotebookParams names %r, which is not a Python variable's name" % name)
return values
def main(source, folder, name, params):
values = parameters(params)
spark = SparkSession.builder.appName("notebook " + name).getOrCreate()
notebook = json.loads(read(spark, source))
cells = notebook.setdefault("cells", [])
inject(cells, values)
# A notebook an earlier run wrote has its outputs, which a cell this run does not reach keeps no more.
for cell in cells:
if cell.get("cell_type") == "code":
cell["outputs"] = []
cell["execution_count"] = None
namespace = {"__name__": "__main__", "spark": spark, "sc": spark.sparkContext}
count = 0
failed = None
for cell in cells:
if cell.get("cell_type") != "code":
continue
count += 1
outputs, failure = run_cell(cell.get("source", ""), namespace, count)
cell["execution_count"] = count
cell["outputs"] = outputs
if failure is not None:
failed = "cell %d raised %s: %s" % (count, type(failure).__name__, failure)
break
folder = folder.rstrip("/")
write(spark, folder + "/" + name + ".ipynb", json.dumps(notebook, indent=1))
write(spark, folder + "/" + name + ".html", page(name, cells))
spark.stop()
if failed is not None:
print("Notebook " + name + " failed: " + failed, file=sys.stderr)
sys.exit(@CELL_RAISED@)
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4] if len(sys.argv) > 4 else "")
""".replace("@CELL_RAISED@", String.valueOf(CELL_RAISED));
private EmrNotebookRunner() {
}
/**
* What the cluster's container runs for an execution: the program written out from its variable, then
* {@code spark-submit} with it, the notebook at {@code source}, the output {@code folder}, the notebook's
* {@code name} and the execution's parameters, as a step's command runs. The execution's
* {@code KERNEL_EXTRA_SPARK_OPTS} environment variable, as AWS's example passes
* {@code "--conf spark.executor.instances=1"}, goes to {@code spark-submit} as its options.
*/
static List<String> command(String source, String folder, String name, String params) {
return List.of("bash", "-c", "printf '%s' \"$" + PROGRAM_VARIABLE + "\" > " + PROGRAM_PATH
+ " && exec spark-submit $KERNEL_EXTRA_SPARK_OPTS \"$@\"", "floci-notebook",
PROGRAM_PATH, source, folder, name, params != null ? params : "");
}
}
@@ -169,6 +169,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
private final ClusterStorage clusterStorage;
private final ReleaseImages releaseImages;
private final Executor stepExecutor;
// The commands other EMR services run on a cluster ({@link #runOnCluster}), by run id, with their cluster's id.
private final Map<String, String> clusterRuns = new HashMap<>();
// The Spark Connect servers of the sessions, in the docker runner mode, and the tokens given for every session.
private final SparkConnectServers sessionServers;
private final SessionOwner sessionOwner = new SessionOwner();
@@ -451,6 +453,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
generation++;
executing.clear();
bootstrapping.clear();
clusterRuns.clear();
sessionServers.reset();
if (bootstrapRunner != null) {
bootstrapRunner.removeImages(Set.of());
@@ -862,6 +865,152 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
return sparkRunner != null && clusterStorage != null;
}
/** Whether {@link #runOnCluster} runs anything: in the docker runner mode, as steps run. */
public boolean runsOnClusters() {
return runsSessionServers();
}
/** What a command run on a cluster ({@link #runOnCluster}) tells its caller, and asks it, as its account. */
public interface ClusterRun {
/** The command's container runs. */
void started();
/** The command has ended, as {@code outcome} says; the cluster's end stops it, which says it was stopped. */
void ended(SparkJobRunner.Outcome outcome);
/** Whether the run is past starting, or going on. */
boolean cancelled();
}
/**
* Runs {@code command} on the cluster as a step's command runs, its {@code spark-submit} a YARN application there
* with the cluster's Spark settings, as {@code runId}, with {@code environment}, as {@code role} (else the
* cluster's instance profile), for at most {@code limit}, telling {@code run}. The cluster keeps its storage while
* it runs, and its end stops it, as a reset's or a shutdown's teardown does. A command that cannot be handed to its
* thread, its cluster shut down or a teardown begun, has ended before this returns, as stopped, or as one that
* could not start. A notebook execution runs its notebook so.
*/
public void runOnCluster(String clusterId, String runId, String role, List<String> command,
Map<String, String> environment, Duration limit, ClusterRun run) {
CommandLaunch launch;
try {
launch = call(() -> commandLaunch(clusterId, runId, role, command, environment, limit));
} catch (RuntimeException e) {
run.ended(SparkJobRunner.Outcome.couldNotStart(reasonOf(e)));
return;
}
if (launch == null) {
run.ended(SparkJobRunner.Outcome.halted());
return;
}
try {
stepExecutor.execute(() -> runCommand(launch, run));
} catch (RuntimeException e) {
run.ended(SparkJobRunner.Outcome.couldNotStart(reasonOf(e)));
forgetCommand(runId);
}
}
// A command that runs no more no longer holds what its cluster kept.
private void forgetCommand(String runId) {
run(() -> {
String clusterId = clusterRuns.remove(runId);
if (clusterId != null) {
clusterStore.get(clusterId).ifPresent(this::releaseEnded);
}
});
}
/**
* A command handed to its thread: its job, what sets its cluster up, its cluster, and the reset and the teardowns
* it was handed off after.
*/
private record CommandLaunch(SparkJobRunner.Job job, ClusterPreparation preparation, String clusterId,
long launchedIn, long teardownsBefore) {
}
// A command's launch, under the service's lock, its cluster keeping its storage from now; null where the cluster
// has shut down or a teardown has begun, which would stop it at once.
private CommandLaunch commandLaunch(String clusterId, String runId, String role, List<String> command,
Map<String, String> environment, Duration limit) {
EmrCluster cluster = requireCluster(clusterId);
if (tornDown || shutDownAt(cluster, now()) != null) {
return null;
}
String accountId = regionResolver.getAccountId();
String region = regionOf(cluster);
OnCluster onCluster = onCluster(cluster, accountId, region, true);
clusterStore.put(cluster.getId(), cluster);
SparkJobRunner.Job job = new SparkJobRunner.Job(SERVICE, runId, accountId, region,
cluster.getReleaseLabel(), SparkJobRunner.Engine.SPARK, onCluster.image(), null, dockerNetwork,
role != null ? role : instanceProfileRole(cluster, accountId),
EmrSparkSteps.sparkDefaults(cluster.getConfigurations(), SNAPSHOT_MAPPER), List.of(), command,
limit, null, null, environment, List.of(), onCluster.storage(),
EmrSparkSteps.coreSite(cluster.getConfigurations(), SNAPSHOT_MAPPER),
EmrSparkSteps.sparkLog4j2(cluster.getConfigurations(), SNAPSHOT_MAPPER),
EmrSparkSteps.mapredSite(cluster.getConfigurations(), SNAPSHOT_MAPPER),
EmrSparkSteps.hadoopLog4j(cluster.getConfigurations(), SNAPSHOT_MAPPER),
EmrSparkSteps.hadoopEnvironment(cluster.getConfigurations(), SNAPSHOT_MAPPER), null);
ClusterPreparation preparation = new ClusterPreparation(cluster.getId(), accountId, region,
onCluster.releaseImage(), onCluster.hdfs(), onCluster.primary());
clusterRuns.put(runId, cluster.getId());
return new CommandLaunch(job, preparation, cluster.getId(), generation, teardowns.get());
}
private static String reasonOf(RuntimeException e) {
return e.getMessage() != null ? e.getMessage() : e.toString();
}
/** Stops a command {@link #runOnCluster} runs, which then ends as stopped. */
public void stopOnCluster(String runId) {
if (sparkRunner != null) {
sparkRunner.stop(runId);
}
}
// A command's thread on its cluster, as a step's: its setup, its run, then its caller told, and what its cluster
// kept released once nothing of it runs any more.
private void runCommand(CommandLaunch launch, ClusterRun run) {
SparkJobRunner.Job job = launch.job();
ClusterPreparation preparation = launch.preparation();
SparkJobRunner.Outcome outcome;
SparkJobRunner.Progress progress = new SparkJobRunner.Progress() {
@Override
public void started() {
RequestScopes.runAs(job.accountId(), job.region(), run::started);
}
@Override
public void timedOut() {
// The outcome says so.
}
// Past starting, or going on, once a teardown has begun, a reset has removed it, its cluster has shut down,
// or its caller has stopped it.
@Override
public boolean cancelled() {
return teardowns.get() != launch.teardownsBefore()
|| !RequestScopes.callAs(job.accountId(), job.region(), () -> commandGoing(launch))
|| RequestScopes.callAs(job.accountId(), job.region(), run::cancelled);
}
};
try {
outcome = sparkRunner.run(preparation.prepare(job, progress::cancelled), progress);
} catch (RuntimeException e) {
outcome = progress.cancelled() ? SparkJobRunner.Outcome.halted()
: SparkJobRunner.Outcome.couldNotStart(reasonOf(e));
} finally {
preparation.release();
}
SparkJobRunner.Outcome ended = outcome;
try {
RequestScopes.runAs(job.accountId(), job.region(), () -> run.ended(ended));
} finally {
RequestScopes.runAs(job.accountId(), job.region(), () -> forgetCommand(job.runId()));
}
}
/**
* Runs a session's Spark Connect server on its cluster, as a step runs, a YARN application there: its driver in a
* container on the cluster, in the image its steps run in, reached through Floci. Its {@code spark-defaults} are
@@ -2065,7 +2214,16 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
// still running on it", and stops their servers.
private void endSessionsOf(EmrCluster cluster) {
Instant now = now();
if (!cluster.isSessionEnabled() || EmrService.shutDownAt(cluster, now) == null) {
if (EmrService.shutDownAt(cluster, now) == null) {
return;
}
// The commands run on it stop too, and end as stopped.
clusterRuns.forEach((runId, clusterId) -> {
if (clusterId.equals(cluster.getId())) {
stopOnCluster(runId);
}
});
if (!cluster.isSessionEnabled()) {
return;
}
for (EmrSession session : sessionStore.scan(key -> true)) {
@@ -2078,8 +2236,12 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
}
}
// Whether a server of the cluster's sessions is still there, its container perhaps still on its storage.
// Whether a server of the cluster's sessions, or a command run on it, is still there, its container perhaps still
// on its storage.
private boolean sessionServersRunning(EmrCluster cluster) {
if (clusterRuns.containsValue(cluster.getId())) {
return true;
}
return cluster.isSessionEnabled() && sessionStore.scan(key -> true).stream()
.anyMatch(session -> cluster.getId().equals(session.getClusterId())
&& sessionServers.runs(session.getId()));
@@ -2311,6 +2473,12 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
.filter(step -> EmrClusterLifecycle.RUNNING.equals(step.getState())).isPresent();
}
// Whether a command's cluster still runs, in the reset it was handed off in.
private synchronized boolean commandGoing(CommandLaunch launch) {
return launch.launchedIn() == generation && clusterStore.get(launch.clusterId())
.filter(cluster -> shutDownAt(cluster, now()) == null).isPresent();
}
private synchronized boolean resetSince(StepLaunch launch) {
return launch.launchedIn() != generation;
}
@@ -38,6 +38,9 @@ public class EmrNotebookExecution {
private String lastStateChangeReason;
private String region;
private long sequence;
// Where its run wrote the notebook as run, and whether Floci runs it on its cluster, as in the docker runner mode.
private String outputNotebookUri;
private boolean containerExecution;
public EmrNotebookExecution() {}
@@ -103,4 +106,8 @@ public class EmrNotebookExecution {
public void setRegion(String region) { this.region = region; }
public long getSequence() { return sequence; }
public void setSequence(long sequence) { this.sequence = sequence; }
public String getOutputNotebookUri() { return outputNotebookUri; }
public void setOutputNotebookUri(String outputNotebookUri) { this.outputNotebookUri = outputNotebookUri; }
public boolean isContainerExecution() { return containerExecution; }
public void setContainerExecution(boolean containerExecution) { this.containerExecution = containerExecution; }
}
+1 -1
View File
@@ -661,7 +661,7 @@ 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 bootstrap actions, steps and sessions' servers in containers
runner-mode: immediate # docker = run bootstrap actions, steps, sessions' servers and notebooks in containers
# docker-network: floci-network
# image-template: "registry.internal/emr-serverless/spark/%s:20250425" # %s = the release label
# hive-image-template: "registry.internal/emr-serverless/hive/%s:20250425" # every cluster's HDFS, and Hive
@@ -0,0 +1,202 @@
package io.floci.aws.services.emr;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.DockerAvailability;
import io.floci.aws.testing.PartitionCleanup;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.floci.aws.testing.S3TestClients;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import org.junit.jupiter.api.extension.RegisterExtension;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;
import java.util.function.Supplier;
import static io.floci.aws.testing.EmrRequests.emr;
import static io.floci.aws.testing.EmrRequests.terminateClusterAndAwaitCleanup;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* EMR notebook executions run for real: a notebook in S3 runs on an emr-7.5.0 cluster's Spark, its parameters put in
* after its parameters cell in place of those an earlier run left, its {@code %%sql} cell run by Spark SQL, and the
* notebook as run, its cells' outputs in it, is written to S3 with its HTML; a notebook whose cell raises fails its
* execution, the error kept in the notebook written and the outputs an earlier run left past it gone; a parameter that
* is not a Python variable's name fails the run before any cell.
*
* <p>A nightly check: the cluster's image, HDFS and YARN, and each notebook's Spark driver take minutes and gigabytes.
*/
@QuarkusTest
@TestProfile(EmrNotebookExecutionNightlyIntegrationTest.Profile.class)
@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true")
// Bounded waits: the cluster's image of up to twenty minutes, its HDFS and YARN, and two notebooks' runs; the Nightly
// checks job's timeout counts the 40.
@Timeout(value = 40, unit = TimeUnit.MINUTES)
class EmrNotebookExecutionNightlyIntegrationTest {
/** Clusters run their steps, and notebook executions their notebooks, in containers. */
public static final class Profile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.services.emr.runner-mode", "docker");
}
}
private static final String ACCOUNT = "000000000000";
private static final ObjectMapper JSON = new ObjectMapper();
// As an earlier run wrote it: the parameters it was given are in a cell of their own.
private static final String NOTEBOOK = """
{"nbformat": 4, "nbformat_minor": 5, "metadata": {}, "cells": [
{"cell_type": "markdown", "metadata": {}, "source": ["# A count"]},
{"cell_type": "code", "metadata": {"tags": ["parameters"]}, "execution_count": null, "outputs": [],
"source": ["limit = 3\\n"]},
{"cell_type": "code", "metadata": {"tags": ["injected-parameters"]}, "execution_count": 1, "outputs": [],
"source": ["limit = 99\\n"]},
{"cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [],
"source": ["print('rows', spark.range(limit).count())\\n"]},
{"cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [],
"source": ["limit * 2"]},
{"cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [],
"source": ["%%sql\\n", "SELECT 41 + 1 AS answer"]},
{"cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [],
"source": ["%matplotlib inline\\n", "label = 'rows: %d' % limit\\n", "label"]},
{"cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [],
"source": ["text = '''\\n", "%d left\\n", "''' % limit\\n", "text.strip()"]}]}
""";
// As an earlier run wrote it: the cell past the one that raises has that run's output.
private static final String FAILING = """
{"nbformat": 4, "nbformat_minor": 5, "metadata": {}, "cells": [
{"cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [],
"source": ["print('before')\\n"]},
{"cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [],
"source": ["spark.sql('SELECT * FROM no_such_table').collect()"]},
{"cell_type": "code", "metadata": {}, "execution_count": 7, "outputs": [{"output_type": "display_data",
"metadata": {}, "data": {"image/png": "iVBORw0KGgo="}}],
"source": ["print('never')"]}]}
""";
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Inject
EmrService emrService;
@BeforeAll
static void configure() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void aNotebookRunsOnItsClusterAndItsRunIsWrittenToS3() throws Exception {
// Enabled, the check needs Docker: without a daemon it fails rather than pass having run nothing.
assertTrue(DockerAvailability.isAvailable(), "the nightly check needs a Docker daemon");
S3Client s3 = AwsTestClients.create(S3Client.builder().forcePathStyle(true), ACCOUNT, Region.US_EAST_1);
cleanup.register(s3::close);
String bucket = "notebooks-" + UUID.randomUUID().toString().substring(0, 8);
s3.createBucket(request -> request.bucket(bucket));
cleanup.register(() -> S3TestClients.deleteBucket(s3, bucket));
s3.putObject(request -> request.bucket(bucket).key("team/count.ipynb"), RequestBody.fromString(NOTEBOOK));
s3.putObject(request -> request.bucket(bucket).key("team/failing.ipynb"), RequestBody.fromString(FAILING));
String clusterId = emr("RunJobFlow", "{\"Name\":\"notebooks\",\"ReleaseLabel\":\"emr-7.5.0\","
+ "\"Applications\":[{\"Name\":\"Hadoop\"},{\"Name\":\"Spark\"},{\"Name\":\"Livy\"},"
+ "{\"Name\":\"JupyterEnterpriseGateway\"}],"
+ "\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true,\"InstanceGroups\":[{\"Name\":\"primary\","
+ "\"InstanceRole\":\"MASTER\",\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":1}]}}")
.then().statusCode(200).extract().jsonPath().getString("JobFlowId");
cleanup.register(() -> terminateClusterAndAwaitCleanup(clusterId, emrService));
await(() -> emr("DescribeCluster", "{\"ClusterId\":\"" + clusterId + "\"}").jsonPath()
.getString("Cluster.Status.State"), "WAITING", List.of("TERMINATED"), Duration.ofMinutes(5));
String counting = start(clusterId, bucket, "team/count.ipynb", "{\"limit\": 5}");
awaitExecution(counting, "FINISHED", Duration.ofMinutes(25));
String uri = emr("DescribeNotebookExecution", "{\"NotebookExecutionId\":\"" + counting + "\"}").jsonPath()
.getString("NotebookExecution.OutputNotebookURI");
assertEquals("s3://" + bucket + "/runs/" + counting + "/count.html", uri);
JsonNode run = JSON.readTree(s3.getObjectAsBytes(request -> request.bucket(bucket)
.key("runs/" + counting + "/count.ipynb")).asUtf8String());
JsonNode cells = run.path("cells");
assertEquals(8, cells.size(), run.toString());
assertEquals("injected-parameters", cells.path(2).path("metadata").path("tags").path(0).asText(),
run.toString());
assertEquals("limit = 5\n", cells.path(2).path("source").path(1).asText(), run.toString());
assertEquals("rows 5\n", cells.path(3).path("outputs").path(0).path("text").path(0).asText(), run.toString());
assertEquals("10", result(cells.path(4)), run.toString());
String answer = String.join("", JSON.convertValue(cells.path(5).path("outputs").path(0).path("text"),
String[].class));
assertTrue(answer.contains("answer") && answer.contains("42"), run.toString());
assertEquals("'rows: 5'", result(cells.path(6)), run.toString());
assertEquals("'5 left'", result(cells.path(7)), run.toString());
String page = s3.getObjectAsBytes(request -> request.bucket(bucket).key("runs/" + counting + "/count.html"))
.asUtf8String();
assertTrue(page.contains("rows 5"), page);
String failing = start(clusterId, bucket, "team/failing.ipynb", null);
awaitExecution(failing, "FAILED", Duration.ofMinutes(10));
JsonNode failed = JSON.readTree(s3.getObjectAsBytes(request -> request.bucket(bucket)
.key("runs/" + failing + "/failing.ipynb")).asUtf8String());
assertEquals("error", failed.path("cells").path(1).path("outputs").path(0).path("output_type").asText(),
failed.toString());
assertTrue(failed.path("cells").path(2).path("outputs").isEmpty(), failed.toString());
assertTrue(failed.path("cells").path(2).path("execution_count").isNull(), failed.toString());
assertTrue(s3.getObjectAsBytes(request -> request.bucket(bucket).key("runs/" + failing + "/failing.html"))
.asUtf8String().contains("no_such_table"));
String misnamed = start(clusterId, bucket, "team/count.ipynb", "{\"two words\": 1}");
awaitExecution(misnamed, "FAILED", Duration.ofMinutes(10));
assertEquals(String.format(EmrNotebookExecutionService.RUN_FAILED, clusterId, 1),
emr("DescribeNotebookExecution", "{\"NotebookExecutionId\":\"" + misnamed + "\"}").jsonPath()
.getString("NotebookExecution.LastStateChangeReason"));
}
// A cell's last expression's value, as the notebook as run holds it.
private static String result(JsonNode cell) {
return cell.path("outputs").path(0).path("data").path("text/plain").path(0).asText();
}
private static String start(String clusterId, String bucket, String key, String params) {
return emr("StartNotebookExecution", "{\"ExecutionEngine\":{\"Id\":\"" + clusterId + "\"},"
+ "\"ServiceRole\":\"EMR_Notebooks_DefaultRole\","
+ "\"NotebookS3Location\":{\"Bucket\":\"" + bucket + "\",\"Key\":\"" + key + "\"},"
+ "\"OutputNotebookS3Location\":{\"Bucket\":\"" + bucket + "\",\"Key\":\"runs\"},"
+ "\"OutputNotebookFormat\":\"HTML\""
+ (params != null ? ",\"NotebookParams\":" + JSON.valueToTree(params) : "") + "}")
.then().statusCode(200).extract().jsonPath().getString("NotebookExecutionId");
}
private static void awaitExecution(String executionId, String status, Duration limit) {
await(() -> emr("DescribeNotebookExecution", "{\"NotebookExecutionId\":\"" + executionId + "\"}")
.jsonPath().getString("NotebookExecution.Status"), status,
List.of("FINISHED", "FAILED", "STOPPED"), limit);
}
private static void await(Supplier<String> read, String state, List<String> ends, Duration limit) {
long deadline = System.nanoTime() + limit.toNanos();
while (true) {
String now = read.get();
if (state.equals(now)) {
return;
}
if (ends.contains(now) || System.nanoTime() - deadline > 0) {
fail("reached " + now + ", not " + state);
}
LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(2));
}
}
}
@@ -0,0 +1,246 @@
package io.floci.aws.services.emr;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.services.emr.model.EmrCluster;
import io.floci.aws.services.emr.model.EmrNotebookExecution;
import io.floci.aws.services.emrserverless.SparkJobRunner;
import io.floci.aws.services.iam.IamService;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import static io.floci.aws.services.emr.EmrServiceFixture.ACCOUNT;
import static io.floci.aws.services.emr.EmrServiceFixture.REGION;
import static io.floci.aws.services.emr.EmrServiceFixture.cluster;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
/**
* Notebook executions in the docker runner mode, each running its notebook on its cluster as a step's command runs:
* what runs, where the notebook as run goes, and the execution's statuses as the run goes, with a runner that stands in
* for Docker and the cluster's threads run by hand.
*/
class EmrNotebookExecutionRunTest {
private static final String NOTEBOOK_APPS = "[{\"Name\":\"Hadoop\"},{\"Name\":\"Spark\"},{\"Name\":\"Livy\"},"
+ "{\"Name\":\"JupyterEnterpriseGateway\"}]";
private final RecordingRunner runner = new RecordingRunner();
private final EmrServiceFixture fixture = EmrServiceFixture.docker(runner, mock(IamService.class));
private final AccountAwareStorageBackend<EmrNotebookExecution> store = AccountAwareStorageBackend.inMemory(ACCOUNT);
private final EmrNotebookExecutionService executions = service();
private EmrNotebookExecutionService service() {
return new EmrNotebookExecutionService(store, fixture.service, new RegionResolver(REGION, ACCOUNT),
fixture.clock, Duration.ofMinutes(10));
}
@Test
void aNotebookRunsOnItsClusterAndItsRunAsWrittenUnderTheOutputPrefix() {
String clusterId = notebookCluster();
EmrNotebookExecution request = request(clusterId);
request.setNotebookS3Bucket("notebooks");
request.setNotebookS3Key("team/analysis.ipynb");
request.setOutputNotebookS3Bucket("results");
request.setOutputNotebookS3Key("runs/");
request.setOutputNotebookFormat("HTML");
request.setNotebookParams("{\"day\":\"2026-11-17\"}");
request.setEnvironmentVariables(Map.of("KERNEL_EXTRA_SPARK_OPTS", "--conf spark.executor.instances=1"));
EmrNotebookExecution started = executions.start(request);
String id = started.getId();
assertEquals("START_PENDING", started.getStatus());
assertEquals("s3://results/runs/" + id + "/analysis.html", started.getOutputNotebookUri());
fixture.runStepThread();
EmrNotebookExecution finished = executions.describe(id);
assertEquals("FINISHED", finished.getStatus());
assertEquals("Execution is finished for cluster " + clusterId + ".", finished.getLastStateChangeReason());
SparkJobRunner.Job job = runner.jobs.get(0);
assertEquals(id, job.runId());
assertEquals(EmrNotebookRunner.command("s3://notebooks/team/analysis.ipynb", "s3://results/runs/" + id,
"analysis", "{\"day\":\"2026-11-17\"}"), job.command());
assertEquals(EmrNotebookRunner.PROGRAM, job.environment().get(EmrNotebookRunner.PROGRAM_VARIABLE));
assertEquals("--conf spark.executor.instances=1", job.environment().get("KERNEL_EXTRA_SPARK_OPTS"));
// On the cluster's storage, its HDFS and YARN running, as a step's command is.
assertNotNull(job.storage());
}
@Test
void aCellThatRaisesFailsTheExecutionAndItsRunGoesBesideTheNotebookWithNoPrefix() {
runner.outcome = SparkJobRunner.Outcome.exitedWith(EmrNotebookRunner.CELL_RAISED);
String clusterId = notebookCluster();
EmrNotebookExecution request = request(clusterId);
request.setNotebookS3Bucket("notebooks");
request.setNotebookS3Key("team/analysis.ipynb");
String id = executions.start(request).getId();
fixture.runStepThread();
EmrNotebookExecution failed = executions.describe(id);
assertEquals("FAILED", failed.getStatus());
assertEquals(String.format(EmrNotebookExecutionService.CELL_FAILED, clusterId),
failed.getLastStateChangeReason());
assertEquals("s3://notebooks/team/" + id + "/analysis.ipynb", failed.getOutputNotebookUri());
}
@Test
void aRunThatFailsOtherwiseSaysItsExitCodeRatherThanACellsError() {
runner.outcome = SparkJobRunner.Outcome.exitedWith(1);
String clusterId = notebookCluster();
String id = executions.start(notebookRequest(clusterId)).getId();
fixture.runStepThread();
assertEquals(String.format(EmrNotebookExecutionService.RUN_FAILED, clusterId, 1),
executions.describe(id).getLastStateChangeReason());
}
@Test
void aRunWhoseClusterShutsDownBeforeItStartsRunsNothing() {
String clusterId = notebookCluster();
String id = executions.start(notebookRequest(clusterId)).getId();
fixture.service.terminateJobFlows(List.of(clusterId));
fixture.runStepThread();
assertTrue(runner.jobs.isEmpty(), "the notebook of a shut-down cluster started");
EmrNotebookExecution failed = executions.describe(id);
assertEquals("FAILED", failed.getStatus());
assertEquals("Execution failed for cluster " + clusterId + ", as the cluster was terminated.",
failed.getLastStateChangeReason());
}
@Test
void aRunHandedToItsThreadBeforeATeardownRunsNothingAfterIt() {
String clusterId = notebookCluster();
String id = executions.start(notebookRequest(clusterId)).getId();
// A reset's teardown, then its wipe, before the thread starts.
fixture.service.stopManagedContainers();
fixture.service.beforeReset();
fixture.runStepThread();
assertTrue(runner.jobs.isEmpty(), "a notebook started after the teardown");
assertEquals("FAILED", executions.describe(id).getStatus());
}
@Test
void aRunNoThreadTakesFailsAtOnceAndHoldsNothingOfItsCluster() {
String clusterId = notebookCluster();
fixture.threadsRefused = true;
EmrNotebookExecution started = executions.start(notebookRequest(clusterId));
assertEquals("FAILED", started.getStatus());
assertTrue(started.getLastStateChangeReason().contains("The pool takes no more threads"),
started.getLastStateChangeReason());
assertEquals("FAILED", executions.describe(started.getId()).getStatus());
// Nothing of the run is left to hold the cluster's storage once it ends.
fixture.threadsRefused = false;
fixture.service.terminateJobFlows(List.of(clusterId));
while (fixture.stepThreadsWaiting() > 0) {
fixture.runStepThread();
}
assertTrue(fixture.clusterStorage.removed.contains(clusterId), fixture.clusterStorage.removed.toString());
}
@Test
void anExecutionOfAnEditorsNotebookAloneFailsAsFlociKeepsNoEditorsLocation() {
String clusterId = notebookCluster();
EmrNotebookExecution started = executions.start(request(clusterId));
assertEquals("FAILED", started.getStatus());
assertEquals(String.format(EmrNotebookExecutionService.NO_NOTEBOOK, clusterId),
started.getLastStateChangeReason());
assertEquals(0, fixture.stepThreadsWaiting());
}
@Test
void aStoppedExecutionIsStoppingUntilItsRunHasStopped() {
String clusterId = notebookCluster();
EmrNotebookExecution request = request(clusterId);
request.setNotebookS3Bucket("notebooks");
request.setNotebookS3Key("analysis.ipynb");
String id = executions.start(request).getId();
executions.stop(id);
assertEquals("STOPPING", executions.describe(id).getStatus());
fixture.runStepThread();
EmrNotebookExecution stopped = executions.describe(id);
assertEquals("STOPPED", stopped.getStatus());
assertEquals("Execution is stopped for cluster " + clusterId + ".", stopped.getLastStateChangeReason());
assertTrue(runner.jobs.isEmpty(), "a stopped execution's notebook did not start");
}
@Test
void anExecutionNoThreadRunsAnyMoreWasInterruptedByARestart() {
String clusterId = notebookCluster();
EmrNotebookExecution request = request(clusterId);
request.setNotebookS3Bucket("notebooks");
request.setNotebookS3Key("analysis.ipynb");
String id = executions.start(request).getId();
// A new process: the stored execution is there, but no thread of it runs the notebook.
EmrNotebookExecution after = service().describe(id);
assertEquals("FAILED", after.getStatus());
assertEquals(EmrNotebookExecutionService.INTERRUPTED, after.getLastStateChangeReason());
}
private String notebookCluster() {
EmrCluster cluster = cluster("notebooks", true);
cluster.setReleaseLabel("emr-7.5.0");
cluster.setApplications(NOTEBOOK_APPS);
return fixture.service.runJobFlow(cluster, REGION).getId();
}
private static EmrNotebookExecution notebookRequest(String clusterId) {
EmrNotebookExecution request = request(clusterId);
request.setNotebookS3Bucket("notebooks");
request.setNotebookS3Key("analysis.ipynb");
return request;
}
private static EmrNotebookExecution request(String clusterId) {
EmrNotebookExecution request = new EmrNotebookExecution();
request.setEngineId(clusterId);
request.setServiceRole("EMR_Notebooks_DefaultRole");
request.setEditorId("e-ABCDEFGHIJK1234567890ABCD");
request.setRelativePath("analysis.ipynb");
request.setName("run");
return request;
}
/** Runs each command at once, as the Docker runner would, ending as {@code outcome} says. */
private static final class RecordingRunner implements SparkJobRunner {
final List<Job> jobs = new CopyOnWriteArrayList<>();
volatile Outcome outcome = Outcome.exitedWith(0);
@Override
public Outcome run(Job job, Progress progress) {
if (progress.cancelled()) {
return Outcome.halted();
}
jobs.add(job);
progress.started();
return outcome;
}
@Override
public void stop(String runId) {
}
@Override
public void removeLeftoverDrivers(String service) {
}
}
}
@@ -24,6 +24,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.RejectedExecutionException;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import java.util.function.Function;
@@ -232,6 +233,8 @@ final class EmrServiceFixture {
private final List<Runnable> deliveries = new ArrayList<>();
// The docker runner mode's step threads, not yet run; a session server's thread may add one too.
private final List<Runnable> stepThreads = new CopyOnWriteArrayList<>();
// Whether the pool refuses what it is handed, as a pool shut down does.
volatile boolean threadsRefused;
private boolean waking;
final InMemoryStorageFactory storage;
private final SparkJobRunner runner;
@@ -314,9 +317,9 @@ final class EmrServiceFixture {
};
service = sessionProbe == null
? new EmrService(storage, config(false), regionResolver, publisher, clock, recorded, runner, bootstrap,
clusterStorage, releaseImages, stepThreads::add, iam)
clusterStorage, releaseImages, this::handToThread, iam)
: new EmrService(storage, config(false), regionResolver, publisher, clock, recorded, runner, bootstrap,
clusterStorage, releaseImages, stepThreads::add, iam,
clusterStorage, releaseImages, this::handToThread, iam,
new SparkConnectServers(runner, task -> Thread.ofPlatform().daemon().start(task), null,
sessionProbe, clock));
}
@@ -338,7 +341,7 @@ final class EmrServiceFixture {
*/
EmrService restartReconciling(SparkJobRunner runner, EmrService.Wakeups wakeups) {
return new EmrService(storage, config(true), new RegionResolver(REGION, ACCOUNT), publisher, clock, wakeups,
runner, bootstrap, clusterStorage, releaseImages, stepThreads::add, iam);
runner, bootstrap, clusterStorage, releaseImages, this::handToThread, iam);
}
/**
@@ -349,7 +352,7 @@ final class EmrServiceFixture {
EmulatorConfig config = config(false);
when(config.services().emr().hiveImageTemplate()).thenReturn(Optional.of(hiveImageTemplate));
return new EmrService(storage, config, new RegionResolver(REGION, ACCOUNT), publisher, clock,
mock(EmrService.Wakeups.class), runner, bootstrap, clusterStorage, releaseImages, stepThreads::add,
mock(EmrService.Wakeups.class), runner, bootstrap, clusterStorage, releaseImages, this::handToThread,
iam);
}
@@ -361,7 +364,7 @@ final class EmrServiceFixture {
EmulatorConfig config = config(false);
when(config.services().emr().pig().enabled()).thenReturn(true);
return new EmrService(storage, config, new RegionResolver(REGION, ACCOUNT), publisher, clock,
mock(EmrService.Wakeups.class), runner, bootstrap, clusterStorage, releaseImages, stepThreads::add,
mock(EmrService.Wakeups.class), runner, bootstrap, clusterStorage, releaseImages, this::handToThread,
iam);
}
@@ -382,6 +385,13 @@ final class EmrServiceFixture {
return config;
}
private void handToThread(Runnable task) {
if (threadsRefused) {
throw new RejectedExecutionException("The pool takes no more threads");
}
stepThreads.add(task);
}
/** Runs the oldest step thread not yet run, as the docker runner mode's pool would. */
void runStepThread() {
stepThreads.remove(0).run();