diff --git a/docs/services/emr-serverless.md b/docs/services/emr-serverless.md index 685fc944ad..98819dd8aa 100644 --- a/docs/services/emr-serverless.md +++ b/docs/services/emr-serverless.md @@ -142,31 +142,47 @@ runner mode a Spark run executes; see [Running Spark job runs](#running-spark-jo `networkConfiguration` come from the application. * **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. 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://-4040.emr-serverless-ui./`, 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. + valid for one hour after you generate it". "For jobs in a 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 or persistent Tez UI." With `runner-mode` set to `docker`, a Spark run's + link opens both for real, through Floci, each on a host of its own, `http://-.emr-serverless-ui./`, 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`. A link's host answers with a `403` page once its hour has passed, or when + it was given before Floci restarted. + * **While the attempt runs**, the link, on port 4040, opens its driver's Spark 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, and once the attempt has + ended, with a `404` one. + * **Once the attempt has ended**, the link, on port 18080, opens a Spark History Server over the run's event logs, + for the 30 days EMR Serverless keeps them: "By default, EMR Serverless stores application logs securely in Amazon + EMR managed storage for a maximum of 30 days". The run's driver writes its event logs where the release's image + says (`spark.eventLog.dir`, `file:///var/log/spark/apps`), on a Docker volume of the run's own, every attempt's + there, and the server runs in a container of the release's image that starts as its link is first opened, the host + answering with a `503` page until it answers, and stops once no link to it is valid. The server lists the run's + applications, one per attempt, rather than opening the attempt's. A history goes 30 days after its run ended, or + once its run has gone, which Floci checks as it starts and every hour; a restart keeps the histories, and a reset + removes them all. Each history and its server carry the owner label of the Floci that keeps them, so another + Floci sharing the Docker daemon leaves them alone. Where Docker cannot tell whether a history is kept, its host + answers with the `503` page too, rather than taking the history for gone. + * **Otherwise**, the link opens a page Floci serves at `/_aws/emr-serverless/dashboard` on its own address + (`base-url`, or `hostname`): for a run whose logs are not kept in managed storage, its + `managedPersistenceMonitoringConfiguration`, or else its application's, with `enabled` false, as with logs in S3 + alone the application UI is "Not supported" ("Otherwise, you can't use the built-in application UIs"), so Floci + keeps none of its event logs; for a run that turns its event logs off (`spark.eventLog.enabled`) or sends them + elsewhere (`spark.eventLog.dir`), as nothing is kept for a history server to read; for a Hive run, as Floci runs + no Tez UI; once a history has gone; and in the `immediate` mode. The page shows 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. Its 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, no 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 @@ -210,11 +226,13 @@ 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: "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. + `GetDashboardForJobRun`'s, valid for an hour: "While a session is active, the URL opens the live Apache Spark UI", + and "After a session ends, the Spark History Server remains available". 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, and one given after, + for 30 days, a Spark History Server over its kept event logs, 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, one given while the session + is `TERMINATING` among them, opens a page about the session on Floci's address. `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). @@ -259,8 +277,8 @@ The server's port is published on the Docker host's loopback interface only, and * **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. + once the session has ended. The server keeps its event logs on a volume of the session's own, so once the session has + ended a new link opens a Spark History Server over them, for 30 days, as a run's does. ## Running Spark job runs diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessAppUis.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessAppUis.java index f46ac5e27d..593ae0d2cc 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessAppUis.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessAppUis.java @@ -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 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 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 grants = new ConcurrentHashMap<>(); + // Where a history link's server was found, and when, by the link's secret. + private final Map 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 - * -.}{@value #UI_HOST}{@code .}. + * 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 -.}{@value #UI_HOST}{@code .}. */ @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 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 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(); + } + } } diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessDashboardController.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessDashboardController.java index d91ad7dcae..76f7f6161c 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessDashboardController.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessDashboardController.java @@ -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; diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessHistories.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessHistories.java new file mode 100644 index 0000000000..3a2ca0fffc --- /dev/null +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessHistories.java @@ -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 starting = ConcurrentHashMap.newKeySet(); + // The containers serving histories this process started, which a shutdown removes. + private final Set 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 labels(EmulatorConfig config, String runId, String accountId, String region, + String component) { + Map 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 Set stillKept(List records, Function id, Predicate ended, + Function endedAt, Instant cutoff) { + Set 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 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 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 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 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 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 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()); + } + } + } +} diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunService.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunService.java index ef7ef58d94..4bf8e116f4 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunService.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunService.java @@ -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 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 historiesKept(Instant cutoff) { + List 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; } /** diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSessionService.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSessionService.java index 454fc7de9f..d3dc13dcf8 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSessionService.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSessionService.java @@ -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 historiesKept(Instant cutoff) { + List 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}. diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java index bf73b7bbe5..5c0798cd5a 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java @@ -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())) diff --git a/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java b/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java index 29c88f6fa8..66c7411061 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java +++ b/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java @@ -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 environment, List archives, Storage storage, Map coreSite, Map sparkLog4j2, Map mapredSite, Map hadoopLog4j, - Map hadoopEnvironment, Executors executors, String platform, int listenPort) { + Map 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); } } diff --git a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessAppUisTest.java b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessAppUisTest.java index fe6d09341a..6e5bd5596f 100644 --- a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessAppUisTest.java +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessAppUisTest.java @@ -21,17 +21,23 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.net.URI; +import java.time.Duration; +import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.Set; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.LockSupport; +import java.util.function.Predicate; import java.util.function.Supplier; 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.assertTrue; import static org.junit.jupiter.api.Assertions.fail; @@ -42,8 +48,9 @@ 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. + * on a host of its own that routes to where Floci reaches the driver's UI, once the driver runs; once it has ended, for + * 30 days, its kept history's Spark History Server, which starts on a link and stops once no link to it is valid; any + * other, Floci's page. */ class EmrServerlessAppUisTest { @@ -54,9 +61,12 @@ class EmrServerlessAppUisTest { 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 static final ContainerLifecycleManager.EndpointInfo HISTORY_SERVER = + new ContainerLifecycleManager.EndpointInfo("127.0.0.1", 41808); private final ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule()); private final FakeDriverRunner runner = new FakeDriverRunner(); + private final FakeHistories histories = new FakeHistories(); 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); @@ -78,7 +88,7 @@ class EmrServerlessAppUisTest { 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); + histories, regionResolver, BASE_URL + "/", clock); } @AfterEach @@ -193,6 +203,148 @@ class EmrServerlessAppUisTest { assertTrue(appUis.sessionUrl(applicationId, terminated).startsWith(PAGE)); } + @Test + void onceItsRunHasEndedItsLinkOpensItsKeptHistoryUntilItsThirtyDaysHavePassed() { + String applicationId = application("SPARK"); + String jobRunId = jobRuns.startJobRun(applicationId, sparkRun()).getJobRunId(); + awaitRun(applicationId, jobRunId, "RUNNING"); + // Its driver kept its event logs, in the volume the runner made for them. + assertTrue(runner.jobs.get(jobRunId).keepsEventLogs()); + histories.keptRuns.add(jobRunId); + runner.end(jobRunId).complete(SparkJobRunner.Outcome.exitedWith(0)); + awaitRun(applicationId, jobRunId, "SUCCESS"); + + URI url = URI.create(appUis.jobRunUrl(applicationId, jobRunId, 1)); + + assertTrue(url.getAuthority().matches("[a-z2-7]{26}-18080\\.emr-serverless-ui\\.localhost:4566"), + url.toString()); + AppUiRoute starting = appUis.route(url.getAuthority(), "http"); + assertEquals(503, starting.status()); + assertEquals(EmrServerlessAppUis.HISTORY_NOT_READY, starting.refusal()); + // The server runs the release's image, on the runs' network. + assertEquals(List.of("server " + jobRunId + " public.ecr.aws/emr-serverless/spark/emr-7.13.0:latest"), + histories.events); + histories.servers.put(jobRunId, HISTORY_SERVER); + AppUiRoute route = appUis.route(url.getAuthority(), "http"); + assertNull(route.refusal()); + assertEquals(41808, route.port()); + assertEquals(EmrServerlessAppUis.HISTORY_NOT_READY, route.unanswered()); + // A live link's port is none of a history link's. + assertEquals(404, appUis.route(url.getAuthority().replace("-18080.", "-4040."), "http").status()); + + clock.advance(EmrServerlessHistories.KEPT); + assertTrue(appUis.jobRunUrl(applicationId, jobRunId, 1).startsWith(PAGE)); + } + + @Test + void aRunThatWritesNoEventLogsWhereTheyAreKeptKeepsNoneAndASessionDoes() { + String applicationId = application("SPARK"); + StartJobRunRequest unmanaged = sparkRun(); + unmanaged.setConfigurationOverrides(Map.of("monitoringConfiguration", + Map.of("managedPersistenceMonitoringConfiguration", Map.of("enabled", false)))); + String unmanagedRun = jobRuns.startJobRun(applicationId, unmanaged).getJobRunId(); + StartJobRunRequest off = sparkRun(); + off.getJobDriver().getSparkSubmit().setSparkSubmitParameters("--conf spark.eventLog.enabled=false"); + String offRun = jobRuns.startJobRun(applicationId, off).getJobRunId(); + StartJobRunRequest elsewhere = sparkRun(); + elsewhere.getJobDriver().getSparkSubmit().setSparkSubmitParameters("--conf spark.eventLog.dir=s3://logs/"); + String elsewhereRun = jobRuns.startJobRun(applicationId, elsewhere).getJobRunId(); + StartJobRunRequest same = sparkRun(); + same.getJobDriver().getSparkSubmit().setSparkSubmitParameters( + "--conf spark.eventLog.dir=file:/var/log/spark/apps/"); + String sameRun = jobRuns.startJobRun(applicationId, same).getJobRunId(); + String sessionId = sessions.startSession(applicationId, sessionRequest()).getSessionId(); + for (String run : List.of(unmanagedRun, offRun, elsewhereRun, sameRun)) { + awaitRun(applicationId, run, "RUNNING"); + } + awaitSession(applicationId, sessionId, "IDLE"); + + assertFalse(runner.jobs.get(unmanagedRun).keepsEventLogs()); + // A run that turns its event logs off, or sends them elsewhere, leaves nothing for a kept history to show. + assertFalse(runner.jobs.get(offRun).keepsEventLogs()); + assertFalse(runner.jobs.get(elsewhereRun).keepsEventLogs()); + assertTrue(runner.jobs.get(sameRun).keepsEventLogs()); + assertTrue(runner.jobs.get(sessionId).keepsEventLogs()); + } + + @Test + void whereDockerCannotTellWhetherAHistoryIsKeptItsLinkAsksToTryAgain() { + String applicationId = application("SPARK"); + String jobRunId = jobRuns.startJobRun(applicationId, sparkRun()).getJobRunId(); + awaitRun(applicationId, jobRunId, "RUNNING"); + runner.end(jobRunId).complete(SparkJobRunner.Outcome.exitedWith(0)); + awaitRun(applicationId, jobRunId, "SUCCESS"); + histories.keptFailure = new IllegalStateException("Docker is not answering"); + + URI url = URI.create(appUis.jobRunUrl(applicationId, jobRunId, 1)); + + // Not taken for a history that has gone. + assertTrue(url.getAuthority().contains("-18080."), url.toString()); + AppUiRoute route = appUis.route(url.getAuthority(), "http"); + assertEquals(503, route.status()); + assertEquals(EmrServerlessAppUis.HISTORY_NOT_READY, route.refusal()); + } + + @Test + void theContainerServingAKeptHistoryStopsOnceNoLinkToItIsValid() { + String applicationId = application("SPARK"); + String jobRunId = jobRuns.startJobRun(applicationId, sparkRun()).getJobRunId(); + awaitRun(applicationId, jobRunId, "RUNNING"); + histories.keptRuns.add(jobRunId); + runner.end(jobRunId).complete(SparkJobRunner.Outcome.exitedWith(0)); + awaitRun(applicationId, jobRunId, "SUCCESS"); + appUis.jobRunUrl(applicationId, jobRunId, 1); + + appUis.reap(jobRunId); + assertFalse(histories.events.contains("stopped " + jobRunId)); + clock.advance(EmrServerlessDashboards.VALIDITY); + appUis.reap(jobRunId); + + assertTrue(histories.events.contains("stopped " + jobRunId)); + // The histories within their 30 days stay, the run's among them. + assertTrue(histories.lastSweep.test(jobRunId)); + } + + @Test + void aKeptHistoryGoesOnceItsThirtyDaysHavePassedAndEveryHistoryOnAReset() { + String applicationId = application("SPARK"); + String jobRunId = jobRuns.startJobRun(applicationId, sparkRun()).getJobRunId(); + awaitRun(applicationId, jobRunId, "RUNNING"); + appUis.removeExpiredHistories(); + // A run that has not ended keeps its history, as its driver writes it. + assertTrue(histories.lastSweep.test(jobRunId)); + runner.end(jobRunId).complete(SparkJobRunner.Outcome.exitedWith(0)); + awaitRun(applicationId, jobRunId, "SUCCESS"); + + clock.advance(EmrServerlessHistories.KEPT.minusSeconds(1)); + appUis.removeExpiredHistories(); + assertTrue(histories.lastSweep.test(jobRunId)); + clock.advance(Duration.ofSeconds(2)); + appUis.removeExpiredHistories(); + assertFalse(histories.lastSweep.test(jobRunId)); + // A run or session that has gone has no history to keep. + assertFalse(histories.lastSweep.test("00fnosuchrun0001")); + + appUis.clear(); + assertFalse(histories.lastSweep.test(jobRunId)); + } + + @Test + void anEndedSessionsLinkOpensItsKeptHistory() { + String applicationId = application("SPARK"); + String sessionId = sessions.startSession(applicationId, sessionRequest()).getSessionId(); + awaitSession(applicationId, sessionId, "IDLE"); + histories.keptRuns.add(sessionId); + histories.servers.put(sessionId, HISTORY_SERVER); + sessions.terminateSession(applicationId, sessionId); + Session terminated = awaitSession(applicationId, sessionId, "TERMINATED"); + + URI url = URI.create(appUis.sessionUrl(applicationId, terminated)); + + assertTrue(url.getAuthority().contains("-18080.emr-serverless-ui."), url.toString()); + assertEquals(41808, appUis.route(url.getAuthority(), "http").port()); + } + @Test void inTheImmediateRunnerModeEveryLinkOpensFlocisPage() { IamService iamService = mock(IamService.class); @@ -201,7 +353,7 @@ class EmrServerlessAppUisTest { 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); + new byte[32]), immediate, sessions, histories, regionResolver, BASE_URL, clock); String applicationId = application("SPARK"); String jobRunId = immediate.startJobRun(applicationId, sparkRun()).getJobRunId(); @@ -274,6 +426,46 @@ class EmrServerlessAppUisTest { return request; } + /** Kept histories as Docker would hold them: which are kept, and which have a server that answers. */ + private static final class FakeHistories extends EmrServerlessHistories { + final Set keptRuns = ConcurrentHashMap.newKeySet(); + final Map servers = new ConcurrentHashMap<>(); + final List events = new CopyOnWriteArrayList<>(); + volatile Predicate lastSweep; + volatile RuntimeException keptFailure; + + FakeHistories() { + super(null, null, null, Runnable::run); + } + + @Override + boolean kept(String runId) { + if (keptFailure != null) { + throw keptFailure; + } + return keptRuns.contains(runId); + } + + @Override + Optional server(String runId, String accountId, String region, + String image, String network) { + if (!servers.containsKey(runId)) { + events.add("server " + runId + " " + image); + } + return Optional.ofNullable(servers.get(runId)); + } + + @Override + void stop(String runId) { + events.add("stopped " + runId); + } + + @Override + void removeAllBut(Predicate kept) { + lastSweep = kept; + } + } + /** * 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. @@ -281,10 +473,12 @@ class EmrServerlessAppUisTest { private static final class FakeDriverRunner implements SparkJobRunner { volatile CompletableFuture starting = CompletableFuture.completedFuture(null); final Map> ends = new ConcurrentHashMap<>(); + final Map jobs = new ConcurrentHashMap<>(); private final Map driverUis = new ConcurrentHashMap<>(); @Override public Outcome run(Job job, Progress progress) { + jobs.put(job.runId(), job); starting.join(); if (progress.cancelled()) { return Outcome.halted(); diff --git a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessDashboardNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessDashboardNightlyIntegrationTest.java index 8dc0782e7f..c2ae44e58a 100644 --- a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessDashboardNightlyIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessDashboardNightlyIntegrationTest.java @@ -1,5 +1,8 @@ package io.floci.aws.services.emrserverless; +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.docker.ContainerLifecycleManager; +import io.floci.aws.core.common.docker.ContainerStorageHelper; import io.floci.aws.testing.AwsTestClients; import io.floci.aws.testing.DockerAvailability; import io.floci.aws.testing.PartitionCleanup; @@ -8,6 +11,7 @@ import io.floci.aws.testing.S3TestClients; import io.quarkus.test.junit.QuarkusTest; import io.quarkus.test.junit.TestProfile; import io.restassured.response.Response; +import jakarta.inject.Inject; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; @@ -37,8 +41,9 @@ 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. + * application, and once the run is cancelled the link reaches nothing and a new one opens the Spark History Server of + * its kept event logs, which names it too; GetResourceDashboard's link, while a session is idle, opens its Spark + * Connect server's Spark UI, and once it has ended, its kept history's. * *

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. @@ -69,13 +74,19 @@ class EmrServerlessDashboardNightlyIntegrationTest { @RegisterExtension final PartitionCleanup cleanup = new PartitionCleanup(); + @Inject + ContainerLifecycleManager lifecycleManager; + + @Inject + EmulatorConfig config; + @BeforeAll static void configure() { RestAssuredJsonUtils.configureAwsContentTypes(); } @Test - void aRunningRunsAndAnIdleSessionsDashboardLinksOpenTheirDriversSparkUi() throws InterruptedException { + void aRunsAndASessionsDashboardLinksOpenTheirSparkUiThenTheirKeptHistory() 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); @@ -96,6 +107,7 @@ class EmrServerlessDashboardNightlyIntegrationTest { "jobDriver": {"sparkSubmit": {"entryPoint": "s3://%s/job.py"}}} """.formatted(UUID.randomUUID(), ROLE, bucket)); String run = "/applications/" + applicationId + "/jobruns/" + jobRunId; + removeHistoryAfter(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); @@ -117,9 +129,12 @@ class EmrServerlessDashboardNightlyIntegrationTest { 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) + // Its event logs were kept: a new link opens the Spark History Server reading them, once it has started. + String history = emrServerless(REGION).when().get(run + "/dashboard").then().statusCode(200) .extract().path("url"); - assertTrue(page.startsWith("http://localhost:" + PORT + EmrServerlessDashboards.PATH + "?"), page); + assertTrue(URI.create(history).getAuthority().contains("-18080.emr-serverless-ui."), history); + Response kept = awaitApplications(history, NAME); + assertEquals(List.of(NAME), kept.jsonPath().getList("name"), kept.asString()); String sessionId = emrServerless(REGION).body(""" {"clientToken": "%s", "executionRoleArn": "%s", "idleTimeoutMinutes": 30} @@ -127,6 +142,7 @@ class EmrServerlessDashboardNightlyIntegrationTest { .when().post("/applications/" + applicationId + "/sessions") .then().statusCode(200).extract().path("sessionId"); String session = "/applications/" + applicationId + "/sessions/" + sessionId; + removeHistoryAfter(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); @@ -141,6 +157,31 @@ class EmrServerlessDashboardNightlyIntegrationTest { 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()); + String sessionHistory = emrServerless(REGION).queryParam("resourceId", sessionId) + .queryParam("resourceType", "SESSION") + .when().get("/applications/" + applicationId + "/dashboard") + .then().statusCode(200).extract().path("url"); + assertTrue(URI.create(sessionHistory).getAuthority().contains("-18080.emr-serverless-ui."), sessionHistory); + Response sessionKept = awaitApplications(sessionHistory, "SparkConnectServer"); + assertEquals(1, sessionKept.jsonPath().getList("name").size(), sessionKept.asString()); + } + + // A run's or session's kept history, and the container serving it, which a link left running, go once the test + // has: Floci keeps a history for 30 days, past any test. + private void removeHistoryAfter(String runId) { + cleanup.register(() -> lifecycleManager.removeVolume(EmrServerlessHistories.volume(config, runId))); + cleanup.register(() -> lifecycleManager.removeIfExists(ContainerStorageHelper.dockerName(config, + "emr-serverless-" + runId + "-history-ui"))); + } + + // The applications a history's server lists once one of them is named, as it reads the event logs at an interval. + private static Response awaitApplications(String url, String named) { + Response[] page = new Response[1]; + await(() -> { + page[0] = open(url + "api/v1/applications"); + return page[0].statusCode() + " " + page[0].asString(); + }, now -> now.startsWith("200 ") && now.contains(named), Duration.ofMinutes(3), url); + return page[0]; } // 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 diff --git a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessHistoriesTest.java b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessHistoriesTest.java new file mode 100644 index 0000000000..275b268698 --- /dev/null +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessHistoriesTest.java @@ -0,0 +1,214 @@ +package io.floci.aws.services.emrserverless; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.InspectVolumeResponse; +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.ContainerExecStubs; +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 org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.RETURNS_SELF; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * EMR Serverless runs' and sessions' kept histories in Docker ({@link EmrServerlessHistories}): a history is its + * volume, and a Spark History Server reads it in a container of its own, started on demand, reached once it answers, + * and removed with the histories that are no longer kept. + */ +class EmrServerlessHistoriesTest { + + private static final String RUN = "00f0000000000001"; + private static final String IMAGE = "public.ecr.aws/emr-serverless/spark/emr-7.13.0:latest"; + + private final EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + private final ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class); + private final DockerClient docker = mock(DockerClient.class, RETURNS_DEEP_STUBS); + private final ContainerBuilder builder = mock(ContainerBuilder.class); + private final ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF); + // The starts it hands off, run when the test says. + private final List starts = new ArrayList<>(); + private final EmrServerlessHistories histories = new EmrServerlessHistories(builder, lifecycle, config, + starts::add); + + @Test + void aKeptHistorysServerStartsFromTheImageWithItsVolumeAndIsReachedOnceItAnswers() { + String volume = EmrServerlessHistories.volume(config, RUN); + String server = ContainerStorageHelper.dockerName(config, "emr-serverless-" + RUN + "-history-ui"); + when(builder.newContainer(IMAGE)).thenReturn(spec); + when(lifecycle.volumeExists(volume)).thenReturn(true); + when(lifecycle.probeContainer(server)).thenReturn(ContainerLiveness.NOT_RUNNING); + when(lifecycle.getDockerClient()).thenReturn(docker); + labelled(volume); + + assertEquals(Optional.empty(), histories.server(RUN, "000000000000", "us-east-1", IMAGE, "floci-network")); + starts.removeFirst().run(); + + verify(spec).withName(server); + verify(spec).withNamedVolume(volume, EmrServerlessHistories.EVENT_LOGS); + verify(spec).withLoopbackPortBinding(EmrServerlessSparkRunner.SPARK_HISTORY_WEB_PORT, 0); + verify(spec).withDockerNetwork(Optional.of("floci-network")); + verify(spec).withEntrypoint(argThat((List entrypoint) -> + entrypoint.getLast().contains("org.apache.spark.deploy.history.HistoryServer") + && entrypoint.getLast().contains("file://" + EmrServerlessHistories.EVENT_LOGS))); + verify(spec).withLabels(argThat(labels -> RUN.equals(labels.get(ContainerStorageHelper.RESOURCE_ID_LABEL)) + && EmrServerlessHistories.SERVER_COMPONENT.equals(labels.get(ContainerStorageHelper.COMPONENT_LABEL)) + && ContainerStorageHelper.ownerIdentity(config).equals( + labels.get(ContainerStorageHelper.OWNER_LABEL)))); + verify(lifecycle).createAndStart(any()); + verify(lifecycle, never()).removeVolume(anyString()); + + // Running, it is reached once its REST API answers. + when(lifecycle.probeContainer(server)).thenReturn(ContainerLiveness.RUNNING); + List> asked = ContainerExecStubs.completeEveryExec(docker, server, 0L, "{}", ""); + ContainerLifecycleManager.EndpointInfo endpoint = new ContainerLifecycleManager.EndpointInfo("localhost", + 32818); + when(lifecycle.resolveEndpoint(server, EmrServerlessSparkRunner.SPARK_HISTORY_WEB_PORT, "floci-network")) + .thenReturn(endpoint); + assertEquals(Optional.of(endpoint), + histories.server(RUN, "000000000000", "us-east-1", IMAGE, "floci-network")); + assertTrue(asked.getFirst().getLast().endsWith("/api/v1/version"), asked.toString()); + } + + @Test + void aHistoryThatHasGoneStartsNoServer() { + String server = ContainerStorageHelper.dockerName(config, "emr-serverless-" + RUN + "-history-ui"); + when(lifecycle.probeContainer(server)).thenReturn(ContainerLiveness.NOT_RUNNING); + + assertEquals(Optional.empty(), histories.server(RUN, "000000000000", "us-east-1", IMAGE, null)); + starts.removeFirst().run(); + + verify(lifecycle, never()).createAndStart(any()); + verify(builder, never()).newContainer(anyString()); + } + + @Test + void aServerAskedForBeforeATeardownStartsNoneAfterIt() { + String server = ContainerStorageHelper.dockerName(config, "emr-serverless-" + RUN + "-history-ui"); + when(lifecycle.volumeExists(EmrServerlessHistories.volume(config, RUN))).thenReturn(true); + when(lifecycle.probeContainer(server)).thenReturn(ContainerLiveness.NOT_RUNNING); + + histories.server(RUN, "000000000000", "us-east-1", IMAGE, null); + histories.stopServers(); + starts.removeFirst().run(); + + verify(lifecycle, never()).createAndStart(any()); + } + + @Test + void aServerStartedThroughATeardownGoes() { + String volume = EmrServerlessHistories.volume(config, RUN); + String server = ContainerStorageHelper.dockerName(config, "emr-serverless-" + RUN + "-history-ui"); + when(builder.newContainer(IMAGE)).thenReturn(spec); + when(lifecycle.volumeExists(volume)).thenReturn(true); + when(lifecycle.probeContainer(server)).thenReturn(ContainerLiveness.NOT_RUNNING); + when(lifecycle.getDockerClient()).thenReturn(docker); + labelled(volume); + // A shutdown while the container is made, which may miss it. + doAnswer(created -> { + histories.stopServers(); + return null; + }).when(lifecycle).createAndStart(any()); + + histories.server(RUN, "000000000000", "us-east-1", IMAGE, null); + starts.removeFirst().run(); + + // As it starts, an earlier one's; by the shutdown; and once it has started, the shutdown's removal having + // come before the container was there. + verify(lifecycle, times(3)).removeIfExistsStrict(server); + verify(lifecycle, never()).removeVolume(anyString()); + } + + @Test + void aServerWhoseHistoryWentAsItStartedGoesWithTheVolumeDockerMadeForIt() { + String volume = EmrServerlessHistories.volume(config, RUN); + String server = ContainerStorageHelper.dockerName(config, "emr-serverless-" + RUN + "-history-ui"); + when(builder.newContainer(IMAGE)).thenReturn(spec); + when(lifecycle.volumeExists(volume)).thenReturn(true); + when(lifecycle.probeContainer(server)).thenReturn(ContainerLiveness.NOT_RUNNING); + when(lifecycle.getDockerClient()).thenReturn(docker); + // Docker made it again, with no labels, as the container mounted it. + when(docker.inspectVolumeCmd(volume).exec().getLabels()).thenReturn(null); + + histories.server(RUN, "000000000000", "us-east-1", IMAGE, null); + starts.removeFirst().run(); + + verify(lifecycle, times(2)).removeIfExistsStrict(server); + verify(lifecycle).removeVolume(volume); + } + + @Test + void theHistoriesNotKeptGoWithTheirServers() { + when(lifecycle.getDockerClient()).thenReturn(docker); + Container keptServer = container("server-kept", "00fkept000000001"); + Container goneServer = container("server-gone", "00fgone000000001"); + String owner = ContainerStorageHelper.OWNER_LABEL + "=" + ContainerStorageHelper.ownerIdentity(config); + // Only this Floci's, by its owner label: another sharing the Docker daemon keeps its own. + when(docker.listContainersCmd().withShowAll(true).withLabelFilter(List.of(ContainerStorageHelper.COMPONENT_LABEL + + "=" + EmrServerlessHistories.SERVER_COMPONENT, owner)).exec()).thenReturn(List.of(keptServer, + goneServer)); + InspectVolumeResponse keptVolume = volume("volume-kept", "00fkept000000001"); + InspectVolumeResponse goneVolume = volume("volume-gone", "00fgone000000001"); + when(docker.listVolumesCmd().withFilter(eq("label"), eq(List.of(ContainerStorageHelper.COMPONENT_LABEL + "=" + + EmrServerlessHistories.VOLUME_COMPONENT, owner))).exec().getVolumes()) + .thenReturn(List.of(keptVolume, goneVolume)); + + histories.removeAllBut("00fkept000000001"::equals); + + verify(lifecycle).removeIfExistsStrict("server-gone"); + verify(lifecycle, never()).removeIfExistsStrict("server-kept"); + verify(lifecycle).removeVolume("volume-gone"); + verify(lifecycle, never()).removeVolume("volume-kept"); + } + + @Test + void aHistorysVolumeIsLabelledForItsRunAndTheService() { + Map labels = EmrServerlessHistories.labels(config, RUN, "000000000000", "us-east-1", + EmrServerlessHistories.VOLUME_COMPONENT); + + assertEquals(RUN, labels.get(ContainerStorageHelper.RESOURCE_ID_LABEL)); + assertEquals(EmrServerlessJobRunService.SERVICE, labels.get(ContainerStorageHelper.SERVICE_LABEL)); + assertEquals(EmrServerlessHistories.VOLUME_COMPONENT, labels.get(ContainerStorageHelper.COMPONENT_LABEL)); + assertEquals(ContainerStorageHelper.ownerIdentity(config), labels.get(ContainerStorageHelper.OWNER_LABEL)); + } + + // The volume is the runner's, with its labels. + private void labelled(String volume) { + when(docker.inspectVolumeCmd(volume).exec().getLabels()).thenReturn(Map.of( + ContainerStorageHelper.COMPONENT_LABEL, EmrServerlessHistories.VOLUME_COMPONENT)); + } + + private static Container container(String id, String runId) { + Container container = mock(Container.class); + when(container.getId()).thenReturn(id); + when(container.getLabels()).thenReturn(Map.of(ContainerStorageHelper.RESOURCE_ID_LABEL, runId)); + return container; + } + + private static InspectVolumeResponse volume(String name, String runId) { + InspectVolumeResponse volume = mock(InspectVolumeResponse.class); + when(volume.getName()).thenReturn(name); + when(volume.getLabels()).thenReturn(Map.of(ContainerStorageHelper.RESOURCE_ID_LABEL, runId)); + return volume; + } +} diff --git a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunnerTest.java b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunnerTest.java index 84c5fe06f3..b30ccad81c 100644 --- a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunnerTest.java +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunnerTest.java @@ -433,6 +433,29 @@ class EmrServerlessSparkRunnerTest { assertFalse(EmrServerlessSparkRunner.servesDriverUi(stepJob(Map.of()))); } + @Test + void aRunThatKeepsItsEventLogsHasThemInAVolumeOfItsOwnAndAStepDoesNot() { + ContainerBuilder builder = mock(ContainerBuilder.class); + ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF); + when(builder.newContainer(anyString())).thenReturn(spec); + EmrServerlessSparkRunner runner = runner(builder); + String volume = EmrServerlessHistories.volume(config, "00f0000000000001"); + + runner.run(job(List.of("s3://bucket/jobs/app.jar"), Map.of()).keepingEventLogs(), progress); + runner.run(stepJob(Map.of()).keepingEventLogs(), progress); + + // Where the release's image writes them, which its Spark History Server reads once it has ended. + verify(lifecycle).ensureVolume(eq(volume), argThat(labels -> + "00f0000000000001".equals(labels.get(ContainerStorageHelper.RESOURCE_ID_LABEL)) + && EmrServerlessHistories.VOLUME_COMPONENT.equals( + labels.get(ContainerStorageHelper.COMPONENT_LABEL)) + && ContainerStorageHelper.ownerIdentity(config).equals( + labels.get(ContainerStorageHelper.OWNER_LABEL)))); + verify(spec).withNamedVolume(volume, EmrServerlessHistories.EVENT_LOGS); + verify(lifecycle, never()).ensureVolume(eq(EmrServerlessHistories.volume(config, "s-1A2B3C4D5E6F7")), + any()); + } + @Test void onTheHostsNetworkADriverServesNoUiForFloci() { SparkJobRunner.Job job = job(List.of("s3://bucket/jobs/app.jar"), Map.of());