From 2517edb471f5ef711f59cfd050fd54531b73fcf6 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:18:09 -0400 Subject: [PATCH] feat(emr): run a session's Spark Connect server on its cluster in the docker runner mode (#8751) With runner-mode docker, StartSession now runs the session's Spark Connect server on its cluster, as "Amazon EMR launches a Spark Connect Server as a YARN application on your cluster": a container on the cluster as a step's is, in the image its steps run in, its HDFS and YARN started first where they are not running, the server's driver in that container and its executors on the cluster's YARN. Its spark-defaults are the cluster's, then the session's EngineConfigurations, with the server's port; it runs as the session's ExecutionRoleArn, else the cluster's instance profile. A client reaches it through Floci as an EMR Serverless session's server is reached (#8731): GetSessionEndpoint answers Floci's address and a token, and a client connects with sc://:/;x-aws-proxy-auth=;authorization=, AWS's string with Floci's port. The proxy drops the authorization parameter, which AWS's own proxy reads, before the call reaches the server. The session is SUBMITTED until its container runs, STARTING until the server answers, then IDLE, BUSY while a call runs on its server and IDLE again once none does. TerminateSession goes through TERMINATING until the server has stopped; the idle timeout stops it too, and the cluster's end ends its sessions and stops their servers on its own, its storage released only once the last of them has gone. A server that exits on its own, or does not answer within 10 minutes, fails the session; one a restart left behind fails as interrupted, its container removed. What EMR Serverless's sessions and these share moves into emrserverless.SparkConnectServers: running each server, asking it whether it answers, the tokens, the calls a session takes, and one check for its next deadline; and SparkConnectSessionOwner, the states a session goes through as its server starts, answers, takes calls and stops, each service giving only how it stores, ends and checks its sessions (both models implement SparkConnectSession). A server being stopped takes no new call, a call's busy and idle reach the owner in order under the server's own lock, and a server's entry goes even where its owner fails to hear it stopped. A step's setup on its cluster (its image, storage, metadata address, added nodes and HDFS) moves into a preparation that steps and sessions' servers share. EmrSessionServerNightlyIntegrationTest runs it for real on an emr-spark-8.1.0 cluster with Spark 4's JVM client from that image: a wrong token refused, queries run, a missing table's Spark error back, TerminateSession removing the server. The nightly job's timeout and image prefetch take the new check. --- .github/ci/prefetch-images.sh | 10 +- .github/workflows/nightly-checks.yml | 9 +- docs/services/emr.md | 58 +- .../aws/core/common/SparkConnectProxy.java | 4 +- .../io/floci/aws/services/emr/EmrService.java | 419 ++++++++++++--- .../floci/aws/services/emr/EmrSessions.java | 57 +- .../aws/services/emr/model/EmrSession.java | 7 +- .../EmrServerlessSessionService.java | 405 +++----------- .../emrserverless/SparkConnectServers.java | 495 ++++++++++++++++++ .../emrserverless/SparkConnectSession.java | 21 + .../SparkConnectSessionOwner.java | 143 +++++ .../services/emrserverless/model/Session.java | 3 +- src/main/resources/application.yml | 2 +- .../core/common/SparkConnectProxyTest.java | 3 + .../emr/EmrServiceContainerStepsTest.java | 4 +- .../aws/services/emr/EmrServiceFixture.java | 41 +- .../emr/EmrSessionIntegrationTest.java | 3 +- ...mrSessionServerNightlyIntegrationTest.java | 223 ++++++++ .../services/emr/EmrSessionServerTest.java | 260 +++++++++ .../aws/services/emr/EmrSessionsTest.java | 3 +- .../EmrServerlessSessionServerTest.java | 4 +- .../EmrServerlessSessionServiceTest.java | 2 +- .../SparkConnectServersTest.java | 201 +++++++ 23 files changed, 1926 insertions(+), 451 deletions(-) create mode 100644 src/main/java/io/floci/aws/services/emrserverless/SparkConnectServers.java create mode 100644 src/main/java/io/floci/aws/services/emrserverless/SparkConnectSession.java create mode 100644 src/main/java/io/floci/aws/services/emrserverless/SparkConnectSessionOwner.java create mode 100644 src/test/java/io/floci/aws/services/emr/EmrSessionServerNightlyIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/emr/EmrSessionServerTest.java create mode 100644 src/test/java/io/floci/aws/services/emrserverless/SparkConnectServersTest.java diff --git a/.github/ci/prefetch-images.sh b/.github/ci/prefetch-images.sh index a55b5d8dba..2add537517 100755 --- a/.github/ci/prefetch-images.sh +++ b/.github/ci/prefetch-images.sh @@ -122,14 +122,18 @@ starts EmrDockerRunnerDockerIntegrationTest EmrHiveStepsDockerIntegrationTest Em && ecr public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest # EmrServerlessHiveDockerIntegrationTest runs EMR Serverless Hive job runs, and EmrHiveStepsDockerIntegrationTest EMR # Hive steps, in the emr-7.5.0 Hive image the runner's default Hive template names, 2.7 GB; every EMR cluster runs its -# HDFS in it, EmrDockerRunnerDockerIntegrationTest's and the nightly EmrFlociContainerNightlyIntegrationTest's and -# EmrPigStepsNightlyIntegrationTest's included. +# HDFS in it, EmrDockerRunnerDockerIntegrationTest's and the nightly EmrFlociContainerNightlyIntegrationTest's, +# EmrPigStepsNightlyIntegrationTest's and EmrSessionServerNightlyIntegrationTest's included (an emr-spark-* cluster's +# Hadoop comes from it too). starts EmrServerlessHiveDockerIntegrationTest EmrHiveStepsDockerIntegrationTest EmrDockerRunnerDockerIntegrationTest \ - EmrFlociContainerNightlyIntegrationTest EmrPigStepsNightlyIntegrationTest \ + EmrFlociContainerNightlyIntegrationTest EmrPigStepsNightlyIntegrationTest EmrSessionServerNightlyIntegrationTest \ && 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 +# The nightly EmrSessionServerNightlyIntegrationTest runs an EMR session's Spark Connect server on an emr-spark-8.1.0 +# cluster, Spark 4, sessions needing the AWS runtime for Apache Spark, and its client in that image. +starts EmrSessionServerNightlyIntegrationTest && ecr public.ecr.aws/emr-serverless/spark4/emr-spark-8.1.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 d7b5252909..5564694696 100644 --- a/.github/workflows/nightly-checks.yml +++ b/.github/workflows/nightly-checks.yml @@ -31,10 +31,11 @@ jobs: # 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, - # 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 + # EmrServerlessCustomImageNightlyIntegrationTest's 85 and 21 for its setup, + # EmrServerlessSparkConnectNightlyIntegrationTest's 30, and EmrSessionServerNightlyIntegrationTest's 40, 230 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: 250 # 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.md b/docs/services/emr.md index 37924b612f..5f2567bbc9 100644 --- a/docs/services/emr.md +++ b/docs/services/emr.md @@ -208,8 +208,10 @@ included; see [Step Functions: Amazon EMR tasks](step-functions.md#amazon-emr-ta ## Sessions A session is "a managed connection between your local PySpark client and a Spark Connect Server running on your Amazon -EMR cluster" (Management Guide, "Interactive sessions"). Floci keeps a session and its lifecycle on its cluster, but -starts no Spark Connect server for it, in either runner mode, so nothing answers Spark Connect at its endpoint. +EMR cluster" (Management Guide, "Interactive sessions"). With `runner-mode` set to `docker`, Floci runs that server on +the session's cluster, 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 on its cluster but runs no server for it. * **Starting**: `StartSession` needs a cluster created with `SessionEnabled` (which `DescribeCluster` reports), on "release emr-spark-8.0.0 or later", with "The Spark application installed on the cluster", that is `RUNNING` or @@ -225,22 +227,52 @@ starts no Spark Connect server for it, in either runner mode, so nothing answers `ValidationException`. A retry with the same `ClientRequestToken` that asks for the same session answers as the first call did, a member left out, empty or at its default counting as the same; the token reused for a different session is refused with `InvalidRequestException`. -* **States**: `StartSession` answers `SUBMITTED`, as "When a session is first created, it enters the SUBMITTED state", - and the session is `IDLE` from then on, with `StartedAt` and `IdleSince` its creation time. It is `TERMINATED` once +* **States**: `StartSession` answers `SUBMITTED`, as "When a session is first created, it enters the SUBMITTED state". + In the `immediate` mode the session is `IDLE` from then on, with `StartedAt` and `IdleSince` its creation time; in + the `docker` mode it goes through `STARTING` and `IDLE`, then `BUSY` and back (see below). It is `TERMINATED` once it has been idle for its `SessionIdleTimeoutInMinutes` (60 when not given: "The default timeout is 60 minutes"), when `TerminateSession` ends it, or when its cluster shuts down, its `StateChangeReason` saying which. Floci never reports - `STARTING`, `STARTED`, `BUSY`, `TERMINATING` or `FAILED`. -* **TerminateSession** ends a session at once as `TERMINATED`; AWS's passes through `TERMINATING` first. A session that - has already ended is refused with `InvalidRequestException`, in Floci's own wording. -* **GetSessionEndpoint** answers for a session that has not ended with an endpoint on Floci's own address - (`/_aws/emr/sessions//`) and a fresh `AuthToken` that expires in an hour, as "Authentication - tokens expire after 1 hour". Nothing answers Spark Connect there, and no `Credentials` are given. A session that has - ended is refused with `InvalidRequestException`, in Floci's own wording. + `STARTED`. +* **TerminateSession** ends a session with no server at once as `TERMINATED`; one whose server runs is `TERMINATING` + until its server has stopped, as "the session enters the TERMINATING state and then transitions to TERMINATED". A + session that has already ended is refused with `InvalidRequestException`, 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 `AuthToken` that expires in an hour, as "Authentication tokens expire after 1 + hour". AWS's endpoint is an `https://` URL per session 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. No `Credentials` are given. A session that has + ended, or is `TERMINATING`, is refused with `InvalidRequestException`, in Floci's own wording. * **ListSessions** returns the newest sessions first, as "Newer sessions are returned first", the later of two started in the same millisecond first too, filtered by `SessionStates`, at most `MaxResults` (1 to 100, 100 by default) to a page. * A session's `EngineConfigurations`, `MonitoringConfiguration` and `Tags` are kept as given and reported by - `GetSession`; none of them configures anything, and no session logs are written. + `GetSession`. In the `docker` mode the engine configurations' `spark-defaults` configure its server (below); the + monitoring configuration configures nothing, and no session logs are written. + +### Running a session's Spark Connect server + +With `runner-mode` set to `docker`, each session runs a Spark Connect server on its cluster, as "Amazon EMR launches a +Spark Connect Server as a YARN application on your cluster": a container on the cluster, as a step's is, in the image +its steps run in, its HDFS and YARN started first where they are not running, the server's driver in that container +and its executors on the cluster's YARN. Its `spark-defaults` are the cluster's, then the session's +`EngineConfigurations`, which are "applied to the Spark Connect Server for that session only"; Floci sets +`spark.connect.grpc.binding.port` itself. It runs as the session's `ExecutionRoleArn`, else the cluster's instance +profile. The server's port is published on the Docker host's loopback interface only, and clients reach it through +Floci, as an EMR Serverless session's are (see EMR Serverless, "Running a session's Spark Connect server"). + +* **Connecting**: build the connection string from `GetSessionEndpoint`'s answer as AWS's guide does, but keep the + endpoint's port: `sc://localhost:4566/;x-aws-proxy-auth=;authorization=`, with + `;use_ssl=true` only where Floci's TLS is on. The token names the session; the `authorization` parameter, which + AWS's proxy reads, is dropped before the call reaches the server. The client's PySpark must match the release's + Spark. +* **Tokens**: a call whose token Floci did not give, or which has expired, fails with gRPC's `UNAUTHENTICATED`; one + to a session that is not `IDLE` or `BUSY`, or, in the `immediate` mode, to any session, 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, its `StateChangeReason` saying why; one Floci + stopped running when it restarted fails too, and its container, if one is left, goes. The cluster's end ends its + sessions and stops their servers. ## Studios @@ -879,7 +911,7 @@ its `STARTING` event, has its events sent after the rest of that call's. | `FLOCI_SERVICES_EMR_CLUSTER_STARTUP_DELAY_SECONDS` | `0` | Seconds a new cluster takes to be ready to run steps, the first half `STARTING` and the second `BOOTSTRAPPING`; `0` makes it ready as soon as it is created | | `FLOCI_SERVICES_EMR_STEP_DURATION_SECONDS` | `0` | Seconds a step stays `RUNNING` before it completes; `0` completes it as soon as it starts | | `FLOCI_SERVICES_EMR_CLUSTER_TERMINATION_DELAY_SECONDS` | `0` | Seconds a cluster stays `TERMINATING` before it is `TERMINATED`; `0` ends it at once | -| `FLOCI_SERVICES_EMR_RUNNER_MODE` | `immediate` | `immediate` completes steps by time without running anything; `docker` runs each step in a container, after the cluster's bootstrap actions (see [Running steps](#running-steps)) | +| `FLOCI_SERVICES_EMR_RUNNER_MODE` | `immediate` | `immediate` completes steps by time without running anything; `docker` runs each step, and each session's Spark Connect server, in a container, after the cluster's bootstrap actions (see [Running steps](#running-steps) and [Running a session's Spark Connect server](#running-a-sessions-spark-connect-server)) | | `FLOCI_SERVICES_EMR_DOCKER_NETWORK` | the global default | Docker network for step containers | | `FLOCI_SERVICES_EMR_IMAGE_TEMPLATE` | `public.ecr.aws/emr-serverless/spark/%s:latest`, or `spark4/` in place of `spark/` for an `emr-spark-*` release | Image for a `docker` step, `%s` standing for the cluster's release label; a mirror sets `FLOCI_SERVICES_EMR_HIVE_IMAGE_TEMPLATE` too | | `FLOCI_SERVICES_EMR_HIVE_IMAGE_TEMPLATE` | `public.ecr.aws/emr-serverless/hive/%s:latest` | The EMR Serverless Hive image a `docker` cluster takes HDFS and YARN from, and a cluster with Hive takes Hive from, `%s` standing for the cluster's release label, or `emr-7.5.0` for the Hadoop of an `emr-spark-*` release; see [Storage and Hive steps](#running-steps) | diff --git a/src/main/java/io/floci/aws/core/common/SparkConnectProxy.java b/src/main/java/io/floci/aws/core/common/SparkConnectProxy.java index 17933359d0..fbf0e49b7c 100644 --- a/src/main/java/io/floci/aws/core/common/SparkConnectProxy.java +++ b/src/main/java/io/floci/aws/core/common/SparkConnectProxy.java @@ -54,8 +54,10 @@ public class SparkConnectProxy { // 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"; + // What the server never gets: the connection's own headers, the token, and the session id AWS's EMR connection + // string puts in an authorization parameter for its own proxy. private static final Set NOT_FORWARDED = Set.of("host", "connection", "keep-alive", "proxy-connection", - "transfer-encoding", "upgrade", "http2-settings", TOKEN_METADATA); + "transfer-encoding", "upgrade", "http2-settings", TOKEN_METADATA, "authorization"); 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."; diff --git a/src/main/java/io/floci/aws/services/emr/EmrService.java b/src/main/java/io/floci/aws/services/emr/EmrService.java index 5700d51897..cf06ed93a7 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrService.java +++ b/src/main/java/io/floci/aws/services/emr/EmrService.java @@ -20,6 +20,8 @@ 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.common.StoredResourceArns; import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageBackend; @@ -37,6 +39,9 @@ import io.floci.aws.services.emr.model.EmrSession; import io.floci.aws.services.emr.model.EmrStep; import io.floci.aws.services.emr.model.SecurityConfiguration; import io.floci.aws.services.emrserverless.EmrServerlessSparkRunner; +import io.floci.aws.services.emrserverless.SparkConnectServers; +import io.floci.aws.services.emrserverless.SparkConnectSession; +import io.floci.aws.services.emrserverless.SparkConnectSessionOwner; import io.floci.aws.services.emrserverless.SparkJobRunner; import io.floci.aws.services.iam.IamService; import io.floci.aws.services.iam.model.IamRole; @@ -101,7 +106,7 @@ import java.util.regex.Pattern; * BOOTSTRAPPING, and leave the image its steps then run in. */ @ApplicationScoped -public class EmrService implements Resettable, StoredResourceArns, ContainerTeardown { +public class EmrService implements Resettable, StoredResourceArns, ContainerTeardown, SparkConnectTargets { private static final Logger LOG = Logger.getLogger(EmrService.class); private static final String UPPER_ALNUM = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; @@ -164,6 +169,9 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear private final ClusterStorage clusterStorage; private final ReleaseImages releaseImages; private final Executor stepExecutor; + // The Spark Connect servers of the sessions, in the docker runner mode, and the tokens given for every session. + private final SparkConnectServers sessionServers; + private final SessionOwner sessionOwner = new SessionOwner(); private final IamService iamService; // Where a step's driver runs: image-template, with the release label for %s, and docker-network; null when // not set. @@ -285,7 +293,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear public EmrService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver, EmrEventPublisher eventPublisher, EmrServerlessSparkRunner sparkRunner, EmrBootstrapRunner bootstrapRunner, EmrClusterStorage clusterStorage, - EmrReleaseImages releaseImages, IamService iamService) { + EmrReleaseImages releaseImages, IamService iamService, SparkConnectProxy proxy) { this(storageFactory, config, regionResolver, eventPublisher, Clock.systemUTC(), Wakeups.timer(Clock.systemUTC()), RUNNER_DOCKER.equalsIgnoreCase(config.services().emr().runnerMode()) ? sparkRunner : null, @@ -293,7 +301,12 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear RUNNER_DOCKER.equalsIgnoreCase(config.services().emr().runnerMode()) ? clusterStorage : null, RUNNER_DOCKER.equalsIgnoreCase(config.services().emr().runnerMode()) ? releaseImages : null, Executors.newCachedThreadPool(Thread.ofPlatform().daemon().name("emr-step-", 0).factory()), - iamService); + iamService, + new SparkConnectServers( + RUNNER_DOCKER.equalsIgnoreCase(config.services().emr().runnerMode()) ? sparkRunner : null, + Executors.newCachedThreadPool(Thread.ofPlatform().daemon().name("emr-session-", 0).factory()), + SparkConnectServers.checkThread("emr-session-checks"), SparkConnectServers.probe(proxy), + Clock.systemUTC())); } EmrService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver, @@ -306,6 +319,16 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear EmrEventPublisher eventPublisher, Clock clock, Wakeups wakeups, SparkJobRunner sparkRunner, BootstrapRunner bootstrapRunner, ClusterStorage clusterStorage, ReleaseImages releaseImages, Executor stepExecutor, IamService iamService) { + this(storageFactory, config, regionResolver, eventPublisher, clock, wakeups, sparkRunner, bootstrapRunner, + clusterStorage, releaseImages, stepExecutor, iamService, + new SparkConnectServers(sparkRunner, stepExecutor, null, (host, port) -> "not probed", clock)); + } + + EmrService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver, + EmrEventPublisher eventPublisher, Clock clock, Wakeups wakeups, SparkJobRunner sparkRunner, + BootstrapRunner bootstrapRunner, ClusterStorage clusterStorage, ReleaseImages releaseImages, + Executor stepExecutor, IamService iamService, SparkConnectServers sessionServers) { + this.sessionServers = sessionServers; this.clusterStore = storageFactory.create("emr", "emr-clusters.json", new TypeReference>() {}); this.sessionStore = storageFactory.create("emr", "emr-sessions.json", @@ -393,6 +416,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear if (stepExecutor instanceof ExecutorService executor) { executor.shutdownNow(); } + sessionServers.shutdown(); } /** @@ -427,6 +451,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear generation++; executing.clear(); bootstrapping.clear(); + sessionServers.reset(); if (bootstrapRunner != null) { bootstrapRunner.removeImages(Set.of()); } @@ -735,7 +760,11 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear regionResolver.buildArn("elasticmapreduce", regionOf(cluster), "cluster/" + cluster.getId() + "/session/" + id), regionResolver.getAccountId(), now(), sequence, parameters); + session.setContainerSession(runsSessionServers()); sessionStore.put(id, session); + if (session.isContainerSession()) { + launchSessionServer(cluster, session); + } return sessionCopy(session); }); } @@ -778,31 +807,96 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear }); } + /** + * Terminates a session that has not ended: at once where no server runs for it, else TERMINATING until its server + * has stopped ({@link EmrSessions#terminate}). + */ public EmrSession terminateSession(String clusterId, String sessionId) { return call(() -> { EmrCluster cluster = requireCluster(clusterId); EmrSession session = EmrSessions.find(cluster, settledSessions(cluster), sessionId); - EmrSessions.terminate(session, now()); - sessionStore.put(session.getId(), session); + if (sessionServers.runs(session.getId())) { + EmrSessions.terminating(session, now()); + sessionStore.put(session.getId(), session); + sessionServers.stop(session.getId()); + } else { + EmrSessions.terminate(session, now()); + sessionStore.put(session.getId(), session); + } return sessionCopy(session); }); } /** * Where a client connects to a session that has not ended, with a token that expires in an hour, as - * "Authentication tokens expire after 1 hour". The endpoint is on Floci's own address, where nothing answers - * Spark Connect, as Floci runs no Spark Connect server for a session. + * "Authentication tokens expire after 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 names the session. AWS's connection string + * adds the session's id as its {@code authorization} parameter, which the proxy drops. A session that is + * TERMINATING is refused as one that has ended. */ public SparkConnectEndpoint sessionEndpoint(String clusterId, String sessionId) { return call(() -> { EmrCluster cluster = requireCluster(clusterId); EmrSession session = EmrSessions.find(cluster, settledSessions(cluster), sessionId); EmrSessions.requireNotEnded(session); - return SparkConnectEndpoint.issue(baseUrl, EmrSessions.ENDPOINT_PATH + cluster.getId() + "/" - + session.getId(), now(), EmrSessions.TOKEN_VALIDITY); + if (EmrSessions.TERMINATING.equals(session.getState())) { + throw invalid("Session " + session.getId() + " has already ended."); + } + SparkConnectEndpoint endpoint = SparkConnectEndpoint.issue(baseUrl, "", now(), + EmrSessions.TOKEN_VALIDITY); + sessionServers.grant(endpoint.authToken(), session.getId(), session.getAccountId(), regionOf(cluster), + endpoint.authTokenExpiresAt()); + return endpoint; }); } + /** Where a Spark Connect call carrying {@code token} goes: a session's server, {@link SparkConnectServers}. */ + @Override + public Optional route(String token) { + return sessionServers.route(token, sessionOwner); + } + + // Whether a session runs a Spark Connect server: in the docker runner mode, where its cluster has storage. + private boolean runsSessionServers() { + return sparkRunner != null && clusterStorage != null; + } + + /** + * Runs a session's Spark Connect server on its cluster, as a step runs, a YARN application there: its driver in a + * container on the cluster, in the image its steps run in, reached through Floci. Its {@code spark-defaults} are + * the cluster's, then the session's engine configurations, "applied to the Spark Connect Server for that session + * only", with the server's port; it runs as the session's runtime role, else the cluster's instance profile. The + * server is in Spark's own jars on the AWS runtime for Apache Spark, which sessions need. + */ + private void launchSessionServer(EmrCluster cluster, EmrSession session) { + String accountId = regionResolver.getAccountId(); + String region = regionOf(cluster); + OnCluster onCluster = onCluster(cluster, accountId, region, true); + // The cluster keeps its storage from now, which its end releases once its servers have gone. + clusterStore.put(cluster.getId(), cluster); + Map sparkDefaults = new LinkedHashMap<>( + EmrSparkSteps.sparkDefaults(cluster.getConfigurations(), SNAPSHOT_MAPPER)); + if (session.getEngineConfigurations() != null) { + sparkDefaults.putAll(EmrSparkSteps.sparkDefaults(session.getEngineConfigurations(), SNAPSHOT_MAPPER)); + } + sparkDefaults.put("spark.connect.grpc.binding.port", String.valueOf(EmrSessions.SPARK_CONNECT_PORT)); + String role = session.getExecutionRoleArn() != null ? session.getExecutionRoleArn() + : instanceProfileRole(cluster, accountId); + SparkJobRunner.Job job = new SparkJobRunner.Job(SERVICE, session.getId(), accountId, region, + cluster.getReleaseLabel(), SparkJobRunner.Engine.SPARK, onCluster.image(), null, dockerNetwork, role, + sparkDefaults, List.of("--class", EmrSessions.SPARK_CONNECT_SERVER, "spark-internal"), null, + Duration.ZERO, null, null, Map.of(), List.of(), onCluster.storage(), + EmrSparkSteps.coreSite(cluster.getConfigurations(), SNAPSHOT_MAPPER), + EmrSparkSteps.sparkLog4j2(cluster.getConfigurations(), SNAPSHOT_MAPPER), + EmrSparkSteps.mapredSite(cluster.getConfigurations(), SNAPSHOT_MAPPER), + EmrSparkSteps.hadoopLog4j(cluster.getConfigurations(), SNAPSHOT_MAPPER), + EmrSparkSteps.hadoopEnvironment(cluster.getConfigurations(), SNAPSHOT_MAPPER), null) + .listeningOn(EmrSessions.SPARK_CONNECT_PORT); + sessionServers.launch(job, new ClusterPreparation(cluster.getId(), accountId, region, + onCluster.releaseImage(), onCluster.hdfs(), onCluster.primary()), sessionOwner); + } + /** * The cluster's sessions, as stored, oldest first, once the cluster and each of them is brought up to date: kept * apart from the cluster, so that its sessions, ended ones included, weigh on no other read or write of it. @@ -815,8 +909,23 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear .sorted(Comparator.comparingLong(EmrSession::getSequence)) .toList(); for (EmrSession session : sessions) { - if (EmrSessions.settle(cluster, session, now)) { + if (session.isContainerSession() && !EmrSessions.ended(session) + && !sessionServers.runs(session.getId())) { + // 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. + boolean terminating = EmrSessions.TERMINATING.equals(session.getState()); + EmrSessions.end(session, terminating ? EmrSessions.TERMINATED : EmrSessions.FAILED, + terminating ? EmrSessions.USER_REQUEST : EmrSessions.INTERRUPTED, now); sessionStore.put(session.getId(), session); + if (sparkRunner != null) { + sparkRunner.removeLeftoverDriver(SERVICE, session.getId()); + } + } else if (EmrSessions.settle(cluster, session, now)) { + sessionStore.put(session.getId(), session); + // An ended session's server goes with it, its tokens and its check. + if (EmrSessions.ended(session)) { + sessionServers.stop(session.getId()); + } } } return sessions; @@ -854,6 +963,99 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear return Objects.equals(rawJson(stored), rawJson(retried)); } + /** + * Why a session takes no Spark Connect call now, or null while it does, IDLE or BUSY. No source gives AWS's answer + * for a session that has not started or has ended, so the wording is Floci's. + */ + private String sessionRefusal(String sessionId) { + return call(() -> { + EmrSession stored = sessionStore.get(sessionId).orElse(null); + EmrCluster cluster = stored != null ? clusterStore.get(stored.getClusterId()).orElse(null) : null; + if (stored == null || cluster == null) { + return String.format(EmrSessions.NOT_READY, sessionId, EmrSessions.TERMINATED); + } + EmrSession session = settledSessions(cluster).stream() + .filter(candidate -> sessionId.equals(candidate.getId())).findFirst().orElse(stored); + if (!session.isContainerSession()) { + return String.format(EmrSessions.NO_SERVER, sessionId); + } + boolean ready = EmrSessions.IDLE.equals(session.getState()) + || EmrSessions.BUSY.equals(session.getState()); + return ready ? null : String.format(EmrSessions.NOT_READY, sessionId, session.getState()); + }); + } + + // Checks an idle session again once its idle timeout would have passed, so it ends then, its server with it; a busy + // one has no deadline, so its check goes. + private void checkSessionLater(EmrSession session) { + if (session.getIdleSince() == null || session.getSessionIdleTimeoutInMinutes() <= 0) { + sessionServers.cancelCheck(session.getId()); + return; + } + String clusterId = session.getClusterId(); + sessionServers.checkAt(session.getId(), + session.getIdleSince().plus(Duration.ofMinutes(session.getSessionIdleTimeoutInMinutes())), + () -> run(() -> clusterStore.get(clusterId).ifPresent(this::settledSessions))); + } + + /** The service as its sessions' servers' owner ({@link SparkConnectSessionOwner}), under its lock. */ + private final class SessionOwner extends SparkConnectSessionOwner { + + @Override + protected T locked(Supplier body) { + return call(body); + } + + @Override + protected Optional find(String sessionId) { + return sessionStore.get(sessionId); + } + + @Override + protected SparkConnectSession session(EmrSession stored) { + return stored; + } + + @Override + protected void save(EmrSession stored) { + sessionStore.put(stored.getId(), stored); + } + + @Override + protected Instant now() { + return EmrService.this.now(); + } + + @Override + protected void end(EmrSession stored, String state, String reason) { + EmrSessions.end(stored, state, reason, now()); + sessionStore.put(stored.getId(), stored); + } + + // The reason it has, as TerminateSession or its cluster's end gave it. + @Override + protected String endReason(EmrSession stored, SparkJobRunner.Outcome outcome) { + return stored.getStateChangeReason(); + } + + @Override + protected void checkLater(EmrSession stored) { + checkSessionLater(stored); + } + + @Override + public String refusal(String sessionId) { + return sessionRefusal(sessionId); + } + + @Override + public void gone(String sessionId) { + // What the session's cluster kept may go now that its server no longer holds it. + run(() -> sessionStore.get(sessionId).flatMap(session -> clusterStore.get(session.getClusterId())) + .ifPresent(EmrService.this::releaseEnded)); + } + } + private static EmrSession sessionCopy(EmrSession session) { return SNAPSHOT_MAPPER.convertValue(session, EmrSession.class); } @@ -1852,12 +2054,37 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear } // What an ended cluster kept goes once no step of it still runs in a container: its bootstrap's image and - // its storage. + // its storage. Its sessions end as it shuts down, their servers with them, whether or not a session is read. private void releaseEnded(EmrCluster cluster) { + endSessionsOf(cluster); releaseBootstrapImage(cluster); releaseStorage(cluster); } + // A cluster shutting down ends its sessions that have not ended, as "Terminating the cluster also ends any sessions + // still running on it", and stops their servers. + private void endSessionsOf(EmrCluster cluster) { + Instant now = now(); + if (!cluster.isSessionEnabled() || EmrService.shutDownAt(cluster, now) == null) { + return; + } + for (EmrSession session : sessionStore.scan(key -> true)) { + if (cluster.getId().equals(session.getClusterId()) && EmrSessions.settle(cluster, session, now)) { + sessionStore.put(session.getId(), session); + if (EmrSessions.ended(session)) { + sessionServers.stop(session.getId()); + } + } + } + } + + // Whether a server of the cluster's sessions is still there, its container perhaps still on its storage. + private boolean sessionServersRunning(EmrCluster cluster) { + return cluster.isSessionEnabled() && sessionStore.scan(key -> true).stream() + .anyMatch(session -> cluster.getId().equals(session.getClusterId()) + && sessionServers.runs(session.getId())); + } + private boolean stepsExecuting(EmrCluster cluster, String accountId) { return cluster.getSteps().stream().anyMatch(step -> executing.contains(stepKey(accountId, step.getId()))); } @@ -1924,7 +2151,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear } String accountId = regionResolver.getAccountId(); String key = clusterKey(accountId, cluster.getId()); - if (stepsExecuting(cluster, accountId) || !storageBeingRemoved.add(key)) { + // A session's server still there keeps it too; once the last has gone, the release is tried again. + if (stepsExecuting(cluster, accountId) || sessionServersRunning(cluster) || !storageBeingRemoved.add(key)) { return; } String clusterId = cluster.getId(); @@ -2087,6 +2315,49 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear return launch.launchedIn() != generation; } + /** + * Where a container runs on the cluster, a step's or a session's server's: the cluster's storage, where it is made + * (null for none); the image, the one its bootstrap left, which holds what its release's does, else the template's; + * the release's image, resolved on the container's thread, for a cluster whose bootstrap left none; what starts + * the cluster's HDFS on its primary node; and that node. + */ + private record OnCluster(SparkJobRunner.Storage storage, String image, Supplier releaseImage, + BiFunction hdfs, Instance primary) { + } + + /** + * Where a container runs on the cluster, {@link OnCluster}, with the cluster's storage made where {@code storage} + * says one needs it and Floci keeps clusters' storage. Every EMR cluster runs HDFS on its primary node, which the + * container's thread starts when it is not running: a NameNode and a DataNode, on a cluster with Hive or HCatalog + * its metastore service, and on one that runs YARN a ResourceManager and a NodeManager, in a container of the + * image its steps run in, as an EMR cluster's nodes hold every application it installs, or else of the release's + * Hive image, the one with HDFS's daemons. + */ + private OnCluster onCluster(EmrCluster cluster, String accountId, String region, boolean storage) { + SparkJobRunner.Storage volumes = null; + if (storage && clusterStorage != null) { + volumes = clusterStorage.volumes(cluster.getId()); + cluster.setStorageCreated(true); + String known = cluster.getId(); + clusterStorage.identify(known, node -> nodeIdentity(known, accountId, region, node)); + } + String image = cluster.getBootstrapImage() != null ? cluster.getBootstrapImage() : imageTemplate; + Supplier releaseImage = cluster.getBootstrapImage() == null ? releaseImage(cluster) : null; + String clusterId = cluster.getId(); + String hdfsHost = masterPrivateDnsName(cluster); + String hdfsImage = hdfsImage(cluster.getReleaseLabel()); + Supplier nodeYarn = runsYarn(cluster) ? currentYarn(cluster, accountId, region) : null; + ClusterStorage.HiveMetastore hiveMetastore = EmrSparkSteps.installsHive(cluster.getReleaseLabel(), + cluster.getApplications(), SNAPSHOT_MAPPER) + ? new ClusterStorage.HiveMetastore(instanceProfileRole(cluster, accountId), + EmrSparkSteps.hiveMetastoreSettings(cluster.getConfigurations(), SNAPSHOT_MAPPER)) + : null; + BiFunction hdfs = volumes == null ? null + : (stepImage, stopped) -> clusterStorage.hdfs(clusterId, accountId, region, hdfsHost, + nodeYarn != null ? stepImage : hdfsImage, dockerNetwork, hiveMetastore, nodeYarn, stopped); + return new OnCluster(volumes, image, releaseImage, hdfs, nodeInstance(cluster, accountId, 0, 1)); + } + /** A step handed to a thread: whose it is, where, and under which reset. */ private record StepLaunch(String accountId, String region, String clusterId, String stepId, long launchedIn, long teardownsBefore) {} @@ -2112,34 +2383,10 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear List application = hive == null ? EmrSparkSteps.application(step, yarn) : null; List command = hive == null && application == null ? EmrSparkSteps.command(step, pigMissing) : null; - SparkJobRunner.Storage storage = null; - if ((hive != null || application != null || command != null) && clusterStorage != null) { - storage = clusterStorage.volumes(cluster.getId()); - cluster.setStorageCreated(true); - String known = cluster.getId(); - clusterStorage.identify(known, node -> nodeIdentity(known, accountId, region, node)); - } - // The image a cluster's bootstrap left, which holds what its release's does; else a cluster with Hive's or - // YARN's, which the step's thread makes, or the release's. - String image = cluster.getBootstrapImage() != null ? cluster.getBootstrapImage() : imageTemplate; - Supplier releaseImage = cluster.getBootstrapImage() == null ? releaseImage(cluster) : null; - // Every EMR cluster runs HDFS on its primary node, which the step's thread starts when it is not running: - // a NameNode and a DataNode, on a cluster with Hive or HCatalog its metastore service, and on one that runs - // YARN a ResourceManager and a NodeManager, in a container of the image its steps run in, as an EMR - // cluster's nodes hold every application it installs, or else of the release's Hive image, the one with - // HDFS's daemons. - String clusterId = cluster.getId(); - String hdfsHost = masterPrivateDnsName(cluster); - String hdfsImage = hdfsImage(cluster.getReleaseLabel()); - Supplier nodeYarn = yarn ? currentYarn(cluster, accountId, region) : null; - ClusterStorage.HiveMetastore hiveMetastore = EmrSparkSteps.installsHive(cluster.getReleaseLabel(), - cluster.getApplications(), SNAPSHOT_MAPPER) - ? new ClusterStorage.HiveMetastore(instanceProfileRole(cluster, accountId), - EmrSparkSteps.hiveMetastoreSettings(cluster.getConfigurations(), SNAPSHOT_MAPPER)) - : null; - BiFunction hdfs = storage == null ? null - : (stepImage, stopped) -> clusterStorage.hdfs(clusterId, accountId, region, hdfsHost, - nodeYarn != null ? stepImage : hdfsImage, dockerNetwork, hiveMetastore, nodeYarn, stopped); + OnCluster onCluster = onCluster(cluster, accountId, region, + hive != null || application != null || command != null); + SparkJobRunner.Storage storage = onCluster.storage(); + String image = onCluster.image(); SparkJobRunner.Job job; if (hive != null) { job = new SparkJobRunner.Job(SERVICE, step.getId(), accountId, region, cluster.getReleaseLabel(), @@ -2168,8 +2415,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear teardowns.get()); executing.add(stepKey(accountId, step.getId())); String containerLogs = yarn ? EmrSparkSteps.containerLogFolder(cluster) : null; - Instance primary = nodeInstance(cluster, accountId, 0, 1); - stepExecutor.execute(() -> runStep(job, launch, releaseImage, hdfs, containerLogs, primary)); + stepExecutor.execute(() -> runStep(job, launch, onCluster.releaseImage(), onCluster.hdfs(), containerLogs, + onCluster.primary())); } @Override @@ -2178,6 +2425,64 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear } } + /** + * What a step's thread, or a session's server's, does on the cluster before its driver runs: the release's image + * resolved, where the cluster names none of its own; and, for a job on the cluster's storage, that storage made, + * the primary node's instance metadata placed, the actions of nodes a resize added run, and its HDFS running, which + * the job then runs on. A job a cancel, its cluster's end or a reset has passed makes none of it. Afterwards the + * image may go once a newer one of its kind is made, and the metadata address to another. + */ + private final class ClusterPreparation implements SparkConnectServers.Preparation { + + private final String clusterId; + private final String accountId; + private final String region; + private final Supplier releaseImage; + private final BiFunction hdfs; + private final Instance primary; + private String image; + private String address; + + ClusterPreparation(String clusterId, String accountId, String region, Supplier releaseImage, + BiFunction hdfs, Instance primary) { + this.clusterId = clusterId; + this.accountId = accountId; + this.region = region; + this.releaseImage = releaseImage; + this.hdfs = hdfs; + this.primary = primary; + } + + @Override + public SparkJobRunner.Job prepare(SparkJobRunner.Job job, BooleanSupplier cancelled) { + image = releaseImage != null && !cancelled.getAsBoolean() ? releaseImage.get() : null; + SparkJobRunner.Job running = image != null ? job.inImage(image) : job; + // The cluster's storage is there, its HDFS running, before its first container mounts it. That container + // reads the primary node's instance metadata, as a step on EMR's primary node does. + if (job.storage() != null && !cancelled.getAsBoolean()) { + clusterStorage.create(clusterId, accountId, region); + MetadataPlace place = metadataPlace(clusterId, accountId, region, running.imageTemplate(), + running.releaseLabel(), primary); + address = place != null ? place.address() : null; + // A node a resize added since the cluster's bootstrap runs its actions before it starts. + bootstrapAddedNodes(clusterId, accountId, region); + SparkJobRunner.Storage storage = hdfs.apply(running.imageTemplate(), cancelled); + running = running.onStorage(address != null ? storage.withMetadataAddress(address) : storage); + } + return running; + } + + @Override + public void release() { + if (image != null) { + releaseImages.released(image); + } + if (address != null) { + clusterStorage.releaseMetadataAddress(address); + } + } + } + // A step's thread: its driver runs to its end, or the step fails at once when Floci does not run its kind. A // cluster with Hive's or YARN's image is made first, when it is not there yet, so a failure to make it fails the // step. @@ -2190,25 +2495,10 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear } else { SparkJobRunner.Outcome outcome; StepProgress progress = new StepProgress(launch); - String image = null; - String address = null; + ClusterPreparation preparation = new ClusterPreparation(launch.clusterId(), launch.accountId(), + launch.region(), releaseImage, hdfs, primary); try { - image = releaseImage != null && !progress.cancelled() ? releaseImage.get() : null; - SparkJobRunner.Job running = image != null ? job.inImage(image) : job; - // The cluster's storage is there, its HDFS running, before its first step's container mounts it. A step - // a cancel, its cluster's end or a reset has passed does not start, so it makes none. Its container - // reads the primary node's instance metadata, as a step on EMR's primary node does. - if (job.storage() != null && !progress.cancelled()) { - clusterStorage.create(launch.clusterId(), launch.accountId(), launch.region()); - MetadataPlace place = metadataPlace(launch.clusterId(), launch.accountId(), launch.region(), - running.imageTemplate(), running.releaseLabel(), primary); - address = place != null ? place.address() : null; - // A node a resize added since the cluster's bootstrap runs its actions before it starts. - bootstrapAddedNodes(launch.clusterId(), launch.accountId(), launch.region()); - SparkJobRunner.Storage storage = hdfs.apply(running.imageTemplate(), progress::cancelled); - running = running.onStorage(address != null ? storage.withMetadataAddress(address) : storage); - } - outcome = sparkRunner.run(running, progress); + outcome = sparkRunner.run(preparation.prepare(job, progress::cancelled), progress); } catch (ClusterStorage.Stopped e) { // It stopped while its HDFS started, before its driver did, as a driver stopped then would. outcome = SparkJobRunner.Outcome.halted(); @@ -2223,14 +2513,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear outcome = SparkJobRunner.Outcome.couldNotStart(e.getMessage()); } } finally { - // Its containers have come and gone, or never came, so a newer image of its kind may remove this one, - // and its address on the cluster's network may go to another. - if (image != null) { - releaseImages.released(image); - } - if (address != null) { - clusterStorage.releaseMetadataAddress(address); - } + preparation.release(); } // A reset since the step started has swept the storage and wiped its cluster, so nothing would remove // volumes made, or mounted, after its sweep: they go now, the step's container being gone. diff --git a/src/main/java/io/floci/aws/services/emr/EmrSessions.java b/src/main/java/io/floci/aws/services/emr/EmrSessions.java index e2b28da1aa..2d978152c4 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrSessions.java +++ b/src/main/java/io/floci/aws/services/emr/EmrSessions.java @@ -26,11 +26,15 @@ import java.util.Set; final class EmrSessions { static final String SUBMITTED = "SUBMITTED"; + static final String STARTING = "STARTING"; static final String IDLE = "IDLE"; + static final String BUSY = "BUSY"; + static final String TERMINATING = "TERMINATING"; static final String TERMINATED = "TERMINATED"; + static final String FAILED = "FAILED"; static final List STATES = - List.of(SUBMITTED, "STARTING", "STARTED", IDLE, "BUSY", "TERMINATING", TERMINATED, "FAILED"); - private static final Set ENDED = Set.of(TERMINATED, "FAILED"); + List.of(SUBMITTED, STARTING, "STARTED", IDLE, BUSY, TERMINATING, TERMINATED, FAILED); + private static final Set ENDED = Set.of(TERMINATED, FAILED); // "Amazon EMR enforces a limit of 1000 concurrent active sessions per cluster." static final int MAX_CONCURRENT_SESSIONS = 1000; // "Sessions end after a configurable idle timeout. The default timeout is 60 minutes, with a maximum of 24 hours." @@ -40,8 +44,9 @@ final class EmrSessions { static final Duration TOKEN_VALIDITY = Duration.ofHours(1); // ListSessions' MaxResultsNumber is 1 to 100. static final int MAX_LIST_RESULTS = 100; - // Where GetSessionEndpoint points; nothing answers Spark Connect there, as Floci runs no server for a session. - static final String ENDPOINT_PATH = "/_aws/emr/sessions/"; + // 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; + static final String SPARK_CONNECT_SERVER = "org.apache.spark.sql.connect.service.SparkConnectServer"; private static final int MAX_NAME_LENGTH = 256; private static final int MIN_TOKEN_LENGTH = 1; private static final int MAX_TOKEN_LENGTH = 36; @@ -54,6 +59,10 @@ final class EmrSessions { static final String IDLE_TIMED_OUT = "The session was idle for its idle timeout."; static final String CLUSTER_ENDED = "The session's cluster was terminated."; static final String USER_REQUEST = "The session was terminated by request."; + static final String INTERRUPTED = "Floci stopped while the session was running."; + static final String NO_SERVER = "Floci runs no Spark Connect server for session %s, as the EMR runner mode is" + + " immediate; floci.services.emr.runner-mode docker runs one."; + static final String NOT_READY = "Session %s is %s, not ready for calls."; private EmrSessions() { } @@ -192,8 +201,8 @@ final class EmrSessions { } /** - * Brings a session of the cluster up to {@code now}: a SUBMITTED one is IDLE from when it was made, as nothing has - * to start; an IDLE one ends once its idle timeout has passed since it went idle; and every one that has not + * Brings a session of the cluster up to {@code now}: a SUBMITTED one with no server to start is IDLE from when it + * was made; an IDLE one ends once its idle timeout has passed since it went idle; and every one that has not * ended ends as its cluster shuts down, whichever comes first. Returns whether it changed. */ static boolean settle(EmrCluster cluster, EmrSession session, Instant now) { @@ -202,7 +211,7 @@ final class EmrSessions { } boolean changed = false; Instant clusterEnd = EmrService.shutDownAt(cluster, now); - if (SUBMITTED.equals(session.getState()) + if (SUBMITTED.equals(session.getState()) && !session.isContainerSession() && (clusterEnd == null || session.getCreatedAt().isBefore(clusterEnd))) { session.setState(IDLE); session.setStartedAt(session.getCreatedAt()); @@ -239,14 +248,38 @@ final class EmrSessions { /** * Terminates a session that has not ended: "After you call this operation, the session enters the TERMINATING - * state and then transitions to TERMINATED." With no server to stop, Floci's is TERMINATED at once. One that has - * already ended is refused, in Floci's own wording, as AWS's answer is not recorded. + * state and then transitions to TERMINATED." With no server to stop, Floci's is TERMINATED at once; one whose + * server runs is TERMINATING until it has stopped ({@link #terminating}). One that has already ended is refused, + * in Floci's own wording, as AWS's answer is not recorded. */ static void terminate(EmrSession session, Instant now) { requireNotEnded(session); end(session, USER_REQUEST, now); } + /** A session whose server is being stopped at the request's word: TERMINATING until it has stopped. */ + static void terminating(EmrSession session, Instant now) { + requireNotEnded(session); + session.setState(TERMINATING); + session.setStateChangeReason(USER_REQUEST); + session.setUpdatedAt(now); + session.setIdleSince(null); + } + + /** Ends a session as {@code state}, TERMINATED or FAILED, for {@code reason}, at {@code at}. */ + static void end(EmrSession session, String state, String reason, Instant at) { + session.setState(state); + session.setStateChangeReason(reason); + session.setEndedAt(at); + session.setUpdatedAt(at); + session.setIdleSince(null); + } + + /** Whether the session has ended, TERMINATED or FAILED. */ + static boolean ended(EmrSession session) { + return ENDED.contains(session.getState()); + } + /** Refuses a session that has ended, which has nothing to connect to or terminate. */ static void requireNotEnded(EmrSession session) { if (ENDED.contains(session.getState())) { @@ -263,10 +296,6 @@ final class EmrSessions { } private static void end(EmrSession session, String reason, Instant at) { - session.setState(TERMINATED); - session.setStateChangeReason(reason); - session.setEndedAt(at); - session.setUpdatedAt(at); - session.setIdleSince(null); + end(session, TERMINATED, reason, at); } } diff --git a/src/main/java/io/floci/aws/services/emr/model/EmrSession.java b/src/main/java/io/floci/aws/services/emr/model/EmrSession.java index b089b87d05..58778100cd 100644 --- a/src/main/java/io/floci/aws/services/emr/model/EmrSession.java +++ b/src/main/java/io/floci/aws/services/emr/model/EmrSession.java @@ -1,5 +1,6 @@ package io.floci.aws.services.emr.model; +import io.floci.aws.services.emrserverless.SparkConnectSession; import io.quarkus.runtime.annotations.RegisterForReflection; import java.time.Instant; @@ -12,7 +13,7 @@ import java.util.Map; * repeated StartSession is a retry. Its engine and monitoring configurations are kept as the request's raw JSON. */ @RegisterForReflection -public class EmrSession { +public class EmrSession implements SparkConnectSession { private String id; private String clusterId; @@ -36,6 +37,8 @@ public class EmrSession { private Map tags = new LinkedHashMap<>(); private String clientRequestToken; private String request; + // Whether Floci runs a Spark Connect server for it, as it does in the docker runner mode. + private boolean containerSession; public EmrSession() {} @@ -87,4 +90,6 @@ public class EmrSession { public void setClientRequestToken(String clientRequestToken) { this.clientRequestToken = clientRequestToken; } public String getRequest() { return request; } public void setRequest(String request) { this.request = request; } + public boolean isContainerSession() { return containerSession; } + public void setContainerSession(boolean containerSession) { this.containerSession = containerSession; } } 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 c248582d2d..1713836056 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSessionService.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSessionService.java @@ -48,6 +48,7 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; /** * EMR Serverless sessions: "a managed connection between your local PySpark client and a Spark driver running on Amazon @@ -79,9 +80,6 @@ public class EmrServerlessSessionService implements SparkConnectTargets, Resetta 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; @@ -102,12 +100,6 @@ public class EmrServerlessSessionService implements SparkConnectTargets, Resetta 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."; @@ -123,16 +115,9 @@ public class EmrServerlessSessionService implements SparkConnectTargets, Resetta 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; + // The sessions' Spark Connect servers, and the tokens given for them. + private final SparkConnectServers servers; + private final SessionOwner owner = new SessionOwner(); // The latest sequence a session was given, EmrServerlessService.nextSequence. private long lastSequence; @@ -147,8 +132,7 @@ public class EmrServerlessSessionService implements SparkConnectTargets, Resetta config.effectiveBaseUrl(), jobRuns.containerRunner(), Executors.newCachedThreadPool(Thread.ofPlatform().daemon().name("emr-serverless-session-", 0) .factory()), - sessionChecks(), - (host, port) -> unanswered(proxy, host, port)); + SparkConnectServers.checkThread("emr-serverless-session-checks"), SparkConnectServers.probe(proxy)); } EmrServerlessSessionService(AccountAwareStorageBackend store, EmrServerlessService applications, @@ -163,11 +147,10 @@ public class EmrServerlessSessionService implements SparkConnectTargets, Resetta EmrServerlessJobRunService jobRuns, IamService iamService, RegionResolver regionResolver, RequestContext requestContext, ObjectMapper objectMapper, Clock clock, String baseUrl, SparkJobRunner sparkRunner, - Executor serverExecutor, ScheduledExecutorService idleChecks, ServerProbe probe) { + Executor serverExecutor, ScheduledExecutorService checks, + SparkConnectServers.Probe probe) { this.sparkRunner = sparkRunner; - this.serverExecutor = serverExecutor; - this.idleChecks = idleChecks; - this.probe = probe; + this.servers = new SparkConnectServers(sparkRunner, serverExecutor, checks, probe, clock); this.store = store; this.applications = applications; this.jobRuns = jobRuns; @@ -181,12 +164,7 @@ public class EmrServerlessSessionService implements SparkConnectTargets, Resetta @PreDestroy void shutdown() { - if (serverExecutor instanceof ExecutorService executor) { - executor.shutdownNow(); - } - if (idleChecks != null) { - idleChecks.shutdownNow(); - } + servers.shutdown(); } /** @@ -194,10 +172,8 @@ public class EmrServerlessSessionService implements SparkConnectTargets, Resetta * teardown stops their containers. */ @Override - public synchronized void beforeReset() { - generation++; - servers.clear(); - grants.clear(); + public void beforeReset() { + servers.reset(); } @Override @@ -290,17 +266,14 @@ public class EmrServerlessSessionService implements SparkConnectTargets, Resetta 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); + if (servers.runs(sessionId)) { 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); + servers.stop(sessionId); LOG.infov("Terminating EMR Serverless session {0} on application {1}", sessionId, applicationId); return copy(session); } @@ -322,12 +295,9 @@ public class EmrServerlessSessionService implements SparkConnectTargets, Resetta if (ENDED.contains(session.getState()) || STATE_TERMINATING.equals(session.getState())) { throw new AwsException("ValidationException", "Session " + sessionId + " has ended.", 400); } - Instant now = now(); - SparkConnectEndpoint endpoint = SparkConnectEndpoint.issue(baseUrl, "", now, TOKEN_VALIDITY); - grants.values().removeIf(grant -> !now.isBefore(grant.expiresAt())); + SparkConnectEndpoint endpoint = SparkConnectEndpoint.issue(baseUrl, "", now(), TOKEN_VALIDITY); AwsArnUtils.Arn arn = AwsArnUtils.parse(session.getArn()); - grants.put(endpoint.authToken(), new Grant(arn.accountId(), arn.region(), sessionId, - endpoint.authTokenExpiresAt())); + servers.grant(endpoint.authToken(), sessionId, arn.accountId(), arn.region(), endpoint.authTokenExpiresAt()); return endpoint; } @@ -338,64 +308,7 @@ public class EmrServerlessSessionService implements SparkConnectTargets, Resetta */ @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); - }); + return servers.route(token, owner); } /** @@ -606,149 +519,28 @@ public class EmrServerlessSessionService implements SparkConnectTargets, Resetta return record; } - // Hands a session's server to a thread of its own, which runs it until the session ends. + // Runs a session's server 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())); + servers.launch(jobRuns.sessionJob(app, record.getSession(), Duration.ZERO, SPARK_CONNECT_PORT), owner); } /** - * 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. + * Why a session takes no Spark Connect call now, or null while it does, IDLE or BUSY. No source gives AWS's answer + * for a session that has not started or has ended, so the wording is Floci's. */ - private synchronized void serverEnded(String sessionId, SparkJobRunner.Outcome outcome, long launchedIn) { - if (launchedIn != generation) { - return; + private synchronized String refusal(String sessionId) { + SessionRecord record = store.get(sessionId).orElse(null); + if (record == null) { + return String.format(NOT_READY, sessionId, STATE_TERMINATED); } - Server server = servers.remove(sessionId); - if (server != null) { - cancelCheck(server); + Session session = settle(record).getSession(); + if (!record.isContainerSession()) { + return String.format(NO_SERVER, sessionId); } - 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); - } - }); + boolean ready = STATE_IDLE.equals(session.getState()) || STATE_BUSY.equals(session.getState()); + return ready ? null : String.format(NOT_READY, sessionId, session.getState()); } /** @@ -758,8 +550,7 @@ public class EmrServerlessSessionService implements SparkConnectTargets, Resetta */ private void checkLater(SessionRecord record) { Session session = record.getSession(); - Server server = servers.get(session.getSessionId()); - if (idleChecks == null || server == null || session.getStartedAt() == null) { + if (session.getStartedAt() == null) { return; } Instant deadline = session.getStartedAt().plus(HARD_LIMIT); @@ -769,53 +560,14 @@ public class EmrServerlessSessionService implements SparkConnectTargets, Resetta 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; - } + servers.checkAt(sessionId, deadline, () -> checkNow(sessionId)); } 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(); - } - } - /** * Sets on {@code session} what a session takes from the request that starts it, as it holds it: its name, role, * runtime configuration overrides alone, as "Only runtime configuration overrides are supported", idle timeout @@ -865,7 +617,7 @@ public class EmrServerlessSessionService implements SparkConnectTargets, Resetta } // 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())) { + if (record.isContainerSession() && !servers.runs(session.getSessionId())) { boolean terminating = STATE_TERMINATING.equals(session.getState()); end(record, terminating ? STATE_TERMINATED : STATE_FAILED, terminating ? null : INTERRUPTED, now()); if (sparkRunner != null) { @@ -898,13 +650,9 @@ public class EmrServerlessSessionService implements SparkConnectTargets, Resetta 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()); - } + // An ended session's server goes with it, its tokens and its check; its thread finds the session ended and + // leaves it so. + servers.stop(session.getSessionId()); } private SessionRecord findSession(String applicationId, String sessionId) { @@ -937,57 +685,56 @@ public class EmrServerlessSessionService implements SparkConnectTargets, Resetta 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; - } + /** The service as its servers' owner ({@link SparkConnectSessionOwner}), its sessions stored in records. */ + private final class SessionOwner extends SparkConnectSessionOwner { @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)); + protected T locked(Supplier body) { + synchronized (EmrServerlessSessionService.this) { + return body.get(); } } @Override - public void timedOut() { - // The run's outcome says so, which serverEnded reads. + protected Optional find(String sessionId) { + return store.get(sessionId); } @Override - public boolean cancelled() { - return !RequestScopes.callAs(job.accountId(), job.region(), () -> stillGoing(job.runId(), launchedIn)); + protected SparkConnectSession session(SessionRecord stored) { + return stored.getSession(); + } + + @Override + protected void save(SessionRecord stored) { + store.put(stored.getSession().getSessionId(), stored); + } + + @Override + protected Instant now() { + return EmrServerlessSessionService.this.now(); + } + + @Override + protected void end(SessionRecord stored, String state, String reason) { + EmrServerlessSessionService.this.end(stored, state, reason, now()); + } + + // A session past its 24 hours says so; one terminated or stopped otherwise says nothing more. + @Override + protected String endReason(SessionRecord stored, SparkJobRunner.Outcome outcome) { + return outcome.timedOut() && !STATE_TERMINATING.equals(stored.getSession().getState()) + ? HARD_LIMIT_REACHED : null; + } + + @Override + protected void checkLater(SessionRecord stored) { + EmrServerlessSessionService.this.checkLater(stored); + } + + @Override + public String refusal(String sessionId) { + return EmrServerlessSessionService.this.refusal(sessionId); } } } diff --git a/src/main/java/io/floci/aws/services/emrserverless/SparkConnectServers.java b/src/main/java/io/floci/aws/services/emrserverless/SparkConnectServers.java new file mode 100644 index 0000000000..23ebb21255 --- /dev/null +++ b/src/main/java/io/floci/aws/services/emrserverless/SparkConnectServers.java @@ -0,0 +1,495 @@ +package io.floci.aws.services.emrserverless; + +import io.floci.aws.core.common.RequestScopes; +import io.floci.aws.core.common.SparkConnectProxy; +import io.floci.aws.core.common.SparkConnectTargets.Route; +import org.jboss.logging.Logger; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.function.BooleanSupplier; + +/** + * The Spark Connect servers a service runs for its sessions, as EMR Serverless's and EMR's do in their docker runner + * mode: each a container the runner runs as a job's driver ({@link SparkJobRunner}), which a client reaches through + * {@link SparkConnectProxy} with a token GetSessionEndpoint gave. It runs each server, asks it whether it answers once + * its container runs, keeps the tokens given for its session, counts the calls it takes, and keeps one check for its + * session's next deadline. The service, its {@link Owner}, holds each session and its state, and is told of each step + * as the session's account and Region, never while this class holds its own lock. + */ +public final class SparkConnectServers { + + private static final Logger LOG = Logger.getLogger(SparkConnectServers.class); + + /** How long a server may take to answer once its container runs. */ + public static final Duration START_LIMIT = Duration.ofMinutes(10); + private static final long PROBE_INTERVAL_MILLIS = 500; + // No source gives AWS's wording for these; they are Floci's. + public static final String SERVER_EXITED = "The session's Spark Connect server exited with code %d."; + public static final String SERVER_NOT_STARTED = "The session's Spark Connect server could not start: %s"; + public static final String SERVER_SILENT = "The session's Spark Connect server did not answer within " + + START_LIMIT.toMinutes() + " minutes: %s"; + public static final String SERVER_ENDED = "The session's Spark Connect server ended with no exit code."; + public static final String TOKEN_EXPIRED = + "The authentication token has expired. Call GetSessionEndpoint for a new one."; + public static final String NO_RUNNING_SERVER = "Session %s has no Spark Connect server running."; + + /** The service whose sessions these are. Each method is called as the session's account and Region. */ + public interface Owner { + + /** The session's server's container runs. */ + void running(String sessionId); + + /** The session's server answers: it takes calls from now. */ + void answering(String sessionId); + + /** The session's server did not answer within {@link #START_LIMIT}, as {@code why} says. */ + void silent(String sessionId, String why); + + /** + * The session's server has stopped, as {@code outcome} says; its tokens and its check go once this returns. + * {@link #failure} tells whether that failed the session. + */ + void stopped(String sessionId, SparkJobRunner.Outcome outcome); + + /** Whether the session waits for its server to answer. */ + boolean starting(String sessionId); + + /** Whether the session's server may still run: the session has not ended, nor is ending. */ + boolean going(String sessionId); + + /** Why the session takes no calls now, or null while it does. */ + String refusal(String sessionId); + + /** The session takes a call, where it took none. */ + void busy(String sessionId); + + /** The session's last call in progress has ended. */ + void idle(String sessionId); + + /** The session's server, stopped, is no longer this class's: its entry, tokens and check have gone. */ + default void gone(String sessionId) { + } + } + + /** + * What a server's thread does before its job runs, and after: makes what the job needs first, as a cluster's + * running storage, and gives back what that took once the job has run or failed to. + */ + public interface Preparation { + + /** The job as it runs, once what it needs is made; {@code cancelled} says whether to stop making it. */ + SparkJobRunner.Job prepare(SparkJobRunner.Job job, BooleanSupplier cancelled); + + /** Gives back what {@link #prepare} took. */ + default void release() { + } + } + + /** Why no Spark Connect server answers at a host and port, or null once one does. */ + @FunctionalInterface + public interface Probe { + String unanswered(String host, int port); + } + + private final SparkJobRunner runner; + private final Executor executor; + private final ScheduledExecutorService checks; + private final Probe probe; + private final Clock clock; + // The sessions whose server a thread of this process runs; guarded by this. + 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 tells its owner nothing more; guarded by this. + private long generation; + + /** + * Servers run by {@code runner} (null where none runs, as in the immediate runner mode, where tokens are still + * kept) on {@code executor}'s threads, their sessions' deadlines checked on {@code checks} (null for none). + */ + public SparkConnectServers(SparkJobRunner runner, Executor executor, ScheduledExecutorService checks, Probe probe, + Clock clock) { + this.runner = runner; + this.executor = executor; + this.checks = checks; + this.probe = probe; + this.clock = clock; + } + + /** One thread that runs sessions' checks; a check a later one replaces leaves its queue at once. */ + public static ScheduledExecutorService checkThread(String name) { + ScheduledThreadPoolExecutor thread = new ScheduledThreadPoolExecutor(1, + Thread.ofPlatform().daemon().name(name).factory()); + thread.setRemoveOnCancelPolicy(true); + return thread; + } + + /** {@link SparkConnectProxy#unanswered}, waited for at most ten seconds. */ + public static Probe probe(SparkConnectProxy proxy) { + return (host, 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(); + } + }; + } + + /** + * What a session whose server stopped as {@code outcome} says ended with, where that failed it: why it could not + * start, or its exit code; null where it did not fail, as when it was stopped or ran out of time. + */ + public static String failure(SparkJobRunner.Outcome outcome) { + if (outcome.timedOut() || outcome.stopped()) { + return null; + } + if (outcome.failure() != null) { + return String.format(SERVER_NOT_STARTED, outcome.failure()); + } + return outcome.exitCode() != null ? String.format(SERVER_EXITED, outcome.exitCode()) : SERVER_ENDED; + } + + /** Whether a thread of this process runs the session's server. */ + public synchronized boolean runs(String sessionId) { + return servers.containsKey(sessionId); + } + + /** Runs the session's server, {@code job}, on a thread of its own until it stops, telling {@code owner}. */ + public void launch(SparkJobRunner.Job job, Owner owner) { + launch(job, (given, cancelled) -> given, owner); + } + + /** {@link #launch(SparkJobRunner.Job, Owner)}, with {@code preparation} run on the thread first. */ + public void launch(SparkJobRunner.Job job, Preparation preparation, Owner owner) { + long launchedIn; + synchronized (this) { + servers.put(job.runId(), new Server(job.accountId(), job.region())); + launchedIn = generation; + } + executor.execute(() -> run(job, preparation, owner, launchedIn)); + } + + /** + * Stops the session's server, where one runs; its tokens and its check go now, and its owner is told once it has + * stopped. + */ + public void stop(String sessionId) { + boolean running; + synchronized (this) { + Server server = servers.get(sessionId); + running = server != null; + if (running) { + // No call starts on it from now, whatever its owner said of its session a moment before. + server.stopping = true; + cancelCheck(server); + } + } + dropGrants(sessionId); + if (running) { + runner.stop(sessionId); + } + } + + /** Keeps a token GetSessionEndpoint gave for the session, until {@code expiresAt}. */ + public void grant(String token, String sessionId, String accountId, String region, Instant expiresAt) { + Instant now = clock.instant(); + grants.values().removeIf(grant -> !now.isBefore(grant.expiresAt())); + grants.put(token, new Grant(accountId, region, sessionId, expiresAt)); + } + + /** Drops every token given for the session. */ + public void dropGrants(String sessionId) { + grants.values().removeIf(grant -> grant.sessionId().equals(sessionId)); + } + + /** + * Where a call carrying {@code token} goes: empty for a token none of these sessions has; refused for an expired + * one, or while {@code owner} says its session takes no calls; else its server, the call counting as one the + * session takes until it ends. + */ + public Optional route(String token, Owner owner) { + Grant grant = grants.get(token); + if (grant == null) { + return Optional.empty(); + } + if (!clock.instant().isBefore(grant.expiresAt())) { + grants.remove(token); + return Optional.of(Route.refused(Route.UNAUTHENTICATED, TOKEN_EXPIRED)); + } + return Optional.of(RequestScopes.callAs(grant.accountId(), grant.region(), () -> callStarted(grant, owner))); + } + + /** Checks the session at {@code at} by {@code check}, run as its account and Region, in place of any it had. */ + public void checkAt(String sessionId, Instant at, Runnable check) { + if (checks == null) { + return; + } + synchronized (this) { + Server server = servers.get(sessionId); + if (server == null) { + return; + } + cancelCheck(server); + server.check = checks.schedule(() -> RequestScopes.runAs(server.accountId, server.region, check), + Math.max(0, Duration.between(clock.instant(), at).toMillis()), TimeUnit.MILLISECONDS); + } + } + + /** Cancels the session's check, where it has one. */ + public synchronized void cancelCheck(String sessionId) { + Server server = servers.get(sessionId); + if (server != null) { + cancelCheck(server); + } + } + + /** A reset has begun: the servers' threads tell their owner nothing more, and every token goes. */ + public synchronized void reset() { + generation++; + servers.values().forEach(SparkConnectServers::cancelCheck); + servers.clear(); + grants.clear(); + } + + public void shutdown() { + if (executor instanceof ExecutorService service) { + service.shutdownNow(); + } + if (checks != null) { + checks.shutdownNow(); + } + } + + /** + * A call starts on the session's server, unless its owner refuses it or the server is being stopped, which is read + * under the lock {@link #stop} marks it under. The count and the owner's busy go together under the server's own + * notifications lock, so a call's busy cannot reach the owner before the idle of the call that ended before it. + */ + private Route callStarted(Grant grant, Owner owner) { + String sessionId = grant.sessionId(); + String refusal = owner.refusal(sessionId); + if (refusal != null) { + return Route.refused(Route.UNAVAILABLE, refusal); + } + Server server; + synchronized (this) { + server = servers.get(sessionId); + if (server == null) { + return Route.refused(Route.UNAVAILABLE, String.format(NO_RUNNING_SERVER, sessionId)); + } + } + synchronized (server.notifications) { + boolean first; + String host; + int port; + long launchedIn; + synchronized (this) { + if (server.stopping || server.host == null || servers.get(sessionId) != server) { + return Route.refused(Route.UNAVAILABLE, String.format(NO_RUNNING_SERVER, sessionId)); + } + first = server.calls++ == 0; + host = server.host; + port = server.port; + launchedIn = generation; + } + if (first) { + owner.busy(sessionId); + } + return Route.to(host, port, () -> RequestScopes.runAs(grant.accountId(), grant.region(), + () -> callEnded(sessionId, server, owner, launchedIn))); + } + } + + // A call has ended: the last one in progress makes its session idle, in order with the calls' busy. + private void callEnded(String sessionId, Server server, Owner owner, long launchedIn) { + synchronized (server.notifications) { + boolean last; + synchronized (this) { + if (launchedIn != generation || servers.get(sessionId) != server || server.calls == 0) { + return; + } + last = --server.calls == 0; + } + if (last) { + owner.idle(sessionId); + } + } + } + + private void run(SparkJobRunner.Job job, Preparation preparation, Owner owner, long launchedIn) { + SparkJobRunner.Outcome outcome; + ServerProgress progress = new ServerProgress(job, owner, launchedIn); + try { + outcome = runner.run(preparation.prepare(job, progress::cancelled), progress); + } catch (RuntimeException e) { + if (progress.cancelled() || Thread.currentThread().isInterrupted()) { + // An end, a reset or Floci's shutdown cut its start short. + outcome = SparkJobRunner.Outcome.halted(); + } else { + LOG.warnv(e, "The Spark Connect server of session {0} could not run", job.runId()); + outcome = SparkJobRunner.Outcome.couldNotStart(e.getMessage() != null ? e.getMessage() + : e.toString()); + } + } finally { + try { + preparation.release(); + } catch (RuntimeException e) { + LOG.warnv(e, "What the Spark Connect server of session {0} took could not all be given back", + job.runId()); + } + } + if (!current(launchedIn)) { + return; + } + String sessionId = job.runId(); + SparkJobRunner.Outcome ended = outcome; + try { + // The owner first, while the server is still here: a session read in between would otherwise look like one + // whose server a restart left behind. + RequestScopes.runAs(job.accountId(), job.region(), () -> owner.stopped(sessionId, ended)); + } catch (RuntimeException e) { + LOG.warnv(e, "Session {0} could not be told its Spark Connect server stopped", sessionId); + } finally { + synchronized (this) { + if (launchedIn == generation) { + Server server = servers.remove(sessionId); + if (server != null) { + cancelCheck(server); + } + } + } + dropGrants(sessionId); + } + try { + RequestScopes.runAs(job.accountId(), job.region(), () -> owner.gone(sessionId)); + } catch (RuntimeException e) { + LOG.warnv(e, "Session {0} could not be told its Spark Connect server has gone", sessionId); + } + } + + // Asks the server whether it answers until it does, its session stops starting, or its time to start is up. + private void await(SparkJobRunner.Job job, Owner owner, String host, int port, long launchedIn) { + String sessionId = job.runId(); + long giveUp = System.nanoTime() + START_LIMIT.toNanos(); + while (current(launchedIn) + && RequestScopes.callAs(job.accountId(), job.region(), () -> owner.starting(sessionId))) { + String unanswered = probe.unanswered(host, port); + if (unanswered == null) { + RequestScopes.runAs(job.accountId(), job.region(), () -> owner.answering(sessionId)); + return; + } + if (System.nanoTime() - giveUp >= 0) { + LOG.warnv("The Spark Connect server of session {0} did not answer: {1}", sessionId, unanswered); + RequestScopes.runAs(job.accountId(), job.region(), () -> owner.silent(sessionId, unanswered)); + stop(sessionId); + return; + } + try { + Thread.sleep(PROBE_INTERVAL_MILLIS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } + } + } + + private synchronized boolean current(long launchedIn) { + return launchedIn == generation; + } + + private synchronized boolean listening(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; + } + + private static void cancelCheck(Server server) { + if (server.check != null) { + server.check.cancel(false); + server.check = null; + } + } + + // A session's running server: its account and Region, where Floci reaches it once its container runs, how many + // calls it is taking, whether it is being stopped, the check for its session's next deadline, and the lock its + // calls' busy and idle reach its owner under, in order. + private static final class Server { + final String accountId; + final String region; + final Object notifications = new Object(); + String host; + int port; + int calls; + boolean stopping; + ScheduledFuture check; + + Server(String accountId, String region) { + this.accountId = accountId; + this.region = region; + } + } + + // 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 its owner, and asks it, as that session. */ + private final class ServerProgress implements SparkJobRunner.Progress { + + private final SparkJobRunner.Job job; + private final Owner owner; + private final long launchedIn; + + ServerProgress(SparkJobRunner.Job job, Owner owner, long launchedIn) { + this.job = job; + this.owner = owner; + this.launchedIn = launchedIn; + } + + @Override + public void started() { + if (current(launchedIn)) { + RequestScopes.runAs(job.accountId(), job.region(), () -> owner.running(job.runId())); + } + } + + @Override + public void listening(String host, int port) { + if (SparkConnectServers.this.listening(job.runId(), host, port, launchedIn)) { + executor.execute(() -> await(job, owner, host, port, launchedIn)); + } + } + + @Override + public void timedOut() { + // The run's outcome says so, which the owner reads. + } + + @Override + public boolean cancelled() { + return !current(launchedIn) + || !RequestScopes.callAs(job.accountId(), job.region(), () -> owner.going(job.runId())); + } + } +} diff --git a/src/main/java/io/floci/aws/services/emrserverless/SparkConnectSession.java b/src/main/java/io/floci/aws/services/emrserverless/SparkConnectSession.java new file mode 100644 index 0000000000..7fbce0f0e6 --- /dev/null +++ b/src/main/java/io/floci/aws/services/emrserverless/SparkConnectSession.java @@ -0,0 +1,21 @@ +package io.floci.aws.services.emrserverless; + +import java.time.Instant; + +/** A Spark Connect session, EMR Serverless's or EMR's, as {@link SparkConnectSessionOwner} moves it between states. */ +public interface SparkConnectSession { + + String getState(); + + void setState(String state); + + Instant getStartedAt(); + + void setStartedAt(Instant startedAt); + + Instant getIdleSince(); + + void setIdleSince(Instant idleSince); + + void setUpdatedAt(Instant updatedAt); +} diff --git a/src/main/java/io/floci/aws/services/emrserverless/SparkConnectSessionOwner.java b/src/main/java/io/floci/aws/services/emrserverless/SparkConnectSessionOwner.java new file mode 100644 index 0000000000..5e0016b929 --- /dev/null +++ b/src/main/java/io/floci/aws/services/emrserverless/SparkConnectSessionOwner.java @@ -0,0 +1,143 @@ +package io.floci.aws.services.emrserverless; + +import org.jboss.logging.Logger; + +import java.time.Instant; +import java.util.Optional; +import java.util.Set; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * A service's sessions as their servers' owner ({@link SparkConnectServers.Owner}): the states a session goes through + * as its server starts, answers, takes calls and stops, which EMR Serverless's sessions and EMR's share. It is + * SUBMITTED until its server's container runs, STARTING until the server answers, then IDLE, its idle timeout counting + * from then; BUSY while a call runs on its server and IDLE again once none does; and once its server stops, TERMINATED, + * or FAILED where that failed it. Each step is taken under the service's lock on the session as stored; {@code R} is + * what the service stores, {@link #session} the session in it. + */ +public abstract class SparkConnectSessionOwner implements SparkConnectServers.Owner { + + private static final Logger LOG = Logger.getLogger(SparkConnectSessionOwner.class); + + public static final String SUBMITTED = "SUBMITTED"; + public static final String STARTING = "STARTING"; + public static final String IDLE = "IDLE"; + public static final String BUSY = "BUSY"; + public static final String TERMINATING = "TERMINATING"; + public static final String TERMINATED = "TERMINATED"; + public static final String FAILED = "FAILED"; + private static final Set ENDED = Set.of(TERMINATED, FAILED); + + /** Runs {@code body} under the service's lock. */ + protected abstract T locked(Supplier body); + + /** The stored session of that id. */ + protected abstract Optional find(String sessionId); + + /** The session in what the service stores. */ + protected abstract SparkConnectSession session(R stored); + + protected abstract void save(R stored); + + protected abstract Instant now(); + + /** Ends the session as {@code state}, TERMINATED or FAILED, for {@code reason} (null for none), now. */ + protected abstract void end(R stored, String state, String reason); + + /** What a session whose server stopped as {@code outcome} says, not failing it, ends TERMINATED for. */ + protected abstract String endReason(R stored, SparkJobRunner.Outcome outcome); + + /** Checks the session again at its next deadline, or cancels its check where it has none. */ + protected abstract void checkLater(R stored); + + @Override + public void running(String sessionId) { + inState(sessionId, SUBMITTED, stored -> { + session(stored).setState(STARTING); + session(stored).setUpdatedAt(now()); + save(stored); + }); + } + + @Override + public void answering(String sessionId) { + inState(sessionId, STARTING, stored -> { + Instant now = now(); + SparkConnectSession session = session(stored); + session.setState(IDLE); + session.setStartedAt(now); + session.setIdleSince(now); + session.setUpdatedAt(now); + save(stored); + checkLater(stored); + LOG.infov("Session {0} is ready", sessionId); + }); + } + + @Override + public void silent(String sessionId, String why) { + inState(sessionId, STARTING, + stored -> end(stored, FAILED, String.format(SparkConnectServers.SERVER_SILENT, why))); + } + + @Override + public void stopped(String sessionId, SparkJobRunner.Outcome outcome) { + locked(() -> { + find(sessionId).filter(stored -> !ENDED.contains(session(stored).getState())).ifPresent(stored -> { + String failure = SparkConnectServers.failure(outcome); + if (TERMINATING.equals(session(stored).getState()) || failure == null) { + end(stored, TERMINATED, endReason(stored, outcome)); + } else { + end(stored, FAILED, failure); + } + }); + return null; + }); + } + + @Override + public boolean starting(String sessionId) { + return locked(() -> find(sessionId).map(stored -> STARTING.equals(session(stored).getState())) + .orElse(false)); + } + + @Override + public boolean going(String sessionId) { + return locked(() -> find(sessionId).map(stored -> !ENDED.contains(session(stored).getState()) + && !TERMINATING.equals(session(stored).getState())).orElse(false)); + } + + // A call has started on an idle session: it is BUSY, and its idle timeout does not run. + @Override + public void busy(String sessionId) { + inState(sessionId, IDLE, stored -> { + session(stored).setState(BUSY); + session(stored).setIdleSince(null); + session(stored).setUpdatedAt(now()); + save(stored); + checkLater(stored); + }); + } + + // Its last call has ended: the session is IDLE again from now. + @Override + public void idle(String sessionId) { + inState(sessionId, BUSY, stored -> { + Instant now = now(); + session(stored).setState(IDLE); + session(stored).setIdleSince(now); + session(stored).setUpdatedAt(now); + save(stored); + checkLater(stored); + }); + } + + // Changes the session, under the service's lock, where it is in state. + private void inState(String sessionId, String state, Consumer change) { + locked(() -> { + find(sessionId).filter(stored -> state.equals(session(stored).getState())).ifPresent(change); + return null; + }); + } +} diff --git a/src/main/java/io/floci/aws/services/emrserverless/model/Session.java b/src/main/java/io/floci/aws/services/emrserverless/model/Session.java index 651d13b6d4..65cddb8d4a 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/model/Session.java +++ b/src/main/java/io/floci/aws/services/emrserverless/model/Session.java @@ -2,6 +2,7 @@ package io.floci.aws.services.emrserverless.model; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonInclude; +import io.floci.aws.services.emrserverless.SparkConnectSession; import io.quarkus.runtime.annotations.RegisterForReflection; import java.time.Instant; @@ -10,7 +11,7 @@ import java.util.Map; /** GetSession's session. Timestamps go out as epoch seconds, the restJson1 default. */ @RegisterForReflection @JsonInclude(JsonInclude.Include.NON_NULL) -public class Session { +public class Session implements SparkConnectSession { private String applicationId; private String sessionId; private String arn; diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index a7c6746722..302e1f4a5c 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -660,7 +660,7 @@ floci: cluster-startup-delay-seconds: 0 # 0 = a cluster is ready as soon as it is created step-duration-seconds: 0 # 0 = a step completes as soon as it starts cluster-termination-delay-seconds: 0 # 0 = a cluster is TERMINATED as soon as it is TERMINATING - runner-mode: immediate # docker = run bootstrap actions and steps in containers + runner-mode: immediate # docker = run bootstrap actions, steps and sessions' servers in containers # 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" # every cluster's HDFS, and Hive diff --git a/src/test/java/io/floci/aws/core/common/SparkConnectProxyTest.java b/src/test/java/io/floci/aws/core/common/SparkConnectProxyTest.java index 996e580346..6f0c719815 100644 --- a/src/test/java/io/floci/aws/core/common/SparkConnectProxyTest.java +++ b/src/test/java/io/floci/aws/core/common/SparkConnectProxyTest.java @@ -90,6 +90,7 @@ class SparkConnectProxyTest { 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)); + assertNull(serverSaw.get().get("authorization")); assertEquals("trailers", serverSaw.get().get("te")); assertNull(serverSaw.get().get("transfer-encoding")); awaitCount(callsEnded, 1); @@ -170,6 +171,8 @@ class SparkConnectProxyTest { .putHeader("te", "trailers"); if (token != null) { options.putHeader(SparkConnectProxy.TOKEN_METADATA, token); + // As AWS's EMR connection string adds the session's id. + options.putHeader("authorization", "is-SESSION"); } // As a gRPC client sends a call: its message streamed, with no Content-Length. return await(client.request(options) diff --git a/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java b/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java index 440b91f160..857dd61e51 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java @@ -6,6 +6,7 @@ import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.ContainerTeardown; import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.SparkConnectProxy; import io.floci.aws.services.ec2.model.Instance; import io.floci.aws.services.emr.model.EmrCluster; import io.floci.aws.services.emr.model.EmrErrorDetail; @@ -1455,7 +1456,8 @@ class EmrServiceContainerStepsTest { new EmrService(new InMemoryStorageFactory(ACCOUNT), config, regionResolver, new EmrEventPublisher(mock(EventBridgeService.class), new ObjectMapper(), regionResolver), - sparkRunner, bootstrapRunner, clusterStorage, mock(EmrReleaseImages.class), mock(IamService.class)) + sparkRunner, bootstrapRunner, clusterStorage, mock(EmrReleaseImages.class), mock(IamService.class), + mock(SparkConnectProxy.class)) .shutdown(); verify(sparkRunner, times(reconcile ? 1 : 0)).removeLeftoverDrivers("emr"); diff --git a/src/test/java/io/floci/aws/services/emr/EmrServiceFixture.java b/src/test/java/io/floci/aws/services/emr/EmrServiceFixture.java index 8c1d738a16..336d43a5b4 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrServiceFixture.java +++ b/src/test/java/io/floci/aws/services/emr/EmrServiceFixture.java @@ -7,6 +7,7 @@ import io.floci.aws.core.common.RegionResolver; import io.floci.aws.services.ec2.model.Instance; import io.floci.aws.services.emr.model.EmrCluster; import io.floci.aws.services.emr.model.EmrStep; +import io.floci.aws.services.emrserverless.SparkConnectServers; import io.floci.aws.services.emrserverless.SparkJobRunner; import io.floci.aws.services.eventbridge.EventBridgeService; import io.floci.aws.services.iam.IamService; @@ -22,6 +23,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.BooleanSupplier; import java.util.function.Consumer; import java.util.function.Function; @@ -228,8 +230,8 @@ final class EmrServiceFixture { Target target = event -> { }; private final List wakeups = new ArrayList<>(); private final List deliveries = new ArrayList<>(); - // The docker runner mode's step threads, not yet run. - private final List stepThreads = new ArrayList<>(); + // The docker runner mode's step threads, not yet run; a session server's thread may add one too. + private final List stepThreads = new CopyOnWriteArrayList<>(); private boolean waking; final InMemoryStorageFactory storage; private final SparkJobRunner runner; @@ -239,6 +241,8 @@ final class EmrServiceFixture { final RecordingReleaseImages releaseImages; private final IamService iam; private final int[] durations; + // How the docker runner mode's session servers are asked whether they answer; null for no session servers. + private final SparkConnectServers.Probe sessionProbe; /** The service as configured by default, every duration 0. */ EmrServiceFixture() { @@ -246,7 +250,7 @@ final class EmrServiceFixture { } EmrServiceFixture(int startupDelaySeconds, int stepDurationSeconds, int terminationDelaySeconds) { - this(new InMemoryStorageFactory(ACCOUNT), new MutableClock(), null, null, null, null, null, + this(new InMemoryStorageFactory(ACCOUNT), new MutableClock(), null, null, null, null, null, null, startupDelaySeconds, stepDurationSeconds, terminationDelaySeconds); } @@ -258,12 +262,23 @@ final class EmrServiceFixture { /** As {@link #docker(SparkJobRunner, IamService)}, its clusters' bootstrap actions run by {@code bootstrap}. */ static EmrServiceFixture docker(SparkJobRunner runner, BootstrapRunner bootstrap, IamService iam) { return new EmrServiceFixture(new InMemoryStorageFactory(ACCOUNT), new MutableClock(), runner, bootstrap, - new RecordingStorage(), new RecordingReleaseImages(), iam, 0, 0, 0); + new RecordingStorage(), new RecordingReleaseImages(), iam, null, 0, 0, 0); + } + + /** + * As {@link #docker(SparkJobRunner, IamService)}, its sessions' Spark Connect servers run by {@code runner} too, + * each on a thread of its own, and asked whether they answer by {@code probe}. + */ + static EmrServiceFixture dockerSessions(SparkJobRunner runner, IamService iam, SparkConnectServers.Probe probe) { + return new EmrServiceFixture(new InMemoryStorageFactory(ACCOUNT), new MutableClock(), runner, null, + new RecordingStorage(), new RecordingReleaseImages(), iam, probe, 0, 0, 0); } private EmrServiceFixture(InMemoryStorageFactory storage, MutableClock clock, SparkJobRunner runner, BootstrapRunner bootstrap, RecordingStorage clusterStorage, - RecordingReleaseImages releaseImages, IamService iam, int... durations) { + RecordingReleaseImages releaseImages, IamService iam, + SparkConnectServers.Probe sessionProbe, int... durations) { + this.sessionProbe = sessionProbe; this.storage = storage; this.clock = clock; this.runner = runner; @@ -286,7 +301,7 @@ final class EmrServiceFixture { }).when(eventBridge).publishServiceEvent(eq("aws.emr"), anyString(), anyString(), isNull(), eq(REGION)); RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT); publisher = new EmrEventPublisher(eventBridge, objectMapper, regionResolver); - service = new EmrService(storage, config(false), regionResolver, publisher, clock, new EmrService.Wakeups() { + EmrService.Wakeups recorded = new EmrService.Wakeups() { @Override public void at(Instant due, Runnable task) { wakeups.add(new Wakeup(due, task)); @@ -296,17 +311,25 @@ final class EmrServiceFixture { public void deliver(Runnable delivery) { deliveries.add(delivery); } - }, runner, bootstrap, clusterStorage, releaseImages, stepThreads::add, iam); + }; + service = sessionProbe == null + ? new EmrService(storage, config(false), regionResolver, publisher, clock, recorded, runner, bootstrap, + clusterStorage, releaseImages, stepThreads::add, iam) + : new EmrService(storage, config(false), regionResolver, publisher, clock, recorded, runner, bootstrap, + clusterStorage, releaseImages, stepThreads::add, iam, + new SparkConnectServers(runner, task -> Thread.ofPlatform().daemon().start(task), null, + sessionProbe, clock)); } /** A new service on the same storage and clock, as after a restart of Floci with persistent storage. */ EmrServiceFixture restart() { - return new EmrServiceFixture(storage, clock, runner, bootstrap, clusterStorage, releaseImages, iam, durations); + return new EmrServiceFixture(storage, clock, runner, bootstrap, clusterStorage, releaseImages, iam, + sessionProbe, durations); } /** A new service on the same storage and clock, as {@link #restart} builds, in the {@code immediate} mode. */ EmrServiceFixture restartImmediate() { - return new EmrServiceFixture(storage, clock, null, null, null, null, iam, durations); + return new EmrServiceFixture(storage, clock, null, null, null, null, iam, null, durations); } /** diff --git a/src/test/java/io/floci/aws/services/emr/EmrSessionIntegrationTest.java b/src/test/java/io/floci/aws/services/emr/EmrSessionIntegrationTest.java index b1fc8ac5ca..623ebdf409 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrSessionIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrSessionIntegrationTest.java @@ -9,7 +9,6 @@ import org.junit.jupiter.api.Test; import java.util.UUID; import static io.floci.aws.testing.EmrRequests.emr; -import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.matchesPattern; @@ -83,7 +82,7 @@ class EmrSessionIntegrationTest { emr("GetSessionEndpoint", "{\"ClusterId\":\"" + clusterId + "\",\"SessionId\":\"" + sessionId + "\"}") .then().statusCode(200) - .body("Endpoint", endsWith("/_aws/emr/sessions/" + clusterId + "/" + sessionId)) + .body("Endpoint", matchesPattern("https?://[^/]+")) .body("AuthToken", matchesPattern("[0-9a-f]{64}")) .body("AuthTokenExpirationTime", notNullValue()); diff --git a/src/test/java/io/floci/aws/services/emr/EmrSessionServerNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/emr/EmrSessionServerNightlyIntegrationTest.java new file mode 100644 index 0000000000..7f79b3e805 --- /dev/null +++ b/src/test/java/io/floci/aws/services/emr/EmrSessionServerNightlyIntegrationTest.java @@ -0,0 +1,223 @@ +package io.floci.aws.services.emr; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.model.Container; +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.path.json.JsonPath; +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 java.util.function.Supplier; + +import static io.floci.aws.testing.EmrRequests.emr; +import static io.floci.aws.testing.EmrRequests.terminateClusterAndAwaitCleanup; +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 session run for real: its Spark Connect server runs on its cluster, the release's image on the cluster's + * YARN, and a Spark Connect client, Spark 4's own JVM client from that image, reaches it through Floci at the endpoint + * GetSessionEndpoint gives, with the token and the session's id in the parameters AWS's connection string puts them + * in. 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 cluster's image, HDFS and YARN, the server and the client each take minutes and gigabytes. + */ +@QuarkusTest +@TestProfile(EmrSessionServerNightlyIntegrationTest.Profile.class) +@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true") +// Bounded waits: the cluster's image of up to twenty minutes, its HDFS and YARN, the server's start, the client's run +// and the session's end; the Nightly checks job's timeout counts the 40. +@Timeout(value = 40, unit = TimeUnit.MINUTES) +class EmrSessionServerNightlyIntegrationTest { + + /** Clusters run their steps and sessions in containers, and Floci listens on a fixed port, its endpoint's. */ + public static final class Profile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of( + "floci.services.emr.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 = 4596; + private static final String RELEASE = "emr-spark-8.1.0"; + // Spark 4's JVM Spark Connect client, which the release's image carries, run as a single source file, 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) throws Exception { + 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 the classic SQL engine and the server, whose classes it + # would otherwise reach for; Spark 4's shared API needs spark-core. + classpath=$(ls /usr/lib/spark/jars/connect-repl/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-connect_*) ;; + *) classpath=$classpath:$jar ;; + esac + done + # Java 17's launcher compiles the one file itself; Arrow needs java.nio opened. + exec /usr/lib/jvm/java-17-amazon-corretto/bin/java --add-opens=java.base/java.nio=ALL-UNNAMED \\ + -cp "$classpath" Probe.java "$@" + """; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @Inject + DockerClient docker; + + @Inject + ContainerBuilder containerBuilder; + + @Inject + ContainerLifecycleManager lifecycleManager; + + @Inject + ContainerReachableEndpoint reachableEndpoint; + + @Inject + EmulatorConfig config; + + @Inject + EmrService emrService; + + @BeforeAll + static void configure() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void aClientRunsQueriesOnTheSessionsServerThroughFlociWithItsToken() 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 clusterId = emr("RunJobFlow", "{\"Name\":\"sessions\",\"ReleaseLabel\":\"" + RELEASE + "\"," + + "\"Applications\":[{\"Name\":\"Hadoop\"},{\"Name\":\"Spark\"}],\"SessionEnabled\":true," + + "\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true,\"InstanceGroups\":[{\"Name\":\"primary\"," + + "\"InstanceRole\":\"MASTER\",\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":1}]}}") + .then().statusCode(200).extract().jsonPath().getString("JobFlowId"); + cleanup.register(() -> terminateClusterAndAwaitCleanup(clusterId, emrService)); + awaitCluster(clusterId, "WAITING", Duration.ofMinutes(5)); + String sessionId = emr("StartSession", "{\"ClusterId\":\"" + clusterId + "\",\"Name\":\"probe\"," + + "\"ClientRequestToken\":\"" + UUID.randomUUID() + "\"}") + .then().statusCode(200).extract().jsonPath().getString("Id"); + + awaitSession(clusterId, sessionId, "IDLE", Duration.ofMinutes(25)); + JsonPath endpoint = emr("GetSessionEndpoint", "{\"ClusterId\":\"" + clusterId + "\",\"SessionId\":\"" + + sessionId + "\"}").then().statusCode(200).extract().jsonPath(); + assertEquals("http://localhost:" + PORT, endpoint.getString("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() + "/;authorization=" + sessionId + + ";x-aws-proxy-auth="; + String server = ContainerStorageHelper.dockerName(config, "emr-" + sessionId); + String image = lifecycleManager.findByName(server).map(Container::getImage) + .orElseThrow(() -> new AssertionError("no container " + server)); + String output = runClient(image, connect + endpoint.getString("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); + assertTrue(output.contains("ERROR=") && output.contains("TABLE_OR_VIEW_NOT_FOUND"), output); + emr("TerminateSession", "{\"ClusterId\":\"" + clusterId + "\",\"SessionId\":\"" + sessionId + "\"}") + .then().statusCode(200); + awaitSession(clusterId, sessionId, "TERMINATED", Duration.ofMinutes(2)); + assertTrue(lifecycleManager.findByName(server).isEmpty(), "the session's server is still there"); + } + + // Runs the client in a container of the cluster's image, as far as Floci's address, and returns its output. + private String runClient(String image, 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 awaitCluster(String clusterId, String state, Duration limit) { + await(() -> emr("DescribeCluster", "{\"ClusterId\":\"" + clusterId + "\"}").jsonPath() + .getString("Cluster.Status.State"), state, List.of("TERMINATED", "TERMINATED_WITH_ERRORS"), limit, + "Cluster " + clusterId); + } + + private void awaitSession(String clusterId, String sessionId, String state, Duration limit) { + await(() -> emr("GetSession", "{\"ClusterId\":\"" + clusterId + "\",\"SessionId\":\"" + sessionId + "\"}") + .jsonPath().getString("Session.State"), state, List.of("FAILED", "TERMINATED"), limit, + "Session " + sessionId); + } + + private static void await(Supplier read, String state, List ends, + Duration limit, String what) { + long deadline = System.nanoTime() + limit.toNanos(); + while (true) { + String now = read.get(); + if (state.equals(now)) { + return; + } + if (ends.contains(now) || System.nanoTime() - deadline > 0) { + fail(what + " is " + now + ", not " + state); + } + LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(2)); + } + } +} diff --git a/src/test/java/io/floci/aws/services/emr/EmrSessionServerTest.java b/src/test/java/io/floci/aws/services/emr/EmrSessionServerTest.java new file mode 100644 index 0000000000..b0d4f17b0f --- /dev/null +++ b/src/test/java/io/floci/aws/services/emr/EmrSessionServerTest.java @@ -0,0 +1,260 @@ +package io.floci.aws.services.emr; + +import io.floci.aws.core.common.SparkConnectEndpoint; +import io.floci.aws.core.common.SparkConnectTargets; +import io.floci.aws.services.emr.model.EmrCluster; +import io.floci.aws.services.emr.model.EmrSession; +import io.floci.aws.services.emrserverless.SparkConnectServers; +import io.floci.aws.services.emrserverless.SparkJobRunner; +import io.floci.aws.services.iam.IamService; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.locks.LockSupport; + +import static io.floci.aws.services.emr.EmrServiceFixture.REGION; +import static io.floci.aws.services.emr.EmrServiceFixture.cluster; +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.Mockito.mock; + +/** + * EMR sessions in the docker runner mode, each running a Spark Connect server on its cluster as a step runs: the + * session's states as its server starts, answers, takes calls and stops, with a runner that stands in for Docker. + */ +class EmrSessionServerTest { + + private static final String RELEASE = "emr-spark-8.1.0"; + private static final String ROLE = "arn:aws:iam::000000000000:role/emr-session-runtime"; + private static final String SERVER_HOST = "127.0.0.1"; + private static final int SERVER_PORT = 40321; + + private final FakeServerRunner runner = new FakeServerRunner(); + private final AtomicBoolean answering = new AtomicBoolean(true); + private final SparkConnectServers.Probe probe = (host, port) -> + answering.get() && SERVER_HOST.equals(host) && port == SERVER_PORT ? null : "Connection refused"; + private final EmrServiceFixture fixture = EmrServiceFixture.dockerSessions(runner, mock(IamService.class), probe); + private final EmrService service = fixture.service; + + @Test + void aSessionRunsItsServerOnItsClusterAndIsIdleOnceTheServerAnswers() { + String clusterId = sessionCluster(); + EmrSession started = service.startSession(clusterId, new EmrSessions.Request("notebook", ROLE, + "[{\"Classification\":\"spark-defaults\",\"Properties\":{\"spark.executor.memory\":\"4g\"}}]", null, + null, null, Map.of())); + + EmrSession idle = awaitState(clusterId, started.getId(), "IDLE"); + + assertEquals("SUBMITTED", started.getState()); + assertNotNull(idle.getStartedAt()); + assertEquals(idle.getStartedAt(), idle.getIdleSince()); + SparkJobRunner.Job job = runner.jobs.get(started.getId()); + assertEquals(EmrSessions.SPARK_CONNECT_PORT, job.listenPort()); + assertEquals(List.of("--class", "org.apache.spark.sql.connect.service.SparkConnectServer", "spark-internal"), + job.application()); + assertEquals("15002", job.sparkDefaults().get("spark.connect.grpc.binding.port")); + assertEquals("4g", job.sparkDefaults().get("spark.executor.memory")); + assertEquals(ROLE, job.executionRole()); + // On the cluster's storage, its HDFS running, as a step's driver is. + assertNotNull(job.storage()); + assertTrue(fixture.clusterStorage.created.contains(clusterId), fixture.clusterStorage.created.toString()); + } + + @Test + void aCallThroughItsTokenMakesTheSessionBusyUntilItEnds() { + String clusterId = sessionCluster(); + String sessionId = service.startSession(clusterId, request()).getId(); + awaitState(clusterId, sessionId, "IDLE"); + SparkConnectEndpoint endpoint = service.sessionEndpoint(clusterId, sessionId); + + SparkConnectTargets.Route route = service.route(endpoint.authToken()).orElseThrow(); + + assertNull(route.refusal()); + assertEquals(SERVER_HOST, route.host()); + assertEquals(SERVER_PORT, route.port()); + assertEquals("BUSY", service.getSession(clusterId, sessionId).getState()); + assertNull(service.getSession(clusterId, sessionId).getIdleSince()); + route.ended().run(); + assertEquals("IDLE", service.getSession(clusterId, sessionId).getState()); + assertTrue(service.route("not-a-token").isEmpty()); + } + + @Test + void aSessionIsStartingUntilItsServerAnswersAndRefusesCallsMeanwhile() { + answering.set(false); + String clusterId = sessionCluster(); + String sessionId = service.startSession(clusterId, request()).getId(); + awaitState(clusterId, sessionId, "STARTING"); + + SparkConnectTargets.Route refused = service.route(service.sessionEndpoint(clusterId, sessionId).authToken()) + .orElseThrow(); + + assertEquals(SparkConnectTargets.Route.UNAVAILABLE, refused.status()); + assertEquals(String.format(EmrSessions.NOT_READY, sessionId, "STARTING"), refused.refusal()); + answering.set(true); + awaitState(clusterId, sessionId, "IDLE"); + } + + @Test + void aTerminatedSessionIsTerminatingUntilItsServerStopsAndItsTokensGo() { + String clusterId = sessionCluster(); + String sessionId = service.startSession(clusterId, request()).getId(); + awaitState(clusterId, sessionId, "IDLE"); + String token = service.sessionEndpoint(clusterId, sessionId).authToken(); + + EmrSession terminating = service.terminateSession(clusterId, sessionId); + EmrSession terminated = awaitState(clusterId, sessionId, "TERMINATED"); + + assertEquals("TERMINATING", terminating.getState()); + assertTrue(runner.stopped.contains(sessionId)); + assertEquals(EmrSessions.USER_REQUEST, terminated.getStateChangeReason()); + assertTrue(service.route(token).isEmpty()); + } + + @Test + void aSessionWhoseServerExitsOnItsOwnHasFailed() { + String clusterId = sessionCluster(); + String sessionId = service.startSession(clusterId, request()).getId(); + awaitState(clusterId, sessionId, "IDLE"); + + runner.end(sessionId).complete(SparkJobRunner.Outcome.exitedWith(1)); + EmrSession failed = awaitState(clusterId, sessionId, "FAILED"); + + assertEquals(String.format(SparkConnectServers.SERVER_EXITED, 1), failed.getStateChangeReason()); + } + + @Test + void anIdleSessionEndsItsServerAtItsIdleTimeoutAndTheClustersEndEndsAnother() { + String clusterId = sessionCluster(); + String timingOut = service.startSession(clusterId, new EmrSessions.Request("short", null, null, null, 30L, + null, Map.of())).getId(); + awaitState(clusterId, timingOut, "IDLE"); + String other = service.startSession(clusterId, request()).getId(); + awaitState(clusterId, other, "IDLE"); + + fixture.clock.advance(Duration.ofMinutes(30)); + assertEquals("TERMINATED", service.getSession(clusterId, timingOut).getState()); + assertTrue(runner.stopped.contains(timingOut)); + assertFalse(runner.stopped.contains(other)); + service.terminateJobFlows(List.of(clusterId)); + + EmrSession ended = service.getSession(clusterId, other); + assertEquals("TERMINATED", ended.getState()); + assertEquals(EmrSessions.CLUSTER_ENDED, ended.getStateChangeReason()); + assertTrue(runner.stopped.contains(other)); + } + + @Test + void theClustersEndStopsItsBusySessionsServerAndItsStorageGoesOnceTheServerHasGone() { + String clusterId = sessionCluster(); + String sessionId = service.startSession(clusterId, request()).getId(); + awaitState(clusterId, sessionId, "IDLE"); + // BUSY, so no idle check would ever stop it. + SparkConnectTargets.Route call = service.route(service.sessionEndpoint(clusterId, sessionId).authToken()) + .orElseThrow(); + + service.terminateJobFlows(List.of(clusterId)); + + // No read of the session: the cluster's end stopped its server. + assertTrue(runner.stopped.contains(sessionId)); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (fixture.stepThreadsWaiting() == 0 && System.nanoTime() - deadline < 0) { + LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10)); + } + assertFalse(fixture.clusterStorage.removed.contains(clusterId)); + fixture.runStepThread(); + assertTrue(fixture.clusterStorage.removed.contains(clusterId), fixture.clusterStorage.removed.toString()); + call.ended().run(); + } + + @Test + void aSessionWhoseServerNoThreadRunsAnyMoreWasInterruptedByARestart() { + String clusterId = sessionCluster(); + String sessionId = service.startSession(clusterId, request()).getId(); + awaitState(clusterId, sessionId, "IDLE"); + + EmrSession after = fixture.restart().service.getSession(clusterId, sessionId); + + assertEquals("FAILED", after.getState()); + assertEquals(EmrSessions.INTERRUPTED, after.getStateChangeReason()); + assertEquals(List.of(sessionId), runner.leftoversRemoved); + } + + private String sessionCluster() { + EmrCluster cluster = cluster("sessions", true); + cluster.setReleaseLabel(RELEASE); + cluster.setApplications("[{\"Name\":\"Spark\"}]"); + cluster.setSessionEnabled(true); + return service.runJobFlow(cluster, REGION).getId(); + } + + private static EmrSessions.Request request() { + return new EmrSessions.Request("notebook", null, null, null, null, null, Map.of()); + } + + // Polls until the session is in state, as its server's thread moves it on its own. + private EmrSession awaitState(String clusterId, String sessionId, String state) { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (true) { + EmrSession session = service.getSession(clusterId, sessionId); + if (state.equals(session.getState())) { + return session; + } + if (System.nanoTime() - deadline > 0) { + fail("Session " + sessionId + " is " + session.getState() + ", not " + state + ": " + + session.getStateChangeReason()); + } + LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10)); + } + } + + /** 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<>(); + private final Map> ends = new ConcurrentHashMap<>(); + + @Override + public Outcome run(Job job, Progress progress) { + jobs.put(job.runId(), job); + 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/emr/EmrSessionsTest.java b/src/test/java/io/floci/aws/services/emr/EmrSessionsTest.java index 5546e4fbf4..ca13fe83d9 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrSessionsTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrSessionsTest.java @@ -198,7 +198,8 @@ class EmrSessionsTest { SparkConnectEndpoint endpoint = service.sessionEndpoint(clusterId, sessionId); - assertEquals("http://localhost:4566/_aws/emr/sessions/" + clusterId + "/" + 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()); assertTrue(endpoint.authToken().matches("[0-9a-f]{64}"), endpoint.authToken()); assertTrue(Duration.between(fixture.clock.instant(), endpoint.authTokenExpiresAt()) .compareTo(Duration.ofMinutes(59)) > 0); diff --git a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSessionServerTest.java b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSessionServerTest.java index 27c9dd422c..7e8e855d13 100644 --- a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSessionServerTest.java +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSessionServerTest.java @@ -171,7 +171,7 @@ class EmrServerlessSessionServerTest { Session failed = awaitState(applicationId, sessionId, "FAILED"); - assertEquals(String.format(EmrServerlessSessionService.SERVER_NOT_STARTED, "java.lang.IllegalStateException"), + assertEquals(String.format(SparkConnectServers.SERVER_NOT_STARTED, "java.lang.IllegalStateException"), failed.getStateDetails()); } @@ -272,7 +272,7 @@ class EmrServerlessSessionServerTest { runner.end(sessionId).complete(SparkJobRunner.Outcome.exitedWith(1)); Session failed = awaitState(applicationId, sessionId, "FAILED"); - assertEquals(String.format(EmrServerlessSessionService.SERVER_EXITED, 1), failed.getStateDetails()); + assertEquals(String.format(SparkConnectServers.SERVER_EXITED, 1), failed.getStateDetails()); } @Test 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 563b6e34d2..4517da3d94 100644 --- a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSessionServiceTest.java +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSessionServiceTest.java @@ -267,7 +267,7 @@ class EmrServerlessSessionServiceTest { 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()); + assertEquals(SparkConnectServers.TOKEN_EXPIRED, sessions.route(token).orElseThrow().refusal()); } @Test diff --git a/src/test/java/io/floci/aws/services/emrserverless/SparkConnectServersTest.java b/src/test/java/io/floci/aws/services/emrserverless/SparkConnectServersTest.java new file mode 100644 index 0000000000..85df531db5 --- /dev/null +++ b/src/test/java/io/floci/aws/services/emrserverless/SparkConnectServersTest.java @@ -0,0 +1,201 @@ +package io.floci.aws.services.emrserverless; + +import io.floci.aws.core.common.SparkConnectTargets.Route; +import org.junit.jupiter.api.Test; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.locks.LockSupport; +import java.util.function.BooleanSupplier; +import java.util.function.Supplier; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * The servers {@link SparkConnectServers} runs, read from its owner's side: what reaches the owner, in what order, and + * what a call is answered, as servers start, take calls and stop. + */ +class SparkConnectServersTest { + + private static final String SESSION = "session-1"; + private static final String TOKEN = "a-token"; + + private final ServerRunner runner = new ServerRunner(); + private final SparkConnectServers servers = new SparkConnectServers(runner, + task -> Thread.ofPlatform().daemon().start(task), null, (host, port) -> null, Clock.systemUTC()); + private final RecordingOwner owner = new RecordingOwner(); + + @Test + void aCallIsRefusedWhenItsServerIsStoppedAfterItsOwnerLetItThrough() { + answeringServer(); + // The session is terminated between the owner's check and the server's. + owner.refusal = () -> { + servers.stop(SESSION); + return null; + }; + + Route route = servers.route(TOKEN, owner).orElseThrow(); + + assertEquals(Route.UNAVAILABLE, route.status()); + assertEquals(String.format(SparkConnectServers.NO_RUNNING_SERVER, SESSION), route.refusal()); + } + + @Test + void aCallsBusyReachesTheOwnerOnlyAfterTheIdleOfTheCallThatEndedBeforeIt() throws Exception { + answeringServer(); + Route first = servers.route(TOKEN, owner).orElseThrow(); + CountDownLatch idleEntered = new CountDownLatch(1); + CountDownLatch idleMayEnd = new CountDownLatch(1); + owner.idleWait = () -> { + idleEntered.countDown(); + await(idleMayEnd); + }; + + CompletableFuture ending = CompletableFuture.runAsync(first.ended()); + await(idleEntered); + CompletableFuture next = CompletableFuture.supplyAsync(() -> servers.route(TOKEN, owner).orElseThrow()); + // The next call waits for the idle in progress, rather than going BUSY under it. + assertThrows(TimeoutException.class, () -> next.get(500, TimeUnit.MILLISECONDS)); + idleMayEnd.countDown(); + ending.get(10, TimeUnit.SECONDS); + next.get(10, TimeUnit.SECONDS); + + assertEquals(List.of("answering", "busy", "idle", "busy"), owner.events); + } + + @Test + void aServersEntryGoesWhenItStopsEvenWhereItsOwnerFailsToHearIt() { + answeringServer(); + owner.stoppedFails = true; + + servers.stop(SESSION); + + awaitTrue(() -> owner.events.contains("gone")); + assertFalse(servers.runs(SESSION)); + assertTrue(servers.route(TOKEN, owner).isEmpty()); + } + + // A session's server, running and answering, with a token for it. + private void answeringServer() { + servers.launch(new SparkJobRunner.Job("test", SESSION, "000000000000", "us-east-1", "emr-7.13.0", + SparkJobRunner.Engine.SPARK, null, null, null, null, Map.of(), List.of(), null, Duration.ZERO, null, + null, Map.of(), List.of(), null, Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), null), owner); + awaitTrue(() -> owner.events.contains("answering")); + servers.grant(TOKEN, SESSION, "000000000000", "us-east-1", Instant.now().plus(Duration.ofHours(1))); + } + + private static void awaitTrue(BooleanSupplier condition) { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (!condition.getAsBoolean()) { + if (System.nanoTime() - deadline > 0) { + fail("not reached in time"); + } + LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10)); + } + } + + private static void await(CountDownLatch latch) { + try { + assertTrue(latch.await(10, TimeUnit.SECONDS)); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(e); + } + } + + /** An owner that records what reaches it, the idle as it ends, and answers as the test sets it to. */ + private static final class RecordingOwner implements SparkConnectServers.Owner { + final List events = new CopyOnWriteArrayList<>(); + volatile Supplier refusal = () -> null; + volatile Runnable idleWait = () -> { }; + volatile boolean stoppedFails; + private volatile boolean answered; + + @Override + public void running(String sessionId) { + } + + @Override + public void answering(String sessionId) { + answered = true; + events.add("answering"); + } + + @Override + public void silent(String sessionId, String why) { + events.add("silent"); + } + + @Override + public void stopped(String sessionId, SparkJobRunner.Outcome outcome) { + if (stoppedFails) { + throw new IllegalStateException("could not store the session"); + } + events.add("stopped"); + } + + @Override + public boolean starting(String sessionId) { + return !answered; + } + + @Override + public boolean going(String sessionId) { + return true; + } + + @Override + public String refusal(String sessionId) { + return refusal.get(); + } + + @Override + public void busy(String sessionId) { + events.add("busy"); + } + + @Override + public void idle(String sessionId) { + idleWait.run(); + events.add("idle"); + } + + @Override + public void gone(String sessionId) { + events.add("gone"); + } + } + + /** Runs a server until it is stopped, listening at once. */ + private static final class ServerRunner implements SparkJobRunner { + private final CompletableFuture end = new CompletableFuture<>(); + + @Override + public Outcome run(Job job, Progress progress) { + progress.started(); + progress.listening("127.0.0.1", 15002); + return end.join(); + } + + @Override + public void stop(String runId) { + end.complete(Outcome.halted()); + } + + @Override + public void removeLeftoverDrivers(String service) { + } + } +}