feat(emr-containers): cull a managed endpoint's idle kernels by its jeg-config (#9275)

An endpoint's configurationOverrides take "the additional
classification jeg-config", whose allow-listed settings are
RemoteMappingKernelManager.cull_idle_timeout and
RemoteMappingKernelManager.cull_interval (EMR on EKS Development
Guide, "Jupyter Enterprise Gateway (JEG) configuration options"). A
Floci endpoint's gateway read neither.

- The gateway job passes those two properties of the endpoint's
  jeg-config classification to the program as its arguments
  (--RemoteMappingKernelManager.cull_idle_timeout=<value>), a later
  classification's winning; other jeg-config properties go nowhere.
- The program's kernel manager is now named RemoteMappingKernelManager,
  as Jupyter Enterprise Gateway's is, so the settings reach it under the
  names the guide gives them, and jupyter_server's culler shuts down a
  kernel idle that long, checking every interval.
- EmrContainersSparkJobs.properties reads any classification of a
  configurationOverrides, sparkDefaults now through it.
- The nightly check gains a method: an endpoint whose jeg-config sets a
  10-second idle timeout culls a python3 kernel left idle within a
  minute. The docker-runner group's budget grows by its seven minutes.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-23 10:47:51 -04:00
1 parent 7b2e60cfe0
commit 86ef90b99c
6 files changed
+120 -43

No files matched your search

+4 -4
View File
@@ -34,9 +34,9 @@ jobs:
# EmrDockerRunnerNightlyIntegrationTest's eleven two-minute tests and two-minute setup,
# EmrClusterShrinkNightlyIntegrationTest's sixteen-minute method and two-minute setup, and
# EmrContainersSparkNightlyIntegrationTest's three six-minute methods, eleven-minute method, two-minute setup before
# each and 21-minute image pull, and EmrContainersGatewayNightlyIntegrationTest's sixteen-minute method and
# 21-minute image pull, 137 minutes. A check added, or a bound raised, raises its group's timeout with it, so a slow
# check fails with its own message.
# each and 21-minute image pull, and EmrContainersGatewayNightlyIntegrationTest's sixteen-minute and seven-minute
# methods and 21-minute image pull, 144 minutes. A check added, or a bound raised, raises its group's timeout with
# it, so a slow check fails with its own message.
strategy:
fail-fast: false
matrix:
@@ -44,7 +44,7 @@ jobs:
- group: standard
timeout: 359
- group: docker-runner
timeout: 157
timeout: 164
timeout-minutes: ${{ matrix.timeout }}
# A fork's schedule would spend its owner's minutes on checks it never asked for; a draft waits until it is
# ready for review, as the CI shards do.
+11 -4
View File
@@ -251,7 +251,14 @@ remote kernel lifecycle management capability that interactive clients need" (EM
restarted kernel answers, the gateway ends the cell with the replies the magic prepared; if it dies first, or does
not answer within a minute, the cell ends with an error saying so. The magic itself refuses a reserved setting,
such as `spark.kubernetes.namespace`.
* **Not emulated yet**: the "Apache Spark with Scala" kernel, `jupyter-kernel-overrides` images, and `jeg-config`'s
culling settings. A browser's CORS preflight (`OPTIONS`), which Jupyter Enterprise Gateway takes without a token,
needs one here. Every kernel runs with the endpoint's execution role, whichever role its
session token was asked for with. `certificateArn` is kept, and the `serverUrl` is plain HTTP on Floci's port.
* **`jeg-config`**: the two settings the guide's "Jupyter Enterprise Gateway (JEG) configuration options"
allow-lists go to the gateway's kernel manager, named `RemoteMappingKernelManager` as Jupyter Enterprise Gateway's
is: `RemoteMappingKernelManager.cull_idle_timeout`, "Timeout in seconds (integer), after which a kernel is
considered idle and ready to be culled. Values of 0 or lower deactivate culling.", and
`RemoteMappingKernelManager.cull_interval`, "The interval in seconds (integer) on which to check for idle kernels
that exceed the cull timeout value." As jupyter_server's culler does by default, a kernel with a client connected
is not culled. Other `jeg-config` properties go nowhere.
* **Not emulated yet**: the "Apache Spark with Scala" kernel and `jupyter-kernel-overrides` images. A browser's CORS
preflight (`OPTIONS`), which Jupyter Enterprise Gateway takes without a token, needs one here. Every kernel runs
with the endpoint's execution role, whichever role its session token was asked for with. `certificateArn` is
kept, and the `serverUrl` is plain HTTP on Floci's port.
@@ -12,6 +12,7 @@ import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -71,6 +72,11 @@ final class EmrContainersGateways {
// after that class path.
static final String CLASS_PATH_VARIABLE = "SPARK_DIST_CLASSPATH";
static final String AWS_SDK = "/usr/share/aws/aws-java-sdk-v2/*";
// The classification of Jupyter Enterprise Gateway's settings, and those the guide allow-lists ("Jupyter
// Enterprise Gateway (JEG) configuration options"), which go to the program as its arguments.
static final String JEG_CONFIG = "jeg-config";
static final List<String> JEG_PROPERTIES = List.of("RemoteMappingKernelManager.cull_idle_timeout",
"RemoteMappingKernelManager.cull_interval");
/** The servers' kind, in the answers to the calls they cannot take. */
static final SessionServers.Kind KIND = new SessionServers.Kind("Jupyter Enterprise Gateway", "Endpoint",
@@ -205,8 +211,9 @@ final class EmrContainersGateways {
# Records the session token of a kernel the kernels API or the sessions API starts, and gives the kernel
# the KERNEL_ID and the AES key the magic reads, as Jupyter Enterprise Gateway's launcher does; forgets
# both once the kernel goes, whether a request, the culler or the kernel's death removes it.
class KernelManager(AsyncMappingKernelManager):
# both once the kernel goes, whether a request, the culler or the kernel's death removes it. Named as
# Jupyter Enterprise Gateway's, whose name the endpoint's jeg-config properties give, from the arguments.
class RemoteMappingKernelManager(AsyncMappingKernelManager):
async def start_kernel(self, *, kernel_id=None, **kwargs):
if kernel_id is not None and kernel_id in self:
@@ -342,7 +349,7 @@ final class EmrContainersGateways {
"--ServerApp.allow_remote_access=True",
"--KernelSpecManager.allowed_kernelspecs=python3",
"--KernelSpecManager.allowed_kernelspecs=spark-python-kubernetes",
], kernel_manager_class=KernelManager))
] + sys.argv[1:], kernel_manager_class=RemoteMappingKernelManager))
""".replace("@HOME@", HOME).replace("@PORT@", String.valueOf(PORT))
.replace("@PROGRAM_VARIABLE@", PROGRAM_VARIABLE).replace("@SESSION_HEADER@", SESSION_HEADER);
@@ -361,9 +368,10 @@ final class EmrContainersGateways {
* {@code configurationOverrides}, listening on {@link #PORT}. Its kernels' {@code spark-submit} gets those
* defaults, in Spark's local mode and client deploy mode whatever master and deploy mode they name, as a job run's
* driver does, on the image's Python: the virtualenv the image gives a PySpark driver is made on YARN and
* Kubernetes alone. Their class path gains the AWS SDK that S3A runs on, which the image's own leaves out. As a
* Spark Connect server does, it checks no token
* itself: Floci reaches it on the Docker host's loopback interface alone, and checks the session token first.
* Kubernetes alone. Their class path gains the AWS SDK that S3A runs on, which the image's own leaves out. The
* allow-listed properties of the endpoint's {@code jeg-config} classification go to the program as its arguments,
* other ones nowhere. As a Spark Connect server does, it checks no token itself: Floci reaches it on the Docker
* host's loopback interface alone, and checks the session token first.
*/
static SparkJobRunner.Job job(ObjectNode endpoint, String imageTemplate, String dockerNetwork) {
AwsArnUtils.Arn arn = AwsArnUtils.parse(endpoint.get("arn").textValue());
@@ -377,8 +385,16 @@ final class EmrContainersGateways {
"spark.kubernetes.driverEnv."));
environment.merge(CLASS_PATH_VARIABLE, AWS_SDK, (endpointClassPath, sdk) -> endpointClassPath + ":" + sdk);
environment.put(PROGRAM_VARIABLE, PROGRAM);
List<String> command = List.of("/bin/bash", "-c", "mkdir -p " + HOME + " && printf '%s' \"$"
+ PROGRAM_VARIABLE + "\" > " + HOME + "/gateway.py && exec python3 " + HOME + "/gateway.py");
List<String> command = new ArrayList<>(List.of("/bin/bash", "-c", "mkdir -p " + HOME + " && printf '%s' \"$"
+ PROGRAM_VARIABLE + "\" > " + HOME + "/gateway.py && exec python3 " + HOME + "/gateway.py \"$@\"",
"gateway"));
Map<String, String> jegConfig =
EmrContainersSparkJobs.properties(endpoint.get("configurationOverrides"), JEG_CONFIG);
for (String property : JEG_PROPERTIES) {
if (jegConfig.containsKey(property)) {
command.add("--" + property + "=" + jegConfig.get(property));
}
}
return new SparkJobRunner.Job(EmrContainersService.SERVICE, endpoint.get("id").textValue(), arn.accountId(),
arn.region(), releaseLabel, SparkJobRunner.Engine.SPARK, image(imageTemplate, releaseLabel), null,
dockerNetwork, endpoint.get("executionRoleArn").textValue(), sparkDefaults, List.of(), command,
@@ -74,13 +74,21 @@ final class EmrContainersSparkJobs {
* {@code spark-defaults} classification of its {@code applicationConfiguration}, a later one's winning.
*/
static Map<String, String> sparkDefaults(JsonNode configurationOverrides) {
return properties(configurationOverrides, SPARK_DEFAULTS);
}
/**
* The properties of a {@code configurationOverrides}' {@code classification}: those of each such classification of
* its {@code applicationConfiguration}, a later one's winning.
*/
static Map<String, String> properties(JsonNode configurationOverrides, String classification) {
JsonNode configurations = configurationOverrides != null
? configurationOverrides.path("applicationConfiguration") : null;
if (configurations == null || !configurations.isArray()) {
return new LinkedHashMap<>();
}
List<?> list = JSON.convertValue(configurations, List.class);
return EmrServerlessJobRunService.classificationProperties(list, SPARK_DEFAULTS);
return EmrServerlessJobRunService.classificationProperties(list, classification);
}
/**
@@ -56,7 +56,8 @@ import static org.junit.jupiter.api.Assertions.fail;
* {@code serverUrl} with a session token, starts a PySpark kernel there, and a session with a kernel of its own, which
* the kernels and sessions listings show that token alone, and runs code on Floci's S3 over the PySpark kernel's
* WebSocket, as the guide's "Example: Deploy a JupyterLab notebook" does through {@code JUPYTER_GATEWAY_URL}, then
* changes its Spark session's settings with {@code %%configure}, as "Modifying PySpark session parameters" does.
* changes its Spark session's settings with {@code %%configure}, as "Modifying PySpark session parameters" does. An
* endpoint whose {@code jeg-config} sets a short idle timeout culls a kernel left idle.
*
* <p>A nightly check: the release's notebook image is about 6 GB.
*/
@@ -65,10 +66,6 @@ import static org.junit.jupiter.api.Assertions.fail;
@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 four cells answers within its two: fifteen minutes, and one for the requests
// between. With the image's pull of up to 21, 37 minutes, which the Nightly checks' docker-runner group counts.
@Timeout(value = 16, unit = TimeUnit.MINUTES)
class EmrContainersGatewayNightlyIntegrationTest {
private static final String ACCOUNT = "000000000000";
@@ -104,7 +101,11 @@ class EmrContainersGatewayNightlyIntegrationTest {
docker.pullImageCmd(NOTEBOOK_IMAGE).exec(new PullImageResultCallback()).awaitCompletion(20, TimeUnit.MINUTES);
}
// 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 four cells answers within its two: fifteen minutes, and one for the
// requests between. The Nightly checks' docker-runner group counts it.
@Test
@Timeout(value = 16, unit = TimeUnit.MINUTES)
void pysparkKernelOnTheEndpointsGatewayRunsCodeOnFlocisS3() throws Exception {
S3Client s3 = AwsTestClients.create(S3Client.builder().forcePathStyle(true), ACCOUNT, Region.US_EAST_1);
cleanup.register(s3::close);
@@ -113,25 +114,8 @@ class EmrContainersGatewayNightlyIntegrationTest {
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 endpointId = endpoint(virtualClusterId, "{}");
String gateway = gateway(virtualClusterId, endpointId);
String token = sessionToken(virtualClusterId, endpointId);
HttpClient http = HttpClient.newHttpClient();
@@ -194,6 +178,60 @@ class EmrContainersGatewayNightlyIntegrationTest {
HttpResponse.BodyHandlers.discarding()).statusCode());
}
// The endpoint's gateway answers within its five minutes, and the kernel goes within its one: six minutes, and one
// for the requests between. The Nightly checks' docker-runner group counts it.
@Test
@Timeout(value = 7, unit = TimeUnit.MINUTES)
void endpointsJegConfigCullsAKernelLeftIdle() throws Exception {
String virtualClusterId = virtualCluster();
// The two settings "Jupyter Enterprise Gateway (JEG) configuration options" allow-lists.
String endpointId = endpoint(virtualClusterId, """
{"applicationConfiguration": [{"classification": "jeg-config", "properties": {
"RemoteMappingKernelManager.cull_idle_timeout": "10",
"RemoteMappingKernelManager.cull_interval": "5"}}]}""");
String gateway = gateway(virtualClusterId, endpointId);
String token = sessionToken(virtualClusterId, endpointId);
HttpClient http = HttpClient.newHttpClient();
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\": \"python3\"}")).build(),
HttpResponse.BodyHandlers.ofString());
assertEquals(201, started.statusCode(), started.body());
assertEquals(List.of(JSON.readTree(started.body()).path("id").textValue()),
ids(http, gateway + "/api/kernels", token));
await("the idle kernel culled").atMost(Duration.ofMinutes(1)).pollInterval(Duration.ofSeconds(1))
.until(() -> ids(http, gateway + "/api/kernels", token).isEmpty());
}
// An endpoint of the virtual cluster with configurationOverrides, once it is ACTIVE.
private String endpoint(String virtualClusterId, String configurationOverrides) {
String endpointId = emr().body("""
{"name": "nightly", "type": "JUPYTER_ENTERPRISE_GATEWAY", "releaseLabel": "%s",
"executionRoleArn": "%s", "clientToken": "%s", "configurationOverrides": %s}
""".formatted(RELEASE, ROLE, UUID.randomUUID(), configurationOverrides))
.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")));
return endpointId;
}
// Where the test reaches the endpoint's gateway: its serverUrl's path, on the test's own port, as the profile's
// base URL names another.
private static String gateway(String virtualClusterId, String endpointId) {
String serverUrl = emr().get("/virtualclusters/" + virtualClusterId + "/endpoints/" + endpointId)
.then().extract().path("endpoint.serverUrl");
String path = URI.create(serverUrl).getPath();
assertEquals(EmrContainersService.GATEWAY_PATH + endpointId, path);
return "http://localhost:" + RestAssured.port + path;
}
// Runs code in the kernel and answers its result's text/plain.
private static String execute(WebSocket socket, Messages messages, String session, String code) throws Exception {
return run(socket, messages, session, code, "execute_result", "/content/data/text~1plain");
@@ -1307,7 +1307,11 @@ class EmrContainersServiceTest {
"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/*"}}]}}
"spark.kubernetes.driverEnv.SPARK_DIST_CLASSPATH": "/opt/extra/*"}},
{"classification": "jeg-config", "properties": {
"RemoteMappingKernelManager.cull_idle_timeout": "3600",
"RemoteMappingKernelManager.cull_interval": "60",
"RemoteMappingKernelManager.cull_connected": "true"}}]}}
""".formatted(RELEASE, ROLE, UUID.randomUUID()))).get("id").textValue();
}
@@ -1354,7 +1358,11 @@ class EmrContainersServiceTest {
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));
assertTrue(job.command().get(2).endsWith("exec python3 /tmp/floci-gateway/gateway.py \"$@\""),
job.command().get(2));
// The guide's "Jupyter Enterprise Gateway (JEG) configuration options" allow-lists the first two.
assertEquals(List.of("gateway", "--RemoteMappingKernelManager.cull_idle_timeout=3600",
"--RemoteMappingKernelManager.cull_interval=60"), job.command().subList(3, job.command().size()));
clock.advance(Duration.ofMinutes(3).plusSeconds(15));
gatewayUnanswered.set(null);