feat(emr-serverless): answer GetDashboardForJobRun with a link to a page of Floci's about the run (#8687)

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". Floci did not serve it, so a client asking for a run's
application UI link, as Airflow's EMR Serverless operator can, failed.

It now checks the run and its attempt as GetJobRun does and answers
with a link to a page Floci serves at /_aws/emr-serverless/dashboard on
its own address: the attempt's state, its times, and where its
driver's logs go in S3 and CloudWatch Logs, which each attempt now
keeps as it was admitted, so a later change to its application's
monitoring configuration moves neither the logs nor what the page says
of them. EMR Serverless opens the
run's live Spark or Tez UI there, or its Spark History Server once it
has ended, neither of which Floci keeps. The link names the run and is
signed with a key Floci makes as it starts, so a changed link, one past
its hour, or one given before a restart, opens a refusal.

The three private HTML escapes (SES's unsubscribe page, Lambda web's
redirect, CodeArtifact's pypi index) become one, core.common.Html,
which the page uses too.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-16 21:04:27 -04:00
1 parent ef07bfd4b3
commit 081fd97c05
16 files changed
+618 -25

No files matched your search

+11
View File
@@ -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).
@@ -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("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
.replace("\"", "&quot;").replace("'", "&#39;");
}
}
@@ -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("<a href=\"").append(pathPrefix).append("/packages/")
.append(SidecarUriUtils.encodeSegment(file.filename())).append("\"");
if (file.requiresPythonOrNull() != null) {
extra.append(" data-requires-python=\"").append(escapeHtml(file.requiresPythonOrNull()))
extra.append(" data-requires-python=\"").append(Html.escape(file.requiresPythonOrNull()))
.append("\"");
}
if (file.yanked()) {
extra.append(" data-yanked=\"\"");
}
extra.append(">").append(escapeHtml(file.filename())).append("</a><br>\n");
extra.append(">").append(Html.escape(file.filename())).append("</a><br>\n");
}
if (bodyHtmlOrNull == null) {
return "<!DOCTYPE html><html><body>\n" + extra + "</body></html>";
@@ -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("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;");
}
/**
* 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
@@ -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,
@@ -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("<p>" + Html.escape(INVALID) + "</p>"));
}
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("<p>" + Html.escape(e.getMessage()) + "</p>"));
}
return page(200, "Job run " + link.jobRunId(), body(view));
}
private static List<String> body(EmrServerlessJobRunService.DashboardView view) {
JobRun run = view.run();
List<String> lines = new ArrayList<>();
lines.add("<table>");
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("</table>");
lines.add("<p>" + Html.escape(NO_UI) + "</p>");
return lines;
}
// A row of the table, left out when the run has no such value.
private static void row(List<String> lines, String name, String value) {
if (value != null && !value.isEmpty()) {
lines.add("<tr><th>" + Html.escape(name) + "</th><td>" + Html.escape(value) + "</td></tr>");
}
}
private static Response page(int status, String title, List<String> body) {
String html = "<!doctype html>\n"
+ "<html lang=\"en\"><head><meta charset=\"utf-8\"><title>" + Html.escape(title)
+ "</title></head>\n<body>\n<h1>" + Html.escape(title) + "</h1>\n"
+ String.join("\n", body) + "\n</body></html>\n";
return Response.status(status).type(MediaType.TEXT_HTML).entity(html).build();
}
}
@@ -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) + "&region=" + 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);
}
}
@@ -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<JobRunAttemptSummary> 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());
@@ -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) {
}
@@ -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; }
}
@@ -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<JobRun> earlierAttempts = new ArrayList<>();
private Map<Integer, DriverLogDestinations> 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<JobRun> getEarlierAttempts() { return earlierAttempts; }
public void setEarlierAttempts(List<JobRun> earlierAttempts) { this.earlierAttempts = earlierAttempts; }
public Map<Integer, DriverLogDestinations> getDriverLogs() { return driverLogs; }
public void setDriverLogs(Map<Integer, DriverLogDestinations> driverLogs) { this.driverLogs = driverLogs; }
}
@@ -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, "<a href=\"" + htmlEscape(location) + "\">Temporary Redirect</a>.\n\n");
end(response, "<a href=\"" + Html.escape(location) + "\">Temporary Redirect</a>.\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("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
.replace("\"", "&#34;").replace("'", "&#39;");
}
}
@@ -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 = "<!doctype html>\n"
+ "<html lang=\"en\"><head><meta charset=\"utf-8\"><title>Unsubscribe</title></head>\n"
+ "<body>\n"
+ "<p>Unsubscribe " + htmlEscape(address) + " from " + htmlEscape(scopeLabel(topic))
+ " on contact list &#39;" + htmlEscape(contactList) + "&#39;?</p>\n"
+ "<p>Unsubscribe " + Html.escape(address) + " from " + Html.escape(scopeLabel(topic))
+ " on contact list &#39;" + Html.escape(contactList) + "&#39;?</p>\n"
+ "<form method=\"post\" action=\""
+ htmlEscape(formAction(region, contactList, topic, address)) + "\">\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.
+ "<input type=\"hidden\" name=\"List-Unsubscribe\" value=\"One-Click\">\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("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
.replace("\"", "&quot;").replace("'", "&#39;");
}
}
@@ -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("&lt;a href=&quot;x&quot; title=&#39;y&#39;&gt;R&amp;D&lt;/a&gt;",
Html.escape("<a href=\"x\" title='y'>R&D</a>"));
}
@Test
void anEntityAlreadyWrittenIsEscapedAgainRatherThanReadAsOne() {
assertEquals("&amp;lt;", Html.escape("&lt;"));
assertEquals("plain text", Html.escape("plain text"));
}
}
@@ -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("<h1>Job run " + jobRunId + "</h1>"))
.body(containsString("<tr><th>State</th><td>SUCCESS</td></tr>"))
.body(containsString("<tr><th>Attempt</th><td>1</td></tr>"))
.body(containsString("<tr><th>Driver logs in S3</th><td>s3://bucket/logs/applications/"
+ applicationId + "/jobs/" + jobRunId + "/SPARK_DRIVER/</td></tr>"))
.body(containsString("<tr><th>Driver logs in CloudWatch Logs</th><td>/floci/runs</td></tr>"))
.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("<td>s3://bucket/before/applications/" + applicationId + "/jobs/" + jobRunId
+ "/SPARK_DRIVER/</td>"))
.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 + "</td>")));
}
@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());
}
}
@@ -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<String, String> 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<String, String> 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<String, String> query = query(dashboards.url("123456789012", "us-east-1", "app", "run", 1));
for (String part : new String[]{"account", "region", "application", "jobRun", "attempt", "expires"}) {
Map<String, String> 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<String, String> unsigned = new LinkedHashMap<>(query);
unsigned.remove("signature");
assertNull(verified(unsigned));
Map<String, String> 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<String, String> query = query(restarted.url("123456789012", "us-east-1", "app", "run", 1));
assertNull(verified(query));
}
private EmrServerlessDashboards.Link verified(Map<String, String> 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<String, String> query(String url) {
Map<String, String> 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;
}
}
@@ -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();