feat(emr-serverless): retry a failed job run as its retry policy allows (#6894)

In the docker runner mode a job run's retryPolicy was stored and
returned, but a run whose driver failed was never tried again: every
run was its one attempt. Now, on release 7.1.0 or later, "EMR
Serverless releases 7.1.0 and higher include support for job
resiliency", a run whose driver fails is tried again as the user
guide's "Job resiliency" gives it:

- a BATCH run until it has made maxAttempts attempts, "The default is
  1, which means to not rerun the job";
- a STREAMING run, which "EMR Serverless indefinitely retries", until
  it has failed maxFailedAttemptsPerHour times within an hour, "The
  default is five".

The failed attempt ends FAILED with its stateDetails, and the next is
SCHEDULED again and runs its driver from the beginning, "its own set
of logs" under attempts/<n>/ in S3 and CloudWatch Logs. A cancelled
run, one past its timeout ("Cancelling: ... or the job run has timed
out"), one Floci's own shutdown stopped and one whose application is
gone are not tried again; a retry is admitted while its application
cannot be deleted, as the first attempt is.
GetJobRun without attempt returns "the latest attempt", and with one
an earlier attempt as it ended; ListJobRunAttempts lists them all,
oldest first, each with its own createdAt and updatedAt. No source says
whether a run's timeout spans its attempts; Floci applies it to each.
Floci sends no EMR Serverless events, so the job run retry event is
not sent.

StartJobRun holds retryPolicy to "Accepted values are 1 to 10,
inclusive" for both members: outside that range is a
ValidationException in the model's constraint form, and a member that
is not an integer a SerializationException, as Smithy's restJson1
malformed-request tests have it.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-29 00:34:34 -05:00
1 parent c9c1c0990b
commit 66a5c05037
5 files changed
+413 -78

No files matched your search

+17 -9
View File
@@ -87,11 +87,19 @@ runner mode a Spark run executes; see [Running Spark job runs](#running-spark-jo
state in the order the filter names them. A state or mode that does not exist, or more than 8
states, is refused with `ValidationException`. An unknown application has no runs. A `nextToken`
resumes only the listing it came from, with the same application and filters.
* **Attempts**: no run is retried, and in the `immediate` mode none fails: every run is a single attempt,
number 1. `GetJobRun`, `ListJobRuns` and `ListJobRunAttempts` report it, with the run's own
creation and update times. `GetJobRun` with `attempt` 1, or without one, returns the run; an
`attempt` of 2 or more answers `ResourceNotFoundException`, and one below 1 or not an integer
`ValidationException`.
* **Attempts**: a run starts as attempt 1, and in the `immediate` mode, where none fails, it stays its
only one. In the `docker` mode a run whose driver fails is tried again on release 7.1.0 or later, as
the user guide's "Job resiliency" gives it: a `BATCH` run until it has made `retryPolicy.maxAttempts`
attempts (1 by default, no retry), and a `STREAMING` run until it has failed
`maxFailedAttemptsPerHour` times within an hour (5 by default). Either outside 1 to 10, the user
guide's "Accepted values", is refused with `ValidationException`, and either not an integer with
`SerializationException`. Each new attempt is `SCHEDULED` again
and runs its driver from the beginning; a cancelled run, one past its timeout, and one Floci's own
shutdown stopped are not tried again. `GetJobRun` without `attempt` returns the latest attempt, with
`attempt` an earlier one as it ended (`FAILED`, with its `stateDetails`), and an attempt the run never
made answers `ResourceNotFoundException`; one below 1 or not an integer is `ValidationException`.
`ListJobRunAttempts` lists every attempt, oldest first, each with its own creation and update times.
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.
@@ -131,15 +139,15 @@ publishes for customizing EMR Serverless images (`public.ecr.aws/emr-serverless/
* **Output**: the driver's output goes to Floci's log, prefixed `emr-serverless:<jobRunId>`. With an S3
log destination, the run's `s3MonitoringConfiguration` or else the application's, its standard output
and error also go to Floci's S3 once the run ends, gzipped, as `stdout.gz` and `stderr.gz` under
`<logUri>/applications/<applicationId>/jobs/<jobRunId>/SPARK_DRIVER/`, with `attempts/1/` before
`<logUri>/applications/<applicationId>/jobs/<jobRunId>/SPARK_DRIVER/`, with `attempts/<n>/` before
`SPARK_DRIVER/` for a `STREAMING` run, or a `BATCH` run whose `retryPolicy` allows more than one
attempt, on release 7.1.0 or later. A cancelled run's logs hold what its driver wrote until it was
attempt, on release 7.1.0 or later, each attempt's logs under its own number. A cancelled run's logs hold what its driver wrote until it was
stopped. Logs that cannot be written, to a bucket that does not exist say, leave the run as it
ended.
* **CloudWatch Logs**: with CloudWatch logging enabled, the run's `cloudWatchLoggingConfiguration` or
else the application's (`"enabled": false` at the run turns it off), the driver's standard output and
error go line by line, while it runs, to the log streams `<prefix>/applications/<applicationId>/jobs/<jobRunId>/SPARK_DRIVER/stdout`
and `.../stderr` in Floci's CloudWatch Logs, with `attempts/1/` before `SPARK_DRIVER` as for S3. The log
and `.../stderr` in Floci's CloudWatch Logs, with `attempts/<n>/` before `SPARK_DRIVER` as for S3. The log
group is `logGroupName`, `/aws/emr-serverless` by default, and `<prefix>` the `logStreamNamePrefix`, if
any; both are created as needed, in the run's account and Region. A `logTypes` sends only the driver's
types it names, and none of the driver's output when it names only `SPARK_EXECUTOR`.
@@ -151,6 +159,6 @@ publishes for customizing EMR Serverless images (`public.ecr.aws/emr-serverless/
* **Jobs do not execute by default**: in the `immediate` runner mode `StartJobRun` records a job run and moves it through its states, but nothing runs. In the `docker` mode a Spark run executes in local mode in one container, so worker counts and sizes, initial and maximum capacity are not applied; a Hive run is `FAILED` without running, in Floci's own wording, as is a driver's failure. Of the monitoring configuration, the S3 log destination gets the driver's `stdout.gz` and `stderr.gz` once a run ends (no event logs, rotated files or uploads while it runs), and CloudWatch Logs the driver's output while it runs (there are no executor logs, local mode having no executors, and `encryptionKeyArn` is ignored), and Floci's CA is not in the job's Java truststore, so a job reaches Floci over its HTTP endpoint only.
* **Unsourced errors**: AWS documents neither the error for a run submitted to an application whose auto-start is off nor the one for a run on a terminated application; Floci answers both with `ValidationException`. The same holds for a `BATCH` timeout outside 1 to 10080 minutes on `emr-7.11.0` or later (`ValidationException`) and for `GetJobRun` naming an attempt a run never made (`ResourceNotFoundException`), both in Floci's own wording. A run needs a `jobDriver`, as every `JobRun` carries one, and `jobDriver` is a union, so a run without a driver, or with one that sets both `sparkSubmit` and `hive` or neither, is refused with `ValidationException` too, in Floci's own wording.
* **StopApplication with running jobs**: AWS requires running jobs to finish or be cancelled before an application stops. Floci does not enforce it; with the default duration of `0` no `BATCH` run is ever running.
* **Not emulated**: retries (`retryPolicy` is stored and returned, but no run is retried), queuing (`QUEUED`), `totalResourceUtilization` and `billedResourceUtilization`, and `shutdownGracePeriodInSeconds` (accepted and ignored: a cancelled run's driver is stopped at once).
* **Not emulated**: the "EMR Serverless Job Run Retry" event, as Floci sends no EMR Serverless events, queuing (`QUEUED`), `totalResourceUtilization` and `billedResourceUtilization`, and `shutdownGracePeriodInSeconds` (accepted and ignored: a cancelled run's driver is stopped at once).
* **Instant Start/Stop**: Floci marks the application `STARTED` or `STOPPED` immediately without provisioning actual compute capacity in the background.
* **Data Plane**: Floci does not implement the data-plane API, such as interactive sessions.
@@ -103,6 +103,10 @@ public class EmrServerlessJobRunService implements Resettable {
private static final long DEFAULT_EXECUTION_TIMEOUT_MINUTES = 720;
// The model's Duration, which bounds executionTimeoutMinutes.
private static final long MAX_EXECUTION_TIMEOUT_MINUTES = 1_000_000;
// RetryPolicy's members: at least 1 in the model, and "Accepted values are 1 to 10, inclusive" for each in
// the user guide's "Job resiliency".
private static final List<String> RETRY_LIMITS = List.of("maxAttempts", "maxFailedAttemptsPerHour");
private static final int MAX_RETRY_LIMIT = 10;
// The EMR Serverless 7.11.0 release notes: for BATCH job runs the maximum "is 7 days from this release
// onwards", and the timeout "can no longer be set to 0".
private static final long MAX_BATCH_EXECUTION_TIMEOUT_MINUTES = 10_080;
@@ -110,8 +114,12 @@ public class EmrServerlessJobRunService implements Resettable {
// The AWS runtime for Apache Spark, emr-spark-8.0.0 on (and emr-spark-8.0-preview).
private static final Pattern SPARK_RUNTIME_RELEASE_LABEL =
Pattern.compile("emr-spark-(\\d{1,6})\\.(\\d{1,6})(?:[.-].*)?");
// No run is retried: every run is its own one attempt.
private static final int ATTEMPT = 1;
// A run's first attempt; a retried run's later ones count on from it.
private static final int FIRST_ATTEMPT = 1;
// maxAttempts: "The default is 1, which means to not rerun the job."
private static final int DEFAULT_MAX_ATTEMPTS = 1;
// maxFailedAttemptsPerHour: "The default is five."
private static final int DEFAULT_MAX_FAILED_ATTEMPTS_PER_HOUR = 5;
private static final int MAX_LIST_RESULTS = 50;
// IAMRoleArn's pattern, as the model and AWS's validation message spell it.
private static final String ROLE_ARN_PATTERN =
@@ -236,28 +244,35 @@ public class EmrServerlessJobRunService implements Resettable {
}
/**
* The run, as its {@code attempt} saw it; without one, "the latest attempt". A run has one
* attempt, so any other number names nothing. No source gives AWS's answer for an attempt a run
* never made; ResourceNotFoundException, in Floci's words, is the modeled error that fits.
* The run, as its {@code attempt} saw it; without one, "the latest attempt". No source gives AWS's
* answer for an attempt a run never made; ResourceNotFoundException, in Floci's words, is the modeled
* error that fits.
*/
public synchronized JobRun getJobRun(String applicationId, String jobRunId, Integer attempt) {
if (attempt != null) {
String violation = SmithyValidationErrors.outOfRange("attempt", attempt, ATTEMPT, Integer.MAX_VALUE);
String violation = SmithyValidationErrors.outOfRange("attempt", attempt, FIRST_ATTEMPT,
Integer.MAX_VALUE);
if (violation != null) {
throw SmithyValidationErrors.validationException(violation);
}
}
applications.getApplication(applicationId);
JobRunRecord record = findRun(applicationId, jobRunId);
if (attempt != null && attempt != ATTEMPT) {
// Refused before the run settles: settling never makes an attempt, only a run's thread does.
if (attempt != null && attempts(record).stream().noneMatch(made -> attempt.equals(made.getAttempt()))) {
throw new AwsException("ResourceNotFoundException",
"Job run " + jobRunId + " has no attempt " + attempt, 404);
}
settle(record);
JobRun run = attempts(record).stream()
.filter(made -> attempt == null ? made == record.getJobRun() : attempt.equals(made.getAttempt()))
.findFirst()
.orElseThrow();
// A copy: a container run's thread may change the stored run while the response is written.
return objectMapper.convertValue(settle(record).getJobRun(), JobRun.class);
return objectMapper.convertValue(run, JobRun.class);
}
/** A run's attempts, which are its one attempt. */
/** A run's attempts, oldest first: "information about all attempts related to a job run". */
public synchronized PaginatedResult<JobRunAttemptSummary> listJobRunAttempts(String applicationId,
String jobRunId,
Integer maxResults,
@@ -270,12 +285,12 @@ public class EmrServerlessJobRunService implements Resettable {
}
applications.getApplication(applicationId);
JobRunRecord record = settle(findRun(applicationId, jobRunId));
PaginatedResult<JobRunRecord> page = Pagination.paginate(List.of(record),
only -> String.format("%010d", ATTEMPT), maxResults != null ? maxResults : MAX_LIST_RESULTS,
PaginatedResult<JobRun> page = Pagination.paginate(attempts(record),
made -> String.format("%010d", made.getAttempt()), maxResults != null ? maxResults : MAX_LIST_RESULTS,
nextToken, String.join("|", "ListJobRunAttempts", applicationId, jobRunId),
token -> new AwsException("ValidationException", "Invalid nextToken.", 400));
return new PaginatedResult<>(
page.items().stream().map(EmrServerlessJobRunService::toAttemptSummary).toList(),
page.items().stream().map(made -> toAttemptSummary(record, made)).toList(),
page.nextToken());
}
@@ -432,7 +447,7 @@ public class EmrServerlessJobRunService implements Resettable {
? request.getExecutionTimeoutMinutes() : DEFAULT_EXECUTION_TIMEOUT_MINUTES);
run.setMode(request.getMode());
run.setRetryPolicy(request.getRetryPolicy());
run.setAttempt(ATTEMPT);
run.setAttempt(FIRST_ATTEMPT);
run.setAttemptCreatedAt(now);
run.setAttemptUpdatedAt(now);
if (sparkRunner == null) {
@@ -578,14 +593,76 @@ public class EmrServerlessJobRunService implements Resettable {
finish(record, STATE_SUCCESS, now);
} else {
// No source gives AWS's wording for a driver that fails; this is Floci's.
run.setStateDetails(outcome.stopped() ? INTERRUPTED
String details = outcome.stopped() ? INTERRUPTED
: outcome.failure() != null ? "Job run could not start: " + outcome.failure()
: "Job run failed: the Spark driver exited with code " + outcome.exitCode() + ".");
: "Job run failed: the Spark driver exited with code " + outcome.exitCode() + ".";
// A driver Floci's own shutdown stopped did not fail, and is not tried again. The next attempt is
// admitted while its application cannot be deleted, as the first was.
if (!outcome.stopped() && retriesAfterFailure(record, now)
&& applications.whileLive(run.getApplicationId(), app -> retry(record, app, details, now))) {
return;
}
run.setStateDetails(details);
finish(record, STATE_FAILED, now);
}
LOG.infov("EMR Serverless job run {0} ended {1}", jobRunId, run.getState());
}
/**
* Whether a run whose latest attempt has just failed is tried again. "EMR Serverless releases 7.1.0 and
* higher include support for job resiliency". A BATCH run is rerun until it has made {@code maxAttempts}
* attempts, by default 1, "which means to not rerun the job". "EMR Serverless indefinitely retries
* streaming jobs if they fail", until "the maximum number of failed attempts allowed with an hour before
* EMR Serverless stops retrying", {@code maxFailedAttemptsPerHour}, by default five, is reached: this
* failure and those of the hour before it count.
*/
private static boolean retriesAfterFailure(JobRunRecord record, Instant now) {
JobRun run = record.getJobRun();
if (!retriesAttempts(run.getReleaseLabel())) {
return false;
}
if (!MODE_STREAMING.equals(run.getMode())) {
return run.getAttempt() < retryLimit(run, "maxAttempts", DEFAULT_MAX_ATTEMPTS);
}
Instant hourBefore = now.minus(Duration.ofHours(1));
long failedWithinTheHour = 1 + record.getEarlierAttempts().stream()
.filter(earlier -> STATE_FAILED.equals(earlier.getState()) && earlier.getEndedAt().isAfter(hourBefore))
.count();
return failedWithinTheHour < retryLimit(run, "maxFailedAttemptsPerHour", DEFAULT_MAX_FAILED_ATTEMPTS_PER_HOUR);
}
// A member of the run's retryPolicy, or its default when the run has none.
private static int retryLimit(JobRun run, String member, int fallback) {
Object limit = run.getRetryPolicy() != null ? run.getRetryPolicy().get(member) : null;
return limit instanceof Number number ? number.intValue() : fallback;
}
/**
* Ends the run's latest attempt FAILED, kept as it then stood, and starts the next: SCHEDULED again,
* its driver started over ("Batch jobs don't have checkpoints, so EMR Serverless always re-runs the job
* from the beginning"), "its own set of logs" under its own attempt number.
*/
private void retry(JobRunRecord record, Application app, String details, Instant now) {
JobRun run = record.getJobRun();
JobRun failed = objectMapper.convertValue(run, JobRun.class);
failed.setStateDetails(details);
end(failed, STATE_FAILED, now);
record.getEarlierAttempts().add(failed);
run.setAttempt(run.getAttempt() + 1);
run.setAttemptCreatedAt(now);
run.setAttemptUpdatedAt(now);
run.setUpdatedAt(now);
run.setState(STATE_SCHEDULED);
run.setStateDetails("");
run.setStartedAt(null);
run.setEndedAt(null);
run.setTotalExecutionDurationSeconds(null);
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());
launch(record, app);
}
/**
* The {@code spark-defaults} properties for a run: the application's runtime configuration, then the
* run's own {@code applicationConfiguration}. The two merge by classification, so a run's
@@ -682,15 +759,14 @@ public class EmrServerlessJobRunService implements Resettable {
// Where under a log destination the user guide puts a run's driver logs, the attempt for a retried run.
private static String driverLogPath(JobRun run) {
String attempts = retried(run) && retriesAttempts(run.getReleaseLabel()) ? "/attempts/" + ATTEMPT : "";
String attempts = retried(run) && retriesAttempts(run.getReleaseLabel()) ? "/attempts/" + run.getAttempt() : "";
return "/applications/" + run.getApplicationId() + "/jobs/" + run.getJobRunId() + attempts + "/"
+ SPARK_DRIVER;
}
// A STREAMING run is retried, and a BATCH run whose retryPolicy allows more than one attempt.
private static boolean retried(JobRun run) {
Object maxAttempts = run.getRetryPolicy() != null ? run.getRetryPolicy().get("maxAttempts") : null;
return MODE_STREAMING.equals(run.getMode()) || maxAttempts instanceof Number number && number.intValue() > 1;
return MODE_STREAMING.equals(run.getMode()) || retryLimit(run, "maxAttempts", DEFAULT_MAX_ATTEMPTS) > 1;
}
// "EMR Serverless releases 7.1.0 and higher support retry attempts for streaming jobs and batch jobs."
@@ -741,7 +817,11 @@ public class EmrServerlessJobRunService implements Resettable {
}
private void finish(JobRunRecord record, String state, Instant endedAt) {
JobRun run = record.getJobRun();
end(record.getJobRun(), state, endedAt);
store.put(record.getJobRun().getJobRunId(), record);
}
private static void end(JobRun run, String state, Instant endedAt) {
run.setState(state);
run.setEndedAt(endedAt);
run.setUpdatedAt(endedAt);
@@ -749,7 +829,13 @@ public class EmrServerlessJobRunService implements Resettable {
// A container run cancelled or failed before its driver ran never started.
run.setTotalExecutionDurationSeconds(run.getStartedAt() != null
? (int) Duration.between(run.getStartedAt(), endedAt).toSeconds() : 0);
store.put(run.getJobRunId(), record);
}
// Every attempt of a run, oldest first: the earlier ones, then the latest.
private static List<JobRun> attempts(JobRunRecord record) {
List<JobRun> attempts = new ArrayList<>(record.getEarlierAttempts());
attempts.add(record.getJobRun());
return attempts;
}
private JobRunRecord findRun(String applicationId, String jobRunId) {
@@ -811,6 +897,7 @@ public class EmrServerlessJobRunService implements Resettable {
}
private static void validate(StartJobRunRequest request) {
Map<String, Integer> retryLimits = retryLimits(request.getRetryPolicy());
List<String> violations = new ArrayList<>();
if (request.getClientToken() == null) {
violations.add(SmithyValidationErrors.notNull("clientToken"));
@@ -831,6 +918,13 @@ public class EmrServerlessJobRunService implements Resettable {
violations.add(violation);
}
}
// No source gives AWS's wording above 10, which the model does not bound; this is the model's form.
retryLimits.forEach((member, limit) -> {
String violation = SmithyValidationErrors.outOfRange("retryPolicy." + member, limit, 1, MAX_RETRY_LIMIT);
if (violation != null) {
violations.add(violation);
}
});
JobDriver driver = request.getJobDriver();
if (driver != null && driver.getSparkSubmit() != null && driver.getSparkSubmit().getEntryPoint() == null) {
violations.add(SmithyValidationErrors.notNull("jobDriver.sparkSubmit.entryPoint"));
@@ -849,6 +943,25 @@ public class EmrServerlessJobRunService implements Resettable {
}
}
/**
* The members of a run's {@code retryPolicy} it gives, each an integer in the model. A restJson1 service
* refuses a body member of another type, a string, a boolean or a fraction where an integer goes, with
* SerializationException, before any constraint (Smithy's restJson1 malformed-request tests); the message
* is Floci's.
*/
private static Map<String, Integer> retryLimits(Map<String, Object> retryPolicy) {
Map<String, Integer> limits = new LinkedHashMap<>();
for (String member : RETRY_LIMITS) {
Object value = retryPolicy != null ? retryPolicy.get(member) : null;
if (value instanceof Integer limit) {
limits.put(member, limit);
} else if (value != null) {
throw new AwsException("SerializationException", "retryPolicy." + member + " must be an integer", 400);
}
}
return limits;
}
/**
* From Amazon EMR release 7.11.0 a BATCH run's timeout is 1 to 10080 minutes; an earlier release, or
@@ -904,24 +1017,25 @@ public class EmrServerlessJobRunService implements Resettable {
return summary;
}
private static JobRunAttemptSummary toAttemptSummary(JobRunRecord record) {
JobRun run = record.getJobRun();
// An attempt of a run: "createdAt", "The date and time when the job run attempt was created", and
// "updatedAt" when it was last updated are the attempt's; "jobCreatedAt" is the run's.
private static JobRunAttemptSummary toAttemptSummary(JobRunRecord record, JobRun attempt) {
JobRunAttemptSummary summary = new JobRunAttemptSummary();
summary.setApplicationId(run.getApplicationId());
summary.setId(run.getJobRunId());
summary.setName(run.getName());
summary.setMode(run.getMode());
summary.setArn(run.getArn());
summary.setCreatedBy(run.getCreatedBy());
summary.setJobCreatedAt(run.getCreatedAt());
summary.setCreatedAt(run.getCreatedAt());
summary.setUpdatedAt(run.getUpdatedAt());
summary.setExecutionRole(run.getExecutionRole());
summary.setState(run.getState());
summary.setStateDetails(run.getStateDetails());
summary.setReleaseLabel(run.getReleaseLabel());
summary.setApplicationId(attempt.getApplicationId());
summary.setId(attempt.getJobRunId());
summary.setName(attempt.getName());
summary.setMode(attempt.getMode());
summary.setArn(attempt.getArn());
summary.setCreatedBy(attempt.getCreatedBy());
summary.setJobCreatedAt(attempt.getCreatedAt());
summary.setCreatedAt(attempt.getAttemptCreatedAt());
summary.setUpdatedAt(attempt.getAttemptUpdatedAt());
summary.setExecutionRole(attempt.getExecutionRole());
summary.setState(attempt.getState());
summary.setStateDetails(attempt.getStateDetails());
summary.setReleaseLabel(attempt.getReleaseLabel());
summary.setType(record.getApplicationType());
summary.setAttempt(ATTEMPT);
summary.setAttempt(attempt.getAttempt());
return summary;
}
@@ -27,6 +27,7 @@ import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.function.Function;
@@ -349,7 +350,21 @@ public class EmrServerlessService {
/** Whether the application exists and has not been deleted, which leaves it TERMINATED. */
public synchronized boolean isLive(String applicationId) {
return storage.get(applicationId).filter(app -> !"TERMINATED".equals(app.getState())).isPresent();
return live(applicationId).isPresent();
}
/**
* Runs {@code use} on the application when it exists and has not been deleted, under this service's
* lock, so that it cannot be deleted meanwhile, as with {@link #admitJobRun}; returns whether it ran.
*/
public synchronized boolean whileLive(String applicationId, Consumer<Application> use) {
Optional<Application> app = live(applicationId);
app.ifPresent(use);
return app.isPresent();
}
private Optional<Application> live(String applicationId) {
return storage.get(applicationId).filter(app -> !"TERMINATED".equals(app.getState()));
}
static AwsException resourceNotFound(String arn) {
@@ -3,11 +3,15 @@ package io.github.hectorvent.floci.services.emrserverless.model;
import com.fasterxml.jackson.databind.JsonNode;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.ArrayList;
import java.util.List;
/**
* 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.
* 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.
*/
@RegisterForReflection
public class JobRunRecord {
@@ -16,6 +20,7 @@ public class JobRunRecord {
private JsonNode request;
private String applicationType;
private boolean containerRun;
private List<JobRun> earlierAttempts = new ArrayList<>();
public JobRun getJobRun() { return jobRun; }
public void setJobRun(JobRun jobRun) { this.jobRun = jobRun; }
@@ -27,4 +32,6 @@ public class JobRunRecord {
public void setApplicationType(String applicationType) { this.applicationType = applicationType; }
public boolean isContainerRun() { return containerRun; }
public void setContainerRun(boolean containerRun) { this.containerRun = containerRun; }
public List<JobRun> getEarlierAttempts() { return earlierAttempts; }
public void setEarlierAttempts(List<JobRun> earlierAttempts) { this.earlierAttempts = earlierAttempts; }
}
@@ -11,6 +11,7 @@ import io.github.hectorvent.floci.services.emrserverless.model.Application;
import io.github.hectorvent.floci.services.emrserverless.model.CreateApplicationRequest;
import io.github.hectorvent.floci.services.emrserverless.model.JobDriver;
import io.github.hectorvent.floci.services.emrserverless.model.JobRun;
import io.github.hectorvent.floci.services.emrserverless.model.JobRunAttemptSummary;
import io.github.hectorvent.floci.services.emrserverless.model.JobRunRecord;
import io.github.hectorvent.floci.services.emrserverless.model.MonitoringConfiguration;
import io.github.hectorvent.floci.services.emrserverless.model.RuntimeConfiguration;
@@ -34,6 +35,7 @@ import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
@@ -67,12 +69,7 @@ class EmrServerlessJobRunServiceTest {
when(iamService.resolveCallerArn(any())).thenReturn(Optional.empty());
store = AccountAwareStorageBackend.inMemory(ACCOUNT_ID);
CreateApplicationRequest create = new CreateApplicationRequest();
create.setName("jobs");
create.setReleaseLabel("emr-7.5.0");
create.setType("SPARK");
create.setClientToken(UUID.randomUUID().toString());
applicationId = applications.createApplication(create).getApplicationId();
applicationId = application("jobs", "emr-7.5.0", null);
}
private EmrServerlessJobRunService service(int runDurationSeconds) {
@@ -271,13 +268,7 @@ class EmrServerlessJobRunServiceTest {
void aRunsDriverOutputGoesToCloudWatchWhenItsOwnOrTheApplicationsLoggingIsEnabled() {
FakeRunner runner = new FakeRunner();
EmrServerlessJobRunService service = dockerService(runner);
CreateApplicationRequest create = new CreateApplicationRequest();
create.setName("watched");
create.setReleaseLabel("emr-7.5.0");
create.setType("SPARK");
create.setClientToken(UUID.randomUUID().toString());
create.setMonitoringConfiguration(cloudWatchLogging(Map.of("enabled", true)));
String watched = applications.createApplication(create).getApplicationId();
String watched = application("watched", "emr-7.5.0", cloudWatchLogging(Map.of("enabled", true)));
StartJobRunRequest own = request(null, null);
own.setConfigurationOverrides(Map.of("monitoringConfiguration", Map.of("cloudWatchLoggingConfiguration",
Map.of("enabled", true, "logGroupName", "spark-jobs", "logStreamNamePrefix", "nightly",
@@ -343,13 +334,7 @@ class EmrServerlessJobRunServiceTest {
void aRunsDriverLogsGoUnderItsOwnS3LogUriOrElseTheApplications() {
FakeRunner runner = new FakeRunner();
EmrServerlessJobRunService service = dockerService(runner);
CreateApplicationRequest create = new CreateApplicationRequest();
create.setName("logged");
create.setReleaseLabel("emr-7.5.0");
create.setType("SPARK");
create.setClientToken(UUID.randomUUID().toString());
create.setMonitoringConfiguration(s3LogUri("s3://logs/app-level"));
String logged = applications.createApplication(create).getApplicationId();
String logged = application("logged", "emr-7.5.0", s3LogUri("s3://logs/app-level"));
StartJobRunRequest ownLogUri = request(null, null);
ownLogUri.setConfigurationOverrides(Map.of("monitoringConfiguration",
Map.of("s3MonitoringConfiguration", Map.of("logUri", "s3://logs/job-level/"))));
@@ -387,6 +372,219 @@ class EmrServerlessJobRunServiceTest {
EmrServerlessJobRunService.driverLogFolder(app, run("emr-7.0.0", "STREAMING", null)));
}
@Test
void aBatchRunWhoseDriverFailsIsTriedAgainUntilItSucceedsEachAttemptWithItsOwnLogs() {
FakeRunner runner = new FakeRunner();
EmrServerlessJobRunService service = dockerService(runner);
String logged = application("logged", "emr-7.5.0", s3LogUri("s3://logs/"));
StartJobRunRequest resilient = request(null, null);
resilient.setRetryPolicy(Map.of("maxAttempts", 3));
String jobRunId = service.startJobRun(logged, resilient).getJobRunId();
runner.outcome = SparkJobRunner.Outcome.exitedWith(1);
runNext();
JobRun scheduled = service.getJobRun(logged, jobRunId, null);
clock.advance(Duration.ofSeconds(10));
runNext();
runner.outcome = SparkJobRunner.Outcome.exitedWith(0);
clock.advance(Duration.ofSeconds(10));
runNext();
assertEquals(List.of("SCHEDULED", "2"), List.of(scheduled.getState(), String.valueOf(scheduled.getAttempt())));
JobRun latest = service.getJobRun(logged, jobRunId, null);
assertEquals("SUCCESS", latest.getState());
assertEquals(3, latest.getAttempt());
// "the attempt generates its own set of logs".
String driver = "s3://logs/applications/" + logged + "/jobs/" + jobRunId + "/attempts/%d/SPARK_DRIVER/";
assertEquals(List.of(driver.formatted(1), driver.formatted(2), driver.formatted(3)),
runner.jobs.stream().map(SparkJobRunner.Job::logFolder).toList());
JobRun first = service.getJobRun(logged, jobRunId, 1);
assertEquals("FAILED", first.getState());
assertEquals("Job run failed: the Spark driver exited with code 1.", first.getStateDetails());
assertEquals(1, first.getAttempt());
List<JobRunAttemptSummary> attempts = service.listJobRunAttempts(logged, jobRunId, null, null).items();
assertEquals(List.of(1, 2, 3), attempts.stream().map(JobRunAttemptSummary::getAttempt).toList());
assertEquals(List.of("FAILED", "FAILED", "SUCCESS"),
attempts.stream().map(JobRunAttemptSummary::getState).toList());
// Each attempt after the first is made as the one before it fails.
assertEquals(List.of(attempts.get(0).getUpdatedAt(), attempts.get(1).getUpdatedAt()),
List.of(attempts.get(1).getCreatedAt(), attempts.get(2).getCreatedAt()));
assertEquals(10, Duration.between(attempts.get(1).getCreatedAt(), attempts.get(2).getCreatedAt()).toSeconds());
assertEquals(List.of(latest.getCreatedAt(), latest.getCreatedAt(), latest.getCreatedAt()),
attempts.stream().map(JobRunAttemptSummary::getJobCreatedAt).toList());
}
@Test
void aBatchRunIsFailedOnceItHasMadeItsMaxAttempts() {
FakeRunner runner = new FakeRunner();
runner.outcome = SparkJobRunner.Outcome.exitedWith(1);
EmrServerlessJobRunService service = dockerService(runner);
StartJobRunRequest resilient = request(null, null);
resilient.setRetryPolicy(Map.of("maxAttempts", 2));
String jobRunId = service.startJobRun(applicationId, resilient).getJobRunId();
runNext();
runNext();
JobRun failed = service.getJobRun(applicationId, jobRunId, null);
assertEquals(List.of("FAILED", "2"), List.of(failed.getState(), String.valueOf(failed.getAttempt())));
assertEquals(2, runner.jobs.size());
assertTrue(tasks.isEmpty());
}
@Test
void aRunIsNotTriedAgainWithoutARetryPolicyOrBeforeRelease710() {
FakeRunner runner = new FakeRunner();
runner.outcome = SparkJobRunner.Outcome.exitedWith(1);
EmrServerlessJobRunService service = dockerService(runner);
StartJobRunRequest resilient = request(null, null);
resilient.setRetryPolicy(Map.of("maxAttempts", 3));
String once = service.startJobRun(applicationId, request(null, null)).getJobRunId();
// "EMR Serverless releases 7.1.0 and higher include support for job resiliency".
String older = application("older", "emr-7.0.0", null);
String beforeResiliency = service.startJobRun(older, resilient).getJobRunId();
runNext();
runNext();
assertEquals(1, service.getJobRun(applicationId, once, null).getAttempt());
assertEquals("FAILED", service.getJobRun(applicationId, once, null).getState());
assertEquals(1, service.getJobRun(older, beforeResiliency, null).getAttempt());
assertTrue(tasks.isEmpty());
}
@Test
void aStreamingRunIsTriedAgainUntilItFailsMaxFailedAttemptsPerHourWithinAnHour() {
FakeRunner runner = new FakeRunner();
runner.outcome = SparkJobRunner.Outcome.exitedWith(1);
EmrServerlessJobRunService service = dockerService(runner);
StartJobRunRequest streaming = request("STREAMING", null);
streaming.setRetryPolicy(Map.of("maxFailedAttemptsPerHour", 2));
String jobRunId = service.startJobRun(applicationId, streaming).getJobRunId();
runNext();
// The first failure is more than an hour old by the second, so it no longer counts.
clock.advance(Duration.ofMinutes(61));
runNext();
clock.advance(Duration.ofMinutes(10));
runNext();
JobRun failed = service.getJobRun(applicationId, jobRunId, null);
assertEquals(List.of("FAILED", "3"), List.of(failed.getState(), String.valueOf(failed.getAttempt())));
assertTrue(tasks.isEmpty());
}
@Test
void aCancelledRunOrOnePastItsTimeoutIsNotTriedAgain() {
FakeRunner runner = new FakeRunner();
EmrServerlessJobRunService service = dockerService(runner);
StartJobRunRequest resilient = request(null, null);
resilient.setRetryPolicy(Map.of("maxAttempts", 3));
String cancelled = service.startJobRun(applicationId, resilient).getJobRunId();
runner.whileRunning = () -> service.cancelJobRun(applicationId, cancelled);
runNext();
runNext();
runner.whileRunning = () -> { };
StartJobRunRequest timed = request(null, 5L);
timed.setRetryPolicy(Map.of("maxAttempts", 3));
String timedOut = service.startJobRun(applicationId, timed).getJobRunId();
runner.outcome = SparkJobRunner.Outcome.outOfTime();
runNext();
assertEquals("CANCELLED", service.getJobRun(applicationId, cancelled, null).getState());
assertEquals("CANCELLED", service.getJobRun(applicationId, timedOut, null).getState());
assertEquals(List.of(1, 1), List.of(service.getJobRun(applicationId, cancelled, null).getAttempt(),
service.getJobRun(applicationId, timedOut, null).getAttempt()));
assertTrue(tasks.isEmpty());
}
@Test
void eachAttemptIsLaunchedWhileItsApplicationCannotBeDeleted() {
FakeRunner runner = new FakeRunner();
runner.outcome = SparkJobRunner.Outcome.exitedWith(1);
// Whether the lock DeleteApplication takes was held as each attempt's driver was handed to its thread.
List<Boolean> launchedHoldingTheApplications = new ArrayList<>();
EmrServerlessJobRunService service = new EmrServerlessJobRunService(store, applications, iamService,
new RegionResolver(REGION, ACCOUNT_ID), null, objectMapper, 0, clock, runner, task -> {
launchedHoldingTheApplications.add(Thread.holdsLock(applications));
tasks.add(task);
});
StartJobRunRequest resilient = request(null, null);
resilient.setRetryPolicy(Map.of("maxAttempts", 2));
service.startJobRun(applicationId, resilient);
runNext();
assertEquals(List.of(true, true), launchedHoldingTheApplications);
}
@Test
void aRunWhoseApplicationIsDeletedWhileItsDriverRunsIsNotTriedAgain() {
FakeRunner runner = new FakeRunner();
runner.outcome = SparkJobRunner.Outcome.exitedWith(1);
EmrServerlessJobRunService service = dockerService(runner);
StartJobRunRequest resilient = request(null, null);
resilient.setRetryPolicy(Map.of("maxAttempts", 3));
String jobRunId = service.startJobRun(applicationId, resilient).getJobRunId();
runner.whileRunning = () -> {
applications.stopApplication(applicationId);
applications.deleteApplication(applicationId);
};
runNext();
JobRun failed = store.get(jobRunId).orElseThrow().getJobRun();
assertEquals(List.of("FAILED", "1"), List.of(failed.getState(), String.valueOf(failed.getAttempt())));
assertTrue(tasks.isEmpty());
}
@Test
void aRetryPolicyMemberOutsideOneToTenOrNotAnIntegerIsRefused() {
EmrServerlessJobRunService service = service(0);
assertEquals("1 validation error detected: Value '0' at 'retryPolicy.maxAttempts' failed to satisfy "
+ "constraint: Member must have value greater than or equal to 1",
refused(service, Map.of("maxAttempts", 0), "ValidationException"));
assertEquals("1 validation error detected: Value '11' at 'retryPolicy.maxFailedAttemptsPerHour' failed to "
+ "satisfy constraint: Member must have value less than or equal to 10",
refused(service, Map.of("maxFailedAttemptsPerHour", 11), "ValidationException"));
// As Smithy's restJson1 malformed-request tests have it: a string, a boolean or a fraction for an integer.
for (Object malformed : List.of("3", true, 2.5)) {
assertEquals("retryPolicy.maxAttempts must be an integer",
refused(service, Map.of("maxAttempts", malformed), "SerializationException"));
}
StartJobRunRequest bounds = request(null, null);
bounds.setRetryPolicy(Map.of("maxAttempts", 10, "maxFailedAttemptsPerHour", 1));
assertEquals(Map.of("maxAttempts", 10, "maxFailedAttemptsPerHour", 1),
service.startJobRun(applicationId, bounds).getRetryPolicy());
}
// The message StartJobRun refuses a run with retryPolicy with, as errorCode with HTTP 400.
private String refused(EmrServerlessJobRunService service, Map<String, Object> retryPolicy, String errorCode) {
StartJobRunRequest request = request(null, null);
request.setRetryPolicy(retryPolicy);
AwsException refusal = assertThrows(AwsException.class, () -> service.startJobRun(applicationId, request));
assertEquals(List.of(errorCode, 400), List.of(refusal.getErrorCode(), refusal.getHttpStatus()));
return refusal.getMessage();
}
// A SPARK application on releaseLabel, with monitoring as its monitoring configuration (null for none).
private String application(String name, String releaseLabel, MonitoringConfiguration monitoring) {
CreateApplicationRequest create = applicationRequest(name, releaseLabel, "SPARK");
create.setMonitoringConfiguration(monitoring);
return applications.createApplication(create).getApplicationId();
}
// The request for an application of type on releaseLabel, which a test adds to as it needs.
private static CreateApplicationRequest applicationRequest(String name, String releaseLabel, String type) {
CreateApplicationRequest create = new CreateApplicationRequest();
create.setName(name);
create.setReleaseLabel(releaseLabel);
create.setType(type);
create.setClientToken(UUID.randomUUID().toString());
return create;
}
private static MonitoringConfiguration s3LogUri(String logUri) {
MonitoringConfiguration monitoring = new MonitoringConfiguration();
monitoring.setProperty("s3MonitoringConfiguration", Map.of("logUri", logUri));
@@ -400,6 +598,7 @@ class EmrServerlessJobRunServiceTest {
run.setReleaseLabel(releaseLabel);
run.setMode(mode);
run.setRetryPolicy(maxAttempts != null ? Map.of("maxAttempts", maxAttempts) : null);
run.setAttempt(1);
return run;
}
@@ -442,11 +641,7 @@ class EmrServerlessJobRunServiceTest {
RuntimeConfiguration defaults = new RuntimeConfiguration();
defaults.setMember("classification", "spark-defaults");
defaults.setMember("properties", Map.of("spark.executor.cores", "4", "spark.app.name", "from-app"));
CreateApplicationRequest create = new CreateApplicationRequest();
create.setName("configured-" + releaseLabel);
create.setReleaseLabel(releaseLabel);
create.setType("SPARK");
create.setClientToken(UUID.randomUUID().toString());
CreateApplicationRequest create = applicationRequest("configured-" + releaseLabel, releaseLabel, "SPARK");
create.setRuntimeConfiguration(List.of(defaults));
return applications.createApplication(create).getApplicationId();
}
@@ -527,12 +722,8 @@ class EmrServerlessJobRunServiceTest {
@Test
void aHiveRunFailsWithoutRunning() {
CreateApplicationRequest create = new CreateApplicationRequest();
create.setName("hive");
create.setReleaseLabel("emr-7.5.0");
create.setType("HIVE");
create.setClientToken(UUID.randomUUID().toString());
String hive = applications.createApplication(create).getApplicationId();
String hive = applications.createApplication(applicationRequest("hive", "emr-7.5.0", "HIVE"))
.getApplicationId();
JobDriver.Hive query = new JobDriver.Hive();
query.setQuery("s3://bucket/queries/report.sql");
StartJobRunRequest request = request(null, null);