feat(emr-containers): run the Scala kernel on a managed endpoint's gateway (#9276)

Interactive endpoints "support the following kernels: Python 3, PySpark
on Kubernetes, Apache Spark with Scala" (EMR on EKS Development Guide,
"Overview of interactive endpoints"). A Floci endpoint's gateway had no
Scala kernel.

- The gateway program writes a spark-scala-kubernetes kernel spec,
  "Apache Spark with Scala", a name of Floci's beside the guide's
  spark-python-kubernetes, as the guide gives the Scala kernel none. It
  runs the image's Apache Toree, beside Jupyter Enterprise Gateway's
  Scala launcher, under spark-submit as Toree's own kernel spec does:
  org.apache.toree.Main with the connection file as its profile, after
  KERNEL_EXTRA_SPARK_OPTS. Its spark is a Spark session in Spark's
  local mode on Floci's S3, as the PySpark kernel's is.
- The docs move the Scala kernel out of "Not emulated yet", and the
  endpoint role every kernel runs with out of it too: "All kernels and
  users that connect to the interactive endpoint utilize the role that
  you specified when you created the endpoint".
- The nightly check lists the new kernel spec and counts an S3 file's
  lines in the Scala kernel. Kernel start, connection and deletion
  become helpers. The method's timeout and the docker-runner group's
  budget grow by its four minutes.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-23 11:20:15 -04:00
1 parent 39fbc98efe
commit 5c7ab956f9
4 files changed
+97 -60

No files matched your search

+3 -3
View File
@@ -34,8 +34,8 @@ jobs:
# EmrDockerRunnerNightlyIntegrationTest's eleven two-minute tests and two-minute setup,
# EmrClusterShrinkNightlyIntegrationTest's sixteen-minute method and two-minute setup, and
# EmrContainersSparkNightlyIntegrationTest's three six-minute methods, eleven-minute method, two-minute setup before
# each and 21-minute image pull, and EmrContainersGatewayNightlyIntegrationTest's sixteen-minute and seven-minute
# methods and 21-minute image pull, 144 minutes. A check added, or a bound raised, raises its group's timeout with
# each and 21-minute image pull, and EmrContainersGatewayNightlyIntegrationTest's twenty-minute and seven-minute
# methods and 21-minute image pull, 148 minutes. A check added, or a bound raised, raises its group's timeout with
# it, so a slow check fails with its own message.
strategy:
fail-fast: false
@@ -44,7 +44,7 @@ jobs:
- group: standard
timeout: 359
- group: docker-runner
timeout: 164
timeout: 168
timeout-minutes: ${{ matrix.timeout }}
# 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.
+19 -16
View File
@@ -232,18 +232,22 @@ remote kernel lifecycle management capability that interactive clients need" (EM
<token>` header, which is what a Jupyter client sends. Any other request gets that gateway's 401
`{"reason": "Unauthorized", "message": ""}`, an expired token's with a message saying so, and one to an endpoint
that is not `ACTIVE` gets 503.
* **Kernels**: the image's `python3` ("Python 3"), and `spark-python-kubernetes` ("PySpark on Kubernetes", the
name the guide's `jupyter-kernel-overrides` example gives it), whose `spark` and `sc` are a Spark session in
Spark's local mode, where EMR on EKS runs each kernel and its executors in pods of their own. It runs on the image's
Python, with `spark.pyspark.virtualenv.enabled` set to `false`: the image's `spark-defaults.conf` turns the
virtualenv on, and `spark-submit` makes one on YARN and Kubernetes alone. As Jupyter Enterprise
Gateway does, a kernel gets the `KERNEL_` variables of its start request's `env`, which a Jupyter client sends from
its own environment; `KERNEL_EXTRA_SPARK_OPTS`, "additional Spark configurations for the Spark kernels", goes to
the PySpark kernel's `spark-submit`. Listing the kernels (`GET /api/kernels`) answers with those started with the
request's session token alone, as the guide's "Monitoring interactive endpoints" has ListKernels "list the kernels
that have been previously started using the same session token", whether the kernels API or the sessions API
(`POST /api/sessions`) started them, and listing the sessions (`GET /api/sessions`) answers with those holding such
kernels; any of the endpoint's tokens reaches a kernel or a session by its id.
* **Kernels**: the image's `python3` ("Python 3"); `spark-python-kubernetes` ("PySpark on Kubernetes", the name the
guide's `jupyter-kernel-overrides` example gives it); and `spark-scala-kubernetes` ("Apache Spark with Scala", a
name of Floci's beside it, as the guide gives the Scala kernel none), which runs the image's Apache Toree under
`spark-submit`, as Toree's own kernel spec does. The Spark kernels' `spark` and `sc` are a Spark session in Spark's
local mode, where EMR on EKS runs each kernel and its executors in pods of their own. The PySpark kernel runs on
the image's Python, with `spark.pyspark.virtualenv.enabled` set to `false`: the image's `spark-defaults.conf` turns
the virtualenv on, and `spark-submit` makes one on YARN and Kubernetes alone. Every kernel runs with the endpoint's
execution role, as "All kernels and users that connect to the interactive endpoint utilize the role that you
specified when you created the endpoint", whichever role its session token was asked for with. As Jupyter
Enterprise Gateway does, a kernel gets the `KERNEL_` variables of its start request's `env`, which a Jupyter client
sends from its own environment; `KERNEL_EXTRA_SPARK_OPTS`, "additional Spark configurations for the Spark kernels",
goes to the Spark kernels' `spark-submit`. Listing the kernels (`GET /api/kernels`) answers with those started with
the request's session token alone, as the guide's "Monitoring interactive endpoints" has ListKernels "list the
kernels that have been previously started using the same session token", whether the kernels API or the sessions
API (`POST /api/sessions`) started them, and listing the sessions (`GET /api/sessions`) answers with those holding
such kernels; any of the endpoint's tokens reaches a kernel or a session by its id.
* **`%%configure`**: the PySpark kernel loads the image's own `%%configure` magic, with which "you can adjust the
Spark configuration associated with a PySpark session" ("Modifying PySpark session parameters"). The magic turns
its cell's settings into `KERNEL_EXTRA_SPARK_OPTS` and posts them, signed with an AES key of its kernel's own, to
@@ -258,7 +262,6 @@ remote kernel lifecycle management capability that interactive clients need" (EM
`RemoteMappingKernelManager.cull_interval`, "The interval in seconds (integer) on which to check for idle kernels
that exceed the cull timeout value." As jupyter_server's culler does by default, a kernel with a client connected
is not culled. Other `jeg-config` properties go nowhere.
* **Not emulated yet**: the "Apache Spark with Scala" kernel and `jupyter-kernel-overrides` images. A browser's CORS
preflight (`OPTIONS`), which Jupyter Enterprise Gateway takes without a token, needs one here. Every kernel runs
with the endpoint's execution role, whichever role its session token was asked for with. `certificateArn` is
kept, and the `serverUrl` is plain HTTP on Floci's port.
* **Not emulated yet**: `jupyter-kernel-overrides` images. A browser's CORS preflight (`OPTIONS`), which Jupyter
Enterprise Gateway takes without a token, needs one here. `certificateArn` is kept, and the `serverUrl` is plain
HTTP on Floci's port.
@@ -20,14 +20,16 @@ import java.util.Map;
/**
* What runs a managed endpoint's Jupyter Enterprise Gateway in the docker runner mode. "The interactive endpoint is
* backed by a Jupyter Enterprise Gateway that provides the remote kernel lifecycle management capability that
* interactive clients need", with the kernels "Python 3" and "PySpark on Kubernetes" (EMR on EKS Development Guide,
* "Overview of interactive endpoints"), which run in the release's {@code notebook-spark} image ("the base image URI
* in your Docker file must use notebook-spark in place of spark", "Custom kernel image with interactive endpoint").
* That image holds jupyter_server and ipykernel but no Enterprise Gateway, so a Python program of Floci's own serves
* the gateway's kernels API on jupyter_server in a container of it, its kernels in the same container: the image's
* {@code python3} kernel, and a {@code spark-python-kubernetes} one, the name the guide's
* {@code jupyter-kernel-overrides} example gives the PySpark kernel, whose {@code spark} and {@code sc} are a Spark
* session in Spark's local mode, on Floci's S3, with the endpoint's execution role's credentials.
* interactive clients need", with the kernels "Python 3", "PySpark on Kubernetes" and "Apache Spark with Scala" (EMR
* on EKS Development Guide, "Overview of interactive endpoints"), which run in the release's {@code notebook-spark}
* image ("the base image URI in your Docker file must use notebook-spark in place of spark", "Custom kernel image with
* interactive endpoint"). That image holds jupyter_server and ipykernel but no Enterprise Gateway, so a Python
* program of Floci's own serves the gateway's kernels API on jupyter_server in a container of it, its kernels in the
* same container: the image's {@code python3} kernel; a {@code spark-python-kubernetes} one, the name the guide's
* {@code jupyter-kernel-overrides} example gives the PySpark kernel; and a {@code spark-scala-kubernetes} one, a name
* of Floci's beside it, as the guide gives the Scala kernel none, which runs the image's Apache Toree, beside Jupyter
* Enterprise Gateway's Scala launcher. The Spark kernels' {@code spark} and {@code sc} are a Spark session in Spark's
* local mode, on Floci's S3, with the endpoint's execution role's credentials.
*
* <p>As Jupyter Enterprise Gateway does, a kernel gets the {@code KERNEL_} variables of the {@code env} its start
* request carries, as a Jupyter client sends those of its own environment: {@code KERNEL_EXTRA_SPARK_OPTS}, "additional
@@ -115,6 +117,8 @@ final class EmrContainersGateways {
SESSION_HEADER = "@SESSION_HEADER@"
# The image's %%configure magic, beside Jupyter Enterprise Gateway's kernel launchers.
MAGICS = "/usr/local/bin/kernel-launchers/python/scripts"
# The image's Apache Toree, which Jupyter Enterprise Gateway's Scala launcher runs.
TOREE = "/usr/local/bin/kernel-launchers/scala/lib/toree-assembly-*.jar"
# Where the magic posts its cell's settings when no ENDPOINT_IP names its gateway: its own host's port.
CONFIGURE_PORT = 18888
# The magic's signature of a post: the SHA-256 of its body, encrypted with its kernel's AES key.
@@ -155,6 +159,15 @@ final class EmrContainersGateways {
"{connection_file}"],
"env": {"PYTHONPATH": MAGICS},
}))
# As Toree's own kernel spec starts it, its connection file its profile.
write(HOME + "/kernels/spark-scala-kubernetes/kernel.json", json.dumps({
"display_name": "Apache Spark with Scala",
"language": "scala",
"argv": ["/bin/bash", "-c",
'exec "$SPARK_HOME/bin/spark-submit" $KERNEL_EXTRA_SPARK_OPTS --class org.apache.toree.Main '
+ TOREE + ' --profile "$0"',
"{connection_file}"],
}))
# Whether the request being served carries the session token the kernel was started with.
@@ -349,6 +362,7 @@ final class EmrContainersGateways {
"--ServerApp.allow_remote_access=True",
"--KernelSpecManager.allowed_kernelspecs=python3",
"--KernelSpecManager.allowed_kernelspecs=spark-python-kubernetes",
"--KernelSpecManager.allowed_kernelspecs=spark-scala-kubernetes",
] + sys.argv[1:], kernel_manager_class=RemoteMappingKernelManager))
""".replace("@HOME@", HOME).replace("@PORT@", String.valueOf(PORT))
.replace("@PROGRAM_VARIABLE@", PROGRAM_VARIABLE).replace("@SESSION_HEADER@", SESSION_HEADER);
@@ -56,7 +56,8 @@ import static org.junit.jupiter.api.Assertions.fail;
* {@code serverUrl} with a session token, starts a PySpark kernel there, and a session with a kernel of its own, which
* the kernels and sessions listings show that token alone, and runs code on Floci's S3 over the PySpark kernel's
* WebSocket, as the guide's "Example: Deploy a JupyterLab notebook" does through {@code JUPYTER_GATEWAY_URL}, then
* changes its Spark session's settings with {@code %%configure}, as "Modifying PySpark session parameters" does. An
* changes its Spark session's settings with {@code %%configure}, as "Modifying PySpark session parameters" does,
* and runs code on Floci's S3 in the "Apache Spark with Scala" kernel too. An
* endpoint whose {@code jeg-config} sets a short idle timeout culls a kernel left idle.
*
* <p>A nightly check: the release's notebook image is about 6 GB.
@@ -101,11 +102,11 @@ class EmrContainersGatewayNightlyIntegrationTest {
docker.pullImageCmd(NOTEBOOK_IMAGE).exec(new PullImageResultCallback()).awaitCompletion(20, TimeUnit.MINUTES);
}
// The endpoint's gateway answers within its five minutes, the kernel's WebSocket opens within its two, once its
// Spark session is up, and each of its four cells answers within its two: fifteen minutes, and one for the
// requests between. The Nightly checks' docker-runner group counts it.
// The endpoint's gateway answers within its five minutes, each kernel's WebSocket opens within its two, once the
// kernel is up, and each of the five cells answers within its two: nineteen minutes, and one for the requests
// between. The Nightly checks' docker-runner group counts it.
@Test
@Timeout(value = 16, unit = TimeUnit.MINUTES)
@Timeout(value = 20, unit = TimeUnit.MINUTES)
void pysparkKernelOnTheEndpointsGatewayRunsCodeOnFlocisS3() throws Exception {
S3Client s3 = AwsTestClients.create(S3Client.builder().forcePathStyle(true), ACCOUNT, Region.US_EAST_1);
cleanup.register(s3::close);
@@ -124,17 +125,15 @@ class EmrContainersGatewayNightlyIntegrationTest {
HttpResponse<String> specs = http.send(HttpRequest.newBuilder(URI.create(gateway + "/api/kernelspecs"))
.header("Authorization", "token " + token).build(), HttpResponse.BodyHandlers.ofString());
assertEquals(200, specs.statusCode(), specs.body());
assertTrue(JSON.readTree(specs.body()).path("kernelspecs").has("spark-python-kubernetes"), specs.body());
JsonNode kernelspecs = JSON.readTree(specs.body()).path("kernelspecs");
assertTrue(kernelspecs.has("spark-python-kubernetes"), specs.body());
assertEquals("Apache Spark with Scala",
kernelspecs.at("/spark-scala-kubernetes/spec/display_name").textValue());
// As a Jupyter client sends its KERNEL_ variables.
HttpResponse<String> started = http.send(HttpRequest.newBuilder(URI.create(gateway + "/api/kernels"))
.header("Authorization", "token " + token)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("""
{"name": "spark-python-kubernetes",
"env": {"KERNEL_EXTRA_SPARK_OPTS": "--conf spark.app.name=from-kernel-env"}}
""")).build(), HttpResponse.BodyHandlers.ofString());
assertEquals(201, started.statusCode(), started.body());
String kernelId = JSON.readTree(started.body()).path("id").textValue();
String kernelId = startKernel(http, gateway, token, """
{"name": "spark-python-kubernetes",
"env": {"KERNEL_EXTRA_SPARK_OPTS": "--conf spark.app.name=from-kernel-env"}}
""");
// ListKernels lists the kernels started with the same session token, through the sessions API too, and the
// sessions listing the sessions holding them.
HttpResponse<String> created = http.send(HttpRequest.newBuilder(URI.create(gateway + "/api/sessions"))
@@ -151,15 +150,10 @@ class EmrContainersGatewayNightlyIntegrationTest {
String another = sessionToken(virtualClusterId, endpointId);
assertEquals(List.of(), ids(http, gateway + "/api/kernels", another), "another session token of the endpoint");
assertEquals(List.of(), ids(http, gateway + "/api/sessions", another), "another session token of the endpoint");
assertEquals(204, http.send(HttpRequest.newBuilder(URI.create(gateway + "/api/sessions/"
+ notebook.path("id").textValue())).header("Authorization", "token " + token).DELETE().build(),
HttpResponse.BodyHandlers.discarding()).statusCode());
delete(http, gateway + "/api/sessions/" + notebook.path("id").textValue(), token);
Messages messages = new Messages();
WebSocket socket = http.newWebSocketBuilder().header("Authorization", "token " + token)
.buildAsync(URI.create(gateway.replaceFirst("^http", "ws") + "/api/kernels/" + kernelId
+ "/channels"), messages)
.get(HANDSHAKE_TIMEOUT.toSeconds(), TimeUnit.SECONDS);
WebSocket socket = connect(http, gateway, token, kernelId, messages);
String session = UUID.randomUUID().toString();
assertEquals("3", execute(socket, messages, session,
"spark.read.text(\"s3://" + bucket + "/lines.txt\").count()"));
@@ -173,9 +167,17 @@ class EmrContainersGatewayNightlyIntegrationTest {
"spark.conf.get(\"spark.app.name\"), spark.conf.get(\"spark.executor.memory\")"));
assertEquals(List.of(kernelId), ids(http, gateway + "/api/kernels", token));
socket.sendClose(WebSocket.NORMAL_CLOSURE, "done").get(10, TimeUnit.SECONDS);
assertEquals(204, http.send(HttpRequest.newBuilder(URI.create(gateway + "/api/kernels/" + kernelId))
.header("Authorization", "token " + token).DELETE().build(),
HttpResponse.BodyHandlers.discarding()).statusCode());
delete(http, gateway + "/api/kernels/" + kernelId, token);
// The Scala kernel's Toree gives its cell a Spark session on Floci's S3 too.
String scalaId = startKernel(http, gateway, token, "{\"name\": \"spark-scala-kubernetes\"}");
Messages scalaMessages = new Messages();
WebSocket scala = connect(http, gateway, token, scalaId, scalaMessages);
String count = execute(scala, scalaMessages, session,
"spark.read.textFile(\"s3://" + bucket + "/lines.txt\").count()");
assertTrue(count.matches("(res\\d+: Long = )?3"), count);
scala.sendClose(WebSocket.NORMAL_CLOSURE, "done").get(10, TimeUnit.SECONDS);
delete(http, gateway + "/api/kernels/" + scalaId, token);
}
// The endpoint's gateway answers within its five minutes, and the kernel goes within its one: six minutes, and one
@@ -192,19 +194,37 @@ class EmrContainersGatewayNightlyIntegrationTest {
String gateway = gateway(virtualClusterId, endpointId);
String token = sessionToken(virtualClusterId, endpointId);
HttpClient http = HttpClient.newHttpClient();
HttpResponse<String> started = http.send(HttpRequest.newBuilder(URI.create(gateway + "/api/kernels"))
.header("Authorization", "token " + token)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("{\"name\": \"python3\"}")).build(),
HttpResponse.BodyHandlers.ofString());
assertEquals(201, started.statusCode(), started.body());
assertEquals(List.of(JSON.readTree(started.body()).path("id").textValue()),
ids(http, gateway + "/api/kernels", token));
String kernelId = startKernel(http, gateway, token, "{\"name\": \"python3\"}");
assertEquals(List.of(kernelId), ids(http, gateway + "/api/kernels", token));
await("the idle kernel culled").atMost(Duration.ofMinutes(1)).pollInterval(Duration.ofSeconds(1))
.until(() -> ids(http, gateway + "/api/kernels", token).isEmpty());
}
// Starts a kernel as a Jupyter client does, with the request body, and answers its id.
private static String startKernel(HttpClient http, String gateway, String token, String body) throws Exception {
HttpResponse<String> started = http.send(HttpRequest.newBuilder(URI.create(gateway + "/api/kernels"))
.header("Authorization", "token " + token)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(body)).build(), HttpResponse.BodyHandlers.ofString());
assertEquals(201, started.statusCode(), started.body());
return JSON.readTree(started.body()).path("id").textValue();
}
// Opens the kernel's channels WebSocket, its messages going to messages.
private static WebSocket connect(HttpClient http, String gateway, String token, String kernelId,
Messages messages) throws Exception {
return http.newWebSocketBuilder().header("Authorization", "token " + token)
.buildAsync(URI.create(gateway.replaceFirst("^http", "ws") + "/api/kernels/" + kernelId
+ "/channels"), messages)
.get(HANDSHAKE_TIMEOUT.toSeconds(), TimeUnit.SECONDS);
}
private static void delete(HttpClient http, String url, String token) throws Exception {
assertEquals(204, http.send(HttpRequest.newBuilder(URI.create(url)).header("Authorization", "token " + token)
.DELETE().build(), HttpResponse.BodyHandlers.discarding()).statusCode(), url);
}
// An endpoint of the virtual cluster with configurationOverrides, once it is ACTIVE.
private String endpoint(String virtualClusterId, String configurationOverrides) {
String endpointId = emr().body("""