diff --git a/.github/ci/prefetch-images.sh b/.github/ci/prefetch-images.sh index 4aa3d0d08f..a55b5d8dba 100755 --- a/.github/ci/prefetch-images.sh +++ b/.github/ci/prefetch-images.sh @@ -127,6 +127,9 @@ starts EmrDockerRunnerDockerIntegrationTest EmrHiveStepsDockerIntegrationTest Em starts EmrServerlessHiveDockerIntegrationTest EmrHiveStepsDockerIntegrationTest EmrDockerRunnerDockerIntegrationTest \ EmrFlociContainerNightlyIntegrationTest EmrPigStepsNightlyIntegrationTest \ && ecr public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest +# The nightly EmrServerlessSparkConnectNightlyIntegrationTest runs a session's Spark Connect server, and its client, in +# the emr-7.13.0 image, 3.7 GB, the first release with sessions. +starts EmrServerlessSparkConnectNightlyIntegrationTest && ecr public.ecr.aws/emr-serverless/spark/emr-7.13.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 17f1258bd5..d7b5252909 100644 --- a/.github/workflows/nightly-checks.yml +++ b/.github/workflows/nightly-checks.yml @@ -30,11 +30,11 @@ jobs: runs-on: ubuntu-latest # The checks run one after another, each within its own @Timeout bounds, so the job allows their sum, and about # twenty minutes for the build, the image and the prefetch: EmrPigStepsNightlyIntegrationTest's 30, - # EmrFlociContainerNightlyIntegrationTest's 20 and 4 for its setup, and - # EmrServerlessCustomImageNightlyIntegrationTest's 85 and 21 for its setup, 160 in all. A check added, or a - # bound raised, raises this with it, so a slow check fails with its own message rather than the job being - # cancelled with none. - timeout-minutes: 180 + # EmrFlociContainerNightlyIntegrationTest's 20 and 4 for its setup, + # EmrServerlessCustomImageNightlyIntegrationTest's 85 and 21 for its setup, and + # EmrServerlessSparkConnectNightlyIntegrationTest's 30, 190 in all. A check added, or a bound raised, raises this + # with it, so a slow check fails with its own message rather than the job being cancelled with none. + timeout-minutes: 210 # 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. if: >- diff --git a/docs/services/emr-serverless.md b/docs/services/emr-serverless.md index 636b868999..a4d7355dbc 100644 --- a/docs/services/emr-serverless.md +++ b/docs/services/emr-serverless.md @@ -9,7 +9,7 @@ EMR Serverless is an AWS service that provides serverless data analytics environ | `floci.emrserverless.enabled` | Whether the EMR Serverless API is enabled | `true` | | `floci.emrserverless.port` | The port the service is exposed on | `4566` | | `floci.services.emrserverless.job-run-duration-seconds` | How long a `BATCH` job run stays `RUNNING` before it succeeds; `0` makes it `SUCCESS` as soon as it starts | `0` | -| `floci.services.emrserverless.runner-mode` | `immediate` moves job runs through their states without running anything; `docker` runs each job run in a container (see [Running Spark job runs](#running-spark-job-runs) and [Running Hive job runs](#running-hive-job-runs)) | `immediate` | +| `floci.services.emrserverless.runner-mode` | `immediate` moves job runs and sessions through their states without running anything; `docker` runs each job run, and each session's Spark Connect server, in a container (see [Running Spark job runs](#running-spark-job-runs), [Running Hive job runs](#running-hive-job-runs) and [Running a session's Spark Connect server](#running-a-sessions-spark-connect-server)) | `immediate` | | `floci.services.emrserverless.docker-network` | Docker network for job run containers | the global default | | `floci.services.emrserverless.image-template` | Image for a `docker` job run whose application names no custom image, `%s` standing for the release label | `public.ecr.aws/emr-serverless/spark/%s:latest`, or `spark4/` in place of `spark/` for an `emr-spark-*` release | | `floci.services.emrserverless.hive-image-template` | Image for a `docker` Hive job run whose application names no custom image, `%s` standing for the release label | `public.ecr.aws/emr-serverless/hive/%s:latest` | @@ -151,8 +151,10 @@ runner mode a Spark run executes; see [Running Spark job runs](#running-spark-jo ## Sessions A session is "a managed connection between your local PySpark client and a Spark driver running on Amazon EMR -Serverless", through Spark Connect. Floci keeps a session and its lifecycle, but runs no Spark driver for it, so -nothing answers Spark Connect at its endpoint. +Serverless", through Spark Connect. With `runner-mode` set to `docker`, Floci runs that driver, a Spark Connect server, +in a container, and a client reaches it through Floci (see [Running a session's Spark +Connect server](#running-a-sessions-spark-connect-server)). With the default `immediate` mode, Floci keeps a session +and its lifecycle but runs no driver for it. * **Starting**: `StartSession` needs a Spark application on `emr-7.13.0` or later, or on the AWS runtime for Apache Spark (`emr-spark-8.0.0` on), whose `interactiveConfiguration.sessionEnabled` is `true`. As for a job run, a @@ -165,22 +167,24 @@ nothing answers Spark Connect at its endpoint. JSON type is refused with `SerializationException`, and a configuration without its `classification` with `ValidationException`. `releaseLabel` and `networkConfiguration` come from the application, and `createdBy` is the caller's ARN. -* **States**: a session is `IDLE` as soon as it starts, with `startedAt` and `idleSince` set. It is `TERMINATED` once - it has been idle for its `idleTimeoutMinutes` (0 to 1,000,000, 60 when not given, as "Default timeout is set to 1 - hour"), or once 24 hours have passed since it started, as "Each session has a hard limit of 24 hours by default", - whichever comes first. No source says what an idle timeout of `0` does; Floci reads it as no idle timeout, as for a - job run's `executionTimeoutMinutes`. Floci never reports `SUBMITTED`, `STARTING`, `STARTED`, `BUSY`, `FAILED` or - `TERMINATING`. -* **TerminateSession** ends a session at once as `TERMINATED`; AWS's passes through `TERMINATING` first. A session - that has already ended is refused with `ValidationException`, in Floci's own wording. +* **States**: in the `immediate` mode a session is `IDLE` as soon as it starts, with `startedAt` and `idleSince` set; in + the `docker` mode it goes through `SUBMITTED`, `STARTING` and `IDLE`, then `BUSY` and back (see below). It is + `TERMINATED` once it has been idle for its `idleTimeoutMinutes` (0 to 1,000,000, 60 when not given, as "Default + timeout is set to 1 hour"), or once 24 hours have passed since it started, as "Each session has a hard limit of 24 + hours by default", whichever comes first. No source says what an idle timeout of `0` does; Floci reads it as no idle + timeout, as for a job run's `executionTimeoutMinutes`. Floci never reports `STARTED`. +* **TerminateSession** ends a session with no server at once as `TERMINATED`; one whose server runs is `TERMINATING` + until its container has stopped, as "After you terminate a session, it enters the TERMINATING state and then the + TERMINATED state". A session that has already ended is refused with `ValidationException`, in Floci's own wording. * **StopApplication** terminates the application's sessions that have not ended, with `stateDetails` saying so. The API reference requires a stopping application's job runs to have ended but names no such requirement for sessions, and once an application is stopped "no resources are running on the application"; AWS's own handling is not recorded. -* **GetSessionEndpoint** answers for a session that has not ended with an endpoint on Floci's own address - (`/_aws/emr-serverless/sessions//`) and a fresh authentication token that expires in an - hour, as "Authentication tokens are time-limited to 1 hour". Nothing answers Spark Connect there. A session that has - ended is refused with `ValidationException`, in Floci's own wording. +* **GetSessionEndpoint** answers for a session that has not ended with Floci's own address as its endpoint, such as + `http://localhost:4566`, and a fresh authentication token that expires in an hour, as "Authentication tokens are + time-limited to 1 hour". AWS's endpoint is an `https://` URL without a port; a Spark Connect URL holds no path, so + Floci's is its address alone, port included, and the token names the session. A session that has ended, or is + `TERMINATING`, is refused with `ValidationException`, in Floci's own wording. * **ListSessions** returns the newest sessions first, filtered by `states`, `createdAtAfter` and `createdAtBefore`, at most 50 per page, grouped by state as `ListJobRuns` groups runs. * **GetResourceDashboard** takes a `resourceType` of `SESSION`, the only one, and gives a link like @@ -190,6 +194,45 @@ nothing answers Spark Connect at its endpoint. A state machine drives applications and job runs through the `emr-serverless:` integrations, `.sync` included; see [Step Functions: Amazon EMR Serverless tasks](step-functions.md#amazon-emr-serverless-tasks). +### Running a session's Spark Connect server + +With `runner-mode` set to `docker`, each session runs a Spark Connect server in a container, as a job run's driver runs: +in the release's image, or the application's custom image, on the same Docker network, with the execution role's +credentials, and with its executors in containers of their own when `executor-containers` is above 0. Its +`spark-defaults` are the application's runtime configuration, then the session's `runtimeConfiguration`, merged as a +job run's `applicationConfiguration` is. Floci sets `spark.connect.grpc.binding.port` itself and drops a +`spark.connect.grpc.binding.address`, as that setting "is reserved by EMR Serverless and cannot be overridden by users". +The server's port is published on the Docker host's loopback interface only, and clients reach it through Floci. + +* **Connecting**: build the connection string from `GetSessionEndpoint`'s answer as AWS's guide does, with the token in + the `x-aws-proxy-auth` parameter, but keep the endpoint's port: + + ```python + endpoint = emr.get_session_endpoint(applicationId=app_id, sessionId=session_id) + scheme, address = endpoint["endpoint"].split("://", 1) # http, localhost:4566 + tls = ";use_ssl=true" if scheme == "https" else "" + spark = SparkSession.builder.remote( + f"sc://{address}/{tls};x-aws-proxy-auth={endpoint['authToken']}").getOrCreate() + ``` + + Floci serves plain HTTP unless its TLS is on, so `use_ssl=true` goes only with an `https://` endpoint, and then the + client has to trust Floci's CA (`GRPC_DEFAULT_SSL_ROOTS_FILE_PATH` for PySpark). The endpoint is `floci.base-url`, as + every URL Floci hands out is, so where Floci is reached through another port, as a container's mapped port, set + `floci.base-url` to that address. As AWS says, the client's PySpark must match the release's Spark (3.5.6 for + `emr-7.13.0`). +* **Tokens**: a call whose token Floci did not give, or which has expired, fails with gRPC's `UNAUTHENTICATED`, as + "When a token expires, gRPC calls fail with an authentication error". A call to a session that is not `IDLE` or + `BUSY`, or, in the `immediate` mode, to any session, fails with `UNAVAILABLE`, in Floci's own wording. +* **States**: a session is `SUBMITTED` until its container runs, `STARTING` until the server answers, then `IDLE`, with + `startedAt` and `idleSince` set. No source says when a session is `BUSY`: Floci makes it `BUSY` while a call runs on + its server, and `IDLE` again once none does, its idle timeout counting from then. A server that does not answer + within 10 minutes, or stops on its own, fails its session with `stateDetails` saying so (why it did not answer, or + its exit code); one Floci stopped running when it restarted fails too, and its container, if one is left, goes. The + 24 hours count from when the server answers. +* **Logs**: no source gives where a session's driver logs go, so Floci sends the server's output to its own log only, + not to the application's monitoring configuration. +* **Spark UI**: `GetResourceDashboard` still links to Floci's page about the session, not to the server's Spark UI. + ## Running Spark job runs With `runner-mode` set to `docker` (`FLOCI_SERVICES_EMRSERVERLESS_RUNNER_MODE=docker`), a Spark job @@ -369,4 +412,4 @@ application's `imageConfiguration`; a `TezTask` image is not used, as Tez's task * **Custom images**: Floci does not check an `imageUri` against the model's pattern, which would refuse the repository URIs Floci's own ECR hands out, nor that the image was built from its release's base image (AWS refuses one that was not from `emr-7.14.0` and `emr-spark-8.1.0` on), nor the image's size. An image that cannot be pulled fails the run, not the request that names it. An image's digest is resolved as the application starts where its `applicationLevelDigestResolution` is true, or left unset on EMR 7.13 or earlier, as the user guide's table has it, and AWS's "Custom images are resolved to a digest at application start; that digest is used for all jobs until the application restarts": the application's image configuration gets the digest of the image in Floci's ECR as its `resolvedImageDigest`, and each run pulls the image by it until the application starts again; a stopped application reports none. An image outside ECR, one in another account's repository (Floci does not check that the application may pull it), or one Floci's ECR does not hold or cannot read without Docker, has no digest to read and is resolved for each run, as every image is from 7.14 on; any other answer from Floci's ECR fails `StartApplication` with `InternalServerException`; such a run's digest comes from its attempt's own pull (see **Image** above), and a job run's image configurations carry no `applicationLevelDigestResolution`. * **Not emulated**: the "EMR Serverless Job Run Retry" event, as Floci sends no EMR Serverless events, queuing (`QUEUED`), `totalResourceUtilization` and `billedResourceUtilization` (of a job run or a session), and `shutdownGracePeriodInSeconds` (accepted and ignored: a cancelled run's driver is stopped at once). * **Instant Start/Stop**: Floci marks the application `STARTED` or `STOPPED` immediately without provisioning actual compute capacity in the background. -* **Sessions run nothing**: a session is kept with its lifecycle, but no Spark driver runs for it, and nothing answers Spark Connect at the endpoint `GetSessionEndpoint` gives (see [Sessions](#sessions)). +* **Sessions in the `immediate` mode run nothing**: a session is kept with its lifecycle, but no Spark driver runs for it, and a Spark Connect call to it is refused; the `docker` mode runs one (see [Running a session's Spark Connect server](#running-a-sessions-spark-connect-server)). diff --git a/src/main/java/io/floci/aws/core/common/SparkConnectEndpoint.java b/src/main/java/io/floci/aws/core/common/SparkConnectEndpoint.java index 3f5a16cff1..4d482d4a27 100644 --- a/src/main/java/io/floci/aws/core/common/SparkConnectEndpoint.java +++ b/src/main/java/io/floci/aws/core/common/SparkConnectEndpoint.java @@ -7,16 +7,17 @@ import java.util.HexFormat; /** * What GetSessionEndpoint answers for a Spark Connect session, EMR Serverless's and EMR's alike: the endpoint a client - * connects to and an authentication token, with when it expires. Each call gives a new token; Floci runs no Spark - * Connect server behind the endpoint, so nothing checks one. + * connects to and an authentication token, with when it expires. Each call gives a new token. Where a service runs a + * Spark Connect server for its sessions, as EMR Serverless does in its docker runner mode, {@link SparkConnectProxy} + * checks the token on each call; elsewhere nothing checks one. */ public record SparkConnectEndpoint(String url, String authToken, Instant authTokenExpiresAt) { private static final int TOKEN_BYTES = 32; /** - * The endpoint at {@code path} on Floci's {@code baseUrl}, a trailing slash of which is dropped, with a new random - * token that expires {@code validity} after {@code now}. + * The endpoint at {@code path} on Floci's {@code baseUrl} (Floci's address itself for an empty one), a trailing + * slash of which is dropped, with a new random token that expires {@code validity} after {@code now}. */ public static SparkConnectEndpoint issue(String baseUrl, String path, Instant now, Duration validity) { String base = baseUrl == null ? "" : baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) diff --git a/src/main/java/io/floci/aws/core/common/SparkConnectProxy.java b/src/main/java/io/floci/aws/core/common/SparkConnectProxy.java new file mode 100644 index 0000000000..17933359d0 --- /dev/null +++ b/src/main/java/io/floci/aws/core/common/SparkConnectProxy.java @@ -0,0 +1,278 @@ +package io.floci.aws.core.common; + +import io.vertx.core.Future; +import io.vertx.core.MultiMap; +import io.vertx.core.Vertx; +import io.vertx.core.buffer.Buffer; +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.HttpVersion; +import io.vertx.core.http.RequestOptions; +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.enterprise.inject.Instance; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.nio.charset.StandardCharsets; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * Spark Connect for the sessions Floci runs a server for. A client's gRPC calls to + * {@code spark.connect.SparkConnectService} on Floci's own port carry the session's authentication token as their + * {@code x-aws-proxy-auth} metadata, as EMR Serverless's connection string puts it + * ({@code sc://:443/;use_ssl=true;x-aws-proxy-auth=}, EMR Serverless user guide, "Run interactive + * sessions with Amazon EMR Serverless through Spark Connect"), and each goes on, over HTTP/2, to the server of the + * session the token was issued for, which {@link SparkConnectTargets} names. A call with no token, or one no service + * issued, ends at once with gRPC's UNAUTHENTICATED, as "When a token expires, gRPC calls fail with an authentication + * error"; one the service refuses ends with the status it gives. + */ +@ApplicationScoped +public class SparkConnectProxy { + + private static final Logger LOG = Logger.getLogger(SparkConnectProxy.class); + + static final String SERVICE_PATH = "/spark.connect.SparkConnectService/"; + /** The call metadata that carries a session's authentication token. */ + public static final String TOKEN_METADATA = "x-aws-proxy-auth"; + // A call to a service no Spark Connect server has, which its gRPC server answers UNIMPLEMENTED once it runs. + private static final String PROBE_PATH = "/grpc.health.v1.Health/Check"; + // An empty gRPC message's bytes: no compression, a length of 0. + private static final int EMPTY_MESSAGE_LENGTH = 5; + // How long a probe waits for the server's answer before it gives up on that call, its stream reset. + private static final long PROBE_TIMEOUT_MILLIS = 5_000; + private static final String GRPC_CONTENT_TYPE = "application/grpc"; + private static final Set NOT_FORWARDED = Set.of("host", "connection", "keep-alive", "proxy-connection", + "transfer-encoding", "upgrade", "http2-settings", TOKEN_METADATA); + static final String NO_TOKEN = "The call carries no " + TOKEN_METADATA + " authentication token."; + public static final String UNKNOWN_TOKEN = + "The authentication token is not valid. Call GetSessionEndpoint for a new one."; + + private final Instance targets; + private final Vertx vertx; + private final HttpClient client; + + @Inject + public SparkConnectProxy(Instance targets, Vertx vertx) { + this.targets = targets; + this.vertx = vertx; + // gRPC's servers speak HTTP/2 from the first byte, with no upgrade from HTTP/1.1. + this.client = vertx.createHttpClient(new HttpClientOptions() + .setProtocolVersion(HttpVersion.HTTP_2) + .setHttp2ClearTextUpgrade(false) + .setConnectTimeout(5_000)); + } + + @PreDestroy + void close() { + client.close(); + } + + void register(@Observes Router router) { + router.route().handler(this::handle); + } + + void handle(RoutingContext context) { + HttpServerRequest request = context.request(); + if (request.version() != HttpVersion.HTTP_2 || request.method() != HttpMethod.POST + || !request.path().startsWith(SERVICE_PATH) || !grpc(request.getHeader("content-type"))) { + context.next(); + return; + } + request.pause(); + String token = request.getHeader(TOKEN_METADATA); + // A service reads its storage to route a call, so off the event loop. + vertx.executeBlocking(() -> route(token), false).onComplete(routed -> { + if (routed.failed()) { + LOG.warnv(routed.cause(), "Spark Connect call {0} could not be routed", request.path()); + refuse(request, SparkConnectTargets.Route.UNAVAILABLE, "The call could not be routed."); + } else if (routed.result().refusal() != null) { + refuse(request, routed.result().status(), routed.result().refusal()); + } else { + forward(request, routed.result()); + } + }); + } + + /** + * Why no Spark Connect server answers at {@code host} and {@code port}, or null once one does: any gRPC answer to + * a call it has no method for says it runs. A port Docker publishes accepts a connection before the server in the + * container listens, so a connection alone says nothing. A call with no answer within + * {@value #PROBE_TIMEOUT_MILLIS} ms is reset, so probes that go unanswered leave no stream behind. + */ + public Future unanswered(String host, int port) { + RequestOptions options = new RequestOptions().setMethod(HttpMethod.POST).setHost(host).setPort(port) + .setURI(PROBE_PATH) + .setIdleTimeout(PROBE_TIMEOUT_MILLIS) + .putHeader("content-type", GRPC_CONTENT_TYPE) + .putHeader("te", "trailers"); + return client.request(options) + // A Buffer of each call's own: one held in a static field would be built into the native image's + // heap, which its build refuses. + .compose(probe -> probe.send(Buffer.buffer(new byte[EMPTY_MESSAGE_LENGTH]))) + .compose(answer -> answer.body().map(body -> answer.statusCode() == 200 ? (String) null + : "the server answered HTTP " + answer.statusCode())) + .recover(failure -> { + LOG.debugv("No Spark Connect server answers at {0}:{1}: {2}", host, port, failure.toString()); + return Future.succeededFuture(failure.toString()); + }); + } + + private SparkConnectTargets.Route route(String token) { + if (token == null || token.isBlank()) { + return SparkConnectTargets.Route.refused(SparkConnectTargets.Route.UNAUTHENTICATED, NO_TOKEN); + } + for (SparkConnectTargets service : targets) { + Optional route = service.route(token); + if (route.isPresent()) { + return route.get(); + } + } + return SparkConnectTargets.Route.refused(SparkConnectTargets.Route.UNAUTHENTICATED, UNKNOWN_TOKEN); + } + + private void forward(HttpServerRequest request, SparkConnectTargets.Route route) { + HttpServerResponse response = request.response(); + AtomicBoolean over = new AtomicBoolean(); + Runnable ended = () -> { + if (over.compareAndSet(false, true)) { + vertx.executeBlocking(() -> { + route.ended().run(); + return null; + }, false); + } + }; + RequestOptions options = new RequestOptions().setMethod(HttpMethod.POST).setHost(route.host()) + .setPort(route.port()).setURI(request.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, SparkConnectTargets.Route.UNAVAILABLE, + "The session's Spark Connect server could not be reached: " + opened.cause().getMessage()); + ended.run(); + return; + } + HttpClientRequest upstream = opened.result(); + // A gRPC call's messages stream with no Content-Length, which Vert.x takes only on a streamed request. + if (request.getHeader("content-length") == null) { + upstream.setChunked(true); + } + // A client that goes away takes its call on the server with it. + response.closeHandler(closed -> { + upstream.reset(); + ended.run(); + }); + upstream.response().onComplete(answered -> { + if (answered.failed()) { + if (response.headWritten()) { + response.reset(); + } else { + refuse(request, SparkConnectTargets.Route.UNAVAILABLE, + "The session's Spark Connect server ended the call: " + answered.cause().getMessage()); + } + ended.run(); + return; + } + relay(answered.result(), response, ended); + }); + // A call whose messages cannot reach the server is reset on both sides, and over. + request.pipeTo(upstream).onFailure(failure -> { + upstream.reset(); + if (!response.ended()) { + response.reset(); + } + ended.run(); + }); + }); + } + + /** + * The server's answer: its messages, then its trailers, which hold the call's gRPC status; or, where the server + * answered "Trailers-Only", its status in its only headers, as grpc-java answers an error raised before any + * message, those headers alone, ending the call, as a client finds the status nowhere else. + */ + private static void relay(HttpClientResponse answer, HttpServerResponse response, Runnable ended) { + response.setStatusCode(answer.statusCode()); + copy(answer.headers(), response.headers()); + if (answer.headers().contains("grpc-status")) { + answer.body().onComplete(read -> { + if (read.succeeded()) { + response.end(); + } else { + response.reset(); + } + ended.run(); + }); + return; + } + answer.pipe().endOnComplete(false).to(response).onComplete(piped -> { + if (piped.succeeded()) { + copy(answer.trailers(), response.trailers()); + response.end(); + } else { + response.reset(); + } + 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()); + } + } + } + + // A call that ends at once, with its status in the only headers it gets, as gRPC's "Trailers-Only" answer. + private static void refuse(HttpServerRequest request, int status, String message) { + request.resume(); + HttpServerResponse response = request.response(); + if (response.ended()) { + return; + } + response.setStatusCode(200) + .putHeader("content-type", GRPC_CONTENT_TYPE) + .putHeader("grpc-status", String.valueOf(status)) + .putHeader("grpc-message", percentEncoded(message)) + .end(); + } + + static boolean grpc(String contentType) { + if (contentType == null) { + return false; + } + String type = contentType.toLowerCase(Locale.ROOT); + return type.equals(GRPC_CONTENT_TYPE) || type.startsWith(GRPC_CONTENT_TYPE + "+") + || type.startsWith(GRPC_CONTENT_TYPE + ";"); + } + + // gRPC's grpc-message: UTF-8, its bytes outside printable ASCII, and '%', percent-encoded. + static String percentEncoded(String message) { + StringBuilder encoded = new StringBuilder(); + for (byte b : message.getBytes(StandardCharsets.UTF_8)) { + if (b >= 0x20 && b <= 0x7e && b != '%') { + encoded.append((char) b); + } else { + encoded.append('%').append(String.format("%02X", b & 0xff)); + } + } + return encoded.toString(); + } +} diff --git a/src/main/java/io/floci/aws/core/common/SparkConnectTargets.java b/src/main/java/io/floci/aws/core/common/SparkConnectTargets.java new file mode 100644 index 0000000000..4f95e86bf1 --- /dev/null +++ b/src/main/java/io/floci/aws/core/common/SparkConnectTargets.java @@ -0,0 +1,40 @@ +package io.floci.aws.core.common; + +import java.util.Optional; + +/** + * A service whose sessions take Spark Connect calls through {@link SparkConnectProxy}: it tells where a call carrying + * an authentication token goes. Called off the event loop, as it may read the service's storage. + */ +public interface SparkConnectTargets { + + /** + * Where a call carrying {@code token} goes, or empty when {@code token} is not one this service issued. A call + * routed to a server counts as running in its session from now until {@link Route#ended} runs. + */ + Optional route(String token); + + /** + * Where a call goes: the server at {@code host} and {@code port}, with {@code ended} to run once the call is over; + * or, when {@code refusal} is not null, nowhere, the call ending at once with the gRPC status {@code status} and + * {@code refusal} as its message. + */ + record Route(String host, int port, Runnable ended, int status, String refusal) { + + /** gRPC's status for a call no server is there to take. */ + public static final int UNAVAILABLE = 14; + + /** gRPC's status for a call whose credentials are missing, unknown or expired. */ + public static final int UNAUTHENTICATED = 16; + + /** A call that goes to the server at {@code host} and {@code port}. */ + public static Route to(String host, int port, Runnable ended) { + return new Route(host, port, ended, 0, null); + } + + /** A call that ends at once with {@code status} and {@code refusal}. */ + public static Route refused(int status, String refusal) { + return new Route(null, 0, () -> { }, status, refusal); + } + } +} diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunService.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunService.java index 334060a238..acc1fd697d 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunService.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunService.java @@ -26,6 +26,7 @@ import io.floci.aws.services.emrserverless.model.JobRunRecord; import io.floci.aws.services.emrserverless.model.JobRunSummary; import io.floci.aws.services.emrserverless.model.MaximumCapacity; import io.floci.aws.services.emrserverless.model.RuntimeConfiguration; +import io.floci.aws.services.emrserverless.model.Session; import io.floci.aws.services.emrserverless.model.StartJobRunRequest; import io.floci.aws.services.emrserverless.model.WorkerTypeSpecification; import io.floci.aws.services.iam.IamService; @@ -85,8 +86,15 @@ public class EmrServerlessJobRunService implements Resettable { private static final String MODE_STREAMING = "STREAMING"; private static final String RUNNER_DOCKER = "docker"; // The service a container run's driver belongs to, which names it and labels it. - private static final String SERVICE = "emr-serverless"; + static final String SERVICE = "emr-serverless"; private static final String SPARK_DEFAULTS = "spark-defaults"; + private static final String SPARK_CONNECT_SERVER = "org.apache.spark.sql.connect.service.SparkConnectServer"; + // Where an emr- release's image keeps the Spark Connect server, as emr-7.13.0's does. + static final String SPARK_CONNECT_JAR = "/usr/lib/spark/connector/lib/spark-connect.jar"; + // spark-submit's application for a class among Spark's own jars. + private static final String SPARK_INTERNAL = "spark-internal"; + private static final String SPARK_CONNECT_PORT = "spark.connect.grpc.binding.port"; + private static final String SPARK_CONNECT_ADDRESS = "spark.connect.grpc.binding.address"; private static final String S3_MONITORING = "s3MonitoringConfiguration"; private static final String CLOUD_WATCH_LOGGING = "cloudWatchLoggingConfiguration"; // "If you don't specify the optional values, then CloudWatch publishes the logs to a default log group". @@ -622,6 +630,48 @@ public class EmrServerlessJobRunService implements Resettable { runExecutor.execute(() -> execute(onPlatform, launchedIn)); } + /** The runner of the docker runner mode, or null in the immediate one. */ + SparkJobRunner containerRunner() { + return sparkRunner; + } + + /** + * What runs a session's Spark Connect server in a container, as a run's driver runs: in the application's image, + * on its network, with the session's execution role and its executors as a run's are, for {@code limit} at most. + * Its {@code spark-defaults} are the application's, then the session's {@code runtimeConfiguration}, merged as a + * run's {@code applicationConfiguration} is, with the server's port {@code port}; a + * {@code spark.connect.grpc.binding.address} is dropped, as "The Spark configuration + * spark.connect.grpc.binding.address is reserved by EMR Serverless and cannot be overridden by users" (EMR + * Serverless user guide, "Run interactive sessions with Amazon EMR Serverless through Spark Connect"). + */ + SparkJobRunner.Job sessionJob(Application app, Session session, Duration limit, int port) { + Object overrides = session.getConfigurationOverrides() != null + ? session.getConfigurationOverrides().get("runtimeConfiguration") : null; + Map sparkDefaults = classificationProperties(app, overrides, session.getReleaseLabel(), + SPARK_DEFAULTS); + sparkDefaults.remove(SPARK_CONNECT_ADDRESS); + sparkDefaults.put(SPARK_CONNECT_PORT, String.valueOf(port)); + AwsArnUtils.Arn arn = AwsArnUtils.parse(session.getArn()); + SparkJobRunner.Job job = new SparkJobRunner.Job(SERVICE, session.getSessionId(), arn.accountId(), + arn.region(), session.getReleaseLabel(), SparkJobRunner.Engine.SPARK, imageTemplate, customImage(app), + dockerNetwork, session.getExecutionRoleArn(), sparkDefaults, + sparkConnectServer(session.getReleaseLabel()), null, limit, null, null, + driverEnvironment(sparkDefaults), archives(sparkDefaults), null, Map.of(), Map.of(), Map.of(), + Map.of(), Map.of(), executors(app, executorContainers)); + return job.withPlatform(honourArchitectures ? DockerPlatforms.forArchitecture(app.getArchitecture()) : null) + .listeningOn(port); + } + + /** + * What starts the Spark Connect server on {@code spark-submit}'s command line: its class, and, on an emr- release, + * whose Spark 3.5 keeps the server in {@value #SPARK_CONNECT_JAR}, that jar as the application; the AWS runtime + * for Apache Spark's Spark 4 carries the server among its own jars. + */ + static List sparkConnectServer(String releaseLabel) { + return List.of("--class", SPARK_CONNECT_SERVER, + sparkRuntime(releaseLabel) ? SPARK_INTERNAL : SPARK_CONNECT_JAR); + } + private void execute(SparkJobRunner.Job job, long launchedIn) { SparkJobRunner.Outcome outcome; try { @@ -1057,16 +1107,26 @@ public class EmrServerlessJobRunService implements Resettable { * considered for this classification." From emr-spark-8.1.0 they merge by property, the run's winning. */ private static Map classificationProperties(Application app, JobRun run, String classification) { + Object overrides = run.getConfigurationOverrides() != null + ? run.getConfigurationOverrides().get("applicationConfiguration") : null; + return classificationProperties(app, overrides, run.getReleaseLabel(), classification); + } + + /** + * A {@code classification}'s properties: the application's runtime configuration, then {@code overrides}, a + * workload's own configuration list on {@code releaseLabel}, merged as {@link #classificationProperties} merges a + * run's. + */ + private static Map classificationProperties(Application app, Object overrides, + String releaseLabel, String classification) { Map properties = new LinkedHashMap<>(); if (app.getRuntimeConfiguration() != null) { for (RuntimeConfiguration configuration : app.getRuntimeConfiguration()) { addProperties(properties, configuration.getMembers(), classification); } } - Object overrides = run.getConfigurationOverrides() != null - ? run.getConfigurationOverrides().get("applicationConfiguration") : null; if (overrides instanceof List configurations) { - boolean replaces = !releaseAtLeast(SPARK_RUNTIME_RELEASE_LABEL, run.getReleaseLabel(), 8, 1); + boolean replaces = !releaseAtLeast(SPARK_RUNTIME_RELEASE_LABEL, releaseLabel, 8, 1); for (Object configuration : configurations) { if (configuration instanceof Map members && classification.equals(members.get("classification"))) { diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSessionService.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSessionService.java index ecf843ac29..ed1a39ec22 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSessionService.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSessionService.java @@ -9,8 +9,12 @@ import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.core.common.RegionResolver; 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.SparkConnectEndpoint; +import io.floci.aws.core.common.SparkConnectProxy; +import io.floci.aws.core.common.SparkConnectTargets; import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.services.emrserverless.model.Application; @@ -19,6 +23,7 @@ import io.floci.aws.services.emrserverless.model.SessionRecord; import io.floci.aws.services.emrserverless.model.SessionSummary; import io.floci.aws.services.emrserverless.model.StartSessionRequest; import io.floci.aws.services.iam.IamService; +import jakarta.annotation.PreDestroy; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; @@ -28,28 +33,54 @@ import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.ArrayList; +import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; /** * EMR Serverless sessions: "a managed connection between your local PySpark client and a Spark driver running on Amazon * EMR Serverless", through Spark Connect (EMR Serverless user guide, "Run interactive sessions with Amazon EMR - * Serverless through Spark Connect"). Floci keeps each session and its lifecycle but starts no Spark driver for it: a - * session is IDLE once started, nothing answers Spark Connect at its endpoint, and it ends when it is terminated, when - * its idle timeout or its 24 hours pass, or when its application stops. + * Serverless through Spark Connect"). A session ends when it is terminated, when its idle timeout or its 24 hours pass, + * or when its application stops. + * + *

In the docker runner mode a session runs a Spark Connect server, its driver, in a container, as a job run's driver + * runs ({@link EmrServerlessJobRunService#sessionJob}): it is SUBMITTED, then STARTING once its container runs, and + * IDLE once the server answers. A client reaches the server through {@link SparkConnectProxy}, with a token + * GetSessionEndpoint gave; the session is BUSY while a call runs there, and IDLE again, its idle timeout counting from + * then, once none does. A server that exits on its own fails its session. In the immediate runner mode no server runs: + * a session is IDLE once started, and a call to it is refused. */ @ApplicationScoped -public class EmrServerlessSessionService { +public class EmrServerlessSessionService implements SparkConnectTargets, Resettable { private static final Logger LOG = Logger.getLogger(EmrServerlessSessionService.class); + static final String STATE_SUBMITTED = "SUBMITTED"; + static final String STATE_STARTING = "STARTING"; static final String STATE_IDLE = "IDLE"; + static final String STATE_BUSY = "BUSY"; + static final String STATE_FAILED = "FAILED"; + static final String STATE_TERMINATING = "TERMINATING"; static final String STATE_TERMINATED = "TERMINATED"; - private static final List STATES = - List.of("SUBMITTED", "STARTING", "STARTED", STATE_IDLE, "BUSY", "FAILED", "TERMINATING", STATE_TERMINATED); - private static final Set ENDED = Set.of("FAILED", STATE_TERMINATED); + private static final List STATES = List.of(STATE_SUBMITTED, STATE_STARTING, "STARTED", STATE_IDLE, + STATE_BUSY, STATE_FAILED, STATE_TERMINATING, STATE_TERMINATED); + private static final Set ENDED = Set.of(STATE_FAILED, STATE_TERMINATED); + // The port a session's Spark Connect server listens on in its container, Spark Connect's own default. + static final int SPARK_CONNECT_PORT = 15002; + // How long a server may take to answer once its container runs, and how often it is asked meanwhile. + static final Duration SERVER_START_LIMIT = Duration.ofMinutes(10); + private static final long SERVER_PROBE_INTERVAL_MILLIS = 500; private static final List RESOURCE_TYPES = List.of("SESSION"); // SessionStateSet holds 1 to 8 states; a ListSessions page holds 1 to 50 sessions. private static final int MAX_FILTER_STATES = 8; @@ -64,13 +95,21 @@ public class EmrServerlessSessionService { static final Duration HARD_LIMIT = Duration.ofHours(24); // "Authentication tokens are time-limited to 1 hour." static final Duration TOKEN_VALIDITY = Duration.ofHours(1); - // Where GetSessionEndpoint points; nothing answers Spark Connect there, as Floci runs no driver for a session. - static final String ENDPOINT_PATH = "/_aws/emr-serverless/sessions/"; private static final String SPARK_TYPE = "SPARK"; // No source gives AWS's wording for these ends; they are Floci's. static final String IDLE_TIMED_OUT = "The session was idle for its idle timeout."; static final String HARD_LIMIT_REACHED = "The session reached its 24 hour limit."; static final String APPLICATION_STOPPED = "The session's application was stopped."; + static final String INTERRUPTED = "Floci stopped while the session was running."; + static final String SERVER_EXITED = "The session's Spark Connect server exited with code %d."; + static final String SERVER_NOT_STARTED = "The session's Spark Connect server could not start: %s"; + static final String SERVER_SILENT = "The session's Spark Connect server did not answer within " + + SERVER_START_LIMIT.toMinutes() + " minutes: %s"; + static final String SERVER_ENDED = "The session's Spark Connect server ended with no exit code."; + static final String TOKEN_EXPIRED = "The authentication token has expired. Call GetSessionEndpoint for a new one."; + static final String NO_SERVER = "Floci runs no Spark Connect server for session %s, as the EMR Serverless runner" + + " mode is immediate; floci.services.emrserverless.runner-mode docker runs one."; + static final String NOT_READY = "Session %s is %s, not ready for calls."; private final AccountAwareStorageBackend store; private final EmrServerlessService applications; @@ -81,21 +120,51 @@ public class EmrServerlessSessionService { private final ObjectMapper objectMapper; private final Clock clock; private final String baseUrl; + // The docker runner mode's runner, which runs each session's Spark Connect server; null in the immediate mode. + private final SparkJobRunner sparkRunner; + private final Executor serverExecutor; + // Ends each session at its next deadline, its idle timeout or its 24 hours, and its server with it. + private final ScheduledExecutorService idleChecks; + private final ServerProbe probe; + // The sessions whose server a thread of this process runs; one not here that has not ended was left by a restart. + private final Map servers = new HashMap<>(); + // The authentication tokens GetSessionEndpoint gave, until they expire or their session ends. + private final Map grants = new ConcurrentHashMap<>(); + // Raised by each reset, so a server's thread from before it writes nothing back after the wipe. + private long generation; @Inject public EmrServerlessSessionService(StorageFactory storageFactory, EmrServerlessService applications, EmrServerlessJobRunService jobRuns, IamService iamService, RegionResolver regionResolver, RequestContext requestContext, - ObjectMapper objectMapper, EmulatorConfig config, Clock clock) { + ObjectMapper objectMapper, EmulatorConfig config, Clock clock, + SparkConnectProxy proxy) { this(storageFactory.create("emrserverless", "emr-serverless-sessions.json", new TypeReference<>() {}), applications, jobRuns, iamService, regionResolver, requestContext, objectMapper, clock, - config.effectiveBaseUrl()); + config.effectiveBaseUrl(), jobRuns.containerRunner(), + Executors.newCachedThreadPool(Thread.ofPlatform().daemon().name("emr-serverless-session-", 0) + .factory()), + sessionChecks(), + (host, port) -> unanswered(proxy, host, port)); } EmrServerlessSessionService(AccountAwareStorageBackend store, EmrServerlessService applications, EmrServerlessJobRunService jobRuns, IamService iamService, RegionResolver regionResolver, RequestContext requestContext, ObjectMapper objectMapper, Clock clock, String baseUrl) { + this(store, applications, jobRuns, iamService, regionResolver, requestContext, objectMapper, clock, baseUrl, + null, Runnable::run, null, (host, port) -> "no server runs"); + } + + EmrServerlessSessionService(AccountAwareStorageBackend store, EmrServerlessService applications, + EmrServerlessJobRunService jobRuns, IamService iamService, + RegionResolver regionResolver, RequestContext requestContext, + ObjectMapper objectMapper, Clock clock, String baseUrl, SparkJobRunner sparkRunner, + Executor serverExecutor, ScheduledExecutorService idleChecks, ServerProbe probe) { + this.sparkRunner = sparkRunner; + this.serverExecutor = serverExecutor; + this.idleChecks = idleChecks; + this.probe = probe; this.store = store; this.applications = applications; this.jobRuns = jobRuns; @@ -107,6 +176,32 @@ public class EmrServerlessSessionService { this.baseUrl = baseUrl; } + @PreDestroy + void shutdown() { + if (serverExecutor instanceof ExecutorService executor) { + executor.shutdownNow(); + } + if (idleChecks != null) { + idleChecks.shutdownNow(); + } + } + + /** + * A reset has begun: the servers' threads from before it write nothing more, and their tokens go. The runner's + * teardown stops their containers. + */ + @Override + public synchronized void beforeReset() { + generation++; + servers.clear(); + grants.clear(); + } + + @Override + public void clear() { + // The sessions live in storage, which the reset wipes. + } + /** * Starts a session, which "The application must be in the STARTED state or have AutoStart enabled, and have * interactive sessions enabled" for, on "EMR release 7.13.0 and later", and, as "Spark Connect is supported only @@ -179,8 +274,9 @@ public class EmrServerlessSessionService { /** * Terminates a session that has not ended: "After you terminate a session, it enters the TERMINATING state and - * then the TERMINATED state." With no driver to stop, Floci's is TERMINATED at once. One that has already ended - * is refused; no source gives AWS's answer for it, so the wording is Floci's. + * then the TERMINATED state." One whose server runs is TERMINATING until its container has stopped; with no + * server, it is TERMINATED at once. One that has already ended is refused; no source gives AWS's answer for it, + * so the wording is Floci's. */ public synchronized Session terminateSession(String applicationId, String sessionId) { applications.getApplication(applicationId); @@ -188,6 +284,20 @@ public class EmrServerlessSessionService { if (ENDED.contains(record.getSession().getState())) { throw new AwsException("ValidationException", "Session " + sessionId + " has already ended.", 400); } + Server server = servers.get(sessionId); + if (server != null) { + cancelCheck(server); + Session session = record.getSession(); + session.setState(STATE_TERMINATING); + session.setStateDetails(""); + session.setIdleSince(null); + session.setUpdatedAt(now()); + store.put(sessionId, record); + dropGrants(sessionId); + sparkRunner.stop(sessionId); + LOG.infov("Terminating EMR Serverless session {0} on application {1}", sessionId, applicationId); + return copy(session); + } end(record, STATE_TERMINATED, null, now()); LOG.infov("Terminated EMR Serverless session {0} on application {1}", sessionId, applicationId); return copy(record.getSession()); @@ -195,17 +305,91 @@ public class EmrServerlessSessionService { /** * Where a client connects to a session that has not ended, with an authentication token, which is "time-limited - * to 1 hour". The endpoint is on Floci's own address, where nothing answers Spark Connect, as Floci runs no driver - * for a session. No source gives AWS's answer for a session that has ended, so the refusal's wording is Floci's. + * to 1 hour". The endpoint is Floci's own address, where {@link SparkConnectProxy} takes a call carrying the token + * on to the session's server: Spark Connect's {@code sc://} URL holds a host and a port but no path, so the token + * alone names the session. No source gives AWS's answer for a session that has ended, so the refusal's wording is + * Floci's. */ public synchronized SparkConnectEndpoint sessionEndpoint(String applicationId, String sessionId) { applications.getApplication(applicationId); Session session = settle(findSession(applicationId, sessionId)).getSession(); - if (ENDED.contains(session.getState())) { + if (ENDED.contains(session.getState()) || STATE_TERMINATING.equals(session.getState())) { throw new AwsException("ValidationException", "Session " + sessionId + " has ended.", 400); } - return SparkConnectEndpoint.issue(baseUrl, ENDPOINT_PATH + applicationId + "/" + sessionId, now(), - TOKEN_VALIDITY); + Instant now = now(); + SparkConnectEndpoint endpoint = SparkConnectEndpoint.issue(baseUrl, "", now, TOKEN_VALIDITY); + grants.values().removeIf(grant -> !now.isBefore(grant.expiresAt())); + AwsArnUtils.Arn arn = AwsArnUtils.parse(session.getArn()); + grants.put(endpoint.authToken(), new Grant(arn.accountId(), arn.region(), sessionId, + endpoint.authTokenExpiresAt())); + return endpoint; + } + + /** + * Where a Spark Connect call carrying {@code token} goes: the server of the session the token was given for, while + * the token has not expired and the session is IDLE or BUSY. The call makes the session BUSY until it ends. No + * source gives AWS's answer for a session that has not started or has ended, so the refusals' wording is Floci's. + */ + @Override + public Optional route(String token) { + Grant grant = grants.get(token); + if (grant == null) { + return Optional.empty(); + } + return Optional.of(RequestScopes.callAs(grant.accountId(), grant.region(), () -> callStarted(token, grant))); + } + + private synchronized Route callStarted(String token, Grant grant) { + if (!clock.instant().isBefore(grant.expiresAt())) { + grants.remove(token); + return Route.refused(Route.UNAUTHENTICATED, TOKEN_EXPIRED); + } + SessionRecord record = store.get(grant.sessionId()).orElse(null); + if (record == null) { + grants.remove(token); + return Route.refused(Route.UNAUTHENTICATED, SparkConnectProxy.UNKNOWN_TOKEN); + } + Session session = settle(record).getSession(); + if (!record.isContainerSession()) { + return Route.refused(Route.UNAVAILABLE, String.format(NO_SERVER, grant.sessionId())); + } + Server server = servers.get(grant.sessionId()); + boolean ready = STATE_IDLE.equals(session.getState()) || STATE_BUSY.equals(session.getState()); + if (server == null || server.host == null || !ready) { + return Route.refused(Route.UNAVAILABLE, String.format(NOT_READY, grant.sessionId(), session.getState())); + } + server.calls++; + if (STATE_IDLE.equals(session.getState())) { + session.setState(STATE_BUSY); + session.setIdleSince(null); + session.setUpdatedAt(now()); + store.put(session.getSessionId(), record); + // A busy session's idle timeout does not run, so only its 24 hours are left to check. + checkLater(record); + } + long launchedIn = generation; + return Route.to(server.host, server.port, () -> RequestScopes.runAs(grant.accountId(), grant.region(), + () -> callEnded(grant.sessionId(), launchedIn))); + } + + // A call has ended: with none left, the session is IDLE again from now. + private synchronized void callEnded(String sessionId, long launchedIn) { + Server server = servers.get(sessionId); + if (launchedIn != generation || server == null) { + return; + } + server.calls = Math.max(0, server.calls - 1); + if (server.calls > 0) { + return; + } + store.get(sessionId).filter(record -> STATE_BUSY.equals(record.getSession().getState())).ifPresent(record -> { + Instant now = now(); + record.getSession().setState(STATE_IDLE); + record.getSession().setIdleSince(now); + record.getSession().setUpdatedAt(now); + store.put(sessionId, record); + checkLater(record); + }); } /** @@ -386,8 +570,6 @@ public class EmrServerlessSessionService { session.setArn(AwsArnUtils.Arn.of("emr-serverless", applicationArn.region(), applicationArn.accountId(), applicationArn.resource() + "/sessions/" + sessionId).toString()); session.setName(request.getName()); - // With no driver to start, a session is ready, and idle, as it starts. - session.setState(STATE_IDLE); session.setStateDetails(""); session.setReleaseLabel(app.getReleaseLabel()); session.setExecutionRoleArn(request.getExecutionRoleArn()); @@ -395,8 +577,14 @@ public class EmrServerlessSessionService { applicationArn.accountId())); session.setCreatedAt(now); session.setUpdatedAt(now); - session.setStartedAt(now); - session.setIdleSince(now); + if (sparkRunner == null) { + // With no driver to start, a session is ready, and idle, as it starts. + session.setState(STATE_IDLE); + session.setStartedAt(now); + session.setIdleSince(now); + } else { + session.setState(STATE_SUBMITTED); + } // "Only runtime configuration overrides are supported." if (request.getConfigurationOverrides() != null && request.getConfigurationOverrides().get("runtimeConfiguration") != null) { @@ -412,10 +600,224 @@ public class EmrServerlessSessionService { record.setSession(session); record.setClientToken(request.getClientToken()); record.setRequest(original); + record.setContainerSession(sparkRunner != null); store.put(sessionId, record); + if (sparkRunner != null) { + launch(record, app); + } return record; } + // Hands a session's server to a thread of its own, which runs it until the session ends. + private void launch(SessionRecord record, Application app) { + Session session = record.getSession(); + // The session's 24 hours count from when its server answers, where settle() reads them, so the runner sets + // none of its own. + SparkJobRunner.Job job = jobRuns.sessionJob(app, session, Duration.ZERO, SPARK_CONNECT_PORT); + servers.put(session.getSessionId(), new Server()); + long launchedIn = generation; + serverExecutor.execute(() -> runServer(job, launchedIn)); + } + + private void runServer(SparkJobRunner.Job job, long launchedIn) { + SparkJobRunner.Outcome outcome; + try { + outcome = sparkRunner.run(job, new ServerProgress(job, launchedIn)); + } catch (RuntimeException e) { + LOG.warnv(e, "The Spark Connect server of EMR Serverless session {0} could not run", job.runId()); + outcome = SparkJobRunner.Outcome.couldNotStart(e.getMessage() != null ? e.getMessage() : e.toString()); + } + SparkJobRunner.Outcome ended = outcome; + RequestScopes.runAs(job.accountId(), job.region(), () -> serverEnded(job.runId(), ended, launchedIn)); + } + + // Asks the server whether it answers until it does, its session stops starting, or its time to start is up. + private void awaitServer(SparkJobRunner.Job job, String host, int port, long launchedIn) { + long giveUp = System.nanoTime() + SERVER_START_LIMIT.toNanos(); + while (RequestScopes.callAs(job.accountId(), job.region(), () -> starting(job.runId(), launchedIn))) { + String unanswered = probe.unanswered(host, port); + if (unanswered == null) { + RequestScopes.runAs(job.accountId(), job.region(), () -> serverReady(job.runId(), launchedIn)); + return; + } + if (System.nanoTime() - giveUp >= 0) { + LOG.warnv("The Spark Connect server of EMR Serverless session {0} did not answer: {1}", job.runId(), + unanswered); + RequestScopes.runAs(job.accountId(), job.region(), + () -> serverSilent(job.runId(), unanswered, launchedIn)); + return; + } + try { + Thread.sleep(SERVER_PROBE_INTERVAL_MILLIS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } + } + } + + private synchronized boolean starting(String sessionId, long launchedIn) { + return launchedIn == generation && store.get(sessionId) + .map(record -> STATE_STARTING.equals(record.getSession().getState())).orElse(false); + } + + // Whether a session's server may still start, or go on. + private synchronized boolean stillGoing(String sessionId, long launchedIn) { + return launchedIn == generation && servers.containsKey(sessionId) && store.get(sessionId) + .map(record -> !ENDED.contains(record.getSession().getState()) + && !STATE_TERMINATING.equals(record.getSession().getState())) + .orElse(false); + } + + private synchronized void serverStarted(String sessionId, long launchedIn) { + if (launchedIn != generation) { + return; + } + store.get(sessionId).filter(record -> STATE_SUBMITTED.equals(record.getSession().getState())) + .ifPresent(record -> { + record.getSession().setState(STATE_STARTING); + record.getSession().setUpdatedAt(now()); + store.put(sessionId, record); + }); + } + + private synchronized boolean serverListening(String sessionId, String host, int port, long launchedIn) { + Server server = servers.get(sessionId); + if (launchedIn != generation || server == null) { + return false; + } + server.host = host; + server.port = port; + return true; + } + + // The server answers: the session is ready, and IDLE, its idle timeout counting from now. + private synchronized void serverReady(String sessionId, long launchedIn) { + if (launchedIn != generation) { + return; + } + store.get(sessionId).filter(record -> STATE_STARTING.equals(record.getSession().getState())) + .ifPresent(record -> { + Instant now = now(); + Session session = record.getSession(); + session.setState(STATE_IDLE); + session.setStartedAt(now); + session.setIdleSince(now); + session.setUpdatedAt(now); + store.put(sessionId, record); + checkLater(record); + LOG.infov("EMR Serverless session {0} is ready", sessionId); + }); + } + + private synchronized void serverSilent(String sessionId, String unanswered, long launchedIn) { + if (launchedIn != generation) { + return; + } + store.get(sessionId).filter(record -> STATE_STARTING.equals(record.getSession().getState())) + .ifPresent(record -> end(record, STATE_FAILED, String.format(SERVER_SILENT, unanswered), now())); + } + + /** + * A session's server has stopped: a session being terminated is TERMINATED, as is one whose server Floci stopped or + * that ran past its 24 hours, and one whose server stopped on its own, or never started, has FAILED. + */ + private synchronized void serverEnded(String sessionId, SparkJobRunner.Outcome outcome, long launchedIn) { + if (launchedIn != generation) { + return; + } + Server server = servers.remove(sessionId); + if (server != null) { + cancelCheck(server); + } + dropGrants(sessionId); + store.get(sessionId).ifPresent(record -> { + String state = record.getSession().getState(); + if (ENDED.contains(state)) { + return; + } + Instant now = now(); + if (STATE_TERMINATING.equals(state)) { + end(record, STATE_TERMINATED, null, now); + } else if (outcome.timedOut()) { + end(record, STATE_TERMINATED, HARD_LIMIT_REACHED, now); + } else if (outcome.stopped()) { + end(record, STATE_TERMINATED, null, now); + } else if (outcome.failure() != null) { + end(record, STATE_FAILED, String.format(SERVER_NOT_STARTED, outcome.failure()), now); + } else if (outcome.exitCode() != null) { + end(record, STATE_FAILED, String.format(SERVER_EXITED, outcome.exitCode()), now); + } else { + end(record, STATE_FAILED, SERVER_ENDED, now); + } + }); + } + + /** + * Checks a session with a server again at its next deadline: once its idle timeout passes, while it is idle, or + * once its 24 hours pass, whichever comes first, so it ends then, its server with it. Each session keeps one check, + * which this replaces, and which ending it cancels. + */ + private void checkLater(SessionRecord record) { + Session session = record.getSession(); + Server server = servers.get(session.getSessionId()); + if (idleChecks == null || server == null || session.getStartedAt() == null) { + return; + } + Instant deadline = session.getStartedAt().plus(HARD_LIMIT); + Long minutes = session.getIdleTimeoutMinutes(); + if (STATE_IDLE.equals(session.getState()) && session.getIdleSince() != null && minutes != null + && minutes > 0) { + Instant idleLimit = session.getIdleSince().plus(Duration.ofMinutes(minutes)); + deadline = idleLimit.isBefore(deadline) ? idleLimit : deadline; + } + if (server.check != null) { + server.check.cancel(false); + } + AwsArnUtils.Arn arn = AwsArnUtils.parse(session.getArn()); + String sessionId = session.getSessionId(); + server.check = idleChecks.schedule( + () -> RequestScopes.runAs(arn.accountId(), arn.region(), () -> checkNow(sessionId)), + Math.max(0, Duration.between(clock.instant(), deadline).toMillis()), TimeUnit.MILLISECONDS); + } + + private static void cancelCheck(Server server) { + if (server.check != null) { + server.check.cancel(false); + server.check = null; + } + } + + private synchronized void checkNow(String sessionId) { + store.get(sessionId).ifPresent(this::settle); + } + + // One thread that ends sessions at their deadlines; a check a later one replaces leaves its queue at once. + private static ScheduledExecutorService sessionChecks() { + ScheduledThreadPoolExecutor checks = new ScheduledThreadPoolExecutor(1, + Thread.ofPlatform().daemon().name("emr-serverless-session-checks").factory()); + checks.setRemoveOnCancelPolicy(true); + return checks; + } + + private void dropGrants(String sessionId) { + grants.values().removeIf(grant -> grant.sessionId().equals(sessionId)); + } + + // Why no server answers at host and port yet, or null once one does. + private static String unanswered(SparkConnectProxy proxy, String host, int port) { + try { + return proxy.unanswered(host, port).toCompletionStage().toCompletableFuture() + .get(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return "interrupted"; + } catch (Exception e) { + LOG.debugv(e, "Probing the Spark Connect server at {0}:{1} failed", host, port); + return e.toString(); + } + } + /** * Ends a session whose time has run out by now: an idle one once its idle timeout has passed since it went idle, * and any once its 24 hours have passed since it started, whichever comes first. An idle timeout of 0 ends @@ -426,6 +828,16 @@ public class EmrServerlessSessionService { if (ENDED.contains(session.getState())) { return record; } + // Its thread ends it; without one, Floci stopped while its server ran, and nothing is left to. A server + // container the startup's cleanup left behind goes now. + if (record.isContainerSession() && !servers.containsKey(session.getSessionId())) { + boolean terminating = STATE_TERMINATING.equals(session.getState()); + end(record, terminating ? STATE_TERMINATED : STATE_FAILED, terminating ? null : INTERRUPTED, now()); + if (sparkRunner != null) { + sparkRunner.removeLeftoverDriver(EmrServerlessJobRunService.SERVICE, session.getSessionId()); + } + return record; + } Instant hardLimit = session.getStartedAt() != null ? session.getStartedAt().plus(HARD_LIMIT) : null; Long idleMinutes = session.getIdleTimeoutMinutes(); Instant idleLimit = STATE_IDLE.equals(session.getState()) && session.getIdleSince() != null @@ -451,6 +863,13 @@ public class EmrServerlessSessionService { session.setTotalExecutionDurationSeconds(Duration.between(session.getStartedAt(), at).toSeconds()); } store.put(session.getSessionId(), record); + dropGrants(session.getSessionId()); + // An ended session's server goes with it, and its check; its thread finds the session ended and leaves it so. + Server server = servers.get(session.getSessionId()); + if (server != null) { + cancelCheck(server); + sparkRunner.stop(session.getSessionId()); + } } private SessionRecord findSession(String applicationId, String sessionId) { @@ -482,4 +901,58 @@ public class EmrServerlessSessionService { private Session copy(Session session) { return objectMapper.convertValue(session, Session.class); } + + /** Why no Spark Connect server answers at a host and port, or null once one does. */ + @FunctionalInterface + interface ServerProbe { + String unanswered(String host, int port); + } + + // A session's running server: where Floci reaches it, once its container runs, how many calls it is taking, and + // the check that ends the session at its next deadline. + private static final class Server { + String host; + int port; + int calls; + ScheduledFuture check; + } + + // What an authentication token was given for: a session, in its account and Region, until it expires. + private record Grant(String accountId, String region, String sessionId, Instant expiresAt) { + } + + /** What the thread running a session's server tells the service, and asks it, as that session. */ + private final class ServerProgress implements SparkJobRunner.Progress { + + private final SparkJobRunner.Job job; + private final long launchedIn; + + ServerProgress(SparkJobRunner.Job job, long launchedIn) { + this.job = job; + this.launchedIn = launchedIn; + } + + @Override + public void started() { + RequestScopes.runAs(job.accountId(), job.region(), () -> serverStarted(job.runId(), launchedIn)); + } + + @Override + public void listening(String host, int port) { + if (RequestScopes.callAs(job.accountId(), job.region(), + () -> serverListening(job.runId(), host, port, launchedIn))) { + serverExecutor.execute(() -> awaitServer(job, host, port, launchedIn)); + } + } + + @Override + public void timedOut() { + // The run's outcome says so, which serverEnded reads. + } + + @Override + public boolean cancelled() { + return !RequestScopes.callAs(job.accountId(), job.region(), () -> stillGoing(job.runId(), launchedIn)); + } + } } diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java index 135a264cf7..a20b68ac2e 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java @@ -619,6 +619,10 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo container.withEnv(HADOOP_ENV_VARIABLE, hadoopEnvFile(job)); } } + if (job.listenPort() > 0) { + // Reached through Floci alone, so published on the host's loopback interface only. + container.withLoopbackPortBinding(job.listenPort(), 0); + } ContainerSpec spec = container .withDockerNetwork(Optional.ofNullable(job.dockerNetwork())) .withHostDockerInternalOnLinux() @@ -649,9 +653,13 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo if (stopped.getAsBoolean()) { return Outcome.halted(); } - lifecycleManager.startCreated(containerId, spec); + ContainerLifecycleManager.ContainerInfo info = lifecycleManager.startCreated(containerId, spec); logHandle = attachLog(containerId, job); progress.started(); + if (job.listenPort() > 0) { + ContainerLifecycleManager.EndpointInfo listening = info.getEndpoint(job.listenPort()); + progress.listening(listening.host(), listening.port()); + } if (job.executors() != null) { capacity = joinCapacity(job.executors().application()); executors = new SparkExecutors(job.executors(), driver(containerId), @@ -751,6 +759,24 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo } } + @Override + public void removeLeftoverDriver(String service, String runId) { + if (launches.get(runId) != null) { + return; + } + try { + lifecycleManager.findByName(ContainerStorageHelper.dockerName(config, service + "-" + runId)) + .ifPresent(container -> { + lifecycleManager.removeIfExists(container.getId()); + LOG.infov("Removed {0} Spark driver {1} of {2}, left running by an earlier Floci process", + service, container.getId(), runId); + }); + } catch (RuntimeException e) { + LOG.warnv("Could not remove the {0} Spark driver of {1} an earlier Floci process left: {2}", service, + runId, e.getMessage()); + } + } + // Floci's log always gets the driver's output, and the job's CloudWatch log streams too when it has some. private Closeable attachLog(String containerId, Job job) { String prefix = job.service() + ":" + job.runId(); diff --git a/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java b/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java index b10fa55fde..6e2fa62362 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java +++ b/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java @@ -31,12 +31,26 @@ public interface SparkJobRunner { */ void removeLeftoverDrivers(String service); + /** + * Removes the driver of {@code service}'s run {@code runId} where an earlier Floci process left it running, as one + * {@link #removeLeftoverDrivers} could not remove; a driver this process runs is left alone. + */ + default void removeLeftoverDriver(String service, String runId) { + } + /** What a run tells the service, and asks it, while it goes. */ interface Progress { /** The run's Spark driver runs. */ void started(); + /** + * The port the run's job listens on ({@link Job#listenPort}) is reachable from Floci at {@code host} and + * {@code port}, now its driver's container runs; what listens there may not be ready yet. + */ + default void listening(String host, int port) { + } + /** * The run resolved the custom image its job names for {@code workerType} ({@link Job#customImage} for its * driver, {@link Executors#image} for its executors) to the image whose manifest digest is {@code digest}, and @@ -97,7 +111,9 @@ public interface SparkJobRunner { * command gets (each empty for none); for an EMR Serverless Spark run, where its executors run, in * containers of their own (null for Spark's local mode, in the driver's container); and the Docker platform * its containers run, as its application's architecture names it with {@code honour-architectures} on, - * {@code linux/amd64} or {@code linux/arm64} (null for the Docker host's own). + * {@code linux/amd64} or {@code linux/arm64} (null for the Docker host's own); and the port in its driver's + * container that something there listens on for Floci, which Floci reaches through the Docker host's loopback + * interface only, as {@link Progress#listening} tells (0 for none). */ record Job(String service, String runId, String accountId, String region, String releaseLabel, Engine engine, String imageTemplate, String customImage, String dockerNetwork, String executionRole, @@ -105,7 +121,22 @@ public interface SparkJobRunner { String logFolder, CloudWatchLogs cloudWatchLogs, Map environment, List archives, Storage storage, Map coreSite, Map sparkLog4j2, Map mapredSite, Map hadoopLog4j, - Map hadoopEnvironment, Executors executors, String platform) { + Map hadoopEnvironment, Executors executors, String platform, int listenPort) { + + /** A job whose driver listens on no port for Floci. */ + public Job(String service, String runId, String accountId, String region, String releaseLabel, Engine engine, + String imageTemplate, String customImage, String dockerNetwork, String executionRole, + Map sparkDefaults, List application, List command, + Duration timeout, String logFolder, CloudWatchLogs cloudWatchLogs, + Map environment, List archives, Storage storage, + Map coreSite, Map sparkLog4j2, Map mapredSite, + Map hadoopLog4j, Map hadoopEnvironment, Executors executors, + String platform) { + this(service, runId, accountId, region, releaseLabel, engine, imageTemplate, customImage, dockerNetwork, + executionRole, sparkDefaults, application, command, timeout, logFolder, cloudWatchLogs, + environment, archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j, + hadoopEnvironment, executors, platform, 0); + } /** A job on the Docker host's own platform. */ public Job(String service, String runId, String accountId, String region, String releaseLabel, Engine engine, @@ -126,7 +157,7 @@ public interface SparkJobRunner { return new Job(service, runId, accountId, region, releaseLabel, engine, imageTemplate, customImage, dockerNetwork, executionRole, sparkDefaults, application, command, timeout, logFolder, cloudWatchLogs, environment, archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j, - hadoopEnvironment, executors, platform); + hadoopEnvironment, executors, platform, listenPort); } /** This job, run in {@code image}. */ @@ -134,7 +165,7 @@ public interface SparkJobRunner { return new Job(service, runId, accountId, region, releaseLabel, engine, image, customImage, dockerNetwork, executionRole, sparkDefaults, application, command, timeout, logFolder, cloudWatchLogs, environment, archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j, hadoopEnvironment, executors, - platform); + platform, listenPort); } /** This job, its executors where {@code executors} has them. */ @@ -142,7 +173,15 @@ public interface SparkJobRunner { return new Job(service, runId, accountId, region, releaseLabel, engine, imageTemplate, customImage, dockerNetwork, executionRole, sparkDefaults, application, command, timeout, logFolder, cloudWatchLogs, environment, archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j, - hadoopEnvironment, executors, platform); + hadoopEnvironment, executors, platform, listenPort); + } + + /** This job, its driver listening on {@code port} for Floci (0 for none). */ + public Job listeningOn(int port) { + return new Job(service, runId, accountId, region, releaseLabel, engine, imageTemplate, customImage, + dockerNetwork, executionRole, sparkDefaults, application, command, timeout, logFolder, + cloudWatchLogs, environment, archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j, + hadoopEnvironment, executors, platform, port); } /** This job, its containers run for {@code platform} (null for the Docker host's own). */ @@ -150,7 +189,7 @@ public interface SparkJobRunner { return new Job(service, runId, accountId, region, releaseLabel, engine, imageTemplate, customImage, dockerNetwork, executionRole, sparkDefaults, application, command, timeout, logFolder, cloudWatchLogs, environment, archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j, - hadoopEnvironment, executors, platform); + hadoopEnvironment, executors, platform, listenPort); } } diff --git a/src/main/java/io/floci/aws/services/emrserverless/model/SessionRecord.java b/src/main/java/io/floci/aws/services/emrserverless/model/SessionRecord.java index bc55b27345..3ea453a051 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/model/SessionRecord.java +++ b/src/main/java/io/floci/aws/services/emrserverless/model/SessionRecord.java @@ -5,13 +5,15 @@ import io.quarkus.runtime.annotations.RegisterForReflection; /** * A stored session: the session as GetSession reports it, plus the client token and the request it came with, which - * decide whether a repeated StartSession is a retry or a conflict. + * decide whether a repeated StartSession is a retry or a conflict, and whether a Spark Connect server runs for it. */ @RegisterForReflection public class SessionRecord { private Session session; private String clientToken; private JsonNode request; + // Whether Floci runs a Spark Connect server for it, as it does in the docker runner mode. + private boolean containerSession; public Session getSession() { return session; } public void setSession(Session session) { this.session = session; } @@ -19,4 +21,6 @@ public class SessionRecord { public void setClientToken(String clientToken) { this.clientToken = clientToken; } public JsonNode getRequest() { return request; } public void setRequest(JsonNode request) { this.request = request; } + public boolean isContainerSession() { return containerSession; } + public void setContainerSession(boolean containerSession) { this.containerSession = containerSession; } } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 87d37172f1..3a3bdb96ba 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -1087,7 +1087,7 @@ floci: emrserverless: enabled: true job-run-duration-seconds: 0 # 0 = BATCH job runs succeed as soon as they start - runner-mode: immediate # docker = run each job run's spark-submit or hive in a container + runner-mode: immediate # docker = run each job run, and each session's Spark Connect server, in a container # docker-network: floci-network # image-template: "registry.internal/emr-serverless/spark/%s:20250425" # %s = the release label # hive-image-template: "registry.internal/emr-serverless/hive/%s:20250425" # for Hive job runs diff --git a/src/test/java/io/floci/aws/core/common/SparkConnectProxyTest.java b/src/test/java/io/floci/aws/core/common/SparkConnectProxyTest.java new file mode 100644 index 0000000000..996e580346 --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/SparkConnectProxyTest.java @@ -0,0 +1,207 @@ +package io.floci.aws.core.common; + +import io.vertx.core.Future; +import io.vertx.core.MultiMap; +import io.vertx.core.Vertx; +import io.vertx.core.buffer.Buffer; +import io.vertx.core.http.HttpClient; +import io.vertx.core.http.HttpClientOptions; +import io.vertx.core.http.HttpMethod; +import io.vertx.core.http.HttpServer; +import io.vertx.core.http.HttpVersion; +import io.vertx.core.http.RequestOptions; +import io.vertx.ext.web.Router; +import jakarta.enterprise.inject.Instance; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Spark Connect calls through {@link SparkConnectProxy}, over HTTP/2 from the first byte as gRPC's are: a server of + * gRPC's shape stands in for a session's Spark Connect server, and a service's routes for its tokens. + */ +class SparkConnectProxyTest { + + private static final String PATH = "/spark.connect.SparkConnectService/ExecutePlan"; + private static final String TOKEN = "a-session-token"; + + private final Map routes = new ConcurrentHashMap<>(); + private final AtomicInteger callsEnded = new AtomicInteger(); + private final AtomicReference serverSaw = new AtomicReference<>(); + private Vertx vertx; + private SparkConnectProxy proxy; + private HttpServer floci; + private HttpServer sparkConnect; + private HttpClient client; + + @BeforeEach + void setUp() throws Exception { + vertx = Vertx.vertx(); + // A server of gRPC's shape: it answers a call with the message it was sent, then status 0 in its trailers. + sparkConnect = await(vertx.createHttpServer().requestHandler(request -> request.body().onSuccess(body -> { + serverSaw.set(MultiMap.caseInsensitiveMultiMap().addAll(request.headers())); + request.response().putHeader("content-type", "application/grpc").write(body); + request.response().trailers().add("grpc-status", "0"); + request.response().end(); + })).listen(0, "127.0.0.1")); + @SuppressWarnings("unchecked") + Instance targets = mock(Instance.class); + SparkConnectTargets service = token -> Optional.ofNullable(routes.get(token)); + when(targets.iterator()).thenAnswer(invocation -> List.of(service).iterator()); + proxy = new SparkConnectProxy(targets, vertx); + Router router = Router.router(vertx); + proxy.register(router); + router.route().handler(context -> context.response().setStatusCode(404).end("not Spark Connect")); + floci = await(vertx.createHttpServer().requestHandler(router).listen(0, "127.0.0.1")); + client = vertx.createHttpClient(new HttpClientOptions().setProtocolVersion(HttpVersion.HTTP_2) + .setHttp2ClearTextUpgrade(false)); + } + + @AfterEach + void tearDown() throws Exception { + await(vertx.close()); + } + + @Test + void aCallWithItsSessionsTokenGoesToTheServerAndItsAnswerAndTrailersComeBack() throws Exception { + routes.put(TOKEN, SparkConnectTargets.Route.to("127.0.0.1", sparkConnect.actualPort(), + callsEnded::incrementAndGet)); + + Answer answer = call(TOKEN, "a message"); + + assertEquals(200, answer.status); + assertEquals("a message", answer.body); + assertEquals("application/grpc", answer.headers.get("content-type")); + assertEquals("0", answer.trailers.get("grpc-status")); + // The token is Floci's to check, so the server never sees it. + assertNull(serverSaw.get().get(SparkConnectProxy.TOKEN_METADATA)); + assertEquals("trailers", serverSaw.get().get("te")); + assertNull(serverSaw.get().get("transfer-encoding")); + awaitCount(callsEnded, 1); + } + + @Test + void aCallWithNoTokenOrOneNoServiceGaveIsUnauthenticated() throws Exception { + Answer none = call(null, "a message"); + Answer unknown = call("not-a-token", "a message"); + + assertEquals("16", none.headers.get("grpc-status")); + assertEquals(SparkConnectProxy.NO_TOKEN, none.headers.get("grpc-message")); + assertEquals("16", unknown.headers.get("grpc-status")); + assertEquals(SparkConnectProxy.UNKNOWN_TOKEN, unknown.headers.get("grpc-message")); + assertEquals("", unknown.body); + } + + @Test + void aCallTheServiceRefusesEndsWithItsStatusAndOneToAServerNotThereIsUnavailable() throws Exception { + routes.put(TOKEN, SparkConnectTargets.Route.refused(SparkConnectTargets.Route.UNAVAILABLE, "Not 100% ready")); + Answer refused = call(TOKEN, "a message"); + int closedPort = sparkConnect.actualPort(); + await(sparkConnect.close()); + routes.put(TOKEN, SparkConnectTargets.Route.to("127.0.0.1", closedPort, callsEnded::incrementAndGet)); + Answer unreachable = call(TOKEN, "a message"); + + assertEquals("14", refused.headers.get("grpc-status")); + // gRPC's grpc-message percent-encodes a '%'. + assertEquals("Not 100%25 ready", refused.headers.get("grpc-message")); + assertEquals("14", unreachable.headers.get("grpc-status")); + assertTrue(unreachable.headers.get("grpc-message").startsWith("The session's Spark Connect server could not")); + awaitCount(callsEnded, 1); + } + + @Test + void aRequestThatIsNotASparkConnectCallGoesOnToFlocisOtherRoutes() throws Exception { + RequestOptions options = new RequestOptions().setMethod(HttpMethod.POST).setHost("127.0.0.1") + .setPort(floci.actualPort()).setURI("/2021-07-13/applications") + .putHeader("content-type", "application/json"); + Answer answer = send(options, "{}"); + + assertEquals(404, answer.status); + assertEquals("not Spark Connect", answer.body); + } + + @Test + void aServerAnswersOnceItsGrpcServerRunsAndAClosedPortSaysWhyNot() throws Exception { + assertNull(await(proxy.unanswered("127.0.0.1", sparkConnect.actualPort()))); + int closedPort = sparkConnect.actualPort(); + await(sparkConnect.close()); + + String why = await(proxy.unanswered("127.0.0.1", closedPort)); + assertTrue(why != null && !why.isEmpty(), String.valueOf(why)); + } + + @Test + void aServersErrorAnsweredTrailersOnlyReachesTheClientAndEndsTheCall() throws Exception { + // As grpc-java answers an error raised before any message: its status in its only headers. + HttpServer failing = await(vertx.createHttpServer().requestHandler(request -> request.body().onSuccess(body -> + request.response().putHeader("content-type", "application/grpc").putHeader("grpc-status", "3") + .putHeader("grpc-message", "TABLE_OR_VIEW_NOT_FOUND").end())) + .listen(0, "127.0.0.1")); + routes.put(TOKEN, SparkConnectTargets.Route.to("127.0.0.1", failing.actualPort(), + callsEnded::incrementAndGet)); + + Answer answer = call(TOKEN, "a message"); + + assertEquals("3", answer.headers.get("grpc-status") != null ? answer.headers.get("grpc-status") + : answer.trailers.get("grpc-status")); + assertEquals("", answer.body); + awaitCount(callsEnded, 1); + } + + private Answer call(String token, String message) throws Exception { + RequestOptions options = new RequestOptions().setMethod(HttpMethod.POST).setHost("127.0.0.1") + .setPort(floci.actualPort()).setURI(PATH) + .putHeader("content-type", "application/grpc") + .putHeader("te", "trailers"); + if (token != null) { + options.putHeader(SparkConnectProxy.TOKEN_METADATA, token); + } + // As a gRPC client sends a call: its message streamed, with no Content-Length. + return await(client.request(options) + .compose(request -> { + request.setChunked(true); + request.write(Buffer.buffer(message)); + return request.end().compose(ended -> request.response()); + }) + .compose(response -> response.body().map(received -> new Answer(response.statusCode(), + response.headers(), received.toString(), response.trailers())))); + } + + private Answer send(RequestOptions options, String body) throws Exception { + return await(client.request(options) + .compose(request -> request.send(Buffer.buffer(body))) + .compose(response -> response.body().map(received -> new Answer(response.statusCode(), + response.headers(), received.toString(), response.trailers())))); + } + + private static void awaitCount(AtomicInteger count, int expected) throws InterruptedException { + CountDownLatch never = new CountDownLatch(1); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (count.get() < expected && System.nanoTime() - deadline < 0) { + never.await(10, TimeUnit.MILLISECONDS); + } + 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, MultiMap headers, String body, MultiMap trailers) { + } +} diff --git a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSessionIntegrationTest.java b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSessionIntegrationTest.java index 9dd7148851..f556b5a5df 100644 --- a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSessionIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSessionIntegrationTest.java @@ -17,7 +17,6 @@ import static io.floci.aws.testing.EmrServerlessRequests.emrServerless; import static io.floci.aws.testing.EmrServerlessRequests.tagsPath; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.matchesPattern; @@ -88,7 +87,7 @@ class EmrServerlessSessionIntegrationTest { .then().statusCode(200) .body("applicationId", equalTo(applicationId)) .body("sessionId", equalTo(sessionId)) - .body("endpoint", endsWith("/_aws/emr-serverless/sessions/" + applicationId + "/" + sessionId)) + .body("endpoint", matchesPattern("https?://[^/]+")) .body("authToken", matchesPattern("[0-9a-f]{64}")) .body("authTokenExpiresAt", notNullValue()); diff --git a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSessionServerTest.java b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSessionServerTest.java new file mode 100644 index 0000000000..27c9dd422c --- /dev/null +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSessionServerTest.java @@ -0,0 +1,368 @@ +package io.floci.aws.services.emrserverless; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import io.floci.aws.config.EmulatorConfig; +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.services.emrserverless.model.CreateApplicationRequest; +import io.floci.aws.services.emrserverless.model.InteractiveConfiguration; +import io.floci.aws.services.emrserverless.model.Session; +import io.floci.aws.services.emrserverless.model.SessionRecord; +import io.floci.aws.services.emrserverless.model.StartSessionRequest; +import io.floci.aws.services.iam.IamService; +import io.floci.aws.testing.InMemoryStorageFactory; +import io.floci.aws.testing.MutableClock; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.List; +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.Executor; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.locks.LockSupport; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * EMR Serverless sessions in the docker runner mode, each running a Spark Connect server through the runner: the + * session's states as its server starts, answers, takes calls and stops, with a runner that stands in for Docker. + */ +class EmrServerlessSessionServerTest { + + private static final String REGION = "us-east-1"; + private static final String ACCOUNT_ID = "000000000000"; + private static final String ROLE = "arn:aws:iam::000000000000:role/emr-serverless-session"; + private static final String SERVER_HOST = "127.0.0.1"; + private static final int SERVER_PORT = 40123; + + private final ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule()); + private final AccountAwareStorageBackend store = AccountAwareStorageBackend.inMemory(ACCOUNT_ID); + private final FakeServerRunner runner = new FakeServerRunner(); + private final AtomicBoolean answering = new AtomicBoolean(true); + private final Executor threads = task -> Thread.ofPlatform().daemon().start(task); + private EmrServerlessService applications; + private EmrServerlessJobRunService jobRuns; + private IamService iamService; + private RegionResolver regionResolver; + private EmrServerlessSessionService sessions; + private MutableClock clock; + + @BeforeEach + void setUp() { + EmulatorConfig config = mock(EmulatorConfig.class); + when(config.defaultAccountId()).thenReturn(ACCOUNT_ID); + clock = new MutableClock(); + regionResolver = new RegionResolver(REGION, ACCOUNT_ID); + applications = new EmrServerlessService(config, new InMemoryStorageFactory(ACCOUNT_ID), regionResolver, clock); + iamService = mock(IamService.class); + when(iamService.resolveCallerArn(any())).thenReturn(Optional.empty()); + jobRuns = new EmrServerlessJobRunService(AccountAwareStorageBackend.inMemory(ACCOUNT_ID), applications, + iamService, regionResolver, null, objectMapper, 0, clock, runner, Runnable::run); + sessions = service(); + } + + private EmrServerlessSessionService service() { + return service(null); + } + + private EmrServerlessSessionService service(ScheduledThreadPoolExecutor checks) { + return new EmrServerlessSessionService(store, applications, jobRuns, iamService, regionResolver, null, + objectMapper, clock, "http://localhost:4566", runner, threads, checks, + (host, port) -> answering.get() && SERVER_HOST.equals(host) && port == SERVER_PORT ? null + : "Connection refused"); + } + + @Test + void aSessionRunsItsServerAndIsIdleOnceTheServerAnswers() { + String applicationId = application("emr-7.13.0"); + StartSessionRequest request = request(); + request.setConfigurationOverrides(Map.of("runtimeConfiguration", List.of(Map.of( + "classification", "spark-defaults", + "properties", Map.of("spark.driver.memory", "2g", "spark.connect.grpc.binding.address", "10.0.0.1"))))); + + Session started = sessions.startSession(applicationId, request); + Session idle = awaitState(applicationId, started.getSessionId(), "IDLE"); + + assertEquals("SUBMITTED", started.getState()); + assertNull(started.getStartedAt()); + assertNotNull(idle.getStartedAt()); + assertEquals(idle.getStartedAt(), idle.getIdleSince()); + SparkJobRunner.Job job = runner.jobs.get(started.getSessionId()); + assertEquals(EmrServerlessSessionService.SPARK_CONNECT_PORT, job.listenPort()); + assertEquals(List.of("--class", "org.apache.spark.sql.connect.service.SparkConnectServer", + EmrServerlessJobRunService.SPARK_CONNECT_JAR), job.application()); + assertEquals("15002", job.sparkDefaults().get("spark.connect.grpc.binding.port")); + assertEquals("2g", job.sparkDefaults().get("spark.driver.memory")); + // "spark.connect.grpc.binding.address is reserved by EMR Serverless and cannot be overridden by users." + assertFalse(job.sparkDefaults().containsKey("spark.connect.grpc.binding.address")); + assertEquals(ROLE, job.executionRole()); + // The session's 24 hours count from when its server answers, so the runner keeps no clock of its own. + assertEquals(Duration.ZERO, job.timeout()); + } + + @Test + void aSessionsTwentyFourHoursCountFromWhenItsServerAnswers() { + String applicationId = application("emr-7.13.0"); + StartSessionRequest request = request(); + request.setIdleTimeoutMinutes(0L); + String sessionId = sessions.startSession(applicationId, request).getSessionId(); + Session idle = awaitState(applicationId, sessionId, "IDLE"); + + clock.advance(Duration.between(clock.instant(), idle.getStartedAt().plus(Duration.ofHours(24))) + .minusSeconds(1)); + assertEquals("IDLE", sessions.getSession(applicationId, sessionId).getState()); + clock.advance(Duration.ofSeconds(1)); + Session ended = sessions.getSession(applicationId, sessionId); + + assertEquals("TERMINATED", ended.getState()); + assertEquals(EmrServerlessSessionService.HARD_LIMIT_REACHED, ended.getStateDetails()); + assertEquals(idle.getStartedAt().plus(Duration.ofHours(24)), ended.getEndedAt()); + assertTrue(runner.stopped.contains(sessionId)); + } + + @Test + void aSessionKeepsOneCheckForItsNextDeadlineHoweverManyCallsEnd() { + ScheduledThreadPoolExecutor checks = new ScheduledThreadPoolExecutor(1); + checks.setRemoveOnCancelPolicy(true); + try { + sessions = service(checks); + String applicationId = application("emr-7.13.0"); + String sessionId = sessions.startSession(applicationId, request()).getSessionId(); + awaitState(applicationId, sessionId, "IDLE"); + String token = sessions.sessionEndpoint(applicationId, sessionId).authToken(); + + for (int call = 0; call < 20; call++) { + sessions.route(token).orElseThrow().ended().run(); + } + assertEquals(1, checks.getQueue().size()); + sessions.terminateSession(applicationId, sessionId); + assertEquals(0, checks.getQueue().size()); + } finally { + checks.shutdownNow(); + } + } + + @Test + void aServerThatCannotStartFailsItsSessionEvenWithNoMessage() { + runner.launchFailure = new IllegalStateException(); + String applicationId = application("emr-7.13.0"); + String sessionId = sessions.startSession(applicationId, request()).getSessionId(); + + Session failed = awaitState(applicationId, sessionId, "FAILED"); + + assertEquals(String.format(EmrServerlessSessionService.SERVER_NOT_STARTED, "java.lang.IllegalStateException"), + failed.getStateDetails()); + } + + @Test + void theAwsRuntimeForApacheSparkStartsTheServerFromSparksOwnJars() { + assertEquals(List.of("--class", "org.apache.spark.sql.connect.service.SparkConnectServer", "spark-internal"), + EmrServerlessJobRunService.sparkConnectServer("emr-spark-8.0.0")); + } + + @Test + void aSessionIsStartingUntilItsServerAnswersAndRefusesCallsMeanwhile() { + answering.set(false); + String applicationId = application("emr-7.13.0"); + String sessionId = sessions.startSession(applicationId, request()).getSessionId(); + awaitState(applicationId, sessionId, "STARTING"); + String token = sessions.sessionEndpoint(applicationId, sessionId).authToken(); + + SparkConnectTargets.Route refused = sessions.route(token).orElseThrow(); + + assertEquals(SparkConnectTargets.Route.UNAVAILABLE, refused.status()); + assertEquals(String.format(EmrServerlessSessionService.NOT_READY, sessionId, "STARTING"), refused.refusal()); + answering.set(true); + awaitState(applicationId, sessionId, "IDLE"); + } + + @Test + void aCallMakesTheSessionBusyUntilTheLastCallEnds() { + String applicationId = application("emr-7.13.0"); + String sessionId = sessions.startSession(applicationId, request()).getSessionId(); + awaitState(applicationId, sessionId, "IDLE"); + String token = sessions.sessionEndpoint(applicationId, sessionId).authToken(); + + SparkConnectTargets.Route first = sessions.route(token).orElseThrow(); + SparkConnectTargets.Route second = sessions.route(token).orElseThrow(); + + assertNull(first.refusal()); + assertEquals(SERVER_HOST, first.host()); + assertEquals(SERVER_PORT, first.port()); + Session busy = sessions.getSession(applicationId, sessionId); + assertEquals("BUSY", busy.getState()); + assertNull(busy.getIdleSince()); + first.ended().run(); + assertEquals("BUSY", sessions.getSession(applicationId, sessionId).getState()); + clock.advance(Duration.ofMinutes(5)); + Instant before = clock.instant().truncatedTo(ChronoUnit.MILLIS); + second.ended().run(); + Instant after = clock.instant(); + Session idle = sessions.getSession(applicationId, sessionId); + assertEquals("IDLE", idle.getState()); + // Idle from when the last call ended. + assertFalse(idle.getIdleSince().isBefore(before)); + assertFalse(idle.getIdleSince().isAfter(after)); + } + + @Test + void aBusySessionDoesNotTimeOutAndAnIdleOneEndsItsServerAtItsIdleTimeout() { + String applicationId = application("emr-7.13.0"); + StartSessionRequest request = request(); + request.setIdleTimeoutMinutes(30L); + String sessionId = sessions.startSession(applicationId, request).getSessionId(); + awaitState(applicationId, sessionId, "IDLE"); + SparkConnectTargets.Route call = sessions.route(sessions.sessionEndpoint(applicationId, sessionId) + .authToken()).orElseThrow(); + + clock.advance(Duration.ofMinutes(45)); + assertEquals("BUSY", sessions.getSession(applicationId, sessionId).getState()); + call.ended().run(); + clock.advance(Duration.ofMinutes(30)); + Session ended = sessions.getSession(applicationId, sessionId); + + assertEquals("TERMINATED", ended.getState()); + assertEquals(EmrServerlessSessionService.IDLE_TIMED_OUT, ended.getStateDetails()); + assertTrue(runner.stopped.contains(sessionId)); + } + + @Test + void aTerminatedSessionIsTerminatingUntilItsServerStopsAndItsTokensGo() { + String applicationId = application("emr-7.13.0"); + String sessionId = sessions.startSession(applicationId, request()).getSessionId(); + awaitState(applicationId, sessionId, "IDLE"); + String token = sessions.sessionEndpoint(applicationId, sessionId).authToken(); + + Session terminating = sessions.terminateSession(applicationId, sessionId); + Session terminated = awaitState(applicationId, sessionId, "TERMINATED"); + + assertEquals("TERMINATING", terminating.getState()); + assertTrue(runner.stopped.contains(sessionId)); + assertNotNull(terminated.getEndedAt()); + assertTrue(sessions.route(token).isEmpty()); + } + + @Test + void aSessionWhoseServerExitsOnItsOwnHasFailed() { + String applicationId = application("emr-7.13.0"); + String sessionId = sessions.startSession(applicationId, request()).getSessionId(); + awaitState(applicationId, sessionId, "IDLE"); + + runner.end(sessionId).complete(SparkJobRunner.Outcome.exitedWith(1)); + Session failed = awaitState(applicationId, sessionId, "FAILED"); + + assertEquals(String.format(EmrServerlessSessionService.SERVER_EXITED, 1), failed.getStateDetails()); + } + + @Test + void aSessionWhoseServerNoThreadRunsAnyMoreWasInterruptedByARestart() { + String applicationId = application("emr-7.13.0"); + String sessionId = sessions.startSession(applicationId, request()).getSessionId(); + awaitState(applicationId, sessionId, "IDLE"); + + // A new process: the stored session is there, but no thread of it runs the session's server. + Session after = service().getSession(applicationId, sessionId); + + assertEquals("FAILED", after.getState()); + assertEquals(EmrServerlessSessionService.INTERRUPTED, after.getStateDetails()); + // Its server's container, should the startup's cleanup have left it, goes too. + assertEquals(List.of(sessionId), runner.leftoversRemoved); + } + + // Polls until the session is in state, as its server's thread moves it on its own. + private Session awaitState(String applicationId, String sessionId, String state) { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (true) { + Session session = sessions.getSession(applicationId, sessionId); + if (state.equals(session.getState())) { + return session; + } + if (System.nanoTime() - deadline > 0) { + fail("Session " + sessionId + " is " + session.getState() + ", not " + state); + } + LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10)); + } + } + + private static StartSessionRequest request() { + StartSessionRequest request = new StartSessionRequest(); + request.setClientToken(UUID.randomUUID().toString()); + request.setExecutionRoleArn(ROLE); + return request; + } + + private String application(String releaseLabel) { + CreateApplicationRequest create = new CreateApplicationRequest(); + create.setName("sessions"); + create.setReleaseLabel(releaseLabel); + create.setType("SPARK"); + create.setClientToken(UUID.randomUUID().toString()); + InteractiveConfiguration interactive = new InteractiveConfiguration(); + interactive.setProperty("sessionEnabled", true); + create.setInteractiveConfiguration(interactive); + return applications.createApplication(create).getApplicationId(); + } + + /** Runs each session's server as the Docker runner would, until it is stopped or told how it ends. */ + private static final class FakeServerRunner implements SparkJobRunner { + final Map jobs = new ConcurrentHashMap<>(); + final Set stopped = ConcurrentHashMap.newKeySet(); + final List leftoversRemoved = new CopyOnWriteArrayList<>(); + volatile RuntimeException launchFailure; + private final Map> ends = new ConcurrentHashMap<>(); + + @Override + public Outcome run(Job job, Progress progress) { + jobs.put(job.runId(), job); + if (launchFailure != null) { + throw launchFailure; + } + if (progress.cancelled()) { + return Outcome.halted(); + } + progress.started(); + progress.listening(SERVER_HOST, SERVER_PORT); + return end(job.runId()).join(); + } + + @Override + public void stop(String runId) { + stopped.add(runId); + end(runId).complete(Outcome.halted()); + } + + @Override + public void removeLeftoverDrivers(String service) { + } + + @Override + public void removeLeftoverDriver(String service, String runId) { + leftoversRemoved.add(runId); + } + + CompletableFuture end(String runId) { + return ends.computeIfAbsent(runId, id -> new CompletableFuture<>()); + } + } +} diff --git a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSessionServiceTest.java b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSessionServiceTest.java index a5208f7b7f..3220129f5c 100644 --- a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSessionServiceTest.java +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSessionServiceTest.java @@ -6,6 +6,7 @@ import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.SparkConnectEndpoint; +import io.floci.aws.core.common.SparkConnectTargets; import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.services.emrserverless.model.AutoStartConfiguration; import io.floci.aws.services.emrserverless.model.CreateApplicationRequest; @@ -240,14 +241,29 @@ class EmrServerlessSessionServiceTest { SparkConnectEndpoint endpoint = sessions.sessionEndpoint(applicationId, sessionId); - assertEquals("http://localhost:4566/_aws/emr-serverless/sessions/" + applicationId + "/" + sessionId, - endpoint.url()); + // Spark Connect's sc:// URL holds no path, so the endpoint is Floci's address and the token names the session. + assertEquals("http://localhost:4566", endpoint.url()); assertEquals(64, endpoint.authToken().length()); assertTrue(Duration.between(clock.instant(), endpoint.authTokenExpiresAt()).compareTo(Duration.ofMinutes(59)) > 0); assertNotEquals(endpoint.authToken(), sessions.sessionEndpoint(applicationId, sessionId).authToken()); } + @Test + void aCallToASessionWithNoServerIsRefusedAsUnavailableAndAnUnknownTokenNamesNone() { + String applicationId = application("emr-7.13.0", "SPARK", true); + String sessionId = sessions.startSession(applicationId, request()).getSessionId(); + String token = sessions.sessionEndpoint(applicationId, sessionId).authToken(); + + SparkConnectTargets.Route route = sessions.route(token).orElseThrow(); + + assertEquals(SparkConnectTargets.Route.UNAVAILABLE, route.status()); + assertEquals(String.format(EmrServerlessSessionService.NO_SERVER, sessionId), route.refusal()); + assertTrue(sessions.route("not-a-token").isEmpty()); + clock.advance(EmrServerlessSessionService.TOKEN_VALIDITY); + assertEquals(EmrServerlessSessionService.TOKEN_EXPIRED, sessions.route(token).orElseThrow().refusal()); + } + @Test void listSessionsFiltersByStateAndGroupsByTheFiltersOrder() { String applicationId = application("emr-7.13.0", "SPARK", true); diff --git a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSparkConnectNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSparkConnectNightlyIntegrationTest.java new file mode 100644 index 0000000000..7c70953573 --- /dev/null +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSparkConnectNightlyIntegrationTest.java @@ -0,0 +1,219 @@ +package io.floci.aws.services.emrserverless; + +import com.github.dockerjava.api.DockerClient; +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.docker.ContainerBuilder; +import io.floci.aws.core.common.docker.ContainerLifecycleManager; +import io.floci.aws.core.common.docker.ContainerReachableEndpoint; +import io.floci.aws.core.common.docker.ContainerSpec; +import io.floci.aws.core.common.docker.ContainerStorageHelper; +import io.floci.aws.testing.DockerAvailability; +import io.floci.aws.testing.PartitionCleanup; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +import io.restassured.response.Response; +import jakarta.inject.Inject; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.api.extension.RegisterExtension; + +import java.net.URI; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.LockSupport; + +import static io.floci.aws.testing.EmrServerlessRequests.deleteApplication; +import static io.floci.aws.testing.EmrServerlessRequests.emrServerless; +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 Serverless session run for real: its Spark Connect server runs in the release's image, and a Spark Connect + * client, Spark's own JVM client from the same image, reaches it through Floci at the endpoint GetSessionEndpoint + * gives, with the token in its {@code x-aws-proxy-auth} parameter as EMR Serverless's connection string puts it. A + * wrong token is refused, queries run, a query's Spark error comes back as Spark's, and TerminateSession stops the + * server. + * + *

A nightly check: the release's image is 3.7 GB, and the server and the client each start a JVM. + */ +@QuarkusTest +@TestProfile(EmrServerlessSparkConnectNightlyIntegrationTest.Profile.class) +@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true") +// Bounded waits: the image's pull of up to twenty minutes, then the server's start, the client's run and the session's +// end, a few minutes; the Nightly checks job's timeout counts the 30. +@Timeout(value = 30, unit = TimeUnit.MINUTES) +class EmrServerlessSparkConnectNightlyIntegrationTest { + + /** Sessions run their servers in containers, and Floci listens on a fixed port, the one its endpoint names. */ + public static final class Profile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of( + "floci.services.emrserverless.runner-mode", "docker", + "quarkus.http.test-port", String.valueOf(PORT), + "floci.port", String.valueOf(PORT), + "floci.base-url", "http://localhost:" + PORT); + } + } + + private static final int PORT = 4597; + private static final String REGION = "us-east-1"; + private static final String RELEASE = "emr-7.13.0"; + private static final String IMAGE = "public.ecr.aws/emr-serverless/spark/emr-7.13.0:latest"; + private static final String ROLE = "arn:aws:iam::000000000000:role/emr-serverless-session"; + // Spark's JVM Spark Connect client, which the release's image carries, compiled and run against the URLs it is + // given: the refused one first, then the session's. + private static final String CLIENT = """ + set -e + mkdir -p /tmp/client && cd /tmp/client && cat > Probe.java <<'JAVA' + import org.apache.spark.sql.SparkSession; + public class Probe { + public static void main(String[] args) { + try { + SparkSession.builder().remote(args[1]).create().range(1).count(); + System.out.println("REFUSED=none"); + } catch (Exception e) { + System.out.println("REFUSED=" + e.getMessage()); + } + SparkSession spark = SparkSession.builder().remote(args[0]).create(); + System.out.println("COUNT=" + spark.range(10).count()); + Object sum = spark.sql("SELECT sum(id) FROM range(5)").collectAsList().get(0).get(0); + System.out.println("SUM=" + sum); + try { + spark.sql("SELECT * FROM no_such_table").collectAsList(); + System.out.println("ERROR=none"); + } catch (Exception e) { + System.out.println("ERROR=" + e.getMessage()); + } + spark.close(); + } + } + JAVA + # The client's own jar first, then Spark's, less those whose classes it replaces. + classpath=/usr/lib/spark/connector/lib/spark-connect-client-jvm.jar + for jar in /usr/lib/spark/jars/*.jar; do + case $(basename "$jar") in + spark-sql_*|spark-catalyst_*|spark-hive*|spark-core_*) ;; + *) classpath=$classpath:$jar ;; + esac + done + javac -cp "$classpath" Probe.java + # Arrow, which the client reads answers with, needs java.nio opened. + exec java --add-opens=java.base/java.nio=ALL-UNNAMED -cp ".:$classpath" Probe "$@" + """; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @Inject + DockerClient docker; + + @Inject + ContainerBuilder containerBuilder; + + @Inject + ContainerLifecycleManager lifecycleManager; + + @Inject + ContainerReachableEndpoint reachableEndpoint; + + @Inject + EmulatorConfig config; + + @BeforeAll + static void configure() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void aClientRunsAQueryOnTheSessionsServerThroughFlociWithItsToken() 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"); + String applicationId = emrServerless(REGION).body(""" + {"name": "spark-connect", "releaseLabel": "%s", "type": "SPARK", "clientToken": "%s", + "interactiveConfiguration": {"sessionEnabled": true}} + """.formatted(RELEASE, UUID.randomUUID())) + .when().post("/applications") + .then().statusCode(200).extract().path("applicationId"); + cleanup.register(() -> deleteApplication(REGION, applicationId)); + String sessionId = emrServerless(REGION).body(""" + {"clientToken": "%s", "executionRoleArn": "%s", "idleTimeoutMinutes": 30} + """.formatted(UUID.randomUUID(), ROLE)) + .when().post("/applications/" + applicationId + "/sessions") + .then().statusCode(200).extract().path("sessionId"); + cleanup.register(() -> emrServerless(REGION).when() + .delete("/applications/" + applicationId + "/sessions/" + sessionId)); + + awaitState(applicationId, sessionId, "IDLE", Duration.ofMinutes(22)); + Response endpoint = emrServerless(REGION).when() + .get("/applications/" + applicationId + "/sessions/" + sessionId + "/endpoint") + .then().statusCode(200).extract().response(); + assertEquals("http://localhost:" + PORT, endpoint.path("endpoint")); + // Floci's address as a container reaches it, where the test's endpoint names the host's loopback. + URI floci = URI.create(reachableEndpoint.baseUrl(false)); + String connect = "sc://" + floci.getHost() + ":" + floci.getPort() + "/;x-aws-proxy-auth="; + String output = runClient(connect + endpoint.path("authToken"), connect + "not-the-token"); + + assertTrue(output.contains("REFUSED=") && output.contains("UNAUTHENTICATED"), output); + assertTrue(output.contains("COUNT=10"), output); + assertTrue(output.contains("SUM=10"), output); + // Spark's own error, which its server answers before any message, reaches the client through Floci. + assertTrue(output.contains("ERROR=") && output.contains("TABLE_OR_VIEW_NOT_FOUND"), output); + assertEquals("IDLE", session(applicationId, sessionId).path("session.state")); + + emrServerless(REGION).when().delete("/applications/" + applicationId + "/sessions/" + sessionId) + .then().statusCode(200); + awaitState(applicationId, sessionId, "TERMINATED", Duration.ofMinutes(2)); + String server = ContainerStorageHelper.dockerName(config, "emr-serverless-" + sessionId); + assertTrue(lifecycleManager.findByName(server).isEmpty(), "the session's server is still there"); + } + + // Runs the client in a container of the release's image, as far as Floci's address, and returns its output. + private String runClient(String sessionUrl, String refusedUrl) throws InterruptedException { + ContainerSpec spec = containerBuilder.newContainer(IMAGE) + .withName("floci-spark-connect-client-" + UUID.randomUUID().toString().substring(0, 8)) + .withEntrypoint(List.of("/bin/bash", "-c", CLIENT, "floci", sessionUrl, refusedUrl)) + .withHostDockerInternalOnLinux() + .withMemoryMb(1536) + .build(); + String containerId = lifecycleManager.create(spec); + try { + lifecycleManager.startCreated(containerId, spec); + int exitCode = docker.waitContainerCmd(containerId).start().awaitStatusCode(5, TimeUnit.MINUTES); + String output = lifecycleManager.lastLogLines(containerId, 200, Duration.ofSeconds(30)); + assertEquals(0, exitCode, output); + return output; + } finally { + lifecycleManager.stopAndRemove(containerId, null, 1); + } + } + + private void awaitState(String applicationId, String sessionId, String state, Duration limit) { + long deadline = System.nanoTime() + limit.toNanos(); + while (true) { + Response session = session(applicationId, sessionId); + String now = session.path("session.state"); + if (state.equals(now)) { + return; + } + if (List.of("FAILED", "TERMINATED").contains(now) || System.nanoTime() - deadline > 0) { + fail("Session " + sessionId + " is " + now + ", not " + state + ": " + + session.path("session.stateDetails")); + } + LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(2)); + } + } + + private static Response session(String applicationId, String sessionId) { + return emrServerless(REGION).when().get("/applications/" + applicationId + "/sessions/" + sessionId) + .then().statusCode(200).extract().response(); + } +}