feat(emr-serverless): run a session's Spark Connect server in the docker runner mode (#8731)

With runner-mode docker, StartSession now runs the session's driver, a
Spark Connect server, in a container, as a job run's driver runs: in the
release's image or the application's custom image, on the same network,
with the execution role's credentials and the application's executors.
Its spark-defaults are the application's runtime configuration, then the
session's runtimeConfiguration; Floci sets the server's port and drops a
spark.connect.grpc.binding.address, which "is reserved by EMR Serverless
and cannot be overridden by users".

A client reaches the server through Floci. GetSessionEndpoint answers
Floci's own address, and the client puts the token in the
x-aws-proxy-auth parameter, as AWS's connection string does
(sc://<host>:443/;use_ssl=true;x-aws-proxy-auth=<token>). The new
core.common.SparkConnectProxy takes gRPC calls to
spark.connect.SparkConnectService on Floci's port, checks the token, and
forwards each call over HTTP/2, trailers included, to the server, whose
port is published on the Docker host's loopback interface only; a
Trailers-Only answer, Spark's error before any message, goes back as
one. A call
with no token, an unknown one or an expired one fails with gRPC's
UNAUTHENTICATED; one to a session that is not ready, or in the immediate
mode, with UNAVAILABLE.

The session is SUBMITTED until its container runs, STARTING until the
server answers, then IDLE. 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. TerminateSession goes through
TERMINATING until the container has stopped; the idle timeout, the 24
hours (counted from when the server answers) and StopApplication stop it
too, each session keeping one check for its next deadline. A server that
exits on its own, or does not answer within 10 minutes, fails the
session with the reason; one a restart left behind fails as interrupted,
and its container, if the startup's cleanup left it, is removed.

The runner's Job gains a listening port, published on loopback and
reported through Progress.listening once the container runs.

EmrServerlessSparkConnectNightlyIntegrationTest runs it for real: the
server in the emr-7.13.0 image and Spark's own JVM Spark Connect client
from that image, which runs a query through Floci with the token and is
refused with a wrong one. The nightly job's timeout and image prefetch
take the new check.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-17 07:55:24 -04:00
1 parent 93c1d39348
commit 50276fa533
17 files changed
+1840 -64

No files matched your search

@@ -7,16 +7,17 @@ import java.util.HexFormat;
/**
* What GetSessionEndpoint answers for a Spark Connect session, EMR Serverless's and EMR's alike: the endpoint a client
* connects to and an authentication token, with when it expires. Each call gives a new token; Floci runs no Spark
* Connect server behind the endpoint, so nothing checks one.
* connects to and an authentication token, with when it expires. Each call gives a new token. Where a service runs a
* Spark Connect server for its sessions, as EMR Serverless does in its docker runner mode, {@link SparkConnectProxy}
* checks the token on each call; elsewhere nothing checks one.
*/
public record SparkConnectEndpoint(String url, String authToken, Instant authTokenExpiresAt) {
private static final int TOKEN_BYTES = 32;
/**
* The endpoint at {@code path} on Floci's {@code baseUrl}, a trailing slash of which is dropped, with a new random
* token that expires {@code validity} after {@code now}.
* The endpoint at {@code path} on Floci's {@code baseUrl} (Floci's address itself for an empty one), a trailing
* slash of which is dropped, with a new random token that expires {@code validity} after {@code now}.
*/
public static SparkConnectEndpoint issue(String baseUrl, String path, Instant now, Duration validity) {
String base = baseUrl == null ? "" : baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1)
@@ -0,0 +1,278 @@
package io.floci.aws.core.common;
import io.vertx.core.Future;
import io.vertx.core.MultiMap;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.http.HttpClientRequest;
import io.vertx.core.http.HttpClientResponse;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.http.HttpVersion;
import io.vertx.core.http.RequestOptions;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Spark Connect for the sessions Floci runs a server for. A client's gRPC calls to
* {@code spark.connect.SparkConnectService} on Floci's own port carry the session's authentication token as their
* {@code x-aws-proxy-auth} metadata, as EMR Serverless's connection string puts it
* ({@code sc://<host>:443/;use_ssl=true;x-aws-proxy-auth=<token>}, EMR Serverless user guide, "Run interactive
* sessions with Amazon EMR Serverless through Spark Connect"), and each goes on, over HTTP/2, to the server of the
* session the token was issued for, which {@link SparkConnectTargets} names. A call with no token, or one no service
* issued, ends at once with gRPC's UNAUTHENTICATED, as "When a token expires, gRPC calls fail with an authentication
* error"; one the service refuses ends with the status it gives.
*/
@ApplicationScoped
public class SparkConnectProxy {
private static final Logger LOG = Logger.getLogger(SparkConnectProxy.class);
static final String SERVICE_PATH = "/spark.connect.SparkConnectService/";
/** The call metadata that carries a session's authentication token. */
public static final String TOKEN_METADATA = "x-aws-proxy-auth";
// A call to a service no Spark Connect server has, which its gRPC server answers UNIMPLEMENTED once it runs.
private static final String PROBE_PATH = "/grpc.health.v1.Health/Check";
// An empty gRPC message's bytes: no compression, a length of 0.
private static final int EMPTY_MESSAGE_LENGTH = 5;
// How long a probe waits for the server's answer before it gives up on that call, its stream reset.
private static final long PROBE_TIMEOUT_MILLIS = 5_000;
private static final String GRPC_CONTENT_TYPE = "application/grpc";
private static final Set<String> NOT_FORWARDED = Set.of("host", "connection", "keep-alive", "proxy-connection",
"transfer-encoding", "upgrade", "http2-settings", TOKEN_METADATA);
static final String NO_TOKEN = "The call carries no " + TOKEN_METADATA + " authentication token.";
public static final String UNKNOWN_TOKEN =
"The authentication token is not valid. Call GetSessionEndpoint for a new one.";
private final Instance<SparkConnectTargets> targets;
private final Vertx vertx;
private final HttpClient client;
@Inject
public SparkConnectProxy(Instance<SparkConnectTargets> targets, Vertx vertx) {
this.targets = targets;
this.vertx = vertx;
// gRPC's servers speak HTTP/2 from the first byte, with no upgrade from HTTP/1.1.
this.client = vertx.createHttpClient(new HttpClientOptions()
.setProtocolVersion(HttpVersion.HTTP_2)
.setHttp2ClearTextUpgrade(false)
.setConnectTimeout(5_000));
}
@PreDestroy
void close() {
client.close();
}
void register(@Observes Router router) {
router.route().handler(this::handle);
}
void handle(RoutingContext context) {
HttpServerRequest request = context.request();
if (request.version() != HttpVersion.HTTP_2 || request.method() != HttpMethod.POST
|| !request.path().startsWith(SERVICE_PATH) || !grpc(request.getHeader("content-type"))) {
context.next();
return;
}
request.pause();
String token = request.getHeader(TOKEN_METADATA);
// A service reads its storage to route a call, so off the event loop.
vertx.<SparkConnectTargets.Route>executeBlocking(() -> route(token), false).onComplete(routed -> {
if (routed.failed()) {
LOG.warnv(routed.cause(), "Spark Connect call {0} could not be routed", request.path());
refuse(request, SparkConnectTargets.Route.UNAVAILABLE, "The call could not be routed.");
} else if (routed.result().refusal() != null) {
refuse(request, routed.result().status(), routed.result().refusal());
} else {
forward(request, routed.result());
}
});
}
/**
* Why no Spark Connect server answers at {@code host} and {@code port}, or null once one does: any gRPC answer to
* a call it has no method for says it runs. A port Docker publishes accepts a connection before the server in the
* container listens, so a connection alone says nothing. A call with no answer within
* {@value #PROBE_TIMEOUT_MILLIS} ms is reset, so probes that go unanswered leave no stream behind.
*/
public Future<String> unanswered(String host, int port) {
RequestOptions options = new RequestOptions().setMethod(HttpMethod.POST).setHost(host).setPort(port)
.setURI(PROBE_PATH)
.setIdleTimeout(PROBE_TIMEOUT_MILLIS)
.putHeader("content-type", GRPC_CONTENT_TYPE)
.putHeader("te", "trailers");
return client.request(options)
// A Buffer of each call's own: one held in a static field would be built into the native image's
// heap, which its build refuses.
.compose(probe -> probe.send(Buffer.buffer(new byte[EMPTY_MESSAGE_LENGTH])))
.compose(answer -> answer.body().map(body -> answer.statusCode() == 200 ? (String) null
: "the server answered HTTP " + answer.statusCode()))
.recover(failure -> {
LOG.debugv("No Spark Connect server answers at {0}:{1}: {2}", host, port, failure.toString());
return Future.succeededFuture(failure.toString());
});
}
private SparkConnectTargets.Route route(String token) {
if (token == null || token.isBlank()) {
return SparkConnectTargets.Route.refused(SparkConnectTargets.Route.UNAUTHENTICATED, NO_TOKEN);
}
for (SparkConnectTargets service : targets) {
Optional<SparkConnectTargets.Route> route = service.route(token);
if (route.isPresent()) {
return route.get();
}
}
return SparkConnectTargets.Route.refused(SparkConnectTargets.Route.UNAUTHENTICATED, UNKNOWN_TOKEN);
}
private void forward(HttpServerRequest request, SparkConnectTargets.Route route) {
HttpServerResponse response = request.response();
AtomicBoolean over = new AtomicBoolean();
Runnable ended = () -> {
if (over.compareAndSet(false, true)) {
vertx.executeBlocking(() -> {
route.ended().run();
return null;
}, false);
}
};
RequestOptions options = new RequestOptions().setMethod(HttpMethod.POST).setHost(route.host())
.setPort(route.port()).setURI(request.uri());
for (Map.Entry<String, String> header : request.headers()) {
if (!NOT_FORWARDED.contains(header.getKey().toLowerCase(Locale.ROOT))) {
options.addHeader(header.getKey(), header.getValue());
}
}
client.request(options).onComplete(opened -> {
if (opened.failed()) {
refuse(request, SparkConnectTargets.Route.UNAVAILABLE,
"The session's Spark Connect server could not be reached: " + opened.cause().getMessage());
ended.run();
return;
}
HttpClientRequest upstream = opened.result();
// A gRPC call's messages stream with no Content-Length, which Vert.x takes only on a streamed request.
if (request.getHeader("content-length") == null) {
upstream.setChunked(true);
}
// A client that goes away takes its call on the server with it.
response.closeHandler(closed -> {
upstream.reset();
ended.run();
});
upstream.response().onComplete(answered -> {
if (answered.failed()) {
if (response.headWritten()) {
response.reset();
} else {
refuse(request, SparkConnectTargets.Route.UNAVAILABLE,
"The session's Spark Connect server ended the call: " + answered.cause().getMessage());
}
ended.run();
return;
}
relay(answered.result(), response, ended);
});
// A call whose messages cannot reach the server is reset on both sides, and over.
request.pipeTo(upstream).onFailure(failure -> {
upstream.reset();
if (!response.ended()) {
response.reset();
}
ended.run();
});
});
}
/**
* The server's answer: its messages, then its trailers, which hold the call's gRPC status; or, where the server
* answered "Trailers-Only", its status in its only headers, as grpc-java answers an error raised before any
* message, those headers alone, ending the call, as a client finds the status nowhere else.
*/
private static void relay(HttpClientResponse answer, HttpServerResponse response, Runnable ended) {
response.setStatusCode(answer.statusCode());
copy(answer.headers(), response.headers());
if (answer.headers().contains("grpc-status")) {
answer.body().onComplete(read -> {
if (read.succeeded()) {
response.end();
} else {
response.reset();
}
ended.run();
});
return;
}
answer.pipe().endOnComplete(false).to(response).onComplete(piped -> {
if (piped.succeeded()) {
copy(answer.trailers(), response.trailers());
response.end();
} else {
response.reset();
}
ended.run();
});
}
private static void copy(MultiMap from, MultiMap to) {
for (Map.Entry<String, String> header : from) {
if (!NOT_FORWARDED.contains(header.getKey().toLowerCase(Locale.ROOT))) {
to.add(header.getKey(), header.getValue());
}
}
}
// A call that ends at once, with its status in the only headers it gets, as gRPC's "Trailers-Only" answer.
private static void refuse(HttpServerRequest request, int status, String message) {
request.resume();
HttpServerResponse response = request.response();
if (response.ended()) {
return;
}
response.setStatusCode(200)
.putHeader("content-type", GRPC_CONTENT_TYPE)
.putHeader("grpc-status", String.valueOf(status))
.putHeader("grpc-message", percentEncoded(message))
.end();
}
static boolean grpc(String contentType) {
if (contentType == null) {
return false;
}
String type = contentType.toLowerCase(Locale.ROOT);
return type.equals(GRPC_CONTENT_TYPE) || type.startsWith(GRPC_CONTENT_TYPE + "+")
|| type.startsWith(GRPC_CONTENT_TYPE + ";");
}
// gRPC's grpc-message: UTF-8, its bytes outside printable ASCII, and '%', percent-encoded.
static String percentEncoded(String message) {
StringBuilder encoded = new StringBuilder();
for (byte b : message.getBytes(StandardCharsets.UTF_8)) {
if (b >= 0x20 && b <= 0x7e && b != '%') {
encoded.append((char) b);
} else {
encoded.append('%').append(String.format("%02X", b & 0xff));
}
}
return encoded.toString();
}
}
@@ -0,0 +1,40 @@
package io.floci.aws.core.common;
import java.util.Optional;
/**
* A service whose sessions take Spark Connect calls through {@link SparkConnectProxy}: it tells where a call carrying
* an authentication token goes. Called off the event loop, as it may read the service's storage.
*/
public interface SparkConnectTargets {
/**
* Where a call carrying {@code token} goes, or empty when {@code token} is not one this service issued. A call
* routed to a server counts as running in its session from now until {@link Route#ended} runs.
*/
Optional<Route> route(String token);
/**
* Where a call goes: the server at {@code host} and {@code port}, with {@code ended} to run once the call is over;
* or, when {@code refusal} is not null, nowhere, the call ending at once with the gRPC status {@code status} and
* {@code refusal} as its message.
*/
record Route(String host, int port, Runnable ended, int status, String refusal) {
/** gRPC's status for a call no server is there to take. */
public static final int UNAVAILABLE = 14;
/** gRPC's status for a call whose credentials are missing, unknown or expired. */
public static final int UNAUTHENTICATED = 16;
/** A call that goes to the server at {@code host} and {@code port}. */
public static Route to(String host, int port, Runnable ended) {
return new Route(host, port, ended, 0, null);
}
/** A call that ends at once with {@code status} and {@code refusal}. */
public static Route refused(int status, String refusal) {
return new Route(null, 0, () -> { }, status, refusal);
}
}
}
@@ -26,6 +26,7 @@ import io.floci.aws.services.emrserverless.model.JobRunRecord;
import io.floci.aws.services.emrserverless.model.JobRunSummary;
import io.floci.aws.services.emrserverless.model.MaximumCapacity;
import io.floci.aws.services.emrserverless.model.RuntimeConfiguration;
import io.floci.aws.services.emrserverless.model.Session;
import io.floci.aws.services.emrserverless.model.StartJobRunRequest;
import io.floci.aws.services.emrserverless.model.WorkerTypeSpecification;
import io.floci.aws.services.iam.IamService;
@@ -85,8 +86,15 @@ public class EmrServerlessJobRunService implements Resettable {
private static final String MODE_STREAMING = "STREAMING";
private static final String RUNNER_DOCKER = "docker";
// The service a container run's driver belongs to, which names it and labels it.
private static final String SERVICE = "emr-serverless";
static final String SERVICE = "emr-serverless";
private static final String SPARK_DEFAULTS = "spark-defaults";
private static final String SPARK_CONNECT_SERVER = "org.apache.spark.sql.connect.service.SparkConnectServer";
// Where an emr- release's image keeps the Spark Connect server, as emr-7.13.0's does.
static final String SPARK_CONNECT_JAR = "/usr/lib/spark/connector/lib/spark-connect.jar";
// spark-submit's application for a class among Spark's own jars.
private static final String SPARK_INTERNAL = "spark-internal";
private static final String SPARK_CONNECT_PORT = "spark.connect.grpc.binding.port";
private static final String SPARK_CONNECT_ADDRESS = "spark.connect.grpc.binding.address";
private static final String S3_MONITORING = "s3MonitoringConfiguration";
private static final String CLOUD_WATCH_LOGGING = "cloudWatchLoggingConfiguration";
// "If you don't specify the optional values, then CloudWatch publishes the logs to a default log group".
@@ -622,6 +630,48 @@ public class EmrServerlessJobRunService implements Resettable {
runExecutor.execute(() -> execute(onPlatform, launchedIn));
}
/** The runner of the docker runner mode, or null in the immediate one. */
SparkJobRunner containerRunner() {
return sparkRunner;
}
/**
* What runs a session's Spark Connect server in a container, as a run's driver runs: in the application's image,
* on its network, with the session's execution role and its executors as a run's are, for {@code limit} at most.
* Its {@code spark-defaults} are the application's, then the session's {@code runtimeConfiguration}, merged as a
* run's {@code applicationConfiguration} is, with the server's port {@code port}; a
* {@code spark.connect.grpc.binding.address} is dropped, as "The Spark configuration
* spark.connect.grpc.binding.address is reserved by EMR Serverless and cannot be overridden by users" (EMR
* Serverless user guide, "Run interactive sessions with Amazon EMR Serverless through Spark Connect").
*/
SparkJobRunner.Job sessionJob(Application app, Session session, Duration limit, int port) {
Object overrides = session.getConfigurationOverrides() != null
? session.getConfigurationOverrides().get("runtimeConfiguration") : null;
Map<String, String> sparkDefaults = classificationProperties(app, overrides, session.getReleaseLabel(),
SPARK_DEFAULTS);
sparkDefaults.remove(SPARK_CONNECT_ADDRESS);
sparkDefaults.put(SPARK_CONNECT_PORT, String.valueOf(port));
AwsArnUtils.Arn arn = AwsArnUtils.parse(session.getArn());
SparkJobRunner.Job job = new SparkJobRunner.Job(SERVICE, session.getSessionId(), arn.accountId(),
arn.region(), session.getReleaseLabel(), SparkJobRunner.Engine.SPARK, imageTemplate, customImage(app),
dockerNetwork, session.getExecutionRoleArn(), sparkDefaults,
sparkConnectServer(session.getReleaseLabel()), null, limit, null, null,
driverEnvironment(sparkDefaults), archives(sparkDefaults), null, Map.of(), Map.of(), Map.of(),
Map.of(), Map.of(), executors(app, executorContainers));
return job.withPlatform(honourArchitectures ? DockerPlatforms.forArchitecture(app.getArchitecture()) : null)
.listeningOn(port);
}
/**
* What starts the Spark Connect server on {@code spark-submit}'s command line: its class, and, on an emr- release,
* whose Spark 3.5 keeps the server in {@value #SPARK_CONNECT_JAR}, that jar as the application; the AWS runtime
* for Apache Spark's Spark 4 carries the server among its own jars.
*/
static List<String> sparkConnectServer(String releaseLabel) {
return List.of("--class", SPARK_CONNECT_SERVER,
sparkRuntime(releaseLabel) ? SPARK_INTERNAL : SPARK_CONNECT_JAR);
}
private void execute(SparkJobRunner.Job job, long launchedIn) {
SparkJobRunner.Outcome outcome;
try {
@@ -1057,16 +1107,26 @@ public class EmrServerlessJobRunService implements Resettable {
* considered for this classification." From emr-spark-8.1.0 they merge by property, the run's winning.
*/
private static Map<String, String> classificationProperties(Application app, JobRun run, String classification) {
Object overrides = run.getConfigurationOverrides() != null
? run.getConfigurationOverrides().get("applicationConfiguration") : null;
return classificationProperties(app, overrides, run.getReleaseLabel(), classification);
}
/**
* A {@code classification}'s properties: the application's runtime configuration, then {@code overrides}, a
* workload's own configuration list on {@code releaseLabel}, merged as {@link #classificationProperties} merges a
* run's.
*/
private static Map<String, String> classificationProperties(Application app, Object overrides,
String releaseLabel, String classification) {
Map<String, String> properties = new LinkedHashMap<>();
if (app.getRuntimeConfiguration() != null) {
for (RuntimeConfiguration configuration : app.getRuntimeConfiguration()) {
addProperties(properties, configuration.getMembers(), classification);
}
}
Object overrides = run.getConfigurationOverrides() != null
? run.getConfigurationOverrides().get("applicationConfiguration") : null;
if (overrides instanceof List<?> configurations) {
boolean replaces = !releaseAtLeast(SPARK_RUNTIME_RELEASE_LABEL, run.getReleaseLabel(), 8, 1);
boolean replaces = !releaseAtLeast(SPARK_RUNTIME_RELEASE_LABEL, releaseLabel, 8, 1);
for (Object configuration : configurations) {
if (configuration instanceof Map<?, ?> members
&& classification.equals(members.get("classification"))) {
@@ -9,8 +9,12 @@ import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestContext;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.core.common.Resettable;
import io.floci.aws.core.common.SmithyValidationErrors;
import io.floci.aws.core.common.SparkConnectEndpoint;
import io.floci.aws.core.common.SparkConnectProxy;
import io.floci.aws.core.common.SparkConnectTargets;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.emrserverless.model.Application;
@@ -19,6 +23,7 @@ import io.floci.aws.services.emrserverless.model.SessionRecord;
import io.floci.aws.services.emrserverless.model.SessionSummary;
import io.floci.aws.services.emrserverless.model.StartSessionRequest;
import io.floci.aws.services.iam.IamService;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -28,28 +33,54 @@ import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* EMR Serverless sessions: "a managed connection between your local PySpark client and a Spark driver running on Amazon
* EMR Serverless", through Spark Connect (EMR Serverless user guide, "Run interactive sessions with Amazon EMR
* Serverless through Spark Connect"). Floci keeps each session and its lifecycle but starts no Spark driver for it: a
* session is IDLE once started, nothing answers Spark Connect at its endpoint, and it ends when it is terminated, when
* its idle timeout or its 24 hours pass, or when its application stops.
* Serverless through Spark Connect"). A session ends when it is terminated, when its idle timeout or its 24 hours pass,
* or when its application stops.
*
* <p>In the docker runner mode a session runs a Spark Connect server, its driver, in a container, as a job run's driver
* runs ({@link EmrServerlessJobRunService#sessionJob}): it is SUBMITTED, then STARTING once its container runs, and
* IDLE once the server answers. A client reaches the server through {@link SparkConnectProxy}, with a token
* GetSessionEndpoint gave; the session is BUSY while a call runs there, and IDLE again, its idle timeout counting from
* then, once none does. A server that exits on its own fails its session. In the immediate runner mode no server runs:
* a session is IDLE once started, and a call to it is refused.
*/
@ApplicationScoped
public class EmrServerlessSessionService {
public class EmrServerlessSessionService implements SparkConnectTargets, Resettable {
private static final Logger LOG = Logger.getLogger(EmrServerlessSessionService.class);
static final String STATE_SUBMITTED = "SUBMITTED";
static final String STATE_STARTING = "STARTING";
static final String STATE_IDLE = "IDLE";
static final String STATE_BUSY = "BUSY";
static final String STATE_FAILED = "FAILED";
static final String STATE_TERMINATING = "TERMINATING";
static final String STATE_TERMINATED = "TERMINATED";
private static final List<String> STATES =
List.of("SUBMITTED", "STARTING", "STARTED", STATE_IDLE, "BUSY", "FAILED", "TERMINATING", STATE_TERMINATED);
private static final Set<String> ENDED = Set.of("FAILED", STATE_TERMINATED);
private static final List<String> STATES = List.of(STATE_SUBMITTED, STATE_STARTING, "STARTED", STATE_IDLE,
STATE_BUSY, STATE_FAILED, STATE_TERMINATING, STATE_TERMINATED);
private static final Set<String> 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<String> RESOURCE_TYPES = List.of("SESSION");
// SessionStateSet holds 1 to 8 states; a ListSessions page holds 1 to 50 sessions.
private static final int MAX_FILTER_STATES = 8;
@@ -64,13 +95,21 @@ public class EmrServerlessSessionService {
static final Duration HARD_LIMIT = Duration.ofHours(24);
// "Authentication tokens are time-limited to 1 hour."
static final Duration TOKEN_VALIDITY = Duration.ofHours(1);
// Where GetSessionEndpoint points; nothing answers Spark Connect there, as Floci runs no driver for a session.
static final String ENDPOINT_PATH = "/_aws/emr-serverless/sessions/";
private static final String SPARK_TYPE = "SPARK";
// No source gives AWS's wording for these ends; they are Floci's.
static final String IDLE_TIMED_OUT = "The session was idle for its idle timeout.";
static final String HARD_LIMIT_REACHED = "The session reached its 24 hour limit.";
static final String APPLICATION_STOPPED = "The session's application was stopped.";
static final String INTERRUPTED = "Floci stopped while the session was running.";
static final String SERVER_EXITED = "The session's Spark Connect server exited with code %d.";
static final String SERVER_NOT_STARTED = "The session's Spark Connect server could not start: %s";
static final String SERVER_SILENT = "The session's Spark Connect server did not answer within "
+ SERVER_START_LIMIT.toMinutes() + " minutes: %s";
static final String SERVER_ENDED = "The session's Spark Connect server ended with no exit code.";
static final String TOKEN_EXPIRED = "The authentication token has expired. Call GetSessionEndpoint for a new one.";
static final String NO_SERVER = "Floci runs no Spark Connect server for session %s, as the EMR Serverless runner"
+ " mode is immediate; floci.services.emrserverless.runner-mode docker runs one.";
static final String NOT_READY = "Session %s is %s, not ready for calls.";
private final AccountAwareStorageBackend<SessionRecord> store;
private final EmrServerlessService applications;
@@ -81,21 +120,51 @@ public class EmrServerlessSessionService {
private final ObjectMapper objectMapper;
private final Clock clock;
private final String baseUrl;
// The docker runner mode's runner, which runs each session's Spark Connect server; null in the immediate mode.
private final SparkJobRunner sparkRunner;
private final Executor serverExecutor;
// Ends each session at its next deadline, its idle timeout or its 24 hours, and its server with it.
private final ScheduledExecutorService idleChecks;
private final ServerProbe probe;
// The sessions whose server a thread of this process runs; one not here that has not ended was left by a restart.
private final Map<String, Server> servers = new HashMap<>();
// The authentication tokens GetSessionEndpoint gave, until they expire or their session ends.
private final Map<String, Grant> grants = new ConcurrentHashMap<>();
// Raised by each reset, so a server's thread from before it writes nothing back after the wipe.
private long generation;
@Inject
public EmrServerlessSessionService(StorageFactory storageFactory, EmrServerlessService applications,
EmrServerlessJobRunService jobRuns, IamService iamService,
RegionResolver regionResolver, RequestContext requestContext,
ObjectMapper objectMapper, EmulatorConfig config, Clock clock) {
ObjectMapper objectMapper, EmulatorConfig config, Clock clock,
SparkConnectProxy proxy) {
this(storageFactory.create("emrserverless", "emr-serverless-sessions.json", new TypeReference<>() {}),
applications, jobRuns, iamService, regionResolver, requestContext, objectMapper, clock,
config.effectiveBaseUrl());
config.effectiveBaseUrl(), jobRuns.containerRunner(),
Executors.newCachedThreadPool(Thread.ofPlatform().daemon().name("emr-serverless-session-", 0)
.factory()),
sessionChecks(),
(host, port) -> unanswered(proxy, host, port));
}
EmrServerlessSessionService(AccountAwareStorageBackend<SessionRecord> store, EmrServerlessService applications,
EmrServerlessJobRunService jobRuns, IamService iamService,
RegionResolver regionResolver, RequestContext requestContext,
ObjectMapper objectMapper, Clock clock, String baseUrl) {
this(store, applications, jobRuns, iamService, regionResolver, requestContext, objectMapper, clock, baseUrl,
null, Runnable::run, null, (host, port) -> "no server runs");
}
EmrServerlessSessionService(AccountAwareStorageBackend<SessionRecord> store, EmrServerlessService applications,
EmrServerlessJobRunService jobRuns, IamService iamService,
RegionResolver regionResolver, RequestContext requestContext,
ObjectMapper objectMapper, Clock clock, String baseUrl, SparkJobRunner sparkRunner,
Executor serverExecutor, ScheduledExecutorService idleChecks, ServerProbe probe) {
this.sparkRunner = sparkRunner;
this.serverExecutor = serverExecutor;
this.idleChecks = idleChecks;
this.probe = probe;
this.store = store;
this.applications = applications;
this.jobRuns = jobRuns;
@@ -107,6 +176,32 @@ public class EmrServerlessSessionService {
this.baseUrl = baseUrl;
}
@PreDestroy
void shutdown() {
if (serverExecutor instanceof ExecutorService executor) {
executor.shutdownNow();
}
if (idleChecks != null) {
idleChecks.shutdownNow();
}
}
/**
* A reset has begun: the servers' threads from before it write nothing more, and their tokens go. The runner's
* teardown stops their containers.
*/
@Override
public synchronized void beforeReset() {
generation++;
servers.clear();
grants.clear();
}
@Override
public void clear() {
// The sessions live in storage, which the reset wipes.
}
/**
* Starts a session, which "The application must be in the STARTED state or have AutoStart enabled, and have
* interactive sessions enabled" for, on "EMR release 7.13.0 and later", and, as "Spark Connect is supported only
@@ -179,8 +274,9 @@ public class EmrServerlessSessionService {
/**
* Terminates a session that has not ended: "After you terminate a session, it enters the TERMINATING state and
* then the TERMINATED state." With no driver to stop, Floci's is TERMINATED at once. One that has already ended
* is refused; no source gives AWS's answer for it, so the wording is Floci's.
* then the TERMINATED state." One whose server runs is TERMINATING until its container has stopped; with no
* server, it is TERMINATED at once. One that has already ended is refused; no source gives AWS's answer for it,
* so the wording is Floci's.
*/
public synchronized Session terminateSession(String applicationId, String sessionId) {
applications.getApplication(applicationId);
@@ -188,6 +284,20 @@ public class EmrServerlessSessionService {
if (ENDED.contains(record.getSession().getState())) {
throw new AwsException("ValidationException", "Session " + sessionId + " has already ended.", 400);
}
Server server = servers.get(sessionId);
if (server != null) {
cancelCheck(server);
Session session = record.getSession();
session.setState(STATE_TERMINATING);
session.setStateDetails("");
session.setIdleSince(null);
session.setUpdatedAt(now());
store.put(sessionId, record);
dropGrants(sessionId);
sparkRunner.stop(sessionId);
LOG.infov("Terminating EMR Serverless session {0} on application {1}", sessionId, applicationId);
return copy(session);
}
end(record, STATE_TERMINATED, null, now());
LOG.infov("Terminated EMR Serverless session {0} on application {1}", sessionId, applicationId);
return copy(record.getSession());
@@ -195,17 +305,91 @@ public class EmrServerlessSessionService {
/**
* Where a client connects to a session that has not ended, with an authentication token, which is "time-limited
* to 1 hour". The endpoint is on Floci's own address, where nothing answers Spark Connect, as Floci runs no driver
* for a session. No source gives AWS's answer for a session that has ended, so the refusal's wording is Floci's.
* to 1 hour". The endpoint is Floci's own address, where {@link SparkConnectProxy} takes a call carrying the token
* on to the session's server: Spark Connect's {@code sc://} URL holds a host and a port but no path, so the token
* alone names the session. No source gives AWS's answer for a session that has ended, so the refusal's wording is
* Floci's.
*/
public synchronized SparkConnectEndpoint sessionEndpoint(String applicationId, String sessionId) {
applications.getApplication(applicationId);
Session session = settle(findSession(applicationId, sessionId)).getSession();
if (ENDED.contains(session.getState())) {
if (ENDED.contains(session.getState()) || STATE_TERMINATING.equals(session.getState())) {
throw new AwsException("ValidationException", "Session " + sessionId + " has ended.", 400);
}
return SparkConnectEndpoint.issue(baseUrl, ENDPOINT_PATH + applicationId + "/" + sessionId, now(),
TOKEN_VALIDITY);
Instant now = now();
SparkConnectEndpoint endpoint = SparkConnectEndpoint.issue(baseUrl, "", now, TOKEN_VALIDITY);
grants.values().removeIf(grant -> !now.isBefore(grant.expiresAt()));
AwsArnUtils.Arn arn = AwsArnUtils.parse(session.getArn());
grants.put(endpoint.authToken(), new Grant(arn.accountId(), arn.region(), sessionId,
endpoint.authTokenExpiresAt()));
return endpoint;
}
/**
* Where a Spark Connect call carrying {@code token} goes: the server of the session the token was given for, while
* the token has not expired and the session is IDLE or BUSY. The call makes the session BUSY until it ends. No
* source gives AWS's answer for a session that has not started or has ended, so the refusals' wording is Floci's.
*/
@Override
public Optional<Route> route(String token) {
Grant grant = grants.get(token);
if (grant == null) {
return Optional.empty();
}
return Optional.of(RequestScopes.callAs(grant.accountId(), grant.region(), () -> callStarted(token, grant)));
}
private synchronized Route callStarted(String token, Grant grant) {
if (!clock.instant().isBefore(grant.expiresAt())) {
grants.remove(token);
return Route.refused(Route.UNAUTHENTICATED, TOKEN_EXPIRED);
}
SessionRecord record = store.get(grant.sessionId()).orElse(null);
if (record == null) {
grants.remove(token);
return Route.refused(Route.UNAUTHENTICATED, SparkConnectProxy.UNKNOWN_TOKEN);
}
Session session = settle(record).getSession();
if (!record.isContainerSession()) {
return Route.refused(Route.UNAVAILABLE, String.format(NO_SERVER, grant.sessionId()));
}
Server server = servers.get(grant.sessionId());
boolean ready = STATE_IDLE.equals(session.getState()) || STATE_BUSY.equals(session.getState());
if (server == null || server.host == null || !ready) {
return Route.refused(Route.UNAVAILABLE, String.format(NOT_READY, grant.sessionId(), session.getState()));
}
server.calls++;
if (STATE_IDLE.equals(session.getState())) {
session.setState(STATE_BUSY);
session.setIdleSince(null);
session.setUpdatedAt(now());
store.put(session.getSessionId(), record);
// A busy session's idle timeout does not run, so only its 24 hours are left to check.
checkLater(record);
}
long launchedIn = generation;
return Route.to(server.host, server.port, () -> RequestScopes.runAs(grant.accountId(), grant.region(),
() -> callEnded(grant.sessionId(), launchedIn)));
}
// A call has ended: with none left, the session is IDLE again from now.
private synchronized void callEnded(String sessionId, long launchedIn) {
Server server = servers.get(sessionId);
if (launchedIn != generation || server == null) {
return;
}
server.calls = Math.max(0, server.calls - 1);
if (server.calls > 0) {
return;
}
store.get(sessionId).filter(record -> STATE_BUSY.equals(record.getSession().getState())).ifPresent(record -> {
Instant now = now();
record.getSession().setState(STATE_IDLE);
record.getSession().setIdleSince(now);
record.getSession().setUpdatedAt(now);
store.put(sessionId, record);
checkLater(record);
});
}
/**
@@ -386,8 +570,6 @@ public class EmrServerlessSessionService {
session.setArn(AwsArnUtils.Arn.of("emr-serverless", applicationArn.region(), applicationArn.accountId(),
applicationArn.resource() + "/sessions/" + sessionId).toString());
session.setName(request.getName());
// With no driver to start, a session is ready, and idle, as it starts.
session.setState(STATE_IDLE);
session.setStateDetails("");
session.setReleaseLabel(app.getReleaseLabel());
session.setExecutionRoleArn(request.getExecutionRoleArn());
@@ -395,8 +577,14 @@ public class EmrServerlessSessionService {
applicationArn.accountId()));
session.setCreatedAt(now);
session.setUpdatedAt(now);
session.setStartedAt(now);
session.setIdleSince(now);
if (sparkRunner == null) {
// With no driver to start, a session is ready, and idle, as it starts.
session.setState(STATE_IDLE);
session.setStartedAt(now);
session.setIdleSince(now);
} else {
session.setState(STATE_SUBMITTED);
}
// "Only runtime configuration overrides are supported."
if (request.getConfigurationOverrides() != null
&& request.getConfigurationOverrides().get("runtimeConfiguration") != null) {
@@ -412,10 +600,224 @@ public class EmrServerlessSessionService {
record.setSession(session);
record.setClientToken(request.getClientToken());
record.setRequest(original);
record.setContainerSession(sparkRunner != null);
store.put(sessionId, record);
if (sparkRunner != null) {
launch(record, app);
}
return record;
}
// Hands a session's server to a thread of its own, which runs it until the session ends.
private void launch(SessionRecord record, Application app) {
Session session = record.getSession();
// The session's 24 hours count from when its server answers, where settle() reads them, so the runner sets
// none of its own.
SparkJobRunner.Job job = jobRuns.sessionJob(app, session, Duration.ZERO, SPARK_CONNECT_PORT);
servers.put(session.getSessionId(), new Server());
long launchedIn = generation;
serverExecutor.execute(() -> runServer(job, launchedIn));
}
private void runServer(SparkJobRunner.Job job, long launchedIn) {
SparkJobRunner.Outcome outcome;
try {
outcome = sparkRunner.run(job, new ServerProgress(job, launchedIn));
} catch (RuntimeException e) {
LOG.warnv(e, "The Spark Connect server of EMR Serverless session {0} could not run", job.runId());
outcome = SparkJobRunner.Outcome.couldNotStart(e.getMessage() != null ? e.getMessage() : e.toString());
}
SparkJobRunner.Outcome ended = outcome;
RequestScopes.runAs(job.accountId(), job.region(), () -> serverEnded(job.runId(), ended, launchedIn));
}
// Asks the server whether it answers until it does, its session stops starting, or its time to start is up.
private void awaitServer(SparkJobRunner.Job job, String host, int port, long launchedIn) {
long giveUp = System.nanoTime() + SERVER_START_LIMIT.toNanos();
while (RequestScopes.callAs(job.accountId(), job.region(), () -> starting(job.runId(), launchedIn))) {
String unanswered = probe.unanswered(host, port);
if (unanswered == null) {
RequestScopes.runAs(job.accountId(), job.region(), () -> serverReady(job.runId(), launchedIn));
return;
}
if (System.nanoTime() - giveUp >= 0) {
LOG.warnv("The Spark Connect server of EMR Serverless session {0} did not answer: {1}", job.runId(),
unanswered);
RequestScopes.runAs(job.accountId(), job.region(),
() -> serverSilent(job.runId(), unanswered, launchedIn));
return;
}
try {
Thread.sleep(SERVER_PROBE_INTERVAL_MILLIS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
}
private synchronized boolean starting(String sessionId, long launchedIn) {
return launchedIn == generation && store.get(sessionId)
.map(record -> STATE_STARTING.equals(record.getSession().getState())).orElse(false);
}
// Whether a session's server may still start, or go on.
private synchronized boolean stillGoing(String sessionId, long launchedIn) {
return launchedIn == generation && servers.containsKey(sessionId) && store.get(sessionId)
.map(record -> !ENDED.contains(record.getSession().getState())
&& !STATE_TERMINATING.equals(record.getSession().getState()))
.orElse(false);
}
private synchronized void serverStarted(String sessionId, long launchedIn) {
if (launchedIn != generation) {
return;
}
store.get(sessionId).filter(record -> STATE_SUBMITTED.equals(record.getSession().getState()))
.ifPresent(record -> {
record.getSession().setState(STATE_STARTING);
record.getSession().setUpdatedAt(now());
store.put(sessionId, record);
});
}
private synchronized boolean serverListening(String sessionId, String host, int port, long launchedIn) {
Server server = servers.get(sessionId);
if (launchedIn != generation || server == null) {
return false;
}
server.host = host;
server.port = port;
return true;
}
// The server answers: the session is ready, and IDLE, its idle timeout counting from now.
private synchronized void serverReady(String sessionId, long launchedIn) {
if (launchedIn != generation) {
return;
}
store.get(sessionId).filter(record -> STATE_STARTING.equals(record.getSession().getState()))
.ifPresent(record -> {
Instant now = now();
Session session = record.getSession();
session.setState(STATE_IDLE);
session.setStartedAt(now);
session.setIdleSince(now);
session.setUpdatedAt(now);
store.put(sessionId, record);
checkLater(record);
LOG.infov("EMR Serverless session {0} is ready", sessionId);
});
}
private synchronized void serverSilent(String sessionId, String unanswered, long launchedIn) {
if (launchedIn != generation) {
return;
}
store.get(sessionId).filter(record -> STATE_STARTING.equals(record.getSession().getState()))
.ifPresent(record -> end(record, STATE_FAILED, String.format(SERVER_SILENT, unanswered), now()));
}
/**
* A session's server has stopped: a session being terminated is TERMINATED, as is one whose server Floci stopped or
* that ran past its 24 hours, and one whose server stopped on its own, or never started, has FAILED.
*/
private synchronized void serverEnded(String sessionId, SparkJobRunner.Outcome outcome, long launchedIn) {
if (launchedIn != generation) {
return;
}
Server server = servers.remove(sessionId);
if (server != null) {
cancelCheck(server);
}
dropGrants(sessionId);
store.get(sessionId).ifPresent(record -> {
String state = record.getSession().getState();
if (ENDED.contains(state)) {
return;
}
Instant now = now();
if (STATE_TERMINATING.equals(state)) {
end(record, STATE_TERMINATED, null, now);
} else if (outcome.timedOut()) {
end(record, STATE_TERMINATED, HARD_LIMIT_REACHED, now);
} else if (outcome.stopped()) {
end(record, STATE_TERMINATED, null, now);
} else if (outcome.failure() != null) {
end(record, STATE_FAILED, String.format(SERVER_NOT_STARTED, outcome.failure()), now);
} else if (outcome.exitCode() != null) {
end(record, STATE_FAILED, String.format(SERVER_EXITED, outcome.exitCode()), now);
} else {
end(record, STATE_FAILED, SERVER_ENDED, now);
}
});
}
/**
* Checks a session with a server again at its next deadline: once its idle timeout passes, while it is idle, or
* once its 24 hours pass, whichever comes first, so it ends then, its server with it. Each session keeps one check,
* which this replaces, and which ending it cancels.
*/
private void checkLater(SessionRecord record) {
Session session = record.getSession();
Server server = servers.get(session.getSessionId());
if (idleChecks == null || server == null || session.getStartedAt() == null) {
return;
}
Instant deadline = session.getStartedAt().plus(HARD_LIMIT);
Long minutes = session.getIdleTimeoutMinutes();
if (STATE_IDLE.equals(session.getState()) && session.getIdleSince() != null && minutes != null
&& minutes > 0) {
Instant idleLimit = session.getIdleSince().plus(Duration.ofMinutes(minutes));
deadline = idleLimit.isBefore(deadline) ? idleLimit : deadline;
}
if (server.check != null) {
server.check.cancel(false);
}
AwsArnUtils.Arn arn = AwsArnUtils.parse(session.getArn());
String sessionId = session.getSessionId();
server.check = idleChecks.schedule(
() -> RequestScopes.runAs(arn.accountId(), arn.region(), () -> checkNow(sessionId)),
Math.max(0, Duration.between(clock.instant(), deadline).toMillis()), TimeUnit.MILLISECONDS);
}
private static void cancelCheck(Server server) {
if (server.check != null) {
server.check.cancel(false);
server.check = null;
}
}
private synchronized void checkNow(String sessionId) {
store.get(sessionId).ifPresent(this::settle);
}
// One thread that ends sessions at their deadlines; a check a later one replaces leaves its queue at once.
private static ScheduledExecutorService sessionChecks() {
ScheduledThreadPoolExecutor checks = new ScheduledThreadPoolExecutor(1,
Thread.ofPlatform().daemon().name("emr-serverless-session-checks").factory());
checks.setRemoveOnCancelPolicy(true);
return checks;
}
private void dropGrants(String sessionId) {
grants.values().removeIf(grant -> grant.sessionId().equals(sessionId));
}
// Why no server answers at host and port yet, or null once one does.
private static String unanswered(SparkConnectProxy proxy, String host, int port) {
try {
return proxy.unanswered(host, port).toCompletionStage().toCompletableFuture()
.get(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return "interrupted";
} catch (Exception e) {
LOG.debugv(e, "Probing the Spark Connect server at {0}:{1} failed", host, port);
return e.toString();
}
}
/**
* Ends a session whose time has run out by now: an idle one once its idle timeout has passed since it went idle,
* and any once its 24 hours have passed since it started, whichever comes first. An idle timeout of 0 ends
@@ -426,6 +828,16 @@ public class EmrServerlessSessionService {
if (ENDED.contains(session.getState())) {
return record;
}
// Its thread ends it; without one, Floci stopped while its server ran, and nothing is left to. A server
// container the startup's cleanup left behind goes now.
if (record.isContainerSession() && !servers.containsKey(session.getSessionId())) {
boolean terminating = STATE_TERMINATING.equals(session.getState());
end(record, terminating ? STATE_TERMINATED : STATE_FAILED, terminating ? null : INTERRUPTED, now());
if (sparkRunner != null) {
sparkRunner.removeLeftoverDriver(EmrServerlessJobRunService.SERVICE, session.getSessionId());
}
return record;
}
Instant hardLimit = session.getStartedAt() != null ? session.getStartedAt().plus(HARD_LIMIT) : null;
Long idleMinutes = session.getIdleTimeoutMinutes();
Instant idleLimit = STATE_IDLE.equals(session.getState()) && session.getIdleSince() != null
@@ -451,6 +863,13 @@ public class EmrServerlessSessionService {
session.setTotalExecutionDurationSeconds(Duration.between(session.getStartedAt(), at).toSeconds());
}
store.put(session.getSessionId(), record);
dropGrants(session.getSessionId());
// An ended session's server goes with it, and its check; its thread finds the session ended and leaves it so.
Server server = servers.get(session.getSessionId());
if (server != null) {
cancelCheck(server);
sparkRunner.stop(session.getSessionId());
}
}
private SessionRecord findSession(String applicationId, String sessionId) {
@@ -482,4 +901,58 @@ public class EmrServerlessSessionService {
private Session copy(Session session) {
return objectMapper.convertValue(session, Session.class);
}
/** Why no Spark Connect server answers at a host and port, or null once one does. */
@FunctionalInterface
interface ServerProbe {
String unanswered(String host, int port);
}
// A session's running server: where Floci reaches it, once its container runs, how many calls it is taking, and
// the check that ends the session at its next deadline.
private static final class Server {
String host;
int port;
int calls;
ScheduledFuture<?> check;
}
// What an authentication token was given for: a session, in its account and Region, until it expires.
private record Grant(String accountId, String region, String sessionId, Instant expiresAt) {
}
/** What the thread running a session's server tells the service, and asks it, as that session. */
private final class ServerProgress implements SparkJobRunner.Progress {
private final SparkJobRunner.Job job;
private final long launchedIn;
ServerProgress(SparkJobRunner.Job job, long launchedIn) {
this.job = job;
this.launchedIn = launchedIn;
}
@Override
public void started() {
RequestScopes.runAs(job.accountId(), job.region(), () -> serverStarted(job.runId(), launchedIn));
}
@Override
public void listening(String host, int port) {
if (RequestScopes.callAs(job.accountId(), job.region(),
() -> serverListening(job.runId(), host, port, launchedIn))) {
serverExecutor.execute(() -> awaitServer(job, host, port, launchedIn));
}
}
@Override
public void timedOut() {
// The run's outcome says so, which serverEnded reads.
}
@Override
public boolean cancelled() {
return !RequestScopes.callAs(job.accountId(), job.region(), () -> stillGoing(job.runId(), launchedIn));
}
}
}
@@ -619,6 +619,10 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
container.withEnv(HADOOP_ENV_VARIABLE, hadoopEnvFile(job));
}
}
if (job.listenPort() > 0) {
// Reached through Floci alone, so published on the host's loopback interface only.
container.withLoopbackPortBinding(job.listenPort(), 0);
}
ContainerSpec spec = container
.withDockerNetwork(Optional.ofNullable(job.dockerNetwork()))
.withHostDockerInternalOnLinux()
@@ -649,9 +653,13 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
if (stopped.getAsBoolean()) {
return Outcome.halted();
}
lifecycleManager.startCreated(containerId, spec);
ContainerLifecycleManager.ContainerInfo info = lifecycleManager.startCreated(containerId, spec);
logHandle = attachLog(containerId, job);
progress.started();
if (job.listenPort() > 0) {
ContainerLifecycleManager.EndpointInfo listening = info.getEndpoint(job.listenPort());
progress.listening(listening.host(), listening.port());
}
if (job.executors() != null) {
capacity = joinCapacity(job.executors().application());
executors = new SparkExecutors(job.executors(), driver(containerId),
@@ -751,6 +759,24 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
}
}
@Override
public void removeLeftoverDriver(String service, String runId) {
if (launches.get(runId) != null) {
return;
}
try {
lifecycleManager.findByName(ContainerStorageHelper.dockerName(config, service + "-" + runId))
.ifPresent(container -> {
lifecycleManager.removeIfExists(container.getId());
LOG.infov("Removed {0} Spark driver {1} of {2}, left running by an earlier Floci process",
service, container.getId(), runId);
});
} catch (RuntimeException e) {
LOG.warnv("Could not remove the {0} Spark driver of {1} an earlier Floci process left: {2}", service,
runId, e.getMessage());
}
}
// Floci's log always gets the driver's output, and the job's CloudWatch log streams too when it has some.
private Closeable attachLog(String containerId, Job job) {
String prefix = job.service() + ":" + job.runId();
@@ -31,12 +31,26 @@ public interface SparkJobRunner {
*/
void removeLeftoverDrivers(String service);
/**
* Removes the driver of {@code service}'s run {@code runId} where an earlier Floci process left it running, as one
* {@link #removeLeftoverDrivers} could not remove; a driver this process runs is left alone.
*/
default void removeLeftoverDriver(String service, String runId) {
}
/** What a run tells the service, and asks it, while it goes. */
interface Progress {
/** The run's Spark driver runs. */
void started();
/**
* The port the run's job listens on ({@link Job#listenPort}) is reachable from Floci at {@code host} and
* {@code port}, now its driver's container runs; what listens there may not be ready yet.
*/
default void listening(String host, int port) {
}
/**
* The run resolved the custom image its job names for {@code workerType} ({@link Job#customImage} for its
* driver, {@link Executors#image} for its executors) to the image whose manifest digest is {@code digest}, and
@@ -97,7 +111,9 @@ public interface SparkJobRunner {
* command gets (each empty for none); for an EMR Serverless Spark run, where its executors run, in
* containers of their own (null for Spark's local mode, in the driver's container); and the Docker platform
* its containers run, as its application's architecture names it with {@code honour-architectures} on,
* {@code linux/amd64} or {@code linux/arm64} (null for the Docker host's own).
* {@code linux/amd64} or {@code linux/arm64} (null for the Docker host's own); and the port in its driver's
* container that something there listens on for Floci, which Floci reaches through the Docker host's loopback
* interface only, as {@link Progress#listening} tells (0 for none).
*/
record Job(String service, String runId, String accountId, String region, String releaseLabel, Engine engine,
String imageTemplate, String customImage, String dockerNetwork, String executionRole,
@@ -105,7 +121,22 @@ public interface SparkJobRunner {
String logFolder, CloudWatchLogs cloudWatchLogs, Map<String, String> environment,
List<String> archives, Storage storage, Map<String, String> coreSite,
Map<String, String> sparkLog4j2, Map<String, String> mapredSite, Map<String, String> hadoopLog4j,
Map<String, String> hadoopEnvironment, Executors executors, String platform) {
Map<String, String> hadoopEnvironment, Executors executors, String platform, int listenPort) {
/** A job whose driver listens on no port for Floci. */
public Job(String service, String runId, String accountId, String region, String releaseLabel, Engine engine,
String imageTemplate, String customImage, String dockerNetwork, String executionRole,
Map<String, String> sparkDefaults, List<String> application, List<String> command,
Duration timeout, String logFolder, CloudWatchLogs cloudWatchLogs,
Map<String, String> environment, List<String> archives, Storage storage,
Map<String, String> coreSite, Map<String, String> sparkLog4j2, Map<String, String> mapredSite,
Map<String, String> hadoopLog4j, Map<String, String> hadoopEnvironment, Executors executors,
String platform) {
this(service, runId, accountId, region, releaseLabel, engine, imageTemplate, customImage, dockerNetwork,
executionRole, sparkDefaults, application, command, timeout, logFolder, cloudWatchLogs,
environment, archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j,
hadoopEnvironment, executors, platform, 0);
}
/** A job on the Docker host's own platform. */
public Job(String service, String runId, String accountId, String region, String releaseLabel, Engine engine,
@@ -126,7 +157,7 @@ public interface SparkJobRunner {
return new Job(service, runId, accountId, region, releaseLabel, engine, imageTemplate, customImage,
dockerNetwork, executionRole, sparkDefaults, application, command, timeout, logFolder,
cloudWatchLogs, environment, archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j,
hadoopEnvironment, executors, platform);
hadoopEnvironment, executors, platform, listenPort);
}
/** This job, run in {@code image}. */
@@ -134,7 +165,7 @@ public interface SparkJobRunner {
return new Job(service, runId, accountId, region, releaseLabel, engine, image, customImage, dockerNetwork,
executionRole, sparkDefaults, application, command, timeout, logFolder, cloudWatchLogs, environment,
archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j, hadoopEnvironment, executors,
platform);
platform, listenPort);
}
/** This job, its executors where {@code executors} has them. */
@@ -142,7 +173,15 @@ public interface SparkJobRunner {
return new Job(service, runId, accountId, region, releaseLabel, engine, imageTemplate, customImage,
dockerNetwork, executionRole, sparkDefaults, application, command, timeout, logFolder,
cloudWatchLogs, environment, archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j,
hadoopEnvironment, executors, platform);
hadoopEnvironment, executors, platform, listenPort);
}
/** This job, its driver listening on {@code port} for Floci (0 for none). */
public Job listeningOn(int port) {
return new Job(service, runId, accountId, region, releaseLabel, engine, imageTemplate, customImage,
dockerNetwork, executionRole, sparkDefaults, application, command, timeout, logFolder,
cloudWatchLogs, environment, archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j,
hadoopEnvironment, executors, platform, port);
}
/** This job, its containers run for {@code platform} (null for the Docker host's own). */
@@ -150,7 +189,7 @@ public interface SparkJobRunner {
return new Job(service, runId, accountId, region, releaseLabel, engine, imageTemplate, customImage,
dockerNetwork, executionRole, sparkDefaults, application, command, timeout, logFolder,
cloudWatchLogs, environment, archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j,
hadoopEnvironment, executors, platform);
hadoopEnvironment, executors, platform, listenPort);
}
}
@@ -5,13 +5,15 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
/**
* A stored session: the session as GetSession reports it, plus the client token and the request it came with, which
* decide whether a repeated StartSession is a retry or a conflict.
* decide whether a repeated StartSession is a retry or a conflict, and whether a Spark Connect server runs for it.
*/
@RegisterForReflection
public class SessionRecord {
private Session session;
private String clientToken;
private JsonNode request;
// Whether Floci runs a Spark Connect server for it, as it does in the docker runner mode.
private boolean containerSession;
public Session getSession() { return session; }
public void setSession(Session session) { this.session = session; }
@@ -19,4 +21,6 @@ public class SessionRecord {
public void setClientToken(String clientToken) { this.clientToken = clientToken; }
public JsonNode getRequest() { return request; }
public void setRequest(JsonNode request) { this.request = request; }
public boolean isContainerSession() { return containerSession; }
public void setContainerSession(boolean containerSession) { this.containerSession = containerSession; }
}