mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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://<host>:<port>/;x-aws-proxy-auth=<token>;authorization=<session id>, 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.
This commit is contained in:
1 parent
948dcadae8
commit
2517edb471
23 files changed
+1926
-451
No files matched your search
@@ -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<String> 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.";
|
||||
|
||||
@@ -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<Map<String, EmrCluster>>() {});
|
||||
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> 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<String, String> 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<EmrSession> {
|
||||
|
||||
@Override
|
||||
protected <T> T locked(Supplier<T> body) {
|
||||
return call(body);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Optional<EmrSession> 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<String> releaseImage,
|
||||
BiFunction<String, BooleanSupplier, SparkJobRunner.Storage> 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<String> releaseImage = cluster.getBootstrapImage() == null ? releaseImage(cluster) : null;
|
||||
String clusterId = cluster.getId();
|
||||
String hdfsHost = masterPrivateDnsName(cluster);
|
||||
String hdfsImage = hdfsImage(cluster.getReleaseLabel());
|
||||
Supplier<ClusterStorage.Yarn> 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<String, BooleanSupplier, SparkJobRunner.Storage> 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<String> application = hive == null ? EmrSparkSteps.application(step, yarn) : null;
|
||||
List<String> 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<String> 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<ClusterStorage.Yarn> 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<String, BooleanSupplier, SparkJobRunner.Storage> 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<String> releaseImage;
|
||||
private final BiFunction<String, BooleanSupplier, SparkJobRunner.Storage> hdfs;
|
||||
private final Instance primary;
|
||||
private String image;
|
||||
private String address;
|
||||
|
||||
ClusterPreparation(String clusterId, String accountId, String region, Supplier<String> releaseImage,
|
||||
BiFunction<String, BooleanSupplier, SparkJobRunner.Storage> 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.
|
||||
|
||||
@@ -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<String> STATES =
|
||||
List.of(SUBMITTED, "STARTING", "STARTED", IDLE, "BUSY", "TERMINATING", TERMINATED, "FAILED");
|
||||
private static final Set<String> ENDED = Set.of(TERMINATED, "FAILED");
|
||||
List.of(SUBMITTED, STARTING, "STARTED", IDLE, BUSY, TERMINATING, TERMINATED, FAILED);
|
||||
private static final Set<String> 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);
|
||||
}
|
||||
}
|
||||
@@ -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<String, String> 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; }
|
||||
}
|
||||
+76
-329
@@ -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<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;
|
||||
@@ -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<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;
|
||||
// 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<SessionRecord> 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> 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<SessionRecord> {
|
||||
|
||||
@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> T locked(Supplier<T> body) {
|
||||
synchronized (EmrServerlessSessionService.this) {
|
||||
return body.get();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void timedOut() {
|
||||
// The run's outcome says so, which serverEnded reads.
|
||||
protected Optional<SessionRecord> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<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 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> 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()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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<R> 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<String> ENDED = Set.of(TERMINATED, FAILED);
|
||||
|
||||
/** Runs {@code body} under the service's lock. */
|
||||
protected abstract <T> T locked(Supplier<T> body);
|
||||
|
||||
/** The stored session of that id. */
|
||||
protected abstract Optional<R> 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<R> change) {
|
||||
locked(() -> {
|
||||
find(sessionId).filter(stored -> state.equals(session(stored).getState())).ifPresent(change);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user