feat(emr-serverless): open an ended run's Spark History Server from its dashboard link (#8907)

With runner-mode docker, GetDashboardForJobRun's link for a Spark run's
attempt that has ended now opens a Spark History Server over the run's
event logs, and GetResourceDashboard's link does the same for a session
that has ended, as "For completed jobs, the application UI is a
persistent application user interface such as the Spark History Server"
and "After a session ends, the Spark History Server remains available".

A run's or session's driver keeps its event logs where the release's
image writes them, /var/log/spark/apps, on a Docker volume of its own,
for the 30 days EMR Serverless keeps logs in managed storage. The server
runs in a container of the release's image that starts as its link is
first opened, answering 503 until it is up, and stops once no link to it
is valid. A history goes 30 days after its run or session ended, or once
it has gone, which Floci checks as it starts and every hour; a restart
keeps the histories and a reset removes them.

A run whose logs are not kept in managed storage keeps no event logs
and still gets Floci's page, as do Hive runs, histories that have gone
and every link in the immediate mode.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-18 16:45:03 -04:00
1 parent d2facef773
commit 1c16ea57cd
12 files changed
+1174 -109

No files matched your search

@@ -5,36 +5,54 @@ 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.ContainerTeardown;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.core.common.Resettable;
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 io.quarkus.runtime.StartupEvent;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* 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}).
* running state, the application UI is a live user interface such as the Spark or Tez web UI. For completed jobs, the
* application UI is a persistent application user interface such as the Spark History Server", and a session's
* likewise. 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, and one given after, for the 30
* days its event logs are kept ({@link EmrServerlessHistories}), a Spark History Server reading them; each on a host of
* its own under {@link #UI_HOST} ({@link AppUiHost}), which Floci's application UI proxy sends on to the container, 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 while a session is ending or once a history has gone, or any in the immediate runner mode, opens a
* page of Floci's own about it ({@link EmrServerlessDashboards}). It also keeps the histories: the container serving
* one stops once no link to it is valid, and a history goes once its 30 days have passed or its run or session has
* gone, which it checks as Floci starts and every hour; a reset removes every history, a shutdown the containers
* serving them.
*/
@ApplicationScoped
public class EmrServerlessAppUis implements AppUiRoutes {
public class EmrServerlessAppUis implements AppUiRoutes, Resettable, ContainerTeardown {
private static final Logger LOG = Logger.getLogger(EmrServerlessAppUis.class);
/** The label under Floci's host name a driver's UI's own host is in. */
static final String UI_HOST = "emr-serverless-ui";
@@ -46,77 +64,138 @@ public class EmrServerlessAppUis implements AppUiRoutes {
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.";
static final String HISTORY_NOT_READY = "The Spark History Server of the kept event logs is starting. Try again in"
+ " a moment.";
static final String HISTORY_GONE = "The history of %s is no longer kept: it is kept for 30 days after it ends.";
private static final Set<String> SESSION_ENDING = Set.of(EmrServerlessSessionService.STATE_TERMINATING,
EmrServerlessSessionService.STATE_TERMINATED, EmrServerlessSessionService.STATE_FAILED);
private static final int HISTORY_PORT = EmrServerlessSparkRunner.SPARK_HISTORY_WEB_PORT;
// How long a history server's address is used before it is asked for again, rather than at each of its pages'
// requests: a container gone since may have left its port to another.
private static final Duration ENDPOINT_RECHECK = Duration.ofSeconds(10);
// How long after a history link has expired the container serving it is checked, and how often the histories are.
private static final Duration REAP_MARGIN = Duration.ofMinutes(1);
private static final Duration SWEEP_INTERVAL = Duration.ofHours(1);
private final EmrServerlessDashboards dashboards;
private final EmrServerlessJobRunService jobRuns;
private final EmrServerlessSessionService sessions;
private final EmrServerlessHistories histories;
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<>();
// The links to drivers' UIs and to kept histories this process has given, by their secret, until they expire.
private final Map<String, Grant> grants = new ConcurrentHashMap<>();
// Where a history link's server was found, and when, by the link's secret.
private final Map<String, Found> found = new ConcurrentHashMap<>();
private final SecureRandom random = new SecureRandom();
// Checks, as history links expire and every hour, the containers and histories that may go; made on first use.
private ScheduledExecutorService reaper;
@Inject
public EmrServerlessAppUis(EmrServerlessDashboards dashboards, EmrServerlessJobRunService jobRuns,
EmrServerlessSessionService sessions, RegionResolver regionResolver,
EmulatorConfig config, Clock clock) {
this(dashboards, jobRuns, sessions, regionResolver, config.effectiveBaseUrl(), clock);
EmrServerlessSessionService sessions, EmrServerlessHistories histories,
RegionResolver regionResolver, EmulatorConfig config, Clock clock) {
this(dashboards, jobRuns, sessions, histories, regionResolver, config.effectiveBaseUrl(), clock);
}
EmrServerlessAppUis(EmrServerlessDashboards dashboards, EmrServerlessJobRunService jobRuns,
EmrServerlessSessionService sessions, RegionResolver regionResolver, String baseUrl,
Clock clock) {
EmrServerlessSessionService sessions, EmrServerlessHistories histories,
RegionResolver regionResolver, String baseUrl, Clock clock) {
this.dashboards = dashboards;
this.jobRuns = jobRuns;
this.sessions = sessions;
this.histories = histories;
this.regionResolver = regionResolver;
this.clock = clock;
this.baseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl;
}
/** A link given: what it names, and whether it opens the kept history rather than the live UI. */
private record Grant(EmrServerlessDashboards.Link link, boolean history) {
String runId() {
return link.jobRunId() != null ? link.jobRunId() : link.sessionId();
}
}
// Where Floci found the server of a history, and when.
private record Found(ContainerLifecycleManager.EndpointInfo endpoint, Instant at) {
}
/**
* 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.
* The link GetDashboardForJobRun gives for a run's attempt, which must be there, for a Spark run in the docker
* runner mode whose logs are in managed storage: its driver's live Spark UI while the attempt has not ended, then
* its kept history's Spark History Server; 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);
EmrServerlessDashboards.Link link = new EmrServerlessDashboards.Link(regionResolver.getAccountId(),
regionResolver.getRegion(), applicationId, jobRunId, null, attempt, expiry());
if (jobRuns.servesDriverUis() && run.getJobDriver() != null && run.getJobDriver().getSparkSubmit() != null
&& view.logs().inManagedStorage()) {
if (!EmrServerlessJobRunService.isTerminal(run)) {
return url(new Grant(link, false));
}
if (historyKept(jobRunId, run.getEndedAt())) {
return url(new Grant(link, true));
}
}
return driverUiUrl(new EmrServerlessDashboards.Link(accountId, region, applicationId, jobRunId, null, attempt,
expiry()));
return dashboards.url(link.accountId(), link.region(), applicationId, jobRunId, attempt);
}
/**
* 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.
* The link GetResourceDashboard gives for a session, in the docker runner mode: its Spark Connect server's live
* Spark UI while it has not ended or begun to, then its kept history's Spark History Server; 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());
EmrServerlessDashboards.Link link = new EmrServerlessDashboards.Link(regionResolver.getAccountId(),
regionResolver.getRegion(), applicationId, null, session.getSessionId(), 0, expiry());
if (jobRuns.servesDriverUis()) {
if (!SESSION_ENDING.contains(session.getState())) {
return url(new Grant(link, false));
}
if (!EmrServerlessSessionService.STATE_TERMINATING.equals(session.getState())
&& historyKept(session.getSessionId(), session.getEndedAt())) {
return url(new Grant(link, true));
}
}
return driverUiUrl(new EmrServerlessDashboards.Link(accountId, region, applicationId, null,
session.getSessionId(), 0, expiry()));
return dashboards.sessionUrl(link.accountId(), link.region(), applicationId, session.getSessionId());
}
private String driverUiUrl(EmrServerlessDashboards.Link link) {
// Within its 30 days, and kept; where Docker cannot tell, the link is given, its host asking to try again until
// Docker can.
private boolean historyKept(String runId, Instant endedAt) {
if (endedAt == null || !clock.instant().isBefore(endedAt.plus(EmrServerlessHistories.KEPT))) {
return false;
}
try {
return histories.kept(runId);
} catch (RuntimeException e) {
LOG.warnv(e, "Could not tell whether the history of EMR Serverless run {0} is kept: {1}", runId,
e.getMessage());
return true;
}
}
private synchronized String url(Grant grant) {
long now = clock.instant().getEpochSecond();
grants.values().removeIf(grant -> now >= grant.expires());
grants.entrySet().removeIf(entry -> {
boolean expired = now >= entry.getValue().link().expires();
if (expired) {
found.remove(entry.getKey());
}
return expired;
});
String secret = AppUiHost.newSecret(random);
grants.put(secret, link);
return AppUiHost.url(baseUrl, secret, SparkExecutors.DRIVER_UI_PORT, UI_HOST, "/");
grants.put(secret, grant);
if (grant.history()) {
reapLater(grant);
}
return AppUiHost.url(baseUrl, secret, grant.history() ? HISTORY_PORT : SparkExecutors.DRIVER_UI_PORT,
UI_HOST, "/");
}
private long expiry() {
@@ -135,8 +214,8 @@ public class EmrServerlessAppUis implements AppUiRoutes {
/**
* 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>}.
* attempt, or the session, has it running, or to its kept history's Spark History Server; 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) {
@@ -144,16 +223,18 @@ public class EmrServerlessAppUis implements AppUiRoutes {
if (host == null) {
return null;
}
EmrServerlessDashboards.Link link = grants.get(host.secret());
if (link == null || clock.instant().getEpochSecond() >= link.expires()) {
Grant grant = grants.get(host.secret());
if (grant == null || clock.instant().getEpochSecond() >= grant.link().expires()) {
return AppUiRoute.refused(403, EmrServerlessDashboardController.INVALID);
}
if (host.port() != SparkExecutors.DRIVER_UI_PORT) {
if (host.port() != (grant.history() ? HISTORY_PORT : SparkExecutors.DRIVER_UI_PORT)) {
return AppUiRoute.refused(404, NO_SUCH_INTERFACE);
}
EmrServerlessDashboards.Link link = grant.link();
try {
return RequestScopes.callAs(link.accountId(), link.region(),
() -> link.jobRunId() != null ? runRoute(link) : sessionRoute(link));
return RequestScopes.callAs(link.accountId(), link.region(), () -> grant.history()
? historyRoute(host.secret(), grant)
: 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());
@@ -189,4 +270,130 @@ public class EmrServerlessAppUis implements AppUiRoutes {
// Its container runs before its Spark has started its UI.
return endpoint.map(found -> AppUiRoute.to(found.host(), found.port(), 503, NOT_ANSWERING));
}
// To the server of a kept history, within its 30 days, which starts where it is not running.
private AppUiRoute historyRoute(String secret, Grant grant) {
EmrServerlessDashboards.Link link = grant.link();
Instant endedAt;
String releaseLabel;
if (link.jobRunId() != null) {
JobRun run = jobRuns.dashboard(link.applicationId(), link.jobRunId(), link.attempt()).run();
endedAt = run.getEndedAt();
releaseLabel = run.getReleaseLabel();
} else {
Session session = sessions.getSession(link.applicationId(), link.sessionId());
endedAt = session.getEndedAt();
releaseLabel = session.getReleaseLabel();
}
Instant now = clock.instant();
String what = (link.jobRunId() != null ? "job run " : "session ") + grant.runId();
if (endedAt == null || !now.isBefore(endedAt.plus(EmrServerlessHistories.KEPT))) {
return AppUiRoute.refused(404, String.format(HISTORY_GONE, what));
}
Found server = found.get(secret);
if (server == null || !now.isBefore(server.at().plus(ENDPOINT_RECHECK))) {
boolean kept;
try {
kept = histories.kept(grant.runId());
} catch (RuntimeException e) {
LOG.warnv(e, "Could not tell whether the history of EMR Serverless run {0} is kept: {1}",
grant.runId(), e.getMessage());
return AppUiRoute.refused(503, HISTORY_NOT_READY);
}
if (!kept) {
return AppUiRoute.refused(404, String.format(HISTORY_GONE, what));
}
Optional<ContainerLifecycleManager.EndpointInfo> endpoint = histories.server(grant.runId(),
link.accountId(), link.region(), jobRuns.historyImage(releaseLabel), jobRuns.dockerNetwork());
if (endpoint.isEmpty()) {
found.remove(secret);
return AppUiRoute.refused(503, HISTORY_NOT_READY);
}
server = new Found(endpoint.get(), now);
found.put(secret, server);
}
Found routed = server;
return new AppUiRoute(server.endpoint().host(), server.endpoint().port(), Map.of(),
() -> found.remove(secret, routed), 0, null, 503, HISTORY_NOT_READY);
}
// Checks, once a history link has expired, whether the container serving its history may stop.
private synchronized void reapLater(Grant grant) {
long delay = Duration.between(clock.instant(), Instant.ofEpochSecond(grant.link().expires()))
.plus(REAP_MARGIN).toMillis();
reaper().schedule(() -> reap(grant.runId()), delay, TimeUnit.MILLISECONDS);
}
private synchronized ScheduledExecutorService reaper() {
if (reaper == null) {
reaper = Executors.newSingleThreadScheduledExecutor(
Thread.ofPlatform().daemon().name("emr-serverless-history").factory());
}
return reaper;
}
/**
* Stops the container serving a run's or session's kept history once no link to it is valid, and removes the
* histories that have gone; under this bean's lock, as a link is given, so one given while this looks keeps its
* container.
*/
synchronized void reap(String runId) {
long now = clock.instant().getEpochSecond();
boolean linked = grants.values().stream().anyMatch(grant -> grant.history() && grant.runId().equals(runId)
&& now < grant.link().expires());
if (!linked) {
histories.stop(runId);
}
removeExpiredHistories();
}
/** Removes the kept histories whose 30 days have passed, or whose run or session has gone. */
void removeExpiredHistories() {
try {
Instant cutoff = clock.instant().minus(EmrServerlessHistories.KEPT);
Set<String> kept = new HashSet<>(jobRuns.historiesKept(cutoff));
kept.addAll(sessions.historiesKept(cutoff));
histories.removeAllBut(kept::contains);
} catch (RuntimeException e) {
LOG.warnv(e, "Could not remove the expired histories of EMR Serverless runs: {0}", e.getMessage());
}
}
/**
* As Floci starts, in the docker runner mode: the containers an earlier process left serving histories go, and the
* histories that have gone, then every hour.
*/
void onStart(@Observes StartupEvent ignored) {
if (!jobRuns.servesDriverUis()) {
return;
}
reaper().execute(() -> {
histories.removeLeftoverServers();
removeExpiredHistories();
});
reaper().scheduleAtFixedRate(this::removeExpiredHistories, SWEEP_INTERVAL.toMinutes(),
SWEEP_INTERVAL.toMinutes(), TimeUnit.MINUTES);
}
@Override
public void stopManagedContainers() {
histories.stopServers();
}
/** A reset forgets every link and removes every kept history. */
@Override
public void clear() {
grants.clear();
found.clear();
if (jobRuns.servesDriverUis()) {
histories.removeAllBut(runId -> false);
}
}
@PreDestroy
synchronized void close() {
if (reaper != null) {
reaper.shutdownNow();
}
}
}
@@ -21,9 +21,9 @@ import java.util.List;
* 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
* Spark History Server likewise; Floci opens a Spark UI or a Spark History Server 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.
*/
@@ -33,12 +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 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 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.";
static final String NO_UI = "Floci opens a job run's live Spark UI, and its Spark History Server for 30 days after,"
+ " only for a Spark run in the docker runner mode with its logs in managed storage, and runs no Tez UI, 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 opens a session's live Spark UI, and its Spark History Server for 30"
+ " days after, only in the docker runner mode, so this page stands in for the application UI EMR"
+ " Serverless opens.";
private final EmrServerlessDashboards dashboards;
private final EmrServerlessJobRunService jobRuns;
@@ -0,0 +1,290 @@
package io.floci.aws.services.emrserverless;
import com.github.dockerjava.api.command.InspectVolumeResponse;
import com.github.dockerjava.api.command.ListVolumesResponse;
import com.github.dockerjava.api.model.Container;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.docker.ContainerBuilder;
import io.floci.aws.core.common.docker.ContainerExec;
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
import io.floci.aws.core.common.docker.ContainerLiveness;
import io.floci.aws.core.common.docker.ContainerStorageHelper;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Duration;
import java.time.Instant;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
import java.util.function.Predicate;
/**
* The kept histories of EMR Serverless Spark runs and sessions in the docker runner mode. Each run's or session's
* driver keeps its Spark event logs in a Docker volume of its own, mounted where the release's image writes them
* ({@code spark.eventLog.dir file:///var/log/spark/apps}), and once it has ended a Spark History Server reads them, in
* a container of its own, made from the release's image, that starts on a link to it and stops once no link to it is
* valid. "By default, EMR Serverless stores application logs securely in Amazon EMR managed storage for a maximum of
* 30 days" (EMR Serverless user guide, "Storing logs"): its owner, {@link EmrServerlessAppUis}, removes a history once
* that has passed, or once its run or session has gone, every history on a reset, and the containers serving them on
* a shutdown.
*/
@ApplicationScoped
public class EmrServerlessHistories {
private static final Logger LOG = Logger.getLogger(EmrServerlessHistories.class);
/** Where a driver writes its Spark event logs, as the release's image's {@code spark-defaults} say. */
static final String EVENT_LOGS = "/var/log/spark/apps";
/** How long a history is kept after its run or session has ended. */
static final Duration KEPT = Duration.ofDays(30);
/** The component labels of a history's volume and of the container serving it. */
static final String VOLUME_COMPONENT = "emr-serverless-history";
static final String SERVER_COMPONENT = "emr-serverless-history-ui";
private static final int SPARK_HISTORY_PORT = EmrServerlessSparkRunner.SPARK_HISTORY_WEB_PORT;
// The Spark History Server on the event logs, on its own port, its logs in /tmp, as the image's own folder for them
// is not its user's.
private static final String SERVER_SCRIPT = "SPARK_LOG_DIR=/tmp SPARK_HISTORY_OPTS=\""
+ "-Dspark.history.fs.logDirectory=file://" + EVENT_LOGS + " -Dspark.history.ui.port=" + SPARK_HISTORY_PORT
+ "\" exec"
+ " /usr/lib/spark/bin/spark-class org.apache.spark.deploy.history.HistoryServer";
private static final String[] ANSWERS = {"curl", "-sf", "-m", "5",
"http://127.0.0.1:" + SPARK_HISTORY_PORT + "/api/v1/version"};
private final ContainerBuilder containerBuilder;
private final ContainerLifecycleManager lifecycleManager;
private final EmulatorConfig config;
private final Executor starts;
// The histories whose server is being started, so that one link's start is not repeated by the next.
private final Set<String> starting = ConcurrentHashMap.newKeySet();
// The containers serving histories this process started, which a shutdown removes.
private final Set<String> servers = ConcurrentHashMap.newKeySet();
// Counts the teardowns and sweeps, so that a server whose start one ran through goes.
private final AtomicLong teardowns = new AtomicLong();
@Inject
public EmrServerlessHistories(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager,
EmulatorConfig config) {
this(containerBuilder, lifecycleManager, config,
task -> Thread.ofPlatform().daemon().name("emr-serverless-history").start(task));
}
EmrServerlessHistories(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager,
EmulatorConfig config, Executor starts) {
this.containerBuilder = containerBuilder;
this.lifecycleManager = lifecycleManager;
this.config = config;
this.starts = starts;
}
String volume(String runId) {
return volume(config, runId);
}
/** The volume a run's or session's driver keeps its event logs in. */
static String volume(EmulatorConfig config, String runId) {
return ContainerStorageHelper.dockerName(config, "emr-serverless-" + runId + "-history");
}
private String serverName(String runId) {
return ContainerStorageHelper.dockerName(config, "emr-serverless-" + runId + "-history-ui");
}
/**
* The labels of a run's or session's history volume, or, as {@code component}, of the container serving it, with
* the Floci deployment that keeps it, so that another sharing the Docker daemon leaves it alone.
*/
static Map<String, String> labels(EmulatorConfig config, String runId, String accountId, String region,
String component) {
Map<String, String> labels = new LinkedHashMap<>(ContainerStorageHelper.resourceIdentityLabels(
EmrServerlessJobRunService.SERVICE, runId, accountId, region));
labels.put(ContainerStorageHelper.COMPONENT_LABEL, component);
labels.put(ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config));
return labels;
}
/**
* The ids of those of {@code records}, runs or sessions, whose kept history stays: those that have not ended, as
* {@code ended} tells, and those that ended after {@code cutoff}, as {@code endedAt} tells.
*/
static <T> Set<String> stillKept(List<T> records, Function<T, String> id, Predicate<T> ended,
Function<T, Instant> endedAt, Instant cutoff) {
Set<String> kept = new HashSet<>();
for (T record : records) {
Instant end = endedAt.apply(record);
if (!ended.test(record) || end == null || end.isAfter(cutoff)) {
kept.add(id.apply(record));
}
}
return kept;
}
/** Whether a run's or session's history is kept: its volume is there. A Docker error goes to the caller. */
boolean kept(String runId) {
return lifecycleManager.volumeExists(volume(runId));
}
/**
* Where Floci reaches the Spark History Server of a run's or session's kept history, once it answers; empty until
* then, the server started, on {@code network}, from {@code image}, where it is not running.
*/
Optional<ContainerLifecycleManager.EndpointInfo> server(String runId, String accountId, String region,
String image, String network) {
String name = serverName(runId);
try {
ContainerLiveness liveness = lifecycleManager.probeContainer(name);
if (liveness == ContainerLiveness.RUNNING) {
if (ContainerExec.run(lifecycleManager.getDockerClient(), name, ANSWERS, 10).exitCode() != 0) {
return Optional.empty();
}
return Optional.of(lifecycleManager.resolveEndpoint(name, SPARK_HISTORY_PORT, network));
}
if (liveness == ContainerLiveness.NOT_RUNNING && starting.add(runId)) {
long teardown = teardowns.get();
starts.execute(() -> {
try {
start(runId, accountId, region, image, network, teardown);
} catch (RuntimeException e) {
LOG.warnv(e, "Could not start the history of EMR Serverless run {0}: {1}", runId,
e.getMessage());
} finally {
starting.remove(runId);
}
});
}
} catch (RuntimeException e) {
LOG.warnv(e, "The history of EMR Serverless run {0} is not reachable: {1}", runId, e.getMessage());
}
return Optional.empty();
}
// The container serving a kept history, with its volume, its port published on the host's loopback interface
// alone; none once a teardown or a sweep has run since it was asked for, or the history has gone, whose volume the
// container would make again, empty.
private void start(String runId, String accountId, String region, String image, String network, long teardown) {
if (teardowns.get() != teardown || !kept(runId)) {
return;
}
String name = serverName(runId);
lifecycleManager.removeIfExistsStrict(name);
// Known before it starts, so a shutdown while it starts removes it.
servers.add(name);
lifecycleManager.createAndStart(containerBuilder.newContainer(image)
.withName(name)
.withEntrypoint(List.of("/bin/bash", "-c", SERVER_SCRIPT))
.withNamedVolume(volume(runId), EVENT_LOGS)
.withLoopbackPortBinding(SPARK_HISTORY_PORT, 0)
.withDockerNetwork(Optional.ofNullable(network))
.withLogRotation()
.withLabels(labels(config, runId, accountId, region, SERVER_COMPONENT))
.build());
// A teardown or a sweep while it started may have missed it, and a history removed meanwhile is a volume
// Docker made again, empty and unlabelled, for it.
boolean recreated = !labelled(volume(runId));
if (teardowns.get() != teardown || recreated) {
lifecycleManager.removeIfExistsStrict(name);
servers.remove(name);
if (recreated) {
lifecycleManager.removeVolume(volume(runId));
}
return;
}
LOG.infov("Started the history of EMR Serverless run {0}", runId);
}
// Whether the volume is a kept history's, as the runner made it, rather than one Docker made for a mount.
private boolean labelled(String volume) {
Map<String, String> labels = lifecycleManager.getDockerClient().inspectVolumeCmd(volume).exec().getLabels();
return labels != null && VOLUME_COMPONENT.equals(labels.get(ContainerStorageHelper.COMPONENT_LABEL));
}
/** Stops the container serving a run's or session's kept history; the history stays. */
void stop(String runId) {
try {
lifecycleManager.removeIfExistsStrict(serverName(runId));
servers.remove(serverName(runId));
} catch (RuntimeException e) {
LOG.warnv(e, "Could not stop the history of EMR Serverless run {0}: {1}", runId, e.getMessage());
}
}
/**
* Removes the kept histories, and the containers serving them, of this Floci's runs and sessions {@code kept}
* refuses.
*/
void removeAllBut(Predicate<String> kept) {
teardowns.incrementAndGet();
try {
for (Container container : listServers()) {
String runId = runIdOf(container.getLabels());
if (!kept.test(runId)) {
lifecycleManager.removeIfExistsStrict(container.getId());
servers.remove(serverName(runId));
}
}
ListVolumesResponse response = lifecycleManager.getDockerClient().listVolumesCmd()
.withFilter("label", List.of(componentLabel(VOLUME_COMPONENT), ownerLabel())).exec();
List<InspectVolumeResponse> volumes = response != null && response.getVolumes() != null
? response.getVolumes() : List.of();
for (InspectVolumeResponse volume : volumes) {
if (!kept.test(runIdOf(volume.getLabels()))) {
lifecycleManager.removeVolume(volume.getName());
}
}
} catch (RuntimeException e) {
LOG.warnv(e, "Could not remove the kept histories of EMR Serverless runs: {0}", e.getMessage());
}
}
// The containers serving this Floci's kept histories.
private List<Container> listServers() {
return lifecycleManager.getDockerClient().listContainersCmd().withShowAll(true)
.withLabelFilter(List.of(componentLabel(SERVER_COMPONENT), ownerLabel())).exec();
}
private String ownerLabel() {
return ContainerStorageHelper.OWNER_LABEL + "=" + ContainerStorageHelper.ownerIdentity(config);
}
private static String runIdOf(Map<String, String> labels) {
return labels != null ? labels.get(ContainerStorageHelper.RESOURCE_ID_LABEL) : null;
}
private static String componentLabel(String component) {
return ContainerStorageHelper.COMPONENT_LABEL + "=" + component;
}
/** Removes the containers an earlier process of this Floci left serving kept histories, which start again. */
void removeLeftoverServers() {
try {
for (Container container : listServers()) {
lifecycleManager.removeIfExistsStrict(container.getId());
}
} catch (RuntimeException e) {
LOG.warnv(e, "Could not remove the containers left serving EMR Serverless kept histories: {0}",
e.getMessage());
}
}
/** Stops every container serving a kept history this process started; the histories stay for a restart. */
void stopServers() {
teardowns.incrementAndGet();
for (String name : Set.copyOf(servers)) {
try {
lifecycleManager.removeIfExistsStrict(name);
servers.remove(name);
} catch (RuntimeException e) {
LOG.warnv(e, "Could not stop the container {0} of an EMR Serverless kept history: {1}", name,
e.getMessage());
}
}
}
}
@@ -683,6 +683,11 @@ public class EmrServerlessJobRunService implements Resettable {
logs.s3Folder(), cloudWatchLogs(logs), driverEnvironment(sparkProperties),
archives(sparkProperties), null, Map.of(), Map.of(), Map.of(), Map.of(), Map.of(),
executors(app, executorContainers));
// Its event logs, kept for its Spark History Server once it ends, as EMR Serverless keeps them in its
// managed storage, where the run writes them.
if (servesDriverUis() && logs.inManagedStorage() && writesEventLogs(sparkProperties)) {
job = job.keepingEventLogs();
}
}
// With honour-architectures on, its containers run for the application's architecture, "x86_64 is the default
// option" on EMR Serverless; with it off, or where the application names none, for the Docker host's own.
@@ -706,6 +711,46 @@ public class EmrServerlessJobRunService implements Resettable {
return sparkRunner != null && sparkRunner.servesDriverUis(dockerNetwork);
}
/**
* Whether a driver with these Spark properties writes its event logs where the release's image has them, which a
* kept history holds: unless it turns them off ({@code spark.eventLog.enabled}) or sends them elsewhere
* ({@code spark.eventLog.dir}).
*/
static boolean writesEventLogs(Map<String, String> properties) {
String enabled = properties.get("spark.eventLog.enabled");
String dir = properties.get("spark.eventLog.dir");
if (enabled != null && !Boolean.parseBoolean(enabled.trim())) {
return false;
}
if (dir == null) {
return true;
}
String path = dir.trim().replaceFirst("^file:(//)?", "");
return EmrServerlessHistories.EVENT_LOGS.equals(path.endsWith("/") ? path.substring(0, path.length() - 1)
: path);
}
/** The image a Spark History Server of a release's kept histories runs: that release's, as its runs' drivers. */
String historyImage(String releaseLabel) {
return EmrServerlessSparkRunner.image(imageTemplate, releaseLabel);
}
/** The Docker network its runs' containers are on, null for the global default. */
String dockerNetwork() {
return dockerNetwork;
}
/**
* The runs, of every account, whose kept history stays ({@link EmrServerlessHistories}): those that have not ended,
* and those that ended after {@code cutoff}.
*/
synchronized Set<String> historiesKept(Instant cutoff) {
List<JobRun> runs = store.scanAllAccountEntries(key -> true).stream()
.map(entry -> entry.value().getJobRun()).toList();
return EmrServerlessHistories.stillKept(runs, JobRun::getJobRunId, EmrServerlessJobRunService::isTerminal,
JobRun::getEndedAt, cutoff);
}
/**
* 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.
@@ -729,8 +774,9 @@ public class EmrServerlessJobRunService implements Resettable {
sparkConnectServer(session.getReleaseLabel()), null, limit, null, null,
driverEnvironment(sparkDefaults), archives(sparkDefaults), null, Map.of(), Map.of(), Map.of(),
Map.of(), Map.of(), executors(app, executorContainers));
return job.withPlatform(honourArchitectures ? DockerPlatforms.forArchitecture(app.getArchitecture()) : null)
.listeningOn(port);
SparkJobRunner.Job listening = job.withPlatform(
honourArchitectures ? DockerPlatforms.forArchitecture(app.getArchitecture()) : null).listeningOn(port);
return servesDriverUis() && writesEventLogs(sparkDefaults) ? listening.keepingEventLogs() : listening;
}
/**
@@ -331,6 +331,18 @@ public class EmrServerlessSessionService implements SparkConnectTargets, Resetta
}
}
/**
* The sessions, of every account, whose kept history stays ({@link EmrServerlessHistories}): those that have not
* ended, and those that ended after {@code cutoff}.
*/
synchronized Set<String> historiesKept(Instant cutoff) {
List<Session> all = store.scanAllAccountEntries(key -> true).stream()
.map(entry -> entry.value().getSession()).toList();
return EmrServerlessHistories.stillKept(all, Session::getSessionId,
session -> STATE_TERMINATED.equals(session.getState()) || STATE_FAILED.equals(session.getState()),
Session::getEndedAt, cutoff);
}
/**
* The session GetResourceDashboard links to, in any state: "Currently, only Session is supported" as its
* {@code resourceType}.
@@ -635,6 +635,15 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
}
if (servesDriverUi(job)) {
container.withLoopbackPortBinding(SparkExecutors.DRIVER_UI_PORT, 0);
if (job.keepsEventLogs()) {
// Its event logs, where the release's image writes them, in a volume of its own that its Spark
// History Server reads once it has ended; Docker fills a new volume with the image's folder, its
// owner the image's user.
String volume = EmrServerlessHistories.volume(config, job.runId());
lifecycleManager.ensureVolume(volume, EmrServerlessHistories.labels(config, job.runId(),
job.accountId(), job.region(), EmrServerlessHistories.VOLUME_COMPONENT));
container.withNamedVolume(volume, EmrServerlessHistories.EVENT_LOGS);
}
}
ContainerSpec spec = container
.withDockerNetwork(Optional.ofNullable(job.dockerNetwork()))
@@ -132,7 +132,9 @@ public interface SparkJobRunner {
* its containers run, as its application's architecture names it with {@code honour-architectures} on,
* {@code linux/amd64} or {@code linux/arm64} (null for the Docker host's own); and the port in its driver's
* container that something there listens on for Floci, which Floci reaches through the Docker host's loopback
* interface only, as {@link Progress#listening} tells (0 for none).
* interface only, as {@link Progress#listening} tells (0 for none); and whether an EMR Serverless Spark run's or
* session's driver keeps its Spark event logs, in a Docker volume of its own, for its Spark History Server once it
* has ended ({@link EmrServerlessHistories}).
*/
record Job(String service, String runId, String accountId, String region, String releaseLabel, Engine engine,
String imageTemplate, String customImage, String dockerNetwork, String executionRole,
@@ -140,7 +142,8 @@ public interface SparkJobRunner {
String logFolder, CloudWatchLogs cloudWatchLogs, Map<String, String> environment,
List<String> archives, Storage storage, Map<String, String> coreSite,
Map<String, String> sparkLog4j2, Map<String, String> mapredSite, Map<String, String> hadoopLog4j,
Map<String, String> hadoopEnvironment, Executors executors, String platform, int listenPort) {
Map<String, String> hadoopEnvironment, Executors executors, String platform, int listenPort,
boolean keepsEventLogs) {
/** A job whose driver listens on no port for Floci. */
public Job(String service, String runId, String accountId, String region, String releaseLabel, Engine engine,
@@ -154,7 +157,7 @@ public interface SparkJobRunner {
this(service, runId, accountId, region, releaseLabel, engine, imageTemplate, customImage, dockerNetwork,
executionRole, sparkDefaults, application, command, timeout, logFolder, cloudWatchLogs,
environment, archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j,
hadoopEnvironment, executors, platform, 0);
hadoopEnvironment, executors, platform, 0, false);
}
/** A job on the Docker host's own platform. */
@@ -176,7 +179,7 @@ public interface SparkJobRunner {
return new Job(service, runId, accountId, region, releaseLabel, engine, imageTemplate, customImage,
dockerNetwork, executionRole, sparkDefaults, application, command, timeout, logFolder,
cloudWatchLogs, environment, archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j,
hadoopEnvironment, executors, platform, listenPort);
hadoopEnvironment, executors, platform, listenPort, keepsEventLogs);
}
/** This job, run in {@code image}. */
@@ -184,7 +187,7 @@ public interface SparkJobRunner {
return new Job(service, runId, accountId, region, releaseLabel, engine, image, customImage, dockerNetwork,
executionRole, sparkDefaults, application, command, timeout, logFolder, cloudWatchLogs, environment,
archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j, hadoopEnvironment, executors,
platform, listenPort);
platform, listenPort, keepsEventLogs);
}
/** This job, its executors where {@code executors} has them. */
@@ -192,7 +195,7 @@ public interface SparkJobRunner {
return new Job(service, runId, accountId, region, releaseLabel, engine, imageTemplate, customImage,
dockerNetwork, executionRole, sparkDefaults, application, command, timeout, logFolder,
cloudWatchLogs, environment, archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j,
hadoopEnvironment, executors, platform, listenPort);
hadoopEnvironment, executors, platform, listenPort, keepsEventLogs);
}
/** This job, its driver listening on {@code port} for Floci (0 for none). */
@@ -200,7 +203,7 @@ public interface SparkJobRunner {
return new Job(service, runId, accountId, region, releaseLabel, engine, imageTemplate, customImage,
dockerNetwork, executionRole, sparkDefaults, application, command, timeout, logFolder,
cloudWatchLogs, environment, archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j,
hadoopEnvironment, executors, platform, port);
hadoopEnvironment, executors, platform, port, keepsEventLogs);
}
/** This job, its containers on {@code network} (null for the global default). */
@@ -208,7 +211,15 @@ public interface SparkJobRunner {
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);
executors, platform, listenPort, keepsEventLogs);
}
/** This job, its Spark event logs kept for its Spark History Server once it ends. */
public Job keepingEventLogs() {
return new Job(service, runId, accountId, region, releaseLabel, engine, imageTemplate, customImage,
dockerNetwork, executionRole, sparkDefaults, application, command, timeout, logFolder,
cloudWatchLogs, environment, archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j,
hadoopEnvironment, executors, platform, listenPort, true);
}
/** This job, its containers run for {@code platform} (null for the Docker host's own). */
@@ -216,7 +227,7 @@ public interface SparkJobRunner {
return new Job(service, runId, accountId, region, releaseLabel, engine, imageTemplate, customImage,
dockerNetwork, executionRole, sparkDefaults, application, command, timeout, logFolder,
cloudWatchLogs, environment, archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j,
hadoopEnvironment, executors, platform, listenPort);
hadoopEnvironment, executors, platform, listenPort, keepsEventLogs);
}
}