From 29e262e7831f354e832a040683a8d3adeb1d9b5d Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Mon, 23 Nov 2026 06:39:56 -0400 Subject: [PATCH] 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. --- .github/ci/prefetch-images.sh | 4 + .github/workflows/nightly-checks.yml | 9 +- docs/services/emr-containers.md | 53 ++- .../io/floci/aws/config/EmulatorConfig.java | 10 + .../aws/core/common/WebSocketUpgrades.java | 20 ++ .../cloudfront/CloudFrontWebSocketProxy.java | 16 +- .../EmrContainersGatewayProxy.java | 303 ++++++++++++++++++ .../emrcontainers/EmrContainersGateways.java | 198 ++++++++++++ .../emrcontainers/EmrContainersService.java | 252 ++++++++++++++- .../emrcontainers/EmrContainersSparkJobs.java | 4 +- .../emrserverless/SessionServers.java | 10 +- ...ntainersGatewayNightlyIntegrationTest.java | 249 ++++++++++++++ .../EmrContainersGatewayProxyTest.java | 217 +++++++++++++ .../EmrContainersServiceTest.java | 249 +++++++++++++- 14 files changed, 1557 insertions(+), 37 deletions(-) create mode 100644 src/main/java/io/floci/aws/services/emrcontainers/EmrContainersGatewayProxy.java create mode 100644 src/main/java/io/floci/aws/services/emrcontainers/EmrContainersGateways.java create mode 100644 src/test/java/io/floci/aws/services/emrcontainers/EmrContainersGatewayNightlyIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/emrcontainers/EmrContainersGatewayProxyTest.java diff --git a/.github/ci/prefetch-images.sh b/.github/ci/prefetch-images.sh index e1c85262fb..e43d63caeb 100755 --- a/.github/ci/prefetch-images.sh +++ b/.github/ci/prefetch-images.sh @@ -146,6 +146,10 @@ starts EmrSessionServerNightlyIntegrationTest && ecr public.ecr.aws/emr-serverle # The nightly EmrContainersSparkNightlyIntegrationTest runs EMR on EKS job runs in the emr-7.5.0 release's EMR on EKS # base image, about 5 GB. starts EmrContainersSparkNightlyIntegrationTest && ecr public.ecr.aws/emr-on-eks/spark/emr-7.5.0:latest +# The nightly EmrContainersGatewayNightlyIntegrationTest runs an EMR on EKS managed endpoint's gateway and a PySpark +# kernel in the emr-7.5.0 release's notebook-spark image, about 6 GB. +starts EmrContainersGatewayNightlyIntegrationTest \ + && ecr public.ecr.aws/emr-on-eks/notebook-spark/emr-7.5.0:latest # package token in shard.txt -> images its tests are known to launch # (measured inline pulls; update alongside image-catalog changes) diff --git a/.github/workflows/nightly-checks.yml b/.github/workflows/nightly-checks.yml index 07725a075f..8df42cdd32 100644 --- a/.github/workflows/nightly-checks.yml +++ b/.github/workflows/nightly-checks.yml @@ -34,8 +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, 100 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 twelve-minute method and 21-minute + # image pull, 133 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: @@ -43,7 +44,7 @@ jobs: - group: standard timeout: 359 - group: docker-runner - timeout: 120 + timeout: 153 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. @@ -75,7 +76,7 @@ jobs: mv selected.txt all-nightly.txt fi fi - runner='/(EmrDockerRunner|EmrClusterShrink|EmrContainersSpark)NightlyIntegrationTest$' + runner='/(EmrDockerRunner|EmrClusterShrink|EmrContainersSpark|EmrContainersGateway)NightlyIntegrationTest$' if [ "$GROUP" = "docker-runner" ]; then grep -E "$runner" all-nightly.txt > nightly.txt || true else diff --git a/docs/services/emr-containers.md b/docs/services/emr-containers.md index ac6e699d0d..2b161b63ca 100644 --- a/docs/services/emr-containers.md +++ b/docs/services/emr-containers.md @@ -16,9 +16,10 @@ container (see [Running job runs](#running-job-runs)). |-----|-------------|---------| | `floci.services.emrcontainers.enabled` | Whether the EMR on EKS API is enabled | `true` | | `floci.services.emrcontainers.job-run-duration-seconds` | In the `immediate` runner mode, how long a job run stays `RUNNING` before it is `COMPLETED`; `0` completes it as soon as it is submitted | `0` | -| `floci.services.emrcontainers.runner-mode` | `immediate` moves job runs through their states without running anything; `docker` runs each job run's Spark job in a container (see [Running job runs](#running-job-runs)) | `immediate` | +| `floci.services.emrcontainers.runner-mode` | `immediate` moves job runs through their states without running anything; `docker` runs each job run's Spark job in a container (see [Running job runs](#running-job-runs)), and each managed endpoint's Jupyter Enterprise Gateway (see [Running managed endpoints](#running-managed-endpoints)) | `immediate` | | `floci.services.emrcontainers.docker-network` | Docker network for job run containers | the global default | | `floci.services.emrcontainers.image-template` | Image for a `docker` job run that names no custom image, `%s` standing for its release's container image tag, `emr-7.2.0:20240610` for `emr-7.2.0-20240610` | `public.ecr.aws/emr-on-eks/spark/%s` | +| `floci.services.emrcontainers.gateway-image-template` | Image a `docker` managed endpoint's gateway and kernels run in, `%s` standing for its release's container image tag | `public.ecr.aws/emr-on-eks/notebook-spark/%s` | | `floci.services.emrcontainers.reconcile-containers-on-startup` | Remove the drivers a previous run of this Floci left on the Docker daemon before the first job run starts; turn it off when two Floci instances share a daemon with the same port and no resource namespace | `true` | | `floci.storage.services.emrcontainers.mode` | Storage mode for EMR on EKS resources | the global storage mode | | `floci.storage.services.emrcontainers.flush-interval-ms` | Flush interval for persistent storage | `5000` | @@ -106,8 +107,9 @@ parameter's value in `jobTemplateParameters`, or else its `defaultValue`. A decl neither, or a `NUMBER` parameter whose value is not a number, is refused with `ValidationException`; a placeholder no parameter declares stays as written. -**Managed endpoints.** An endpoint is `ACTIVE` as soon as it is created and `TERMINATED` once deleted. -Floci runs no Jupyter Enterprise Gateway, so an endpoint has no `serverUrl`. +**Managed endpoints.** In the `immediate` runner mode, an endpoint is `ACTIVE` as soon as it is created and +`TERMINATED` once deleted, and has no `serverUrl`, as nothing runs it; in the `docker` one it runs a Jupyter +Enterprise Gateway (see [Running managed endpoints](#running-managed-endpoints)). `GetManagedEndpointSessionCredentials` accepts the `TOKEN` credential type alone and a duration of up to 12 hours, 15 minutes by default, as the API reference gives them, and answers a random token. @@ -198,3 +200,48 @@ wrapper with `FLOCI_SERVICES_EMRCONTAINERS_RUNNER_MODE=docker` (see [Docker](../ makes its next attempt. A driver that cannot start, or that Floci stopped, is not retried. Floci sends no EMR on EKS events, so there is no `EMR Job Run New Driver Attempt` event for each new driver. * **Not emulated yet**: a run waits for its container however long it takes, with no `job-start-timeout`. + +## Running managed endpoints + +With `runner-mode` set to `docker`, a managed endpoint runs the Jupyter Enterprise Gateway that "provides the +remote kernel lifecycle management capability that interactive clients need" (EMR on EKS Development Guide, +"Overview of interactive endpoints"), so a self-hosted Jupyter or JupyterLab can run kernels on it as the guide's +"Example: Deploy a JupyterLab notebook" does, with `JUPYTER_GATEWAY_URL` set to the endpoint's `serverUrl` and +`JUPYTER_GATEWAY_AUTH_TOKEN` to a token `GetManagedEndpointSessionCredentials` gave for it. + +* **Image**: the gateway and its kernels run in one container of the release's `notebook-spark` image on Amazon + ECR Public, the base image of interactive endpoints ("the base image URI in your Docker file must use + notebook-spark in place of spark"), so `emr-7.5.0-latest` runs + `public.ecr.aws/emr-on-eks/notebook-spark/emr-7.5.0:latest`. 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. The first + endpoint of a release pulls its image. The container gets the endpoint's execution role's credentials and the + `spark-defaults` of its `configurationOverrides`, and reaches Floci's S3, as a job run's driver does. +* **States**: an endpoint is `CREATING` until its gateway answers ("Initially, your endpoint is in the CREATING + state"), then `ACTIVE`, with its `serverUrl` and `stateDetails` "Endpoint created successfully. It took + *m* Minutes *s* Seconds", the guide's wording. `DeleteManagedEndpoint` makes it `TERMINATING` until its gateway + has stopped, then `TERMINATED`. A gateway that cannot start, exits or does not answer within 10 minutes ends its + endpoint `TERMINATED_WITH_ERRORS`, with `failureReason` `INTERNAL_ERROR` and a `stateDetails` of Floci's own, as + does Floci shutting down, and a restart that finds an endpoint still `CREATING` or `ACTIVE`, once it is read + again: its kernels go with the container. +* **serverUrl**: Floci's own port, at `/_aws/emr-containers/endpoints/` under Floci's base URL, as + every URL Floci gives is (`FLOCI_BASE_URL`, its host replaced by `FLOCI_HOSTNAME` where that is set; see + [Docker Compose](../configuration/docker-compose.md)). A client that reaches Floci at another address, such as a + port Testcontainers maps, joins that path to the address it uses. A request there goes to the + endpoint's gateway, its kernels' WebSocket tunnelled through, when it carries a token given for that endpoint and + not yet expired, as Jupyter Enterprise Gateway takes one: its last `token` parameter, else an `Authorization: token + ` header, which is what a Jupyter client sends. Any other request gets that gateway's 401 + `{"reason": "Unauthorized", "message": ""}`, an expired token's with a message saying so, and one to an endpoint + that is not `ACTIVE` gets 503. +* **Kernels**: the image's `python3` ("Python 3"), and `spark-python-kubernetes` ("PySpark on Kubernetes", the + name the guide's `jupyter-kernel-overrides` example gives it), whose `spark` and `sc` are a Spark session in + Spark's local mode, where EMR on EKS runs each kernel and its executors in pods of their own. It runs on the image's + Python, with `spark.pyspark.virtualenv.enabled` set to `false`: the image's `spark-defaults.conf` turns the + virtualenv on, and `spark-submit` makes one on YARN and Kubernetes alone. As Jupyter Enterprise + Gateway does, a kernel gets the `KERNEL_` variables of its start request's `env`, which a Jupyter client sends from + its own environment; `KERNEL_EXTRA_SPARK_OPTS`, "additional Spark configurations for the Spark kernels", goes to + the PySpark kernel's `spark-submit`. +* **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. diff --git a/src/main/java/io/floci/aws/config/EmulatorConfig.java b/src/main/java/io/floci/aws/config/EmulatorConfig.java index 8c286771e0..85f12ed646 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -1239,6 +1239,16 @@ public interface EmulatorConfig { */ Optional 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 gatewayImageTemplate(); + /** * When true, Floci removes, in the {@code docker} runner mode, every EMR on EKS driver a previous run of * this same Floci left on the daemon before its first job run starts. Turn it off when two Floci diff --git a/src/main/java/io/floci/aws/core/common/WebSocketUpgrades.java b/src/main/java/io/floci/aws/core/common/WebSocketUpgrades.java index 321281ec4c..e7662edcad 100644 --- a/src/main/java/io/floci/aws/core/common/WebSocketUpgrades.java +++ b/src/main/java/io/floci/aws/core/common/WebSocketUpgrades.java @@ -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 diff --git a/src/main/java/io/floci/aws/services/cloudfront/CloudFrontWebSocketProxy.java b/src/main/java/io/floci/aws/services/cloudfront/CloudFrontWebSocketProxy.java index e3fa262e97..e8b788f1da 100644 --- a/src/main/java/io/floci/aws/services/cloudfront/CloudFrontWebSocketProxy.java +++ b/src/main/java/io/floci/aws/services/cloudfront/CloudFrontWebSocketProxy.java @@ -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); - } } diff --git a/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersGatewayProxy.java b/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersGatewayProxy.java new file mode 100644 index 0000000000..4d1649addf --- /dev/null +++ b/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersGatewayProxy.java @@ -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 } 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 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.>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 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 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 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 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()); + } +} diff --git a/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersGateways.java b/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersGateways.java new file mode 100644 index 0000000000..3653d2ff72 --- /dev/null +++ b/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersGateways.java @@ -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. + * + *

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 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); + environment.put(PROGRAM_VARIABLE, PROGRAM); + List 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"; + } + } +} 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 d1f107c8a1..51ce26913f 100644 --- a/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersService.java +++ b/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersService.java @@ -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 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 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 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 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 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 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 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(); diff --git a/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersSparkJobs.java b/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersSparkJobs.java index e2aa5442c0..bad9c65818 100644 --- a/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersSparkJobs.java +++ b/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersSparkJobs.java @@ -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. diff --git a/src/main/java/io/floci/aws/services/emrserverless/SessionServers.java b/src/main/java/io/floci/aws/services/emrserverless/SessionServers.java index f08363e1f6..70d09c083b 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/SessionServers.java +++ b/src/main/java/io/floci/aws/services/emrserverless/SessionServers.java @@ -227,8 +227,16 @@ public final class SessionServers { * session takes until it ends. */ public Optional 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(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())) { diff --git a/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersGatewayNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersGatewayNightlyIntegrationTest.java new file mode 100644 index 0000000000..302939f3b3 --- /dev/null +++ b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersGatewayNightlyIntegrationTest.java @@ -0,0 +1,249 @@ +package io.floci.aws.services.emrcontainers; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.PullImageResultCallback; +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.CloudFormationSettingsProfile; +import io.floci.aws.testing.DockerAvailability; +import io.floci.aws.testing.EksRequests; +import io.floci.aws.testing.EnforcementFixtures; +import io.floci.aws.testing.PartitionCleanup; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.floci.aws.testing.S3TestClients; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.RestAssured; +import io.restassured.specification.RequestSpecification; +import jakarta.inject.Inject; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.api.extension.RegisterExtension; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; + +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.net.http.WebSocket; +import java.time.Duration; +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; + +import static io.restassured.RestAssured.given; +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +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 + * WebSocket, as the guide's "Example: Deploy a JupyterLab notebook" does through {@code JUPYTER_GATEWAY_URL}. + * + *

A nightly check: the release's notebook image is about 6 GB. + */ +@QuarkusTest +@TestProfile(CloudFormationSettingsProfile.class) +@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true") +// One instance, so that the image is pulled once for the class. +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +// The endpoint's gateway answers within its five minutes, the kernel's WebSocket opens within its two, once its Spark +// session is up, and each of its two cells answers within its two: eleven minutes, and one for the requests between. +// With the image's pull of up to 21, 33 minutes, which the Nightly checks' docker-runner group counts. +@Timeout(value = 12, unit = TimeUnit.MINUTES) +class EmrContainersGatewayNightlyIntegrationTest { + + private static final String ACCOUNT = "000000000000"; + private static final String REGION = "us-east-1"; + private static final String ROLE = "arn:aws:iam::000000000000:role/emr-job"; + private static final String RELEASE = "emr-7.5.0-latest"; + // The release's notebook image, which the gateway's default template names. + private static final String NOTEBOOK_IMAGE = "public.ecr.aws/emr-on-eks/notebook-spark/emr-7.5.0:latest"; + private static final Duration ACTIVE_TIMEOUT = Duration.ofMinutes(5); + // jupyter_server holds a kernel's handshake until the kernel answers, up to its own minute, and the PySpark kernel + // answers once its Spark session is up. + private static final Duration HANDSHAKE_TIMEOUT = Duration.ofMinutes(2); + private static final Duration REPLY_TIMEOUT = Duration.ofMinutes(2); + private static final ObjectMapper JSON = new ObjectMapper(); + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @Inject + DockerClient docker; + + @BeforeAll + static void configure() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + // The notebook image's pull alone may take its twenty minutes. + @BeforeAll + @Timeout(value = 21, unit = TimeUnit.MINUTES) + void pullImage() throws InterruptedException { + // Enabled, the check needs Docker: without a daemon it fails rather than pass having run nothing. + assertTrue(DockerAvailability.isAvailable(), "the nightly check needs a Docker daemon"); + docker.pullImageCmd(NOTEBOOK_IMAGE).exec(new PullImageResultCallback()).awaitCompletion(20, TimeUnit.MINUTES); + } + + @Test + void pysparkKernelOnTheEndpointsGatewayRunsCodeOnFlocisS3() throws Exception { + S3Client s3 = AwsTestClients.create(S3Client.builder().forcePathStyle(true), ACCOUNT, Region.US_EAST_1); + cleanup.register(s3::close); + String bucket = "emr-eks-jeg-" + 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(); + String endpointId = emr().body(""" + {"name": "nightly", "type": "JUPYTER_ENTERPRISE_GATEWAY", "releaseLabel": "%s", + "executionRoleArn": "%s", "clientToken": "%s"} + """.formatted(RELEASE, ROLE, UUID.randomUUID())) + .post("/virtualclusters/" + virtualClusterId + "/endpoints") + .then().statusCode(200) + .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"))); + String serverUrl = emr().get("/virtualclusters/" + virtualClusterId + "/endpoints/" + endpointId) + .then().extract().path("endpoint.serverUrl"); + // On the profile's base URL; the test's own server is on a port of its own. + 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"); + + HttpClient http = HttpClient.newHttpClient(); + assertEquals(401, http.send(HttpRequest.newBuilder(URI.create(gateway + "/api/kernelspecs")).build(), + HttpResponse.BodyHandlers.discarding()).statusCode(), "a request without the session token"); + HttpResponse specs = http.send(HttpRequest.newBuilder(URI.create(gateway + "/api/kernelspecs")) + .header("Authorization", "token " + token).build(), HttpResponse.BodyHandlers.ofString()); + assertEquals(200, specs.statusCode(), specs.body()); + assertTrue(JSON.readTree(specs.body()).path("kernelspecs").has("spark-python-kubernetes"), specs.body()); + // As a Jupyter client sends its KERNEL_ variables. + HttpResponse started = http.send(HttpRequest.newBuilder(URI.create(gateway + "/api/kernels")) + .header("Authorization", "token " + token) + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(""" + {"name": "spark-python-kubernetes", + "env": {"KERNEL_EXTRA_SPARK_OPTS": "--conf spark.app.name=from-kernel-env"}} + """)).build(), HttpResponse.BodyHandlers.ofString()); + assertEquals(201, started.statusCode(), started.body()); + String kernelId = JSON.readTree(started.body()).path("id").textValue(); + + Messages messages = new Messages(); + WebSocket socket = http.newWebSocketBuilder().header("Authorization", "token " + token) + .buildAsync(URI.create(gateway.replaceFirst("^http", "ws") + "/api/kernels/" + kernelId + + "/channels"), messages) + .get(HANDSHAKE_TIMEOUT.toSeconds(), TimeUnit.SECONDS); + String session = UUID.randomUUID().toString(); + assertEquals("3", execute(socket, messages, session, + "spark.read.text(\"s3://" + bucket + "/lines.txt\").count()")); + assertEquals("'from-kernel-env'", execute(socket, messages, session, "spark.conf.get(\"spark.app.name\")")); + socket.sendClose(WebSocket.NORMAL_CLOSURE, "done").get(10, TimeUnit.SECONDS); + assertEquals(204, http.send(HttpRequest.newBuilder(URI.create(gateway + "/api/kernels/" + kernelId)) + .header("Authorization", "token " + token).DELETE().build(), + HttpResponse.BodyHandlers.discarding()).statusCode()); + } + + // Runs code in the kernel, as a Jupyter client sends an execute_request, and answers its result's text/plain. + private static String execute(WebSocket socket, Messages messages, String session, String code) throws Exception { + String messageId = UUID.randomUUID().toString(); + ObjectNode request = JSON.createObjectNode(); + request.putObject("header").put("msg_id", messageId).put("username", "nightly").put("session", session) + .put("msg_type", "execute_request").put("version", "5.3").put("date", Instant.now().toString()); + request.putObject("parent_header"); + request.putObject("metadata"); + request.putObject("content").put("code", code).put("silent", false).put("store_history", true) + .put("allow_stdin", false).put("stop_on_error", true).putObject("user_expressions"); + request.putArray("buffers"); + request.put("channel", "shell"); + socket.sendText(JSON.writeValueAsString(request), true).get(10, TimeUnit.SECONDS); + return await("an execute_result for " + code).atMost(REPLY_TIMEOUT).pollInterval(Duration.ofMillis(100)) + .until(() -> result(messages, messageId), Objects::nonNull); + } + + // The text/plain of the result of the request messageId among the messages come so far, or null until it comes. + private static String result(Messages messages, String messageId) throws Exception { + for (String text = messages.received.poll(); text != null; text = messages.received.poll()) { + JsonNode message = JSON.readTree(text); + if (!messageId.equals(message.at("/parent_header/msg_id").textValue())) { + continue; + } + String type = message.at("/header/msg_type").textValue(); + if ("execute_result".equals(type)) { + return message.at("/content/data/text~1plain").textValue(); + } + if ("error".equals(type)) { + fail("the kernel raised: " + message.path("content")); + } + } + return null; + } + + private String virtualCluster() { + String eksCluster = "emr-" + UUID.randomUUID().toString().substring(0, 8); + EksRequests.eks(ACCOUNT, REGION) + .body(""" + {"name": "%s", "roleArn": "arn:aws:iam::000000000000:role/eks-role", "version": "1.29"} + """.formatted(eksCluster)) + .post("/clusters") + .then().statusCode(200); + cleanup.register(() -> EksRequests.eks(ACCOUNT, REGION).delete("/clusters/" + eksCluster) + .then().statusCode(200)); + String id = emr().body(""" + {"name": "nightly", "clientToken": "%s", + "containerProvider": {"type": "EKS", "id": "%s", "info": {"eksInfo": {"namespace": "spark"}}}} + """.formatted(UUID.randomUUID(), eksCluster)) + .post("/virtualclusters") + .then().statusCode(200) + .extract().path("id"); + cleanup.register(() -> emr().delete("/virtualclusters/" + id).then().statusCode(200)); + return id; + } + + private static RequestSpecification emr() { + return given().header("Authorization", EnforcementFixtures.auth(ACCOUNT, REGION, "emr-containers")) + .contentType("application/json") + .urlEncodingEnabled(false); + } + + /** The kernel's messages, each whole, as its WebSocket sends them. */ + private static final class Messages implements WebSocket.Listener { + final BlockingQueue received = new LinkedBlockingQueue<>(); + private final StringBuilder partial = new StringBuilder(); + + @Override + public CompletionStage onText(WebSocket webSocket, CharSequence data, boolean last) { + partial.append(data); + if (last) { + received.add(partial.toString()); + partial.setLength(0); + } + webSocket.request(1); + return null; + } + } +} diff --git a/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersGatewayProxyTest.java b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersGatewayProxyTest.java new file mode 100644 index 0000000000..4771fd591c --- /dev/null +++ b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersGatewayProxyTest.java @@ -0,0 +1,217 @@ +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.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.http.WebSocket; +import io.vertx.core.http.WebSocketConnectOptions; +import io.vertx.core.json.JsonObject; +import io.vertx.ext.web.Router; +import org.awaitility.Awaitility; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +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.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Requests to an endpoint's {@code serverUrl} through {@link EmrContainersGatewayProxy}: a server that echoes what it + * gets stands in for the endpoint's gateway, and the service's routes for its tokens. + */ +class EmrContainersGatewayProxyTest { + + private static final String ENDPOINT = "ep0123456789a"; + private static final String TOKEN = "a-session-token"; + private static final String BASE = EmrContainersService.GATEWAY_PATH + ENDPOINT; + + private final AtomicInteger requestsEnded = new AtomicInteger(); + private Vertx vertx; + private HttpServer gateway; + private HttpServer floci; + private HttpClient client; + private EmrContainersService service; + + @BeforeEach + void setUp() throws Exception { + vertx = Vertx.vertx(); + // A gateway that answers a request with what it got, and echoes each WebSocket message; at /partial it + // breaks off its answer after a part of the body it gave the length of. + gateway = await(vertx.createHttpServer().requestHandler(request -> { + if (WebSocketUpgrades.isHandshake(request)) { + request.toWebSocket().onSuccess(socket -> socket.textMessageHandler(message -> + socket.writeTextMessage("echo " + message + " on " + request.uri()))); + return; + } + if (request.path().equals("/partial")) { + request.response().putHeader("content-length", "100").write("partial") + .onComplete(written -> request.connection().close()); + return; + } + request.body().onSuccess(body -> request.response().setStatusCode(201) + .putHeader("content-type", "application/json") + .end(new JsonObject().put("method", request.method().name()).put("uri", request.uri()) + .put("authorization", request.getHeader("Authorization")) + .put("body", body.toString()).encode())); + }).listen(0, "127.0.0.1")); + service = mock(EmrContainersService.class); + when(service.gatewayRoute(anyString(), any())).thenReturn(Optional.empty()); + when(service.gatewayRoute(ENDPOINT, TOKEN)).thenAnswer(invocation -> Optional.of( + SparkConnectTargets.Route.to("127.0.0.1", gateway.actualPort(), requestsEnded::incrementAndGet))); + ServiceConfigAccess serviceConfigAccess = mock(ServiceConfigAccess.class); + when(serviceConfigAccess.isEnabled(eq(EmrContainersService.SERVICE))).thenReturn(true); + EmrContainersGatewayProxy proxy = new EmrContainersGatewayProxy(service, serviceConfigAccess, vertx); + Router router = Router.router(vertx); + proxy.register(router); + router.route().handler(context -> context.response().setStatusCode(404).end("not a gateway")); + 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 requestWithItsEndpointsTokenGoesToItsGatewayWithoutTheToken() throws Exception { + Answer byParameter = request(HttpMethod.POST, BASE + "/api/kernels?token=" + TOKEN + "&path=nb", null, + "{\"name\": \"python3\"}"); + Answer byHeader = request(HttpMethod.GET, BASE + "/api/kernelspecs", "token " + TOKEN, null); + + assertEquals(201, byParameter.status); + JsonObject gotByParameter = new JsonObject(byParameter.body); + assertEquals("POST", gotByParameter.getString("method")); + assertEquals("/api/kernels?path=nb", gotByParameter.getString("uri")); + assertEquals("{\"name\": \"python3\"}", gotByParameter.getString("body")); + JsonObject gotByHeader = new JsonObject(byHeader.body); + assertEquals("/api/kernelspecs", gotByHeader.getString("uri")); + // The token is Floci's to check, so the gateway never sees it. + assertNull(gotByHeader.getString("authorization")); + awaitCount(requestsEnded, 2); + } + + @Test + void queryIsReadAsTheGatewayReadsIt() throws Exception { + // Its last token parameter is the one checked, and a malformed escape stays as it came. + Answer answer = request(HttpMethod.GET, BASE + "/api/kernels?%GG=1&token=not-a-token&token=" + TOKEN, null, + null); + + assertEquals(201, answer.status); + assertEquals("/api/kernels?%GG=1", new JsonObject(answer.body).getString("uri")); + awaitCount(requestsEnded, 1); + } + + @Test + void answerTheGatewayBreaksOffBreaksOffTheViewers() { + ExecutionException broken = assertThrows(ExecutionException.class, + () -> request(HttpMethod.GET, BASE + "/partial", "token " + TOKEN, null)); + + assertTrue(broken.getCause().getMessage().toLowerCase().contains("closed"), broken.getCause().toString()); + awaitCount(requestsEnded, 1); + } + + @Test + void requestWithoutATokenGivenForItsEndpointGetsTheGatewaysUnauthorized() throws Exception { + Answer none = request(HttpMethod.GET, BASE + "/api/kernels", null, null); + Answer unknown = request(HttpMethod.GET, BASE + "/api/kernels", "token not-a-token", null); + Answer otherScheme = request(HttpMethod.GET, BASE + "/api/kernels", "Bearer " + TOKEN, null); + + for (Answer answer : new Answer[] {none, unknown, otherScheme}) { + assertEquals(401, answer.status); + assertEquals(new JsonObject().put("reason", "Unauthorized").put("message", ""), + new JsonObject(answer.body)); + } + } + + @Test + void requestTheServiceRefusesGetsItsReason() throws Exception { + when(service.gatewayRoute(ENDPOINT, "expired")).thenReturn(Optional.of(SparkConnectTargets.Route.refused( + SparkConnectTargets.Route.UNAUTHENTICATED, "The authentication token has expired."))); + when(service.gatewayRoute(ENDPOINT, "terminating")).thenReturn(Optional.of(SparkConnectTargets.Route.refused( + SparkConnectTargets.Route.UNAVAILABLE, "Endpoint " + ENDPOINT + " is TERMINATING."))); + + Answer expired = request(HttpMethod.GET, BASE + "/api/kernels", "token expired", null); + Answer terminating = request(HttpMethod.GET, BASE + "/api/kernels", "token terminating", null); + + assertEquals(401, expired.status); + assertEquals("The authentication token has expired.", new JsonObject(expired.body).getString("message")); + assertEquals(503, terminating.status); + assertEquals("Service Unavailable", new JsonObject(terminating.body).getString("reason")); + assertEquals("Endpoint " + ENDPOINT + " is TERMINATING.", + new JsonObject(terminating.body).getString("message")); + } + + @Test + void kernelsWebSocketIsTunnelledToTheGateway() throws Exception { + WebSocket socket = await(vertx.createWebSocketClient().connect(new WebSocketConnectOptions() + .setHost("127.0.0.1").setPort(floci.actualPort()) + .setURI(BASE + "/api/kernels/k1/channels?session_id=s1") + .addHeader("Authorization", "token " + TOKEN))); + CompletableFuture echoed = new CompletableFuture<>(); + socket.textMessageHandler(echoed::complete); + + socket.writeTextMessage("execute_request"); + + assertEquals("echo execute_request on /api/kernels/k1/channels?session_id=s1", + echoed.get(10, TimeUnit.SECONDS)); + await(socket.close()); + awaitCount(requestsEnded, 1); + } + + @Test + void kernelsWebSocketWithoutAValidTokenIsRefused() { + Exception refused = assertThrows(Exception.class, () -> await( + vertx.createWebSocketClient().connect(new WebSocketConnectOptions().setHost("127.0.0.1") + .setPort(floci.actualPort()).setURI(BASE + "/api/kernels/k1/channels")))); + assertTrue(refused.getMessage().contains("401"), refused.getMessage()); + } + + private Answer request(HttpMethod method, String uri, String authorization, String body) 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); + } + // 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))) + .compose(response -> response.body() + .map(read -> new Answer(response.statusCode(), read.toString())))); + } + + // Awaitility's, by name: this class's own await takes a Future. + private static void awaitCount(AtomicInteger count, int expected) { + Awaitility.await("requests ended").atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(10)) + .until(() -> count.get() >= expected); + assertEquals(expected, count.get()); + } + + 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/EmrContainersServiceTest.java b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersServiceTest.java index a434f46421..c9c1658289 100644 --- a/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersServiceTest.java +++ b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersServiceTest.java @@ -5,12 +5,14 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.SparkConnectTargets; import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.InMemoryStorage; 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.emrcontainers.EmrContainersService.ListQuery; +import io.floci.aws.services.emrserverless.SessionServers; import io.floci.aws.services.emrserverless.SparkJobRunner; import io.floci.aws.services.iam.IamService; import io.floci.aws.testing.MutableClock; @@ -28,9 +30,16 @@ import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; +import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; +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.assertThrows; @@ -696,7 +705,7 @@ class EmrContainersServiceTest { when(iam.resolveCallerArn(eq(null))).thenReturn(Optional.empty()); 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, executor, - "registry.internal/emr-on-eks/spark/%s", "floci-net", delays); + "registry.internal/emr-on-eks/spark/%s", "floci-net", delays, null); } private EmrContainersService dockerService(FakeRunner runner, QueuedExecutor executor) { @@ -1271,6 +1280,244 @@ class EmrContainersServiceTest { } } + // ── Managed endpoints' gateways ─────────────────────────────────────────────── + + // Why the gateways' probe finds none answering, until a test sets it to null. + private final AtomicReference gatewayUnanswered = new AtomicReference<>(); + + // A docker service whose endpoints' gateways run on threads of their own, Floci at http://floci.test:4566/. + private EmrContainersService gatewayService(GatewayRunner runner, + List> stores) { + IamService iam = mock(IamService.class); + when(iam.resolveCallerArn(eq(null))).thenReturn(Optional.empty()); + // A pool, as the service's own is, so that its shutdown interrupts the gateways' threads. + SessionServers servers = new SessionServers(EmrContainersGateways.KIND, runner, + Executors.newCachedThreadPool(Thread.ofPlatform().daemon().factory()), null, + (host, port) -> gatewayUnanswered.get(), clock); + 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, + "registry.internal/emr-on-eks/notebook-spark/%s", "http://floci.test:4566/")); + } + + private String gatewayEndpoint(EmrContainersService service, String clusterId) { + return service.createManagedEndpoint(clusterId, json(""" + {"name": "studio", "type": "JUPYTER_ENTERPRISE_GATEWAY", "releaseLabel": "%s", + "executionRoleArn": "%s", "clientToken": "%s", + "configurationOverrides": {"applicationConfiguration": [{"classification": "spark-defaults", + "properties": {"spark.sql.shuffle.partitions": "4", "spark.master": "k8s://https://eks.test:443", + "spark.submit.deployMode": "cluster", + "spark.kubernetes.driverEnv.SPARK_DIST_CLASSPATH": "/opt/extra/*"}}]}} + """.formatted(RELEASE, ROLE, UUID.randomUUID()))).get("id").textValue(); + } + + private static JsonNode endpoint(EmrContainersService service, String clusterId, String endpointId) { + return service.describeManagedEndpoint(clusterId, endpointId).get("endpoint"); + } + + // The endpoint once it is in that state, which a gateway's thread puts it in. + private static JsonNode awaitEndpoint(EmrContainersService service, String clusterId, String endpointId, + String state) { + return await("endpoint " + endpointId + " " + state).atMost(Duration.ofSeconds(10)) + .pollInterval(Duration.ofMillis(10)) + .until(() -> endpoint(service, clusterId, endpointId), endpoint -> state.equals(state(endpoint))); + } + + private String sessionToken(EmrContainersService service, String clusterId, String endpointId) { + return service.getManagedEndpointSessionCredentials(clusterId, endpointId, + json("{\"executionRoleArn\": \"%s\", \"credentialType\": \"TOKEN\"}".formatted(ROLE))) + .at("/credentials/token").textValue(); + } + + @Test + void dockerEndpointRunsItsGatewayAndIsActiveWithItsServerUrlOnceTheGatewayAnswers() { + GatewayRunner runner = new GatewayRunner(); + gatewayUnanswered.set("not yet"); + EmrContainersService service = gatewayService(runner, stores()); + String clusterId = virtualCluster(service, EKS_CLUSTER); + String endpointId = gatewayEndpoint(service, clusterId); + + JsonNode creating = endpoint(service, clusterId, endpointId); + assertEquals("CREATING", state(creating), "Initially, your endpoint is in the CREATING state"); + assertFalse(creating.has("serverUrl")); + SparkJobRunner.Job job = runner.awaitJob(endpointId); + assertEquals("registry.internal/emr-on-eks/notebook-spark/emr-7.5.0:latest", job.imageTemplate()); + assertEquals(EmrContainersGateways.PORT, job.listenPort()); + assertEquals(ROLE, job.executionRole()); + assertEquals("floci-net", job.dockerNetwork()); + assertEquals("4", job.sparkDefaults().get("spark.sql.shuffle.partitions")); + assertEquals("false", job.sparkDefaults().get(EmrContainersGateways.PYSPARK_VIRTUALENV), + "a kernel in Spark's local mode runs on the image's Python"); + assertFalse(job.sparkDefaults().containsKey("spark.master"), "the runner's local mode stands"); + assertEquals("client", job.sparkDefaults().get("spark.submit.deployMode")); + assertEquals("/opt/extra/*:" + EmrContainersGateways.AWS_SDK, + job.environment().get(EmrContainersGateways.CLASS_PATH_VARIABLE), + "a kernel's driver keeps the endpoint's class path and gains S3A's AWS SDK"); + assertEquals(EmrContainersGateways.PROGRAM, job.environment().get(EmrContainersGateways.PROGRAM_VARIABLE)); + assertTrue(job.command().get(2).endsWith("exec python3 /tmp/floci-gateway/gateway.py"), job.command().get(2)); + + clock.advance(Duration.ofMinutes(3).plusSeconds(15)); + gatewayUnanswered.set(null); + JsonNode active = awaitEndpoint(service, clusterId, endpointId, "ACTIVE"); + + assertEquals("http://floci.test:4566/_aws/emr-containers/endpoints/" + endpointId, + active.get("serverUrl").textValue()); + assertEquals("Endpoint created successfully. It took 3 Minutes 15 Seconds", + active.get("stateDetails").textValue()); + runner.stop(endpointId); + } + + @Test + void sessionTokenReachesItsOwnEndpointsGatewayUntilItExpires() { + GatewayRunner runner = new GatewayRunner(); + EmrContainersService service = gatewayService(runner, stores()); + String clusterId = virtualCluster(service, EKS_CLUSTER); + String endpointId = gatewayEndpoint(service, clusterId); + String otherId = gatewayEndpoint(service, clusterId); + awaitEndpoint(service, clusterId, endpointId, "ACTIVE"); + awaitEndpoint(service, clusterId, otherId, "ACTIVE"); + String token = sessionToken(service, clusterId, endpointId); + + SparkConnectTargets.Route route = service.gatewayRoute(endpointId, token).orElseThrow(); + assertEquals("127.0.0.1", route.host()); + assertEquals(GatewayRunner.PORT, route.port()); + route.ended().run(); + assertTrue(service.gatewayRoute(otherId, token).isEmpty(), "another endpoint's token is not its"); + assertTrue(service.gatewayRoute(endpointId, "not-a-token").isEmpty()); + assertTrue(service.gatewayRoute(endpointId, null).isEmpty()); + + clock.advance(Duration.ofMinutes(15)); + SparkConnectTargets.Route expired = service.gatewayRoute(endpointId, token).orElseThrow(); + assertEquals(SparkConnectTargets.Route.UNAUTHENTICATED, expired.status()); + assertEquals("The authentication token has expired. Call GetManagedEndpointSessionCredentials for a new " + + "one.", expired.refusal()); + runner.stop(endpointId); + runner.stop(otherId); + } + + @Test + void deletedDockerEndpointStopsItsGatewayAndItsTokensGo() { + 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"); + String token = sessionToken(service, clusterId, endpointId); + + service.deleteManagedEndpoint(clusterId, endpointId); + JsonNode terminated = awaitEndpoint(service, clusterId, endpointId, "TERMINATED"); + + assertTrue(runner.stopped.contains(endpointId)); + assertFalse(terminated.has("serverUrl")); + assertTrue(service.gatewayRoute(endpointId, token).isEmpty()); + } + + @Test + void dockerEndpointWhoseGatewayExitsIsTerminatedWithErrors() { + 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"); + + runner.end(endpointId, SparkJobRunner.Outcome.exitedWith(1)); + JsonNode failed = awaitEndpoint(service, clusterId, endpointId, "TERMINATED_WITH_ERRORS"); + + assertEquals("INTERNAL_ERROR", failed.get("failureReason").textValue()); + assertEquals("The endpoint's Jupyter Enterprise Gateway exited with code 1.", + failed.get("stateDetails").textValue()); + assertFalse(failed.has("serverUrl")); + } + + @Test + void dockerEndpointsGatewayStoppedWithFlociIsTerminatedWithErrors() { + 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"); + + service.shutdown(); + JsonNode lost = awaitEndpoint(service, clusterId, endpointId, "TERMINATED_WITH_ERRORS"); + + assertEquals("INTERNAL_ERROR", lost.get("failureReason").textValue()); + assertEquals("The endpoint's Jupyter Enterprise Gateway stopped with Floci.", + lost.get("stateDetails").textValue()); + assertFalse(lost.has("serverUrl")); + assertTrue(runner.stopped.isEmpty(), "nothing deleted it"); + } + + @Test + void dockerEndpointAnEarlierProcessRanIsTerminatedWithErrors() { + List> stores = stores(); + GatewayRunner earlierRunner = new GatewayRunner(); + EmrContainersService earlier = gatewayService(earlierRunner, stores); + String clusterId = virtualCluster(earlier, EKS_CLUSTER); + String endpointId = gatewayEndpoint(earlier, clusterId); + awaitEndpoint(earlier, clusterId, endpointId, "ACTIVE"); + + EmrContainersService restarted = gatewayService(new GatewayRunner(), stores); + JsonNode lost = endpoint(restarted, clusterId, endpointId); + + assertEquals("TERMINATED_WITH_ERRORS", state(lost)); + assertEquals("INTERNAL_ERROR", lost.get("failureReason").textValue()); + assertEquals("The endpoint's Jupyter Enterprise Gateway stopped with Floci.", + lost.get("stateDetails").textValue()); + earlierRunner.stop(endpointId); + } + + /** + * A runner whose gateways listen at once on 127.0.0.1:{@value #PORT} and run until they are stopped, interrupted, + * or ended as a test says. + */ + private static final class GatewayRunner implements SparkJobRunner { + static final int PORT = 18888; + final List jobs = new CopyOnWriteArrayList<>(); + final Set stopped = ConcurrentHashMap.newKeySet(); + private final Map> ends = new ConcurrentHashMap<>(); + + @Override + public Outcome run(Job job, Progress progress) { + jobs.add(job); + progress.started(); + progress.listening("127.0.0.1", PORT); + try { + return end(job.runId()).get(); + } catch (InterruptedException e) { + // As the Docker runner answers when Floci's shutdown interrupts it. + return Outcome.halted(); + } catch (ExecutionException e) { + throw new IllegalStateException(e); + } + } + + @Override + public void stop(String runId) { + stopped.add(runId); + end(runId, Outcome.halted()); + } + + @Override + public void removeLeftoverDrivers(String service) { + } + + void end(String runId, Outcome outcome) { + end(runId).complete(outcome); + } + + Job awaitJob(String runId) { + return await("a gateway started for " + runId).atMost(Duration.ofSeconds(10)) + .pollInterval(Duration.ofMillis(10)) + .until(() -> jobs.stream().filter(started -> started.runId().equals(runId)).findFirst(), + Optional::isPresent) + .get(); + } + + private CompletableFuture end(String runId) { + return ends.computeIfAbsent(runId, id -> new CompletableFuture<>()); + } + } + /** A runner that starts the driver at once, runs {@code whileRunning}, and ends as {@code outcome} says. */ private static final class FakeRunner implements SparkJobRunner { final List jobs = new ArrayList<>();