feat(emr-serverless): open the live Spark UI from dashboard links (#8890)

With runner-mode docker, GetDashboardForJobRun's link for a Spark run's
attempt that has not ended now opens its driver's Spark UI for real, and
GetResourceDashboard's link does the same for a session's Spark Connect
server, as "For jobs in a running state, the application UI is a live
user interface such as the Spark or Tez web UI" and "While a session is
active, the URL opens the live Apache Spark UI".

Each link opens on a host of its own,
<secret>-4040.emr-serverless-ui.<Floci's host>, through the application
UI proxy EMR's on-cluster UIs use. That proxy moves to core.common
(AppUiProxy, AppUiRoutes, AppUiRoute, AppUiHost), and each service
registers the label its hosts are under. The runner turns the driver's
UI on for every EMR Serverless Spark run, as the release's image turns
it off, publishes port 4040 on the Docker host's loopback interface, and
keeps where Floci reaches it while the container runs.

A run whose logs are not kept in managed storage gets no live UI, as
with logs in S3 alone the application UI is "Not supported". A Hive
run, a run or session that has ended, and every link in the immediate
mode still open Floci's own page, which now says whether the attempt's
logs are in managed storage.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-18 15:41:25 -04:00
1 parent 3ebd1bc38c
commit 3ffec01a76
26 files changed
+1226 -152

No files matched your search

+4 -2
View File
@@ -131,8 +131,10 @@ starts EmrServerlessHiveDockerIntegrationTest EmrHiveStepsNightlyIntegrationTest
EmrNotebookExecutionNightlyIntegrationTest EmrAppUiNightlyIntegrationTest \
&& ecr public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest
# The nightly EmrServerlessSparkConnectNightlyIntegrationTest runs a session's Spark Connect server, and its client, in
# the emr-7.13.0 image, 3.7 GB, the first release with sessions.
starts EmrServerlessSparkConnectNightlyIntegrationTest && ecr public.ecr.aws/emr-serverless/spark/emr-7.13.0:latest
# the emr-7.13.0 image, 3.7 GB, the first release with sessions, and EmrServerlessDashboardNightlyIntegrationTest a job
# run and a session in it, whose dashboards it opens.
starts EmrServerlessSparkConnectNightlyIntegrationTest EmrServerlessDashboardNightlyIntegrationTest \
&& ecr public.ecr.aws/emr-serverless/spark/emr-7.13.0:latest
# The nightly EmrSessionServerNightlyIntegrationTest runs an EMR session's Spark Connect server on an emr-spark-8.1.0
# cluster, Spark 4, sessions needing the AWS runtime for Apache Spark, and its client in that image.
starts EmrSessionServerNightlyIntegrationTest && ecr public.ecr.aws/emr-serverless/spark4/emr-spark-8.1.0:latest
+5 -4
View File
@@ -34,10 +34,11 @@ jobs:
# EmrServerlessCustomImageNightlyIntegrationTest's 85 and 21 for its setup,
# EmrServerlessSparkConnectNightlyIntegrationTest's 30, EmrSessionServerNightlyIntegrationTest's 40,
# EmrHiveStepsNightlyIntegrationTest's five two-minute tests, one five-minute test and six-minute setup,
# EmrNotebookExecutionNightlyIntegrationTest's 40, and EmrAppUiNightlyIntegrationTest's 30, 321 in all. A check
# added, or a bound raised, raises this with it, so a slow check fails with its own message rather than the job
# being cancelled with none.
timeout-minutes: 341
# EmrNotebookExecutionNightlyIntegrationTest's 40, EmrAppUiNightlyIntegrationTest's 30, and
# EmrServerlessDashboardNightlyIntegrationTest's 15, 336 in all. A check added, or a bound raised, raises this with
# it, so a slow check fails with its own message rather than the job being cancelled with none; a hosted runner
# ends any job at 360 minutes, which this stays under.
timeout-minutes: 356
# 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.
if: >-
+34 -10
View File
@@ -143,13 +143,30 @@ runner mode a Spark run executes; see [Running Spark job runs](#running-spark-jo
* **Dashboard**: `GetDashboardForJobRun` gives "a URL that you can use to access the application UIs for a job run",
for the latest attempt or the `attempt` asked for, checked as `GetJobRun` checks it, and, as AWS's, "The URL is
valid for one hour after you generate it". EMR Serverless opens the run's live Spark or Tez UI while it runs and its
Spark History Server or persistent Tez UI once it has ended; Floci keeps neither, so the URL opens a page Floci
serves at `/_aws/emr-serverless/dashboard` on its own address (`base-url`, or `hostname`), with the attempt's
state, its times and where its driver's logs go in S3 and in CloudWatch Logs, kept as the attempt was admitted, so
a later change to the application's monitoring configuration does not move them. The link names the run and is signed
with a key Floci makes as it starts: one changed, or past its hour, or given before Floci restarted, opens a `403`
page asking for a new one, and one whose run has gone a `404`. Like the rest of Floci, the page asks for no
credentials. `accessSystemProfileLogs`, for jobs on Lake Formation, changes nothing.
Spark History Server or persistent Tez UI once it has ended. With `runner-mode` set to `docker`, a link given for a
Spark run's attempt that has not ended opens its driver's Spark UI for real, through Floci, on a host of its own:
`http://<secret>-4040.emr-serverless-ui.<Floci's host and port>/`, the secret 26 random letters and digits that only
this link holds, so the host itself is the link's authority, as the UI takes no AWS credentials. Floci's host must
resolve its subdomains: `localhost` and `localhost.floci.io` do, and Floci's TLS certificate names
`*.emr-serverless-ui.localhost` and `*.emr-serverless-ui.localhost.floci.io`. Requests to the host go on to the
driver's UI, port 4040 of its container, which Docker publishes on the host's loopback interface alone, or which
Floci, in a container on the same network, reaches there. The release's image turns the UI off; Floci turns it on
before the run's own settings, so a run that turns it off again has none. Until the driver runs, and then until its
Spark has started the UI, or for good where the run turned it off, the host answers with a `503` page asking to try
again; once the attempt has ended, with a `404` one; past its hour, or given before Floci restarted, with a `403`
one. A run whose logs are not kept in managed storage,
its `managedPersistenceMonitoringConfiguration`, or else its application's, with `enabled` false, gets no live UI,
as with logs in S3 alone the application UI is "Not supported" ("Otherwise, you can't use the built-in application
UIs"). Floci keeps no Spark History Server for a run that has ended, and runs no Tez UI, so the link for an ended
run, a Hive run, one without managed storage, or any in the `immediate` mode, opens a page Floci serves at
`/_aws/emr-serverless/dashboard` on its own address (`base-url`, or `hostname`), with the attempt's state, its times,
where its driver's logs go in S3 and in CloudWatch Logs, and whether they are kept in managed storage, kept as the
attempt was admitted, so a later change to the application's monitoring configuration does not move them. That link
names the run and is signed with a key Floci makes as it starts: one changed, or past its hour, or given before
Floci restarted, opens a `403` page asking for a new one, and one whose run has gone a `404`. Like the rest of Floci,
neither link asks for credentials. AWS's link, by a user's report, opens a limited number of times ("This URL has
already been used the maximum number of times. Please generate a new URL."); Floci's open as often as asked within
their hour. `accessSystemProfileLogs`, for jobs on Lake Formation, changes nothing.
## Sessions
@@ -193,8 +210,11 @@ and its lifecycle but runs no driver for it.
* **ListSessions** returns the newest sessions first, as `ListJobRuns` orders runs, filtered by `states`,
`createdAtAfter` and `createdAtBefore`, at most 50 per page, grouped by state as `ListJobRuns` groups runs.
* **GetResourceDashboard** takes a `resourceType` of `SESSION`, the only one, and gives a link like
`GetDashboardForJobRun`'s, valid for an hour, to a page about the session on Floci's address, which stands in for
the session's Spark UI or Spark History Server. `accessSystemProfileLogs` changes nothing.
`GetDashboardForJobRun`'s, valid for an hour: "While a session is active, the URL opens the live Apache Spark UI".
With `runner-mode` set to `docker`, a link given before the session has ended, or begun to, opens its Spark Connect
server's Spark UI, as a run's link opens its driver's (see [Running a session's Spark Connect
server](#running-a-sessions-spark-connect-server)); any other opens a page about the session on Floci's address,
which stands in for the session's Spark UI or Spark History Server. `accessSystemProfileLogs` changes nothing.
A state machine drives applications and job runs through the `emr-serverless:` integrations, `.sync`
included; see [Step Functions: Amazon EMR Serverless tasks](step-functions.md#amazon-emr-serverless-tasks).
@@ -236,7 +256,11 @@ The server's port is published on the Docker host's loopback interface only, and
24 hours count from when the server answers.
* **Logs**: no source gives where a session's driver logs go, so Floci sends the server's output to its own log only,
not to the application's monitoring configuration.
* **Spark UI**: `GetResourceDashboard` still links to Floci's page about the session, not to the server's Spark UI.
* **Spark UI**: `GetResourceDashboard`'s link opens the server's Spark UI on a host of its own, as a run's link opens
its driver's (see **Dashboard** under job runs): port 4040 of the server's container, published on the host's
loopback interface alone. Its host answers with a `503` page until the server's container runs, and with a `404` one
once the session has ended. Floci keeps no Spark History Server for a session that has ended, whose link opens
Floci's page about it.
## Running Spark job runs
@@ -79,6 +79,7 @@ public class TlsConfigSource implements ConfigSource {
"*.execute-api.localhost.localstack.cloud",
"*.cloudfront.localhost.floci.io", "*.cloudfront.localhost",
"*.emrappui.localhost.floci.io", "*.emrappui.localhost",
"*.emr-serverless-ui.localhost.floci.io", "*.emr-serverless-ui.localhost",
"host.docker.internal"));
for (String region : AwsRegions.KNOWN_IDS.stream().sorted().toList()) {
sans.add("*.dkr.ecr." + region + ".localhost.floci.io");
@@ -0,0 +1,58 @@
package io.floci.aws.core.common;
import java.net.URI;
import java.security.SecureRandom;
import java.util.Locale;
/**
* The host of an application UI Floci opens through {@link AppUiProxy}, {@code <secret>-<port>.<label>.<Floci's host>}:
* the secret of the link, which is its authority, as no request to the interface carries AWS credentials; the port of
* the interface; and, after the label of the service whose interface it is ({@link AppUiRoutes#hostLabel}), Floci's
* own host and port, which {@code rest} holds from the dot before the label.
*/
public record AppUiHost(String secret, int port, String rest) {
/** A secret's length: 26 characters of base32, 130 random bits. */
public static final int SECRET_LENGTH = 26;
// In lower case, as a host name is read without case.
private static final String BASE32 = "abcdefghijklmnopqrstuvwxyz234567";
/** The host {@code hostHeader} names, or null where it is not an interface's host under {@code label}. */
public static AppUiHost parse(String hostHeader, String label) {
String host = hostHeader.toLowerCase(Locale.ROOT);
int dot = host.indexOf('.');
int dash = dot > 0 ? host.lastIndexOf('-', dot) : -1;
if (dash != SECRET_LENGTH || !host.startsWith(label + ".", dot + 1)) {
return null;
}
try {
return new AppUiHost(host.substring(0, dash), Integer.parseInt(host.substring(dash + 1, dot)),
host.substring(dot));
} catch (NumberFormatException e) {
return null;
}
}
/** A new link's secret, drawn from {@code random}. */
public static String newSecret(SecureRandom random) {
StringBuilder secret = new StringBuilder(SECRET_LENGTH);
for (int i = 0; i < SECRET_LENGTH; i++) {
secret.append(BASE32.charAt(random.nextInt(BASE32.length())));
}
return secret.toString();
}
/**
* The URL of {@code path} on the interface on {@code port} of the link {@code secret}, under {@code label} on
* Floci's {@code baseUrl}.
*/
public static String url(String baseUrl, String secret, int port, String label, String path) {
URI base = URI.create(baseUrl);
return base.getScheme() + "://" + secret + "-" + port + "." + label + "." + base.getRawAuthority() + path;
}
/** The origin of the link's interface on {@code otherPort}, as a browser reaches it over {@code scheme}. */
public String origin(String scheme, int otherPort) {
return scheme + "://" + secret + "-" + otherPort + rest;
}
}
@@ -1,7 +1,5 @@
package io.floci.aws.services.emr;
package io.floci.aws.core.common;
import io.floci.aws.core.common.Html;
import io.floci.aws.core.common.ServiceConfigAccess;
import io.vertx.core.MultiMap;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
@@ -17,9 +15,12 @@ import io.vertx.core.net.SocketAddress;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import jakarta.annotation.PreDestroy;
import jakarta.annotation.Priority;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import jakarta.interceptor.Interceptor;
import org.jboss.logging.Logger;
import java.net.URI;
@@ -31,16 +32,17 @@ import java.util.Map;
import java.util.Set;
/**
* The on-cluster application UIs Floci opens for real ({@link EmrAppUiService}): a request to an interface's own host,
* {@code <secret>-<port>.emrappui.<Floci's host>}, goes on to that port of the cluster's primary node, and its answer
* comes back with each link to one of the node's interfaces, which its daemons write by the node's name, made a link
* to that interface's own host. The secret in the host is the link's authority, as no request to the interface carries
* AWS credentials; one that is not this process's, or whose hour has passed, is answered with a page saying so.
* The application UIs Floci opens for real, those of an EMR cluster's primary node and of an EMR Serverless run's
* driver among them: a request to an interface's own host, {@link AppUiHost}, goes on to where the service whose label
* the host holds finds that interface ({@link AppUiRoutes}), and its answer comes back with each link to one of its
* sibling interfaces, which their daemons write by their own address, made a link to that interface's own host. The
* secret in the host is the link's authority, as no request to the interface carries AWS credentials; one that is not
* this process's, or whose hour has passed, is answered with a page saying so.
*/
@ApplicationScoped
public class EmrAppUiProxy {
public class AppUiProxy {
private static final Logger LOG = Logger.getLogger(EmrAppUiProxy.class);
private static final Logger LOG = Logger.getLogger(AppUiProxy.class);
// What does not go on: the connection's own headers, the host, which the interface is asked for under the
// browser's, and the encodings the browser takes, as only an answer that is not compressed can have its links made
@@ -56,20 +58,19 @@ public class EmrAppUiProxy {
// How long the interface may send nothing, its answer or the rest of it, before the request is given up.
private static final Duration IDLE_TIMEOUT = Duration.ofMinutes(1);
private final EmrAppUiService appUis;
private final List<AppUiRoutes> services;
private final ServiceConfigAccess serviceConfigAccess;
private final Vertx vertx;
private final HttpClient client;
private final Duration idleTimeout;
@Inject
public EmrAppUiProxy(EmrAppUiService appUis, ServiceConfigAccess serviceConfigAccess, Vertx vertx) {
this(appUis, serviceConfigAccess, vertx, IDLE_TIMEOUT);
public AppUiProxy(Instance<AppUiRoutes> services, ServiceConfigAccess serviceConfigAccess, Vertx vertx) {
this(services.stream().toList(), serviceConfigAccess, vertx, IDLE_TIMEOUT);
}
EmrAppUiProxy(EmrAppUiService appUis, ServiceConfigAccess serviceConfigAccess, Vertx vertx,
Duration idleTimeout) {
this.appUis = appUis;
AppUiProxy(List<AppUiRoutes> services, ServiceConfigAccess serviceConfigAccess, Vertx vertx, Duration idleTimeout) {
this.services = services;
this.serviceConfigAccess = serviceConfigAccess;
this.vertx = vertx;
this.idleTimeout = idleTimeout;
@@ -81,26 +82,28 @@ public class EmrAppUiProxy {
client.close();
}
void register(@Observes Router router) {
// Ahead of the routes the other observers add, whose paths an interface's own may be: the ResourceManager's REST
// answers are under /ws/, where API Gateway's WebSocket route takes every request. A request to any other host goes
// on to them.
void register(@Observes @Priority(Interceptor.Priority.APPLICATION) Router router) {
router.route().handler(this::handle);
}
void handle(RoutingContext context) {
HttpServerRequest request = context.request();
String hostHeader = request.getHeader("host");
AppUiRoutes service = hostHeader != null ? serviceOf(hostHeader) : null;
// This route runs ahead of the filter that refuses a disabled service, so it checks for itself.
if (hostHeader == null || !hostHeader.toLowerCase(Locale.ROOT).contains("." + EmrAppUiService.UI_HOST + ".")
|| !serviceConfigAccess.isEnabled("emr")) {
if (service == null || !serviceConfigAccess.isEnabled(service.service())) {
context.next();
return;
}
request.pause();
// Finding the interface may ask Docker where it is, so off the event loop.
vertx.<EmrAppUiService.UiRoute>executeBlocking(() -> appUis.route(hostHeader, request.scheme()), false)
vertx.<AppUiRoute>executeBlocking(() -> service.route(hostHeader, request.scheme()), false)
.onComplete(routed -> {
if (routed.failed()) {
LOG.warnv(routed.cause(), "EMR application UI request to {0} could not be routed",
hostHeader);
LOG.warnv(routed.cause(), "Application UI request to {0} could not be routed", hostHeader);
refuse(request, 502, "The interface could not be reached.");
} else if (routed.result() == null) {
request.resume();
@@ -113,7 +116,18 @@ public class EmrAppUiProxy {
});
}
private void forward(HttpServerRequest request, String hostHeader, EmrAppUiService.UiRoute route) {
// The service whose label the host holds, or null where it holds none.
private AppUiRoutes serviceOf(String hostHeader) {
String host = hostHeader.toLowerCase(Locale.ROOT);
for (AppUiRoutes service : services) {
if (host.contains("." + service.hostLabel() + ".")) {
return service;
}
}
return null;
}
private void forward(HttpServerRequest request, String hostHeader, AppUiRoute route) {
URI authority = URI.create("http://" + hostHeader);
RequestOptions options = new RequestOptions().setMethod(request.method())
.setServer(SocketAddress.inetSocketAddress(route.port(), route.host()))
@@ -131,7 +145,8 @@ public class EmrAppUiProxy {
client.request(options).onComplete(opened -> {
if (opened.failed()) {
route.unreachable().run();
refuse(request, 502, "The cluster's interface did not answer: " + opened.cause().getMessage());
refuse(request, route.unansweredStatus(), route.unanswered() != null ? route.unanswered()
: "The interface did not answer: " + opened.cause().getMessage());
return;
}
HttpClientRequest upstream = opened.result();
@@ -148,7 +163,7 @@ public class EmrAppUiProxy {
if (response.headWritten()) {
response.reset();
} else {
refuse(request, 502, "The cluster's interface did not answer: "
refuse(request, 502, "The interface did not answer: "
+ answered.cause().getMessage());
}
return;
@@ -0,0 +1,33 @@
package io.floci.aws.core.common;
import java.util.Map;
/**
* Where a request to an application UI's host goes ({@link AppUiProxy}): the interface's address; each link to one of
* its sibling interfaces its pages hold, as their daemons write it, and as the browser reaches that interface; what
* to do when the address does not answer, and how such a request is answered, {@code unansweredStatus} with a page
* saying {@code unanswered}, or, where that is null, a {@code 502} saying why; else why the request is refused, with
* its HTTP status.
*/
public record AppUiRoute(String host, int port, Map<String, String> rewrites, Runnable unreachable, int status,
String refusal, int unansweredStatus, String unanswered) {
/** A route whose interface, when it does not answer, is a {@code 502}. */
public AppUiRoute(String host, int port, Map<String, String> rewrites, Runnable unreachable, int status,
String refusal) {
this(host, port, rewrites, unreachable, status, refusal, 502, null);
}
/** A request refused with {@code status}, its page saying {@code refusal}. */
public static AppUiRoute refused(int status, String refusal) {
return new AppUiRoute(null, 0, Map.of(), () -> { }, status, refusal);
}
/**
* A request to the interface at {@code host} and {@code port}, whose pages link to no sibling, answered with
* {@code unansweredStatus} and a page saying {@code unanswered} while the interface does not answer.
*/
public static AppUiRoute to(String host, int port, int unansweredStatus, String unanswered) {
return new AppUiRoute(host, port, Map.of(), () -> { }, 0, null, unansweredStatus, unanswered);
}
}
@@ -0,0 +1,20 @@
package io.floci.aws.core.common;
/**
* A service's application UIs that Floci opens for real, each on a host of its own, {@link AppUiHost}, which
* {@link AppUiProxy} sends on to the interface.
*/
public interface AppUiRoutes {
/** The label under Floci's host the hosts of the service's interfaces are in. */
String hostLabel();
/** The service whose interfaces these are, which must be enabled for a request to one to go on. */
String service();
/**
* The route of a request whose {@code Host} is {@code hostHeader}, over {@code scheme}; null where the host is none
* of the service's links. Called off the event loop, as finding an interface may ask Docker.
*/
AppUiRoute route(String hostHeader, String scheme);
}
@@ -2,6 +2,9 @@ package io.floci.aws.services.emr;
import com.fasterxml.jackson.core.type.TypeReference;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AppUiHost;
import io.floci.aws.core.common.AppUiRoute;
import io.floci.aws.core.common.AppUiRoutes;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.LinkSigner;
import io.floci.aws.core.common.RegionResolver;
@@ -18,7 +21,6 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
@@ -29,7 +31,6 @@ import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
@@ -46,15 +47,15 @@ import java.util.regex.Pattern;
* In the docker runner mode, an on-cluster UI that runs on the cluster's primary node, its ResourceManager, an
* application master through it, its MapReduce JobHistory server, the NodeManager of a primary node that works, the
* Spark History Server of a cluster with Spark, or the YARN timeline server and the Tez UI of one with Hadoop and Tez,
* opens for real through {@link EmrAppUiProxy}, on a host of its own under {@link #UI_HOST}, as AWS's are under
* "emrappui-prod.us-east-1.amazonaws.com" (Management Guide, "View Amazon EMR application history"). A persistent
* application UI opens the same interfaces while its cluster runs, and, for the 30 days after it ends, its kept
* history's, served by a container of its own. Any other link opens a page of Floci's own about the cluster
* ({@link EmrAppUiController}). Either link is valid for {@link #VALIDITY}: the page's is signed with a key of this
* process, and a proxied interface's host holds a secret this process gave it.
* opens for real through Floci's application UI proxy ({@link AppUiRoutes}), on a host of its own under
* {@link #UI_HOST}, as AWS's are under "emrappui-prod.us-east-1.amazonaws.com" (Management Guide, "View Amazon EMR
* application history"). A persistent application UI opens the same interfaces while its cluster runs, and, for the
* 30 days after it ends, its kept history's, served by a container of its own. Any other link opens a page of
* Floci's own about the cluster ({@link EmrAppUiController}). Either link is valid for {@link #VALIDITY}: the page's
* is signed with a key of this process, and a proxied interface's host holds a secret this process gave it.
*/
@ApplicationScoped
public class EmrAppUiService {
public class EmrAppUiService implements AppUiRoutes {
/** Where Floci serves the page a presigned URL opens. */
static final String PATH = "/_aws/emr/app-ui";
@@ -72,9 +73,6 @@ public class EmrAppUiService {
static final String ACTIVE = "ACTIVE";
/** The label under Floci's host name an on-cluster UI's own host is in. */
static final String UI_HOST = "emrappui";
// A link's secret: 26 characters of base32, 130 random bits, in lower case, as a host name is read without case.
private static final int SECRET_LENGTH = 26;
private static final String BASE32 = "abcdefghijklmnopqrstuvwxyz234567";
static final String RESOURCE_MANAGER = "ResourceManager";
static final String APPLICATION_MASTER = "ApplicationMaster";
static final String JOB_HISTORY_SERVER = "JobHistoryServer";
@@ -323,9 +321,7 @@ public class EmrAppUiService {
clusters.startPrimaryNode(cluster.getId());
}
}
URI base = URI.create(baseUrl);
return new Presigned(base.getScheme() + "://" + secret + "-" + port + "." + UI_HOST + "."
+ base.getRawAuthority() + landing, ready);
return new Presigned(AppUiHost.url(baseUrl, secret, port, UI_HOST, landing), ready);
}
// Checks, once the link has expired, whether the container serving the cluster's kept history may stop.
@@ -403,11 +399,7 @@ public class EmrAppUiService {
}
private String secret() {
StringBuilder secret = new StringBuilder(SECRET_LENGTH);
for (int i = 0; i < SECRET_LENGTH; i++) {
secret.append(BASE32.charAt(random.nextInt(BASE32.length())));
}
return secret.toString();
return AppUiHost.newSecret(random);
}
/**
@@ -423,43 +415,35 @@ public class EmrAppUiService {
private record Found(ContainerLifecycleManager.EndpointInfo endpoint, Instant at) {
}
/**
* Where a request to a proxied interface's host goes: the interface's address on the primary node, and each link
* to one of the node's interfaces its pages hold, by the node's name, as the browser reaches that interface; else
* why it is refused, with its HTTP status.
*/
public record UiRoute(String host, int port, Map<String, String> rewrites, Runnable unreachable, int status,
String refusal) {
@Override
public String hostLabel() {
return UI_HOST;
}
static UiRoute refused(int status, String refusal) {
return new UiRoute(null, 0, Map.of(), () -> { }, status, refusal);
}
@Override
public String service() {
return "emr";
}
/**
* The route of a request whose {@code Host} is {@code hostHeader}, over {@code scheme}; null where the host is not
* a proxied interface's, {@code <secret>-<port>.}{@value #UI_HOST}{@code .<Floci's host>}.
* The route of a request whose {@code Host} is {@code hostHeader}, over {@code scheme}: to the interface's address
* on the primary node, with each link to one of the node's interfaces its pages hold, by the node's name, made the
* browser's; null where the host is not a proxied interface's, {@code <secret>-<port>.}{@value #UI_HOST}{@code
* .<Floci's host>}.
*/
public UiRoute route(String hostHeader, String scheme) {
String host = hostHeader.toLowerCase(Locale.ROOT);
int dot = host.indexOf('.');
int dash = dot > 0 ? host.lastIndexOf('-', dot) : -1;
if (dash != SECRET_LENGTH || !host.startsWith(UI_HOST + ".", dot + 1)) {
@Override
public AppUiRoute route(String hostHeader, String scheme) {
AppUiHost host = AppUiHost.parse(hostHeader, UI_HOST);
if (host == null) {
return null;
}
String secret = host.substring(0, dash);
int port;
try {
port = Integer.parseInt(host.substring(dash + 1, dot));
} catch (NumberFormatException e) {
return null;
}
Grant grant = grants.get(secret);
int port = host.port();
Grant grant = grants.get(host.secret());
if (grant == null || !clock.instant().isBefore(grant.expires())) {
return UiRoute.refused(403, EmrAppUiController.INVALID);
return AppUiRoute.refused(403, EmrAppUiController.INVALID);
}
if (!grant.ports().contains(port)) {
return UiRoute.refused(404, NO_SUCH_INTERFACE);
return AppUiRoute.refused(404, NO_SUCH_INTERFACE);
}
// A live interface is there only while its cluster runs or waits, and its kept history only once it has ended,
// for its 30 days: outside them, the port found for it is no longer the cluster's own.
@@ -469,11 +453,11 @@ public class EmrAppUiService {
boolean up = cluster != null && (EmrClusterLifecycle.RUNNING.equals(cluster.getState())
|| EmrClusterLifecycle.WAITING.equals(cluster.getState()));
if (!grant.history() && !up) {
return UiRoute.refused(404, String.format(CLUSTER_ENDED, grant.clusterId()));
return AppUiRoute.refused(404, String.format(CLUSTER_ENDED, grant.clusterId()));
}
if (grant.history() && (cluster == null || up || cluster.getEndDateTime() == null
|| !now.isBefore(cluster.getEndDateTime().plus(EmrService.HISTORY_KEPT)))) {
return UiRoute.refused(404, String.format(HISTORY_GONE, grant.clusterId()));
return AppUiRoute.refused(404, String.format(HISTORY_GONE, grant.clusterId()));
}
Found found = grant.endpoints().get(port);
if (found == null || !now.isBefore(found.at().plus(ENDPOINT_RECHECK))) {
@@ -482,20 +466,19 @@ public class EmrAppUiService {
: clusters.webInterface(grant.clusterId(), port)).orElse(null);
if (endpoint == null) {
grant.endpoints().remove(port);
return UiRoute.refused(503, grant.history() ? HISTORY_NOT_READY : NOT_READY);
return AppUiRoute.refused(503, grant.history() ? HISTORY_NOT_READY : NOT_READY);
}
found = new Found(endpoint, now);
grant.endpoints().put(port, found);
}
// The node's daemons write links to one another by the node's name, which the browser reaches as each
// interface's own host, under this one's Floci host and port.
String rest = host.substring(dot);
Map<String, String> rewrites = new LinkedHashMap<>();
for (int other : grant.ports()) {
rewrites.put("http://" + grant.primaryHost() + ":" + other, scheme + "://" + secret + "-" + other + rest);
rewrites.put("http://" + grant.primaryHost() + ":" + other, host.origin(scheme, other));
}
Found routed = found;
return new UiRoute(found.endpoint().host(), found.endpoint().port(), rewrites,
return new AppUiRoute(found.endpoint().host(), found.endpoint().port(), rewrites,
() -> grant.endpoints().remove(port, routed), 0, null);
}
@@ -0,0 +1,192 @@
package io.floci.aws.services.emrserverless;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AppUiHost;
import io.floci.aws.core.common.AppUiRoute;
import io.floci.aws.core.common.AppUiRoutes;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
import io.floci.aws.services.emrserverless.model.JobRun;
import io.floci.aws.services.emrserverless.model.Session;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Instant;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* The application UIs a {@code GetDashboardForJobRun} or {@code GetResourceDashboard} link opens. "For jobs in a
* running state, the application UI is a live user interface such as the Spark or Tez web UI", and "While a session is
* active, the URL opens the live Apache Spark UI". In the docker runner mode, where Floci runs a Spark run's driver, or
* a session's Spark Connect server, in a container, a link given before it has ended opens that driver's Spark UI for
* real, on a host of its own under {@link #UI_HOST} ({@link AppUiHost}), which Floci's application UI proxy sends on
* to the driver's container while it runs, on a network where that container has an address of its own. The secret in
* the host is the link's authority, as no request to the UI carries AWS credentials, and is valid for
* {@link EmrServerlessDashboards#VALIDITY}, as "The URL is valid for one hour after you generate it". Any other link, a
* Hive run's, that of a run whose logs are not in managed storage, one given once the run or session has ended, or any
* in the immediate runner mode, opens a page of Floci's own about it ({@link EmrServerlessDashboards}).
*/
@ApplicationScoped
public class EmrServerlessAppUis implements AppUiRoutes {
/** The label under Floci's host name a driver's UI's own host is in. */
static final String UI_HOST = "emr-serverless-ui";
// No source gives AWS's wording for these; they are Floci's.
static final String NO_SUCH_INTERFACE = "This link opens none of the driver's interfaces on that port.";
static final String NOT_RUNNING = "The driver is not running yet. Try again in a moment.";
static final String NOT_ANSWERING = "The driver's Spark UI is not answering yet: it starts with the driver's Spark,"
+ " unless the run turns it off (spark.ui.enabled). Try again in a moment.";
static final String RUN_ENDED = "Attempt %d of job run %s is no longer running, and its live Spark UI is there only"
+ " while it runs.";
static final String SESSION_ENDED = "Session %s has ended, and its live Spark UI is there only while it is active.";
private static final Set<String> SESSION_ENDING = Set.of(EmrServerlessSessionService.STATE_TERMINATING,
EmrServerlessSessionService.STATE_TERMINATED, EmrServerlessSessionService.STATE_FAILED);
private final EmrServerlessDashboards dashboards;
private final EmrServerlessJobRunService jobRuns;
private final EmrServerlessSessionService sessions;
private final RegionResolver regionResolver;
private final Clock clock;
private final String baseUrl;
// The links to drivers' UIs this process has given, by their secret, until they expire.
private final Map<String, EmrServerlessDashboards.Link> grants = new ConcurrentHashMap<>();
private final SecureRandom random = new SecureRandom();
@Inject
public EmrServerlessAppUis(EmrServerlessDashboards dashboards, EmrServerlessJobRunService jobRuns,
EmrServerlessSessionService sessions, RegionResolver regionResolver,
EmulatorConfig config, Clock clock) {
this(dashboards, jobRuns, sessions, regionResolver, config.effectiveBaseUrl(), clock);
}
EmrServerlessAppUis(EmrServerlessDashboards dashboards, EmrServerlessJobRunService jobRuns,
EmrServerlessSessionService sessions, RegionResolver regionResolver, String baseUrl,
Clock clock) {
this.dashboards = dashboards;
this.jobRuns = jobRuns;
this.sessions = sessions;
this.regionResolver = regionResolver;
this.clock = clock;
this.baseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl;
}
/**
* The link GetDashboardForJobRun gives for a run's attempt, which must be there: its driver's live Spark UI, for a
* Spark run in the docker runner mode whose attempt has not ended and whose logs are in managed storage; else
* Floci's page about the attempt.
*/
public String jobRunUrl(String applicationId, String jobRunId, int attempt) {
EmrServerlessJobRunService.DashboardView view = jobRuns.dashboard(applicationId, jobRunId, attempt);
JobRun run = view.run();
String accountId = regionResolver.getAccountId();
String region = regionResolver.getRegion();
boolean live = jobRuns.servesDriverUis() && run.getJobDriver() != null
&& run.getJobDriver().getSparkSubmit() != null && !EmrServerlessJobRunService.isTerminal(run)
&& view.logs().inManagedStorage();
if (!live) {
return dashboards.url(accountId, region, applicationId, jobRunId, attempt);
}
return driverUiUrl(new EmrServerlessDashboards.Link(accountId, region, applicationId, jobRunId, null, attempt,
expiry()));
}
/**
* The link GetResourceDashboard gives for a session: its Spark Connect server's live Spark UI, in the docker runner
* mode while the session has not ended or begun to; else Floci's page about the session.
*/
public String sessionUrl(String applicationId, Session session) {
String accountId = regionResolver.getAccountId();
String region = regionResolver.getRegion();
if (!jobRuns.servesDriverUis() || SESSION_ENDING.contains(session.getState())) {
return dashboards.sessionUrl(accountId, region, applicationId, session.getSessionId());
}
return driverUiUrl(new EmrServerlessDashboards.Link(accountId, region, applicationId, null,
session.getSessionId(), 0, expiry()));
}
private String driverUiUrl(EmrServerlessDashboards.Link link) {
long now = clock.instant().getEpochSecond();
grants.values().removeIf(grant -> now >= grant.expires());
String secret = AppUiHost.newSecret(random);
grants.put(secret, link);
return AppUiHost.url(baseUrl, secret, SparkExecutors.DRIVER_UI_PORT, UI_HOST, "/");
}
private long expiry() {
return clock.instant().plus(EmrServerlessDashboards.VALIDITY).getEpochSecond();
}
@Override
public String hostLabel() {
return UI_HOST;
}
@Override
public String service() {
return EmrServerlessJobRunService.SERVICE;
}
/**
* The route of a request whose {@code Host} is {@code hostHeader}: to the driver's Spark UI while the run's
* attempt, or the session, has it running; null where the host is not a driver's UI's, {@code
* <secret>-<port>.}{@value #UI_HOST}{@code .<Floci's host>}.
*/
@Override
public AppUiRoute route(String hostHeader, String scheme) {
AppUiHost host = AppUiHost.parse(hostHeader, UI_HOST);
if (host == null) {
return null;
}
EmrServerlessDashboards.Link link = grants.get(host.secret());
if (link == null || clock.instant().getEpochSecond() >= link.expires()) {
return AppUiRoute.refused(403, EmrServerlessDashboardController.INVALID);
}
if (host.port() != SparkExecutors.DRIVER_UI_PORT) {
return AppUiRoute.refused(404, NO_SUCH_INTERFACE);
}
try {
return RequestScopes.callAs(link.accountId(), link.region(),
() -> link.jobRunId() != null ? runRoute(link) : sessionRoute(link));
} catch (AwsException e) {
// The run, its application or the session has gone.
return AppUiRoute.refused(404, e.getMessage());
}
}
private AppUiRoute runRoute(EmrServerlessDashboards.Link link) {
JobRun run = jobRuns.dashboard(link.applicationId(), link.jobRunId(), link.attempt()).run();
if (EmrServerlessJobRunService.isTerminal(run)) {
return AppUiRoute.refused(404, String.format(RUN_ENDED, link.attempt(), link.jobRunId()));
}
return driverUi(link.jobRunId()).orElseGet(() -> AppUiRoute.refused(503, NOT_RUNNING));
}
// A session that is ending may still have its server running: its UI goes with the server.
private AppUiRoute sessionRoute(EmrServerlessDashboards.Link link) {
Session session = sessions.getSession(link.applicationId(), link.sessionId());
boolean ended = !EmrServerlessSessionService.STATE_TERMINATING.equals(session.getState())
&& SESSION_ENDING.contains(session.getState());
Optional<AppUiRoute> driver = ended ? Optional.empty() : driverUi(link.sessionId());
if (driver.isPresent()) {
return driver.get();
}
return SESSION_ENDING.contains(session.getState())
? AppUiRoute.refused(404, String.format(SESSION_ENDED, link.sessionId()))
: AppUiRoute.refused(503, NOT_RUNNING);
}
private Optional<AppUiRoute> driverUi(String runId) {
SparkJobRunner runner = jobRuns.containerRunner();
Optional<ContainerLifecycleManager.EndpointInfo> endpoint = runner != null ? runner.driverUi(runId)
: Optional.empty();
// Its container runs before its Spark has started its UI.
return endpoint.map(found -> AppUiRoute.to(found.host(), found.port(), 503, NOT_ANSWERING));
}
}
@@ -2,7 +2,6 @@ package io.floci.aws.services.emrserverless;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.Pagination;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.SparkConnectEndpoint;
import io.floci.aws.services.emrserverless.model.Application;
import io.floci.aws.services.emrserverless.model.ApplicationSummary;
@@ -59,18 +58,15 @@ public class EmrServerlessController {
private final EmrServerlessService service;
private final EmrServerlessJobRunService jobRuns;
private final EmrServerlessSessionService sessions;
private final EmrServerlessDashboards dashboards;
private final RegionResolver regionResolver;
private final EmrServerlessAppUis appUis;
@Inject
public EmrServerlessController(EmrServerlessService service, EmrServerlessJobRunService jobRuns,
EmrServerlessSessionService sessions, EmrServerlessDashboards dashboards,
RegionResolver regionResolver) {
EmrServerlessSessionService sessions, EmrServerlessAppUis appUis) {
this.service = service;
this.jobRuns = jobRuns;
this.sessions = sessions;
this.dashboards = dashboards;
this.regionResolver = regionResolver;
this.appUis = appUis;
}
@POST
@@ -189,7 +185,7 @@ public class EmrServerlessController {
/**
* The link to a run's application UI, for the attempt asked for or else the latest, the run and attempt checked as
* GetJobRun checks them ({@link EmrServerlessDashboards}). {@code accessSystemProfileLogs} is for jobs on Lake
* GetJobRun checks them ({@link EmrServerlessAppUis}). {@code accessSystemProfileLogs} is for jobs on Lake
* Formation, which Floci runs none of, so it changes nothing.
*/
@GET
@@ -199,8 +195,7 @@ public class EmrServerlessController {
@QueryParam("attempt") String attempt) {
JobRun run = jobRuns.getJobRun(applicationId, jobRunId, EmrServerlessJobRunService.parseAttempt(attempt));
GetDashboardForJobRunResponse response = new GetDashboardForJobRunResponse();
response.setUrl(dashboards.url(regionResolver.getAccountId(), regionResolver.getRegion(), applicationId,
jobRunId, run.getAttempt() != null ? run.getAttempt() : 1));
response.setUrl(appUis.jobRunUrl(applicationId, jobRunId, run.getAttempt() != null ? run.getAttempt() : 1));
return response;
}
@@ -294,7 +289,7 @@ public class EmrServerlessController {
}
/**
* The link to a session's application UI ({@link EmrServerlessDashboards}). {@code accessSystemProfileLogs} is for
* The link to a session's application UI ({@link EmrServerlessAppUis}). {@code accessSystemProfileLogs} is for
* sessions on Lake Formation, which Floci runs none of, so it changes nothing.
*/
@GET
@@ -304,8 +299,7 @@ public class EmrServerlessController {
@QueryParam("resourceType") String resourceType) {
Session session = sessions.dashboardResource(applicationId, resourceId, resourceType);
GetResourceDashboardResponse response = new GetResourceDashboardResponse();
response.setUrl(dashboards.sessionUrl(regionResolver.getAccountId(), regionResolver.getRegion(),
applicationId, session.getSessionId()));
response.setUrl(appUis.sessionUrl(applicationId, session));
return response;
}
}
@@ -18,11 +18,12 @@ import java.util.ArrayList;
import java.util.List;
/**
* The page a {@code GetDashboardForJobRun} or {@code GetResourceDashboard} link opens
* ({@link EmrServerlessDashboards}). EMR Serverless opens the run's live Spark or Tez UI while it runs and its Spark
* History Server or persistent Tez UI once it has ended, and a session's live Spark UI or Spark History Server
* likewise; Floci keeps neither, so the page shows the attempt as GetJobRun gives it and where its driver's logs go, as
* it was admitted, or the session as GetSession gives it. A link that is not one of this process's, or whose hour has
* The page a {@code GetDashboardForJobRun} or {@code GetResourceDashboard} link opens where it opens no live Spark UI
* ({@link EmrServerlessAppUis}, {@link EmrServerlessDashboards}). EMR Serverless opens the run's live Spark or Tez UI
* while it runs and its Spark History Server or persistent Tez UI once it has ended, and a session's live Spark UI or
* Spark History Server likewise; Floci opens a live Spark UI only in the docker runner mode, so elsewhere the page
* shows the attempt as GetJobRun gives it and where its driver's logs go, as it was admitted, or the session as
* GetSession gives it. A link that is not one of this process's, or whose hour has
* passed, opens a refusal instead, and so does one whose run or session has gone. Like the rest of Floci the page takes
* no AWS credentials: the link is all it asks for.
*/
@@ -32,10 +33,12 @@ public class EmrServerlessDashboardController {
// No source gives AWS's wording for these; they are Floci's.
static final String INVALID = "This dashboard link is not valid, or its hour has passed. Call"
+ " GetDashboardForJobRun or GetResourceDashboard for a new one.";
static final String NO_UI = "Floci keeps no Spark UI, Tez UI or Spark History Server for a job run, so this page"
static final String NO_UI = "Floci opens a job run's live Spark UI only while a Spark run runs in the docker"
+ " runner mode with its logs in managed storage, and keeps no Tez UI or Spark History Server, so this page"
+ " stands in for the application UI EMR Serverless opens. The driver's output is in its logs.";
static final String NO_SESSION_UI = "Floci keeps no Spark UI or Spark History Server for a session, and runs no"
+ " Spark driver for one, so this page stands in for the application UI EMR Serverless opens.";
static final String NO_SESSION_UI = "Floci opens a session's live Spark UI only while its Spark Connect server runs"
+ " in the docker runner mode, and keeps no Spark History Server, so this page stands in for the"
+ " application UI EMR Serverless opens.";
private final EmrServerlessDashboards dashboards;
private final EmrServerlessJobRunService jobRuns;
@@ -99,6 +102,7 @@ public class EmrServerlessDashboardController {
Html.row(lines, "Driver logs in CloudWatch Logs", view.logs().logGroup());
Html.row(lines, "Driver stdout stream", view.logs().stdoutStream());
Html.row(lines, "Driver stderr stream", view.logs().stderrStream());
Html.row(lines, "Logs in managed storage", view.logs().inManagedStorage() ? "Yes" : "No");
lines.add("</table>");
lines.add("<p>" + Html.escape(NO_UI) + "</p>");
return lines;
@@ -12,9 +12,9 @@ import java.time.Duration;
/**
* The links {@code GetDashboardForJobRun} gives, "a URL that you can use to access the application UIs for a job run",
* and {@code GetResourceDashboard} gives for a session. Each "is valid for one hour after you generate it. To access
* the application UI after that hour elapses, you must invoke the API again to generate a new URL." Floci keeps no
* Spark UI or Spark History Server for a run or a session, so a link opens a page of Floci's own about it
* and {@code GetResourceDashboard} gives for a session, where they open no live Spark UI ({@link EmrServerlessAppUis}).
* Each "is valid for one hour after you generate it. To access the application UI after that hour elapses, you must
* invoke the API again to generate a new URL." Such a link opens a page of Floci's own about the run or the session
* ({@link EmrServerlessDashboardController}). It names the account, Region, application, the run and its attempt or
* the session, and when it expires, signed with a key this process makes: a link changed, or past its hour, opens
* nothing, and the links given before a restart open nothing after it.
@@ -99,6 +99,7 @@ public class EmrServerlessJobRunService implements Resettable {
private static final String SPARK_CONNECT_ADDRESS = "spark.connect.grpc.binding.address";
private static final String S3_MONITORING = "s3MonitoringConfiguration";
private static final String CLOUD_WATCH_LOGGING = "cloudWatchLoggingConfiguration";
private static final String MANAGED_PERSISTENCE = "managedPersistenceMonitoringConfiguration";
// "If you don't specify the optional values, then CloudWatch publishes the logs to a default log group".
private static final String DEFAULT_LOG_GROUP = "/aws/emr-serverless";
private static final String SPARK_DRIVER = "SPARK_DRIVER";
@@ -347,6 +348,11 @@ public class EmrServerlessJobRunService implements Resettable {
if (logs == null) {
// A run stored before Floci kept its attempts' destinations: where its application now sends them.
logs = driverLogDestinations(applications.getApplication(applicationId), run);
} else if (logs.managedStorage() == null) {
// An attempt stored before Floci kept whether its logs were in managed storage: as the run's own
// configuration says, or else as its application's now does.
logs = new DriverLogDestinations(logs.s3Folder(), logs.logGroup(), logs.stdoutStream(),
logs.stderrStream(), managedStorage(applications.getApplication(applicationId), run));
}
return new DashboardView(run, logs);
}
@@ -614,7 +620,19 @@ public class EmrServerlessJobRunService implements Resettable {
SparkJobRunner.CloudWatchLogs cloudWatch = driverCloudWatchLogs(app, run);
return new DriverLogDestinations(driverLogFolder(app, run), cloudWatch != null ? cloudWatch.logGroup() : null,
cloudWatch != null ? cloudWatch.stdoutStream() : null,
cloudWatch != null ? cloudWatch.stderrStream() : null);
cloudWatch != null ? cloudWatch.stderrStream() : null, managedStorage(app, run));
}
/**
* Whether a run's logs are kept in EMR Serverless's managed storage: its {@code
* managedPersistenceMonitoringConfiguration}, or else its application's, "Enables managed logging and defaults to
* true. If set to false, managed logging will be turned off." Its application UIs need it: with logs in an S3
* bucket alone, the application UI is "Not supported", and "Otherwise, you can't use the built-in application UIs"
* (EMR Serverless user guide, "Storing logs").
*/
static boolean managedStorage(Application app, JobRun run) {
return !(monitoring(app, run, MANAGED_PERSISTENCE) instanceof Map<?, ?> configuration
&& Boolean.FALSE.equals(configuration.get("enabled")));
}
// Where the run's latest attempt sends its driver's logs, as it was admitted.
@@ -680,6 +698,14 @@ public class EmrServerlessJobRunService implements Resettable {
return sparkRunner;
}
/**
* Whether the drivers of its Spark runs and sessions serve their Spark UI for Floci to open: in the docker runner
* mode, on a network where a container has an address of its own.
*/
boolean servesDriverUis() {
return sparkRunner != null && sparkRunner.servesDriverUis(dockerNetwork);
}
/**
* What runs a session's Spark Connect server in a container, as a run's driver runs: in the application's image,
* on its network, with the session's execution role and its executors as a run's are, for {@code limit} at most.
@@ -1357,7 +1383,7 @@ public class EmrServerlessJobRunService implements Resettable {
return regionResolver.getRegion().equals(AwsArnUtils.parse(run.getArn()).region());
}
private static boolean isTerminal(JobRun run) {
static boolean isTerminal(JobRun run) {
return TERMINAL_STATES.contains(run.getState());
}
@@ -480,6 +480,8 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
private final ContainerLaunches launches = new ContainerLaunches();
// What the workers of each application's runs with executors of their own hold, by application, while any runs.
private final Map<String, SparkExecutors.Capacity> capacities = new ConcurrentHashMap<>();
// Where Floci reaches the Spark UI of each EMR Serverless Spark run's driver, by run, while its container runs.
private final Map<String, ContainerLifecycleManager.EndpointInfo> driverUis = new ConcurrentHashMap<>();
private final ContainerBuilder containerBuilder;
private final ContainerLifecycleManager lifecycleManager;
@@ -521,7 +523,8 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
@Override
public Outcome run(Job given, Progress progress) {
String network = containerBuilder.resolveDockerNetwork(Optional.ofNullable(given.dockerNetwork())).orElse(null);
Job job = executorsApart(given, network) ? given : given.withExecutors(null);
// On the network it resolves to, which tells whether its executors run apart and its driver serves its UI.
Job job = (executorsApart(given, network) ? given : given.withExecutors(null)).onNetwork(network);
ContainerLaunches.Launch launch = launches.begin(job.runId());
Optional<SessionCreds> credentials = Optional.empty();
Closeable logHandle = null;
@@ -630,6 +633,9 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
// Reached through Floci alone, so published on the host's loopback interface only.
container.withLoopbackPortBinding(job.listenPort(), 0);
}
if (servesDriverUi(job)) {
container.withLoopbackPortBinding(SparkExecutors.DRIVER_UI_PORT, 0);
}
ContainerSpec spec = container
.withDockerNetwork(Optional.ofNullable(job.dockerNetwork()))
.withHostDockerInternalOnLinux()
@@ -662,6 +668,12 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
}
ContainerLifecycleManager.ContainerInfo info = lifecycleManager.startCreated(containerId, spec);
logHandle = attachLog(containerId, job);
// Found before the run is told it runs, so that a link to its UI then finds it.
ContainerLifecycleManager.EndpointInfo driverUi = servesDriverUi(job)
? info.getEndpoint(SparkExecutors.DRIVER_UI_PORT) : null;
if (driverUi != null) {
driverUis.put(job.runId(), driverUi);
}
progress.started();
if (job.listenPort() > 0) {
ContainerLifecycleManager.EndpointInfo listening = info.getEndpoint(job.listenPort());
@@ -690,6 +702,7 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
LOG.warnv(e, "Spark run {0} of {1} could not run", job.runId(), job.service());
return Outcome.couldNotStart(e.getMessage());
} finally {
driverUis.remove(job.runId());
// The executors go with their driver, however the run ended, and their workers' share of the
// application's capacity with them.
if (executors != null) {
@@ -709,6 +722,28 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
}
}
@Override
public Optional<ContainerLifecycleManager.EndpointInfo> driverUi(String runId) {
return Optional.ofNullable(driverUis.get(runId));
}
@Override
public boolean servesDriverUis(String dockerNetwork) {
return ownNetwork(containerBuilder.resolveDockerNetwork(Optional.ofNullable(dockerNetwork)).orElse(null));
}
/**
* Whether a job's driver serves its Spark UI for Floci to open: an EMR Serverless Spark run's or session's, which
* GetDashboardForJobRun and GetResourceDashboard link to while it runs, on a network where its container has an
* address of its own, as on the host's network every driver's UI would be on the host's port. The release's image
* turns the UI off ({@code spark.ui.enabled false} in its {@code spark-defaults}); a run's own settings may still
* do so.
*/
static boolean servesDriverUi(Job job) {
return EmrServerlessJobRunService.SERVICE.equals(job.service()) && job.engine() == Engine.SPARK
&& ownNetwork(job.dockerNetwork());
}
@Override
public void stop(String runId) {
ContainerLaunches.Launch launch = launches.get(runId);
@@ -918,8 +953,12 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
*/
static boolean executorsApart(Job job, String network) {
return job.executors() != null && job.engine() == Engine.SPARK && job.command() == null
&& job.storage() == null && !"host".equals(network)
&& (network == null || !network.startsWith("container:"));
&& job.storage() == null && ownNetwork(network);
}
// Whether a container on the network has an address of its own, rather than the host's or another container's.
private static boolean ownNetwork(String network) {
return !"host".equals(network) && (network == null || !network.startsWith("container:"));
}
private static String newSecret() {
@@ -1616,10 +1655,15 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
if (onYarn(job)) {
settings.addAll(yarnSettings(job, executorEnvironment));
}
// The driver's UI, which Floci follows the driver through; its kill links, which any container on the network
// reaches, are turned off after the run's own settings (SparkExecutors.DRIVER_WRAPPER).
if (job.executors() != null) {
// The driver's UI, which a dashboard link opens, and which Floci follows a driver with executors of its own
// through. Its kill links, which any container on the network reaches, are off: for a driver with executors of
// its own, after the run's own settings (SparkExecutors.DRIVER_WRAPPER); for any other, unless the run turns
// them on.
if (servesDriverUi(job)) {
settings.add(new SparkSetting("spark.ui.enabled", "true"));
if (job.executors() == null) {
settings.add(new SparkSetting("spark.ui.killEnabled", "false"));
}
}
job.sparkDefaults().forEach((key, value) -> settings.add(new SparkSetting(key, value)));
return settings;
@@ -1,8 +1,11 @@
package io.floci.aws.services.emrserverless;
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* Runs a Spark application, or a Hive query, to its end, in the EMR services' {@code docker} runner mode: an
@@ -25,6 +28,22 @@ public interface SparkJobRunner {
*/
void stop(String runId);
/**
* Where Floci reaches the Spark UI of run {@code runId}'s driver while its container runs, for an EMR Serverless
* Spark run or session; empty for any other run, and before or after its container runs.
*/
default Optional<ContainerLifecycleManager.EndpointInfo> driverUi(String runId) {
return Optional.empty();
}
/**
* Whether the drivers of EMR Serverless Spark runs and sessions on {@code dockerNetwork} (null for the default)
* serve their Spark UI for Floci to open ({@link #driverUi}).
*/
default boolean servesDriverUis(String dockerNetwork) {
return false;
}
/**
* Removes the drivers of {@code service}'s runs an earlier Floci process left running, which no thread
* follows any more. The service calls it before any run of its own can start.
@@ -184,6 +203,14 @@ public interface SparkJobRunner {
hadoopEnvironment, executors, platform, port);
}
/** This job, its containers on {@code network} (null for the global default). */
public Job onNetwork(String network) {
return new Job(service, runId, accountId, region, releaseLabel, engine, imageTemplate, customImage,
network, executionRole, sparkDefaults, application, command, timeout, logFolder, cloudWatchLogs,
environment, archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j, hadoopEnvironment,
executors, platform, listenPort);
}
/** This job, its containers run for {@code platform} (null for the Docker host's own). */
public Job withPlatform(String platform) {
return new Job(service, runId, accountId, region, releaseLabel, engine, imageTemplate, customImage,
@@ -4,8 +4,16 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
/**
* Where one attempt of a run sends its driver's logs, as the attempt was admitted: an S3 folder, and a CloudWatch Logs
* group with the driver's two streams, each null where it sends none.
* group with the driver's two streams, each null where it sends none; and whether EMR Serverless keeps them in its
* managed storage, which its application UIs need, null for an attempt stored before Floci kept it, which its run's
* configuration then tells.
*/
@RegisterForReflection
public record DriverLogDestinations(String s3Folder, String logGroup, String stdoutStream, String stderrStream) {
public record DriverLogDestinations(String s3Folder, String logGroup, String stdoutStream, String stderrStream,
Boolean managedStorage) {
/** Whether the attempt's logs are kept in managed storage. */
public boolean inManagedStorage() {
return !Boolean.FALSE.equals(managedStorage);
}
}
@@ -1,6 +1,5 @@
package io.floci.aws.services.emr;
package io.floci.aws.core.common;
import io.floci.aws.core.common.ServiceConfigAccess;
import io.vertx.core.Future;
import io.vertx.core.MultiMap;
import io.vertx.core.Vertx;
@@ -18,6 +17,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -32,17 +32,21 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Requests to an on-cluster application UI's own host through {@link EmrAppUiProxy}: a server stands in for the
* interface on the cluster's primary node, and a route for what the link's host resolves to.
* Requests to an application UI's own host through {@link AppUiProxy}: a server stands in for the interface, an EMR
* cluster's primary node's here, and a service's routes for what the link's host resolves to.
*/
class EmrAppUiProxyTest {
class AppUiProxyTest {
private static final String HOST = "s".repeat(26) + "-8088.emrappui.localhost";
private static final String NODE_ORIGIN = "http://ip-10-0-0-1.ec2.internal:19888";
private static final String BROWSER_ORIGIN = "http://" + "s".repeat(26) + "-19888.emrappui.localhost:4566";
private static final Map<String, String> REWRITES = Map.of(NODE_ORIGIN, BROWSER_ORIGIN);
private final EmrAppUiService appUis = mock(EmrAppUiService.class);
private static final String REFUSAL = "This link is not valid, or its hour has passed.";
private final AppUiRoutes appUis = mock(AppUiRoutes.class);
private final AppUiRoutes otherService = mock(AppUiRoutes.class);
private final ServiceConfigAccess services = mock(ServiceConfigAccess.class);
private final AtomicReference<MultiMap> interfaceSaw = new AtomicReference<>();
private final AtomicReference<String> interfaceSawUri = new AtomicReference<>();
private final AtomicReference<Buffer> interfaceSawBody = new AtomicReference<>();
@@ -67,11 +71,15 @@ class EmrAppUiProxyTest {
interfaceSawBody.set(body);
answer.answer(request.response(), body);
})).listen(0, "127.0.0.1"));
ServiceConfigAccess services = mock(ServiceConfigAccess.class);
when(appUis.hostLabel()).thenReturn("emrappui");
when(appUis.service()).thenReturn("emr");
when(otherService.hostLabel()).thenReturn("other-ui");
when(otherService.service()).thenReturn("other");
when(services.isEnabled("emr")).thenReturn(true);
when(services.isEnabled("other")).thenReturn(true);
Router router = Router.router(vertx);
// An interface that sends nothing for two seconds is given up.
new EmrAppUiProxy(appUis, services, vertx, Duration.ofSeconds(2)).register(router);
new AppUiProxy(List.of(appUis, otherService), services, vertx, Duration.ofSeconds(2)).register(router);
router.route().handler(context -> context.response().setStatusCode(404).end("not a link"));
floci = await(vertx.createHttpServer().requestHandler(router).listen(0, "127.0.0.1"));
client = vertx.createHttpClient();
@@ -172,12 +180,12 @@ class EmrAppUiProxyTest {
@Test
void aRefusedLinkIsAnsweredWithAPageSayingWhy() throws Exception {
when(appUis.route(eq(HOST + ":4566"), anyString()))
.thenReturn(EmrAppUiService.UiRoute.refused(403, EmrAppUiController.INVALID));
.thenReturn(AppUiRoute.refused(403, REFUSAL));
Answered response = send(HttpMethod.GET, "/cluster", null);
assertEquals(403, response.statusCode());
assertTrue(response.body().toString().contains("not valid, or its hour has passed"));
assertTrue(response.body().toString().contains(REFUSAL));
}
@Test
@@ -185,7 +193,7 @@ class EmrAppUiProxyTest {
int closed = node.actualPort();
await(node.close());
AtomicBoolean forgotten = new AtomicBoolean();
when(appUis.route(eq(HOST + ":4566"), anyString())).thenReturn(new EmrAppUiService.UiRoute("127.0.0.1",
when(appUis.route(eq(HOST + ":4566"), anyString())).thenReturn(new AppUiRoute("127.0.0.1",
closed, REWRITES, () -> forgotten.set(true), 0, null));
Answered response = send(HttpMethod.GET, "/cluster", null);
@@ -204,8 +212,46 @@ class EmrAppUiProxyTest {
assertEquals("not a link", response.body().toString());
}
@Test
void aHostUnderAnotherServicesLabelGoesToThatServicesRoutes() throws Exception {
String host = "s".repeat(26) + "-4040.other-ui.localhost";
when(otherService.route(eq(host + ":4566"), eq("http"))).thenReturn(AppUiRoute.to("127.0.0.1",
node.actualPort(), 502, null));
answer = (response, body) -> response.putHeader("content-type", "text/plain").end("the driver's UI");
Answered response = send(host, HttpMethod.GET, "/jobs/", null);
assertEquals(200, response.statusCode());
assertEquals("the driver's UI", response.body().toString());
assertEquals(host + ":4566", interfaceSaw.get().get("host"));
}
@Test
void anInterfaceThatIsNotUpYetIsAnsweredAsItsRouteSays() throws Exception {
int closed = node.actualPort();
await(node.close());
when(appUis.route(eq(HOST + ":4566"), anyString())).thenReturn(AppUiRoute.to("127.0.0.1", closed, 503,
"Not answering yet."));
Answered response = send(HttpMethod.GET, "/cluster", null);
assertEquals(503, response.statusCode());
assertTrue(response.body().toString().contains("Not answering yet."));
}
@Test
void aHostOfADisabledServiceGoesOnToTheRestOfFloci() throws Exception {
routeTo(node.actualPort());
when(services.isEnabled("emr")).thenReturn(false);
Answered response = send(HttpMethod.GET, "/cluster", null);
assertEquals(404, response.statusCode());
assertEquals("not a link", response.body().toString());
}
private void routeTo(int port) {
when(appUis.route(eq(HOST + ":4566"), eq("http"))).thenReturn(new EmrAppUiService.UiRoute("127.0.0.1", port,
when(appUis.route(eq(HOST + ":4566"), eq("http"))).thenReturn(new AppUiRoute("127.0.0.1", port,
REWRITES, () -> { }, 0, null));
}
@@ -222,9 +268,13 @@ class EmrAppUiProxyTest {
}
private Answered send(HttpMethod method, String uri, String body) throws Exception {
return send(HOST, method, uri, body);
}
private Answered send(String host, HttpMethod method, String uri, String body) throws Exception {
RequestOptions options = new RequestOptions().setMethod(method)
.setServer(SocketAddress.inetSocketAddress(floci.actualPort(), "127.0.0.1"))
.setHost(HOST).setPort(4566).setURI(uri);
.setHost(host).setPort(4566).setURI(uri);
return await(client.request(options).compose(request -> body == null ? request.send()
: request.send(Buffer.buffer(body)))
.compose(response -> response.body().map(read -> new Answered(response, read))));
@@ -176,6 +176,17 @@ class EmrAppUiIntegrationTest {
}
// The page a link opens, asked for on the address this test's Floci listens on, which the link's base URL is not.
@Test
void aRequestToAnInterfacesHostReachesItsProxyWhateverItsPath() {
// The ResourceManager's REST answers are under /ws/, a path API Gateway's WebSocket route takes too.
given().header("Host", "a".repeat(26) + "-8088.emrappui.localhost:4566")
.when().get("/ws/v1/cluster/apps")
.then().statusCode(403).body(containsString(Html.escape(EmrAppUiController.INVALID)));
given().header("Host", "a".repeat(26) + "-4040.emr-serverless-ui.localhost:4566")
.when().get("/ws/v1/cluster/apps")
.then().statusCode(403);
}
private static Response page(String url) {
URI link = URI.create(url);
return given().urlEncodingEnabled(false).when().get(link.getRawPath() + "?" + link.getRawQuery());
@@ -1,5 +1,6 @@
package io.floci.aws.services.emr;
import io.floci.aws.core.common.AppUiRoute;
import io.floci.aws.core.common.LinkSigner;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
@@ -55,7 +56,7 @@ class EmrOnClusterAppUiTest {
assertEquals("/cluster", url.getPath());
assertTrue(url.getAuthority().matches("[a-z2-7]{26}-8088\\.emrappui\\.localhost:4566"), link.url());
String secret = url.getHost().substring(0, 26);
EmrAppUiService.UiRoute route = appUis.route(url.getAuthority(), "http");
AppUiRoute route = appUis.route(url.getAuthority(), "http");
assertNull(route.refusal());
assertEquals("localhost", route.host());
assertEquals(32801, route.port());
@@ -110,7 +111,7 @@ class EmrOnClusterAppUiTest {
assertEquals("/app/application_1_0001", tez.getFragment());
// Its page asks the timeline server and the ResourceManager, on their own hosts under the same link.
String secret = tez.getHost().substring(0, 26);
EmrAppUiService.UiRoute route = appUis.route(tez.getAuthority(), "http");
AppUiRoute route = appUis.route(tez.getAuthority(), "http");
String primary = EmrService.masterPrivateDnsName(fixture.service.describeCluster(clusterId));
assertEquals("http://" + secret + "-8188.emrappui.localhost:4566",
route.rewrites().get("http://" + primary + ":8188"));
@@ -127,7 +128,7 @@ class EmrOnClusterAppUiTest {
assertFalse(second.ready());
// One start, its command run as a step's on the cluster, its HDFS and YARN started first.
assertEquals(1, fixture.stepThreadsWaiting());
EmrAppUiService.UiRoute notYet = appUis.route(URI.create(first.url()).getAuthority(), "http");
AppUiRoute notYet = appUis.route(URI.create(first.url()).getAuthority(), "http");
assertEquals(503, notYet.status());
assertEquals(EmrAppUiService.NOT_READY, notYet.refusal());
fixture.runStepThread();
@@ -149,7 +150,7 @@ class EmrOnClusterAppUiTest {
// Not a link's host at all, which goes on to the rest of Floci.
assertNull(appUis.route("bucket.emrappui.localhost:4566", "http"));
fixture.clock.advance(EmrAppUiService.VALIDITY);
EmrAppUiService.UiRoute expired = appUis.route(authority, "http");
AppUiRoute expired = appUis.route(authority, "http");
assertEquals(403, expired.status());
assertEquals(EmrAppUiController.INVALID, expired.refusal());
}
@@ -178,7 +179,7 @@ class EmrOnClusterAppUiTest {
assertNull(appUis.route(authority, "http").refusal());
fixture.service.terminateJobFlows(List.of(clusterId));
EmrAppUiService.UiRoute ended = appUis.route(authority, "http");
AppUiRoute ended = appUis.route(authority, "http");
// Its node's port, still within the link's hour, may be another container's by then.
assertEquals(404, ended.status());
@@ -1,5 +1,6 @@
package io.floci.aws.services.emr;
import io.floci.aws.core.common.AppUiRoute;
import io.floci.aws.core.common.LinkSigner;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
@@ -73,7 +74,7 @@ class EmrPersistentAppUiTest {
URI url = URI.create(starting.url());
assertEquals(EmrAppUiService.HISTORY_NOT_READY, appUis.route(url.getAuthority(), "http").refusal());
fixture.clusterStorage.historyInterfaces.put(SPARK_HISTORY, ON_HOST);
EmrAppUiService.UiRoute route = appUis.route(url.getAuthority(), "http");
AppUiRoute route = appUis.route(url.getAuthority(), "http");
assertNull(route.refusal());
assertEquals(32803, route.port());
assertTrue(appUis.persistentUrl(appUi, "SHS", null).ready());
@@ -0,0 +1,327 @@
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.AppUiRoute;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
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.JobDriver;
import io.floci.aws.services.emrserverless.model.Session;
import io.floci.aws.services.emrserverless.model.StartJobRunRequest;
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.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;
import java.util.function.Supplier;
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.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* The links GetDashboardForJobRun and GetResourceDashboard give in the docker runner mode
* ({@link EmrServerlessAppUis}): while a Spark run's attempt, or a session, has not ended, its driver's live Spark UI,
* on a host of its own that routes to where Floci reaches the driver's UI, once the driver runs; any other, Floci's
* page.
*/
class EmrServerlessAppUisTest {
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-runs";
private static final String BASE_URL = "http://localhost:4566";
private static final String PAGE = BASE_URL + EmrServerlessDashboards.PATH + "?";
private static final ContainerLifecycleManager.EndpointInfo DRIVER_UI =
new ContainerLifecycleManager.EndpointInfo("127.0.0.1", 41040);
private final ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule());
private final FakeDriverRunner runner = new FakeDriverRunner();
private final Executor threads = task -> Thread.ofPlatform().daemon().start(task);
private final MutableClock clock = new MutableClock();
private final RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT_ID);
private EmrServerlessService applications;
private EmrServerlessJobRunService jobRuns;
private EmrServerlessSessionService sessions;
private EmrServerlessAppUis appUis;
@BeforeEach
void setUp() {
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.defaultAccountId()).thenReturn(ACCOUNT_ID);
applications = new EmrServerlessService(config, new InMemoryStorageFactory(ACCOUNT_ID), regionResolver, clock);
IamService 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, threads);
sessions = new EmrServerlessSessionService(AccountAwareStorageBackend.inMemory(ACCOUNT_ID), applications,
jobRuns, iamService, regionResolver, null, objectMapper, clock, BASE_URL, runner, threads, null,
(host, port) -> null);
appUis = new EmrServerlessAppUis(new EmrServerlessDashboards(BASE_URL, clock, new byte[32]), jobRuns, sessions,
regionResolver, BASE_URL + "/", clock);
}
@AfterEach
void tearDown() {
runner.starting.complete(null);
runner.ends.values().forEach(end -> end.complete(SparkJobRunner.Outcome.halted()));
}
@Test
void aRunningSparkRunsLinkOpensItsDriversSparkUiOnAHostOfItsOwn() {
String applicationId = application("SPARK");
String jobRunId = jobRuns.startJobRun(applicationId, sparkRun()).getJobRunId();
awaitRun(applicationId, jobRunId, "RUNNING");
URI url = URI.create(appUis.jobRunUrl(applicationId, jobRunId, 1));
assertTrue(url.getAuthority().matches("[a-z2-7]{26}-4040\\.emr-serverless-ui\\.localhost:4566"),
url.toString());
assertEquals("/", url.getPath());
AppUiRoute route = appUis.route(url.getAuthority(), "http");
assertNull(route.refusal());
assertEquals("127.0.0.1", route.host());
assertEquals(41040, route.port());
// Until the driver's Spark has started its UI, a request to it is asked again later.
assertEquals(503, route.unansweredStatus());
assertEquals(EmrServerlessAppUis.NOT_ANSWERING, route.unanswered());
}
@Test
void aLinkGivenBeforeTheDriverRunsIsRefusedUntilItDoes() {
runner.starting = new CompletableFuture<>();
String applicationId = application("SPARK");
String jobRunId = jobRuns.startJobRun(applicationId, sparkRun()).getJobRunId();
String authority = URI.create(appUis.jobRunUrl(applicationId, jobRunId, 1)).getAuthority();
AppUiRoute notYet = appUis.route(authority, "http");
runner.starting.complete(null);
awaitRun(applicationId, jobRunId, "RUNNING");
assertEquals(503, notYet.status());
assertEquals(EmrServerlessAppUis.NOT_RUNNING, notYet.refusal());
assertEquals(41040, appUis.route(authority, "http").port());
}
@Test
void onceItsAttemptHasEndedTheLinkReachesNothingAndANewOneOpensFlocisPage() {
String applicationId = application("SPARK");
String jobRunId = jobRuns.startJobRun(applicationId, sparkRun()).getJobRunId();
awaitRun(applicationId, jobRunId, "RUNNING");
String authority = URI.create(appUis.jobRunUrl(applicationId, jobRunId, 1)).getAuthority();
runner.end(jobRunId).complete(SparkJobRunner.Outcome.exitedWith(0));
awaitRun(applicationId, jobRunId, "SUCCESS");
AppUiRoute ended = appUis.route(authority, "http");
assertEquals(404, ended.status());
assertEquals(String.format(EmrServerlessAppUis.RUN_ENDED, 1, jobRunId), ended.refusal());
assertTrue(appUis.jobRunUrl(applicationId, jobRunId, 1).startsWith(PAGE));
}
@Test
void aRunWhoseLogsAreNotInManagedStorageOrAHiveRunOpensFlocisPage() {
String sparkApplication = application("SPARK");
StartJobRunRequest unmanaged = sparkRun();
unmanaged.setConfigurationOverrides(Map.of("monitoringConfiguration",
Map.of("managedPersistenceMonitoringConfiguration", Map.of("enabled", false))));
String unmanagedRun = jobRuns.startJobRun(sparkApplication, unmanaged).getJobRunId();
String hiveApplication = application("HIVE");
String hiveRun = jobRuns.startJobRun(hiveApplication, hiveRun()).getJobRunId();
awaitRun(sparkApplication, unmanagedRun, "RUNNING");
awaitRun(hiveApplication, hiveRun, "RUNNING");
// "Otherwise, you can't use the built-in application UIs."
assertTrue(appUis.jobRunUrl(sparkApplication, unmanagedRun, 1).startsWith(PAGE));
// Floci runs no Tez UI.
assertTrue(appUis.jobRunUrl(hiveApplication, hiveRun, 1).startsWith(PAGE));
}
@Test
void aLinkPastItsHourNotThisProcesssOrToAnotherPortIsRefused() {
String applicationId = application("SPARK");
String jobRunId = jobRuns.startJobRun(applicationId, sparkRun()).getJobRunId();
awaitRun(applicationId, jobRunId, "RUNNING");
String authority = URI.create(appUis.jobRunUrl(applicationId, jobRunId, 1)).getAuthority();
String secret = authority.substring(0, 26);
assertEquals(404, appUis.route(secret + "-18080.emr-serverless-ui.localhost:4566", "http").status());
assertEquals(403, appUis.route("a".repeat(26) + "-4040.emr-serverless-ui.localhost:4566", "http").status());
// Not a link's host at all, which goes on to the rest of Floci.
assertNull(appUis.route(secret + "-4040.emrappui.localhost:4566", "http"));
clock.advance(EmrServerlessDashboards.VALIDITY);
AppUiRoute expired = appUis.route(authority, "http");
assertEquals(403, expired.status());
assertEquals(EmrServerlessDashboardController.INVALID, expired.refusal());
}
@Test
void aSessionsLinkOpensItsServersSparkUiWhileItIsActive() {
String applicationId = application("SPARK");
String sessionId = sessions.startSession(applicationId, sessionRequest()).getSessionId();
awaitSession(applicationId, sessionId, "IDLE");
String authority = URI.create(appUis.sessionUrl(applicationId,
sessions.getSession(applicationId, sessionId))).getAuthority();
assertEquals(41040, appUis.route(authority, "http").port());
sessions.terminateSession(applicationId, sessionId);
Session terminated = awaitSession(applicationId, sessionId, "TERMINATED");
AppUiRoute ended = appUis.route(authority, "http");
assertEquals(404, ended.status());
assertEquals(String.format(EmrServerlessAppUis.SESSION_ENDED, sessionId), ended.refusal());
assertTrue(appUis.sessionUrl(applicationId, terminated).startsWith(PAGE));
}
@Test
void inTheImmediateRunnerModeEveryLinkOpensFlocisPage() {
IamService iamService = mock(IamService.class);
when(iamService.resolveCallerArn(any())).thenReturn(Optional.empty());
EmrServerlessJobRunService immediate = new EmrServerlessJobRunService(
AccountAwareStorageBackend.inMemory(ACCOUNT_ID), applications, iamService, regionResolver, null,
objectMapper, 60, clock);
EmrServerlessAppUis pages = new EmrServerlessAppUis(new EmrServerlessDashboards(BASE_URL, clock,
new byte[32]), immediate, sessions, regionResolver, BASE_URL, clock);
String applicationId = application("SPARK");
String jobRunId = immediate.startJobRun(applicationId, sparkRun()).getJobRunId();
assertEquals("RUNNING", immediate.getJobRun(applicationId, jobRunId, null).getState());
assertTrue(pages.jobRunUrl(applicationId, jobRunId, 1).startsWith(PAGE));
}
private void awaitRun(String applicationId, String jobRunId, String state) {
await(() -> jobRuns.getJobRun(applicationId, jobRunId, null).getState(), state, "Job run " + jobRunId);
}
private Session awaitSession(String applicationId, String sessionId, String state) {
await(() -> sessions.getSession(applicationId, sessionId).getState(), state, "Session " + sessionId);
return sessions.getSession(applicationId, sessionId);
}
// Polls until what is looked at is in state, as a run's or a session's thread moves it on its own.
private static void await(Supplier<String> current, String state, String what) {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
while (!state.equals(current.get())) {
if (System.nanoTime() - deadline > 0) {
fail(what + " is " + current.get() + ", not " + state);
}
LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10));
}
}
private String application(String type) {
CreateApplicationRequest create = new CreateApplicationRequest();
create.setName("dashboards");
create.setReleaseLabel("emr-7.13.0");
create.setType(type);
create.setClientToken(UUID.randomUUID().toString());
if ("SPARK".equals(type)) {
InteractiveConfiguration interactive = new InteractiveConfiguration();
interactive.setProperty("sessionEnabled", true);
create.setInteractiveConfiguration(interactive);
}
return applications.createApplication(create).getApplicationId();
}
private static StartJobRunRequest sparkRun() {
JobDriver.SparkSubmit sparkSubmit = new JobDriver.SparkSubmit();
sparkSubmit.setEntryPoint("s3://bucket/jobs/report.py");
JobDriver driver = new JobDriver();
driver.setSparkSubmit(sparkSubmit);
return runRequest(driver);
}
private static StartJobRunRequest hiveRun() {
JobDriver.Hive hive = new JobDriver.Hive();
hive.setQuery("s3://bucket/queries/report.sql");
JobDriver driver = new JobDriver();
driver.setHive(hive);
return runRequest(driver);
}
private static StartJobRunRequest runRequest(JobDriver driver) {
StartJobRunRequest request = new StartJobRunRequest();
request.setClientToken(UUID.randomUUID().toString());
request.setExecutionRoleArn(ROLE);
request.setJobDriver(driver);
return request;
}
private static StartSessionRequest sessionRequest() {
StartSessionRequest request = new StartSessionRequest();
request.setClientToken(UUID.randomUUID().toString());
request.setExecutionRoleArn(ROLE);
return request;
}
/**
* Runs each driver as the Docker runner would, its Spark UI reachable from once it starts until it ends: once
* {@link #starting} completes, and until it is stopped or told how it ends.
*/
private static final class FakeDriverRunner implements SparkJobRunner {
volatile CompletableFuture<Void> starting = CompletableFuture.completedFuture(null);
final Map<String, CompletableFuture<Outcome>> ends = new ConcurrentHashMap<>();
private final Map<String, ContainerLifecycleManager.EndpointInfo> driverUis = new ConcurrentHashMap<>();
@Override
public Outcome run(Job job, Progress progress) {
starting.join();
if (progress.cancelled()) {
return Outcome.halted();
}
driverUis.put(job.runId(), DRIVER_UI);
try {
progress.started();
if (job.listenPort() > 0) {
progress.listening("127.0.0.1", 40123);
}
return end(job.runId()).join();
} finally {
driverUis.remove(job.runId());
}
}
@Override
public Optional<ContainerLifecycleManager.EndpointInfo> driverUi(String runId) {
return Optional.ofNullable(driverUis.get(runId));
}
@Override
public boolean servesDriverUis(String dockerNetwork) {
return true;
}
@Override
public void stop(String runId) {
end(runId).complete(Outcome.halted());
}
@Override
public void removeLeftoverDrivers(String service) {
}
CompletableFuture<Outcome> end(String runId) {
return ends.computeIfAbsent(runId, id -> new CompletableFuture<>());
}
}
}
@@ -0,0 +1,177 @@
package io.floci.aws.services.emrserverless;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.DockerAvailability;
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.response.Response;
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 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.time.Duration;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;
import java.util.function.Predicate;
import java.util.function.Supplier;
import static io.floci.aws.testing.EmrServerlessRequests.deleteApplication;
import static io.floci.aws.testing.EmrServerlessRequests.emrServerless;
import static io.floci.aws.testing.EmrServerlessRequests.startJobRun;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* EMR Serverless dashboards open for real: GetDashboardForJobRun's link, while a PySpark run runs in the release's
* image, opens its driver's Spark UI through Floci on a host of its own, its pages and its REST API naming the run's
* application, and once the run is cancelled the link reaches nothing and a new one opens Floci's page;
* GetResourceDashboard's link, while a session is idle, opens its Spark Connect server's Spark UI.
*
* <p>A nightly check: the release's image is 3.7 GB, and the run and the session each start a JVM. It shares the Spark
* Connect check's profile, so the two run on one Floci.
*/
@QuarkusTest
@TestProfile(EmrServerlessSparkConnectNightlyIntegrationTest.Profile.class)
@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true")
// Bounded waits: the image, the Spark Connect check's, which the job prefetches, or its pull, then the run's start and
// end and the session's, a minute or two; the Nightly checks job's timeout counts the 15.
@Timeout(value = 15, unit = TimeUnit.MINUTES)
class EmrServerlessDashboardNightlyIntegrationTest {
private static final int PORT = 4597;
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
private static final String RELEASE = "emr-7.13.0";
private static final String ROLE = "arn:aws:iam::000000000000:role/emr-serverless-dashboard";
private static final String NAME = "floci-dashboard";
// A run that does some work, under a name its UI shows, then waits to be cancelled.
private static final String JOB = """
import time
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("%s").getOrCreate()
print(spark.range(1000).selectExpr("sum(id)").collect())
time.sleep(1200)
""".formatted(NAME);
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@BeforeAll
static void configure() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void aRunningRunsAndAnIdleSessionsDashboardLinksOpenTheirDriversSparkUi() 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");
S3Client s3 = AwsTestClients.create(S3Client.builder().forcePathStyle(true), ACCOUNT, Region.US_EAST_1);
cleanup.register(s3::close);
String bucket = "emr-dashboard-" + 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("job.py"), RequestBody.fromString(JOB));
String applicationId = emrServerless(REGION).body("""
{"name": "dashboards", "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 jobRunId = startJobRun(REGION, applicationId, """
{"clientToken": "%s", "executionRoleArn": "%s",
"jobDriver": {"sparkSubmit": {"entryPoint": "s3://%s/job.py"}}}
""".formatted(UUID.randomUUID(), ROLE, bucket));
String run = "/applications/" + applicationId + "/jobruns/" + jobRunId;
cleanup.register(() -> emrServerless(REGION).when().delete(run));
await(() -> emrServerless(REGION).when().get(run).then().statusCode(200).extract().path("jobRun.state"),
"RUNNING"::equals, Duration.ofMinutes(10), "job run " + jobRunId);
String live = emrServerless(REGION).when().get(run + "/dashboard").then().statusCode(200)
.extract().path("url");
assertTrue(URI.create(live).getAuthority().matches("[a-z2-7]{26}-4040\\.emr-serverless-ui\\.localhost:"
+ PORT), live);
// The driver's UI answers once its JVM has started it, first with a page saying Spark is starting up.
Response jobs = awaitPage(live + "jobs/", "Spark Jobs");
assertTrue(jobs.asString().contains("Spark Jobs") && jobs.asString().contains(NAME), jobs.asString());
Response applications = open(live + "api/v1/applications");
assertEquals(200, applications.statusCode(), applications.asString());
assertEquals(List.of(NAME), applications.jsonPath().getList("name"));
emrServerless(REGION).when().delete(run).then().statusCode(200);
await(() -> emrServerless(REGION).when().get(run).then().statusCode(200).extract().path("jobRun.state"),
"CANCELLED"::equals, Duration.ofMinutes(2), "job run " + jobRunId);
Response ended = open(live + "jobs/");
assertEquals(404, ended.statusCode(), ended.asString());
assertTrue(ended.asString().contains("is no longer running"), ended.asString());
String page = emrServerless(REGION).when().get(run + "/dashboard").then().statusCode(200)
.extract().path("url");
assertTrue(page.startsWith("http://localhost:" + PORT + EmrServerlessDashboards.PATH + "?"), page);
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");
String session = "/applications/" + applicationId + "/sessions/" + sessionId;
cleanup.register(() -> emrServerless(REGION).when().delete(session));
await(() -> emrServerless(REGION).when().get(session).then().statusCode(200).extract()
.path("session.state"), "IDLE"::equals, Duration.ofMinutes(5), "session " + sessionId);
String sessionUi = emrServerless(REGION).queryParam("resourceId", sessionId)
.queryParam("resourceType", "SESSION")
.when().get("/applications/" + applicationId + "/dashboard")
.then().statusCode(200).extract().path("url");
Response sessionJobs = awaitPage(sessionUi + "jobs/", "Spark Jobs");
assertTrue(sessionJobs.asString().contains("Spark Jobs"), sessionJobs.asString());
emrServerless(REGION).when().delete(session).then().statusCode(200);
await(() -> emrServerless(REGION).when().get(session).then().statusCode(200).extract()
.path("session.state"), "TERMINATED"::equals, Duration.ofMinutes(2), "session " + sessionId);
assertEquals(404, open(sessionUi + "jobs/").statusCode());
}
// A page of a driver's UI once it shows what is asked for: its link's host answers 503 until the UI listens, and
// the UI a page saying Spark is starting up until its Spark has.
private static Response awaitPage(String url, String showing) {
Response[] page = new Response[1];
await(() -> {
page[0] = open(url);
return page[0].statusCode() + " " + page[0].asString();
}, now -> now.startsWith("200 ") && now.contains(showing), Duration.ofMinutes(3), url);
return page[0];
}
// A browser's request to the link: to Floci, under the link's host.
private static Response open(String url) {
URI uri = URI.create(url);
return given().header("Host", uri.getRawAuthority()).header("Accept", "application/json, text/html")
.redirects().follow(false)
.get("http://localhost:" + PORT + uri.getRawPath()
+ (uri.getRawQuery() != null ? "?" + uri.getRawQuery() : ""));
}
private static void await(Supplier<String> current, Predicate<String> reached, Duration limit, String what) {
long deadline = System.nanoTime() + limit.toNanos();
String now = current.get();
while (!reached.test(now)) {
if (List.of("FAILED", "TERMINATED").contains(now) || System.nanoTime() - deadline > 0) {
fail(what + " is " + now + " after " + limit);
}
LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(2));
now = current.get();
}
}
}
@@ -1,6 +1,7 @@
package io.floci.aws.services.emrserverless;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsException;
@@ -43,6 +44,7 @@ import java.util.TreeMap;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -290,6 +292,26 @@ class EmrServerlessJobRunServiceTest {
assertEquals(409, conflict.getHttpStatus());
}
@Test
void anAttemptStoredBeforeItsManagedStorageWasKeptTakesItFromItsRun() throws Exception {
EmrServerlessJobRunService service = service(0);
StartJobRunRequest unmanaged = request("BATCH", null);
unmanaged.setConfigurationOverrides(Map.of("monitoringConfiguration",
Map.of("managedPersistenceMonitoringConfiguration", Map.of("enabled", false))));
String unmanagedRun = service.startJobRun(applicationId, unmanaged).getJobRunId();
String managedRun = service.startJobRun(applicationId, request("BATCH", null)).getJobRunId();
// As an earlier Floci stored them: each attempt's destinations without whether its logs were managed.
for (String jobRunId : List.of(unmanagedRun, managedRun)) {
ObjectNode stored = objectMapper.valueToTree(store.get(jobRunId).orElseThrow());
stored.get("driverLogs").forEach(logs -> ((ObjectNode) logs).remove("managedStorage"));
store.put(jobRunId, objectMapper.treeToValue(stored, JobRunRecord.class));
}
assertFalse(service.dashboard(applicationId, unmanagedRun, 1).logs().inManagedStorage());
assertTrue(service.dashboard(applicationId, managedRun, 1).logs().inManagedStorage());
}
@Test
void negativeRunDurationIsRefused() {
assertThrows(IllegalArgumentException.class, () -> service(-1));
@@ -80,6 +80,7 @@ import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -90,6 +91,9 @@ import static org.mockito.Mockito.when;
class EmrServerlessSparkRunnerTest {
private static final String ENDPOINT = "http://floci:4566";
// Where Floci reaches the driver's Spark UI once its container runs.
private static final ContainerLifecycleManager.EndpointInfo DRIVER_UI =
new ContainerLifecycleManager.EndpointInfo("127.0.0.1", 41040);
// A cluster's storage, its HDFS running on its primary node.
private static final SparkJobRunner.Storage STORAGE = new SparkJobRunner.Storage(
"floci-aws-emr-j-2AXXXXXXGAPLF-home", "floci-aws-emr-j-2AXXXXXXGAPLF-mnt")
@@ -130,6 +134,8 @@ class EmrServerlessSparkRunnerTest {
"--conf", "spark.hadoop.aws.glue.endpoint=http://floci:4566",
"--conf", "spark.hadoop.hive.metastore.glue.catalogid=123456789012",
"--conf", "spark.hadoop.aws.region=eu-west-1",
"--conf", "spark.ui.enabled=true",
"--conf", "spark.ui.killEnabled=false",
"--conf", "spark.executor.cores=4",
"--conf", "spark.sql.shuffle.partitions=8",
"--conf", "spark.executor.cores=2",
@@ -156,7 +162,7 @@ class EmrServerlessSparkRunnerTest {
job(List.of("s3://bucket/jobs/app.jar"), Map.of()), ENDPOINT);
assertEquals("--conf", arguments.get(arguments.size() - 3));
assertEquals("spark.hadoop.aws.region=eu-west-1", arguments.get(arguments.size() - 2));
assertEquals("spark.ui.killEnabled=false", arguments.get(arguments.size() - 2));
assertEquals("s3://bucket/jobs/app.jar", arguments.get(arguments.size() - 1));
}
@@ -358,6 +364,8 @@ class EmrServerlessSparkRunnerTest {
ContainerBuilder builder = mock(ContainerBuilder.class);
ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(builder.newContainer(anyString())).thenReturn(spec);
// A network the job names is the one it resolves to.
when(builder.resolveDockerNetwork(Optional.of("floci-network"))).thenReturn(Optional.of("floci-network"));
runner(builder).run(job(Duration.ZERO), progress);
@@ -410,6 +418,50 @@ class EmrServerlessSparkRunnerTest {
assertFalse(arguments.contains("spark.ui.killEnabled=false"));
}
@Test
void aServerlessSparkRunsDriverHasItsUiOnAndAStepsDoesNot() {
List<String> arguments = EmrServerlessSparkRunner.sparkSubmitArguments(job(List.of("s3://bucket/jobs/app.jar"),
Map.of("spark.ui.enabled", "false")), ENDPOINT);
// Floci's comes before the run's own, which wins: the release's image turns it off.
int on = arguments.indexOf("spark.ui.enabled=true");
assertTrue(on > 0 && arguments.indexOf("spark.ui.enabled=false") > on);
// Its kill links, which any container on the network reaches, are off unless the run turns them on.
assertTrue(arguments.indexOf("spark.ui.killEnabled=false") > on);
assertFalse(EmrServerlessSparkRunner.sparkSubmitArguments(stepJob(Map.of()), ENDPOINT)
.contains("spark.ui.enabled=true"));
assertFalse(EmrServerlessSparkRunner.servesDriverUi(stepJob(Map.of())));
}
@Test
void onTheHostsNetworkADriverServesNoUiForFloci() {
SparkJobRunner.Job job = job(List.of("s3://bucket/jobs/app.jar"), Map.of());
// Every driver's UI would be on the host's port, another run's among them.
assertFalse(EmrServerlessSparkRunner.servesDriverUi(job.onNetwork("host")));
assertFalse(EmrServerlessSparkRunner.servesDriverUi(job.onNetwork("container:floci")));
assertTrue(EmrServerlessSparkRunner.servesDriverUi(job.onNetwork(null)));
assertFalse(EmrServerlessSparkRunner.sparkSubmitArguments(job.onNetwork("host"), ENDPOINT)
.contains("spark.ui.enabled=true"));
}
@Test
void aServerlessSparkRunsDriverPublishesItsUiOnTheLoopbackInterfaceFoundWhileItRuns() {
ContainerBuilder builder = mock(ContainerBuilder.class);
ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(builder.newContainer(anyString())).thenReturn(spec);
EmrServerlessSparkRunner runner = runner(builder);
SparkJobRunner.Job job = job(List.of("s3://bucket/jobs/app.jar"), Map.of());
List<Optional<ContainerLifecycleManager.EndpointInfo>> seen = new ArrayList<>();
doAnswer(started -> seen.add(runner.driverUi(job.runId()))).when(progress).started();
runner.run(job, progress);
verify(spec).withLoopbackPortBinding(SparkExecutors.DRIVER_UI_PORT, 0);
assertEquals(List.of(Optional.of(DRIVER_UI)), seen);
assertEquals(Optional.empty(), runner.driverUi(job.runId()));
}
@Test
void whatTheDriversContainerForcesComesAfterTheRunsOwnOptionsAndBeforeItsPrimaryResource() {
List<String> arguments = EmrServerlessSparkRunner.sparkSubmitArguments(job(null,
@@ -2302,6 +2354,8 @@ class EmrServerlessSparkRunnerTest {
private EmrServerlessSparkRunner runner(ContainerBuilder builder) {
when(lifecycle.getDockerClient()).thenReturn(docker);
when(lifecycle.create(any())).thenReturn("driver");
when(lifecycle.startCreated(eq("driver"), any())).thenReturn(new ContainerLifecycleManager.ContainerInfo(
"driver", Map.of(SparkExecutors.DRIVER_UI_PORT, DRIVER_UI)));
when(docker.inspectContainerCmd("driver").exec().getState().getRunning()).thenReturn(false);
when(docker.inspectContainerCmd("driver").exec().getState().getExitCodeLong()).thenReturn(0L);
when(awsEnv.flociEndpoint()).thenReturn(ENDPOINT);
@@ -4,9 +4,8 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.services.emrserverless.EmrServerlessAppUis;
import io.floci.aws.services.emrserverless.EmrServerlessController;
import io.floci.aws.services.emrserverless.EmrServerlessDashboards;
import io.floci.aws.services.emrserverless.EmrServerlessJobRunService;
import io.floci.aws.services.emrserverless.EmrServerlessService;
import io.floci.aws.services.emrserverless.EmrServerlessSessionService;
@@ -82,8 +81,8 @@ class AslExecutorEmrServerlessSyncTest {
.sfnService(instance)
.customResourceLiveness(null)
.emrServerlessTaskInvoker(new EmrServerlessTaskInvoker(
new EmrServerlessController(applications, jobRuns, sessions,
mock(EmrServerlessDashboards.class), mock(RegionResolver.class)), objectMapper))
new EmrServerlessController(applications, jobRuns, sessions, mock(EmrServerlessAppUis.class)),
objectMapper))
.nanoTime(testNanos::get)
.sleeper(testNanos::addAndGet)
.build();