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

@@ -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) {