feat(emr-containers): run a managed endpoint's Jupyter Enterprise Gateway (#9232)

An EMR on EKS managed endpoint ran nothing: it was ACTIVE at once with no
serverUrl, so no Jupyter client could start a kernel on it, and its
session tokens opened nothing.

- With runner-mode docker, an endpoint runs a Jupyter Enterprise Gateway,
  which "provides the remote kernel lifecycle management capability that
  interactive clients need", in a container of its release's
  notebook-spark image on Amazon ECR Public, the base image of
  interactive endpoints. That image holds jupyter_server and ipykernel but
  no Enterprise Gateway, so a program of Floci's own serves the gateway's
  kernels API on jupyter_server, passing a kernel the KERNEL_ variables
  of its start request's env, as Jupyter Enterprise Gateway does.
- Its kernels are the image's python3, and spark-python-kubernetes, whose
  spark and sc are a Spark session in Spark's local mode on Floci's S3,
  with the endpoint's execution role, KERNEL_EXTRA_SPARK_OPTS going to
  its spark-submit.
- The endpoint is CREATING until the gateway answers, then ACTIVE with
  its serverUrl and the guide's "Endpoint created successfully. It took
  m Minutes s Seconds". DeleteManagedEndpoint makes it TERMINATING until
  the gateway has stopped. A gateway that fails, and one a restart left,
  end it TERMINATED_WITH_ERRORS with INTERNAL_ERROR.
- serverUrl is a path of the endpoint's own on Floci's port. A request
  there goes on to the gateway, its kernels' WebSocket tunnelled, when it
  carries a live token GetManagedEndpointSessionCredentials gave for that
  endpoint, as a token parameter or an Authorization: token header, as
  Jupyter Enterprise Gateway 2.6.0 takes one; any other gets that
  gateway's 401 {"reason": "Unauthorized", "message": ""}.
- SessionServers, which runs EMR Serverless's and EMR's Spark Connect
  servers and keeps their tokens, runs the gateways too, a token given
  for one endpoint reaching no other. CloudFront's WebSocket splice moves
  to WebSocketUpgrades, which the gateway's tunnel shares.
- gateway-image-template replaces the notebook image's registry.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-23 06:39:56 -04:00
1 parent 2f652f3f87
commit 29e262e783
14 files changed
+1557 -37

No files matched your search

@@ -1239,6 +1239,16 @@ public interface EmulatorConfig {
*/
Optional<String> imageTemplate();
/**
* The image a managed endpoint's Jupyter Enterprise Gateway and its kernels run in, in the {@code docker}
* runner mode, with {@code %s} standing for its release's container image tag, for example
* "registry.internal/emr-on-eks/notebook-spark/%s". If omitted, Floci uses the release's
* {@code notebook-spark} image on Amazon ECR Public.
*
* Env var: FLOCI_SERVICES_EMRCONTAINERS_GATEWAY_IMAGE_TEMPLATE
*/
Optional<String> gatewayImageTemplate();
/**
* When true, Floci removes, in the {@code docker} runner mode, every EMR on EKS driver a previous run of
* <em>this same</em> Floci left on the daemon before its first job run starts. Turn it off when two Floci
@@ -9,6 +9,8 @@ import io.vertx.core.http.HttpVersion;
import io.vertx.core.net.NetSocket;
import org.jboss.logging.Logger;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* The parts of proxying a WebSocket handshake that the proxies Floci emulates share. An ALB and a
* CloudFront distribution both forward a WebSocket upgrade to their origin with its upgrade headers
@@ -59,6 +61,24 @@ public final class WebSocketUpgrades {
LOG.warnv(err, "Could not close refused WebSocket origin connection to {0}", connection.remoteAddress()));
}
/**
* Joins two connections into a byte tunnel, as an upgraded WebSocket's two ends: each reads into the other until
* either ends, closes or fails, which closes both, and then {@code closed} runs, once.
*/
public static void splice(NetSocket one, NetSocket other, Runnable closed) {
AtomicBoolean over = new AtomicBoolean();
Runnable close = () -> {
if (over.compareAndSet(false, true)) {
one.close();
other.close();
closed.run();
}
};
Runnable onData = () -> { };
relay(one, other, onData, close);
relay(other, one, onData, close);
}
/**
* Copies everything {@code source} reads to {@code destination}, pausing the source while the
* destination's write queue is full. {@code onData} runs for each buffer, and {@code close} when
@@ -169,7 +169,8 @@ public class CloudFrontWebSocketProxy {
viewerResponse.putHeader("Upgrade", response.getHeader("Upgrade"));
NetSocket originSocket = response.netSocket();
request.toNetSocket()
.onSuccess(viewerSocket -> splice(viewerSocket, originSocket))
.onSuccess(viewerSocket -> WebSocketUpgrades.splice(viewerSocket, originSocket,
() -> { }))
.onFailure(err -> {
LOG.debugv("CloudFront WebSocket tunnel lost the viewer: {0}", err.getMessage());
originSocket.close();
@@ -304,17 +305,4 @@ public class CloudFrontWebSocketProxy {
}
}
}
private static void splice(NetSocket viewer, NetSocket origin) {
AtomicBoolean closed = new AtomicBoolean();
Runnable close = () -> {
if (closed.compareAndSet(false, true)) {
viewer.close();
origin.close();
}
};
Runnable onData = () -> { };
WebSocketUpgrades.relay(viewer, origin, onData, close);
WebSocketUpgrades.relay(origin, viewer, onData, close);
}
}
@@ -0,0 +1,303 @@
package io.floci.aws.services.emrcontainers;
import io.floci.aws.core.common.ServiceConfigAccess;
import io.floci.aws.core.common.SparkConnectTargets;
import io.floci.aws.core.common.WebSocketUpgrades;
import io.vertx.core.MultiMap;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.http.HttpClientRequest;
import io.vertx.core.http.HttpClientResponse;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.http.RequestOptions;
import io.vertx.core.json.JsonObject;
import io.vertx.core.net.NetSocket;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* A managed endpoint's {@code serverUrl}, where a Jupyter client reaches its Jupyter Enterprise Gateway with
* {@code JUPYTER_GATEWAY_URL} set to it and {@code JUPYTER_GATEWAY_AUTH_TOKEN} to a token
* GetManagedEndpointSessionCredentials gave for the endpoint ("Example: Deploy a JupyterLab notebook", EMR on EKS
* Development Guide). A request under the endpoint's path on Floci's own port goes on to its gateway
* ({@link EmrContainersGateways}), its kernels' WebSocket a byte tunnel once the gateway takes the upgrade, when it
* 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.
*/
@ApplicationScoped
public class EmrContainersGatewayProxy {
private static final Logger LOG = Logger.getLogger(EmrContainersGatewayProxy.class);
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.
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");
private final EmrContainersService service;
private final ServiceConfigAccess serviceConfigAccess;
private final Vertx vertx;
private final HttpClient client;
@Inject
public EmrContainersGatewayProxy(EmrContainersService service, ServiceConfigAccess serviceConfigAccess,
Vertx vertx) {
this.service = service;
this.serviceConfigAccess = serviceConfigAccess;
this.vertx = vertx;
// Keep-alive, since a request without it sends Connection: close in place of Connection: Upgrade.
this.client = vertx.createHttpClient(new HttpClientOptions().setKeepAlive(true).setConnectTimeout(5_000));
}
@PreDestroy
void close() {
client.close();
}
void register(@Observes Router router) {
router.route(EmrContainersService.GATEWAY_PATH + "*").handler(this::handle);
}
void handle(RoutingContext context) {
HttpServerRequest request = context.request();
// 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;
}
String rest = request.path().substring(EmrContainersService.GATEWAY_PATH.length());
int slash = rest.indexOf('/');
String endpointId = slash < 0 ? rest : rest.substring(0, slash);
String path = slash < 0 ? "/" : rest.substring(slash);
String token = token(request);
request.pause();
// A service reads its storage to route a request, so off the event loop.
vertx.<Optional<SparkConnectTargets.Route>>executeBlocking(() -> service.gatewayRoute(endpointId, token),
false).onComplete(routed -> {
if (routed.failed()) {
LOG.warnv(routed.cause(), "A request to endpoint {0}'s gateway could not be routed",
endpointId);
refuse(request, 502, "Bad Gateway", "The request could not be routed.");
} else if (routed.result().isEmpty()) {
refuse(request, 401, "Unauthorized", "");
} else if (routed.result().get().refusal() != null) {
SparkConnectTargets.Route refused = routed.result().get();
if (refused.status() == SparkConnectTargets.Route.UNAUTHENTICATED) {
refuse(request, 401, "Unauthorized", refused.refusal());
} else {
refuse(request, 503, "Service Unavailable", refused.refusal());
}
} else {
forward(request, path + query(request), routed.result().get());
}
});
}
// The request's token, as Jupyter Enterprise Gateway reads it with Tornado's get_argument: its last token
// parameter, else its Authorization header.
static String token(HttpServerRequest request) {
String token = null;
for (String parameter : parameters(request.query())) {
int equals = parameter.indexOf('=');
if (TOKEN_PARAMETER.equals(decoded(equals < 0 ? parameter : parameter.substring(0, equals)))) {
token = equals < 0 ? "" : decoded(parameter.substring(equals + 1));
}
}
if (token != null) {
return token;
}
String authorization = request.getHeader("Authorization");
return authorization != null && authorization.startsWith(TOKEN_PREFIX)
? authorization.substring(TOKEN_PREFIX.length()) : null;
}
// The request's query as the gateway gets it: without its token.
static String query(HttpServerRequest request) {
List<String> kept = new ArrayList<>();
for (String parameter : parameters(request.query())) {
int equals = parameter.indexOf('=');
if (!TOKEN_PARAMETER.equals(decoded(equals < 0 ? parameter : parameter.substring(0, equals)))) {
kept.add(parameter);
}
}
return kept.isEmpty() ? "" : "?" + String.join("&", kept);
}
private static List<String> parameters(String query) {
return query == null || query.isEmpty() ? List.of() : List.of(query.split("&"));
}
// A query parameter's name or value with its escapes decoded. Tornado leaves a malformed escape as it came, so
// a name holding one is never the token's, and a value holding one is no token Floci gave.
private static String decoded(String text) {
try {
return URLDecoder.decode(text, StandardCharsets.UTF_8);
} catch (IllegalArgumentException e) {
return text;
}
}
private void forward(HttpServerRequest request, String uri, SparkConnectTargets.Route route) {
AtomicBoolean over = new AtomicBoolean();
Runnable ended = () -> {
if (over.compareAndSet(false, true)) {
vertx.executeBlocking(() -> {
route.ended().run();
return null;
}, false);
}
};
RequestOptions options = new RequestOptions().setMethod(request.method()).setHost(route.host())
.setPort(route.port()).setURI(uri);
for (Map.Entry<String, String> header : request.headers()) {
if (!NOT_FORWARDED.contains(header.getKey().toLowerCase(Locale.ROOT))) {
options.addHeader(header.getKey(), header.getValue());
}
}
client.request(options).onComplete(opened -> {
if (opened.failed()) {
refuse(request, 502, "Bad Gateway",
"The endpoint's gateway could not be reached: " + opened.cause().getMessage());
ended.run();
} else if (WebSocketUpgrades.isHandshake(request)) {
upgrade(request, opened.result(), ended);
} else {
exchange(request, opened.result(), ended);
}
});
}
// A request and its answer, each streamed through.
private static void exchange(HttpServerRequest request, HttpClientRequest upstream, Runnable ended) {
HttpServerResponse response = request.response();
// A body sent in chunks goes on in chunks.
if (request.getHeader("content-length") == null && request.getHeader("transfer-encoding") != null) {
upstream.setChunked(true);
}
response.closeHandler(closed -> {
upstream.reset();
ended.run();
});
// The answer is held as it arrives, its body read once the relay is ready for it.
upstream.response().map(HttpClientResponse::pause).onComplete(answered -> {
if (answered.failed()) {
if (response.headWritten()) {
response.reset();
} else {
refuse(request, 502, "Bad Gateway",
"The endpoint's gateway ended the request: " + answered.cause().getMessage());
}
ended.run();
return;
}
HttpClientResponse answer = answered.result();
int status = answer.statusCode();
response.setStatusCode(status);
copy(answer.headers(), response.headers());
// One the gateway streams, with no length, goes on in chunks as it came.
if (answer.getHeader("content-length") == null && request.method() != HttpMethod.HEAD && status != 204
&& status != 304 && status >= 200) {
response.setChunked(true);
}
// A gateway that breaks off its answer breaks off the viewer's too, which would otherwise wait for the
// rest of a body whose length it was given.
answer.pipe().endOnFailure(false).to(response).onComplete(piped -> {
if (piped.failed()) {
response.reset();
}
ended.run();
});
});
request.pipeTo(upstream).onFailure(failure -> {
upstream.reset();
if (!response.ended()) {
response.reset();
}
ended.run();
});
}
// A kernel's WebSocket: the handshake goes to the gateway, and once it switches protocols the two connections
// are joined; any other answer goes back as it is.
private static void upgrade(HttpServerRequest request, HttpClientRequest upstream, Runnable ended) {
upstream.putHeader("Connection", "Upgrade");
upstream.putHeader("Upgrade", request.getHeader("Upgrade"));
upstream.connect().onComplete(connected -> {
HttpServerResponse response = request.response();
if (connected.failed()) {
refuse(request, 502, "Bad Gateway",
"The endpoint's gateway refused the connection: " + connected.cause().getMessage());
ended.run();
return;
}
HttpClientResponse answer = connected.result();
response.setStatusCode(answer.statusCode());
copy(answer.headers(), response.headers());
if (answer.statusCode() != 101) {
request.resume();
answer.body().onComplete(read -> {
if (read.succeeded()) {
response.end(read.result());
} else {
response.end();
}
WebSocketUpgrades.closeRefusedRequest(upstream);
ended.run();
});
return;
}
response.putHeader("Connection", "Upgrade");
response.putHeader("Upgrade", answer.getHeader("Upgrade"));
NetSocket gateway = answer.netSocket();
request.toNetSocket()
.onSuccess(viewer -> WebSocketUpgrades.splice(viewer, gateway, ended))
.onFailure(failure -> {
gateway.close();
ended.run();
});
});
}
private static void copy(MultiMap from, MultiMap to) {
for (Map.Entry<String, String> header : from) {
if (!NOT_FORWARDED.contains(header.getKey().toLowerCase(Locale.ROOT))) {
to.add(header.getKey(), header.getValue());
}
}
}
// Jupyter Enterprise Gateway's JSON error: its reason, and its message.
private static void refuse(HttpServerRequest request, int status, String reason, String message) {
request.resume();
HttpServerResponse response = request.response();
if (response.ended() || response.headWritten()) {
return;
}
response.setStatusCode(status)
.putHeader("content-type", "application/json")
.end(new JsonObject().put("reason", reason).put("message", message).encode());
}
}
@@ -0,0 +1,198 @@
package io.floci.aws.services.emrcontainers;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.services.emrserverless.EmrServerlessJobRunService;
import io.floci.aws.services.emrserverless.SessionServers;
import io.floci.aws.services.emrserverless.SparkJobRunner;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.List;
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.
*
* <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
* 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.
*/
final class EmrContainersGateways {
/** The image a gateway runs in, {@code %s} standing for its release's container image tag. */
static final String DEFAULT_IMAGE_TEMPLATE =
"public.ecr.aws/emr-on-eks/notebook-spark/%s"; // partition-literal: ECR Public, where AWS publishes them
/** The port the gateway listens on in its container. */
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";
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.
static final String PYSPARK_VIRTUALENV = "spark.pyspark.virtualenv.enabled";
// The runner's spark-defaults name local mode first, and an endpoint's would come after them.
static final String MASTER = "spark.master";
// S3A, which Floci's s3:// paths go through, runs on the AWS SDK v2. The image holds it, but its
// spark-defaults.conf leaves it off the driver's class path, and Spark's launcher adds this variable's entries
// after that class path.
static final String CLASS_PATH_VARIABLE = "SPARK_DIST_CLASSPATH";
static final String AWS_SDK = "/usr/share/aws/aws-java-sdk-v2/*";
/** The servers' kind, in the answers to the calls they cannot take. */
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.
static final String PROGRAM = """
import json
import os
import sys
from jupyter_client.jsonutil import json_default
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.utils import url_escape, url_path_join
from tornado import web
HOME = "@HOME@"
PYSPARK_KERNEL = '''
import sys
from ipykernel.kernelapp import IPKernelApp
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
IPKernelApp.launch_instance(argv=sys.argv[1:], user_ns={"spark": spark, "sc": spark.sparkContext})
'''
def write(path, text):
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as out:
out.write(text)
write(HOME + "/pyspark_kernel.py", PYSPARK_KERNEL)
write(HOME + "/kernels/spark-python-kubernetes/kernel.json", json.dumps({
"display_name": "PySpark on Kubernetes",
"language": "python",
"argv": ["/bin/bash", "-c",
'exec "$SPARK_HOME/bin/spark-submit" $KERNEL_EXTRA_SPARK_OPTS ' + HOME
+ '/pyspark_kernel.py -f "$0"',
"{connection_file}"],
}))
class MainKernelHandler(handlers.MainKernelHandler):
@web.authenticated
@authorized
async def post(self):
km = self.kernel_manager
model = self.get_json_body() or {}
env = dict(os.environ)
env.pop("@PROGRAM_VARIABLE@", None)
env.update({key: str(value) for key, value in (model.get("env") or {}).items()
if key.startswith("KERNEL_")})
kernel_id = await ensure_async(km.start_kernel(
kernel_name=model.get("name") or km.default_kernel_name, path=model.get("path"), env=env))
kernel = await ensure_async(km.kernel_model(kernel_id))
self.set_header("Location", url_path_join(self.base_url, "api", "kernels", url_escape(kernel_id)))
self.set_status(201)
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]
os.environ["JUPYTER_PATH"] = HOME
sys.exit(ServerApp.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",
"--IdentityProvider.token=", "--ServerApp.disable_check_xsrf=True",
"--ServerApp.allow_remote_access=True",
"--KernelSpecManager.allowed_kernelspecs=python3",
"--KernelSpecManager.allowed_kernelspecs=spark-python-kubernetes",
]))
""".replace("@HOME@", HOME).replace("@PORT@", String.valueOf(PORT))
.replace("@PROGRAM_VARIABLE@", PROGRAM_VARIABLE);
private EmrContainersGateways() {
}
/** The gateway's image for a release label: {@code imageTemplate}'s, else {@link #DEFAULT_IMAGE_TEMPLATE}'s. */
static String image(String imageTemplate, String releaseLabel) {
return String.format(imageTemplate != null ? imageTemplate : DEFAULT_IMAGE_TEMPLATE,
EmrContainersSparkJobs.containerImageTag(releaseLabel));
}
/**
* What runs an endpoint's gateway: its program, written out from its variable, in the endpoint's release's image,
* on {@code dockerNetwork}, with the endpoint's execution role and the {@code spark-defaults} of its
* {@code configurationOverrides}, listening on {@link #PORT}. Its kernels' {@code spark-submit} gets those
* defaults, in Spark's local mode and client deploy mode whatever master and deploy mode they name, as a job run's
* 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. 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) {
AwsArnUtils.Arn arn = AwsArnUtils.parse(endpoint.get("arn").textValue());
String releaseLabel = endpoint.get("releaseLabel").textValue();
Map<String, String> sparkDefaults =
new LinkedHashMap<>(EmrContainersSparkJobs.sparkDefaults(endpoint.get("configurationOverrides")));
sparkDefaults.remove(MASTER);
sparkDefaults.put(EmrContainersSparkJobs.DEPLOY_MODE, EmrContainersSparkJobs.CLIENT);
sparkDefaults.put(PYSPARK_VIRTUALENV, "false");
Map<String, String> environment = new LinkedHashMap<>(EmrServerlessJobRunService.environment(sparkDefaults,
"spark.kubernetes.driverEnv."));
environment.merge(CLASS_PATH_VARIABLE, AWS_SDK, (endpointClassPath, sdk) -> endpointClassPath + ":" + sdk);
environment.put(PROGRAM_VARIABLE, PROGRAM);
List<String> command = List.of("/bin/bash", "-c", "mkdir -p " + HOME + " && printf '%s' \"$"
+ PROGRAM_VARIABLE + "\" > " + HOME + "/gateway.py && exec python3 " + HOME + "/gateway.py");
return new SparkJobRunner.Job(EmrContainersService.SERVICE, endpoint.get("id").textValue(), arn.accountId(),
arn.region(), releaseLabel, SparkJobRunner.Engine.SPARK, image(imageTemplate, releaseLabel), null,
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).listeningOn(PORT);
}
/**
* 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
* listens, so a connection alone says nothing.
*/
static String unanswered(HttpClient client, String host, int port) {
HttpRequest request = HttpRequest.newBuilder(URI.create("http://" + host + ":" + port + "/api"))
.timeout(PROBE_TIMEOUT)
.GET()
.build();
try {
client.send(request, HttpResponse.BodyHandlers.discarding());
return null;
} catch (IOException e) {
return e.toString();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return "interrupted";
}
}
}
@@ -17,6 +17,7 @@ import io.floci.aws.core.common.RequestContext;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.core.common.Resettable;
import io.floci.aws.core.common.SmithyValidationErrors;
import io.floci.aws.core.common.SparkConnectTargets;
import io.floci.aws.core.common.StoredResourceArns;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageFactory;
@@ -24,6 +25,7 @@ import io.floci.aws.services.eks.EksService;
import io.floci.aws.services.eks.model.AccessConfig;
import io.floci.aws.services.eks.model.Cluster;
import io.floci.aws.services.emrserverless.EmrServerlessSparkRunner;
import io.floci.aws.services.emrserverless.SessionServers;
import io.floci.aws.services.emrserverless.SparkJobRunner;
import io.floci.aws.services.iam.IamService;
import jakarta.annotation.PreDestroy;
@@ -32,6 +34,7 @@ import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.math.BigDecimal;
import java.net.http.HttpClient;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
@@ -140,7 +143,19 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
// to 1000 concurrent job runs", and "buffered jobs fail after 30 minutes if no slot frees up".
private static final int DEFAULT_MAX_CONCURRENT_JOB_RUNS = 1000;
private static final Duration QUEUE_TIMEOUT = Duration.ofMinutes(30);
private static final Set<String> FINISHED_ENDPOINT_STATES = Set.of(TERMINATED, "TERMINATED_WITH_ERRORS");
private static final String CREATING = "CREATING";
private static final String TERMINATING = "TERMINATING";
private static final String TERMINATED_WITH_ERRORS = "TERMINATED_WITH_ERRORS";
private static final Set<String> FINISHED_ENDPOINT_STATES = Set.of(TERMINATED, TERMINATED_WITH_ERRORS);
/** The path under Floci's base URL that an endpoint's serverUrl is, its id after it. */
static final String GATEWAY_PATH = "/_aws/emr-containers/endpoints/";
// No source gives AWS's wording for an endpoint whose gateway failed; these are Floci's.
static final String GATEWAY_NOT_STARTED = "The endpoint's Jupyter Enterprise Gateway could not start: %s";
static final String GATEWAY_EXITED = "The endpoint's Jupyter Enterprise Gateway exited with code %d.";
static final String GATEWAY_ENDED = "The endpoint's Jupyter Enterprise Gateway ended with no exit code.";
static final String GATEWAY_SILENT = "The endpoint's Jupyter Enterprise Gateway did not answer within "
+ SessionServers.START_LIMIT.toMinutes() + " minutes: %s";
static final String GATEWAY_LOST = "The endpoint's Jupyter Enterprise Gateway stopped with Floci.";
private static final String TOKEN_CREDENTIAL = "TOKEN";
private static final int DEFAULT_SESSION_SECONDS = 15 * 60;
private static final int MAX_SESSION_SECONDS = 12 * 60 * 60;
@@ -173,6 +188,9 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
private final String dockerNetwork;
// Where a retry waits for its backoff in the docker runner mode; null in the immediate one.
private final Delays delays;
// The managed endpoints' gateways in the docker runner mode; null in the immediate one.
private final EndpointGateways gateways;
private final GatewayOwner gatewayOwner = new GatewayOwner();
// The ARNs of the runs whose containers a thread of this process runs; a launched run not here was left by a
// restart.
private final Set<String> executing = new HashSet<>();
@@ -194,7 +212,12 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
Executors.newCachedThreadPool(Thread.ofPlatform().daemon().name("emr-containers-run-", 0).factory()),
config.services().emrcontainers().imageTemplate().orElse(null),
config.services().emrcontainers().dockerNetwork().orElse(null),
RUNNER_DOCKER.equalsIgnoreCase(config.services().emrcontainers().runnerMode()) ? Delays.timer() : null);
RUNNER_DOCKER.equalsIgnoreCase(config.services().emrcontainers().runnerMode()) ? Delays.timer() : null,
RUNNER_DOCKER.equalsIgnoreCase(config.services().emrcontainers().runnerMode())
? EndpointGateways.of(sparkRunner, clock,
config.services().emrcontainers().gatewayImageTemplate().orElse(null),
config.effectiveBaseUrl())
: null);
// Before any run of this process starts: a driver an earlier one left belongs to a run read as FAILED.
if (this.sparkRunner != null && config.services().emrcontainers().reconcileContainersOnStartup()) {
sparkRunner.removeLeftoverDrivers(SERVICE);
@@ -211,7 +234,7 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
int jobRunDurationSeconds) {
this(virtualClusters, jobRuns, endpoints, jobTemplates, securityConfigurations, mapper, regionResolver,
eksService, iamService, requestContext, clock, jobRunDurationSeconds, null, Runnable::run, null, null,
null);
null, null);
}
EmrContainersService(AccountAwareStorageBackend<ObjectNode> virtualClusters,
@@ -222,7 +245,7 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
ObjectMapper mapper, RegionResolver regionResolver, EksService eksService,
IamService iamService, RequestContext requestContext, Clock clock,
int jobRunDurationSeconds, SparkJobRunner sparkRunner, Executor runExecutor,
String imageTemplate, String dockerNetwork, Delays delays) {
String imageTemplate, String dockerNetwork, Delays delays, EndpointGateways gateways) {
this.virtualClusters = virtualClusters;
this.jobRuns = jobRuns;
this.endpoints = endpoints;
@@ -240,6 +263,7 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
this.imageTemplate = imageTemplate;
this.dockerNetwork = dockerNetwork;
this.delays = delays;
this.gateways = gateways;
}
@PreDestroy
@@ -250,6 +274,26 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
if (delays != null) {
delays.close();
}
if (gateways != null) {
gateways.servers().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.
*/
record EndpointGateways(SessionServers servers, String imageTemplate, String baseUrl) {
static EndpointGateways of(SparkJobRunner runner, Clock clock, String imageTemplate, String baseUrl) {
HttpClient probes = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
return new EndpointGateways(new SessionServers(EmrContainersGateways.KIND, runner,
Executors.newCachedThreadPool(Thread.ofPlatform().daemon().name("emr-containers-gateway-", 0)
.factory()),
null, (host, port) -> EmrContainersGateways.unanswered(probes, host, port), clock),
imageTemplate, baseUrl);
}
}
/** Runs a task once its delay has passed, as a retry waits for its backoff; a test runs them when it chooses. */
@@ -619,7 +663,9 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
endpoint.put("arn", arn);
endpoint.put("virtualClusterId", virtualClusterId);
endpoint.set("type", request.get("type"));
endpoint.put("state", ACTIVE);
// "Initially, your endpoint is in the CREATING state. After a few minutes, it transitions to the ACTIVE state"
// (EMR on EKS Development Guide, "Create an interactive endpoint"), once its gateway answers.
endpoint.put("state", gateways != null ? CREATING : ACTIVE);
endpoint.set("releaseLabel", request.get("releaseLabel"));
endpoint.set("executionRoleArn", request.get("executionRoleArn"));
copy(request, endpoint, "certificateArn", "configurationOverrides");
@@ -627,13 +673,18 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
endpoint.set("tags", tags(request.get("tags")));
endpoint.put(CLIENT_TOKEN, clientToken);
endpoints.put(arn, endpoint);
if (gateways != null) {
gateways.servers().launch(EmrContainersGateways.job(endpoint, gateways.imageTemplate(), dockerNetwork),
gatewayOwner);
}
return pick(endpoint, "id", "name", "arn", "virtualClusterId");
}
public synchronized ObjectNode describeManagedEndpoint(String virtualClusterId, String id) {
EmrContainersRequestShapes.check("DescribeManagedEndpoint",
object("id", id).put("virtualClusterId", virtualClusterId));
ObjectNode endpoint = endpoint(virtualClusterId, id).orElseThrow(() -> notFound(endpointMissing(id)));
ObjectNode endpoint = endpoint(virtualClusterId, id).map(this::settledEndpoint)
.orElseThrow(() -> notFound(endpointMissing(id)));
return wrap("endpoint", endpoint);
}
@@ -643,6 +694,7 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
EmrContainersRequestShapes.check("ListManagedEndpoints", shape);
String prefix = arn(VIRTUAL_CLUSTERS + virtualClusterId + ENDPOINTS);
List<ObjectNode> matching = endpoints.scan(key -> key.startsWith(prefix)).stream()
.map(this::settledEndpoint)
.filter(query::matches)
.filter(endpoint -> types == null || types.isEmpty()
|| types.contains(endpoint.path("type").textValue()))
@@ -653,11 +705,19 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
public synchronized ObjectNode deleteManagedEndpoint(String virtualClusterId, String id) {
EmrContainersRequestShapes.check("DeleteManagedEndpoint",
object("id", id).put("virtualClusterId", virtualClusterId));
ObjectNode endpoint = endpoint(virtualClusterId, id).orElseThrow(() -> invalid(endpointMissing(id)));
if (!FINISHED_ENDPOINT_STATES.contains(endpoint.path("state").textValue())) {
ObjectNode endpoint = endpoint(virtualClusterId, id).map(this::settledEndpoint)
.orElseThrow(() -> invalid(endpointMissing(id)));
String state = endpoint.path("state").textValue();
if (!FINISHED_ENDPOINT_STATES.contains(state) && !TERMINATING.equals(state)) {
ObjectNode terminated = endpoint.deepCopy();
terminated.put("state", TERMINATED);
boolean gatewayRuns = gateways != null && gateways.servers().runs(id);
// TERMINATING until its gateway has stopped.
terminated.put("state", gatewayRuns ? TERMINATING : TERMINATED);
endpoints.put(terminated.get("arn").textValue(), terminated);
if (gatewayRuns) {
// Off the request's thread, as stopping a container waits for Docker.
runExecutor.execute(() -> gateways.servers().stop(id));
}
}
return object("id", id).put("virtualClusterId", virtualClusterId);
}
@@ -667,7 +727,7 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
request.put("virtualClusterIdentifier", virtualClusterId);
request.put("endpointIdentifier", endpointId);
EmrContainersRequestShapes.check("GetManagedEndpointSessionCredentials", request);
ObjectNode endpoint = endpoint(virtualClusterId, endpointId)
ObjectNode endpoint = endpoint(virtualClusterId, endpointId).map(this::settledEndpoint)
.orElseThrow(() -> notFound(endpointMissing(endpointId)));
if (!ACTIVE.equals(endpoint.path("state").textValue())) {
throw invalid("Endpoint " + endpointId + " is " + endpoint.path("state").textValue()
@@ -683,14 +743,176 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
if (seconds < 1 || seconds > MAX_SESSION_SECONDS) {
throw invalid("durationInSeconds must be between 1 and " + MAX_SESSION_SECONDS + ".");
}
ObjectNode credentials = object("token", sessionToken());
String token = sessionToken();
Instant expiresAt = now().plusSeconds(seconds);
// "The token acts as proof of authentication to connect to the interactive endpoint server" ("Retrieve an auth
// token to connect to the interactive endpoint").
if (gateways != null) {
gateways.servers().grant(token, endpointId, regionResolver.getAccountId(), regionResolver.getRegion(),
expiresAt);
}
ObjectNode credentials = object("token", token);
ObjectNode response = object("id", newId(JOB_RUN_ID_LENGTH));
response.set("credentials", credentials);
response.set("endpointCredentials", credentials.deepCopy());
response.put("expiresAt", timestamp(now().plusSeconds(seconds)));
response.put("expiresAt", timestamp(expiresAt));
return response;
}
/**
* Where a call to endpoint {@code endpointId}'s gateway carrying {@code token} goes: empty for a token not given
* for that endpoint, as in the immediate runner mode, where no gateway runs; refused for an expired one, or while
* the endpoint is not ACTIVE; else its gateway. Called off the event loop, as the account and Region of none.
*/
public Optional<SparkConnectTargets.Route> gatewayRoute(String endpointId, String token) {
return gateways == null || token == null ? Optional.empty()
: gateways.servers().route(token, endpointId, gatewayOwner);
}
/**
* 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.
*/
private ObjectNode settledEndpoint(ObjectNode endpoint) {
String state = endpoint.path("state").textValue();
if (gateways == null || FINISHED_ENDPOINT_STATES.contains(state)
|| gateways.servers().runs(endpoint.get("id").textValue())) {
return endpoint;
}
ObjectNode ended = endpoint.deepCopy();
if (TERMINATING.equals(state)) {
ended.put("state", TERMINATED);
} else {
endWithErrors(ended, GATEWAY_LOST);
}
endpoints.put(ended.get("arn").textValue(), ended);
return ended;
}
private static void endWithErrors(ObjectNode endpoint, String details) {
endpoint.put("state", TERMINATED_WITH_ERRORS);
endpoint.put("stateDetails", details);
endpoint.put("failureReason", INTERNAL_ERROR);
endpoint.remove("serverUrl");
}
// The stored endpoint of that id, in the account and Region the call runs as.
private Optional<ObjectNode> endpointById(String id) {
return endpoints.scan(key -> key.endsWith(ENDPOINTS + id)).stream().findFirst();
}
/**
* The endpoints as their gateways' owner: CREATING until the gateway answers, then ACTIVE with its
* {@code serverUrl} and AWS's "Endpoint created successfully. It took 3 Minutes 15 Seconds" for the time it took
* ("Retrieve the gateway server URL of your interactive endpoint"); TERMINATED once a deleted endpoint's gateway
* has stopped, and TERMINATED_WITH_ERRORS, with INTERNAL_ERROR, when it stops otherwise or never answers. Each
* step is taken under the service's lock.
*/
private final class GatewayOwner implements SessionServers.Owner {
@Override
public void running(String endpointId) {
}
@Override
public void answering(String endpointId) {
synchronized (EmrContainersService.this) {
endpointById(endpointId).filter(stored -> CREATING.equals(stored.path("state").textValue()))
.ifPresent(stored -> {
ObjectNode active = stored.deepCopy();
Duration took = Duration.between(Instant.parse(stored.get("createdAt").textValue()),
now());
active.put("state", ACTIVE);
active.put("serverUrl", serverUrl(endpointId));
active.put("stateDetails", "Endpoint created successfully. It took "
+ took.toMinutes() + " Minutes " + took.toSecondsPart() + " Seconds");
endpoints.put(active.get("arn").textValue(), active);
LOG.infov("EMR on EKS endpoint {0} is ACTIVE", endpointId);
});
}
}
@Override
public void silent(String endpointId, String why) {
synchronized (EmrContainersService.this) {
endpointById(endpointId).filter(stored -> CREATING.equals(stored.path("state").textValue()))
.ifPresent(stored -> {
ObjectNode failed = stored.deepCopy();
endWithErrors(failed, String.format(GATEWAY_SILENT, why));
endpoints.put(failed.get("arn").textValue(), failed);
});
}
}
@Override
public void stopped(String endpointId, SparkJobRunner.Outcome outcome) {
synchronized (EmrContainersService.this) {
endpointById(endpointId)
.filter(stored -> !FINISHED_ENDPOINT_STATES.contains(stored.path("state").textValue()))
.ifPresent(stored -> {
ObjectNode ended = stored.deepCopy();
if (TERMINATING.equals(stored.path("state").textValue())) {
ended.put("state", TERMINATED);
ended.remove("serverUrl");
} else if (outcome.stopped()) {
// Stopped with no delete asking for it: Floci is shutting down, its kernels going
// with the gateway, as they do when a restart leaves one behind.
endWithErrors(ended, GATEWAY_LOST);
} else {
endWithErrors(ended, outcome.failure() != null
? String.format(GATEWAY_NOT_STARTED, outcome.failure())
: outcome.exitCode() != null
? String.format(GATEWAY_EXITED, outcome.exitCode()) : GATEWAY_ENDED);
}
endpoints.put(ended.get("arn").textValue(), ended);
LOG.infov("EMR on EKS endpoint {0} is {1}", endpointId,
ended.get("state").textValue());
});
}
}
@Override
public boolean starting(String endpointId) {
return inState(endpointId, CREATING);
}
@Override
public boolean going(String endpointId) {
return inState(endpointId, CREATING) || inState(endpointId, ACTIVE);
}
@Override
public String refusal(String endpointId) {
synchronized (EmrContainersService.this) {
String state = endpointById(endpointId).map(stored -> stored.path("state").textValue())
.orElse(TERMINATED);
return ACTIVE.equals(state) ? null : "Endpoint " + endpointId + " is " + state + ".";
}
}
@Override
public void busy(String endpointId) {
}
@Override
public void idle(String endpointId) {
}
private boolean inState(String endpointId, String state) {
synchronized (EmrContainersService.this) {
return endpointById(endpointId).filter(stored -> state.equals(stored.path("state").textValue()))
.isPresent();
}
}
}
// An endpoint's serverUrl: its path under Floci's base URL, which Floci's proxy serves.
private String serverUrl(String endpointId) {
String base = gateways.baseUrl() == null ? "" : gateways.baseUrl().endsWith("/")
? gateways.baseUrl().substring(0, gateways.baseUrl().length() - 1) : gateways.baseUrl();
return base + GATEWAY_PATH + endpointId;
}
// ── Security configurations ──────────────────────────────────────────────────
public synchronized ObjectNode createSecurityConfiguration(ObjectNode request) {
@@ -835,12 +1057,18 @@ public class EmrContainersService implements Resettable, StoredResourceArns {
public synchronized void beforeReset() {
generation++;
executing.clear();
if (gateways != null) {
gateways.servers().reset();
}
}
@Override
public synchronized void clear() {
generation++;
executing.clear();
if (gateways != null) {
gateways.servers().reset();
}
virtualClusters.clear();
jobRuns.clear();
endpoints.clear();
@@ -42,8 +42,8 @@ final class EmrContainersSparkJobs {
private static final String DRIVER_CONTAINER_IMAGE = "spark.kubernetes.driver.container.image";
private static final String DRIVER_ENV_PREFIX = "spark.kubernetes.driverEnv.";
// The base image's spark-defaults.conf runs a driver in Kubernetes' cluster mode, which local mode refuses.
private static final String DEPLOY_MODE = "spark.submit.deployMode";
private static final String CLIENT = "client";
static final String DEPLOY_MODE = "spark.submit.deployMode";
static final String CLIENT = "client";
private static final String SPARK_SQL = "spark-sql";
// A release label is its image's repository and tag joined by a hyphen: emr-7.2.0-20240610 runs the image tagged
// emr-7.2.0:20240610, and emr-7.2.0-java11-latest the one tagged emr-7.2.0-java11:latest.
@@ -227,8 +227,16 @@ public final class SessionServers {
* session takes until it ends.
*/
public Optional<Route> route(String token, Owner owner) {
return route(token, null, owner);
}
/**
* {@link #route(String, Owner)}, for a call to the server of session {@code sessionId} alone: a token given for
* another session is not one of its, and empty too.
*/
public Optional<Route> route(String token, String sessionId, Owner owner) {
Grant grant = grants.get(token);
if (grant == null) {
if (grant == null || sessionId != null && !sessionId.equals(grant.sessionId())) {
return Optional.empty();
}
if (!clock.instant().isBefore(grant.expiresAt())) {