feat(emr-containers): run a managed endpoint's Jupyter Enterprise Gateway (#9232)

An EMR on EKS managed endpoint ran nothing: it was ACTIVE at once with no
serverUrl, so no Jupyter client could start a kernel on it, and its
session tokens opened nothing.

- With runner-mode docker, an endpoint runs a Jupyter Enterprise Gateway,
  which "provides the remote kernel lifecycle management capability that
  interactive clients need", in a container of its release's
  notebook-spark image on Amazon ECR Public, the base image of
  interactive endpoints. That image holds jupyter_server and ipykernel but
  no Enterprise Gateway, so a program of Floci's own serves the gateway's
  kernels API on jupyter_server, passing a kernel the KERNEL_ variables
  of its start request's env, as Jupyter Enterprise Gateway does.
- Its kernels are the image's python3, and spark-python-kubernetes, whose
  spark and sc are a Spark session in Spark's local mode on Floci's S3,
  with the endpoint's execution role, KERNEL_EXTRA_SPARK_OPTS going to
  its spark-submit.
- The endpoint is CREATING until the gateway answers, then ACTIVE with
  its serverUrl and the guide's "Endpoint created successfully. It took
  m Minutes s Seconds". DeleteManagedEndpoint makes it TERMINATING until
  the gateway has stopped. A gateway that fails, and one a restart left,
  end it TERMINATED_WITH_ERRORS with INTERNAL_ERROR.
- serverUrl is a path of the endpoint's own on Floci's port. A request
  there goes on to the gateway, its kernels' WebSocket tunnelled, when it
  carries a live token GetManagedEndpointSessionCredentials gave for that
  endpoint, as a token parameter or an Authorization: token header, as
  Jupyter Enterprise Gateway 2.6.0 takes one; any other gets that
  gateway's 401 {"reason": "Unauthorized", "message": ""}.
- SessionServers, which runs EMR Serverless's and EMR's Spark Connect
  servers and keeps their tokens, runs the gateways too, a token given
  for one endpoint reaching no other. CloudFront's WebSocket splice moves
  to WebSocketUpgrades, which the gateway's tunnel shares.
- gateway-image-template replaces the notebook image's registry.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-23 06:39:56 -04:00
1 parent 2f652f3f87
commit 29e262e783
14 files changed
+1557 -37

No files matched your search

@@ -0,0 +1,249 @@
package io.floci.aws.services.emrcontainers;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.PullImageResultCallback;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.CloudFormationSettingsProfile;
import io.floci.aws.testing.DockerAvailability;
import io.floci.aws.testing.EksRequests;
import io.floci.aws.testing.EnforcementFixtures;
import io.floci.aws.testing.PartitionCleanup;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.floci.aws.testing.S3TestClients;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.RestAssured;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import org.junit.jupiter.api.extension.RegisterExtension;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.WebSocket;
import java.time.Duration;
import java.time.Instant;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
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 on EKS managed endpoint, run for real in the {@code docker} runner mode: it runs a Jupyter Enterprise Gateway
* in its release's {@code notebook-spark} image from Amazon ECR Public, and a Jupyter client reaches it at its
* {@code serverUrl} with a session token, starts a PySpark kernel there, and runs code on Floci's S3 over the kernel's
* WebSocket, as the guide's "Example: Deploy a JupyterLab notebook" does through {@code JUPYTER_GATEWAY_URL}.
*
* <p>A nightly check: the release's notebook image is about 6 GB.
*/
@QuarkusTest
@TestProfile(CloudFormationSettingsProfile.class)
@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true")
// One instance, so that the image is pulled once for the class.
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
// The endpoint's gateway answers within its five minutes, the kernel's WebSocket opens within its two, once its Spark
// session is up, and each of its two cells answers within its two: eleven minutes, and one for the requests between.
// With the image's pull of up to 21, 33 minutes, which the Nightly checks' docker-runner group counts.
@Timeout(value = 12, unit = TimeUnit.MINUTES)
class EmrContainersGatewayNightlyIntegrationTest {
private static final String ACCOUNT = "000000000000";
private static final String REGION = "us-east-1";
private static final String ROLE = "arn:aws:iam::000000000000:role/emr-job";
private static final String RELEASE = "emr-7.5.0-latest";
// The release's notebook image, which the gateway's default template names.
private static final String NOTEBOOK_IMAGE = "public.ecr.aws/emr-on-eks/notebook-spark/emr-7.5.0:latest";
private static final Duration ACTIVE_TIMEOUT = Duration.ofMinutes(5);
// jupyter_server holds a kernel's handshake until the kernel answers, up to its own minute, and the PySpark kernel
// answers once its Spark session is up.
private static final Duration HANDSHAKE_TIMEOUT = Duration.ofMinutes(2);
private static final Duration REPLY_TIMEOUT = Duration.ofMinutes(2);
private static final ObjectMapper JSON = new ObjectMapper();
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Inject
DockerClient docker;
@BeforeAll
static void configure() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
// The notebook image's pull alone may take its twenty minutes.
@BeforeAll
@Timeout(value = 21, unit = TimeUnit.MINUTES)
void pullImage() 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");
docker.pullImageCmd(NOTEBOOK_IMAGE).exec(new PullImageResultCallback()).awaitCompletion(20, TimeUnit.MINUTES);
}
@Test
void pysparkKernelOnTheEndpointsGatewayRunsCodeOnFlocisS3() throws Exception {
S3Client s3 = AwsTestClients.create(S3Client.builder().forcePathStyle(true), ACCOUNT, Region.US_EAST_1);
cleanup.register(s3::close);
String bucket = "emr-eks-jeg-" + UUID.randomUUID().toString().substring(0, 8);
s3.createBucket(request -> request.bucket(bucket));
cleanup.register(() -> S3TestClients.deleteBucket(s3, bucket));
s3.putObject(request -> request.bucket(bucket).key("lines.txt"), RequestBody.fromString("a\nb\nc\n"));
String virtualClusterId = virtualCluster();
String endpointId = emr().body("""
{"name": "nightly", "type": "JUPYTER_ENTERPRISE_GATEWAY", "releaseLabel": "%s",
"executionRoleArn": "%s", "clientToken": "%s"}
""".formatted(RELEASE, ROLE, UUID.randomUUID()))
.post("/virtualclusters/" + virtualClusterId + "/endpoints")
.then().statusCode(200)
.extract().path("id");
cleanup.register(() -> emr().delete("/virtualclusters/" + virtualClusterId + "/endpoints/" + endpointId)
.then().statusCode(200));
await().atMost(ACTIVE_TIMEOUT).pollInterval(Duration.ofSeconds(1)).until(() -> "ACTIVE".equals(
emr().get("/virtualclusters/" + virtualClusterId + "/endpoints/" + endpointId)
.then().statusCode(200).extract().path("endpoint.state")));
String serverUrl = emr().get("/virtualclusters/" + virtualClusterId + "/endpoints/" + endpointId)
.then().extract().path("endpoint.serverUrl");
// On the profile's base URL; the test's own server is on a port of its own.
String path = URI.create(serverUrl).getPath();
assertEquals(EmrContainersService.GATEWAY_PATH + endpointId, path);
String gateway = "http://localhost:" + RestAssured.port + path;
String token = emr().body("""
{"executionRoleArn": "%s", "credentialType": "TOKEN"}
""".formatted(ROLE))
.post("/virtualclusters/" + virtualClusterId + "/endpoints/" + endpointId + "/credentials")
.then().statusCode(200)
.extract().path("credentials.token");
HttpClient http = HttpClient.newHttpClient();
assertEquals(401, http.send(HttpRequest.newBuilder(URI.create(gateway + "/api/kernelspecs")).build(),
HttpResponse.BodyHandlers.discarding()).statusCode(), "a request without the session token");
HttpResponse<String> specs = http.send(HttpRequest.newBuilder(URI.create(gateway + "/api/kernelspecs"))
.header("Authorization", "token " + token).build(), HttpResponse.BodyHandlers.ofString());
assertEquals(200, specs.statusCode(), specs.body());
assertTrue(JSON.readTree(specs.body()).path("kernelspecs").has("spark-python-kubernetes"), specs.body());
// As a Jupyter client sends its KERNEL_ variables.
HttpResponse<String> started = http.send(HttpRequest.newBuilder(URI.create(gateway + "/api/kernels"))
.header("Authorization", "token " + token)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("""
{"name": "spark-python-kubernetes",
"env": {"KERNEL_EXTRA_SPARK_OPTS": "--conf spark.app.name=from-kernel-env"}}
""")).build(), HttpResponse.BodyHandlers.ofString());
assertEquals(201, started.statusCode(), started.body());
String kernelId = JSON.readTree(started.body()).path("id").textValue();
Messages messages = new Messages();
WebSocket socket = http.newWebSocketBuilder().header("Authorization", "token " + token)
.buildAsync(URI.create(gateway.replaceFirst("^http", "ws") + "/api/kernels/" + kernelId
+ "/channels"), messages)
.get(HANDSHAKE_TIMEOUT.toSeconds(), TimeUnit.SECONDS);
String session = UUID.randomUUID().toString();
assertEquals("3", execute(socket, messages, session,
"spark.read.text(\"s3://" + bucket + "/lines.txt\").count()"));
assertEquals("'from-kernel-env'", execute(socket, messages, session, "spark.conf.get(\"spark.app.name\")"));
socket.sendClose(WebSocket.NORMAL_CLOSURE, "done").get(10, TimeUnit.SECONDS);
assertEquals(204, http.send(HttpRequest.newBuilder(URI.create(gateway + "/api/kernels/" + kernelId))
.header("Authorization", "token " + token).DELETE().build(),
HttpResponse.BodyHandlers.discarding()).statusCode());
}
// Runs code in the kernel, as a Jupyter client sends an execute_request, and answers its result's text/plain.
private static String execute(WebSocket socket, Messages messages, String session, String code) throws Exception {
String messageId = UUID.randomUUID().toString();
ObjectNode request = JSON.createObjectNode();
request.putObject("header").put("msg_id", messageId).put("username", "nightly").put("session", session)
.put("msg_type", "execute_request").put("version", "5.3").put("date", Instant.now().toString());
request.putObject("parent_header");
request.putObject("metadata");
request.putObject("content").put("code", code).put("silent", false).put("store_history", true)
.put("allow_stdin", false).put("stop_on_error", true).putObject("user_expressions");
request.putArray("buffers");
request.put("channel", "shell");
socket.sendText(JSON.writeValueAsString(request), true).get(10, TimeUnit.SECONDS);
return await("an execute_result for " + code).atMost(REPLY_TIMEOUT).pollInterval(Duration.ofMillis(100))
.until(() -> result(messages, messageId), Objects::nonNull);
}
// The text/plain of the result of the request messageId among the messages come so far, or null until it comes.
private static String result(Messages messages, String messageId) throws Exception {
for (String text = messages.received.poll(); text != null; text = messages.received.poll()) {
JsonNode message = JSON.readTree(text);
if (!messageId.equals(message.at("/parent_header/msg_id").textValue())) {
continue;
}
String type = message.at("/header/msg_type").textValue();
if ("execute_result".equals(type)) {
return message.at("/content/data/text~1plain").textValue();
}
if ("error".equals(type)) {
fail("the kernel raised: " + message.path("content"));
}
}
return null;
}
private String virtualCluster() {
String eksCluster = "emr-" + UUID.randomUUID().toString().substring(0, 8);
EksRequests.eks(ACCOUNT, REGION)
.body("""
{"name": "%s", "roleArn": "arn:aws:iam::000000000000:role/eks-role", "version": "1.29"}
""".formatted(eksCluster))
.post("/clusters")
.then().statusCode(200);
cleanup.register(() -> EksRequests.eks(ACCOUNT, REGION).delete("/clusters/" + eksCluster)
.then().statusCode(200));
String id = emr().body("""
{"name": "nightly", "clientToken": "%s",
"containerProvider": {"type": "EKS", "id": "%s", "info": {"eksInfo": {"namespace": "spark"}}}}
""".formatted(UUID.randomUUID(), eksCluster))
.post("/virtualclusters")
.then().statusCode(200)
.extract().path("id");
cleanup.register(() -> emr().delete("/virtualclusters/" + id).then().statusCode(200));
return id;
}
private static RequestSpecification emr() {
return given().header("Authorization", EnforcementFixtures.auth(ACCOUNT, REGION, "emr-containers"))
.contentType("application/json")
.urlEncodingEnabled(false);
}
/** The kernel's messages, each whole, as its WebSocket sends them. */
private static final class Messages implements WebSocket.Listener {
final BlockingQueue<String> received = new LinkedBlockingQueue<>();
private final StringBuilder partial = new StringBuilder();
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
partial.append(data);
if (last) {
received.add(partial.toString());
partial.setLength(0);
}
webSocket.request(1);
return null;
}
}
}
@@ -0,0 +1,217 @@
package io.floci.aws.services.emrcontainers;
import io.floci.aws.core.common.ServiceConfigAccess;
import io.floci.aws.core.common.SparkConnectTargets;
import io.floci.aws.core.common.WebSocketUpgrades;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.RequestOptions;
import io.vertx.core.http.WebSocket;
import io.vertx.core.http.WebSocketConnectOptions;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Requests to an endpoint's {@code serverUrl} through {@link EmrContainersGatewayProxy}: a server that echoes what it
* gets stands in for the endpoint's gateway, and the service's routes for its tokens.
*/
class EmrContainersGatewayProxyTest {
private static final String ENDPOINT = "ep0123456789a";
private static final String TOKEN = "a-session-token";
private static final String BASE = EmrContainersService.GATEWAY_PATH + ENDPOINT;
private final AtomicInteger requestsEnded = new AtomicInteger();
private Vertx vertx;
private HttpServer gateway;
private HttpServer floci;
private HttpClient client;
private EmrContainersService service;
@BeforeEach
void setUp() throws Exception {
vertx = Vertx.vertx();
// A gateway that answers a request with what it got, and echoes each WebSocket message; at /partial it
// breaks off its answer after a part of the body it gave the length of.
gateway = await(vertx.createHttpServer().requestHandler(request -> {
if (WebSocketUpgrades.isHandshake(request)) {
request.toWebSocket().onSuccess(socket -> socket.textMessageHandler(message ->
socket.writeTextMessage("echo " + message + " on " + request.uri())));
return;
}
if (request.path().equals("/partial")) {
request.response().putHeader("content-length", "100").write("partial")
.onComplete(written -> request.connection().close());
return;
}
request.body().onSuccess(body -> request.response().setStatusCode(201)
.putHeader("content-type", "application/json")
.end(new JsonObject().put("method", request.method().name()).put("uri", request.uri())
.put("authorization", request.getHeader("Authorization"))
.put("body", body.toString()).encode()));
}).listen(0, "127.0.0.1"));
service = mock(EmrContainersService.class);
when(service.gatewayRoute(anyString(), any())).thenReturn(Optional.empty());
when(service.gatewayRoute(ENDPOINT, TOKEN)).thenAnswer(invocation -> Optional.of(
SparkConnectTargets.Route.to("127.0.0.1", gateway.actualPort(), requestsEnded::incrementAndGet)));
ServiceConfigAccess serviceConfigAccess = mock(ServiceConfigAccess.class);
when(serviceConfigAccess.isEnabled(eq(EmrContainersService.SERVICE))).thenReturn(true);
EmrContainersGatewayProxy proxy = new EmrContainersGatewayProxy(service, serviceConfigAccess, vertx);
Router router = Router.router(vertx);
proxy.register(router);
router.route().handler(context -> context.response().setStatusCode(404).end("not a gateway"));
floci = await(vertx.createHttpServer().requestHandler(router).listen(0, "127.0.0.1"));
client = vertx.createHttpClient();
}
@AfterEach
void tearDown() throws Exception {
await(vertx.close());
}
@Test
void requestWithItsEndpointsTokenGoesToItsGatewayWithoutTheToken() throws Exception {
Answer byParameter = request(HttpMethod.POST, BASE + "/api/kernels?token=" + TOKEN + "&path=nb", null,
"{\"name\": \"python3\"}");
Answer byHeader = request(HttpMethod.GET, BASE + "/api/kernelspecs", "token " + TOKEN, null);
assertEquals(201, byParameter.status);
JsonObject gotByParameter = new JsonObject(byParameter.body);
assertEquals("POST", gotByParameter.getString("method"));
assertEquals("/api/kernels?path=nb", gotByParameter.getString("uri"));
assertEquals("{\"name\": \"python3\"}", gotByParameter.getString("body"));
JsonObject gotByHeader = new JsonObject(byHeader.body);
assertEquals("/api/kernelspecs", gotByHeader.getString("uri"));
// The token is Floci's to check, so the gateway never sees it.
assertNull(gotByHeader.getString("authorization"));
awaitCount(requestsEnded, 2);
}
@Test
void queryIsReadAsTheGatewayReadsIt() throws Exception {
// Its last token parameter is the one checked, and a malformed escape stays as it came.
Answer answer = request(HttpMethod.GET, BASE + "/api/kernels?%GG=1&token=not-a-token&token=" + TOKEN, null,
null);
assertEquals(201, answer.status);
assertEquals("/api/kernels?%GG=1", new JsonObject(answer.body).getString("uri"));
awaitCount(requestsEnded, 1);
}
@Test
void answerTheGatewayBreaksOffBreaksOffTheViewers() {
ExecutionException broken = assertThrows(ExecutionException.class,
() -> request(HttpMethod.GET, BASE + "/partial", "token " + TOKEN, null));
assertTrue(broken.getCause().getMessage().toLowerCase().contains("closed"), broken.getCause().toString());
awaitCount(requestsEnded, 1);
}
@Test
void requestWithoutATokenGivenForItsEndpointGetsTheGatewaysUnauthorized() throws Exception {
Answer none = request(HttpMethod.GET, BASE + "/api/kernels", null, null);
Answer unknown = request(HttpMethod.GET, BASE + "/api/kernels", "token not-a-token", null);
Answer otherScheme = request(HttpMethod.GET, BASE + "/api/kernels", "Bearer " + TOKEN, null);
for (Answer answer : new Answer[] {none, unknown, otherScheme}) {
assertEquals(401, answer.status);
assertEquals(new JsonObject().put("reason", "Unauthorized").put("message", ""),
new JsonObject(answer.body));
}
}
@Test
void requestTheServiceRefusesGetsItsReason() throws Exception {
when(service.gatewayRoute(ENDPOINT, "expired")).thenReturn(Optional.of(SparkConnectTargets.Route.refused(
SparkConnectTargets.Route.UNAUTHENTICATED, "The authentication token has expired.")));
when(service.gatewayRoute(ENDPOINT, "terminating")).thenReturn(Optional.of(SparkConnectTargets.Route.refused(
SparkConnectTargets.Route.UNAVAILABLE, "Endpoint " + ENDPOINT + " is TERMINATING.")));
Answer expired = request(HttpMethod.GET, BASE + "/api/kernels", "token expired", null);
Answer terminating = request(HttpMethod.GET, BASE + "/api/kernels", "token terminating", null);
assertEquals(401, expired.status);
assertEquals("The authentication token has expired.", new JsonObject(expired.body).getString("message"));
assertEquals(503, terminating.status);
assertEquals("Service Unavailable", new JsonObject(terminating.body).getString("reason"));
assertEquals("Endpoint " + ENDPOINT + " is TERMINATING.",
new JsonObject(terminating.body).getString("message"));
}
@Test
void kernelsWebSocketIsTunnelledToTheGateway() throws Exception {
WebSocket socket = await(vertx.createWebSocketClient().connect(new WebSocketConnectOptions()
.setHost("127.0.0.1").setPort(floci.actualPort())
.setURI(BASE + "/api/kernels/k1/channels?session_id=s1")
.addHeader("Authorization", "token " + TOKEN)));
CompletableFuture<String> echoed = new CompletableFuture<>();
socket.textMessageHandler(echoed::complete);
socket.writeTextMessage("execute_request");
assertEquals("echo execute_request on /api/kernels/k1/channels?session_id=s1",
echoed.get(10, TimeUnit.SECONDS));
await(socket.close());
awaitCount(requestsEnded, 1);
}
@Test
void kernelsWebSocketWithoutAValidTokenIsRefused() {
Exception refused = assertThrows(Exception.class, () -> await(
vertx.createWebSocketClient().connect(new WebSocketConnectOptions().setHost("127.0.0.1")
.setPort(floci.actualPort()).setURI(BASE + "/api/kernels/k1/channels"))));
assertTrue(refused.getMessage().contains("401"), refused.getMessage());
}
private Answer request(HttpMethod method, String uri, String authorization, String body) throws Exception {
RequestOptions options = new RequestOptions().setMethod(method).setHost("127.0.0.1")
.setPort(floci.actualPort()).setURI(uri);
if (authorization != null) {
options.addHeader("Authorization", authorization);
}
// The answer's body is read as its head arrives, on the event loop: asked for later, it may have gone by.
return await(client.request(options)
.compose(request -> body == null ? request.send() : request.send(Buffer.buffer(body)))
.compose(response -> response.body()
.map(read -> new Answer(response.statusCode(), read.toString()))));
}
// Awaitility's, by name: this class's own await takes a Future.
private static void awaitCount(AtomicInteger count, int expected) {
Awaitility.await("requests ended").atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(10))
.until(() -> count.get() >= expected);
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, String body) {
}
}
@@ -5,12 +5,14 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsException;
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.core.storage.InMemoryStorage;
import io.floci.aws.services.eks.EksService;
import io.floci.aws.services.eks.model.AccessConfig;
import io.floci.aws.services.eks.model.Cluster;
import io.floci.aws.services.emrcontainers.EmrContainersService.ListQuery;
import io.floci.aws.services.emrserverless.SessionServers;
import io.floci.aws.services.emrserverless.SparkJobRunner;
import io.floci.aws.services.iam.IamService;
import io.floci.aws.testing.MutableClock;
@@ -28,9 +30,16 @@ 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.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicReference;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -696,7 +705,7 @@ class EmrContainersServiceTest {
when(iam.resolveCallerArn(eq(null))).thenReturn(Optional.empty());
return new EmrContainersService(stores.get(0), stores.get(1), stores.get(2), stores.get(3), stores.get(4),
mapper, new RegionResolver(REGION, ACCOUNT_ID), eks, iam, null, clock, 0, runner, executor,
"registry.internal/emr-on-eks/spark/%s", "floci-net", delays);
"registry.internal/emr-on-eks/spark/%s", "floci-net", delays, null);
}
private EmrContainersService dockerService(FakeRunner runner, QueuedExecutor executor) {
@@ -1271,6 +1280,244 @@ class EmrContainersServiceTest {
}
}
// ── Managed endpoints' gateways ───────────────────────────────────────────────
// Why the gateways' probe finds none answering, until a test sets it to null.
private final AtomicReference<String> gatewayUnanswered = new AtomicReference<>();
// A docker service whose endpoints' gateways run on threads of their own, Floci at http://floci.test:4566/.
private EmrContainersService gatewayService(GatewayRunner runner,
List<AccountAwareStorageBackend<ObjectNode>> stores) {
IamService iam = mock(IamService.class);
when(iam.resolveCallerArn(eq(null))).thenReturn(Optional.empty());
// A pool, as the service's own is, so that its shutdown interrupts the gateways' threads.
SessionServers servers = new SessionServers(EmrContainersGateways.KIND, runner,
Executors.newCachedThreadPool(Thread.ofPlatform().daemon().factory()), null,
(host, port) -> gatewayUnanswered.get(), clock);
return new EmrContainersService(stores.get(0), stores.get(1), stores.get(2), stores.get(3), stores.get(4),
mapper, new RegionResolver(REGION, ACCOUNT_ID), eks, iam, null, clock, 0, runner, Runnable::run,
null, "floci-net", delays, new EmrContainersService.EndpointGateways(servers,
"registry.internal/emr-on-eks/notebook-spark/%s", "http://floci.test:4566/"));
}
private String gatewayEndpoint(EmrContainersService service, String clusterId) {
return service.createManagedEndpoint(clusterId, json("""
{"name": "studio", "type": "JUPYTER_ENTERPRISE_GATEWAY", "releaseLabel": "%s",
"executionRoleArn": "%s", "clientToken": "%s",
"configurationOverrides": {"applicationConfiguration": [{"classification": "spark-defaults",
"properties": {"spark.sql.shuffle.partitions": "4", "spark.master": "k8s://https://eks.test:443",
"spark.submit.deployMode": "cluster",
"spark.kubernetes.driverEnv.SPARK_DIST_CLASSPATH": "/opt/extra/*"}}]}}
""".formatted(RELEASE, ROLE, UUID.randomUUID()))).get("id").textValue();
}
private static JsonNode endpoint(EmrContainersService service, String clusterId, String endpointId) {
return service.describeManagedEndpoint(clusterId, endpointId).get("endpoint");
}
// The endpoint once it is in that state, which a gateway's thread puts it in.
private static JsonNode awaitEndpoint(EmrContainersService service, String clusterId, String endpointId,
String state) {
return await("endpoint " + endpointId + " " + state).atMost(Duration.ofSeconds(10))
.pollInterval(Duration.ofMillis(10))
.until(() -> endpoint(service, clusterId, endpointId), endpoint -> state.equals(state(endpoint)));
}
private String sessionToken(EmrContainersService service, String clusterId, String endpointId) {
return service.getManagedEndpointSessionCredentials(clusterId, endpointId,
json("{\"executionRoleArn\": \"%s\", \"credentialType\": \"TOKEN\"}".formatted(ROLE)))
.at("/credentials/token").textValue();
}
@Test
void dockerEndpointRunsItsGatewayAndIsActiveWithItsServerUrlOnceTheGatewayAnswers() {
GatewayRunner runner = new GatewayRunner();
gatewayUnanswered.set("not yet");
EmrContainersService service = gatewayService(runner, stores());
String clusterId = virtualCluster(service, EKS_CLUSTER);
String endpointId = gatewayEndpoint(service, clusterId);
JsonNode creating = endpoint(service, clusterId, endpointId);
assertEquals("CREATING", state(creating), "Initially, your endpoint is in the CREATING state");
assertFalse(creating.has("serverUrl"));
SparkJobRunner.Job job = runner.awaitJob(endpointId);
assertEquals("registry.internal/emr-on-eks/notebook-spark/emr-7.5.0:latest", job.imageTemplate());
assertEquals(EmrContainersGateways.PORT, job.listenPort());
assertEquals(ROLE, job.executionRole());
assertEquals("floci-net", job.dockerNetwork());
assertEquals("4", job.sparkDefaults().get("spark.sql.shuffle.partitions"));
assertEquals("false", job.sparkDefaults().get(EmrContainersGateways.PYSPARK_VIRTUALENV),
"a kernel in Spark's local mode runs on the image's Python");
assertFalse(job.sparkDefaults().containsKey("spark.master"), "the runner's local mode stands");
assertEquals("client", job.sparkDefaults().get("spark.submit.deployMode"));
assertEquals("/opt/extra/*:" + EmrContainersGateways.AWS_SDK,
job.environment().get(EmrContainersGateways.CLASS_PATH_VARIABLE),
"a kernel's driver keeps the endpoint's class path and gains S3A's AWS SDK");
assertEquals(EmrContainersGateways.PROGRAM, job.environment().get(EmrContainersGateways.PROGRAM_VARIABLE));
assertTrue(job.command().get(2).endsWith("exec python3 /tmp/floci-gateway/gateway.py"), job.command().get(2));
clock.advance(Duration.ofMinutes(3).plusSeconds(15));
gatewayUnanswered.set(null);
JsonNode active = awaitEndpoint(service, clusterId, endpointId, "ACTIVE");
assertEquals("http://floci.test:4566/_aws/emr-containers/endpoints/" + endpointId,
active.get("serverUrl").textValue());
assertEquals("Endpoint created successfully. It took 3 Minutes 15 Seconds",
active.get("stateDetails").textValue());
runner.stop(endpointId);
}
@Test
void sessionTokenReachesItsOwnEndpointsGatewayUntilItExpires() {
GatewayRunner runner = new GatewayRunner();
EmrContainersService service = gatewayService(runner, stores());
String clusterId = virtualCluster(service, EKS_CLUSTER);
String endpointId = gatewayEndpoint(service, clusterId);
String otherId = gatewayEndpoint(service, clusterId);
awaitEndpoint(service, clusterId, endpointId, "ACTIVE");
awaitEndpoint(service, clusterId, otherId, "ACTIVE");
String token = sessionToken(service, clusterId, endpointId);
SparkConnectTargets.Route route = service.gatewayRoute(endpointId, token).orElseThrow();
assertEquals("127.0.0.1", route.host());
assertEquals(GatewayRunner.PORT, route.port());
route.ended().run();
assertTrue(service.gatewayRoute(otherId, token).isEmpty(), "another endpoint's token is not its");
assertTrue(service.gatewayRoute(endpointId, "not-a-token").isEmpty());
assertTrue(service.gatewayRoute(endpointId, null).isEmpty());
clock.advance(Duration.ofMinutes(15));
SparkConnectTargets.Route expired = service.gatewayRoute(endpointId, token).orElseThrow();
assertEquals(SparkConnectTargets.Route.UNAUTHENTICATED, expired.status());
assertEquals("The authentication token has expired. Call GetManagedEndpointSessionCredentials for a new "
+ "one.", expired.refusal());
runner.stop(endpointId);
runner.stop(otherId);
}
@Test
void deletedDockerEndpointStopsItsGatewayAndItsTokensGo() {
GatewayRunner runner = new GatewayRunner();
EmrContainersService service = gatewayService(runner, stores());
String clusterId = virtualCluster(service, EKS_CLUSTER);
String endpointId = gatewayEndpoint(service, clusterId);
awaitEndpoint(service, clusterId, endpointId, "ACTIVE");
String token = sessionToken(service, clusterId, endpointId);
service.deleteManagedEndpoint(clusterId, endpointId);
JsonNode terminated = awaitEndpoint(service, clusterId, endpointId, "TERMINATED");
assertTrue(runner.stopped.contains(endpointId));
assertFalse(terminated.has("serverUrl"));
assertTrue(service.gatewayRoute(endpointId, token).isEmpty());
}
@Test
void dockerEndpointWhoseGatewayExitsIsTerminatedWithErrors() {
GatewayRunner runner = new GatewayRunner();
EmrContainersService service = gatewayService(runner, stores());
String clusterId = virtualCluster(service, EKS_CLUSTER);
String endpointId = gatewayEndpoint(service, clusterId);
awaitEndpoint(service, clusterId, endpointId, "ACTIVE");
runner.end(endpointId, SparkJobRunner.Outcome.exitedWith(1));
JsonNode failed = awaitEndpoint(service, clusterId, endpointId, "TERMINATED_WITH_ERRORS");
assertEquals("INTERNAL_ERROR", failed.get("failureReason").textValue());
assertEquals("The endpoint's Jupyter Enterprise Gateway exited with code 1.",
failed.get("stateDetails").textValue());
assertFalse(failed.has("serverUrl"));
}
@Test
void dockerEndpointsGatewayStoppedWithFlociIsTerminatedWithErrors() {
GatewayRunner runner = new GatewayRunner();
EmrContainersService service = gatewayService(runner, stores());
String clusterId = virtualCluster(service, EKS_CLUSTER);
String endpointId = gatewayEndpoint(service, clusterId);
awaitEndpoint(service, clusterId, endpointId, "ACTIVE");
service.shutdown();
JsonNode lost = awaitEndpoint(service, clusterId, endpointId, "TERMINATED_WITH_ERRORS");
assertEquals("INTERNAL_ERROR", lost.get("failureReason").textValue());
assertEquals("The endpoint's Jupyter Enterprise Gateway stopped with Floci.",
lost.get("stateDetails").textValue());
assertFalse(lost.has("serverUrl"));
assertTrue(runner.stopped.isEmpty(), "nothing deleted it");
}
@Test
void dockerEndpointAnEarlierProcessRanIsTerminatedWithErrors() {
List<AccountAwareStorageBackend<ObjectNode>> stores = stores();
GatewayRunner earlierRunner = new GatewayRunner();
EmrContainersService earlier = gatewayService(earlierRunner, stores);
String clusterId = virtualCluster(earlier, EKS_CLUSTER);
String endpointId = gatewayEndpoint(earlier, clusterId);
awaitEndpoint(earlier, clusterId, endpointId, "ACTIVE");
EmrContainersService restarted = gatewayService(new GatewayRunner(), stores);
JsonNode lost = endpoint(restarted, clusterId, endpointId);
assertEquals("TERMINATED_WITH_ERRORS", state(lost));
assertEquals("INTERNAL_ERROR", lost.get("failureReason").textValue());
assertEquals("The endpoint's Jupyter Enterprise Gateway stopped with Floci.",
lost.get("stateDetails").textValue());
earlierRunner.stop(endpointId);
}
/**
* A runner whose gateways listen at once on 127.0.0.1:{@value #PORT} and run until they are stopped, interrupted,
* or ended as a test says.
*/
private static final class GatewayRunner implements SparkJobRunner {
static final int PORT = 18888;
final List<Job> jobs = new CopyOnWriteArrayList<>();
final Set<String> stopped = ConcurrentHashMap.newKeySet();
private final Map<String, CompletableFuture<Outcome>> ends = new ConcurrentHashMap<>();
@Override
public Outcome run(Job job, Progress progress) {
jobs.add(job);
progress.started();
progress.listening("127.0.0.1", PORT);
try {
return end(job.runId()).get();
} catch (InterruptedException e) {
// As the Docker runner answers when Floci's shutdown interrupts it.
return Outcome.halted();
} catch (ExecutionException e) {
throw new IllegalStateException(e);
}
}
@Override
public void stop(String runId) {
stopped.add(runId);
end(runId, Outcome.halted());
}
@Override
public void removeLeftoverDrivers(String service) {
}
void end(String runId, Outcome outcome) {
end(runId).complete(outcome);
}
Job awaitJob(String runId) {
return await("a gateway started for " + runId).atMost(Duration.ofSeconds(10))
.pollInterval(Duration.ofMillis(10))
.until(() -> jobs.stream().filter(started -> started.runId().equals(runId)).findFirst(),
Optional::isPresent)
.get();
}
private CompletableFuture<Outcome> end(String runId) {
return ends.computeIfAbsent(runId, id -> new CompletableFuture<>());
}
}
/** A runner that starts the driver at once, runs {@code whileRunning}, and ends as {@code outcome} says. */
private static final class FakeRunner implements SparkJobRunner {
final List<Job> jobs = new ArrayList<>();