diff --git a/docs/services/emr-serverless.md b/docs/services/emr-serverless.md index f4af7f93e7..a51ab66874 100644 --- a/docs/services/emr-serverless.md +++ b/docs/services/emr-serverless.md @@ -33,6 +33,7 @@ The emulator implements the standard AWS `emr-serverless` service endpoints: * `GET /applications/{applicationId}/jobruns/{jobRunId}` (GetJobRun) * `DELETE /applications/{applicationId}/jobruns/{jobRunId}` (CancelJobRun) * `GET /applications/{applicationId}/jobruns/{jobRunId}/attempts` (ListJobRunAttempts) +* `GET /applications/{applicationId}/jobruns/{jobRunId}/dashboard` (GetDashboardForJobRun) * `POST /tags/{resourceArn}` (TagResource) * `DELETE /tags/{resourceArn}?tagKeys=...` (UntagResource) * `GET /tags/{resourceArn}` (ListTagsForResource) @@ -130,6 +131,16 @@ runner mode a Spark run executes; see [Running Spark job runs](#running-spark-jo No source says whether a run's timeout spans its attempts; Floci applies it to each. * `createdBy` is the caller's ARN, as `GetCallerIdentity` reports it. `releaseLabel` and `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; Floci keeps neither, so the URL opens a page Floci + serves at `/_aws/emr-serverless/dashboard` on its own address (`base-url`, or `hostname`), with the attempt's + state, its times and where its driver's logs go in S3 and in CloudWatch Logs, kept as the attempt was admitted, so + a later change to the application's monitoring configuration does not move them. The link names the run and is signed + with a key Floci makes as it starts: one changed, or past its hour, or given before Floci restarted, opens a `403` + page asking for a new one, and one whose run has gone a `404`. Like the rest of Floci, the page asks for no + credentials. `accessSystemProfileLogs`, for jobs on Lake Formation, changes nothing. 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). diff --git a/src/main/java/io/floci/aws/core/common/Html.java b/src/main/java/io/floci/aws/core/common/Html.java new file mode 100644 index 0000000000..0c6f6fceaa --- /dev/null +++ b/src/main/java/io/floci/aws/core/common/Html.java @@ -0,0 +1,17 @@ +package io.floci.aws.core.common; + +/** Text put into an HTML page Floci serves, escaped so that it is shown as it is and never read as markup. */ +public final class Html { + + private Html() { + } + + /** + * {@code value} with each character HTML reads as markup, in an element's text or in an attribute quoted either + * way, written as its entity. + */ + public static String escape(String value) { + return value.replace("&", "&").replace("<", "<").replace(">", ">") + .replace("\"", """).replace("'", "'"); + } +} diff --git a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactPypiController.java b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactPypiController.java index 48e5b22daa..c4fc008619 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactPypiController.java +++ b/src/main/java/io/floci/aws/services/codeartifact/CodeArtifactPypiController.java @@ -1,6 +1,7 @@ package io.floci.aws.services.codeartifact; import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.Html; import io.floci.aws.core.common.MultipartFormParser; import io.floci.aws.core.common.StreamingResponses; import io.floci.aws.services.codeartifact.CodeArtifactService.AuthorizationTokenScope; @@ -203,13 +204,13 @@ public class CodeArtifactPypiController { extra.append("").append(escapeHtml(file.filename())).append("
\n"); + extra.append(">").append(Html.escape(file.filename())).append("
\n"); } if (bodyHtmlOrNull == null) { return "\n" + extra + ""; @@ -221,10 +222,6 @@ public class CodeArtifactPypiController { return bodyHtmlOrNull.substring(0, bodyClose) + extra + bodyHtmlOrNull.substring(bodyClose); } - private static String escapeHtml(String value) { - return value.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """); - } - /** * pypi's real download route is a bare filename with no package name or version anywhere in * the URL, unlike Maven's GAV path or nuget's content route, so there is nothing in a download diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessController.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessController.java index 702e17227a..a5146c3e1d 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessController.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessController.java @@ -2,6 +2,7 @@ package io.floci.aws.services.emrserverless; import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.core.common.Pagination; +import io.floci.aws.core.common.RegionResolver; import io.floci.aws.services.emrserverless.model.Application; import io.floci.aws.services.emrserverless.model.ApplicationSummary; import io.floci.aws.services.emrserverless.model.CancelJobRunResponse; @@ -9,6 +10,7 @@ import io.floci.aws.services.emrserverless.model.CreateApplicationRequest; import io.floci.aws.services.emrserverless.model.CreateApplicationResponse; import io.floci.aws.services.emrserverless.model.DeleteApplicationResponse; import io.floci.aws.services.emrserverless.model.GetApplicationResponse; +import io.floci.aws.services.emrserverless.model.GetDashboardForJobRunResponse; import io.floci.aws.services.emrserverless.model.GetJobRunResponse; import io.floci.aws.services.emrserverless.model.JobRun; import io.floci.aws.services.emrserverless.model.JobRunAttemptSummary; @@ -46,11 +48,16 @@ public class EmrServerlessController { private final EmrServerlessService service; private final EmrServerlessJobRunService jobRuns; + private final EmrServerlessDashboards dashboards; + private final RegionResolver regionResolver; @Inject - public EmrServerlessController(EmrServerlessService service, EmrServerlessJobRunService jobRuns) { + public EmrServerlessController(EmrServerlessService service, EmrServerlessJobRunService jobRuns, + EmrServerlessDashboards dashboards, RegionResolver regionResolver) { this.service = service; this.jobRuns = jobRuns; + this.dashboards = dashboards; + this.regionResolver = regionResolver; } @POST @@ -167,6 +174,23 @@ public class EmrServerlessController { return response; } + /** + * The link to a run's application UI, for the attempt asked for or else the latest, the run and attempt checked as + * GetJobRun checks them ({@link EmrServerlessDashboards}). {@code accessSystemProfileLogs} is for jobs on Lake + * Formation, which Floci runs none of, so it changes nothing. + */ + @GET + @Path("/{applicationId}/jobruns/{jobRunId}/dashboard") + public GetDashboardForJobRunResponse getDashboardForJobRun(@PathParam("applicationId") String applicationId, + @PathParam("jobRunId") String jobRunId, + @QueryParam("attempt") String attempt) { + JobRun run = jobRuns.getJobRun(applicationId, jobRunId, EmrServerlessJobRunService.parseAttempt(attempt)); + GetDashboardForJobRunResponse response = new GetDashboardForJobRunResponse(); + response.setUrl(dashboards.url(regionResolver.getAccountId(), regionResolver.getRegion(), applicationId, + jobRunId, run.getAttempt() != null ? run.getAttempt() : 1)); + return response; + } + @GET @Path("/{applicationId}/jobruns/{jobRunId}/attempts") public ListJobRunAttemptsResponse listJobRunAttempts(@PathParam("applicationId") String applicationId, diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessDashboardController.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessDashboardController.java new file mode 100644 index 0000000000..efd09b8d86 --- /dev/null +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessDashboardController.java @@ -0,0 +1,101 @@ +package io.floci.aws.services.emrserverless; + +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.Html; +import io.floci.aws.core.common.RequestScopes; +import io.floci.aws.services.emrserverless.model.JobRun; +import jakarta.inject.Inject; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; + +import java.util.ArrayList; +import java.util.List; + +/** + * The page a {@code GetDashboardForJobRun} link opens ({@link EmrServerlessDashboards}). EMR Serverless opens the run's + * live Spark or Tez UI while it runs and its Spark History Server or persistent Tez UI once it has ended; Floci keeps + * neither, so the page shows the attempt as GetJobRun gives it and where its driver's logs go, as it was admitted. 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 + * has gone. Like the rest of Floci the page takes no AWS credentials: the link is all it asks for. + */ +@Path(EmrServerlessDashboards.PATH) +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 for a new one."; + static final String NO_UI = "Floci keeps no Spark UI, Tez UI or Spark History Server for a job run, so this page" + + " stands in for the application UI EMR Serverless opens. The driver's output is in its logs."; + + private final EmrServerlessDashboards dashboards; + private final EmrServerlessJobRunService jobRuns; + + @Inject + public EmrServerlessDashboardController(EmrServerlessDashboards dashboards, EmrServerlessJobRunService jobRuns) { + this.dashboards = dashboards; + this.jobRuns = jobRuns; + } + + @GET + @Produces(MediaType.TEXT_HTML) + public Response dashboard(@QueryParam("account") String accountId, @QueryParam("region") String region, + @QueryParam("application") String applicationId, + @QueryParam("jobRun") String jobRunId, @QueryParam("attempt") String attempt, + @QueryParam("expires") String expires, + @QueryParam("signature") String signature) { + EmrServerlessDashboards.Link link = dashboards.verified(accountId, region, applicationId, jobRunId, attempt, + expires, signature); + if (link == null) { + return page(403, "Job run dashboard", List.of("

" + Html.escape(INVALID) + "

")); + } + EmrServerlessJobRunService.DashboardView view; + try { + view = RequestScopes.callAs(link.accountId(), link.region(), + () -> jobRuns.dashboard(link.applicationId(), link.jobRunId(), link.attempt())); + } catch (AwsException e) { + return page(404, "Job run " + link.jobRunId(), List.of("

" + Html.escape(e.getMessage()) + "

")); + } + return page(200, "Job run " + link.jobRunId(), body(view)); + } + + private static List body(EmrServerlessJobRunService.DashboardView view) { + JobRun run = view.run(); + List lines = new ArrayList<>(); + lines.add(""); + row(lines, "Application", run.getApplicationId()); + row(lines, "Job run", run.getJobRunId()); + row(lines, "Name", run.getName()); + row(lines, "Attempt", run.getAttempt() != null ? String.valueOf(run.getAttempt()) : null); + row(lines, "State", run.getState()); + row(lines, "State details", run.getStateDetails()); + row(lines, "Release label", run.getReleaseLabel()); + row(lines, "Created", run.getCreatedAt() != null ? run.getCreatedAt().toString() : null); + row(lines, "Updated", run.getUpdatedAt() != null ? run.getUpdatedAt().toString() : null); + row(lines, "Driver logs in S3", view.logs().s3Folder()); + row(lines, "Driver logs in CloudWatch Logs", view.logs().logGroup()); + row(lines, "Driver stdout stream", view.logs().stdoutStream()); + row(lines, "Driver stderr stream", view.logs().stderrStream()); + lines.add("
"); + lines.add("

" + Html.escape(NO_UI) + "

"); + return lines; + } + + // A row of the table, left out when the run has no such value. + private static void row(List lines, String name, String value) { + if (value != null && !value.isEmpty()) { + lines.add("" + Html.escape(name) + "" + Html.escape(value) + ""); + } + } + + private static Response page(int status, String title, List body) { + String html = "\n" + + "" + Html.escape(title) + + "\n\n

" + Html.escape(title) + "

\n" + + String.join("\n", body) + "\n\n"; + return Response.status(status).type(MediaType.TEXT_HTML).entity(html).build(); + } +} diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessDashboards.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessDashboards.java new file mode 100644 index 0000000000..c5fee03562 --- /dev/null +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessDashboards.java @@ -0,0 +1,109 @@ +package io.floci.aws.services.emrserverless; + +import io.floci.aws.config.EmulatorConfig; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Duration; +import java.util.HexFormat; + +/** + * The links {@code GetDashboardForJobRun} gives: "a URL that you can use to access the application UIs for a job run", + * which "is valid for one hour after you generate it. To access the application UI after that hour elapses, you must + * invoke the API again to generate a new URL." Floci keeps no Spark UI or Spark History Server for a run, so a link + * opens a page of Floci's own about the run ({@link EmrServerlessDashboardController}). It names the run's account, + * Region, application, run and attempt, and when it expires, signed with a key this process makes: a link changed, or + * past its hour, opens nothing, and the links given before a restart open nothing after it. + */ +@ApplicationScoped +public class EmrServerlessDashboards { + + /** Where Floci serves the page a link opens. */ + static final String PATH = "/_aws/emr-serverless/dashboard"; + static final Duration VALIDITY = Duration.ofHours(1); + private static final String ALGORITHM = "HmacSHA256"; + private static final int KEY_BYTES = 32; + + private final String baseUrl; + private final Clock clock; + private final byte[] key; + + @Inject + public EmrServerlessDashboards(EmulatorConfig config, Clock clock) { + this(config.effectiveBaseUrl(), clock, newKey()); + } + + EmrServerlessDashboards(String baseUrl, Clock clock, byte[] key) { + this.baseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl; + this.clock = clock; + this.key = key.clone(); + } + + /** What a link names: one attempt of a run, and the second, since the epoch, it expires at. */ + public record Link(String accountId, String region, String applicationId, String jobRunId, int attempt, + long expires) { + } + + /** A link to a run's attempt, valid for {@link #VALIDITY} from now. */ + public String url(String accountId, String region, String applicationId, String jobRunId, int attempt) { + Link link = new Link(accountId, region, applicationId, jobRunId, attempt, + clock.instant().plus(VALIDITY).getEpochSecond()); + return baseUrl + PATH + "?account=" + encoded(accountId) + "®ion=" + encoded(region) + + "&application=" + encoded(applicationId) + "&jobRun=" + encoded(jobRunId) + + "&attempt=" + attempt + "&expires=" + link.expires() + "&signature=" + signature(link); + } + + /** + * The link a page request's parameters name, or null when one is missing or malformed, the signature is not this + * process's for them, or the link has expired. + */ + public Link verified(String accountId, String region, String applicationId, String jobRunId, String attempt, + String expires, String signature) { + if (accountId == null || region == null || applicationId == null || jobRunId == null || signature == null) { + return null; + } + Link link; + try { + link = new Link(accountId, region, applicationId, jobRunId, Integer.parseInt(attempt), + Long.parseLong(expires)); + } catch (NumberFormatException e) { + return null; + } + byte[] expected = signature(link).getBytes(StandardCharsets.US_ASCII); + if (!MessageDigest.isEqual(expected, signature.getBytes(StandardCharsets.US_ASCII)) + || clock.instant().getEpochSecond() >= link.expires()) { + return null; + } + return link; + } + + private String signature(Link link) { + String signed = String.join("\n", link.accountId(), link.region(), link.applicationId(), link.jobRunId(), + String.valueOf(link.attempt()), String.valueOf(link.expires())); + try { + Mac mac = Mac.getInstance(ALGORITHM); + mac.init(new SecretKeySpec(key, ALGORITHM)); + return HexFormat.of().formatHex(mac.doFinal(signed.getBytes(StandardCharsets.UTF_8))); + } catch (GeneralSecurityException e) { + throw new IllegalStateException("Could not sign an EMR Serverless dashboard link", e); + } + } + + private static byte[] newKey() { + byte[] key = new byte[KEY_BYTES]; + new SecureRandom().nextBytes(key); + return key; + } + + private static String encoded(String value) { + return URLEncoder.encode(value, StandardCharsets.UTF_8); + } +} 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 8395872c29..d929c4ebe2 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunService.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunService.java @@ -19,6 +19,7 @@ import io.floci.aws.core.common.docker.DockerPlatforms; import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.services.emrserverless.model.Application; +import io.floci.aws.services.emrserverless.model.DriverLogDestinations; import io.floci.aws.services.emrserverless.model.ImageConfiguration; import io.floci.aws.services.emrserverless.model.JobDriver; import io.floci.aws.services.emrserverless.model.JobRun; @@ -325,6 +326,24 @@ public class EmrServerlessJobRunService implements Resettable { return objectMapper.convertValue(run, JobRun.class); } + /** + * What a run's dashboard page shows of one attempt, which must still be there: the attempt, as GetJobRun gives + * it, and where its driver's logs go. + */ + public synchronized DashboardView dashboard(String applicationId, String jobRunId, int attempt) { + JobRun run = getJobRun(applicationId, jobRunId, attempt); + DriverLogDestinations logs = findRun(applicationId, jobRunId).getDriverLogs().get(attempt); + if (logs == null) { + // A run stored before Floci kept its attempts' destinations: where its application now sends them. + logs = driverLogDestinations(applications.getApplication(applicationId), run); + } + return new DashboardView(run, logs); + } + + /** An attempt of a run, and where its driver's logs go, as the attempt was admitted. */ + public record DashboardView(JobRun run, DriverLogDestinations logs) { + } + /** A run's attempts, oldest first: "information about all attempts related to a job run". */ public synchronized PaginatedResult listJobRunAttempts(String applicationId, String jobRunId, @@ -533,10 +552,39 @@ public class EmrServerlessJobRunService implements Resettable { record.setRequest(original); record.setApplicationType(app.getType()); record.setContainerRun(sparkRunner != null); + keepDriverLogs(record, app); store.put(jobRunId, record); return record; } + /** + * Keeps where the run's latest attempt sends its driver's logs, from the configuration it is admitted with, so that + * a later change to its application's monitoring configuration moves neither the logs nor what its dashboard says + * of them. + */ + private static void keepDriverLogs(JobRunRecord record, Application app) { + JobRun run = record.getJobRun(); + record.getDriverLogs().put(run.getAttempt(), driverLogDestinations(app, run)); + } + + private static DriverLogDestinations driverLogDestinations(Application app, JobRun run) { + SparkJobRunner.CloudWatchLogs cloudWatch = driverCloudWatchLogs(app, run); + return new DriverLogDestinations(driverLogFolder(app, run), cloudWatch != null ? cloudWatch.logGroup() : null, + cloudWatch != null ? cloudWatch.stdoutStream() : null, + cloudWatch != null ? cloudWatch.stderrStream() : null); + } + + // Where the run's latest attempt sends its driver's logs, as it was admitted. + private static DriverLogDestinations keptDriverLogs(JobRunRecord record, Application app) { + DriverLogDestinations logs = record.getDriverLogs().get(record.getJobRun().getAttempt()); + return logs != null ? logs : driverLogDestinations(app, record.getJobRun()); + } + + private static SparkJobRunner.CloudWatchLogs cloudWatchLogs(DriverLogDestinations logs) { + return logs.logGroup() != null + ? new SparkJobRunner.CloudWatchLogs(logs.logGroup(), logs.stdoutStream(), logs.stderrStream()) : null; + } + /** * Hands a container run to a thread of its own, which runs it to its end. A run whose driver is not its * application's type, a {@code hive} one on a Spark application or a {@code sparkSubmit} one on a Hive @@ -556,12 +604,13 @@ public class EmrServerlessJobRunService implements Resettable { Long minutes = run.getExecutionTimeoutMinutes(); Duration timeout = MODE_STREAMING.equals(run.getMode()) || minutes == null || minutes == 0 ? Duration.ZERO : Duration.ofMinutes(minutes); + DriverLogDestinations logs = keptDriverLogs(record, app); SparkJobRunner.Job job; if (hive != null) { job = new SparkJobRunner.Job(SERVICE, run.getJobRunId(), arn.accountId(), arn.region(), run.getReleaseLabel(), SparkJobRunner.Engine.HIVE, hiveImageTemplate, customImage(app), dockerNetwork, run.getExecutionRole(), Map.of(), hiveArguments(app, run, hive), null, timeout, - driverLogFolder(app, run), driverCloudWatchLogs(app, run), Map.of(), List.of(), null, Map.of(), + logs.s3Folder(), cloudWatchLogs(logs), Map.of(), List.of(), null, Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), null); } else { JobDriver.SparkSubmit sparkSubmit = run.getJobDriver().getSparkSubmit(); @@ -570,7 +619,7 @@ public class EmrServerlessJobRunService implements Resettable { job = new SparkJobRunner.Job(SERVICE, run.getJobRunId(), arn.accountId(), arn.region(), run.getReleaseLabel(), SparkJobRunner.Engine.SPARK, imageTemplate, customImage(app), dockerNetwork, run.getExecutionRole(), sparkDefaults, application(sparkSubmit), null, timeout, - driverLogFolder(app, run), driverCloudWatchLogs(app, run), driverEnvironment(sparkProperties), + logs.s3Folder(), cloudWatchLogs(logs), driverEnvironment(sparkProperties), archives(sparkProperties), null, Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), executors(app, executorContainers)); } @@ -999,6 +1048,7 @@ public class EmrServerlessJobRunService implements Resettable { run.setEndedAt(null); run.setTotalExecutionDurationSeconds(null); applyImages(run, app); + keepDriverLogs(record, app); store.put(run.getJobRunId(), record); LOG.infov("EMR Serverless job run {0} failed its attempt {1}; attempt {2} starts", run.getJobRunId(), failed.getAttempt(), run.getAttempt()); diff --git a/src/main/java/io/floci/aws/services/emrserverless/model/DriverLogDestinations.java b/src/main/java/io/floci/aws/services/emrserverless/model/DriverLogDestinations.java new file mode 100644 index 0000000000..b173426424 --- /dev/null +++ b/src/main/java/io/floci/aws/services/emrserverless/model/DriverLogDestinations.java @@ -0,0 +1,11 @@ +package io.floci.aws.services.emrserverless.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** + * Where one attempt of a run sends its driver's logs, as the attempt was admitted: an S3 folder, and a CloudWatch Logs + * group with the driver's two streams, each null where it sends none. + */ +@RegisterForReflection +public record DriverLogDestinations(String s3Folder, String logGroup, String stdoutStream, String stderrStream) { +} diff --git a/src/main/java/io/floci/aws/services/emrserverless/model/GetDashboardForJobRunResponse.java b/src/main/java/io/floci/aws/services/emrserverless/model/GetDashboardForJobRunResponse.java new file mode 100644 index 0000000000..ccabb2988f --- /dev/null +++ b/src/main/java/io/floci/aws/services/emrserverless/model/GetDashboardForJobRunResponse.java @@ -0,0 +1,11 @@ +package io.floci.aws.services.emrserverless.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +public class GetDashboardForJobRunResponse { + private String url; + + public String getUrl() { return url; } + public void setUrl(String url) { this.url = url; } +} diff --git a/src/main/java/io/floci/aws/services/emrserverless/model/JobRunRecord.java b/src/main/java/io/floci/aws/services/emrserverless/model/JobRunRecord.java index 90f9739c29..1aee92e546 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/model/JobRunRecord.java +++ b/src/main/java/io/floci/aws/services/emrserverless/model/JobRunRecord.java @@ -4,14 +4,17 @@ import com.fasterxml.jackson.databind.JsonNode; import io.quarkus.runtime.annotations.RegisterForReflection; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; /** * A stored job run: the run as GetJobRun reports it, plus what only Floci needs. The client token * and the request it came with decide whether a repeated StartJobRun is a retry or a conflict; the * application type fills ListJobRuns' {@code type}. A container run is one the {@code docker} runner * mode runs, whose state its container decides. A run retried after a failed attempt keeps each earlier - * attempt as GetJobRun reports it for that attempt, oldest first; {@code jobRun} is the latest. + * attempt as GetJobRun reports it for that attempt, oldest first; {@code jobRun} is the latest. Each attempt's + * driver log destinations are kept as it was admitted, by attempt number. */ @RegisterForReflection public class JobRunRecord { @@ -21,6 +24,7 @@ public class JobRunRecord { private String applicationType; private boolean containerRun; private List earlierAttempts = new ArrayList<>(); + private Map driverLogs = new LinkedHashMap<>(); public JobRun getJobRun() { return jobRun; } public void setJobRun(JobRun jobRun) { this.jobRun = jobRun; } @@ -34,4 +38,6 @@ public class JobRunRecord { public void setContainerRun(boolean containerRun) { this.containerRun = containerRun; } public List getEarlierAttempts() { return earlierAttempts; } public void setEarlierAttempts(List earlierAttempts) { this.earlierAttempts = earlierAttempts; } + public Map getDriverLogs() { return driverLogs; } + public void setDriverLogs(Map driverLogs) { this.driverLogs = driverLogs; } } diff --git a/src/main/java/io/floci/aws/services/lambdaweb/LambdaWebMetadataServer.java b/src/main/java/io/floci/aws/services/lambdaweb/LambdaWebMetadataServer.java index bee483807e..f98e0ae411 100644 --- a/src/main/java/io/floci/aws/services/lambdaweb/LambdaWebMetadataServer.java +++ b/src/main/java/io/floci/aws/services/lambdaweb/LambdaWebMetadataServer.java @@ -1,6 +1,7 @@ package io.floci.aws.services.lambdaweb; import io.floci.aws.core.common.AvailabilityZoneIds; +import io.floci.aws.core.common.Html; import io.floci.aws.core.common.docker.ContainerReachableEndpoint; import io.vertx.core.Future; import io.vertx.core.Vertx; @@ -167,7 +168,7 @@ public class LambdaWebMetadataServer { } response.putHeader("Location", location).putHeader("Date", LambdaWebErrorPages.platformDate(Instant.now())); if (method == HttpMethod.GET) { - end(response, "Temporary Redirect.\n\n"); + end(response, "Temporary Redirect.\n\n"); } else if (method == HttpMethod.HEAD) { response.end(); } else { @@ -189,9 +190,4 @@ public class LambdaWebMetadataServer { byte[] bytes = body.getBytes(StandardCharsets.UTF_8); return response.putHeader("Content-Length", String.valueOf(bytes.length)).end(Buffer.buffer(bytes)); } - - private static String htmlEscape(String value) { - return value.replace("&", "&").replace("<", "<").replace(">", ">") - .replace("\"", """).replace("'", "'"); - } } diff --git a/src/main/java/io/floci/aws/services/ses/SesUnsubscribeController.java b/src/main/java/io/floci/aws/services/ses/SesUnsubscribeController.java index 6973b7b63f..b40ab48ed1 100644 --- a/src/main/java/io/floci/aws/services/ses/SesUnsubscribeController.java +++ b/src/main/java/io/floci/aws/services/ses/SesUnsubscribeController.java @@ -1,6 +1,7 @@ package io.floci.aws.services.ses; import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.Html; import jakarta.inject.Inject; import jakarta.ws.rs.GET; import jakarta.ws.rs.POST; @@ -55,10 +56,10 @@ public class SesUnsubscribeController { String html = "\n" + "Unsubscribe\n" + "\n" - + "

Unsubscribe " + htmlEscape(address) + " from " + htmlEscape(scopeLabel(topic)) - + " on contact list '" + htmlEscape(contactList) + "'?

\n" + + "

Unsubscribe " + Html.escape(address) + " from " + Html.escape(scopeLabel(topic)) + + " on contact list '" + Html.escape(contactList) + "'?

\n" + "
\n" + + Html.escape(formAction(region, contactList, topic, address)) + "\">\n" // RFC 8058 one-click parameter, so the form's POST body matches the advertised // List-Unsubscribe-Post: List-Unsubscribe=One-Click header. + "\n" @@ -114,9 +115,4 @@ public class SesUnsubscribeController { private static String enc(String value) { return URLEncoder.encode(value, StandardCharsets.UTF_8); } - - private static String htmlEscape(String value) { - return value.replace("&", "&").replace("<", "<").replace(">", ">") - .replace("\"", """).replace("'", "'"); - } } diff --git a/src/test/java/io/floci/aws/core/common/HtmlTest.java b/src/test/java/io/floci/aws/core/common/HtmlTest.java new file mode 100644 index 0000000000..39c7489f12 --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/HtmlTest.java @@ -0,0 +1,20 @@ +package io.floci.aws.core.common; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class HtmlTest { + + @Test + void markupInTextOrInAnAttributeQuotedEitherWayIsShownAsItIs() { + assertEquals("<a href="x" title='y'>R&D</a>", + Html.escape("R&D")); + } + + @Test + void anEntityAlreadyWrittenIsEscapedAgainRatherThanReadAsOne() { + assertEquals("&lt;", Html.escape("<")); + assertEquals("plain text", Html.escape("plain text")); + } +} diff --git a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessDashboardIntegrationTest.java b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessDashboardIntegrationTest.java new file mode 100644 index 0000000000..fd59217959 --- /dev/null +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessDashboardIntegrationTest.java @@ -0,0 +1,144 @@ +package io.floci.aws.services.emrserverless; + +import io.floci.aws.core.common.Html; +import io.floci.aws.testing.EmrServerlessRequests; +import io.floci.aws.testing.PartitionCleanup; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import java.net.URI; +import java.util.UUID; + +import static io.floci.aws.testing.EmrServerlessRequests.emrServerless; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * GetDashboardForJobRun through the REST API, and the page its link opens on Floci: the run's attempt, its state and + * where its driver's logs go, as Floci keeps no Spark UI or Spark History Server to open. + */ +@QuarkusTest +class EmrServerlessDashboardIntegrationTest { + + private static final String REGION = "eu-west-1"; + private static final String ROLE = "arn:aws:iam::000000000000:role/emr-serverless-job"; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void aRunsDashboardLinkOpensAPageWithItsStateAndWhereItsDriverLogsGo() { + String applicationId = application(); + String jobRunId = run(applicationId, """ + , "configurationOverrides": {"monitoringConfiguration": { + "s3MonitoringConfiguration": {"logUri": "s3://bucket/logs/"}, + "cloudWatchLoggingConfiguration": {"enabled": true, "logGroupName": "/floci/runs"}}}"""); + + String url = emrServerless(REGION).when() + .get("/applications/" + applicationId + "/jobruns/" + jobRunId + "/dashboard") + .then().statusCode(200).extract().path("url"); + + assertTrue(url.contains("/_aws/emr-serverless/dashboard?"), url); + page(url).then().statusCode(200).contentType(containsString("text/html")) + .body(containsString("

Job run " + jobRunId + "

")) + .body(containsString("StateSUCCESS")) + .body(containsString("Attempt1")) + .body(containsString("Driver logs in S3s3://bucket/logs/applications/" + + applicationId + "/jobs/" + jobRunId + "/SPARK_DRIVER/")) + .body(containsString("Driver logs in CloudWatch Logs/floci/runs")) + .body(containsString(Html.escape(EmrServerlessDashboardController.NO_UI))); + } + + @Test + void aRunsPageShowsWhereItsLogsWentEvenOnceItsApplicationSendsThemElsewhere() { + String applicationId = application(); + emrServerless(REGION).body(""" + {"clientToken": "%s", "monitoringConfiguration": { + "s3MonitoringConfiguration": {"logUri": "s3://bucket/before/"}}} + """.formatted(UUID.randomUUID())) + .when().patch("/applications/" + applicationId).then().statusCode(200); + String jobRunId = run(applicationId, ""); + String url = emrServerless(REGION).when() + .get("/applications/" + applicationId + "/jobruns/" + jobRunId + "/dashboard") + .then().statusCode(200).extract().path("url"); + emrServerless(REGION).when().post("/applications/" + applicationId + "/stop").then().statusCode(200); + + emrServerless(REGION).body(""" + {"clientToken": "%s", "monitoringConfiguration": { + "s3MonitoringConfiguration": {"logUri": "s3://bucket/after/"}}} + """.formatted(UUID.randomUUID())) + .when().patch("/applications/" + applicationId).then().statusCode(200); + + page(url).then().statusCode(200) + .body(containsString("s3://bucket/before/applications/" + applicationId + "/jobs/" + jobRunId + + "/SPARK_DRIVER/")) + .body(not(containsString("s3://bucket/after/"))); + } + + @Test + void aLinkWhoseSignatureIsChangedOpensARefusal() { + String applicationId = application(); + String jobRunId = run(applicationId, ""); + String url = emrServerless(REGION).when() + .get("/applications/" + applicationId + "/jobruns/" + jobRunId + "/dashboard") + .then().statusCode(200).extract().path("url"); + int signature = url.indexOf("signature=") + "signature=".length(); + String changed = url.substring(0, signature) + (url.charAt(signature) == '0' ? '1' : '0') + + url.substring(signature + 1); + + page(changed).then().statusCode(403) + .body(containsString(Html.escape(EmrServerlessDashboardController.INVALID))) + .body(not(containsString(jobRunId + ""))); + } + + @Test + void aRunOrAttemptThatIsNotThereIsRefusedAsGetJobRunRefusesIt() { + String applicationId = application(); + String jobRunId = run(applicationId, ""); + String dashboard = "/applications/" + applicationId + "/jobruns/" + jobRunId + "/dashboard"; + + emrServerless(REGION).when().get("/applications/" + applicationId + "/jobruns/00fmissing/dashboard") + .then().statusCode(404).body("__type", equalTo("ResourceNotFoundException")); + emrServerless(REGION).queryParam("attempt", 2).when().get(dashboard) + .then().statusCode(404).body("message", equalTo("Job run " + jobRunId + " has no attempt 2")); + emrServerless(REGION).queryParam("attempt", 0).when().get(dashboard) + .then().statusCode(400).body("__type", equalTo("ValidationException")); + // A run is in its application's Region alone, as GetJobRun finds it. + emrServerless("us-east-1").when().get(dashboard) + .then().statusCode(404).body("__type", equalTo("ResourceNotFoundException")); + } + + private String application() { + String applicationId = EmrServerlessRequests.createSparkApplication(REGION, "emr-7.5.0"); + cleanup.register(() -> EmrServerlessRequests.deleteApplication(REGION, applicationId)); + return applicationId; + } + + // A run, ended before it is returned, so its application stops when the test is done. + private static String run(String applicationId, String extra) { + String jobRunId = EmrServerlessRequests.startJobRun(REGION, applicationId, """ + {"clientToken": "%s", "executionRoleArn": "%s", + "jobDriver": {"sparkSubmit": {"entryPoint": "s3://bucket/jobs/app.py"}}%s} + """.formatted(UUID.randomUUID(), ROLE, extra)); + EmrServerlessRequests.awaitJobRun(REGION, applicationId, jobRunId); + return jobRunId; + } + + // The page a link opens, asked for on the address this test's Floci listens on, which the link's base URL is not. + private static Response page(String url) { + URI link = URI.create(url); + return given().urlEncodingEnabled(false).when().get(link.getRawPath() + "?" + link.getRawQuery()); + } +} diff --git a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessDashboardsTest.java b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessDashboardsTest.java new file mode 100644 index 0000000000..ca3eba79f5 --- /dev/null +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessDashboardsTest.java @@ -0,0 +1,97 @@ +package io.floci.aws.services.emrserverless; + +import io.floci.aws.testing.MutableClock; +import org.junit.jupiter.api.Test; + +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class EmrServerlessDashboardsTest { + + // Where MutableClock starts; each read moves it a millisecond, within the second a link's expiry is counted in. + private static final Instant NOW = Instant.parse("2026-01-01T00:00:00Z"); + private static final byte[] KEY = "a key of this process, 32 bytes!".getBytes(StandardCharsets.US_ASCII); + + private final MutableClock clock = new MutableClock(); + private final EmrServerlessDashboards dashboards = new EmrServerlessDashboards("http://localhost:4566/", clock, + KEY); + + @Test + void aLinkNamesTheRunsAttemptOnFlocisAddressAndExpiresInAnHour() { + String url = dashboards.url("123456789012", "eu-west-1", "00fabcd", "00frun", 2); + + assertTrue(url.startsWith("http://localhost:4566/_aws/emr-serverless/dashboard?"), url); + Map query = query(url); + assertEquals("123456789012", query.get("account")); + assertEquals("eu-west-1", query.get("region")); + assertEquals("00fabcd", query.get("application")); + assertEquals("00frun", query.get("jobRun")); + assertEquals("2", query.get("attempt")); + // "The URL is valid for one hour after you generate it." + assertEquals(String.valueOf(NOW.plus(Duration.ofHours(1)).getEpochSecond()), query.get("expires")); + assertEquals(new EmrServerlessDashboards.Link("123456789012", "eu-west-1", "00fabcd", "00frun", 2, + NOW.plus(Duration.ofHours(1)).getEpochSecond()), verified(query)); + } + + @Test + void aLinkWhoseHourHasPassedOpensNothing() { + Map query = query(dashboards.url("123456789012", "us-east-1", "app", "run", 1)); + + clock.advance(Duration.ofMinutes(59)); + assertNotNull(verified(query)); + clock.advance(Duration.ofMinutes(1)); + assertNull(verified(query)); + } + + @Test + void aLinkWithAnyOfItsPartsChangedOpensNothing() { + Map query = query(dashboards.url("123456789012", "us-east-1", "app", "run", 1)); + + for (String part : new String[]{"account", "region", "application", "jobRun", "attempt", "expires"}) { + Map changed = new LinkedHashMap<>(query); + changed.put(part, part.equals("attempt") || part.equals("expires") + ? String.valueOf(Long.parseLong(query.get(part)) + 1) : query.get(part) + "x"); + assertNull(verified(changed), part); + } + Map unsigned = new LinkedHashMap<>(query); + unsigned.remove("signature"); + assertNull(verified(unsigned)); + Map malformed = new LinkedHashMap<>(query); + malformed.put("attempt", "one"); + assertNull(verified(malformed)); + } + + @Test + void aLinkFromAnotherProcessesKeyOpensNothing() { + EmrServerlessDashboards restarted = new EmrServerlessDashboards("http://localhost:4566", clock, + "another process's key, 32 bytes".getBytes(StandardCharsets.US_ASCII)); + Map query = query(restarted.url("123456789012", "us-east-1", "app", "run", 1)); + + assertNull(verified(query)); + } + + private EmrServerlessDashboards.Link verified(Map query) { + return dashboards.verified(query.get("account"), query.get("region"), query.get("application"), + query.get("jobRun"), query.get("attempt"), query.get("expires"), query.get("signature")); + } + + private static Map query(String url) { + Map query = new LinkedHashMap<>(); + for (String pair : URI.create(url).getRawQuery().split("&")) { + int equals = pair.indexOf('='); + query.put(pair.substring(0, equals), + URLDecoder.decode(pair.substring(equals + 1), StandardCharsets.UTF_8)); + } + return query; + } +} diff --git a/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorEmrServerlessSyncTest.java b/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorEmrServerlessSyncTest.java index 383cffaf79..8c2799aa08 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorEmrServerlessSyncTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorEmrServerlessSyncTest.java @@ -4,7 +4,9 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RegionResolver; import io.floci.aws.services.emrserverless.EmrServerlessController; +import io.floci.aws.services.emrserverless.EmrServerlessDashboards; import io.floci.aws.services.emrserverless.EmrServerlessJobRunService; import io.floci.aws.services.emrserverless.EmrServerlessService; import io.floci.aws.services.emrserverless.model.Application; @@ -77,7 +79,8 @@ class AslExecutorEmrServerlessSyncTest { .sfnService(instance) .customResourceLiveness(null) .emrServerlessTaskInvoker(new EmrServerlessTaskInvoker( - new EmrServerlessController(applications, jobRuns), objectMapper)) + new EmrServerlessController(applications, jobRuns, mock(EmrServerlessDashboards.class), + mock(RegionResolver.class)), objectMapper)) .nanoTime(testNanos::get) .sleeper(testNanos::addAndGet) .build();