diff --git a/.github/workflows/nightly-checks.yml b/.github/workflows/nightly-checks.yml
index dda3f37f62..afac1e0c29 100644
--- a/.github/workflows/nightly-checks.yml
+++ b/.github/workflows/nightly-checks.yml
@@ -34,9 +34,9 @@ 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 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.
+ # each and 21-minute image pull, and EmrContainersGatewayNightlyIntegrationTest's twenty-minute, seven-minute and
+ # eighteen-minute methods and 21-minute image pull, 166 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
matrix:
@@ -44,7 +44,7 @@ jobs:
- group: standard
timeout: 359
- group: docker-runner
- timeout: 168
+ timeout: 186
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.
diff --git a/docs/services/emr-containers.md b/docs/services/emr-containers.md
index b7f726fdf2..34982ce7a6 100644
--- a/docs/services/emr-containers.md
+++ b/docs/services/emr-containers.md
@@ -263,5 +263,12 @@ 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**: `jupyter-kernel-overrides` images. `certificateArn` is kept, and the `serverUrl` is plain HTTP
- on Floci's port.
+* **`jupyter-kernel-overrides`**: a kernel the overrides give a `container-image`, `python3` or
+ `spark-python-kubernetes` (the kernels the guide's example names, as "You can't add new kernel image types"), runs
+ in a container of that image of its own, as on EMR on EKS each kernel is a pod of its image. The gateway asks Floci
+ for the container, with a secret Floci gives that gateway alone, and the image's Jupyter Enterprise Gateway launcher
+ there sends back where the kernel listens, encrypted for the gateway, which signals it through the launcher. A
+ PySpark kernel's `%%configure` posts to the gateway's port 9547 over TLS, as its `ENDPOINT_IP` says, and the
+ restart gives the kernel a new container, its clients moved onto it. The gateway waits for a kernel's container
+ `KERNEL_LAUNCH_TIMEOUT` seconds, at most the guide's maximum of 400, or 400 when the client gives none.
+* **Not emulated yet**: `certificateArn` is kept, and the `serverUrl` is plain HTTP on Floci's port.
diff --git a/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersGateways.java b/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersGateways.java
index 4254677542..f944e27244 100644
--- a/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersGateways.java
+++ b/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersGateways.java
@@ -1,5 +1,6 @@
package io.floci.aws.services.emrcontainers;
+import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.services.emrserverless.EmrServerlessJobRunService;
@@ -11,8 +12,10 @@ import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
+import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
+import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -51,6 +54,13 @@ import java.util.Map;
* the restarted kernel answers, ends the cell with the replies the magic prepared, as the restart takes the kernel
* down before it can; a kernel that dies first, or does not answer in jupyter_server's time for a restart, ends it
* with an error. A kernel's requests take their turn.
+ *
+ *
A kernel the endpoint's {@code jupyter-kernel-overrides} gives an image of its own runs in a container of that
+ * image, as on EMR on EKS each kernel is a pod of its image: the program's provisioner asks Floci for it
+ * ({@link EmrContainersKernelContainersRoute}), and the image's Jupyter Enterprise Gateway launcher sends back where
+ * the kernel listens, encrypted for the provisioner's key, and takes its signals on its comm port. Its
+ * {@code %%configure} magic posts to the program's port 9547 over TLS, as its {@code ENDPOINT_IP} says; the restart
+ * gives the kernel new ports and a new key, which the program moves the kernel's clients onto.
*/
final class EmrContainersGateways {
@@ -79,6 +89,25 @@ final class EmrContainersGateways {
static final String JEG_CONFIG = "jeg-config";
static final List JEG_PROPERTIES = List.of("RemoteMappingKernelManager.cull_idle_timeout",
"RemoteMappingKernelManager.cull_interval");
+ // The classification that gives a kernel an image of its own, a configuration per kernel naming it, its
+ // container-image property the image ("Custom kernel image with interactive endpoint"); the kernels its example
+ // names, as "You can't add new kernel image types".
+ static final String KERNEL_OVERRIDES = "jupyter-kernel-overrides";
+ static final String CONTAINER_IMAGE = "container-image";
+ static final String PYTHON_KERNEL = "python3";
+ static final String PYSPARK_KERNEL = "spark-python-kubernetes";
+ static final List OVERRIDABLE_KERNELS = List.of(PYTHON_KERNEL, PYSPARK_KERNEL);
+ // Where the program learns which kernels run in containers of their own, and the secret it asks Floci for them
+ // with, in SECRET_HEADER.
+ static final String OVERRIDES_VARIABLE = "FLOCI_KERNEL_OVERRIDES";
+ static final String SECRET_VARIABLE = "FLOCI_KERNEL_CONTAINERS_SECRET";
+ static final String KERNEL_CONTAINERS_VARIABLE = "FLOCI_KERNEL_CONTAINERS_PATH";
+ static final String SECRET_HEADER = "X-Floci-Kernel-Containers-Secret";
+ // Jupyter Enterprise Gateway's Python kernel launcher, in the image, which a kernel's own container runs.
+ static final String LAUNCHER = "/usr/local/bin/kernel-launchers/python/scripts/launch_ipykernel.py";
+ // What the launcher's additional-info says to load the %%configure magic.
+ private static final String CONFIGURE_MAGIC_ENABLED = Base64.getEncoder()
+ .encodeToString("{\"configure_magic_enabled\": \"true\"}".getBytes(StandardCharsets.UTF_8));
/** The servers' kind, in the answers to the calls they cannot take. */
static final SessionServers.Kind KIND = new SessionServers.Kind("Jupyter Enterprise Gateway", "Endpoint",
@@ -94,13 +123,21 @@ final class EmrContainersGateways {
import json
import os
import secrets
+ import signal
+ import socket
+ import ssl
+ import subprocess
import sys
import uuid
+ from importlib.metadata import EntryPoint
- from Cryptodome.Cipher import AES
+ from Cryptodome.Cipher import AES, PKCS1_v1_5
from Cryptodome.Hash import SHA256
+ from Cryptodome.PublicKey import RSA
from Cryptodome.Util.Padding import unpad
from jupyter_client.jsonutil import json_default
+ from jupyter_client.kernelspec import KernelSpecManager
+ from jupyter_client.provisioning import KernelProvisionerBase, KernelProvisionerFactory
from jupyter_core.utils import ensure_async
from jupyter_server.auth.decorator import authorized
from jupyter_server.serverapp import ServerApp
@@ -111,9 +148,13 @@ final class EmrContainersGateways {
from jupyter_server.services.sessions import handlers as session_handlers
from jupyter_server.utils import url_escape, url_path_join
from tornado import httpserver, web
+ from tornado.httpclient import AsyncHTTPClient, HTTPRequest
from tornado.websocket import WebSocketClosedError
+ from traitlets import Unicode
HOME = "@HOME@"
+ # The program's kernel specs come first, for the server and for the overrides' lookups alike.
+ os.environ["JUPYTER_PATH"] = HOME
SESSION_HEADER = "@SESSION_HEADER@"
# The image's %%configure magic, beside Jupyter Enterprise Gateway's kernel launchers.
MAGICS = "/usr/local/bin/kernel-launchers/python/scripts"
@@ -130,6 +171,19 @@ final class EmrContainersGateways {
STARTED_WITH = {}
# Each running kernel's launch.
LAUNCHED = {}
+ # The kernels the endpoint's jupyter-kernel-overrides gives images of their own, each in a container Floci
+ # runs, where and with what secret the program asks Floci for those, and how long it waits for one: what
+ # KERNEL_LAUNCH_TIMEOUT says, at most its maximum, 400 seconds.
+ OVERRIDDEN = [kernel for kernel in os.environ.get("@OVERRIDES_VARIABLE@", "").split(",") if kernel]
+ KERNEL_CONTAINERS = (os.environ.get("AWS_ENDPOINT_URL", "").rstrip("/")
+ + os.environ.get("@KERNEL_CONTAINERS_VARIABLE@", ""))
+ KERNEL_CONTAINERS_SECRET = os.environ.pop("@SECRET_VARIABLE@", None)
+ SECRET_HEADER = "@SECRET_HEADER@"
+ LAUNCH_TIMEOUT = 400
+ # Where the magic of a kernel in a container of its own posts its cell's settings: its ENDPOINT_IP, the
+ # program's address, on this port, over TLS.
+ CONFIGURE_TLS_PORT = 9547
+ CONTAINER_PROVISIONER = "floci-kernel-container"
PYSPARK_KERNEL = '''
import sys
@@ -168,6 +222,12 @@ final class EmrContainersGateways {
+ TOREE + ' --profile "$0"',
"{connection_file}"],
}))
+ # A kernel the overrides give an image of its own runs in a container Floci starts, through the provisioner.
+ for kernel in OVERRIDDEN:
+ spec = KernelSpecManager().get_kernel_spec(kernel).to_dict()
+ spec["metadata"] = dict(spec.get("metadata") or {}, kernel_provisioner={
+ "provisioner_name": CONTAINER_PROVISIONER, "config": {"kernel": kernel}})
+ write(HOME + "/kernels/" + kernel + "/kernel.json", json.dumps(spec))
# Whether the request being served carries the session token the kernel was started with.
@@ -212,6 +272,130 @@ final class EmrContainersGateways {
return [message for message in (error, reply, idle) if message]
+ # Asks Floci for a kernel's container, or for its end.
+ async def kernel_container(method, kernel_id, body=None):
+ await AsyncHTTPClient().fetch(HTTPRequest(
+ KERNEL_CONTAINERS + kernel_id, method=method, body=None if body is None else json.dumps(body),
+ headers={SECRET_HEADER: KERNEL_CONTAINERS_SECRET, "Content-Type": "application/json"},
+ allow_nonstandard_methods=True, request_timeout=60))
+
+
+ # A kernel in a container of its own, of the image the overrides give it, which Floci starts at the
+ # program's request, running Jupyter Enterprise Gateway's launcher: the launcher sends where the kernel
+ # listens, encrypted for the program's key, and takes the program's signals on its comm port.
+ class ContainerProvisioner(KernelProvisionerBase):
+
+ kernel = Unicode(config=True)
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+ self.comm = None
+ self.aes_key = None
+
+ @property
+ def has_process(self):
+ return self.comm is not None
+
+ async def pre_launch(self, **kwargs):
+ kwargs = await super().pre_launch(**kwargs)
+ kwargs["cmd"] = []
+ return kwargs
+
+ async def launch_kernel(self, cmd, **kwargs):
+ env = kwargs.get("env") or {}
+ key = RSA.generate(2048)
+ response = asyncio.get_running_loop().create_future()
+
+ async def respond(reader, writer):
+ data = await reader.read()
+ writer.close()
+ if not response.done():
+ response.set_result((data, writer.get_extra_info("peername")[0]))
+
+ server = await asyncio.start_server(respond, "0.0.0.0", 0)
+ try:
+ await kernel_container("POST", self.kernel_id, {
+ "kernel": self.kernel,
+ "responseAddress": socket.gethostbyname(socket.gethostname()) + ":"
+ + str(server.sockets[0].getsockname()[1]),
+ "publicKey": base64.b64encode(key.publickey().export_key("DER")).decode(),
+ "env": {name: value for name, value in env.items() if name.startswith("KERNEL_")}})
+ timeout = min(int(env.get("KERNEL_LAUNCH_TIMEOUT") or LAUNCH_TIMEOUT), LAUNCH_TIMEOUT)
+ data, host = await asyncio.wait_for(response, timeout)
+ payload = json.loads(base64.b64decode(data))
+ aes_key = PKCS1_v1_5.new(key).decrypt(base64.b64decode(payload["key"]), None)
+ cipher = AES.new(aes_key, AES.MODE_GCM, nonce=base64.b64decode(payload["nonce"]))
+ info = json.loads(unpad(cipher.decrypt_and_verify(base64.b64decode(payload["conn_info"]),
+ base64.b64decode(payload["tag"])), 16))
+ connection_info = {
+ "ip": host, "transport": info.get("transport", "tcp"), "key": info["key"].encode(),
+ "signature_scheme": info["signature_scheme"], "kernel_name": self.kernel,
+ **{name: int(info[name]) for name in ("shell_port", "iopub_port", "stdin_port",
+ "hb_port", "control_port")}}
+ comm = (host, int(info["comm_port"]))
+ except BaseException:
+ # A launch that fails after Floci was asked for the container stops it.
+ await self.cleanup()
+ raise
+ finally:
+ server.close()
+ self.aes_key = aes_key.hex()
+ self.comm = comm
+ self.connection_info = connection_info
+ # Each launch's launcher, a restart's too, gives its magic a key of its own.
+ launch = LAUNCHED.get(self.kernel_id)
+ if launch is not None:
+ launch.key = self.aes_key
+ return self.connection_info
+
+ # Sends the launcher a request on its comm port; false where it takes none.
+ async def tell(self, request):
+ if self.comm is None:
+ return False
+ try:
+ reader, writer = await asyncio.wait_for(asyncio.open_connection(*self.comm), 5)
+ writer.write(json.dumps(request).encode())
+ await writer.drain()
+ writer.close()
+ await writer.wait_closed()
+ return True
+ except (OSError, asyncio.TimeoutError):
+ return False
+
+ async def poll(self):
+ return None if await self.tell({"signum": 0}) else 1
+
+ async def wait(self):
+ for _ in range(50):
+ if await self.poll() is not None:
+ return 1
+ await asyncio.sleep(0.2)
+ return None
+
+ async def send_signal(self, signum):
+ await self.tell({"signum": signum})
+
+ async def kill(self, restart=False):
+ await self.tell({"signum": signal.SIGKILL})
+ await self.cleanup(restart)
+
+ async def terminate(self, restart=False):
+ await self.tell({"signum": signal.SIGTERM})
+
+ # Best effort, as jupyter_client's shutdown and restart go on whatever a provisioner's cleanup
+ # meets: a container Floci fails to stop here still stops with the endpoint's gateway.
+ async def cleanup(self, restart=False):
+ self.comm = None
+ try:
+ await kernel_container("DELETE", self.kernel_id)
+ except Exception:
+ self.log.exception("Kernel %s's container could not be stopped", self.kernel_id)
+
+
+ KernelProvisionerFactory.instance().provisioners[CONTAINER_PROVISIONER] = EntryPoint(
+ CONTAINER_PROVISIONER, "__main__:ContainerProvisioner", KernelProvisionerFactory.GROUP_NAME)
+
+
# A kernel's AES key, which only it and the program hold, its launch environment, and the lock its
# %%configure requests take in turn.
class Launch:
@@ -240,9 +424,38 @@ final class EmrContainersGateways {
env.update({"KERNEL_ID": kernel_id, "ADDITIONAL_INFO": json.dumps({"AES_KEY": key})})
kernel_id = await super().start_kernel(kernel_id=kernel_id, env=env, **kwargs)
STARTED_WITH[kernel_id] = SESSION.get()
- LAUNCHED[kernel_id] = Launch(key, env)
+ # A launcher in a container of its own gives its magic a key of its own, and its restarts, the
+ # auto-restarter's too, give the kernel new ports and a new key.
+ provisioner = self.get_kernel(kernel_id).provisioner
+ LAUNCHED[kernel_id] = Launch(getattr(provisioner, "aes_key", None) or key, env)
+ if isinstance(provisioner, ContainerProvisioner):
+ self.add_restart_callback(kernel_id, lambda: self.rebind(kernel_id), "restart")
return kernel_id
+ async def restart_kernel(self, kernel_id, now=False):
+ restarted = await super().restart_kernel(kernel_id, now=now)
+ self.rebind(kernel_id)
+ return restarted
+
+ # A kernel back on new ports, with a new key, as one in a container of its own after a restart: its
+ # clients move onto them, as jupyter_server moves a client that connects again, and so does its
+ # activity watch.
+ def rebind(self, kernel_id):
+ if kernel_id not in self or not self.ports_changed(kernel_id):
+ return
+ self.stop_watching_activity(kernel_id)
+ self.start_watching_activity(kernel_id)
+ kernel = self.get_kernel(kernel_id)
+ for connection in list(ZMQChannelsWebsocketConnection._open_sockets):
+ if connection.kernel_id == kernel_id:
+ for stream in connection.channels.values():
+ if not stream.closed():
+ stream.close()
+ connection.session.key = kernel.session.key
+ connection.create_stream()
+ for stream in connection.channels.values():
+ stream.on_recv_stream(connection.handle_outgoing_message)
+
def remove_kernel(self, kernel_id):
STARTED_WITH.pop(kernel_id, None)
LAUNCHED.pop(kernel_id, None)
@@ -261,6 +474,7 @@ final class EmrContainersGateways {
await client.wait_for_ready(timeout=self.kernel_info_timeout)
finally:
client.stop_channels()
+ self.rebind(kernel_id)
class WithSession:
@@ -343,9 +557,17 @@ final class EmrContainersGateways {
def init_webapp(self):
super().init_webapp()
- httpserver.HTTPServer(web.Application([(r"/api/kernels/configure/([^/]+)", ConfigureHandler,
- {"kernel_manager": self.kernel_manager})])
- ).listen(CONFIGURE_PORT, "127.0.0.1")
+ configure = web.Application([(r"/api/kernels/configure/([^/]+)", ConfigureHandler,
+ {"kernel_manager": self.kernel_manager})])
+ httpserver.HTTPServer(configure).listen(CONFIGURE_PORT, "127.0.0.1")
+ if OVERRIDDEN:
+ # The magic does not check the certificate; the image's openssl makes one.
+ subprocess.run(["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-days", "3650",
+ "-subj", "/CN=floci-gateway", "-keyout", HOME + "/configure.key",
+ "-out", HOME + "/configure.crt"], check=True, capture_output=True)
+ tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
+ tls.load_cert_chain(HOME + "/configure.crt", HOME + "/configure.key")
+ httpserver.HTTPServer(configure, ssl_options=tls).listen(CONFIGURE_TLS_PORT, "0.0.0.0")
REPLACED = {kernel_handlers.MainKernelHandler: MainKernelHandler,
@@ -354,7 +576,6 @@ final class EmrContainersGateways {
for module in (kernel_handlers, session_handlers):
module.default_handlers = [(path, REPLACED.get(handler, handler))
for path, handler in module.default_handlers]
- os.environ["JUPYTER_PATH"] = HOME
sys.exit(GatewayApp.launch_instance(argv=[
"--ServerApp.ip=0.0.0.0", "--ServerApp.port=@PORT@", "--ServerApp.port_retries=0",
"--ServerApp.open_browser=False", "--ServerApp.allow_origin=*", "--ServerApp.root_dir=/home/hadoop",
@@ -365,7 +586,10 @@ final class EmrContainersGateways {
"--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);
+ .replace("@PROGRAM_VARIABLE@", PROGRAM_VARIABLE).replace("@SESSION_HEADER@", SESSION_HEADER)
+ .replace("@OVERRIDES_VARIABLE@", OVERRIDES_VARIABLE)
+ .replace("@KERNEL_CONTAINERS_VARIABLE@", KERNEL_CONTAINERS_VARIABLE)
+ .replace("@SECRET_VARIABLE@", SECRET_VARIABLE).replace("@SECRET_HEADER@", SECRET_HEADER);
private EmrContainersGateways() {
}
@@ -384,21 +608,24 @@ final class EmrContainersGateways {
* driver does, on the image's Python: the virtualenv the image gives a PySpark driver is made on YARN and
* Kubernetes alone. Their class path gains the AWS SDK that S3A runs on, which the image's own leaves out. The
* allow-listed properties of the endpoint's {@code jeg-config} classification go to the program as its arguments,
- * other ones nowhere. As a Spark Connect server does, it checks no token itself: Floci reaches it on the Docker
+ * other ones nowhere. Where its {@code jupyter-kernel-overrides} gives kernels images of their own, the program
+ * learns their names, and where and with {@code secret} it asks Floci for their containers
+ * ({@link #kernelJob}). As a Spark Connect server does, it checks no token itself: Floci reaches it on the Docker
* host's loopback interface alone, and checks the session token first.
*/
- static SparkJobRunner.Job job(ObjectNode endpoint, String imageTemplate, String dockerNetwork) {
+ static SparkJobRunner.Job job(ObjectNode endpoint, String imageTemplate, String dockerNetwork, String secret) {
AwsArnUtils.Arn arn = AwsArnUtils.parse(endpoint.get("arn").textValue());
String releaseLabel = endpoint.get("releaseLabel").textValue();
- Map sparkDefaults =
- new LinkedHashMap<>(EmrContainersSparkJobs.sparkDefaults(endpoint.get("configurationOverrides")));
- sparkDefaults.remove(MASTER);
- sparkDefaults.put(EmrContainersSparkJobs.DEPLOY_MODE, EmrContainersSparkJobs.CLIENT);
- sparkDefaults.put(PYSPARK_VIRTUALENV, "false");
- Map environment = new LinkedHashMap<>(EmrServerlessJobRunService.environment(sparkDefaults,
- "spark.kubernetes.driverEnv."));
- environment.merge(CLASS_PATH_VARIABLE, AWS_SDK, (endpointClassPath, sdk) -> endpointClassPath + ":" + sdk);
+ Map sparkDefaults = sparkDefaults(endpoint);
+ Map environment = environment(sparkDefaults);
environment.put(PROGRAM_VARIABLE, PROGRAM);
+ Map kernelImages = kernelImages(endpoint);
+ if (!kernelImages.isEmpty()) {
+ environment.put(OVERRIDES_VARIABLE, String.join(",", kernelImages.keySet()));
+ environment.put(KERNEL_CONTAINERS_VARIABLE,
+ EmrContainersKernelContainersRoute.PATH + endpoint.get("id").textValue() + "/");
+ environment.put(SECRET_VARIABLE, secret);
+ }
List command = new ArrayList<>(List.of("/bin/bash", "-c", "mkdir -p " + HOME + " && printf '%s' \"$"
+ PROGRAM_VARIABLE + "\" > " + HOME + "/gateway.py && exec python3 " + HOME + "/gateway.py \"$@\"",
"gateway"));
@@ -416,6 +643,84 @@ final class EmrContainersGateways {
Map.of(), null).listeningOn(PORT);
}
+ /**
+ * What runs kernel {@code kernelId} of an endpoint's gateway in a container of its own, run {@code runId}: the
+ * image its {@code jupyter-kernel-overrides} gives the kernel, running Jupyter Enterprise Gateway's launcher there,
+ * which sends where the kernel listens to {@code responseAddress}, encrypted for {@code publicKey}, as it does for
+ * Jupyter Enterprise Gateway. It has the gateway's settings and environment, with the {@code KERNEL_} variables of
+ * {@code kernelEnvironment}; a PySpark kernel's launcher runs under {@code spark-submit}, after
+ * {@code KERNEL_EXTRA_SPARK_OPTS}, and loads the {@code %%configure} magic.
+ */
+ static SparkJobRunner.Job kernelJob(ObjectNode endpoint, String runId, String kernelName, String kernelId,
+ String responseAddress, String publicKey,
+ Map kernelEnvironment, String imageTemplate,
+ String dockerNetwork) {
+ AwsArnUtils.Arn arn = AwsArnUtils.parse(endpoint.get("arn").textValue());
+ String releaseLabel = endpoint.get("releaseLabel").textValue();
+ Map sparkDefaults = sparkDefaults(endpoint);
+ Map environment = environment(sparkDefaults);
+ kernelEnvironment.forEach((name, value) -> {
+ if (name.startsWith("KERNEL_")) {
+ environment.put(name, value);
+ }
+ });
+ String launch = " " + LAUNCHER + " --kernel-id \"$1\" --response-address \"$2\" --public-key \"$3\""
+ + " --port-range 0..0";
+ List command = PYSPARK_KERNEL.equals(kernelName)
+ ? List.of("/bin/bash", "-c", "exec \"$SPARK_HOME/bin/spark-submit\" $KERNEL_EXTRA_SPARK_OPTS" + launch
+ + " --spark-context-initialization-mode lazy --cluster-type spark"
+ + " --RemoteProcessProxy.additional-info \"$4\"",
+ "kernel", kernelId, responseAddress, publicKey, CONFIGURE_MAGIC_ENABLED)
+ : List.of("/bin/bash", "-c", "exec python3" + launch
+ + " --spark-context-initialization-mode none --cluster-type none",
+ "kernel", kernelId, responseAddress, publicKey);
+ return new SparkJobRunner.Job(EmrContainersService.SERVICE, runId, arn.accountId(), arn.region(),
+ releaseLabel, SparkJobRunner.Engine.SPARK, image(imageTemplate, releaseLabel),
+ kernelImages(endpoint).get(kernelName), dockerNetwork, endpoint.get("executionRoleArn").textValue(),
+ sparkDefaults, List.of(), command, Duration.ZERO, null, null, environment, List.of(), null, Map.of(),
+ Map.of(), Map.of(), Map.of(), Map.of(), null);
+ }
+
+ /**
+ * The images an endpoint's {@code jupyter-kernel-overrides} gives its kernels, by kernel name, a later one's
+ * winning; a kernel other than those it may override goes unnamed.
+ */
+ static Map kernelImages(ObjectNode endpoint) {
+ Map images = new LinkedHashMap<>();
+ for (JsonNode configuration : endpoint.path("configurationOverrides").path("applicationConfiguration")) {
+ if (!KERNEL_OVERRIDES.equals(configuration.path("classification").textValue())) {
+ continue;
+ }
+ for (JsonNode kernel : configuration.path("configurations")) {
+ String name = kernel.path("classification").textValue();
+ JsonNode image = kernel.path("properties").path(CONTAINER_IMAGE);
+ if (OVERRIDABLE_KERNELS.contains(name) && image.isTextual()) {
+ images.put(name, image.textValue());
+ }
+ }
+ }
+ return images;
+ }
+
+ // The endpoint's spark-defaults as its kernels' spark-submit gets them: in Spark's local mode and client deploy
+ // mode, with no virtualenv.
+ private static Map sparkDefaults(ObjectNode endpoint) {
+ Map sparkDefaults =
+ new LinkedHashMap<>(EmrContainersSparkJobs.sparkDefaults(endpoint.get("configurationOverrides")));
+ sparkDefaults.remove(MASTER);
+ sparkDefaults.put(EmrContainersSparkJobs.DEPLOY_MODE, EmrContainersSparkJobs.CLIENT);
+ sparkDefaults.put(PYSPARK_VIRTUALENV, "false");
+ return sparkDefaults;
+ }
+
+ // The environment of the endpoint's driver, with the AWS SDK that S3A runs on on its class path.
+ private static Map environment(Map sparkDefaults) {
+ Map environment = new LinkedHashMap<>(EmrServerlessJobRunService.environment(sparkDefaults,
+ "spark.kubernetes.driverEnv."));
+ environment.merge(CLASS_PATH_VARIABLE, AWS_SDK, (endpointClassPath, sdk) -> endpointClassPath + ":" + sdk);
+ return environment;
+ }
+
/**
* Why no gateway answers at {@code host} and {@code port}, or null once one does: any HTTP answer to its API's
* root says jupyter_server runs. A port Docker publishes takes a connection before the server in the container
diff --git a/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersKernelContainers.java b/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersKernelContainers.java
new file mode 100644
index 0000000000..d6b1d21207
--- /dev/null
+++ b/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersKernelContainers.java
@@ -0,0 +1,187 @@
+package io.floci.aws.services.emrcontainers;
+
+import io.floci.aws.services.emrserverless.SparkJobRunner;
+import org.jboss.logging.Logger;
+
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.SecureRandom;
+import java.util.HashMap;
+import java.util.HexFormat;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.regex.Pattern;
+
+/**
+ * The containers of the kernels an endpoint's {@code jupyter-kernel-overrides} gives an image of their own ("Custom
+ * kernel image with interactive endpoint"), each kernel in a container of its own, as on EMR on EKS each is a pod of
+ * its image. The endpoint's gateway asks for a kernel's container as it starts the kernel, and for its end as it stops
+ * it, with a secret Floci gives that gateway alone; an endpoint's containers end with its gateway.
+ */
+final class EmrContainersKernelContainers {
+
+ private static final Logger LOG = Logger.getLogger(EmrContainersKernelContainers.class);
+
+ /** A kernel's id, as jupyter_client makes one. */
+ static final Pattern KERNEL_ID = Pattern.compile("[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}");
+ /** Where a kernel's launcher sends where it listens: a host on the gateway's network, and a port. */
+ static final Pattern RESPONSE_ADDRESS = Pattern.compile("[0-9A-Za-z.-]{1,253}:[0-9]{1,5}");
+ /** The public key the launcher encrypts that with, in base64. */
+ static final Pattern PUBLIC_KEY = Pattern.compile("[A-Za-z0-9+/]{1,4096}={0,2}");
+
+ private final SparkJobRunner runner;
+ private final Executor executor;
+ // Each gateway's secret, account and Region, by its endpoint.
+ private final Map gateways = new ConcurrentHashMap<>();
+ // The run of each kernel's container, by endpoint, then kernel.
+ private final Map> kernels = new HashMap<>();
+ private final AtomicLong launches = new AtomicLong();
+
+ EmrContainersKernelContainers(SparkJobRunner runner, Executor executor) {
+ this.runner = runner;
+ this.executor = executor;
+ }
+
+ /** What a gateway was given: its secret, and its endpoint's account and Region. */
+ record Gateway(String secret, String accountId, String region) {
+ }
+
+ // A kernel's container's run, and whether it was asked to stop.
+ private static final class Kernel {
+ final String runId;
+ volatile boolean stopped;
+
+ Kernel(String runId) {
+ this.runId = runId;
+ }
+ }
+
+ /** A new secret for endpoint {@code endpointId}'s gateway, in place of any an earlier gateway had. */
+ String secretFor(String endpointId, String accountId, String region) {
+ byte[] bytes = new byte[32];
+ new SecureRandom().nextBytes(bytes);
+ String secret = HexFormat.of().formatHex(bytes);
+ gateways.put(endpointId, new Gateway(secret, accountId, region));
+ return secret;
+ }
+
+ /** The gateway of endpoint {@code endpointId} that {@code secret} is the secret of, or null for none. */
+ Gateway gateway(String endpointId, String secret) {
+ Gateway gateway = gateways.get(endpointId);
+ return gateway != null && secret != null && MessageDigest.isEqual(
+ gateway.secret().getBytes(StandardCharsets.UTF_8), secret.getBytes(StandardCharsets.UTF_8))
+ ? gateway : null;
+ }
+
+ /** The id of a new run of a kernel's container: its endpoint's and its own, with a count. */
+ String runId(String endpointId, String kernelId) {
+ return endpointId + "-" + kernelId + "-" + launches.incrementAndGet();
+ }
+
+ /**
+ * Runs {@code job}, kernel {@code kernelId}'s container, on a thread of its own, its earlier one stopped; false,
+ * running nothing, once the endpoint's gateway has ended ({@link #stopAll}), which takes its kernels under the
+ * same lock.
+ */
+ boolean launch(String endpointId, String kernelId, SparkJobRunner.Job job) {
+ Kernel kernel = new Kernel(job.runId());
+ Kernel earlier;
+ synchronized (this) {
+ if (!gateways.containsKey(endpointId)) {
+ return false;
+ }
+ earlier = kernels.computeIfAbsent(endpointId, id -> new HashMap<>()).put(kernelId, kernel);
+ }
+ if (earlier != null) {
+ stop(earlier);
+ }
+ executor.execute(() -> {
+ try {
+ SparkJobRunner.Outcome outcome = runner.run(job, new Progress(kernel));
+ if (outcome.failure() != null) {
+ LOG.warnv("The container of kernel {0} of endpoint {1} could not start: {2}", kernelId,
+ endpointId, outcome.failure());
+ }
+ } catch (RuntimeException e) {
+ LOG.warnv(e, "The container of kernel {0} of endpoint {1} failed", kernelId, endpointId);
+ } finally {
+ synchronized (this) {
+ Map endpointKernels = kernels.get(endpointId);
+ if (endpointKernels != null && endpointKernels.remove(kernelId, kernel)
+ && endpointKernels.isEmpty()) {
+ kernels.remove(endpointId);
+ }
+ }
+ }
+ });
+ return true;
+ }
+
+ /** Stops kernel {@code kernelId}'s container, where it runs. */
+ void stop(String endpointId, String kernelId) {
+ Kernel kernel;
+ synchronized (this) {
+ Map endpointKernels = kernels.get(endpointId);
+ kernel = endpointKernels != null ? endpointKernels.get(kernelId) : null;
+ }
+ if (kernel != null) {
+ stop(kernel);
+ }
+ }
+
+ /** Stops the containers of the endpoint's kernels, its gateway's secret going with them. */
+ void stopAll(String endpointId) {
+ List running;
+ synchronized (this) {
+ gateways.remove(endpointId);
+ Map endpointKernels = kernels.get(endpointId);
+ running = endpointKernels != null ? List.copyOf(endpointKernels.values()) : List.of();
+ }
+ running.forEach(this::stop);
+ }
+
+ /** Stops every kernel's container, the gateways' secrets going with them, as a reset ends every endpoint. */
+ void reset() {
+ List running;
+ synchronized (this) {
+ gateways.clear();
+ running = kernels.values().stream().flatMap(endpointKernels -> endpointKernels.values().stream())
+ .toList();
+ }
+ running.forEach(this::stop);
+ }
+
+ /** {@link #reset}, and the threads that run the containers stop, as Floci does. */
+ void shutdown() {
+ reset();
+ if (executor instanceof ExecutorService service) {
+ service.shutdownNow();
+ }
+ }
+
+ private void stop(Kernel kernel) {
+ kernel.stopped = true;
+ runner.stop(kernel.runId);
+ }
+
+ // A kernel's container's run: cancelled once asked to stop.
+ private record Progress(Kernel kernel) implements SparkJobRunner.Progress {
+
+ @Override
+ public void started() {
+ }
+
+ @Override
+ public void timedOut() {
+ }
+
+ @Override
+ public boolean cancelled() {
+ return kernel.stopped;
+ }
+ }
+}
diff --git a/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersKernelContainersRoute.java b/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersKernelContainersRoute.java
new file mode 100644
index 0000000000..c60f4ba59a
--- /dev/null
+++ b/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersKernelContainersRoute.java
@@ -0,0 +1,122 @@
+package io.floci.aws.services.emrcontainers;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.floci.aws.core.common.ServiceConfigAccess;
+import io.vertx.core.Future;
+import io.vertx.core.Vertx;
+import io.vertx.core.buffer.Buffer;
+import io.vertx.core.http.HttpMethod;
+import io.vertx.core.http.HttpServerRequest;
+import io.vertx.core.json.JsonObject;
+import io.vertx.ext.web.Router;
+import io.vertx.ext.web.RoutingContext;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.event.Observes;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.io.IOException;
+
+/**
+ * Where an endpoint's gateway asks Floci for the container of a kernel that the endpoint's
+ * {@code jupyter-kernel-overrides} gives an image of its own, and for its end ({@link EmrContainersKernelContainers}):
+ * {@code POST} and {@code DELETE} on {@link #PATH}{@code /}, with the secret Floci gave that
+ * gateway in {@link EmrContainersGateways#SECRET_HEADER}. Floci's own: on EMR on EKS the service runs a kernel's pod
+ * itself.
+ */
+@ApplicationScoped
+public class EmrContainersKernelContainersRoute {
+
+ static final String PATH = "/_aws/emr-containers/kernel-containers/";
+
+ private static final Logger LOG = Logger.getLogger(EmrContainersKernelContainersRoute.class);
+ private static final ObjectMapper JSON = new ObjectMapper();
+ // A start's body: a kernel's name, a response address, a public key and the kernel's KERNEL_ variables.
+ private static final long MAX_BODY = 64 * 1024;
+
+ private final EmrContainersService service;
+ private final ServiceConfigAccess serviceConfigAccess;
+ private final Vertx vertx;
+
+ @Inject
+ public EmrContainersKernelContainersRoute(EmrContainersService service, ServiceConfigAccess serviceConfigAccess,
+ Vertx vertx) {
+ this.service = service;
+ this.serviceConfigAccess = serviceConfigAccess;
+ this.vertx = vertx;
+ }
+
+ void register(@Observes Router router) {
+ router.route(PATH + ":endpointId/:kernelId").handler(this::handle);
+ }
+
+ void handle(RoutingContext context) {
+ // This route runs ahead of the filter that refuses a disabled service, so it checks for itself.
+ if (!serviceConfigAccess.isEnabled(EmrContainersService.SERVICE)) {
+ context.next();
+ return;
+ }
+ HttpServerRequest request = context.request();
+ String endpointId = context.pathParam("endpointId");
+ String kernelId = context.pathParam("kernelId");
+ String secret = request.getHeader(EmrContainersGateways.SECRET_HEADER);
+ if (request.method() == HttpMethod.DELETE) {
+ vertx.executeBlocking(
+ () -> service.stopKernelContainer(endpointId, kernelId, secret), false)
+ .onComplete(stopped -> {
+ if (stopped.failed()) {
+ LOG.warnv(stopped.cause(), "Kernel {0}'s container could not be stopped", kernelId);
+ answer(request, 500, "The kernel's container could not be stopped.");
+ } else if (stopped.result() == null) {
+ request.response().setStatusCode(204).end();
+ } else {
+ answer(request, stopped.result().status(), stopped.result().message());
+ }
+ });
+ return;
+ }
+ if (request.method() != HttpMethod.POST) {
+ answer(request, 405, "A kernel's container is started with POST and stopped with DELETE.");
+ return;
+ }
+ String length = request.getHeader("content-length");
+ if (length == null || !length.matches("[0-9]{1,6}") || Long.parseLong(length) > MAX_BODY) {
+ answer(request, 400, "The request's body has no length, or too long a one.");
+ return;
+ }
+ // Quarkus hands the route the request paused, and resumes it for a handler set on it but not for body().
+ Future received = request.body();
+ request.resume();
+ received.onComplete(read -> {
+ JsonNode body;
+ try {
+ body = read.succeeded() ? JSON.readTree(read.result().getBytes()) : null;
+ } catch (IOException e) {
+ body = null;
+ }
+ if (body == null || !body.isObject()) {
+ answer(request, 400, "The request's body is no JSON object.");
+ return;
+ }
+ JsonNode start = body;
+ vertx.executeBlocking(
+ () -> service.startKernelContainer(endpointId, kernelId, secret, start), false)
+ .onComplete(started -> {
+ if (started.failed()) {
+ LOG.warnv(started.cause(), "Kernel {0}'s container could not be started", kernelId);
+ answer(request, 500, "The kernel's container could not be started.");
+ } else if (started.result() == null) {
+ answer(request, 201, "The kernel's container is starting.");
+ } else {
+ answer(request, started.result().status(), started.result().message());
+ }
+ });
+ });
+ }
+
+ private static void answer(HttpServerRequest request, int status, String message) {
+ request.response().setStatusCode(status).putHeader("content-type", "application/json")
+ .end(new JsonObject().put("message", message).encode());
+ }
+}
diff --git a/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersService.java b/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersService.java
index 6a091df445..4ff8e9c0e4 100644
--- a/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersService.java
+++ b/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersService.java
@@ -276,15 +276,17 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
}
if (gateways != null) {
gateways.servers().shutdown();
+ gateways.kernels().shutdown();
}
}
/**
- * The managed endpoints' gateways of the docker runner mode: the servers that run them, the image they run in
- * ({@code gateway-image-template}, null when not set), and Floci's base URL, which their {@code serverUrl} is
- * under.
+ * The managed endpoints' gateways of the docker runner mode: the servers that run them, the containers of their
+ * kernels with images of their own, the image they run in ({@code gateway-image-template}, null when not set), and
+ * Floci's base URL, which their {@code serverUrl} is under.
*/
- record EndpointGateways(SessionServers servers, String imageTemplate, String baseUrl) {
+ record EndpointGateways(SessionServers servers, EmrContainersKernelContainers kernels, String imageTemplate,
+ String baseUrl) {
static EndpointGateways of(SparkJobRunner runner, Clock clock, String imageTemplate, String baseUrl) {
HttpClient probes = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
@@ -292,6 +294,8 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
Executors.newCachedThreadPool(Thread.ofPlatform().daemon().name("emr-containers-gateway-", 0)
.factory()),
null, (host, port) -> EmrContainersGateways.unanswered(probes, host, port), clock),
+ new EmrContainersKernelContainers(runner, Executors.newCachedThreadPool(
+ Thread.ofPlatform().daemon().name("emr-containers-kernel-", 0).factory())),
imageTemplate, baseUrl);
}
}
@@ -674,7 +678,8 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
endpoint.put(CLIENT_TOKEN, clientToken);
endpoints.put(arn, endpoint);
if (gateways != null) {
- gateways.servers().launch(EmrContainersGateways.job(endpoint, gateways.imageTemplate(), dockerNetwork),
+ gateways.servers().launch(EmrContainersGateways.job(endpoint, gateways.imageTemplate(), dockerNetwork,
+ gateways.kernels().secretFor(id, regionResolver.getAccountId(), regionResolver.getRegion())),
gatewayOwner);
}
return pick(endpoint, "id", "name", "arn", "virtualClusterId");
@@ -778,6 +783,72 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
return gateways == null ? Optional.empty() : gateways.servers().routeWithoutToken(endpointId, gatewayOwner);
}
+ /**
+ * Starts the container of kernel {@code kernelId} of endpoint {@code endpointId}, as its gateway asks with
+ * {@code secret}, the one Floci gave it: the kernel's {@code kernel} names one the endpoint's
+ * {@code jupyter-kernel-overrides} gives an image, its {@code responseAddress} and {@code publicKey} where its
+ * launcher sends where the kernel listens, and its {@code env} the kernel's {@code KERNEL_} variables. Null once
+ * started, else why not, as the status and message of the answer. Called off the event loop.
+ */
+ public KernelContainerRefusal startKernelContainer(String endpointId, String kernelId, String secret,
+ JsonNode request) {
+ EmrContainersKernelContainers.Gateway gateway =
+ gateways == null ? null : gateways.kernels().gateway(endpointId, secret);
+ if (gateway == null) {
+ return notSigned(endpointId);
+ }
+ String kernel = request.path("kernel").textValue();
+ String responseAddress = request.path("responseAddress").textValue();
+ String publicKey = request.path("publicKey").textValue();
+ if (!EmrContainersKernelContainers.KERNEL_ID.matcher(kernelId).matches() || responseAddress == null
+ || !EmrContainersKernelContainers.RESPONSE_ADDRESS.matcher(responseAddress).matches()
+ || publicKey == null || !EmrContainersKernelContainers.PUBLIC_KEY.matcher(publicKey).matches()
+ || !request.path("env").isObject()) {
+ return new KernelContainerRefusal(400, "The request names no kernel id, response address, public key "
+ + "and env.");
+ }
+ Map environment = new LinkedHashMap<>();
+ request.get("env").properties().forEach(variable -> {
+ if (variable.getValue().isTextual()) {
+ environment.put(variable.getKey(), variable.getValue().textValue());
+ }
+ });
+ return RequestScopes.callAs(gateway.accountId(), gateway.region(), () -> {
+ synchronized (this) {
+ ObjectNode endpoint = endpointById(endpointId).orElse(null);
+ if (endpoint == null || !ACTIVE.equals(endpoint.path("state").textValue())) {
+ return new KernelContainerRefusal(409, "Endpoint " + endpointId + " is not ACTIVE.");
+ }
+ if (!EmrContainersGateways.kernelImages(endpoint).containsKey(kernel)) {
+ return new KernelContainerRefusal(400, "Endpoint " + endpointId
+ + "'s jupyter-kernel-overrides gives kernel " + kernel + " no image.");
+ }
+ // Refused where the gateway's end has taken its secret and kernels since its secret was checked.
+ return gateways.kernels().launch(endpointId, kernelId, EmrContainersGateways.kernelJob(endpoint,
+ gateways.kernels().runId(endpointId, kernelId), kernel, kernelId, responseAddress, publicKey,
+ environment, gateways.imageTemplate(), dockerNetwork)) ? null
+ : new KernelContainerRefusal(409, "Endpoint " + endpointId + "'s gateway has stopped.");
+ }
+ });
+ }
+
+ /** Stops the container of kernel {@code kernelId}, as its gateway asks with {@code secret}: null, else why not. */
+ public KernelContainerRefusal stopKernelContainer(String endpointId, String kernelId, String secret) {
+ if (gateways == null || gateways.kernels().gateway(endpointId, secret) == null) {
+ return notSigned(endpointId);
+ }
+ gateways.kernels().stop(endpointId, kernelId);
+ return null;
+ }
+
+ /** Why a gateway's call for a kernel's container is refused: the answer's status and message. */
+ public record KernelContainerRefusal(int status, String message) {
+ }
+
+ private static KernelContainerRefusal notSigned(String endpointId) {
+ return new KernelContainerRefusal(403, "The request is not signed by endpoint " + endpointId + "'s gateway.");
+ }
+
/**
* The endpoint as it stands, stored: in the docker runner mode, one whose gateway no thread of this process runs,
* as after a restart, has ended, TERMINATED_WITH_ERRORS, or TERMINATED where it was being deleted.
@@ -855,6 +926,8 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
@Override
public void stopped(String endpointId, SparkJobRunner.Outcome outcome) {
+ // Its kernels' own containers go with the gateway.
+ gateways.kernels().stopAll(endpointId);
synchronized (EmrContainersService.this) {
endpointById(endpointId)
.filter(stored -> !FINISHED_ENDPOINT_STATES.contains(stored.path("state").textValue()))
@@ -1068,6 +1141,7 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
executing.clear();
if (gateways != null) {
gateways.servers().reset();
+ gateways.kernels().reset();
}
}
@@ -1077,6 +1151,7 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
executing.clear();
if (gateways != null) {
gateways.servers().reset();
+ gateways.kernels().reset();
}
virtualClusters.clear();
jobRuns.clear();
diff --git a/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersGatewayNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersGatewayNightlyIntegrationTest.java
index 755fe3ee0c..696bc83f13 100644
--- a/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersGatewayNightlyIntegrationTest.java
+++ b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersGatewayNightlyIntegrationTest.java
@@ -59,7 +59,7 @@ import static org.junit.jupiter.api.Assertions.fail;
* JupyterLab notebook" does through {@code JUPYTER_GATEWAY_URL}, then 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.
+ * idle, and one whose {@code jupyter-kernel-overrides} gives its kernels an image runs each in a container of its own.
*
* A nightly check: the release's notebook image is about 6 GB.
*/
@@ -234,6 +234,58 @@ class EmrContainersGatewayNightlyIntegrationTest {
.DELETE().build(), HttpResponse.BodyHandlers.discarding()).statusCode(), url);
}
+ // The endpoint's gateway answers within its five minutes; each kernel's container starts, and its WebSocket
+ // opens, within its two, and each of the four cells answers within its two: seventeen minutes, and one for the
+ // requests between. The Nightly checks' docker-runner group counts it.
+ @Test
+ @Timeout(value = 18, unit = TimeUnit.MINUTES)
+ void kernelsTheOverridesGiveAnImageRunInContainersOfTheirOwn() throws Exception {
+ S3Client s3 = AwsTestClients.create(S3Client.builder().forcePathStyle(true), ACCOUNT, Region.US_EAST_1);
+ cleanup.register(s3::close);
+ String bucket = "emr-eks-kernel-" + 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("lines.txt"), RequestBody.fromString("a\nb\nc\n"));
+ String virtualClusterId = virtualCluster();
+ // As "Custom kernel image with interactive endpoint" overrides them, with the release's own image.
+ String endpointId = endpoint(virtualClusterId, """
+ {"applicationConfiguration": [{"classification": "jupyter-kernel-overrides", "configurations": [
+ {"classification": "python3", "properties": {"container-image": "%s"}},
+ {"classification": "spark-python-kubernetes", "properties": {"container-image": "%s"}}]}]}"""
+ .formatted(NOTEBOOK_IMAGE, NOTEBOOK_IMAGE));
+ String gateway = gateway(virtualClusterId, endpointId);
+ String token = sessionToken(virtualClusterId, endpointId);
+ HttpClient http = HttpClient.newHttpClient();
+ String session = UUID.randomUUID().toString();
+
+ String python = startKernel(http, gateway, token, "{\"name\": \"python3\"}");
+ assertEquals(1, docker.listContainersCmd().withNameFilter(List.of(python)).exec().size(),
+ "the kernel's own container");
+ Messages pythonMessages = new Messages();
+ WebSocket pythonSocket = connect(http, gateway, token, python, pythonMessages);
+ // Jupyter Enterprise Gateway's launcher gives the kernel its gateway's address.
+ assertEquals("True", execute(pythonSocket, pythonMessages, session,
+ "import os; os.environ.get('ENDPOINT_IP') is not None"));
+ pythonSocket.sendClose(WebSocket.NORMAL_CLOSURE, "done").get(10, TimeUnit.SECONDS);
+ delete(http, gateway + "/api/kernels/" + python, token);
+ await("the kernel's container gone").atMost(Duration.ofMinutes(1)).pollInterval(Duration.ofSeconds(1))
+ .until(() -> docker.listContainersCmd().withNameFilter(List.of(python)).exec().isEmpty());
+
+ String pyspark = startKernel(http, gateway, token, "{\"name\": \"spark-python-kubernetes\"}");
+ Messages messages = new Messages();
+ WebSocket socket = connect(http, gateway, token, pyspark, messages);
+ assertEquals("3", execute(socket, messages, session,
+ "spark.read.text(\"s3://" + bucket + "/lines.txt\").count()"));
+ // Its %%configure restarts it in a new container, under the same id, the client staying connected.
+ assertEquals("ok", run(socket, messages, session, """
+ %%configure -f
+ {"conf": {"spark.app.name": "from-configure"}}""", "execute_reply", "/content/status"));
+ assertEquals("'from-configure'", execute(socket, messages, session, "spark.conf.get(\"spark.app.name\")"));
+ assertEquals(List.of(pyspark), ids(http, gateway + "/api/kernels", token));
+ socket.sendClose(WebSocket.NORMAL_CLOSURE, "done").get(10, TimeUnit.SECONDS);
+ delete(http, gateway + "/api/kernels/" + pyspark, token);
+ }
+
// An endpoint of the virtual cluster with configurationOverrides, once it is ACTIVE.
private String endpoint(String virtualClusterId, String configurationOverrides) {
String endpointId = emr().body("""
@@ -245,9 +297,12 @@ class EmrContainersGatewayNightlyIntegrationTest {
.extract().path("id");
cleanup.register(() -> emr().delete("/virtualclusters/" + virtualClusterId + "/endpoints/" + endpointId)
.then().statusCode(200));
- await().atMost(ACTIVE_TIMEOUT).pollInterval(Duration.ofSeconds(1)).until(() -> "ACTIVE".equals(
- emr().get("/virtualclusters/" + virtualClusterId + "/endpoints/" + endpointId)
- .then().statusCode(200).extract().path("endpoint.state")));
+ // ACTIVE once its gateway answers, or ended with errors where it cannot start, which stateDetails says.
+ JsonNode endpoint = await().atMost(ACTIVE_TIMEOUT).pollInterval(Duration.ofSeconds(1))
+ .until(() -> JSON.readTree(emr().get("/virtualclusters/" + virtualClusterId + "/endpoints/"
+ + endpointId).then().statusCode(200).extract().asString()).path("endpoint"),
+ settled -> !"CREATING".equals(settled.path("state").textValue()));
+ assertEquals("ACTIVE", endpoint.path("state").textValue(), endpoint.toString());
return endpointId;
}
diff --git a/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersKernelContainersRouteTest.java b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersKernelContainersRouteTest.java
new file mode 100644
index 0000000000..1b642872ab
--- /dev/null
+++ b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersKernelContainersRouteTest.java
@@ -0,0 +1,124 @@
+package io.floci.aws.services.emrcontainers;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import io.floci.aws.core.common.ServiceConfigAccess;
+import io.vertx.core.Future;
+import io.vertx.core.Vertx;
+import io.vertx.core.buffer.Buffer;
+import io.vertx.core.http.HttpClient;
+import io.vertx.core.http.HttpMethod;
+import io.vertx.core.http.HttpServer;
+import io.vertx.core.http.RequestOptions;
+import io.vertx.core.json.JsonObject;
+import io.vertx.ext.web.Router;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+import java.util.concurrent.TimeUnit;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * Calls to {@link EmrContainersKernelContainersRoute}, as an endpoint's gateway makes them for its kernels' containers:
+ * a mock of the service stands behind it.
+ */
+class EmrContainersKernelContainersRouteTest {
+
+ private static final String ENDPOINT = "ep0123456789a";
+ private static final String KERNEL = "0b9e3c4e-6a1f-4c2d-9b8e-1f2a3b4c5d6e";
+ private static final String PATH = EmrContainersKernelContainersRoute.PATH + ENDPOINT + "/" + KERNEL;
+
+ private Vertx vertx;
+ private HttpServer floci;
+ private HttpClient client;
+ private EmrContainersService service;
+
+ @BeforeEach
+ void setUp() throws Exception {
+ vertx = Vertx.vertx();
+ service = mock(EmrContainersService.class);
+ ServiceConfigAccess serviceConfigAccess = mock(ServiceConfigAccess.class);
+ when(serviceConfigAccess.isEnabled(eq(EmrContainersService.SERVICE))).thenReturn(true);
+ Router router = Router.router(vertx);
+ // As Quarkus hands a route the request: paused.
+ router.route().handler(context -> {
+ context.request().pause();
+ context.next();
+ });
+ new EmrContainersKernelContainersRoute(service, serviceConfigAccess, vertx).register(router);
+ floci = await(vertx.createHttpServer().requestHandler(router).listen(0, "127.0.0.1"));
+ client = vertx.createHttpClient();
+ }
+
+ @AfterEach
+ void tearDown() throws Exception {
+ await(vertx.close());
+ }
+
+ @Test
+ void startGoesToTheServiceWithItsSecretAndBody() throws Exception {
+ Answer started = request(HttpMethod.POST, "a-secret", "{\"kernel\": \"python3\"}");
+
+ assertEquals(201, started.status);
+ ArgumentCaptor body = ArgumentCaptor.forClass(JsonNode.class);
+ verify(service).startKernelContainer(eq(ENDPOINT), eq(KERNEL), eq("a-secret"), body.capture());
+ assertEquals("python3", body.getValue().path("kernel").textValue());
+ }
+
+ @Test
+ void refusalGivesItsStatusAndMessage() throws Exception {
+ when(service.startKernelContainer(anyString(), anyString(), any(), any())).thenReturn(
+ new EmrContainersService.KernelContainerRefusal(403, "not signed"));
+ when(service.stopKernelContainer(anyString(), anyString(), any())).thenReturn(
+ new EmrContainersService.KernelContainerRefusal(403, "not signed"));
+
+ Answer start = request(HttpMethod.POST, null, "{}");
+ Answer stop = request(HttpMethod.DELETE, null, null);
+
+ assertEquals(403, start.status);
+ assertEquals("not signed", new JsonObject(start.body).getString("message"));
+ assertEquals(403, stop.status);
+ }
+
+ @Test
+ void stopGoesToTheService() throws Exception {
+ Answer stopped = request(HttpMethod.DELETE, "a-secret", null);
+
+ assertEquals(204, stopped.status);
+ verify(service).stopKernelContainer(ENDPOINT, KERNEL, "a-secret");
+ }
+
+ @Test
+ void startWithoutAJsonObjectOrWithAnotherMethodIsRefused() throws Exception {
+ assertEquals(400, request(HttpMethod.POST, "a-secret", "not json").status);
+ assertEquals(400, request(HttpMethod.POST, "a-secret", "[]").status);
+ assertEquals(405, request(HttpMethod.GET, "a-secret", null).status);
+ }
+
+ private Answer request(HttpMethod method, String secret, String body) throws Exception {
+ RequestOptions options = new RequestOptions().setMethod(method).setHost("127.0.0.1")
+ .setPort(floci.actualPort()).setURI(PATH);
+ if (secret != null) {
+ options.addHeader(EmrContainersGateways.SECRET_HEADER, secret);
+ }
+ return await(client.request(options)
+ .compose(request -> body == null ? request.send() : request.send(Buffer.buffer(body)))
+ .compose(response -> response.body()
+ .map(read -> new Answer(response.statusCode(), read.toString()))));
+ }
+
+ private static T await(Future future) throws Exception {
+ return future.toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
+ }
+
+ private record Answer(int status, String body) {
+ }
+}
diff --git a/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersKernelContainersTest.java b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersKernelContainersTest.java
new file mode 100644
index 0000000000..e8af4c6eb1
--- /dev/null
+++ b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersKernelContainersTest.java
@@ -0,0 +1,123 @@
+package io.floci.aws.services.emrcontainers;
+
+import io.floci.aws.services.emrserverless.SparkJobRunner;
+import org.junit.jupiter.api.Test;
+
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/** The kernels' containers {@link EmrContainersKernelContainers} runs, read from its runner's side. */
+class EmrContainersKernelContainersTest {
+
+ private static final String ENDPOINT = "ep0123456789a";
+ private static final String KERNEL = "0b9e3c4e-6a1f-4c2d-9b8e-1f2a3b4c5d6e";
+
+ private final Runner runner = new Runner();
+ private final EmrContainersKernelContainers kernels = new EmrContainersKernelContainers(runner,
+ task -> Thread.ofPlatform().daemon().start(task));
+
+ @Test
+ void secretIsTheGatewaysAlone() {
+ String secret = kernels.secretFor(ENDPOINT, "000000000000", "us-east-1");
+
+ assertNotNull(kernels.gateway(ENDPOINT, secret));
+ assertNull(kernels.gateway(ENDPOINT, secret + "0"));
+ assertNull(kernels.gateway(ENDPOINT, null));
+ assertNull(kernels.gateway("ep0000000000000", secret));
+ }
+
+ @Test
+ void launchOnceTheGatewayHasEndedRunsNothing() {
+ kernels.secretFor(ENDPOINT, "000000000000", "us-east-1");
+ kernels.stopAll(ENDPOINT);
+
+ // As a call whose secret was checked before the gateway ended reaches it after.
+ assertFalse(kernels.launch(ENDPOINT, KERNEL, job(kernels.runId(ENDPOINT, KERNEL))));
+ assertEquals(List.of(), runner.started);
+ }
+
+ @Test
+ void launchAgainStopsTheKernelsEarlierContainer() {
+ kernels.secretFor(ENDPOINT, "000000000000", "us-east-1");
+ String first = kernels.runId(ENDPOINT, KERNEL);
+ assertTrue(kernels.launch(ENDPOINT, KERNEL, job(first)));
+ awaitStarted(first);
+
+ assertTrue(kernels.launch(ENDPOINT, KERNEL, job(kernels.runId(ENDPOINT, KERNEL))));
+
+ assertEquals(Set.of(first), runner.stopped);
+ }
+
+ @Test
+ void resetStopsEveryKernelsContainerAndForgetsTheSecrets() {
+ String secret = kernels.secretFor(ENDPOINT, "000000000000", "us-east-1");
+ String runId = kernels.runId(ENDPOINT, KERNEL);
+ assertTrue(kernels.launch(ENDPOINT, KERNEL, job(runId)));
+ awaitStarted(runId);
+
+ kernels.reset();
+
+ assertEquals(Set.of(runId), runner.stopped);
+ assertNull(kernels.gateway(ENDPOINT, secret));
+ }
+
+ private void awaitStarted(String runId) {
+ await("run " + runId + " started").atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(10))
+ .until(() -> runner.started.contains(runId));
+ }
+
+ private static SparkJobRunner.Job job(String runId) {
+ return new SparkJobRunner.Job(EmrContainersService.SERVICE, runId, "000000000000", "us-east-1",
+ "emr-7.5.0-latest", SparkJobRunner.Engine.SPARK, null, null, null, null, Map.of(), List.of(),
+ List.of(), Duration.ZERO, null, null, Map.of(), List.of(), null, Map.of(), Map.of(), Map.of(),
+ Map.of(), Map.of(), null);
+ }
+
+ /** A runner that records the runs it starts, each running until it is stopped, and the runs it stops. */
+ private static final class Runner implements SparkJobRunner {
+ final List started = new CopyOnWriteArrayList<>();
+ final Set stopped = ConcurrentHashMap.newKeySet();
+ private final Map ends = new ConcurrentHashMap<>();
+
+ @Override
+ public Outcome run(Job job, Progress progress) {
+ if (progress.cancelled()) {
+ return Outcome.halted();
+ }
+ started.add(job.runId());
+ try {
+ end(job.runId()).await(10, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ return Outcome.halted();
+ }
+
+ @Override
+ public void stop(String runId) {
+ stopped.add(runId);
+ end(runId).countDown();
+ }
+
+ private CountDownLatch end(String runId) {
+ return ends.computeIfAbsent(runId, id -> new CountDownLatch(1));
+ }
+
+ @Override
+ public void removeLeftoverDrivers(String service) {
+ }
+ }
+}
diff --git a/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersServiceTest.java b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersServiceTest.java
index 1ac8413872..69af5f4bbb 100644
--- a/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersServiceTest.java
+++ b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersServiceTest.java
@@ -42,6 +42,7 @@ import java.util.concurrent.atomic.AtomicReference;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
@@ -1297,6 +1298,7 @@ class EmrContainersServiceTest {
return new EmrContainersService(stores.get(0), stores.get(1), stores.get(2), stores.get(3), stores.get(4),
mapper, new RegionResolver(REGION, ACCOUNT_ID), eks, iam, null, clock, 0, runner, Runnable::run,
null, "floci-net", delays, new EmrContainersService.EndpointGateways(servers,
+ new EmrContainersKernelContainers(runner, task -> Thread.ofPlatform().daemon().start(task)),
"registry.internal/emr-on-eks/notebook-spark/%s", "http://floci.test:4566/"));
}
@@ -1419,6 +1421,117 @@ class EmrContainersServiceTest {
runner.stop(endpointId);
}
+ private static final String KERNEL = "0b9e3c4e-6a1f-4c2d-9b8e-1f2a3b4c5d6e";
+
+ // An endpoint whose jupyter-kernel-overrides gives both kernels the guide's example names an image, and the
+ // Scala kernel one, which it cannot override.
+ private String overriddenEndpoint(EmrContainersService service, String clusterId) {
+ return service.createManagedEndpoint(clusterId, json("""
+ {"name": "custom", "type": "JUPYTER_ENTERPRISE_GATEWAY", "releaseLabel": "%s",
+ "executionRoleArn": "%s", "clientToken": "%s",
+ "configurationOverrides": {"applicationConfiguration": [{
+ "classification": "jupyter-kernel-overrides", "configurations": [
+ {"classification": "python3",
+ "properties": {"container-image": "registry.internal/custom-notebook-python:latest"}},
+ {"classification": "spark-python-kubernetes",
+ "properties": {"container-image": "registry.internal/custom-notebook-spark:latest"}},
+ {"classification": "spark-scala-kubernetes",
+ "properties": {"container-image": "registry.internal/custom-notebook-scala:latest"}}]}]}}
+ """.formatted(RELEASE, ROLE, UUID.randomUUID()))).get("id").textValue();
+ }
+
+ // What the gateway sends to start a kernel's container.
+ private ObjectNode kernelStart(String kernel, String responseAddress) {
+ return json("""
+ {"kernel": "%s", "responseAddress": "%s", "publicKey": "cHVibGljLWtleQ==",
+ "env": {"KERNEL_EXTRA_SPARK_OPTS": "--conf spark.app.name=custom", "PATH": "/opt/elsewhere"}}
+ """.formatted(kernel, responseAddress));
+ }
+
+ @Test
+ void kernelTheOverridesGiveAnImageRunsInAContainerOfItAsItsGatewayAsks() {
+ GatewayRunner runner = new GatewayRunner();
+ EmrContainersService service = gatewayService(runner, stores());
+ String clusterId = virtualCluster(service, EKS_CLUSTER);
+ String endpointId = overriddenEndpoint(service, clusterId);
+ awaitEndpoint(service, clusterId, endpointId, "ACTIVE");
+ Map gateway = runner.awaitJob(endpointId).environment();
+ // "You can't add new kernel image types": the Scala kernel's goes unnamed.
+ assertEquals("python3,spark-python-kubernetes", gateway.get(EmrContainersGateways.OVERRIDES_VARIABLE));
+ assertEquals(EmrContainersKernelContainersRoute.PATH + endpointId + "/",
+ gateway.get(EmrContainersGateways.KERNEL_CONTAINERS_VARIABLE));
+ String secret = gateway.get(EmrContainersGateways.SECRET_VARIABLE);
+
+ assertNull(service.startKernelContainer(endpointId, KERNEL, secret,
+ kernelStart("spark-python-kubernetes", "10.0.0.5:40000")));
+ SparkJobRunner.Job pyspark = runner.awaitJob(endpointId + "-" + KERNEL + "-1");
+ assertEquals("registry.internal/custom-notebook-spark:latest", pyspark.customImage());
+ assertTrue(pyspark.command().get(2).startsWith("exec \"$SPARK_HOME/bin/spark-submit\" $KERNEL_EXTRA_SPARK_OPTS "
+ + EmrContainersGateways.LAUNCHER), pyspark.command().get(2));
+ assertEquals(List.of("kernel", KERNEL, "10.0.0.5:40000", "cHVibGljLWtleQ==",
+ "eyJjb25maWd1cmVfbWFnaWNfZW5hYmxlZCI6ICJ0cnVlIn0="),
+ pyspark.command().subList(3, pyspark.command().size()), "its launcher loads the %%configure magic");
+ assertEquals("--conf spark.app.name=custom", pyspark.environment().get("KERNEL_EXTRA_SPARK_OPTS"));
+ assertFalse(pyspark.environment().containsKey("PATH"), "a kernel's KERNEL_ variables alone");
+ assertFalse(pyspark.environment().containsKey(EmrContainersGateways.SECRET_VARIABLE));
+ assertEquals("false", pyspark.sparkDefaults().get(EmrContainersGateways.PYSPARK_VIRTUALENV));
+ assertEquals(ROLE, pyspark.executionRole());
+ assertEquals("floci-net", pyspark.dockerNetwork());
+
+ String python = "1b9e3c4e-6a1f-4c2d-9b8e-1f2a3b4c5d6e";
+ assertNull(service.startKernelContainer(endpointId, python, secret, kernelStart("python3", "10.0.0.5:40001")));
+ SparkJobRunner.Job python3 = runner.awaitJob(endpointId + "-" + python + "-2");
+ assertEquals("registry.internal/custom-notebook-python:latest", python3.customImage());
+ assertTrue(python3.command().get(2).startsWith("exec python3 " + EmrContainersGateways.LAUNCHER),
+ python3.command().get(2));
+
+ assertNull(service.stopKernelContainer(endpointId, KERNEL, secret));
+ assertTrue(runner.stopped.contains(pyspark.runId()));
+ runner.stop(endpointId);
+ // A kernel's container goes with its gateway, and the gateway's secret too.
+ await("the kernel's container stopped").atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(10))
+ .until(() -> runner.stopped.contains(python3.runId()));
+ assertEquals(403, service.startKernelContainer(endpointId, python, secret,
+ kernelStart("python3", "10.0.0.5:40001")).status());
+ }
+
+ @Test
+ void kernelContainerIsRefusedWithoutItsGatewaysSecretOrAKernelTheOverridesGiveAnImage() {
+ GatewayRunner runner = new GatewayRunner();
+ EmrContainersService service = gatewayService(runner, stores());
+ String clusterId = virtualCluster(service, EKS_CLUSTER);
+ String endpointId = overriddenEndpoint(service, clusterId);
+ awaitEndpoint(service, clusterId, endpointId, "ACTIVE");
+ String secret = runner.awaitJob(endpointId).environment().get(EmrContainersGateways.SECRET_VARIABLE);
+ ObjectNode start = kernelStart("python3", "10.0.0.5:40000");
+
+ assertEquals(403, service.startKernelContainer(endpointId, KERNEL, "not-the-secret", start).status());
+ assertEquals(403, service.startKernelContainer(endpointId, KERNEL, null, start).status());
+ assertEquals(403, service.stopKernelContainer(endpointId, KERNEL, "not-the-secret").status());
+ assertEquals(400, service.startKernelContainer(endpointId, KERNEL, secret,
+ kernelStart("spark-scala-kubernetes", "10.0.0.5:40000")).status(), "no image for it");
+ assertEquals(400, service.startKernelContainer(endpointId, KERNEL, secret,
+ kernelStart("python3", "10.0.0.5:40000 --kernel-id other")).status());
+ assertEquals(400, service.startKernelContainer(endpointId, "not-a-kernel", secret, start).status());
+ assertEquals(List.of(endpointId), runner.jobs.stream().map(SparkJobRunner.Job::runId).toList(),
+ "the gateway's alone");
+ runner.stop(endpointId);
+ }
+
+ @Test
+ void endpointWithoutOverridesGivesItsGatewayNoSecret() {
+ GatewayRunner runner = new GatewayRunner();
+ EmrContainersService service = gatewayService(runner, stores());
+ String clusterId = virtualCluster(service, EKS_CLUSTER);
+ String endpointId = gatewayEndpoint(service, clusterId);
+ awaitEndpoint(service, clusterId, endpointId, "ACTIVE");
+
+ Map gateway = runner.awaitJob(endpointId).environment();
+ assertFalse(gateway.containsKey(EmrContainersGateways.OVERRIDES_VARIABLE));
+ assertFalse(gateway.containsKey(EmrContainersGateways.SECRET_VARIABLE));
+ runner.stop(endpointId);
+ }
+
@Test
void deletedDockerEndpointStopsItsGatewayAndItsTokensGo() {
GatewayRunner runner = new GatewayRunner();