mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(emr-serverless): run a session's Spark Connect server in the docker runner mode (#8731)
With runner-mode docker, StartSession now runs the session's driver, a Spark Connect server, in a container, as a job run's driver runs: in the release's image or the application's custom image, on the same network, with the execution role's credentials and the application's executors. Its spark-defaults are the application's runtime configuration, then the session's runtimeConfiguration; Floci sets the server's port and drops a spark.connect.grpc.binding.address, which "is reserved by EMR Serverless and cannot be overridden by users". A client reaches the server through Floci. GetSessionEndpoint answers Floci's own address, and the client puts the token in the x-aws-proxy-auth parameter, as AWS's connection string does (sc://<host>:443/;use_ssl=true;x-aws-proxy-auth=<token>). The new core.common.SparkConnectProxy takes gRPC calls to spark.connect.SparkConnectService on Floci's port, checks the token, and forwards each call over HTTP/2, trailers included, to the server, whose port is published on the Docker host's loopback interface only; a Trailers-Only answer, Spark's error before any message, goes back as one. A call with no token, an unknown one or an expired one fails with gRPC's UNAUTHENTICATED; one to a session that is not ready, or in the immediate mode, with UNAVAILABLE. The session is SUBMITTED until its container runs, STARTING until the server answers, then IDLE. No source says when a session is BUSY: Floci makes it BUSY while a call runs on its server and IDLE again once none does, its idle timeout counting from then. TerminateSession goes through TERMINATING until the container has stopped; the idle timeout, the 24 hours (counted from when the server answers) and StopApplication stop it too, each session keeping one check for its next deadline. A server that exits on its own, or does not answer within 10 minutes, fails the session with the reason; one a restart left behind fails as interrupted, and its container, if the startup's cleanup left it, is removed. The runner's Job gains a listening port, published on loopback and reported through Progress.listening once the container runs. EmrServerlessSparkConnectNightlyIntegrationTest runs it for real: the server in the emr-7.13.0 image and Spark's own JVM Spark Connect client from that image, which runs a query through Floci with the token and is refused with a wrong one. The nightly job's timeout and image prefetch take the new check.
This commit is contained in:
1 parent
93c1d39348
commit
50276fa533
17 files changed
+1840
-64
No files matched your search
@@ -0,0 +1,207 @@
|
||||
package io.floci.aws.core.common;
|
||||
|
||||
import io.vertx.core.Future;
|
||||
import io.vertx.core.MultiMap;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.buffer.Buffer;
|
||||
import io.vertx.core.http.HttpClient;
|
||||
import io.vertx.core.http.HttpClientOptions;
|
||||
import io.vertx.core.http.HttpMethod;
|
||||
import io.vertx.core.http.HttpServer;
|
||||
import io.vertx.core.http.HttpVersion;
|
||||
import io.vertx.core.http.RequestOptions;
|
||||
import io.vertx.ext.web.Router;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Spark Connect calls through {@link SparkConnectProxy}, over HTTP/2 from the first byte as gRPC's are: a server of
|
||||
* gRPC's shape stands in for a session's Spark Connect server, and a service's routes for its tokens.
|
||||
*/
|
||||
class SparkConnectProxyTest {
|
||||
|
||||
private static final String PATH = "/spark.connect.SparkConnectService/ExecutePlan";
|
||||
private static final String TOKEN = "a-session-token";
|
||||
|
||||
private final Map<String, SparkConnectTargets.Route> routes = new ConcurrentHashMap<>();
|
||||
private final AtomicInteger callsEnded = new AtomicInteger();
|
||||
private final AtomicReference<MultiMap> serverSaw = new AtomicReference<>();
|
||||
private Vertx vertx;
|
||||
private SparkConnectProxy proxy;
|
||||
private HttpServer floci;
|
||||
private HttpServer sparkConnect;
|
||||
private HttpClient client;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
vertx = Vertx.vertx();
|
||||
// A server of gRPC's shape: it answers a call with the message it was sent, then status 0 in its trailers.
|
||||
sparkConnect = await(vertx.createHttpServer().requestHandler(request -> request.body().onSuccess(body -> {
|
||||
serverSaw.set(MultiMap.caseInsensitiveMultiMap().addAll(request.headers()));
|
||||
request.response().putHeader("content-type", "application/grpc").write(body);
|
||||
request.response().trailers().add("grpc-status", "0");
|
||||
request.response().end();
|
||||
})).listen(0, "127.0.0.1"));
|
||||
@SuppressWarnings("unchecked")
|
||||
Instance<SparkConnectTargets> targets = mock(Instance.class);
|
||||
SparkConnectTargets service = token -> Optional.ofNullable(routes.get(token));
|
||||
when(targets.iterator()).thenAnswer(invocation -> List.of(service).iterator());
|
||||
proxy = new SparkConnectProxy(targets, vertx);
|
||||
Router router = Router.router(vertx);
|
||||
proxy.register(router);
|
||||
router.route().handler(context -> context.response().setStatusCode(404).end("not Spark Connect"));
|
||||
floci = await(vertx.createHttpServer().requestHandler(router).listen(0, "127.0.0.1"));
|
||||
client = vertx.createHttpClient(new HttpClientOptions().setProtocolVersion(HttpVersion.HTTP_2)
|
||||
.setHttp2ClearTextUpgrade(false));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
await(vertx.close());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCallWithItsSessionsTokenGoesToTheServerAndItsAnswerAndTrailersComeBack() throws Exception {
|
||||
routes.put(TOKEN, SparkConnectTargets.Route.to("127.0.0.1", sparkConnect.actualPort(),
|
||||
callsEnded::incrementAndGet));
|
||||
|
||||
Answer answer = call(TOKEN, "a message");
|
||||
|
||||
assertEquals(200, answer.status);
|
||||
assertEquals("a message", answer.body);
|
||||
assertEquals("application/grpc", answer.headers.get("content-type"));
|
||||
assertEquals("0", answer.trailers.get("grpc-status"));
|
||||
// The token is Floci's to check, so the server never sees it.
|
||||
assertNull(serverSaw.get().get(SparkConnectProxy.TOKEN_METADATA));
|
||||
assertEquals("trailers", serverSaw.get().get("te"));
|
||||
assertNull(serverSaw.get().get("transfer-encoding"));
|
||||
awaitCount(callsEnded, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCallWithNoTokenOrOneNoServiceGaveIsUnauthenticated() throws Exception {
|
||||
Answer none = call(null, "a message");
|
||||
Answer unknown = call("not-a-token", "a message");
|
||||
|
||||
assertEquals("16", none.headers.get("grpc-status"));
|
||||
assertEquals(SparkConnectProxy.NO_TOKEN, none.headers.get("grpc-message"));
|
||||
assertEquals("16", unknown.headers.get("grpc-status"));
|
||||
assertEquals(SparkConnectProxy.UNKNOWN_TOKEN, unknown.headers.get("grpc-message"));
|
||||
assertEquals("", unknown.body);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCallTheServiceRefusesEndsWithItsStatusAndOneToAServerNotThereIsUnavailable() throws Exception {
|
||||
routes.put(TOKEN, SparkConnectTargets.Route.refused(SparkConnectTargets.Route.UNAVAILABLE, "Not 100% ready"));
|
||||
Answer refused = call(TOKEN, "a message");
|
||||
int closedPort = sparkConnect.actualPort();
|
||||
await(sparkConnect.close());
|
||||
routes.put(TOKEN, SparkConnectTargets.Route.to("127.0.0.1", closedPort, callsEnded::incrementAndGet));
|
||||
Answer unreachable = call(TOKEN, "a message");
|
||||
|
||||
assertEquals("14", refused.headers.get("grpc-status"));
|
||||
// gRPC's grpc-message percent-encodes a '%'.
|
||||
assertEquals("Not 100%25 ready", refused.headers.get("grpc-message"));
|
||||
assertEquals("14", unreachable.headers.get("grpc-status"));
|
||||
assertTrue(unreachable.headers.get("grpc-message").startsWith("The session's Spark Connect server could not"));
|
||||
awaitCount(callsEnded, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRequestThatIsNotASparkConnectCallGoesOnToFlocisOtherRoutes() throws Exception {
|
||||
RequestOptions options = new RequestOptions().setMethod(HttpMethod.POST).setHost("127.0.0.1")
|
||||
.setPort(floci.actualPort()).setURI("/2021-07-13/applications")
|
||||
.putHeader("content-type", "application/json");
|
||||
Answer answer = send(options, "{}");
|
||||
|
||||
assertEquals(404, answer.status);
|
||||
assertEquals("not Spark Connect", answer.body);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aServerAnswersOnceItsGrpcServerRunsAndAClosedPortSaysWhyNot() throws Exception {
|
||||
assertNull(await(proxy.unanswered("127.0.0.1", sparkConnect.actualPort())));
|
||||
int closedPort = sparkConnect.actualPort();
|
||||
await(sparkConnect.close());
|
||||
|
||||
String why = await(proxy.unanswered("127.0.0.1", closedPort));
|
||||
assertTrue(why != null && !why.isEmpty(), String.valueOf(why));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aServersErrorAnsweredTrailersOnlyReachesTheClientAndEndsTheCall() throws Exception {
|
||||
// As grpc-java answers an error raised before any message: its status in its only headers.
|
||||
HttpServer failing = await(vertx.createHttpServer().requestHandler(request -> request.body().onSuccess(body ->
|
||||
request.response().putHeader("content-type", "application/grpc").putHeader("grpc-status", "3")
|
||||
.putHeader("grpc-message", "TABLE_OR_VIEW_NOT_FOUND").end()))
|
||||
.listen(0, "127.0.0.1"));
|
||||
routes.put(TOKEN, SparkConnectTargets.Route.to("127.0.0.1", failing.actualPort(),
|
||||
callsEnded::incrementAndGet));
|
||||
|
||||
Answer answer = call(TOKEN, "a message");
|
||||
|
||||
assertEquals("3", answer.headers.get("grpc-status") != null ? answer.headers.get("grpc-status")
|
||||
: answer.trailers.get("grpc-status"));
|
||||
assertEquals("", answer.body);
|
||||
awaitCount(callsEnded, 1);
|
||||
}
|
||||
|
||||
private Answer call(String token, String message) throws Exception {
|
||||
RequestOptions options = new RequestOptions().setMethod(HttpMethod.POST).setHost("127.0.0.1")
|
||||
.setPort(floci.actualPort()).setURI(PATH)
|
||||
.putHeader("content-type", "application/grpc")
|
||||
.putHeader("te", "trailers");
|
||||
if (token != null) {
|
||||
options.putHeader(SparkConnectProxy.TOKEN_METADATA, token);
|
||||
}
|
||||
// As a gRPC client sends a call: its message streamed, with no Content-Length.
|
||||
return await(client.request(options)
|
||||
.compose(request -> {
|
||||
request.setChunked(true);
|
||||
request.write(Buffer.buffer(message));
|
||||
return request.end().compose(ended -> request.response());
|
||||
})
|
||||
.compose(response -> response.body().map(received -> new Answer(response.statusCode(),
|
||||
response.headers(), received.toString(), response.trailers()))));
|
||||
}
|
||||
|
||||
private Answer send(RequestOptions options, String body) throws Exception {
|
||||
return await(client.request(options)
|
||||
.compose(request -> request.send(Buffer.buffer(body)))
|
||||
.compose(response -> response.body().map(received -> new Answer(response.statusCode(),
|
||||
response.headers(), received.toString(), response.trailers()))));
|
||||
}
|
||||
|
||||
private static void awaitCount(AtomicInteger count, int expected) throws InterruptedException {
|
||||
CountDownLatch never = new CountDownLatch(1);
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
|
||||
while (count.get() < expected && System.nanoTime() - deadline < 0) {
|
||||
never.await(10, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
assertEquals(expected, count.get());
|
||||
}
|
||||
|
||||
private static <T> T await(Future<T> future) throws Exception {
|
||||
return future.toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
private record Answer(int status, MultiMap headers, String body, MultiMap trailers) {
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -17,7 +17,6 @@ import static io.floci.aws.testing.EmrServerlessRequests.emrServerless;
|
||||
import static io.floci.aws.testing.EmrServerlessRequests.tagsPath;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.endsWith;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.hamcrest.Matchers.matchesPattern;
|
||||
@@ -88,7 +87,7 @@ class EmrServerlessSessionIntegrationTest {
|
||||
.then().statusCode(200)
|
||||
.body("applicationId", equalTo(applicationId))
|
||||
.body("sessionId", equalTo(sessionId))
|
||||
.body("endpoint", endsWith("/_aws/emr-serverless/sessions/" + applicationId + "/" + sessionId))
|
||||
.body("endpoint", matchesPattern("https?://[^/]+"))
|
||||
.body("authToken", matchesPattern("[0-9a-f]{64}"))
|
||||
.body("authTokenExpiresAt", notNullValue());
|
||||
|
||||
|
||||
+368
@@ -0,0 +1,368 @@
|
||||
package io.floci.aws.services.emrserverless;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.SparkConnectTargets;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.services.emrserverless.model.CreateApplicationRequest;
|
||||
import io.floci.aws.services.emrserverless.model.InteractiveConfiguration;
|
||||
import io.floci.aws.services.emrserverless.model.Session;
|
||||
import io.floci.aws.services.emrserverless.model.SessionRecord;
|
||||
import io.floci.aws.services.emrserverless.model.StartSessionRequest;
|
||||
import io.floci.aws.services.iam.IamService;
|
||||
import io.floci.aws.testing.InMemoryStorageFactory;
|
||||
import io.floci.aws.testing.MutableClock;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ScheduledThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.locks.LockSupport;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* EMR Serverless sessions in the docker runner mode, each running a Spark Connect server through the runner: the
|
||||
* session's states as its server starts, answers, takes calls and stops, with a runner that stands in for Docker.
|
||||
*/
|
||||
class EmrServerlessSessionServerTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ACCOUNT_ID = "000000000000";
|
||||
private static final String ROLE = "arn:aws:iam::000000000000:role/emr-serverless-session";
|
||||
private static final String SERVER_HOST = "127.0.0.1";
|
||||
private static final int SERVER_PORT = 40123;
|
||||
|
||||
private final ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule());
|
||||
private final AccountAwareStorageBackend<SessionRecord> store = AccountAwareStorageBackend.inMemory(ACCOUNT_ID);
|
||||
private final FakeServerRunner runner = new FakeServerRunner();
|
||||
private final AtomicBoolean answering = new AtomicBoolean(true);
|
||||
private final Executor threads = task -> Thread.ofPlatform().daemon().start(task);
|
||||
private EmrServerlessService applications;
|
||||
private EmrServerlessJobRunService jobRuns;
|
||||
private IamService iamService;
|
||||
private RegionResolver regionResolver;
|
||||
private EmrServerlessSessionService sessions;
|
||||
private MutableClock clock;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
when(config.defaultAccountId()).thenReturn(ACCOUNT_ID);
|
||||
clock = new MutableClock();
|
||||
regionResolver = new RegionResolver(REGION, ACCOUNT_ID);
|
||||
applications = new EmrServerlessService(config, new InMemoryStorageFactory(ACCOUNT_ID), regionResolver, clock);
|
||||
iamService = mock(IamService.class);
|
||||
when(iamService.resolveCallerArn(any())).thenReturn(Optional.empty());
|
||||
jobRuns = new EmrServerlessJobRunService(AccountAwareStorageBackend.inMemory(ACCOUNT_ID), applications,
|
||||
iamService, regionResolver, null, objectMapper, 0, clock, runner, Runnable::run);
|
||||
sessions = service();
|
||||
}
|
||||
|
||||
private EmrServerlessSessionService service() {
|
||||
return service(null);
|
||||
}
|
||||
|
||||
private EmrServerlessSessionService service(ScheduledThreadPoolExecutor checks) {
|
||||
return new EmrServerlessSessionService(store, applications, jobRuns, iamService, regionResolver, null,
|
||||
objectMapper, clock, "http://localhost:4566", runner, threads, checks,
|
||||
(host, port) -> answering.get() && SERVER_HOST.equals(host) && port == SERVER_PORT ? null
|
||||
: "Connection refused");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSessionRunsItsServerAndIsIdleOnceTheServerAnswers() {
|
||||
String applicationId = application("emr-7.13.0");
|
||||
StartSessionRequest request = request();
|
||||
request.setConfigurationOverrides(Map.of("runtimeConfiguration", List.of(Map.of(
|
||||
"classification", "spark-defaults",
|
||||
"properties", Map.of("spark.driver.memory", "2g", "spark.connect.grpc.binding.address", "10.0.0.1")))));
|
||||
|
||||
Session started = sessions.startSession(applicationId, request);
|
||||
Session idle = awaitState(applicationId, started.getSessionId(), "IDLE");
|
||||
|
||||
assertEquals("SUBMITTED", started.getState());
|
||||
assertNull(started.getStartedAt());
|
||||
assertNotNull(idle.getStartedAt());
|
||||
assertEquals(idle.getStartedAt(), idle.getIdleSince());
|
||||
SparkJobRunner.Job job = runner.jobs.get(started.getSessionId());
|
||||
assertEquals(EmrServerlessSessionService.SPARK_CONNECT_PORT, job.listenPort());
|
||||
assertEquals(List.of("--class", "org.apache.spark.sql.connect.service.SparkConnectServer",
|
||||
EmrServerlessJobRunService.SPARK_CONNECT_JAR), job.application());
|
||||
assertEquals("15002", job.sparkDefaults().get("spark.connect.grpc.binding.port"));
|
||||
assertEquals("2g", job.sparkDefaults().get("spark.driver.memory"));
|
||||
// "spark.connect.grpc.binding.address is reserved by EMR Serverless and cannot be overridden by users."
|
||||
assertFalse(job.sparkDefaults().containsKey("spark.connect.grpc.binding.address"));
|
||||
assertEquals(ROLE, job.executionRole());
|
||||
// The session's 24 hours count from when its server answers, so the runner keeps no clock of its own.
|
||||
assertEquals(Duration.ZERO, job.timeout());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSessionsTwentyFourHoursCountFromWhenItsServerAnswers() {
|
||||
String applicationId = application("emr-7.13.0");
|
||||
StartSessionRequest request = request();
|
||||
request.setIdleTimeoutMinutes(0L);
|
||||
String sessionId = sessions.startSession(applicationId, request).getSessionId();
|
||||
Session idle = awaitState(applicationId, sessionId, "IDLE");
|
||||
|
||||
clock.advance(Duration.between(clock.instant(), idle.getStartedAt().plus(Duration.ofHours(24)))
|
||||
.minusSeconds(1));
|
||||
assertEquals("IDLE", sessions.getSession(applicationId, sessionId).getState());
|
||||
clock.advance(Duration.ofSeconds(1));
|
||||
Session ended = sessions.getSession(applicationId, sessionId);
|
||||
|
||||
assertEquals("TERMINATED", ended.getState());
|
||||
assertEquals(EmrServerlessSessionService.HARD_LIMIT_REACHED, ended.getStateDetails());
|
||||
assertEquals(idle.getStartedAt().plus(Duration.ofHours(24)), ended.getEndedAt());
|
||||
assertTrue(runner.stopped.contains(sessionId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSessionKeepsOneCheckForItsNextDeadlineHoweverManyCallsEnd() {
|
||||
ScheduledThreadPoolExecutor checks = new ScheduledThreadPoolExecutor(1);
|
||||
checks.setRemoveOnCancelPolicy(true);
|
||||
try {
|
||||
sessions = service(checks);
|
||||
String applicationId = application("emr-7.13.0");
|
||||
String sessionId = sessions.startSession(applicationId, request()).getSessionId();
|
||||
awaitState(applicationId, sessionId, "IDLE");
|
||||
String token = sessions.sessionEndpoint(applicationId, sessionId).authToken();
|
||||
|
||||
for (int call = 0; call < 20; call++) {
|
||||
sessions.route(token).orElseThrow().ended().run();
|
||||
}
|
||||
assertEquals(1, checks.getQueue().size());
|
||||
sessions.terminateSession(applicationId, sessionId);
|
||||
assertEquals(0, checks.getQueue().size());
|
||||
} finally {
|
||||
checks.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aServerThatCannotStartFailsItsSessionEvenWithNoMessage() {
|
||||
runner.launchFailure = new IllegalStateException();
|
||||
String applicationId = application("emr-7.13.0");
|
||||
String sessionId = sessions.startSession(applicationId, request()).getSessionId();
|
||||
|
||||
Session failed = awaitState(applicationId, sessionId, "FAILED");
|
||||
|
||||
assertEquals(String.format(EmrServerlessSessionService.SERVER_NOT_STARTED, "java.lang.IllegalStateException"),
|
||||
failed.getStateDetails());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theAwsRuntimeForApacheSparkStartsTheServerFromSparksOwnJars() {
|
||||
assertEquals(List.of("--class", "org.apache.spark.sql.connect.service.SparkConnectServer", "spark-internal"),
|
||||
EmrServerlessJobRunService.sparkConnectServer("emr-spark-8.0.0"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSessionIsStartingUntilItsServerAnswersAndRefusesCallsMeanwhile() {
|
||||
answering.set(false);
|
||||
String applicationId = application("emr-7.13.0");
|
||||
String sessionId = sessions.startSession(applicationId, request()).getSessionId();
|
||||
awaitState(applicationId, sessionId, "STARTING");
|
||||
String token = sessions.sessionEndpoint(applicationId, sessionId).authToken();
|
||||
|
||||
SparkConnectTargets.Route refused = sessions.route(token).orElseThrow();
|
||||
|
||||
assertEquals(SparkConnectTargets.Route.UNAVAILABLE, refused.status());
|
||||
assertEquals(String.format(EmrServerlessSessionService.NOT_READY, sessionId, "STARTING"), refused.refusal());
|
||||
answering.set(true);
|
||||
awaitState(applicationId, sessionId, "IDLE");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCallMakesTheSessionBusyUntilTheLastCallEnds() {
|
||||
String applicationId = application("emr-7.13.0");
|
||||
String sessionId = sessions.startSession(applicationId, request()).getSessionId();
|
||||
awaitState(applicationId, sessionId, "IDLE");
|
||||
String token = sessions.sessionEndpoint(applicationId, sessionId).authToken();
|
||||
|
||||
SparkConnectTargets.Route first = sessions.route(token).orElseThrow();
|
||||
SparkConnectTargets.Route second = sessions.route(token).orElseThrow();
|
||||
|
||||
assertNull(first.refusal());
|
||||
assertEquals(SERVER_HOST, first.host());
|
||||
assertEquals(SERVER_PORT, first.port());
|
||||
Session busy = sessions.getSession(applicationId, sessionId);
|
||||
assertEquals("BUSY", busy.getState());
|
||||
assertNull(busy.getIdleSince());
|
||||
first.ended().run();
|
||||
assertEquals("BUSY", sessions.getSession(applicationId, sessionId).getState());
|
||||
clock.advance(Duration.ofMinutes(5));
|
||||
Instant before = clock.instant().truncatedTo(ChronoUnit.MILLIS);
|
||||
second.ended().run();
|
||||
Instant after = clock.instant();
|
||||
Session idle = sessions.getSession(applicationId, sessionId);
|
||||
assertEquals("IDLE", idle.getState());
|
||||
// Idle from when the last call ended.
|
||||
assertFalse(idle.getIdleSince().isBefore(before));
|
||||
assertFalse(idle.getIdleSince().isAfter(after));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBusySessionDoesNotTimeOutAndAnIdleOneEndsItsServerAtItsIdleTimeout() {
|
||||
String applicationId = application("emr-7.13.0");
|
||||
StartSessionRequest request = request();
|
||||
request.setIdleTimeoutMinutes(30L);
|
||||
String sessionId = sessions.startSession(applicationId, request).getSessionId();
|
||||
awaitState(applicationId, sessionId, "IDLE");
|
||||
SparkConnectTargets.Route call = sessions.route(sessions.sessionEndpoint(applicationId, sessionId)
|
||||
.authToken()).orElseThrow();
|
||||
|
||||
clock.advance(Duration.ofMinutes(45));
|
||||
assertEquals("BUSY", sessions.getSession(applicationId, sessionId).getState());
|
||||
call.ended().run();
|
||||
clock.advance(Duration.ofMinutes(30));
|
||||
Session ended = sessions.getSession(applicationId, sessionId);
|
||||
|
||||
assertEquals("TERMINATED", ended.getState());
|
||||
assertEquals(EmrServerlessSessionService.IDLE_TIMED_OUT, ended.getStateDetails());
|
||||
assertTrue(runner.stopped.contains(sessionId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTerminatedSessionIsTerminatingUntilItsServerStopsAndItsTokensGo() {
|
||||
String applicationId = application("emr-7.13.0");
|
||||
String sessionId = sessions.startSession(applicationId, request()).getSessionId();
|
||||
awaitState(applicationId, sessionId, "IDLE");
|
||||
String token = sessions.sessionEndpoint(applicationId, sessionId).authToken();
|
||||
|
||||
Session terminating = sessions.terminateSession(applicationId, sessionId);
|
||||
Session terminated = awaitState(applicationId, sessionId, "TERMINATED");
|
||||
|
||||
assertEquals("TERMINATING", terminating.getState());
|
||||
assertTrue(runner.stopped.contains(sessionId));
|
||||
assertNotNull(terminated.getEndedAt());
|
||||
assertTrue(sessions.route(token).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSessionWhoseServerExitsOnItsOwnHasFailed() {
|
||||
String applicationId = application("emr-7.13.0");
|
||||
String sessionId = sessions.startSession(applicationId, request()).getSessionId();
|
||||
awaitState(applicationId, sessionId, "IDLE");
|
||||
|
||||
runner.end(sessionId).complete(SparkJobRunner.Outcome.exitedWith(1));
|
||||
Session failed = awaitState(applicationId, sessionId, "FAILED");
|
||||
|
||||
assertEquals(String.format(EmrServerlessSessionService.SERVER_EXITED, 1), failed.getStateDetails());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSessionWhoseServerNoThreadRunsAnyMoreWasInterruptedByARestart() {
|
||||
String applicationId = application("emr-7.13.0");
|
||||
String sessionId = sessions.startSession(applicationId, request()).getSessionId();
|
||||
awaitState(applicationId, sessionId, "IDLE");
|
||||
|
||||
// A new process: the stored session is there, but no thread of it runs the session's server.
|
||||
Session after = service().getSession(applicationId, sessionId);
|
||||
|
||||
assertEquals("FAILED", after.getState());
|
||||
assertEquals(EmrServerlessSessionService.INTERRUPTED, after.getStateDetails());
|
||||
// Its server's container, should the startup's cleanup have left it, goes too.
|
||||
assertEquals(List.of(sessionId), runner.leftoversRemoved);
|
||||
}
|
||||
|
||||
// Polls until the session is in state, as its server's thread moves it on its own.
|
||||
private Session awaitState(String applicationId, String sessionId, String state) {
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
|
||||
while (true) {
|
||||
Session session = sessions.getSession(applicationId, sessionId);
|
||||
if (state.equals(session.getState())) {
|
||||
return session;
|
||||
}
|
||||
if (System.nanoTime() - deadline > 0) {
|
||||
fail("Session " + sessionId + " is " + session.getState() + ", not " + state);
|
||||
}
|
||||
LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10));
|
||||
}
|
||||
}
|
||||
|
||||
private static StartSessionRequest request() {
|
||||
StartSessionRequest request = new StartSessionRequest();
|
||||
request.setClientToken(UUID.randomUUID().toString());
|
||||
request.setExecutionRoleArn(ROLE);
|
||||
return request;
|
||||
}
|
||||
|
||||
private String application(String releaseLabel) {
|
||||
CreateApplicationRequest create = new CreateApplicationRequest();
|
||||
create.setName("sessions");
|
||||
create.setReleaseLabel(releaseLabel);
|
||||
create.setType("SPARK");
|
||||
create.setClientToken(UUID.randomUUID().toString());
|
||||
InteractiveConfiguration interactive = new InteractiveConfiguration();
|
||||
interactive.setProperty("sessionEnabled", true);
|
||||
create.setInteractiveConfiguration(interactive);
|
||||
return applications.createApplication(create).getApplicationId();
|
||||
}
|
||||
|
||||
/** Runs each session's server as the Docker runner would, until it is stopped or told how it ends. */
|
||||
private static final class FakeServerRunner implements SparkJobRunner {
|
||||
final Map<String, Job> jobs = new ConcurrentHashMap<>();
|
||||
final Set<String> stopped = ConcurrentHashMap.newKeySet();
|
||||
final List<String> leftoversRemoved = new CopyOnWriteArrayList<>();
|
||||
volatile RuntimeException launchFailure;
|
||||
private final Map<String, CompletableFuture<Outcome>> ends = new ConcurrentHashMap<>();
|
||||
|
||||
@Override
|
||||
public Outcome run(Job job, Progress progress) {
|
||||
jobs.put(job.runId(), job);
|
||||
if (launchFailure != null) {
|
||||
throw launchFailure;
|
||||
}
|
||||
if (progress.cancelled()) {
|
||||
return Outcome.halted();
|
||||
}
|
||||
progress.started();
|
||||
progress.listening(SERVER_HOST, SERVER_PORT);
|
||||
return end(job.runId()).join();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop(String runId) {
|
||||
stopped.add(runId);
|
||||
end(runId).complete(Outcome.halted());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeLeftoverDrivers(String service) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeLeftoverDriver(String service, String runId) {
|
||||
leftoversRemoved.add(runId);
|
||||
}
|
||||
|
||||
CompletableFuture<Outcome> end(String runId) {
|
||||
return ends.computeIfAbsent(runId, id -> new CompletableFuture<>());
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
-2
@@ -6,6 +6,7 @@ import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.SparkConnectEndpoint;
|
||||
import io.floci.aws.core.common.SparkConnectTargets;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.services.emrserverless.model.AutoStartConfiguration;
|
||||
import io.floci.aws.services.emrserverless.model.CreateApplicationRequest;
|
||||
@@ -240,14 +241,29 @@ class EmrServerlessSessionServiceTest {
|
||||
|
||||
SparkConnectEndpoint endpoint = sessions.sessionEndpoint(applicationId, sessionId);
|
||||
|
||||
assertEquals("http://localhost:4566/_aws/emr-serverless/sessions/" + applicationId + "/" + sessionId,
|
||||
endpoint.url());
|
||||
// Spark Connect's sc:// URL holds no path, so the endpoint is Floci's address and the token names the session.
|
||||
assertEquals("http://localhost:4566", endpoint.url());
|
||||
assertEquals(64, endpoint.authToken().length());
|
||||
assertTrue(Duration.between(clock.instant(), endpoint.authTokenExpiresAt()).compareTo(Duration.ofMinutes(59))
|
||||
> 0);
|
||||
assertNotEquals(endpoint.authToken(), sessions.sessionEndpoint(applicationId, sessionId).authToken());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCallToASessionWithNoServerIsRefusedAsUnavailableAndAnUnknownTokenNamesNone() {
|
||||
String applicationId = application("emr-7.13.0", "SPARK", true);
|
||||
String sessionId = sessions.startSession(applicationId, request()).getSessionId();
|
||||
String token = sessions.sessionEndpoint(applicationId, sessionId).authToken();
|
||||
|
||||
SparkConnectTargets.Route route = sessions.route(token).orElseThrow();
|
||||
|
||||
assertEquals(SparkConnectTargets.Route.UNAVAILABLE, route.status());
|
||||
assertEquals(String.format(EmrServerlessSessionService.NO_SERVER, sessionId), route.refusal());
|
||||
assertTrue(sessions.route("not-a-token").isEmpty());
|
||||
clock.advance(EmrServerlessSessionService.TOKEN_VALIDITY);
|
||||
assertEquals(EmrServerlessSessionService.TOKEN_EXPIRED, sessions.route(token).orElseThrow().refusal());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listSessionsFiltersByStateAndGroupsByTheFiltersOrder() {
|
||||
String applicationId = application("emr-7.13.0", "SPARK", true);
|
||||
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
package io.floci.aws.services.emrserverless;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.docker.ContainerBuilder;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.core.common.docker.ContainerReachableEndpoint;
|
||||
import io.floci.aws.core.common.docker.ContainerSpec;
|
||||
import io.floci.aws.core.common.docker.ContainerStorageHelper;
|
||||
import io.floci.aws.testing.DockerAvailability;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.Response;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
import java.net.URI;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.locks.LockSupport;
|
||||
|
||||
import static io.floci.aws.testing.EmrServerlessRequests.deleteApplication;
|
||||
import static io.floci.aws.testing.EmrServerlessRequests.emrServerless;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
/**
|
||||
* An EMR Serverless session run for real: its Spark Connect server runs in the release's image, and a Spark Connect
|
||||
* client, Spark's own JVM client from the same image, reaches it through Floci at the endpoint GetSessionEndpoint
|
||||
* gives, with the token in its {@code x-aws-proxy-auth} parameter as EMR Serverless's connection string puts it. A
|
||||
* wrong token is refused, queries run, a query's Spark error comes back as Spark's, and TerminateSession stops the
|
||||
* server.
|
||||
*
|
||||
* <p>A nightly check: the release's image is 3.7 GB, and the server and the client each start a JVM.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(EmrServerlessSparkConnectNightlyIntegrationTest.Profile.class)
|
||||
@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true")
|
||||
// Bounded waits: the image's pull of up to twenty minutes, then the server's start, the client's run and the session's
|
||||
// end, a few minutes; the Nightly checks job's timeout counts the 30.
|
||||
@Timeout(value = 30, unit = TimeUnit.MINUTES)
|
||||
class EmrServerlessSparkConnectNightlyIntegrationTest {
|
||||
|
||||
/** Sessions run their servers in containers, and Floci listens on a fixed port, the one its endpoint names. */
|
||||
public static final class Profile implements QuarkusTestProfile {
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of(
|
||||
"floci.services.emrserverless.runner-mode", "docker",
|
||||
"quarkus.http.test-port", String.valueOf(PORT),
|
||||
"floci.port", String.valueOf(PORT),
|
||||
"floci.base-url", "http://localhost:" + PORT);
|
||||
}
|
||||
}
|
||||
|
||||
private static final int PORT = 4597;
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String RELEASE = "emr-7.13.0";
|
||||
private static final String IMAGE = "public.ecr.aws/emr-serverless/spark/emr-7.13.0:latest";
|
||||
private static final String ROLE = "arn:aws:iam::000000000000:role/emr-serverless-session";
|
||||
// Spark's JVM Spark Connect client, which the release's image carries, compiled and run against the URLs it is
|
||||
// given: the refused one first, then the session's.
|
||||
private static final String CLIENT = """
|
||||
set -e
|
||||
mkdir -p /tmp/client && cd /tmp/client && cat > Probe.java <<'JAVA'
|
||||
import org.apache.spark.sql.SparkSession;
|
||||
public class Probe {
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
SparkSession.builder().remote(args[1]).create().range(1).count();
|
||||
System.out.println("REFUSED=none");
|
||||
} catch (Exception e) {
|
||||
System.out.println("REFUSED=" + e.getMessage());
|
||||
}
|
||||
SparkSession spark = SparkSession.builder().remote(args[0]).create();
|
||||
System.out.println("COUNT=" + spark.range(10).count());
|
||||
Object sum = spark.sql("SELECT sum(id) FROM range(5)").collectAsList().get(0).get(0);
|
||||
System.out.println("SUM=" + sum);
|
||||
try {
|
||||
spark.sql("SELECT * FROM no_such_table").collectAsList();
|
||||
System.out.println("ERROR=none");
|
||||
} catch (Exception e) {
|
||||
System.out.println("ERROR=" + e.getMessage());
|
||||
}
|
||||
spark.close();
|
||||
}
|
||||
}
|
||||
JAVA
|
||||
# The client's own jar first, then Spark's, less those whose classes it replaces.
|
||||
classpath=/usr/lib/spark/connector/lib/spark-connect-client-jvm.jar
|
||||
for jar in /usr/lib/spark/jars/*.jar; do
|
||||
case $(basename "$jar") in
|
||||
spark-sql_*|spark-catalyst_*|spark-hive*|spark-core_*) ;;
|
||||
*) classpath=$classpath:$jar ;;
|
||||
esac
|
||||
done
|
||||
javac -cp "$classpath" Probe.java
|
||||
# Arrow, which the client reads answers with, needs java.nio opened.
|
||||
exec java --add-opens=java.base/java.nio=ALL-UNNAMED -cp ".:$classpath" Probe "$@"
|
||||
""";
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@Inject
|
||||
DockerClient docker;
|
||||
|
||||
@Inject
|
||||
ContainerBuilder containerBuilder;
|
||||
|
||||
@Inject
|
||||
ContainerLifecycleManager lifecycleManager;
|
||||
|
||||
@Inject
|
||||
ContainerReachableEndpoint reachableEndpoint;
|
||||
|
||||
@Inject
|
||||
EmulatorConfig config;
|
||||
|
||||
@BeforeAll
|
||||
static void configure() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClientRunsAQueryOnTheSessionsServerThroughFlociWithItsToken() throws InterruptedException {
|
||||
// Enabled, the check needs Docker: without a daemon it fails rather than pass having run nothing.
|
||||
assertTrue(DockerAvailability.isAvailable(), "the nightly check needs a Docker daemon");
|
||||
String applicationId = emrServerless(REGION).body("""
|
||||
{"name": "spark-connect", "releaseLabel": "%s", "type": "SPARK", "clientToken": "%s",
|
||||
"interactiveConfiguration": {"sessionEnabled": true}}
|
||||
""".formatted(RELEASE, UUID.randomUUID()))
|
||||
.when().post("/applications")
|
||||
.then().statusCode(200).extract().path("applicationId");
|
||||
cleanup.register(() -> deleteApplication(REGION, applicationId));
|
||||
String sessionId = emrServerless(REGION).body("""
|
||||
{"clientToken": "%s", "executionRoleArn": "%s", "idleTimeoutMinutes": 30}
|
||||
""".formatted(UUID.randomUUID(), ROLE))
|
||||
.when().post("/applications/" + applicationId + "/sessions")
|
||||
.then().statusCode(200).extract().path("sessionId");
|
||||
cleanup.register(() -> emrServerless(REGION).when()
|
||||
.delete("/applications/" + applicationId + "/sessions/" + sessionId));
|
||||
|
||||
awaitState(applicationId, sessionId, "IDLE", Duration.ofMinutes(22));
|
||||
Response endpoint = emrServerless(REGION).when()
|
||||
.get("/applications/" + applicationId + "/sessions/" + sessionId + "/endpoint")
|
||||
.then().statusCode(200).extract().response();
|
||||
assertEquals("http://localhost:" + PORT, endpoint.path("endpoint"));
|
||||
// Floci's address as a container reaches it, where the test's endpoint names the host's loopback.
|
||||
URI floci = URI.create(reachableEndpoint.baseUrl(false));
|
||||
String connect = "sc://" + floci.getHost() + ":" + floci.getPort() + "/;x-aws-proxy-auth=";
|
||||
String output = runClient(connect + endpoint.path("authToken"), connect + "not-the-token");
|
||||
|
||||
assertTrue(output.contains("REFUSED=") && output.contains("UNAUTHENTICATED"), output);
|
||||
assertTrue(output.contains("COUNT=10"), output);
|
||||
assertTrue(output.contains("SUM=10"), output);
|
||||
// Spark's own error, which its server answers before any message, reaches the client through Floci.
|
||||
assertTrue(output.contains("ERROR=") && output.contains("TABLE_OR_VIEW_NOT_FOUND"), output);
|
||||
assertEquals("IDLE", session(applicationId, sessionId).path("session.state"));
|
||||
|
||||
emrServerless(REGION).when().delete("/applications/" + applicationId + "/sessions/" + sessionId)
|
||||
.then().statusCode(200);
|
||||
awaitState(applicationId, sessionId, "TERMINATED", Duration.ofMinutes(2));
|
||||
String server = ContainerStorageHelper.dockerName(config, "emr-serverless-" + sessionId);
|
||||
assertTrue(lifecycleManager.findByName(server).isEmpty(), "the session's server is still there");
|
||||
}
|
||||
|
||||
// Runs the client in a container of the release's image, as far as Floci's address, and returns its output.
|
||||
private String runClient(String sessionUrl, String refusedUrl) throws InterruptedException {
|
||||
ContainerSpec spec = containerBuilder.newContainer(IMAGE)
|
||||
.withName("floci-spark-connect-client-" + UUID.randomUUID().toString().substring(0, 8))
|
||||
.withEntrypoint(List.of("/bin/bash", "-c", CLIENT, "floci", sessionUrl, refusedUrl))
|
||||
.withHostDockerInternalOnLinux()
|
||||
.withMemoryMb(1536)
|
||||
.build();
|
||||
String containerId = lifecycleManager.create(spec);
|
||||
try {
|
||||
lifecycleManager.startCreated(containerId, spec);
|
||||
int exitCode = docker.waitContainerCmd(containerId).start().awaitStatusCode(5, TimeUnit.MINUTES);
|
||||
String output = lifecycleManager.lastLogLines(containerId, 200, Duration.ofSeconds(30));
|
||||
assertEquals(0, exitCode, output);
|
||||
return output;
|
||||
} finally {
|
||||
lifecycleManager.stopAndRemove(containerId, null, 1);
|
||||
}
|
||||
}
|
||||
|
||||
private void awaitState(String applicationId, String sessionId, String state, Duration limit) {
|
||||
long deadline = System.nanoTime() + limit.toNanos();
|
||||
while (true) {
|
||||
Response session = session(applicationId, sessionId);
|
||||
String now = session.path("session.state");
|
||||
if (state.equals(now)) {
|
||||
return;
|
||||
}
|
||||
if (List.of("FAILED", "TERMINATED").contains(now) || System.nanoTime() - deadline > 0) {
|
||||
fail("Session " + sessionId + " is " + now + ", not " + state + ": "
|
||||
+ session.path("session.stateDetails"));
|
||||
}
|
||||
LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(2));
|
||||
}
|
||||
}
|
||||
|
||||
private static Response session(String applicationId, String sessionId) {
|
||||
return emrServerless(REGION).when().get("/applications/" + applicationId + "/sessions/" + sessionId)
|
||||
.then().statusCode(200).extract().response();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user