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:
Priamo Germosen authored and GitHub committed 2026-11-17 12:18:09 -04:00
1 parent 948dcadae8
commit 2517edb471
23 files changed
+1926 -451

No files matched your search

@@ -90,6 +90,7 @@ class SparkConnectProxyTest {
assertEquals("0", answer.trailers.get("grpc-status"));
// The token is Floci's to check, so the server never sees it.
assertNull(serverSaw.get().get(SparkConnectProxy.TOKEN_METADATA));
assertNull(serverSaw.get().get("authorization"));
assertEquals("trailers", serverSaw.get().get("te"));
assertNull(serverSaw.get().get("transfer-encoding"));
awaitCount(callsEnded, 1);
@@ -170,6 +171,8 @@ class SparkConnectProxyTest {
.putHeader("te", "trailers");
if (token != null) {
options.putHeader(SparkConnectProxy.TOKEN_METADATA, token);
// As AWS's EMR connection string adds the session's id.
options.putHeader("authorization", "is-SESSION");
}
// As a gRPC client sends a call: its message streamed, with no Content-Length.
return await(client.request(options)
@@ -6,6 +6,7 @@ import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.ContainerTeardown;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.SparkConnectProxy;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.emr.model.EmrCluster;
import io.floci.aws.services.emr.model.EmrErrorDetail;
@@ -1455,7 +1456,8 @@ class EmrServiceContainerStepsTest {
new EmrService(new InMemoryStorageFactory(ACCOUNT), config, regionResolver,
new EmrEventPublisher(mock(EventBridgeService.class), new ObjectMapper(), regionResolver),
sparkRunner, bootstrapRunner, clusterStorage, mock(EmrReleaseImages.class), mock(IamService.class))
sparkRunner, bootstrapRunner, clusterStorage, mock(EmrReleaseImages.class), mock(IamService.class),
mock(SparkConnectProxy.class))
.shutdown();
verify(sparkRunner, times(reconcile ? 1 : 0)).removeLeftoverDrivers("emr");
@@ -7,6 +7,7 @@ import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.emr.model.EmrCluster;
import io.floci.aws.services.emr.model.EmrStep;
import io.floci.aws.services.emrserverless.SparkConnectServers;
import io.floci.aws.services.emrserverless.SparkJobRunner;
import io.floci.aws.services.eventbridge.EventBridgeService;
import io.floci.aws.services.iam.IamService;
@@ -22,6 +23,7 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import java.util.function.Function;
@@ -228,8 +230,8 @@ final class EmrServiceFixture {
Target target = event -> { };
private final List<Wakeup> wakeups = new ArrayList<>();
private final List<Runnable> deliveries = new ArrayList<>();
// The docker runner mode's step threads, not yet run.
private final List<Runnable> stepThreads = new ArrayList<>();
// The docker runner mode's step threads, not yet run; a session server's thread may add one too.
private final List<Runnable> stepThreads = new CopyOnWriteArrayList<>();
private boolean waking;
final InMemoryStorageFactory storage;
private final SparkJobRunner runner;
@@ -239,6 +241,8 @@ final class EmrServiceFixture {
final RecordingReleaseImages releaseImages;
private final IamService iam;
private final int[] durations;
// How the docker runner mode's session servers are asked whether they answer; null for no session servers.
private final SparkConnectServers.Probe sessionProbe;
/** The service as configured by default, every duration 0. */
EmrServiceFixture() {
@@ -246,7 +250,7 @@ final class EmrServiceFixture {
}
EmrServiceFixture(int startupDelaySeconds, int stepDurationSeconds, int terminationDelaySeconds) {
this(new InMemoryStorageFactory(ACCOUNT), new MutableClock(), null, null, null, null, null,
this(new InMemoryStorageFactory(ACCOUNT), new MutableClock(), null, null, null, null, null, null,
startupDelaySeconds, stepDurationSeconds, terminationDelaySeconds);
}
@@ -258,12 +262,23 @@ final class EmrServiceFixture {
/** As {@link #docker(SparkJobRunner, IamService)}, its clusters' bootstrap actions run by {@code bootstrap}. */
static EmrServiceFixture docker(SparkJobRunner runner, BootstrapRunner bootstrap, IamService iam) {
return new EmrServiceFixture(new InMemoryStorageFactory(ACCOUNT), new MutableClock(), runner, bootstrap,
new RecordingStorage(), new RecordingReleaseImages(), iam, 0, 0, 0);
new RecordingStorage(), new RecordingReleaseImages(), iam, null, 0, 0, 0);
}
/**
* As {@link #docker(SparkJobRunner, IamService)}, its sessions' Spark Connect servers run by {@code runner} too,
* each on a thread of its own, and asked whether they answer by {@code probe}.
*/
static EmrServiceFixture dockerSessions(SparkJobRunner runner, IamService iam, SparkConnectServers.Probe probe) {
return new EmrServiceFixture(new InMemoryStorageFactory(ACCOUNT), new MutableClock(), runner, null,
new RecordingStorage(), new RecordingReleaseImages(), iam, probe, 0, 0, 0);
}
private EmrServiceFixture(InMemoryStorageFactory storage, MutableClock clock, SparkJobRunner runner,
BootstrapRunner bootstrap, RecordingStorage clusterStorage,
RecordingReleaseImages releaseImages, IamService iam, int... durations) {
RecordingReleaseImages releaseImages, IamService iam,
SparkConnectServers.Probe sessionProbe, int... durations) {
this.sessionProbe = sessionProbe;
this.storage = storage;
this.clock = clock;
this.runner = runner;
@@ -286,7 +301,7 @@ final class EmrServiceFixture {
}).when(eventBridge).publishServiceEvent(eq("aws.emr"), anyString(), anyString(), isNull(), eq(REGION));
RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT);
publisher = new EmrEventPublisher(eventBridge, objectMapper, regionResolver);
service = new EmrService(storage, config(false), regionResolver, publisher, clock, new EmrService.Wakeups() {
EmrService.Wakeups recorded = new EmrService.Wakeups() {
@Override
public void at(Instant due, Runnable task) {
wakeups.add(new Wakeup(due, task));
@@ -296,17 +311,25 @@ final class EmrServiceFixture {
public void deliver(Runnable delivery) {
deliveries.add(delivery);
}
}, runner, bootstrap, clusterStorage, releaseImages, stepThreads::add, iam);
};
service = sessionProbe == null
? new EmrService(storage, config(false), regionResolver, publisher, clock, recorded, runner, bootstrap,
clusterStorage, releaseImages, stepThreads::add, iam)
: new EmrService(storage, config(false), regionResolver, publisher, clock, recorded, runner, bootstrap,
clusterStorage, releaseImages, stepThreads::add, iam,
new SparkConnectServers(runner, task -> Thread.ofPlatform().daemon().start(task), null,
sessionProbe, clock));
}
/** A new service on the same storage and clock, as after a restart of Floci with persistent storage. */
EmrServiceFixture restart() {
return new EmrServiceFixture(storage, clock, runner, bootstrap, clusterStorage, releaseImages, iam, durations);
return new EmrServiceFixture(storage, clock, runner, bootstrap, clusterStorage, releaseImages, iam,
sessionProbe, durations);
}
/** A new service on the same storage and clock, as {@link #restart} builds, in the {@code immediate} mode. */
EmrServiceFixture restartImmediate() {
return new EmrServiceFixture(storage, clock, null, null, null, null, iam, durations);
return new EmrServiceFixture(storage, clock, null, null, null, null, iam, null, durations);
}
/**
@@ -9,7 +9,6 @@ import org.junit.jupiter.api.Test;
import java.util.UUID;
import static io.floci.aws.testing.EmrRequests.emr;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.matchesPattern;
@@ -83,7 +82,7 @@ class EmrSessionIntegrationTest {
emr("GetSessionEndpoint", "{\"ClusterId\":\"" + clusterId + "\",\"SessionId\":\"" + sessionId + "\"}")
.then().statusCode(200)
.body("Endpoint", endsWith("/_aws/emr/sessions/" + clusterId + "/" + sessionId))
.body("Endpoint", matchesPattern("https?://[^/]+"))
.body("AuthToken", matchesPattern("[0-9a-f]{64}"))
.body("AuthTokenExpirationTime", notNullValue());
@@ -0,0 +1,223 @@
package io.floci.aws.services.emr;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.model.Container;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.docker.ContainerBuilder;
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
import io.floci.aws.core.common.docker.ContainerReachableEndpoint;
import io.floci.aws.core.common.docker.ContainerSpec;
import io.floci.aws.core.common.docker.ContainerStorageHelper;
import io.floci.aws.testing.DockerAvailability;
import io.floci.aws.testing.PartitionCleanup;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import io.restassured.path.json.JsonPath;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.net.URI;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;
import java.util.function.Supplier;
import static io.floci.aws.testing.EmrRequests.emr;
import static io.floci.aws.testing.EmrRequests.terminateClusterAndAwaitCleanup;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* An EMR session run for real: its Spark Connect server runs on its cluster, the release's image on the cluster's
* YARN, and a Spark Connect client, Spark 4's own JVM client from that image, reaches it through Floci at the endpoint
* GetSessionEndpoint gives, with the token and the session's id in the parameters AWS's connection string puts them
* in. A wrong token is refused, queries run, a query's Spark error comes back as Spark's, and TerminateSession stops
* the server.
*
* <p>A nightly check: the cluster's image, HDFS and YARN, the server and the client each take minutes and gigabytes.
*/
@QuarkusTest
@TestProfile(EmrSessionServerNightlyIntegrationTest.Profile.class)
@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true")
// Bounded waits: the cluster's image of up to twenty minutes, its HDFS and YARN, the server's start, the client's run
// and the session's end; the Nightly checks job's timeout counts the 40.
@Timeout(value = 40, unit = TimeUnit.MINUTES)
class EmrSessionServerNightlyIntegrationTest {
/** Clusters run their steps and sessions in containers, and Floci listens on a fixed port, its endpoint's. */
public static final class Profile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of(
"floci.services.emr.runner-mode", "docker",
"quarkus.http.test-port", String.valueOf(PORT),
"floci.port", String.valueOf(PORT),
"floci.base-url", "http://localhost:" + PORT);
}
}
private static final int PORT = 4596;
private static final String RELEASE = "emr-spark-8.1.0";
// Spark 4's JVM Spark Connect client, which the release's image carries, run as a single source file, against
// the URLs it is given: the refused one first, then the session's.
private static final String CLIENT = """
set -e
mkdir -p /tmp/client && cd /tmp/client && cat > Probe.java <<'JAVA'
import org.apache.spark.sql.SparkSession;
public class Probe {
public static void main(String[] args) throws Exception {
try {
SparkSession.builder().remote(args[1]).create().range(1).count();
System.out.println("REFUSED=none");
} catch (Exception e) {
System.out.println("REFUSED=" + e.getMessage());
}
SparkSession spark = SparkSession.builder().remote(args[0]).create();
System.out.println("COUNT=" + spark.range(10).count());
Object sum = spark.sql("SELECT sum(id) FROM range(5)").collectAsList().get(0).get(0);
System.out.println("SUM=" + sum);
try {
spark.sql("SELECT * FROM no_such_table").collectAsList();
System.out.println("ERROR=none");
} catch (Exception e) {
System.out.println("ERROR=" + e.getMessage());
}
spark.close();
}
}
JAVA
# The client's own jar first, then Spark's, less the classic SQL engine and the server, whose classes it
# would otherwise reach for; Spark 4's shared API needs spark-core.
classpath=$(ls /usr/lib/spark/jars/connect-repl/spark-connect-client-jvm_*.jar)
for jar in /usr/lib/spark/jars/*.jar; do
case $(basename "$jar") in
spark-sql_*|spark-catalyst_*|spark-hive*|spark-connect_*) ;;
*) classpath=$classpath:$jar ;;
esac
done
# Java 17's launcher compiles the one file itself; Arrow needs java.nio opened.
exec /usr/lib/jvm/java-17-amazon-corretto/bin/java --add-opens=java.base/java.nio=ALL-UNNAMED \\
-cp "$classpath" Probe.java "$@"
""";
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Inject
DockerClient docker;
@Inject
ContainerBuilder containerBuilder;
@Inject
ContainerLifecycleManager lifecycleManager;
@Inject
ContainerReachableEndpoint reachableEndpoint;
@Inject
EmulatorConfig config;
@Inject
EmrService emrService;
@BeforeAll
static void configure() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void aClientRunsQueriesOnTheSessionsServerThroughFlociWithItsToken() throws InterruptedException {
// Enabled, the check needs Docker: without a daemon it fails rather than pass having run nothing.
assertTrue(DockerAvailability.isAvailable(), "the nightly check needs a Docker daemon");
String clusterId = emr("RunJobFlow", "{\"Name\":\"sessions\",\"ReleaseLabel\":\"" + RELEASE + "\","
+ "\"Applications\":[{\"Name\":\"Hadoop\"},{\"Name\":\"Spark\"}],\"SessionEnabled\":true,"
+ "\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true,\"InstanceGroups\":[{\"Name\":\"primary\","
+ "\"InstanceRole\":\"MASTER\",\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":1}]}}")
.then().statusCode(200).extract().jsonPath().getString("JobFlowId");
cleanup.register(() -> terminateClusterAndAwaitCleanup(clusterId, emrService));
awaitCluster(clusterId, "WAITING", Duration.ofMinutes(5));
String sessionId = emr("StartSession", "{\"ClusterId\":\"" + clusterId + "\",\"Name\":\"probe\","
+ "\"ClientRequestToken\":\"" + UUID.randomUUID() + "\"}")
.then().statusCode(200).extract().jsonPath().getString("Id");
awaitSession(clusterId, sessionId, "IDLE", Duration.ofMinutes(25));
JsonPath endpoint = emr("GetSessionEndpoint", "{\"ClusterId\":\"" + clusterId + "\",\"SessionId\":\""
+ sessionId + "\"}").then().statusCode(200).extract().jsonPath();
assertEquals("http://localhost:" + PORT, endpoint.getString("Endpoint"));
// Floci's address as a container reaches it, where the test's endpoint names the host's loopback.
URI floci = URI.create(reachableEndpoint.baseUrl(false));
String connect = "sc://" + floci.getHost() + ":" + floci.getPort() + "/;authorization=" + sessionId
+ ";x-aws-proxy-auth=";
String server = ContainerStorageHelper.dockerName(config, "emr-" + sessionId);
String image = lifecycleManager.findByName(server).map(Container::getImage)
.orElseThrow(() -> new AssertionError("no container " + server));
String output = runClient(image, connect + endpoint.getString("AuthToken"), connect + "not-the-token");
assertTrue(output.contains("REFUSED=") && output.contains("UNAUTHENTICATED"), output);
assertTrue(output.contains("COUNT=10"), output);
assertTrue(output.contains("SUM=10"), output);
assertTrue(output.contains("ERROR=") && output.contains("TABLE_OR_VIEW_NOT_FOUND"), output);
emr("TerminateSession", "{\"ClusterId\":\"" + clusterId + "\",\"SessionId\":\"" + sessionId + "\"}")
.then().statusCode(200);
awaitSession(clusterId, sessionId, "TERMINATED", Duration.ofMinutes(2));
assertTrue(lifecycleManager.findByName(server).isEmpty(), "the session's server is still there");
}
// Runs the client in a container of the cluster's image, as far as Floci's address, and returns its output.
private String runClient(String image, String sessionUrl, String refusedUrl) throws InterruptedException {
ContainerSpec spec = containerBuilder.newContainer(image)
.withName("floci-spark-connect-client-" + UUID.randomUUID().toString().substring(0, 8))
.withEntrypoint(List.of("/bin/bash", "-c", CLIENT, "floci", sessionUrl, refusedUrl))
.withHostDockerInternalOnLinux()
.withMemoryMb(1536)
.build();
String containerId = lifecycleManager.create(spec);
try {
lifecycleManager.startCreated(containerId, spec);
int exitCode = docker.waitContainerCmd(containerId).start().awaitStatusCode(5, TimeUnit.MINUTES);
String output = lifecycleManager.lastLogLines(containerId, 200, Duration.ofSeconds(30));
assertEquals(0, exitCode, output);
return output;
} finally {
lifecycleManager.stopAndRemove(containerId, null, 1);
}
}
private void awaitCluster(String clusterId, String state, Duration limit) {
await(() -> emr("DescribeCluster", "{\"ClusterId\":\"" + clusterId + "\"}").jsonPath()
.getString("Cluster.Status.State"), state, List.of("TERMINATED", "TERMINATED_WITH_ERRORS"), limit,
"Cluster " + clusterId);
}
private void awaitSession(String clusterId, String sessionId, String state, Duration limit) {
await(() -> emr("GetSession", "{\"ClusterId\":\"" + clusterId + "\",\"SessionId\":\"" + sessionId + "\"}")
.jsonPath().getString("Session.State"), state, List.of("FAILED", "TERMINATED"), limit,
"Session " + sessionId);
}
private static void await(Supplier<String> read, String state, List<String> ends,
Duration limit, String what) {
long deadline = System.nanoTime() + limit.toNanos();
while (true) {
String now = read.get();
if (state.equals(now)) {
return;
}
if (ends.contains(now) || System.nanoTime() - deadline > 0) {
fail(what + " is " + now + ", not " + state);
}
LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(2));
}
}
}
@@ -0,0 +1,260 @@
package io.floci.aws.services.emr;
import io.floci.aws.core.common.SparkConnectEndpoint;
import io.floci.aws.core.common.SparkConnectTargets;
import io.floci.aws.services.emr.model.EmrCluster;
import io.floci.aws.services.emr.model.EmrSession;
import io.floci.aws.services.emrserverless.SparkConnectServers;
import io.floci.aws.services.emrserverless.SparkJobRunner;
import io.floci.aws.services.iam.IamService;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.LockSupport;
import static io.floci.aws.services.emr.EmrServiceFixture.REGION;
import static io.floci.aws.services.emr.EmrServiceFixture.cluster;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;
/**
* EMR sessions in the docker runner mode, each running a Spark Connect server on its cluster as a step runs: the
* session's states as its server starts, answers, takes calls and stops, with a runner that stands in for Docker.
*/
class EmrSessionServerTest {
private static final String RELEASE = "emr-spark-8.1.0";
private static final String ROLE = "arn:aws:iam::000000000000:role/emr-session-runtime";
private static final String SERVER_HOST = "127.0.0.1";
private static final int SERVER_PORT = 40321;
private final FakeServerRunner runner = new FakeServerRunner();
private final AtomicBoolean answering = new AtomicBoolean(true);
private final SparkConnectServers.Probe probe = (host, port) ->
answering.get() && SERVER_HOST.equals(host) && port == SERVER_PORT ? null : "Connection refused";
private final EmrServiceFixture fixture = EmrServiceFixture.dockerSessions(runner, mock(IamService.class), probe);
private final EmrService service = fixture.service;
@Test
void aSessionRunsItsServerOnItsClusterAndIsIdleOnceTheServerAnswers() {
String clusterId = sessionCluster();
EmrSession started = service.startSession(clusterId, new EmrSessions.Request("notebook", ROLE,
"[{\"Classification\":\"spark-defaults\",\"Properties\":{\"spark.executor.memory\":\"4g\"}}]", null,
null, null, Map.of()));
EmrSession idle = awaitState(clusterId, started.getId(), "IDLE");
assertEquals("SUBMITTED", started.getState());
assertNotNull(idle.getStartedAt());
assertEquals(idle.getStartedAt(), idle.getIdleSince());
SparkJobRunner.Job job = runner.jobs.get(started.getId());
assertEquals(EmrSessions.SPARK_CONNECT_PORT, job.listenPort());
assertEquals(List.of("--class", "org.apache.spark.sql.connect.service.SparkConnectServer", "spark-internal"),
job.application());
assertEquals("15002", job.sparkDefaults().get("spark.connect.grpc.binding.port"));
assertEquals("4g", job.sparkDefaults().get("spark.executor.memory"));
assertEquals(ROLE, job.executionRole());
// On the cluster's storage, its HDFS running, as a step's driver is.
assertNotNull(job.storage());
assertTrue(fixture.clusterStorage.created.contains(clusterId), fixture.clusterStorage.created.toString());
}
@Test
void aCallThroughItsTokenMakesTheSessionBusyUntilItEnds() {
String clusterId = sessionCluster();
String sessionId = service.startSession(clusterId, request()).getId();
awaitState(clusterId, sessionId, "IDLE");
SparkConnectEndpoint endpoint = service.sessionEndpoint(clusterId, sessionId);
SparkConnectTargets.Route route = service.route(endpoint.authToken()).orElseThrow();
assertNull(route.refusal());
assertEquals(SERVER_HOST, route.host());
assertEquals(SERVER_PORT, route.port());
assertEquals("BUSY", service.getSession(clusterId, sessionId).getState());
assertNull(service.getSession(clusterId, sessionId).getIdleSince());
route.ended().run();
assertEquals("IDLE", service.getSession(clusterId, sessionId).getState());
assertTrue(service.route("not-a-token").isEmpty());
}
@Test
void aSessionIsStartingUntilItsServerAnswersAndRefusesCallsMeanwhile() {
answering.set(false);
String clusterId = sessionCluster();
String sessionId = service.startSession(clusterId, request()).getId();
awaitState(clusterId, sessionId, "STARTING");
SparkConnectTargets.Route refused = service.route(service.sessionEndpoint(clusterId, sessionId).authToken())
.orElseThrow();
assertEquals(SparkConnectTargets.Route.UNAVAILABLE, refused.status());
assertEquals(String.format(EmrSessions.NOT_READY, sessionId, "STARTING"), refused.refusal());
answering.set(true);
awaitState(clusterId, sessionId, "IDLE");
}
@Test
void aTerminatedSessionIsTerminatingUntilItsServerStopsAndItsTokensGo() {
String clusterId = sessionCluster();
String sessionId = service.startSession(clusterId, request()).getId();
awaitState(clusterId, sessionId, "IDLE");
String token = service.sessionEndpoint(clusterId, sessionId).authToken();
EmrSession terminating = service.terminateSession(clusterId, sessionId);
EmrSession terminated = awaitState(clusterId, sessionId, "TERMINATED");
assertEquals("TERMINATING", terminating.getState());
assertTrue(runner.stopped.contains(sessionId));
assertEquals(EmrSessions.USER_REQUEST, terminated.getStateChangeReason());
assertTrue(service.route(token).isEmpty());
}
@Test
void aSessionWhoseServerExitsOnItsOwnHasFailed() {
String clusterId = sessionCluster();
String sessionId = service.startSession(clusterId, request()).getId();
awaitState(clusterId, sessionId, "IDLE");
runner.end(sessionId).complete(SparkJobRunner.Outcome.exitedWith(1));
EmrSession failed = awaitState(clusterId, sessionId, "FAILED");
assertEquals(String.format(SparkConnectServers.SERVER_EXITED, 1), failed.getStateChangeReason());
}
@Test
void anIdleSessionEndsItsServerAtItsIdleTimeoutAndTheClustersEndEndsAnother() {
String clusterId = sessionCluster();
String timingOut = service.startSession(clusterId, new EmrSessions.Request("short", null, null, null, 30L,
null, Map.of())).getId();
awaitState(clusterId, timingOut, "IDLE");
String other = service.startSession(clusterId, request()).getId();
awaitState(clusterId, other, "IDLE");
fixture.clock.advance(Duration.ofMinutes(30));
assertEquals("TERMINATED", service.getSession(clusterId, timingOut).getState());
assertTrue(runner.stopped.contains(timingOut));
assertFalse(runner.stopped.contains(other));
service.terminateJobFlows(List.of(clusterId));
EmrSession ended = service.getSession(clusterId, other);
assertEquals("TERMINATED", ended.getState());
assertEquals(EmrSessions.CLUSTER_ENDED, ended.getStateChangeReason());
assertTrue(runner.stopped.contains(other));
}
@Test
void theClustersEndStopsItsBusySessionsServerAndItsStorageGoesOnceTheServerHasGone() {
String clusterId = sessionCluster();
String sessionId = service.startSession(clusterId, request()).getId();
awaitState(clusterId, sessionId, "IDLE");
// BUSY, so no idle check would ever stop it.
SparkConnectTargets.Route call = service.route(service.sessionEndpoint(clusterId, sessionId).authToken())
.orElseThrow();
service.terminateJobFlows(List.of(clusterId));
// No read of the session: the cluster's end stopped its server.
assertTrue(runner.stopped.contains(sessionId));
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
while (fixture.stepThreadsWaiting() == 0 && System.nanoTime() - deadline < 0) {
LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10));
}
assertFalse(fixture.clusterStorage.removed.contains(clusterId));
fixture.runStepThread();
assertTrue(fixture.clusterStorage.removed.contains(clusterId), fixture.clusterStorage.removed.toString());
call.ended().run();
}
@Test
void aSessionWhoseServerNoThreadRunsAnyMoreWasInterruptedByARestart() {
String clusterId = sessionCluster();
String sessionId = service.startSession(clusterId, request()).getId();
awaitState(clusterId, sessionId, "IDLE");
EmrSession after = fixture.restart().service.getSession(clusterId, sessionId);
assertEquals("FAILED", after.getState());
assertEquals(EmrSessions.INTERRUPTED, after.getStateChangeReason());
assertEquals(List.of(sessionId), runner.leftoversRemoved);
}
private String sessionCluster() {
EmrCluster cluster = cluster("sessions", true);
cluster.setReleaseLabel(RELEASE);
cluster.setApplications("[{\"Name\":\"Spark\"}]");
cluster.setSessionEnabled(true);
return service.runJobFlow(cluster, REGION).getId();
}
private static EmrSessions.Request request() {
return new EmrSessions.Request("notebook", null, null, null, null, null, Map.of());
}
// Polls until the session is in state, as its server's thread moves it on its own.
private EmrSession awaitState(String clusterId, String sessionId, String state) {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
while (true) {
EmrSession session = service.getSession(clusterId, sessionId);
if (state.equals(session.getState())) {
return session;
}
if (System.nanoTime() - deadline > 0) {
fail("Session " + sessionId + " is " + session.getState() + ", not " + state + ": "
+ session.getStateChangeReason());
}
LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10));
}
}
/** Runs each session's server as the Docker runner would, until it is stopped or told how it ends. */
private static final class FakeServerRunner implements SparkJobRunner {
final Map<String, Job> jobs = new ConcurrentHashMap<>();
final Set<String> stopped = ConcurrentHashMap.newKeySet();
final List<String> leftoversRemoved = new CopyOnWriteArrayList<>();
private final Map<String, CompletableFuture<Outcome>> ends = new ConcurrentHashMap<>();
@Override
public Outcome run(Job job, Progress progress) {
jobs.put(job.runId(), job);
if (progress.cancelled()) {
return Outcome.halted();
}
progress.started();
progress.listening(SERVER_HOST, SERVER_PORT);
return end(job.runId()).join();
}
@Override
public void stop(String runId) {
stopped.add(runId);
end(runId).complete(Outcome.halted());
}
@Override
public void removeLeftoverDrivers(String service) {
}
@Override
public void removeLeftoverDriver(String service, String runId) {
leftoversRemoved.add(runId);
}
CompletableFuture<Outcome> end(String runId) {
return ends.computeIfAbsent(runId, id -> new CompletableFuture<>());
}
}
}
@@ -198,7 +198,8 @@ class EmrSessionsTest {
SparkConnectEndpoint endpoint = service.sessionEndpoint(clusterId, sessionId);
assertEquals("http://localhost:4566/_aws/emr/sessions/" + clusterId + "/" + sessionId, endpoint.url());
// Spark Connect's sc:// URL holds no path, so the endpoint is Floci's address and the token names the session.
assertEquals("http://localhost:4566", endpoint.url());
assertTrue(endpoint.authToken().matches("[0-9a-f]{64}"), endpoint.authToken());
assertTrue(Duration.between(fixture.clock.instant(), endpoint.authTokenExpiresAt())
.compareTo(Duration.ofMinutes(59)) > 0);
@@ -171,7 +171,7 @@ class EmrServerlessSessionServerTest {
Session failed = awaitState(applicationId, sessionId, "FAILED");
assertEquals(String.format(EmrServerlessSessionService.SERVER_NOT_STARTED, "java.lang.IllegalStateException"),
assertEquals(String.format(SparkConnectServers.SERVER_NOT_STARTED, "java.lang.IllegalStateException"),
failed.getStateDetails());
}
@@ -272,7 +272,7 @@ class EmrServerlessSessionServerTest {
runner.end(sessionId).complete(SparkJobRunner.Outcome.exitedWith(1));
Session failed = awaitState(applicationId, sessionId, "FAILED");
assertEquals(String.format(EmrServerlessSessionService.SERVER_EXITED, 1), failed.getStateDetails());
assertEquals(String.format(SparkConnectServers.SERVER_EXITED, 1), failed.getStateDetails());
}
@Test
@@ -267,7 +267,7 @@ class EmrServerlessSessionServiceTest {
assertEquals(String.format(EmrServerlessSessionService.NO_SERVER, sessionId), route.refusal());
assertTrue(sessions.route("not-a-token").isEmpty());
clock.advance(EmrServerlessSessionService.TOKEN_VALIDITY);
assertEquals(EmrServerlessSessionService.TOKEN_EXPIRED, sessions.route(token).orElseThrow().refusal());
assertEquals(SparkConnectServers.TOKEN_EXPIRED, sessions.route(token).orElseThrow().refusal());
}
@Test
@@ -0,0 +1,201 @@
package io.floci.aws.services.emrserverless;
import io.floci.aws.core.common.SparkConnectTargets.Route;
import org.junit.jupiter.api.Test;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.LockSupport;
import java.util.function.BooleanSupplier;
import java.util.function.Supplier;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* The servers {@link SparkConnectServers} runs, read from its owner's side: what reaches the owner, in what order, and
* what a call is answered, as servers start, take calls and stop.
*/
class SparkConnectServersTest {
private static final String SESSION = "session-1";
private static final String TOKEN = "a-token";
private final ServerRunner runner = new ServerRunner();
private final SparkConnectServers servers = new SparkConnectServers(runner,
task -> Thread.ofPlatform().daemon().start(task), null, (host, port) -> null, Clock.systemUTC());
private final RecordingOwner owner = new RecordingOwner();
@Test
void aCallIsRefusedWhenItsServerIsStoppedAfterItsOwnerLetItThrough() {
answeringServer();
// The session is terminated between the owner's check and the server's.
owner.refusal = () -> {
servers.stop(SESSION);
return null;
};
Route route = servers.route(TOKEN, owner).orElseThrow();
assertEquals(Route.UNAVAILABLE, route.status());
assertEquals(String.format(SparkConnectServers.NO_RUNNING_SERVER, SESSION), route.refusal());
}
@Test
void aCallsBusyReachesTheOwnerOnlyAfterTheIdleOfTheCallThatEndedBeforeIt() throws Exception {
answeringServer();
Route first = servers.route(TOKEN, owner).orElseThrow();
CountDownLatch idleEntered = new CountDownLatch(1);
CountDownLatch idleMayEnd = new CountDownLatch(1);
owner.idleWait = () -> {
idleEntered.countDown();
await(idleMayEnd);
};
CompletableFuture<Void> ending = CompletableFuture.runAsync(first.ended());
await(idleEntered);
CompletableFuture<Route> next = CompletableFuture.supplyAsync(() -> servers.route(TOKEN, owner).orElseThrow());
// The next call waits for the idle in progress, rather than going BUSY under it.
assertThrows(TimeoutException.class, () -> next.get(500, TimeUnit.MILLISECONDS));
idleMayEnd.countDown();
ending.get(10, TimeUnit.SECONDS);
next.get(10, TimeUnit.SECONDS);
assertEquals(List.of("answering", "busy", "idle", "busy"), owner.events);
}
@Test
void aServersEntryGoesWhenItStopsEvenWhereItsOwnerFailsToHearIt() {
answeringServer();
owner.stoppedFails = true;
servers.stop(SESSION);
awaitTrue(() -> owner.events.contains("gone"));
assertFalse(servers.runs(SESSION));
assertTrue(servers.route(TOKEN, owner).isEmpty());
}
// A session's server, running and answering, with a token for it.
private void answeringServer() {
servers.launch(new SparkJobRunner.Job("test", SESSION, "000000000000", "us-east-1", "emr-7.13.0",
SparkJobRunner.Engine.SPARK, null, null, null, null, Map.of(), List.of(), null, Duration.ZERO, null,
null, Map.of(), List.of(), null, Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), null), owner);
awaitTrue(() -> owner.events.contains("answering"));
servers.grant(TOKEN, SESSION, "000000000000", "us-east-1", Instant.now().plus(Duration.ofHours(1)));
}
private static void awaitTrue(BooleanSupplier condition) {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
while (!condition.getAsBoolean()) {
if (System.nanoTime() - deadline > 0) {
fail("not reached in time");
}
LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10));
}
}
private static void await(CountDownLatch latch) {
try {
assertTrue(latch.await(10, TimeUnit.SECONDS));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException(e);
}
}
/** An owner that records what reaches it, the idle as it ends, and answers as the test sets it to. */
private static final class RecordingOwner implements SparkConnectServers.Owner {
final List<String> events = new CopyOnWriteArrayList<>();
volatile Supplier<String> refusal = () -> null;
volatile Runnable idleWait = () -> { };
volatile boolean stoppedFails;
private volatile boolean answered;
@Override
public void running(String sessionId) {
}
@Override
public void answering(String sessionId) {
answered = true;
events.add("answering");
}
@Override
public void silent(String sessionId, String why) {
events.add("silent");
}
@Override
public void stopped(String sessionId, SparkJobRunner.Outcome outcome) {
if (stoppedFails) {
throw new IllegalStateException("could not store the session");
}
events.add("stopped");
}
@Override
public boolean starting(String sessionId) {
return !answered;
}
@Override
public boolean going(String sessionId) {
return true;
}
@Override
public String refusal(String sessionId) {
return refusal.get();
}
@Override
public void busy(String sessionId) {
events.add("busy");
}
@Override
public void idle(String sessionId) {
idleWait.run();
events.add("idle");
}
@Override
public void gone(String sessionId) {
events.add("gone");
}
}
/** Runs a server until it is stopped, listening at once. */
private static final class ServerRunner implements SparkJobRunner {
private final CompletableFuture<Outcome> end = new CompletableFuture<>();
@Override
public Outcome run(Job job, Progress progress) {
progress.started();
progress.listening("127.0.0.1", 15002);
return end.join();
}
@Override
public void stop(String runId) {
end.complete(Outcome.halted());
}
@Override
public void removeLeftoverDrivers(String service) {
}
}
}