mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(emr-containers): list only the kernels a managed endpoint's session token started (#9251)
A managed endpoint's gateway listed every kernel it ran to any session token, where ListKernels is "Request that the interactive endpoint list the kernels that have been previously started using the same session token" (EMR on EKS Development Guide, "Monitoring interactive endpoints"). - The proxy passes the gateway the SHA-256 of the token a request carries, in a header of Floci's own, in place of the token, and drops one the client sent. - The gateway program's kernel manager records the digest a kernel was started with, whether the kernels API or the sessions API started it, and drops the record when the kernel goes, whether a request, the culler or the kernel's death removes it. - GET /api/kernels answers with the kernels started with the request's digest alone, and GET /api/sessions with the sessions holding them. Any of the endpoint's tokens still reaches a kernel or a session by its id, as the guide scopes only the listing. - The nightly check starts a session beside its PySpark kernel, lists both kernels and the session with the token that started them, and nothing with another token of the endpoint.
This commit is contained in:
1 parent
711d9ea887
commit
3f2cd7198e
5 files changed
+159
-25
No files matched your search
@@ -239,9 +239,12 @@ remote kernel lifecycle management capability that interactive clients need" (EM
|
||||
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`.
|
||||
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.
|
||||
* **Not emulated yet**: the "Apache Spark with Scala" kernel, `%%configure`, `jupyter-kernel-overrides` images,
|
||||
`jeg-config`'s culling settings, and listing only the kernels a session token started. 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.
|
||||
and `jeg-config`'s culling settings. 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.
|
||||
@@ -1,5 +1,6 @@
|
||||
package io.floci.aws.services.emrcontainers;
|
||||
|
||||
import io.floci.aws.core.common.Digests;
|
||||
import io.floci.aws.core.common.ServiceConfigAccess;
|
||||
import io.floci.aws.core.common.SparkConnectTargets;
|
||||
import io.floci.aws.core.common.WebSocketUpgrades;
|
||||
@@ -42,7 +43,8 @@ import java.util.concurrent.atomic.AtomicBoolean;
|
||||
* carries a token given for that endpoint and not yet expired, as Jupyter Enterprise Gateway 2.6.0 takes one: a
|
||||
* {@code token} parameter, or an {@code Authorization: token <token>} header. One without such a token gets that
|
||||
* gateway's answer, 401 with {@code {"reason": "Unauthorized", "message": ""}}; one whose endpoint is not ACTIVE,
|
||||
* 503, its message saying why.
|
||||
* 503, its message saying why. The gateway gets the token's SHA-256 in place of the token, in
|
||||
* {@link EmrContainersGateways#SESSION_HEADER}, to list a session token's kernels by.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class EmrContainersGatewayProxy {
|
||||
@@ -51,11 +53,11 @@ public class EmrContainersGatewayProxy {
|
||||
|
||||
private static final String TOKEN_PREFIX = "token ";
|
||||
private static final String TOKEN_PARAMETER = "token";
|
||||
// What the gateway never gets: the connection's own headers, which the upgrade puts back where it is one, and the
|
||||
// token.
|
||||
// What the gateway never gets: the connection's own headers, which the upgrade puts back where it is one, the
|
||||
// token, and a session header the client sent, as only Floci gives one.
|
||||
private static final Set<String> NOT_FORWARDED = Set.of("host", "connection", "keep-alive", "proxy-connection",
|
||||
"proxy-authorization", "proxy-authenticate", "te", "trailer", "transfer-encoding", "upgrade",
|
||||
"authorization");
|
||||
"authorization", EmrContainersGateways.SESSION_HEADER.toLowerCase(Locale.ROOT));
|
||||
|
||||
private final EmrContainersService service;
|
||||
private final ServiceConfigAccess serviceConfigAccess;
|
||||
@@ -111,7 +113,7 @@ public class EmrContainersGatewayProxy {
|
||||
refuse(request, 503, "Service Unavailable", refused.refusal());
|
||||
}
|
||||
} else {
|
||||
forward(request, path + query(request), routed.result().get());
|
||||
forward(request, path + query(request), Digests.sha256Hex(token), routed.result().get());
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -160,7 +162,7 @@ public class EmrContainersGatewayProxy {
|
||||
}
|
||||
}
|
||||
|
||||
private void forward(HttpServerRequest request, String uri, SparkConnectTargets.Route route) {
|
||||
private void forward(HttpServerRequest request, String uri, String session, SparkConnectTargets.Route route) {
|
||||
AtomicBoolean over = new AtomicBoolean();
|
||||
Runnable ended = () -> {
|
||||
if (over.compareAndSet(false, true)) {
|
||||
@@ -177,6 +179,7 @@ public class EmrContainersGatewayProxy {
|
||||
options.addHeader(header.getKey(), header.getValue());
|
||||
}
|
||||
}
|
||||
options.addHeader(EmrContainersGateways.SESSION_HEADER, session);
|
||||
client.request(options).onComplete(opened -> {
|
||||
if (opened.failed()) {
|
||||
refuse(request, 502, "Bad Gateway",
|
||||
|
||||
@@ -32,6 +32,12 @@ import java.util.Map;
|
||||
* request carries, as a Jupyter client sends those of its own environment: {@code KERNEL_EXTRA_SPARK_OPTS}, "additional
|
||||
* Spark configurations for the Spark kernels" ("Example: Deploy a JupyterLab notebook"), goes to the PySpark kernel's
|
||||
* {@code spark-submit}. jupyter_server alone starts a kernel with its name and path only.
|
||||
*
|
||||
* <p>ListKernels is "Request that the interactive endpoint list the kernels that have been previously started using
|
||||
* the same session token" ("Monitoring interactive endpoints"), so the program lists only the kernels started with
|
||||
* the session token of the request asking, which it knows by the digest of it Floci passes in
|
||||
* {@link #SESSION_HEADER}, whether the kernels API or the sessions API started them. It lists sessions the same way,
|
||||
* as a session holds its kernel's model.
|
||||
*/
|
||||
final class EmrContainersGateways {
|
||||
|
||||
@@ -42,6 +48,8 @@ final class EmrContainersGateways {
|
||||
static final int PORT = 8888;
|
||||
// Where the program goes in the container, from the variable it comes in.
|
||||
static final String PROGRAM_VARIABLE = "FLOCI_GATEWAY";
|
||||
/** The header in which the gateway gets a digest of the session token a request carries. */
|
||||
static final String SESSION_HEADER = "X-Floci-Session";
|
||||
private static final String HOME = "/tmp/floci-gateway";
|
||||
private static final Duration PROBE_TIMEOUT = Duration.ofSeconds(5);
|
||||
// The image's spark-defaults.conf turns it on, and spark-submit refuses it outside YARN and Kubernetes.
|
||||
@@ -58,8 +66,10 @@ final class EmrContainersGateways {
|
||||
static final SessionServers.Kind KIND = new SessionServers.Kind("Jupyter Enterprise Gateway", "Endpoint",
|
||||
"GetManagedEndpointSessionCredentials");
|
||||
|
||||
// Python 3.9's, the image's; jupyter_server 2's kernels API, its handler replaced by one that passes on the env.
|
||||
// Python 3.9's, the image's; jupyter_server 2's kernels and sessions APIs, their handlers replaced by ones that
|
||||
// pass on the env and list by session token, and its kernel manager by one that records each kernel's token.
|
||||
static final String PROGRAM = """
|
||||
import contextvars
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
@@ -68,11 +78,18 @@ final class EmrContainersGateways {
|
||||
from jupyter_core.utils import ensure_async
|
||||
from jupyter_server.auth.decorator import authorized
|
||||
from jupyter_server.serverapp import ServerApp
|
||||
from jupyter_server.services.kernels import handlers
|
||||
from jupyter_server.services.kernels import handlers as kernel_handlers
|
||||
from jupyter_server.services.kernels.kernelmanager import AsyncMappingKernelManager
|
||||
from jupyter_server.services.sessions import handlers as session_handlers
|
||||
from jupyter_server.utils import url_escape, url_path_join
|
||||
from tornado import web
|
||||
|
||||
HOME = "@HOME@"
|
||||
SESSION_HEADER = "@SESSION_HEADER@"
|
||||
# The session token of the request being served, by the digest of it Floci passes on.
|
||||
SESSION = contextvars.ContextVar("session", default=None)
|
||||
# The session token each running kernel was started with, by that digest.
|
||||
STARTED_WITH = {}
|
||||
|
||||
PYSPARK_KERNEL = '''
|
||||
import sys
|
||||
@@ -102,7 +119,41 @@ final class EmrContainersGateways {
|
||||
}))
|
||||
|
||||
|
||||
class MainKernelHandler(handlers.MainKernelHandler):
|
||||
# Whether the request being served carries the session token the kernel was started with.
|
||||
def mine(kernel_id):
|
||||
return SESSION.get() is not None and STARTED_WITH.get(kernel_id) == SESSION.get()
|
||||
|
||||
|
||||
# Records the session token of a kernel the kernels API or the sessions API starts, and forgets it once
|
||||
# the kernel goes, whether a request, the culler or the kernel's death removes it.
|
||||
class KernelManager(AsyncMappingKernelManager):
|
||||
|
||||
async def start_kernel(self, *, kernel_id=None, **kwargs):
|
||||
starts = kernel_id is None or kernel_id not in self
|
||||
kernel_id = await super().start_kernel(kernel_id=kernel_id, **kwargs)
|
||||
if starts:
|
||||
STARTED_WITH[kernel_id] = SESSION.get()
|
||||
return kernel_id
|
||||
|
||||
def remove_kernel(self, kernel_id):
|
||||
STARTED_WITH.pop(kernel_id, None)
|
||||
return super().remove_kernel(kernel_id)
|
||||
|
||||
|
||||
class WithSession:
|
||||
|
||||
def prepare(self, *args, **kwargs):
|
||||
SESSION.set(self.request.headers.get(SESSION_HEADER))
|
||||
return super().prepare(*args, **kwargs)
|
||||
|
||||
|
||||
class MainKernelHandler(WithSession, kernel_handlers.MainKernelHandler):
|
||||
|
||||
@web.authenticated
|
||||
@authorized
|
||||
async def get(self):
|
||||
kernels = await ensure_async(self.kernel_manager.list_kernels())
|
||||
self.finish(json.dumps([kernel for kernel in kernels if mine(kernel["id"])], default=json_default))
|
||||
|
||||
@web.authenticated
|
||||
@authorized
|
||||
@@ -121,8 +172,28 @@ final class EmrContainersGateways {
|
||||
self.finish(json.dumps(kernel, default=json_default))
|
||||
|
||||
|
||||
handlers.default_handlers = [(path, MainKernelHandler if handler is handlers.MainKernelHandler else handler)
|
||||
for path, handler in handlers.default_handlers]
|
||||
# Sessions list as kernels do: a session holds its kernel's model.
|
||||
class SessionRootHandler(WithSession, session_handlers.SessionRootHandler):
|
||||
|
||||
@web.authenticated
|
||||
@authorized
|
||||
async def get(self):
|
||||
sessions = await ensure_async(self.session_manager.list_sessions())
|
||||
self.finish(json.dumps([session for session in sessions if mine(session["kernel"]["id"])],
|
||||
default=json_default))
|
||||
|
||||
|
||||
# Its PATCH starts a kernel when it names a kernel spec.
|
||||
class SessionHandler(WithSession, session_handlers.SessionHandler):
|
||||
pass
|
||||
|
||||
|
||||
REPLACED = {kernel_handlers.MainKernelHandler: MainKernelHandler,
|
||||
session_handlers.SessionRootHandler: SessionRootHandler,
|
||||
session_handlers.SessionHandler: SessionHandler}
|
||||
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(ServerApp.launch_instance(argv=[
|
||||
"--ServerApp.ip=0.0.0.0", "--ServerApp.port=@PORT@", "--ServerApp.port_retries=0",
|
||||
@@ -131,9 +202,9 @@ final class EmrContainersGateways {
|
||||
"--ServerApp.allow_remote_access=True",
|
||||
"--KernelSpecManager.allowed_kernelspecs=python3",
|
||||
"--KernelSpecManager.allowed_kernelspecs=spark-python-kubernetes",
|
||||
]))
|
||||
], kernel_manager_class=KernelManager))
|
||||
""".replace("@HOME@", HOME).replace("@PORT@", String.valueOf(PORT))
|
||||
.replace("@PROGRAM_VARIABLE@", PROGRAM_VARIABLE);
|
||||
.replace("@PROGRAM_VARIABLE@", PROGRAM_VARIABLE).replace("@SESSION_HEADER@", SESSION_HEADER);
|
||||
|
||||
private EmrContainersGateways() {
|
||||
}
|
||||
|
||||
+43
-7
@@ -35,6 +35,8 @@ import java.net.http.HttpResponse;
|
||||
import java.net.http.WebSocket;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
@@ -51,7 +53,8 @@ import static org.junit.jupiter.api.Assertions.fail;
|
||||
/**
|
||||
* An EMR on EKS managed endpoint, run for real in the {@code docker} runner mode: it runs a Jupyter Enterprise Gateway
|
||||
* in its release's {@code notebook-spark} image from Amazon ECR Public, and a Jupyter client reaches it at its
|
||||
* {@code serverUrl} with a session token, starts a PySpark kernel there, and runs code on Floci's S3 over the kernel's
|
||||
* {@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}.
|
||||
*
|
||||
* <p>A nightly check: the release's notebook image is about 6 GB.
|
||||
@@ -128,12 +131,7 @@ class EmrContainersGatewayNightlyIntegrationTest {
|
||||
String path = URI.create(serverUrl).getPath();
|
||||
assertEquals(EmrContainersService.GATEWAY_PATH + endpointId, path);
|
||||
String gateway = "http://localhost:" + RestAssured.port + path;
|
||||
String token = emr().body("""
|
||||
{"executionRoleArn": "%s", "credentialType": "TOKEN"}
|
||||
""".formatted(ROLE))
|
||||
.post("/virtualclusters/" + virtualClusterId + "/endpoints/" + endpointId + "/credentials")
|
||||
.then().statusCode(200)
|
||||
.extract().path("credentials.token");
|
||||
String token = sessionToken(virtualClusterId, endpointId);
|
||||
|
||||
HttpClient http = HttpClient.newHttpClient();
|
||||
assertEquals(401, http.send(HttpRequest.newBuilder(URI.create(gateway + "/api/kernelspecs")).build(),
|
||||
@@ -152,6 +150,25 @@ class EmrContainersGatewayNightlyIntegrationTest {
|
||||
""")).build(), HttpResponse.BodyHandlers.ofString());
|
||||
assertEquals(201, started.statusCode(), started.body());
|
||||
String kernelId = JSON.readTree(started.body()).path("id").textValue();
|
||||
// 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"))
|
||||
.header("Authorization", "token " + token)
|
||||
.header("Content-Type", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofString("""
|
||||
{"path": "nightly.ipynb", "type": "notebook", "kernel": {"name": "python3"}}
|
||||
""")).build(), HttpResponse.BodyHandlers.ofString());
|
||||
assertEquals(201, created.statusCode(), created.body());
|
||||
JsonNode notebook = JSON.readTree(created.body());
|
||||
assertEquals(List.of(kernelId, notebook.at("/kernel/id").textValue()), ids(http, gateway + "/api/kernels",
|
||||
token));
|
||||
assertEquals(List.of(notebook.path("id").textValue()), ids(http, gateway + "/api/sessions", token));
|
||||
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());
|
||||
|
||||
Messages messages = new Messages();
|
||||
WebSocket socket = http.newWebSocketBuilder().header("Authorization", "token " + token)
|
||||
@@ -203,6 +220,25 @@ class EmrContainersGatewayNightlyIntegrationTest {
|
||||
return null;
|
||||
}
|
||||
|
||||
// The ids the listing at url answers a request carrying token with.
|
||||
private static List<String> ids(HttpClient http, String url, String token) throws Exception {
|
||||
HttpResponse<String> listed = http.send(HttpRequest.newBuilder(URI.create(url))
|
||||
.header("Authorization", "token " + token).build(), HttpResponse.BodyHandlers.ofString());
|
||||
assertEquals(200, listed.statusCode(), listed.body());
|
||||
List<String> ids = new ArrayList<>();
|
||||
JSON.readTree(listed.body()).forEach(kernel -> ids.add(kernel.path("id").textValue()));
|
||||
return ids;
|
||||
}
|
||||
|
||||
private static String sessionToken(String virtualClusterId, String endpointId) {
|
||||
return emr().body("""
|
||||
{"executionRoleArn": "%s", "credentialType": "TOKEN"}
|
||||
""".formatted(ROLE))
|
||||
.post("/virtualclusters/" + virtualClusterId + "/endpoints/" + endpointId + "/credentials")
|
||||
.then().statusCode(200)
|
||||
.extract().path("credentials.token");
|
||||
}
|
||||
|
||||
private String virtualCluster() {
|
||||
String eksCluster = "emr-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
EksRequests.eks(ACCOUNT, REGION)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package io.floci.aws.services.emrcontainers;
|
||||
|
||||
import io.floci.aws.core.common.Digests;
|
||||
import io.floci.aws.core.common.ServiceConfigAccess;
|
||||
import io.floci.aws.core.common.SparkConnectTargets;
|
||||
import io.floci.aws.core.common.WebSocketUpgrades;
|
||||
@@ -73,6 +74,7 @@ class EmrContainersGatewayProxyTest {
|
||||
.putHeader("content-type", "application/json")
|
||||
.end(new JsonObject().put("method", request.method().name()).put("uri", request.uri())
|
||||
.put("authorization", request.getHeader("Authorization"))
|
||||
.put("session", request.getHeader(EmrContainersGateways.SESSION_HEADER))
|
||||
.put("body", body.toString()).encode()));
|
||||
}).listen(0, "127.0.0.1"));
|
||||
service = mock(EmrContainersService.class);
|
||||
@@ -112,6 +114,17 @@ class EmrContainersGatewayProxyTest {
|
||||
awaitCount(requestsEnded, 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void gatewayKnowsTheSessionTokenByItsDigestAlone() throws Exception {
|
||||
// Floci's digest replaces one the client sends, which would let it list another token's kernels.
|
||||
Answer answer = request(HttpMethod.GET, BASE + "/api/kernels", "token " + TOKEN, null,
|
||||
Digests.sha256Hex("another-session-token"));
|
||||
|
||||
assertEquals(201, answer.status);
|
||||
assertEquals(Digests.sha256Hex(TOKEN), new JsonObject(answer.body).getString("session"));
|
||||
awaitCount(requestsEnded, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void queryIsReadAsTheGatewayReadsIt() throws Exception {
|
||||
// Its last token parameter is the one checked, and a malformed escape stays as it came.
|
||||
@@ -189,11 +202,19 @@ class EmrContainersGatewayProxyTest {
|
||||
}
|
||||
|
||||
private Answer request(HttpMethod method, String uri, String authorization, String body) throws Exception {
|
||||
return request(method, uri, authorization, body, null);
|
||||
}
|
||||
|
||||
private Answer request(HttpMethod method, String uri, String authorization, String body, String session)
|
||||
throws Exception {
|
||||
RequestOptions options = new RequestOptions().setMethod(method).setHost("127.0.0.1")
|
||||
.setPort(floci.actualPort()).setURI(uri);
|
||||
if (authorization != null) {
|
||||
options.addHeader("Authorization", authorization);
|
||||
}
|
||||
if (session != null) {
|
||||
options.addHeader(EmrContainersGateways.SESSION_HEADER, session);
|
||||
}
|
||||
// The answer's body is read as its head arrives, on the event loop: asked for later, it may have gone by.
|
||||
return await(client.request(options)
|
||||
.compose(request -> body == null ? request.send() : request.send(Buffer.buffer(body)))
|
||||
|
||||
Reference in new issue
Block a user