fix(emr-serverless): honour a cancel's grace period, keep flexExecution and check architecture (#9184)

CancelJobRun ignored its shutdownGracePeriodInSeconds and stopped a
run's driver at once, StartJobRun dropped flexExecution, and
CreateApplication and UpdateApplication took any architecture.

- From emr-7.9.0 a RUNNING run in the docker mode gets the grace
  period it is cancelled with, "during which the job can perform
  cleanup operations prior to final termination". Its driver gets
  SIGTERM through an init process, the run is CANCELLING until the
  driver ends, and a driver still running when the period ends is
  stopped. A batch run has none by default and a streaming run 120
  seconds; a run not yet RUNNING, or on an earlier release, is stopped
  at once, and a value other than 0 or 15 to 1800 is refused with
  ValidationException, in Floci's words. Step Functions' cancelJobRun
  passes its ShutdownGracePeriodInSeconds on, read in either case.
- A run keeps its flexExecution's one member, enabled, which GetJobRun,
  ListJobRuns and ListJobRunAttempts give back; an enabled that is not
  a boolean is refused with SerializationException.
- An architecture other than ARM64 or X86_64 is refused with the
  framework's ValidationException, from the one list CloudFormation's
  application provisioner checks too.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-22 02:57:31 -04:00
1 parent a9bea6567c
commit 8bc759420f
16 files changed
+388 -27

No files matched your search

+18 -3
View File
@@ -132,7 +132,19 @@ runner mode a Spark run executes; see [Running Spark job runs](#running-spark-jo
Apache Spark's releases, `emr-spark-8.0.0` on, hold their `BATCH` runs to it too: the notes apply it "from this
release onwards", and the release list puts them after EMR Serverless 7.14.0.
* **CancelJobRun** moves a run that has not finished to `CANCELLED`. A finished run answers
`ValidationException` "Job run is not in a cancellable state".
`ValidationException` "Job run is not in a cancellable state". In the `docker` mode, from release
`emr-7.9.0` on, a `RUNNING` run gets the `shutdownGracePeriodInSeconds` it is cancelled with, "during which
the job can perform cleanup operations prior to final termination": its driver gets SIGTERM, which runs its
JVM shutdown hooks, the run is `CANCELLING` until the driver ends, and a driver still running when the period
ends is stopped. "The default behavior for shutdown is to have no grace period" for a `BATCH` run, and a
`STREAMING` run has a "120-second grace period enabled by default"; 0 is "Immediate termination". "Grace period
shutdown is only available for jobs in RUNNING state", so a run that has not started yet, or one on an earlier
release, is stopped at once, and "Subsequent cancel requests during the CANCELLING state are ignored". A value
other than 0 or 15 to 1800, the user guide's "Valid Range for Shutdown Grace period", is refused with
`ValidationException`, in Floci's own wording.
* **StartJobRun** keeps the run's `flexExecution` ("The Amazon EMR Serverless Flex settings for the job run"),
which `GetJobRun`, `ListJobRuns` and `ListJobRunAttempts` give back; an `enabled` that is not a boolean is
refused with `SerializationException`. Floci has no Flex capacity to run it on, so it changes nothing else.
* **StopApplication** refuses an application with a run that has not finished, a `STREAMING` run or
a `CANCELLING` one included, as the API reference says "All scheduled and running jobs must be
completed or cancelled before stopping an application." It answers `ValidationException`, the one
@@ -342,7 +354,8 @@ worker of its own on EMR Serverless (see **Executors** below).
image first, or the run is `FAILED` with "Could not pull image"), and `RUNNING` once the Spark driver runs, which sets `startedAt`. It
is `SUCCESS` when the driver exits with code 0 and `FAILED` otherwise, with the exit code in
`stateDetails`. `CancelJobRun`, or a `BATCH` run passing its `executionTimeoutMinutes`, makes it
`CANCELLING` until the driver is stopped, then `CANCELLED`, as the job run states describe. A run
`CANCELLING` until the driver is stopped, or ends within its grace period (see **CancelJobRun** above), then
`CANCELLED`, as the job run states describe. A run
Floci was running when it stopped is `FAILED` once it is read again. Floci's shutdown and a state
reset stop every driver, one whose image is still being pulled included, and a driver a hard stop
left running is removed the first time job runs are used after Floci restarts, unless
@@ -435,6 +448,8 @@ worker of its own on EMR Serverless (see **Executors** below).
move every run to emulation. A host of another architecture runs the image under emulation, which Docker Desktop
has and a Linux host gets from QEMU's `binfmt_misc` handlers; without it the driver cannot start
("exec format error") and the run fails. Floci does not fall back to the host's platform when the setting is on.
`CreateApplication` and `UpdateApplication` refuse an `architecture` other than `ARM64` or `X86_64`, the
model's enum, with the framework's `ValidationException`.
## Running Hive job runs
@@ -479,6 +494,6 @@ application's `imageConfiguration`; a `TezTask` image is not used, as Tez's task
directory; Spark alone unpacks the others, into its own files folder. Floci reads an archive itself,
whatever the execution role may read, though Spark's own read of it uses the role's credentials.
* **Custom images**: Floci does not check an `imageUri` against the model's pattern, which would refuse the repository URIs Floci's own ECR hands out, nor that the image was built from its release's base image (AWS refuses one that was not from `emr-7.14.0` and `emr-spark-8.1.0` on), nor the image's size. An image that cannot be pulled fails the run, not the request that names it. An image's digest is resolved as the application starts where its `applicationLevelDigestResolution` is true, or left unset on EMR 7.13 or earlier, as the user guide's table has it, and AWS's "Custom images are resolved to a digest at application start; that digest is used for all jobs until the application restarts": the application's image configuration gets the digest of the image in Floci's ECR as its `resolvedImageDigest`, and each run pulls the image by it until the application starts again; a stopped application reports none. An image outside ECR, one in another account's repository (Floci does not check that the application may pull it), or one Floci's ECR does not hold or cannot read without Docker, has no digest to read and is resolved for each run, as every image is from 7.14 on; any other answer from Floci's ECR fails `StartApplication` with `InternalServerException`; such a run's digest comes from its attempt's own pull (see **Image** above), and a job run's image configurations carry no `applicationLevelDigestResolution`.
* **Not emulated**: the "EMR Serverless Job Run Retry" event, as Floci sends no EMR Serverless events, the account's limit of 2000 `QUEUED` runs, `totalResourceUtilization` and `billedResourceUtilization` (of a job run or a session), 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, the account's limit of 2000 `QUEUED` runs, `totalResourceUtilization` and `billedResourceUtilization` (of a job run or a session), and Flex capacity (`flexExecution` is kept and given back only).
* **Instant Start/Stop**: Floci marks the application `STARTED` or `STOPPED` immediately without provisioning actual compute capacity in the background.
* **Sessions in the `immediate` mode run nothing**: a session is kept with its lifecycle, but no Spark driver runs for it, and a Spark Connect call to it is refused; the `docker` mode runs one (see [Running a session's Spark Connect server](#running-a-sessions-spark-connect-server)).
@@ -53,7 +53,6 @@ public class EmrServerlessCfnProvisioner implements CfnResourceProvisioner {
Set.of("initialCapacity", "imageConfiguration", "workerTypeSpecifications");
private static final String SCHEDULER = "schedulerConfiguration";
/** The registry schema's {@code Architecture} enum, which model validation holds a template to. */
private static final Set<String> ARCHITECTURES = Set.of("ARM64", "X86_64");
/** The schema's read-only properties, which a user cannot set. */
private static final List<String> READ_ONLY = List.of("ApplicationId", "Arn");
@@ -157,7 +156,7 @@ public class EmrServerlessCfnProvisioner implements CfnResourceProvisioner {
*/
private static void checkTemplate(JsonNode template) {
String architecture = template.path("Architecture").textValue();
if (architecture != null && !ARCHITECTURES.contains(architecture)) {
if (architecture != null && !EmrServerlessService.ARCHITECTURES.contains(architecture)) {
throw CfnPropertyTypes.modelValidation("#/Architecture: " + architecture + " is not a valid enum value)");
}
for (String readOnly : READ_ONLY) {
@@ -216,8 +216,10 @@ public class EmrServerlessController {
@DELETE
@Path("/{applicationId}/jobruns/{jobRunId}")
public CancelJobRunResponse cancelJobRun(@PathParam("applicationId") String applicationId,
@PathParam("jobRunId") String jobRunId) {
JobRun run = jobRuns.cancelJobRun(applicationId, jobRunId);
@PathParam("jobRunId") String jobRunId,
@QueryParam("shutdownGracePeriodInSeconds") String gracePeriod) {
JobRun run = jobRuns.cancelJobRun(applicationId, jobRunId,
EmrServerlessJobRunService.queryInteger(gracePeriod, "shutdownGracePeriodInSeconds"));
CancelJobRunResponse response = new CancelJobRunResponse();
response.setApplicationId(run.getApplicationId());
response.setJobRunId(run.getJobRunId());
@@ -99,6 +99,10 @@ public class EmrServerlessJobRunService implements Resettable {
static final String STATE_QUEUED = "QUEUED";
private static final String MODE_BATCH = "BATCH";
private static final String MODE_STREAMING = "STREAMING";
// CancelJobRun's grace period: its default for a streaming run, and its range.
private static final int DEFAULT_STREAMING_GRACE_SECONDS = 120;
private static final int MIN_GRACE_SECONDS = 15;
private static final int MAX_GRACE_SECONDS = 1800;
private static final String RUNNER_DOCKER = "docker";
// The service a container run's driver belongs to, which names it and labels it.
static final String SERVICE = "emr-serverless";
@@ -463,11 +467,18 @@ public class EmrServerlessJobRunService implements Resettable {
applications.stopApplication(applicationId);
}
/** Cancels a run that has not finished, with the default grace period of {@link #gracePeriod}. */
public synchronized JobRun cancelJobRun(String applicationId, String jobRunId) {
return cancelJobRun(applicationId, jobRunId, null);
}
/**
* Cancels a run that has not finished. A finished run is refused, with AWS's wording. A container
* run is CANCELLING until its driver has stopped.
* run is CANCELLING until its driver has stopped: at once, or after the grace period of {@link #gracePeriod}, in
* which its driver gets SIGTERM and may end by itself, and is stopped when the period ends if it has not.
*/
public synchronized JobRun cancelJobRun(String applicationId, String jobRunId) {
public synchronized JobRun cancelJobRun(String applicationId, String jobRunId, Integer gracePeriodSeconds) {
checkGracePeriod(gracePeriodSeconds);
applications.getApplication(applicationId);
JobRunRecord record = settle(findRun(applicationId, jobRunId));
if (isTerminal(record.getJobRun())) {
@@ -483,10 +494,19 @@ public class EmrServerlessJobRunService implements Resettable {
}
if (record.isContainerRun()) {
JobRun run = record.getJobRun();
// "Subsequent cancel requests during the CANCELLING state are ignored."
if (!STATE_CANCELLING.equals(run.getState())) {
long grace = gracePeriod(run, gracePeriodSeconds);
markCancelling(record);
runExecutor.execute(() -> sparkRunner.stop(jobRunId));
LOG.infov("Cancelling EMR Serverless job run {0} on application {1}", jobRunId, applicationId);
if (grace > 0) {
record.setShutdownDeadline(now.plusSeconds(grace));
store.put(jobRunId, record);
runExecutor.execute(() -> sparkRunner.interrupt(jobRunId));
} else {
runExecutor.execute(() -> sparkRunner.stop(jobRunId));
}
LOG.infov("Cancelling EMR Serverless job run {0} on application {1} with a grace period of {2}s",
jobRunId, applicationId, grace);
}
return run;
}
@@ -532,13 +552,18 @@ public class EmrServerlessJobRunService implements Resettable {
/** GetJobRun's {@code attempt}, an integer in the query string. */
static Integer parseAttempt(String value) {
return queryInteger(value, "attempt");
}
/** An integer {@code member} of the query string, null where it is not given; another value is refused. */
static Integer queryInteger(String value, String member) {
if (value == null || value.isBlank()) {
return null;
}
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
throw new AwsException("ValidationException", "attempt must be an integer.", 400);
throw new AwsException("ValidationException", member + " must be an integer.", 400);
}
}
@@ -577,6 +602,19 @@ public class EmrServerlessJobRunService implements Resettable {
? request.getExecutionTimeoutMinutes() : DEFAULT_EXECUTION_TIMEOUT_MINUTES);
run.setMode(request.getMode());
run.setRetryPolicy(request.getRetryPolicy());
run.setFlexExecution(flexExecution(request.getFlexExecution()));
}
// StartJobRun's flexExecution as the model's FlexExecution holds it: its one member, enabled, where it is given.
private static Map<String, Object> flexExecution(Map<String, Object> given) {
if (given == null) {
return null;
}
Map<String, Object> flex = new LinkedHashMap<>();
if (given.get("enabled") != null) {
flex.put("enabled", given.get("enabled"));
}
return flex;
}
/**
@@ -732,9 +770,13 @@ public class EmrServerlessJobRunService implements Resettable {
// option" on EMR Serverless; with it off, or where the application names none, for the Docker host's own.
SparkJobRunner.Job onPlatform = job.withPlatform(
honourArchitectures ? DockerPlatforms.forArchitecture(app.getArchitecture()) : null);
// Where a cancel may give it a grace period, its driver runs under an init process, which passes it the
// SIGTERM that starts the period.
SparkJobRunner.Job launched = gracefulCancels(run.getReleaseLabel())
? onPlatform.asInterruptible() : onPlatform;
executing.add(run.getJobRunId());
long launchedIn = generation;
runExecutor.execute(() -> execute(onPlatform, launchedIn));
runExecutor.execute(() -> execute(launched, launchedIn));
}
/** The runner of the docker runner mode, or null in the immediate one. */
@@ -1094,10 +1136,50 @@ public class EmrServerlessJobRunService implements Resettable {
private synchronized boolean stillGoing(String jobRunId, long launchedIn) {
return launchedIn == generation && store.get(jobRunId)
.map(record -> STATE_SCHEDULED.equals(record.getJobRun().getState())
|| STATE_RUNNING.equals(record.getJobRun().getState()))
|| STATE_RUNNING.equals(record.getJobRun().getState()) || shuttingDown(record))
.orElse(false);
}
// A run cancelled with a grace period that has not ended, whose driver may still end by itself.
private boolean shuttingDown(JobRunRecord record) {
return STATE_CANCELLING.equals(record.getJobRun().getState()) && record.getShutdownDeadline() != null
&& clock.instant().isBefore(record.getShutdownDeadline());
}
/**
* The grace period, in seconds, of a cancel of {@code run}. From Amazon EMR release 7.9.0 a RUNNING run is given
* one, "during which the job can perform cleanup operations prior to final termination", the one asked for or else
* the default: "The default behavior for shutdown is to have no grace period" for a batch run, and a streaming run
* has a "120-second grace period enabled by default". "Grace period shutdown is only available for jobs in
* RUNNING state", so another run, or one on an earlier release, ends at once (EMR Serverless User Guide, "EMR
* Serverless job run cancellation with grace period").
*/
private static long gracePeriod(JobRun run, Integer asked) {
if (!STATE_RUNNING.equals(run.getState()) || !gracefulCancels(run.getReleaseLabel())) {
return 0;
}
if (asked != null) {
return asked;
}
return MODE_STREAMING.equals(run.getMode()) ? DEFAULT_STREAMING_GRACE_SECONDS : 0;
}
/**
* Refuses a grace period other than 0, "Immediate termination", or one in the "Valid Range for Shutdown Grace
* period: 15-1800 seconds". No source gives AWS's error for one outside it, so the wording is Floci's.
*/
private static void checkGracePeriod(Integer seconds) {
if (seconds != null && seconds != 0 && (seconds < MIN_GRACE_SECONDS || seconds > MAX_GRACE_SECONDS)) {
throw new AwsException("ValidationException", "shutdownGracePeriodInSeconds must be 0, or from "
+ MIN_GRACE_SECONDS + " to " + MAX_GRACE_SECONDS + " seconds.", 400);
}
}
// "This feature is supported with Amazon EMR releases 7.9.0 and higher", the AWS runtime for Apache Spark's too.
private static boolean gracefulCancels(String releaseLabel) {
return releaseAtLeast(RELEASE_LABEL, releaseLabel, 7, 9) || sparkRuntime(releaseLabel);
}
private synchronized void driverStarted(String jobRunId, long launchedIn) {
if (launchedIn != generation) {
return;
@@ -1667,6 +1749,11 @@ public class EmrServerlessJobRunService implements Resettable {
private static void validate(StartJobRunRequest request) {
Map<String, Integer> retryLimits = retryLimits(request.getRetryPolicy());
// FlexExecution's one member, "enabled", a boolean; another JSON type is refused as retryPolicy's are.
Object flex = request.getFlexExecution() != null ? request.getFlexExecution().get("enabled") : null;
if (flex != null && !(flex instanceof Boolean)) {
throw new AwsException("SerializationException", "flexExecution.enabled must be a boolean", 400);
}
List<String> violations = new ArrayList<>();
if (request.getClientToken() == null) {
violations.add(SmithyValidationErrors.notNull("clientToken"));
@@ -1787,6 +1874,7 @@ public class EmrServerlessJobRunService implements Resettable {
summary.setId(run.getJobRunId());
summary.setName(run.getName());
summary.setMode(run.getMode());
summary.setFlexExecution(run.getFlexExecution());
summary.setArn(run.getArn());
summary.setCreatedBy(run.getCreatedBy());
summary.setCreatedAt(run.getCreatedAt());
@@ -1810,6 +1898,7 @@ public class EmrServerlessJobRunService implements Resettable {
summary.setId(attempt.getJobRunId());
summary.setName(attempt.getName());
summary.setMode(attempt.getMode());
summary.setFlexExecution(attempt.getFlexExecution());
summary.setArn(attempt.getArn());
summary.setCreatedBy(attempt.getCreatedBy());
summary.setJobCreatedAt(attempt.getCreatedAt());
@@ -72,6 +72,8 @@ public class EmrServerlessService {
UpdateApplicationRequest::getIdentityCenterConfiguration,
UpdateApplicationRequest::getJobLevelCostAllocationConfiguration);
private static final int MAX_TAGS = 50;
/** The model's Architecture enum, which an application's architecture must be in. */
public static final List<String> ARCHITECTURES = List.of("ARM64", "X86_64");
private static final String RESERVED_PREFIX = "aws:";
private static final Pattern TAG_TEXT = Pattern.compile("[A-Za-z0-9 /_.:=+@-]*");
// ResourceArn's resource: an application, or one of its job runs or sessions.
@@ -126,6 +128,7 @@ public class EmrServerlessService {
if (request.getClientToken() == null || request.getClientToken().isBlank()) {
throw new AwsException("ValidationException", "clientToken is required", 400);
}
validateArchitecture(request.getArchitecture());
validateImages(request.getImageConfiguration(), request.getWorkerTypeSpecifications(), true);
SchedulerConfiguration scheduler = request.getSchedulerConfiguration() != null
? EmrServerlessScheduler.merged(null, request.getSchedulerConfiguration()) : null;
@@ -210,6 +213,7 @@ public class EmrServerlessService {
}
public synchronized Application updateApplication(String applicationId, UpdateApplicationRequest request) {
validateArchitecture(request.getArchitecture());
validateImages(request.getImageConfiguration(), request.getWorkerTypeSpecifications(), false);
Application app = getApplication(applicationId);
@@ -718,6 +722,14 @@ public class EmrServerlessService {
return violations;
}
/** An architecture outside the model's enum, refused as the framework refuses one. */
private static void validateArchitecture(String architecture) {
if (architecture != null && !ARCHITECTURES.contains(architecture)) {
throw SmithyValidationErrors.validationException(
SmithyValidationErrors.notInEnum(architecture, "architecture", ARCHITECTURES));
}
}
/**
* Refuses an image configuration, the application's or a worker type's, that a new application leaves
* without an {@code imageUri} ("This field is required when you create a new application"), or whose image
@@ -33,6 +33,8 @@ public class JobRun {
private Long executionTimeoutMinutes;
private String mode;
private Map<String, Object> retryPolicy;
// StartJobRun's flexExecution as sent; null where it gave none.
private Map<String, Object> flexExecution;
private Integer attempt;
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
private Instant attemptCreatedAt;
@@ -87,6 +89,9 @@ public class JobRun {
public void setMode(String mode) { this.mode = mode; }
public Map<String, Object> getRetryPolicy() { return retryPolicy; }
public void setRetryPolicy(Map<String, Object> retryPolicy) { this.retryPolicy = retryPolicy; }
public Map<String, Object> getFlexExecution() { return flexExecution; }
public void setFlexExecution(Map<String, Object> flexExecution) { this.flexExecution = flexExecution; }
public Integer getAttempt() { return attempt; }
public void setAttempt(Integer attempt) { this.attempt = attempt; }
public Instant getAttemptCreatedAt() { return attemptCreatedAt; }
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.Map;
/**
* One entry of ListJobRunAttempts. {@code id} is the run's id, {@code jobCreatedAt} when the run was
@@ -17,6 +18,7 @@ public class JobRunAttemptSummary {
private String id;
private String name;
private String mode;
private Map<String, Object> flexExecution;
private String arn;
private String createdBy;
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
@@ -40,6 +42,9 @@ public class JobRunAttemptSummary {
public void setName(String name) { this.name = name; }
public String getMode() { return mode; }
public void setMode(String mode) { this.mode = mode; }
public Map<String, Object> getFlexExecution() { return flexExecution; }
public void setFlexExecution(Map<String, Object> flexExecution) { this.flexExecution = flexExecution; }
public String getArn() { return arn; }
public void setArn(String arn) { this.arn = arn; }
public String getCreatedBy() { return createdBy; }
@@ -3,6 +3,7 @@ package io.floci.aws.services.emrserverless.model;
import com.fasterxml.jackson.databind.JsonNode;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
@@ -14,7 +15,8 @@ import java.util.Map;
* 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. Each attempt's
* driver log destinations are kept as it was admitted, by attempt number.
* driver log destinations are kept as it was admitted, by attempt number. A container run cancelled with a grace
* period keeps when that period ends, until which its driver may run on to shut down by itself.
*/
@RegisterForReflection
public class JobRunRecord {
@@ -27,6 +29,7 @@ public class JobRunRecord {
private boolean containerRun;
private List<JobRun> earlierAttempts = new ArrayList<>();
private Map<Integer, DriverLogDestinations> driverLogs = new LinkedHashMap<>();
private Instant shutdownDeadline;
public JobRun getJobRun() { return jobRun; }
public void setJobRun(JobRun jobRun) { this.jobRun = jobRun; }
@@ -44,4 +47,6 @@ public class JobRunRecord {
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; }
public Instant getShutdownDeadline() { return shutdownDeadline; }
public void setShutdownDeadline(Instant shutdownDeadline) { this.shutdownDeadline = shutdownDeadline; }
}
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.Map;
/** One entry of ListJobRuns. Unlike JobRun, the run's id is {@code id}. */
@RegisterForReflection
@@ -14,6 +15,7 @@ public class JobRunSummary {
private String id;
private String name;
private String mode;
private Map<String, Object> flexExecution;
private String arn;
private String createdBy;
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
@@ -39,6 +41,9 @@ public class JobRunSummary {
public void setName(String name) { this.name = name; }
public String getMode() { return mode; }
public void setMode(String mode) { this.mode = mode; }
public Map<String, Object> getFlexExecution() { return flexExecution; }
public void setFlexExecution(Map<String, Object> flexExecution) { this.flexExecution = flexExecution; }
public String getArn() { return arn; }
public void setArn(String arn) { this.arn = arn; }
public String getCreatedBy() { return createdBy; }
@@ -6,7 +6,7 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.Map;
/**
* StartJobRun's body. configurationOverrides, executionIamPolicy and retryPolicy are kept as sent
* StartJobRun's body. configurationOverrides, executionIamPolicy, retryPolicy and flexExecution are kept as sent
* and returned by GetJobRun unchanged.
*/
@RegisterForReflection
@@ -22,6 +22,7 @@ public class StartJobRunRequest {
private String name;
private String mode;
private Map<String, Object> retryPolicy;
private Map<String, Object> flexExecution;
public String getClientToken() { return clientToken; }
public void setClientToken(String clientToken) { this.clientToken = clientToken; }
@@ -43,4 +44,6 @@ public class StartJobRunRequest {
public void setMode(String mode) { this.mode = mode; }
public Map<String, Object> getRetryPolicy() { return retryPolicy; }
public void setRetryPolicy(Map<String, Object> retryPolicy) { this.retryPolicy = retryPolicy; }
public Map<String, Object> getFlexExecution() { return flexExecution; }
public void setFlexExecution(Map<String, Object> flexExecution) { this.flexExecution = flexExecution; }
}
@@ -114,7 +114,13 @@ public class EmrServerlessTaskInvoker {
case "cancelJobRun" -> {
String applicationId = requiredId(request, "ApplicationId");
String jobRunId = requiredId(request, "JobRunId");
ObjectNode response = toStates(call(region, () -> emrServerless.cancelJobRun(applicationId, jobRunId)),
// Read in either case, as the other members are; a value of another JSON type than a number is passed
// on as its JSON, for the cancel to refuse as it refuses one in the query string.
JsonNode grace = field(request, "ShutdownGracePeriodInSeconds");
String gracePeriod = grace.isMissingNode() || grace.isNull() ? null
: grace.isValueNode() ? grace.asText() : grace.toString();
ObjectNode response = toStates(call(region,
() -> emrServerless.cancelJobRun(applicationId, jobRunId, gracePeriod)),
"CancelJobRunResponse");
yield new Job(api, applicationId, jobRunId, response);
}
@@ -157,7 +163,7 @@ public class EmrServerlessTaskInvoker {
Supplier<Object> undo = switch (job.api()) {
case "createApplication" -> () -> emrServerless.deleteApplication(job.applicationId());
case "startApplication" -> () -> emrServerless.stopApplication(job.applicationId());
case "startJobRun" -> () -> emrServerless.cancelJobRun(job.applicationId(), job.jobRunId());
case "startJobRun" -> () -> emrServerless.cancelJobRun(job.applicationId(), job.jobRunId(), null);
default -> null;
};
if (undo == null) {
@@ -528,4 +528,48 @@ public class EmrServerlessIntegrationTest {
.body("application.releaseLabel", equalTo("emr-7.5.0"))
.body("application.maximumCapacity.cpu", equalTo("100 vCPU"));
}
@Test
@Order(14)
void anArchitectureOutsideItsEnumIsRefusedOnCreateAndUpdate() {
givenReq()
.body("""
{"releaseLabel": "emr-7.5.0", "type": "SPARK", "clientToken": "%s", "architecture": "x86"}
""".formatted(UUID.randomUUID()))
.when()
.post("/applications")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", containsString("Value 'x86' at 'architecture' failed to satisfy constraint"));
String graviton = givenReq()
.body("""
{"releaseLabel": "emr-7.5.0", "type": "SPARK", "clientToken": "%s", "architecture": "ARM64"}
""".formatted(UUID.randomUUID()))
.when()
.post("/applications")
.then()
.statusCode(200)
.extract().path("applicationId");
try {
givenReq()
.body("""
{"clientToken": "%s", "architecture": "ARM"}
""".formatted(UUID.randomUUID()))
.when()
.patch("/applications/" + graviton)
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", containsString("Value 'ARM' at 'architecture' failed to satisfy constraint"));
givenReq()
.when()
.get("/applications/" + graviton)
.then()
.statusCode(200)
.body("application.architecture", equalTo("ARM64"));
} finally {
EmrServerlessRequests.deleteApplication("us-east-1", graviton);
}
}
}
@@ -741,4 +741,31 @@ class EmrServerlessJobRunIntegrationTest {
EmrServerlessRequests.emrServerless("eu-west-1").when().get("/applications/" + applicationId + "/jobruns")
.then().statusCode(200).body("jobRuns", empty());
}
@Test
void aRunKeepsItsFlexExecutionAndCancelJobRunChecksItsGracePeriod() {
String applicationId = createApplication("");
String jobRunId = startedRunId(applicationId, sparkRun(UUID.randomUUID().toString(),
", \"mode\": \"STREAMING\", \"flexExecution\": {\"enabled\": true}"));
String run = "/applications/" + applicationId + "/jobruns/" + jobRunId;
givenReq().when().get(run).then().statusCode(200).body("jobRun.flexExecution.enabled", equalTo(true));
givenReq().when().get("/applications/" + applicationId + "/jobruns").then().statusCode(200)
.body("jobRuns.find { it.id == '" + jobRunId + "' }.flexExecution.enabled", equalTo(true));
startJobRun(applicationId,
sparkRun(UUID.randomUUID().toString(), ", \"flexExecution\": {\"enabled\": \"yes\"}"))
.then().statusCode(400)
.body("__type", equalTo("SerializationException"));
givenReq().queryParam("shutdownGracePeriodInSeconds", "soon").when().delete(run)
.then().statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("shutdownGracePeriodInSeconds must be an integer."));
givenReq().queryParam("shutdownGracePeriodInSeconds", 10).when().delete(run)
.then().statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("shutdownGracePeriodInSeconds must be 0, or from 15 to 1800 seconds."));
givenReq().when().get(run).then().statusCode(200).body("jobRun.state", equalTo("RUNNING"));
givenReq().queryParam("shutdownGracePeriodInSeconds", 30).when().delete(run).then().statusCode(200);
givenReq().when().get(run).then().statusCode(200).body("jobRun.state", equalTo("CANCELLED"));
}
}
@@ -1035,6 +1035,113 @@ class EmrServerlessJobRunServiceTest {
assertTrue(tasks.isEmpty());
}
@Test
void aRunCancelledWithAGracePeriodGetsSigtermAndMayEndByItselfUntilThePeriodEnds() {
FakeRunner runner = new FakeRunner();
EmrServerlessJobRunService service = dockerService(runner);
String graceful = application("graceful", "emr-7.9.0", null);
String ended = service.startJobRun(graceful, request(null, null)).getJobRunId();
List<String> cancelling = new ArrayList<>();
runner.whileRunning = () -> {
cancelling.add(service.cancelJobRun(graceful, ended, 60).getState());
// A second cancel while it is CANCELLING changes nothing.
service.cancelJobRun(graceful, ended, 0);
clock.advance(Duration.ofSeconds(59));
};
runNext();
runNext();
assertEquals(List.of("CANCELLING"), cancelling);
assertEquals(List.of(false, false), runner.cancelledAsRunning, "its driver may run on within the period");
assertEquals(Set.of(ended), runner.interrupted);
assertTrue(runner.stopped.isEmpty());
assertTrue(tasks.isEmpty());
assertTrue(runner.jobs.get(0).interruptible(), "its driver gets the SIGTERM through an init process");
assertEquals("CANCELLED", service.getJobRun(graceful, ended, null).getState());
String outlasted = service.startJobRun(graceful, request(null, null)).getJobRunId();
runner.cancelledAsRunning.clear();
runner.whileRunning = () -> {
service.cancelJobRun(graceful, outlasted, 15);
clock.advance(Duration.ofSeconds(15));
};
runNext();
runNext();
assertEquals(List.of(false, true), runner.cancelledAsRunning, "its driver is stopped when the period ends");
assertEquals("CANCELLED", service.getJobRun(graceful, outlasted, null).getState());
}
@Test
void aStreamingRunHasAGracePeriodByDefaultAndABatchRunOrAnEarlierReleaseNone() {
FakeRunner runner = new FakeRunner();
EmrServerlessJobRunService service = dockerService(runner);
String graceful = application("graceful", "emr-7.9.0", null);
String earlier = application("earlier", "emr-7.8.0", null);
String streaming = service.startJobRun(graceful, request("STREAMING", null)).getJobRunId();
runner.whileRunning = () -> {
service.cancelJobRun(graceful, streaming);
clock.advance(Duration.ofSeconds(119));
};
runNext();
runNext();
String batch = service.startJobRun(graceful, request(null, null)).getJobRunId();
runner.whileRunning = () -> service.cancelJobRun(graceful, batch);
runNext();
runNext();
String immediate = service.startJobRun(graceful, request("STREAMING", null)).getJobRunId();
runner.whileRunning = () -> service.cancelJobRun(graceful, immediate, 0);
runNext();
runNext();
String older = service.startJobRun(earlier, request("STREAMING", null)).getJobRunId();
runner.whileRunning = () -> service.cancelJobRun(earlier, older, 60);
runNext();
runNext();
assertEquals(Set.of(streaming), runner.interrupted);
assertEquals(Set.of(batch, immediate, older), runner.stopped);
assertEquals(List.of(false, false, false, true, false, true, false, true), runner.cancelledAsRunning);
assertFalse(runner.jobs.get(3).interruptible(), "an earlier release's driver needs no init process");
for (String run : List.of(streaming, batch, immediate)) {
assertEquals("CANCELLED", service.getJobRun(graceful, run, null).getState());
}
assertEquals("CANCELLED", service.getJobRun(earlier, older, null).getState());
}
@Test
void aGracePeriodOutsideItsRangeIsRefused() {
EmrServerlessJobRunService service = service(60);
String running = service.startJobRun(applicationId, request(null, null)).getJobRunId();
for (int seconds : List.of(14, 1801, -1)) {
AwsException refused = assertThrows(AwsException.class,
() -> service.cancelJobRun(applicationId, running, seconds));
assertEquals("ValidationException", refused.getErrorCode());
assertEquals("shutdownGracePeriodInSeconds must be 0, or from 15 to 1800 seconds.", refused.getMessage());
}
assertEquals("CANCELLED", service.cancelJobRun(applicationId, running, 1800).getState());
}
@Test
void aRunKeepsItsFlexExecutionAndANonBooleanEnabledIsRefused() {
EmrServerlessJobRunService service = service(0);
StartJobRunRequest flex = request(null, null);
// A member FlexExecution does not have is not kept.
flex.setFlexExecution(Map.of("enabled", true, "capacity", "spare"));
String jobRunId = service.startJobRun(applicationId, flex).getJobRunId();
assertEquals(Map.of("enabled", true), service.getJobRun(applicationId, jobRunId, null).getFlexExecution());
JobRunSummary listed = service.listJobRuns(applicationId, null, null, null, null, null, null).items().stream()
.filter(summary -> jobRunId.equals(summary.getId())).findFirst().orElseThrow();
assertEquals(Map.of("enabled", true), listed.getFlexExecution());
assertEquals(Map.of("enabled", true),
service.listJobRunAttempts(applicationId, jobRunId, null, null).items().get(0).getFlexExecution());
StartJobRunRequest notBoolean = request(null, null);
notBoolean.setFlexExecution(Map.of("enabled", "yes"));
AwsException refused = assertThrows(AwsException.class, () -> service.startJobRun(applicationId, notBoolean));
assertEquals("SerializationException", refused.getErrorCode());
}
@Test
void eachAttemptIsLaunchedWhileItsApplicationCannotBeDeleted() {
FakeRunner runner = new FakeRunner();
@@ -1739,6 +1846,7 @@ class EmrServerlessJobRunServiceTest {
private static final class FakeRunner implements SparkJobRunner {
final List<Job> jobs = new ArrayList<>();
final Set<String> stopped = new HashSet<>();
final Set<String> interrupted = new HashSet<>();
final List<String> driversStarted = new ArrayList<>();
// What progress.cancelled() said once the driver ran, and again after whileRunning.
final List<Boolean> cancelledAsRunning = new ArrayList<>();
@@ -1789,6 +1897,11 @@ class EmrServerlessJobRunServiceTest {
stopped.add(runId);
}
@Override
public void interrupt(String runId) {
interrupted.add(runId);
}
@Override
public void removeLeftoverDrivers(String service) {
// A test's drivers live no longer than its runs.
@@ -401,7 +401,9 @@ class EmrServerlessServiceTest {
}
UpdateApplicationRequest other = new UpdateApplicationRequest();
other.setMaximumCapacity(capacity("200 vCPU"));
setter.invoke(other, someValue(setter.getParameterTypes()[0]));
// An architecture in the model's enum, which a value outside it would be refused for first.
setter.invoke(other, "setArchitecture".equals(setter.getName()) ? "ARM64"
: someValue(setter.getParameterTypes()[0]));
AwsException refusal = assertThrows(AwsException.class,
() -> service.updateApplication(applicationId, other), setter.getName());
assertEquals("ValidationException", refusal.getErrorCode());
@@ -31,6 +31,7 @@ import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -126,37 +127,37 @@ class AslExecutorEmrServerlessSyncTest {
assertEquals("data", run.path("Tags").path("team").asText());
assertEquals("4g", run.path("ConfigurationOverrides").path("ApplicationConfiguration").path(0)
.path("Properties").path("spark.executor.memory").asText());
verify(jobRuns, never()).cancelJobRun(anyString(), anyString());
verify(jobRuns, never()).cancelJobRun(anyString(), anyString(), any());
}
@Test
void startJobRunSyncCancelsItsRunWhenTheTaskTimesOut() {
when(jobRuns.getJobRun(APPLICATION_ID, JOB_RUN_ID, null)).thenReturn(jobRun("RUNNING"));
when(jobRuns.cancelJobRun(APPLICATION_ID, JOB_RUN_ID)).thenReturn(jobRun("CANCELLED"));
when(jobRuns.cancelJobRun(APPLICATION_ID, JOB_RUN_ID, null)).thenReturn(jobRun("CANCELLED"));
Execution execution = run(timingOut("startJobRun.sync"), START_JOB_RUN);
assertEquals("FAILED", execution.getStatus());
assertEquals("States.Timeout", execution.getError());
verify(jobRuns).cancelJobRun(APPLICATION_ID, JOB_RUN_ID);
verify(jobRuns).cancelJobRun(APPLICATION_ID, JOB_RUN_ID, null);
}
@Test
void startJobRunSyncStillTimesOutWhenEmrServerlessRefusesTheCancel() {
when(jobRuns.getJobRun(APPLICATION_ID, JOB_RUN_ID, null)).thenReturn(jobRun("RUNNING"));
when(jobRuns.cancelJobRun(APPLICATION_ID, JOB_RUN_ID))
when(jobRuns.cancelJobRun(APPLICATION_ID, JOB_RUN_ID, null))
.thenThrow(new AwsException("ValidationException", "Job run is not in a cancellable state", 400));
Execution execution = run(timingOut("startJobRun.sync"), START_JOB_RUN);
assertEquals("States.Timeout", execution.getError());
verify(jobRuns).cancelJobRun(APPLICATION_ID, JOB_RUN_ID);
verify(jobRuns).cancelJobRun(APPLICATION_ID, JOB_RUN_ID, null);
}
@Test
void anInternalErrorCancellingTheRunFailsTheTaskWithIt() {
when(jobRuns.getJobRun(APPLICATION_ID, JOB_RUN_ID, null)).thenReturn(jobRun("RUNNING"));
when(jobRuns.cancelJobRun(APPLICATION_ID, JOB_RUN_ID))
when(jobRuns.cancelJobRun(APPLICATION_ID, JOB_RUN_ID, null))
.thenThrow(new AwsException("InternalServerException", "Request processing failed", 500));
Execution execution = run(timingOut("startJobRun.sync"), START_JOB_RUN);
@@ -168,7 +169,8 @@ class AslExecutorEmrServerlessSyncTest {
@Test
void aFaultWhileCancellingTheRunIsNotPassedOver() {
when(jobRuns.getJobRun(APPLICATION_ID, JOB_RUN_ID, null)).thenReturn(jobRun("RUNNING"));
when(jobRuns.cancelJobRun(APPLICATION_ID, JOB_RUN_ID)).thenThrow(new IllegalStateException("store closed"));
when(jobRuns.cancelJobRun(APPLICATION_ID, JOB_RUN_ID, null))
.thenThrow(new IllegalStateException("store closed"));
Execution execution = run(timingOut("startJobRun.sync"), START_JOB_RUN);
@@ -179,7 +181,7 @@ class AslExecutorEmrServerlessSyncTest {
@Test
void cancelJobRunSyncFailsWhenTheRunSucceedsInstead() throws Exception {
when(jobRuns.cancelJobRun(APPLICATION_ID, JOB_RUN_ID)).thenReturn(jobRun("CANCELLING"));
when(jobRuns.cancelJobRun(APPLICATION_ID, JOB_RUN_ID, null)).thenReturn(jobRun("CANCELLING"));
when(jobRuns.getJobRun(APPLICATION_ID, JOB_RUN_ID, null)).thenReturn(jobRun("SUCCESS"));
Execution execution = run(task("cancelJobRun.sync"),
@@ -189,6 +191,33 @@ class AslExecutorEmrServerlessSyncTest {
assertEquals("SUCCESS", objectMapper.readTree(execution.getCause()).path("JobRun").path("State").asText());
}
@Test
void cancelJobRunSyncPassesItsGracePeriodOn() {
when(jobRuns.cancelJobRun(APPLICATION_ID, JOB_RUN_ID, 30)).thenReturn(jobRun("CANCELLING"));
when(jobRuns.getJobRun(APPLICATION_ID, JOB_RUN_ID, null)).thenReturn(jobRun("CANCELLED"));
Execution execution = run(task("cancelJobRun.sync"), "{\"ApplicationId\": \"" + APPLICATION_ID
+ "\", \"JobRunId\": \"" + JOB_RUN_ID + "\", \"ShutdownGracePeriodInSeconds\": 30}");
assertEquals("SUCCEEDED", execution.getStatus());
verify(jobRuns).cancelJobRun(APPLICATION_ID, JOB_RUN_ID, 30);
}
@Test
void cancelJobRunSyncReadsItsGracePeriodInEitherCaseAndRefusesOneThatIsNotANumber() {
when(jobRuns.cancelJobRun(APPLICATION_ID, JOB_RUN_ID, 45)).thenReturn(jobRun("CANCELLING"));
when(jobRuns.getJobRun(APPLICATION_ID, JOB_RUN_ID, null)).thenReturn(jobRun("CANCELLED"));
String ids = "{\"applicationId\": \"" + APPLICATION_ID + "\", \"jobRunId\": \"" + JOB_RUN_ID + "\", ";
Execution lowercase = run(task("cancelJobRun.sync"), ids + "\"shutdownGracePeriodInSeconds\": 45}");
Execution structure = run(task("cancelJobRun.sync"), ids + "\"ShutdownGracePeriodInSeconds\": {}}");
assertEquals("SUCCEEDED", lowercase.getStatus());
verify(jobRuns).cancelJobRun(APPLICATION_ID, JOB_RUN_ID, 45);
assertEquals("FAILED", structure.getStatus());
verify(jobRuns, times(1)).cancelJobRun(anyString(), anyString(), any());
}
@Test
void createApplicationSyncDeletesTheApplicationWhenTheTaskTimesOut() {
Application creating = application("CREATING");