diff --git a/docs/services/emr.md b/docs/services/emr.md
index f847ac7111..73697c08b7 100644
--- a/docs/services/emr.md
+++ b/docs/services/emr.md
@@ -105,8 +105,11 @@ given time", a `CANCEL_PENDING` one counted as running), which `RunJobFlow` and
step is not submitted and the action fails with a message that the ActionOnFailure setting is not valid"), which
`AddJobFlowSteps` refuses with `ValidationException`, a step naming none taking `TERMINATE_CLUSTER`, as it is
submitted, and so refused too; and `CancelSteps` "Available only
-in Amazon EMR versions 4.8.0 and later, excluding version 5.0.0", with at most 256 steps a request, refused otherwise
-with `InvalidRequestException`.
+in Amazon EMR versions 4.8.0 and later, excluding version 5.0.0", with at most 100 steps a request from release
+7.14.0 and 256 before it ("With Amazon EMR releases 7.14.0 and later, the maximum number of steps you can cancel per
+request is 100. With earlier releases, the maximum is 256 steps per request"), refused otherwise with
+`InvalidRequestException`. A `StepCancellationOption` other than `SEND_INTERRUPT` and `TERMINATE_PROCESS` gets the
+framework's enum message.
In the `docker` runner mode a cancelled `RUNNING` step is `CANCEL_PENDING` while its driver stops, and keeps its
place among the running steps until the driver is gone: then it is `CANCELLED`, and the next `PENDING` step starts.
@@ -114,7 +117,13 @@ That is Floci's reading of the Management Guide's "Canceling a running step does
running, assuming no change to stepConcurrencyLevel", beside "Canceling a running or pending step removes that step
from the active step count"; its step events have a `CANCEL_PENDING` row, "was cancelled at Time and is pending
cancellation". Cancelling a `CANCEL_PENDING` step again answers `SUBMITTED`, and the step is `CANCELLED` however
-its driver ends. The step's container stops, and what the applications it started on YARN have logged goes to
+its driver ends. `StepCancellationOption` says how the driver goes, as the Management Guide's "Cancel steps" describes:
+with `SEND_INTERRUPT`, the default, "EMR sends a SIGTERM signal to the step", and the step's command, which a step's
+container runs under an init process so that the signal reaches it, may catch it to clean up, or runs on if it
+ignores it; with `TERMINATE_PROCESS` "EMR sends a SIGKILL signal to the step and all its descendant processes which
+terminates them immediately", as Floci's cancel always did. A `TERMINATE_PROCESS` cancel kills a step a
+`SEND_INTERRUPT` one left running, and a cluster's end kills it too. The step's container stops, and what the
+applications it started on YARN have logged goes to
`containers/` (see **Output**), while an application in `--deploy-mode cluster` runs on to its end: EMR's cancel
signals the step and its descendant processes, and "asynchronous processes are not affected", as the Management
Guide puts it. In the `immediate` mode nothing runs, so a cancelled `RUNNING` step is `CANCELLED` at once and makes
diff --git a/src/main/java/io/floci/aws/services/emr/EmrClusterLifecycle.java b/src/main/java/io/floci/aws/services/emr/EmrClusterLifecycle.java
index 1439acac2b..70742c41e1 100644
--- a/src/main/java/io/floci/aws/services/emr/EmrClusterLifecycle.java
+++ b/src/main/java/io/floci/aws/services/emr/EmrClusterLifecycle.java
@@ -76,8 +76,11 @@ final class EmrClusterLifecycle {
/** {@code step} of {@code cluster} has just gone RUNNING. */
void start(EmrCluster cluster, EmrStep step, String region);
- /** {@code step}, which was RUNNING, has just been cancelled. */
- void stop(EmrStep step);
+ /**
+ * {@code step}, which was RUNNING, has just been cancelled: with {@code terminateProcess} its process is killed
+ * at once, and else sent SIGTERM and left to end.
+ */
+ void stop(EmrStep step, boolean terminateProcess);
}
/**
@@ -171,9 +174,19 @@ final class EmrClusterLifecycle {
* ({@link #stepEnded}), and keeps its place among the running steps meanwhile: "Canceling a running step does
* not allow a pending step to start running, assuming no change to stepConcurrencyLevel". One that completes
* by time, nothing running it, is CANCELLED at once and makes room for the next PENDING one.
+ *
+ *
The Management Guide's "Cancel steps": with {@code SEND_INTERRUPT}, the default, "EMR sends a SIGTERM signal
+ * to the step", which may catch it "to terminate descendant step processes or wait for them to complete"; with
+ * {@code TERMINATE_PROCESS} ({@code terminateProcess}) "EMR sends a SIGKILL signal to the step and all its
+ * descendant processes which terminates them immediately". A step whose SEND_INTERRUPT cancel is pending is
+ * killed by a TERMINATE_PROCESS one.
*/
- String cancel(EmrCluster cluster, EmrStep step, Instant now, String region) {
+ String cancel(EmrCluster cluster, EmrStep step, Instant now, String region, boolean terminateProcess) {
if (CANCEL_PENDING.equals(step.getState())) {
+ if (terminateProcess && step.isInterrupted()) {
+ step.setInterrupted(false);
+ execution.stop(step, true);
+ }
return null;
}
boolean running = RUNNING.equals(step.getState()) && cancelsRunningSteps(cluster.getReleaseLabel());
@@ -182,8 +195,9 @@ final class EmrClusterLifecycle {
}
if (running && !timed(step)) {
step.setState(CANCEL_PENDING);
+ step.setInterrupted(!terminateProcess);
events.queue(events.stepCancelPending(cluster, step, now), region);
- execution.stop(step);
+ execution.stop(step, terminateProcess);
return null;
}
cancelStep(cluster, step, now, region);
@@ -334,6 +348,8 @@ final class EmrClusterLifecycle {
*/
void stepEnded(EmrCluster cluster, EmrStep step, String failure, Instant at, String region) {
if (CANCEL_PENDING.equals(step.getState())) {
+ // Its driver has ended, so there is nothing left to kill.
+ step.setInterrupted(false);
cancelStep(cluster, step, at, region);
runSteps(cluster, at, region);
return;
@@ -403,12 +419,14 @@ final class EmrClusterLifecycle {
}
private void cancelStep(EmrCluster cluster, EmrStep step, Instant at, String region) {
- boolean running = RUNNING.equals(step.getState());
+ // Running, or left to end after a SIGTERM: a step its cluster's end cancels has its process killed.
+ boolean going = RUNNING.equals(step.getState()) || step.isInterrupted();
step.setState(CANCELLED);
+ step.setInterrupted(false);
step.setEndDateTime(at);
events.queue(events.stepStatusChange(cluster, step, CANCELLED), region);
- if (running && !timed(step)) {
- execution.stop(step);
+ if (going && !timed(step)) {
+ execution.stop(step, true);
}
}
diff --git a/src/main/java/io/floci/aws/services/emr/EmrHandler.java b/src/main/java/io/floci/aws/services/emr/EmrHandler.java
index 0cb5a8a361..3006185399 100644
--- a/src/main/java/io/floci/aws/services/emr/EmrHandler.java
+++ b/src/main/java/io/floci/aws/services/emr/EmrHandler.java
@@ -307,8 +307,8 @@ public class EmrHandler {
private Response handleCancelSteps(JsonNode request) {
requireMembers(request, "StepIds");
- List infos = service.cancelSteps(
- text(request, "ClusterId"), stringList(request.path("StepIds")));
+ List infos = service.cancelSteps(text(request, "ClusterId"),
+ stringList(request.path("StepIds")), text(request, "StepCancellationOption"));
ObjectNode response = objectMapper.createObjectNode();
ArrayNode arr = response.putArray("CancelStepsInfoList");
for (EmrService.CancelStepInfo info : infos) {
diff --git a/src/main/java/io/floci/aws/services/emr/EmrService.java b/src/main/java/io/floci/aws/services/emr/EmrService.java
index adaa9ecaf4..620ca5a9aa 100644
--- a/src/main/java/io/floci/aws/services/emr/EmrService.java
+++ b/src/main/java/io/floci/aws/services/emr/EmrService.java
@@ -241,11 +241,15 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
private static final long MAX_IDLE_TIMEOUT_SECONDS = 604_800;
// StepConcurrencyLevel: "You can specify a minimum of 1 step and a maximum of 256 steps" (ModifyCluster), "The
// maximum value is 256" (RunJobFlow). And "only 256 steps can be RUNNING or PENDING at any given time" (Management
- // Guide), and "A maximum of 256 steps are allowed in each CancelSteps request". No source gives AWS's answer to
- // any of them, so their words are Floci's.
+ // Guide), and "With Amazon EMR releases 7.14.0 and later, the maximum number of steps you can cancel per request
+ // is 100. With earlier releases, the maximum is 256 steps per request" ("Cancel steps"). No source gives AWS's
+ // answer to any of them, so their words are Floci's.
private static final int MAX_STEP_CONCURRENCY = 256;
private static final int MAX_ACTIVE_STEPS = 256;
private static final int MAX_CANCELLED_STEPS = 256;
+ private static final int MAX_CANCELLED_STEPS_FROM_7_14 = 100;
+ private static final String TERMINATE_PROCESS = "TERMINATE_PROCESS";
+ private static final List STEP_CANCELLATION_OPTIONS = List.of("SEND_INTERRUPT", TERMINATE_PROCESS);
// A release label's major, minor and patch versions.
private static final Pattern RELEASE_VERSION = Pattern.compile("emr-(\\d{1,6})\\.(\\d{1,6})\\.(\\d{1,6})");
private static final int MAX_PORT = 65_535;
@@ -730,6 +734,19 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
public record CancelStepInfo(String stepId, String status, String reason) {}
public List cancelSteps(String clusterId, List stepIds) {
+ return cancelSteps(clusterId, stepIds, null);
+ }
+
+ /**
+ * Cancels the steps with {@code option}, SEND_INTERRUPT (the default, for null) or TERMINATE_PROCESS, the model's
+ * StepCancellationOption ({@link EmrClusterLifecycle#cancel}).
+ */
+ public List cancelSteps(String clusterId, List stepIds, String option) {
+ if (option != null && !STEP_CANCELLATION_OPTIONS.contains(option)) {
+ throw SmithyValidationErrors.validationException(
+ SmithyValidationErrors.notInEnum(option, "stepCancellationOption", STEP_CANCELLATION_OPTIONS));
+ }
+ boolean terminateProcess = TERMINATE_PROCESS.equals(option);
return call(() -> {
EmrCluster cluster = requireCluster(clusterId);
// CancelSteps is "Available only in Amazon EMR versions 4.8.0 and later, excluding version 5.0.0".
@@ -737,15 +754,17 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
throw invalid("CancelSteps is available only in Amazon EMR versions 4.8.0 and later, excluding"
+ " version 5.0.0, and cluster " + clusterId + " runs " + cluster.getReleaseLabel() + ".");
}
- if (stepIds.size() > MAX_CANCELLED_STEPS) {
- throw invalid("A CancelSteps request can cancel at most " + MAX_CANCELLED_STEPS + " steps, and this"
- + " one names " + stepIds.size() + ".");
+ int most = releaseAtLeast(cluster.getReleaseLabel(), 7, 14, 0)
+ ? MAX_CANCELLED_STEPS_FROM_7_14 : MAX_CANCELLED_STEPS;
+ if (stepIds.size() > most) {
+ throw invalid("A CancelSteps request can cancel at most " + most + " steps on release "
+ + cluster.getReleaseLabel() + ", and this one names " + stepIds.size() + ".");
}
List result = new ArrayList<>();
for (String stepId : stepIds) {
EmrStep step = stepOf(cluster, stepId).orElse(null);
String refusal = step == null ? "Step does not exist."
- : lifecycle.cancel(cluster, step, now(), regionOf(cluster));
+ : lifecycle.cancel(cluster, step, now(), regionOf(cluster), terminateProcess);
result.add(refusal == null
? new CancelStepInfo(stepId, "SUBMITTED", null)
: new CancelStepInfo(stepId, "FAILED", refusal));
@@ -2793,6 +2812,18 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
.filter(step -> EmrClusterLifecycle.RUNNING.equals(step.getState())).isPresent();
}
+ /**
+ * Whether a step's driver may go on, in its reset: RUNNING, or, once its driver runs, interrupted and free to end
+ * on its own. One interrupted before its driver started has no process to signal, so it does not start.
+ */
+ private synchronized boolean mayGoOn(StepLaunch launch, boolean driverStarted) {
+ return launch.launchedIn() == generation && clusterStore.get(launch.clusterId())
+ .flatMap(cluster -> stepOf(cluster, launch.stepId()))
+ .filter(step -> EmrClusterLifecycle.RUNNING.equals(step.getState()) || (driverStarted
+ && EmrClusterLifecycle.CANCEL_PENDING.equals(step.getState()) && step.isInterrupted()))
+ .isPresent();
+ }
+
// Whether a command's cluster still runs, in the reset it was handed off in.
private synchronized boolean commandGoing(CommandLaunch launch) {
return launch.launchedIn() == generation && clusterStore.get(launch.clusterId())
@@ -2882,7 +2913,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
executionRole(cluster, step, accountId), Map.of(), hive.arguments(), hive.runner(),
Duration.ZERO, EmrSparkSteps.logFolder(cluster, step), null,
EmrSparkSteps.hiveEnvironment(cluster.getConfigurations(), SNAPSHOT_MAPPER), List.of(),
- storage, Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), null);
+ storage, Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), null).asInterruptible();
} else if (application == null && command == null) {
job = null;
} else {
@@ -2897,7 +2928,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
EmrSparkSteps.sparkLog4j2(cluster.getConfigurations(), SNAPSHOT_MAPPER),
EmrSparkSteps.mapredSite(cluster.getConfigurations(), SNAPSHOT_MAPPER),
EmrSparkSteps.hadoopLog4j(cluster.getConfigurations(), SNAPSHOT_MAPPER),
- EmrSparkSteps.hadoopEnvironment(cluster.getConfigurations(), SNAPSHOT_MAPPER), null);
+ EmrSparkSteps.hadoopEnvironment(cluster.getConfigurations(), SNAPSHOT_MAPPER), null)
+ .asInterruptible();
}
StepLaunch launch = new StepLaunch(accountId, region, cluster.getId(), step.getId(), generation,
teardowns.get());
@@ -2908,8 +2940,12 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
}
@Override
- public void stop(EmrStep step) {
- sparkRunner.stop(step.getId());
+ public void stop(EmrStep step, boolean terminateProcess) {
+ if (terminateProcess) {
+ sparkRunner.stop(step.getId());
+ } else {
+ sparkRunner.interrupt(step.getId());
+ }
}
}
@@ -3926,7 +3962,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
@Override
public boolean cancelled() {
return teardowns.get() != launch.teardownsBefore()
- || !RequestScopes.callAs(launch.accountId(), launch.region(), () -> stillRunning(launch));
+ || !RequestScopes.callAs(launch.accountId(), launch.region(),
+ () -> mayGoOn(launch, driverStarted));
}
}
diff --git a/src/main/java/io/floci/aws/services/emr/model/EmrStep.java b/src/main/java/io/floci/aws/services/emr/model/EmrStep.java
index 1468b5f6f6..0e35294318 100644
--- a/src/main/java/io/floci/aws/services/emr/model/EmrStep.java
+++ b/src/main/java/io/floci/aws/services/emr/model/EmrStep.java
@@ -31,6 +31,8 @@ public class EmrStep {
private boolean runInContainer;
private String failureReason;
private String failureMessage;
+ // Whether its cancel is pending after SEND_INTERRUPT, its process sent SIGTERM and free to finish on its own.
+ private boolean interrupted;
private Instant creationDateTime;
private Instant startDateTime;
private Instant endDateTime;
@@ -79,6 +81,9 @@ public class EmrStep {
public String getFailureReason() { return failureReason; }
public void setFailureReason(String failureReason) { this.failureReason = failureReason; }
+ public boolean isInterrupted() { return interrupted; }
+ public void setInterrupted(boolean interrupted) { this.interrupted = interrupted; }
+
public String getFailureMessage() { return failureMessage; }
public void setFailureMessage(String failureMessage) { this.failureMessage = failureMessage; }
diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java
index 5c0798cd5a..ead5dcae45 100644
--- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java
+++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java
@@ -2,6 +2,8 @@ package io.floci.aws.services.emrserverless;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.InspectContainerResponse;
+import com.github.dockerjava.api.exception.ConflictException;
+import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.StreamType;
@@ -52,6 +54,7 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
+import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.function.BooleanSupplier;
@@ -482,6 +485,8 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
private final Map capacities = new ConcurrentHashMap<>();
// Where Floci reaches the Spark UI of each EMR Serverless Spark run's driver, by run, while its container runs.
private final Map driverUis = new ConcurrentHashMap<>();
+ // The runs asked to interrupt their driver, which the thread watching each sends it SIGTERM for.
+ private final Set interrupts = ConcurrentHashMap.newKeySet();
private final ContainerBuilder containerBuilder;
private final ContainerLifecycleManager lifecycleManager;
@@ -556,6 +561,9 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
ContainerBuilder.Builder container = containerBuilder.newContainer(launchImage(job, progress))
.withName(ContainerStorageHelper.dockerName(config, job.service() + "-" + job.runId()))
.withEnv(environment(awsEnvironment, job.environment()));
+ if (job.interruptible()) {
+ container.withInit();
+ }
// bash -c's script gets "floci" as its $0, and what runs after it as its arguments, "$@".
if (job.engine() == Engine.HIVE) {
List hive = hiveArguments(job, endpoint, executorEnvironment);
@@ -712,6 +720,7 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
return Outcome.couldNotStart(e.getMessage());
} finally {
driverUis.remove(job.runId());
+ interrupts.remove(job.runId());
// The executors go with their driver, however the run ended, and their workers' share of the
// application's capacity with them.
if (executors != null) {
@@ -722,6 +731,7 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
}
String unclaimed = launches.end(job.runId(), launch);
if (unclaimed != null) {
+ killInterruptible(job, unclaimed);
lifecycleManager.stopAndRemove(unclaimed, logHandle, STOP_TIMEOUT_SECONDS);
} else if (logHandle != null) {
// Floci's teardown claimed the driver, but the log stream is still this run's to close.
@@ -763,6 +773,50 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
}
}
+ /**
+ * Asks the thread watching the run's running driver to send its container SIGTERM, which the container's init
+ * process passes on to the driver ({@link Job#asInterruptible}), and to let the run end as the driver does. Like
+ * {@link #stop}, it makes no Docker call, so the caller is never held up by Docker. A run whose driver has not
+ * started yet is not interrupted here: its caller reports it cancelled until then.
+ */
+ @Override
+ public void interrupt(String runId) {
+ if (launches.get(runId) != null) {
+ interrupts.add(runId);
+ }
+ }
+
+ // Sends the driver's container SIGTERM; one Docker cannot send it to is stopped instead, so the run still ends.
+ private void sendSigterm(String containerId, Job job, ContainerLaunches.Launch launch) {
+ try {
+ lifecycleManager.getDockerClient().killContainerCmd(containerId).withSignal("SIGTERM").exec();
+ } catch (NotFoundException | ConflictException e) {
+ // Gone, or no longer running: the next look finds it ended.
+ } catch (RuntimeException e) {
+ LOG.warnv(e, "Could not send SIGTERM to the driver of Spark run {0}; stopping it", job.runId());
+ launch.requestStop();
+ }
+ }
+
+ /**
+ * Sends an interruptible job's driver container SIGKILL, where it still runs, before it is stopped: Docker's stop
+ * sends SIGTERM first, which the container's init process passes on to the driver, so a driver stopped at once
+ * would get a SIGTERM to handle ({@link Job#asInterruptible}).
+ */
+ private void killInterruptible(Job job, String containerId) {
+ if (!job.interruptible()) {
+ return;
+ }
+ try {
+ lifecycleManager.getDockerClient().killContainerCmd(containerId).exec();
+ } catch (NotFoundException | ConflictException e) {
+ // Gone, or no longer running: nothing to kill.
+ } catch (RuntimeException e) {
+ // Docker's stop that follows sends SIGKILL at its end anyway.
+ LOG.warnv(e, "Could not kill the driver of Spark run {0}", job.runId());
+ }
+ }
+
/**
* Stops every run inside {@link #run}, so a reset or a shutdown orphans none: a running driver is
* stopped and removed now, and one whose image is still being pulled as soon as its container is up.
@@ -1808,6 +1862,9 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
SparkExecutors executors) throws InterruptedException {
Instant deadline = job.timeout().isZero() ? null : clock.instant().plus(job.timeout());
while (!launch.stopRequested() && !progress.cancelled()) {
+ if (interrupts.remove(job.runId())) {
+ sendSigterm(containerId, job, launch);
+ }
if (executors != null) {
executors.follow();
}
@@ -1845,6 +1902,7 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
}
// Closed however the read ends, which ends Docker's stream and the compressors.
try (DriverOutput output = new DriverOutput()) {
+ killInterruptible(job, containerId);
lifecycleManager.stop(containerId, STOP_TIMEOUT_SECONDS);
lifecycleManager.getDockerClient().logContainerCmd(containerId)
.withStdOut(true)
diff --git a/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java b/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java
index 66c7411061..9286fad76b 100644
--- a/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java
+++ b/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java
@@ -28,6 +28,16 @@ public interface SparkJobRunner {
*/
void stop(String runId);
+ /**
+ * Sends the run's running driver SIGTERM and lets it end as it will, where {@link #stop} ends it at once: a driver
+ * that handles the signal may clean up first, and one that ignores it runs on. {@link #run} then returns its exit
+ * code. Without a driver running yet there is nothing to interrupt, so the run is stopped; that is all a runner
+ * that cannot signal its drivers does.
+ */
+ default void interrupt(String runId) {
+ stop(runId);
+ }
+
/**
* Where Floci reaches the Spark UI of run {@code runId}'s driver while its container runs, for an EMR Serverless
* Spark run or session; empty for any other run, and before or after its container runs.
@@ -143,7 +153,7 @@ public interface SparkJobRunner {
List archives, Storage storage, Map coreSite,
Map sparkLog4j2, Map mapredSite, Map hadoopLog4j,
Map hadoopEnvironment, Executors executors, String platform, int listenPort,
- boolean keepsEventLogs) {
+ boolean keepsEventLogs, boolean interruptible) {
/** A job whose driver listens on no port for Floci. */
public Job(String service, String runId, String accountId, String region, String releaseLabel, Engine engine,
@@ -157,7 +167,7 @@ public interface SparkJobRunner {
this(service, runId, accountId, region, releaseLabel, engine, imageTemplate, customImage, dockerNetwork,
executionRole, sparkDefaults, application, command, timeout, logFolder, cloudWatchLogs,
environment, archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j,
- hadoopEnvironment, executors, platform, 0, false);
+ hadoopEnvironment, executors, platform, 0, false, false);
}
/** A job on the Docker host's own platform. */
@@ -179,7 +189,7 @@ public interface SparkJobRunner {
return new Job(service, runId, accountId, region, releaseLabel, engine, imageTemplate, customImage,
dockerNetwork, executionRole, sparkDefaults, application, command, timeout, logFolder,
cloudWatchLogs, environment, archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j,
- hadoopEnvironment, executors, platform, listenPort, keepsEventLogs);
+ hadoopEnvironment, executors, platform, listenPort, keepsEventLogs, interruptible);
}
/** This job, run in {@code image}. */
@@ -187,7 +197,7 @@ public interface SparkJobRunner {
return new Job(service, runId, accountId, region, releaseLabel, engine, image, customImage, dockerNetwork,
executionRole, sparkDefaults, application, command, timeout, logFolder, cloudWatchLogs, environment,
archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j, hadoopEnvironment, executors,
- platform, listenPort, keepsEventLogs);
+ platform, listenPort, keepsEventLogs, interruptible);
}
/** This job, its executors where {@code executors} has them. */
@@ -195,7 +205,7 @@ public interface SparkJobRunner {
return new Job(service, runId, accountId, region, releaseLabel, engine, imageTemplate, customImage,
dockerNetwork, executionRole, sparkDefaults, application, command, timeout, logFolder,
cloudWatchLogs, environment, archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j,
- hadoopEnvironment, executors, platform, listenPort, keepsEventLogs);
+ hadoopEnvironment, executors, platform, listenPort, keepsEventLogs, interruptible);
}
/** This job, its driver listening on {@code port} for Floci (0 for none). */
@@ -203,7 +213,7 @@ public interface SparkJobRunner {
return new Job(service, runId, accountId, region, releaseLabel, engine, imageTemplate, customImage,
dockerNetwork, executionRole, sparkDefaults, application, command, timeout, logFolder,
cloudWatchLogs, environment, archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j,
- hadoopEnvironment, executors, platform, port, keepsEventLogs);
+ hadoopEnvironment, executors, platform, port, keepsEventLogs, interruptible);
}
/** This job, its containers on {@code network} (null for the global default). */
@@ -211,7 +221,7 @@ public interface SparkJobRunner {
return new Job(service, runId, accountId, region, releaseLabel, engine, imageTemplate, customImage,
network, executionRole, sparkDefaults, application, command, timeout, logFolder, cloudWatchLogs,
environment, archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j, hadoopEnvironment,
- executors, platform, listenPort, keepsEventLogs);
+ executors, platform, listenPort, keepsEventLogs, interruptible);
}
/** This job, its Spark event logs kept for its Spark History Server once it ends. */
@@ -219,7 +229,19 @@ public interface SparkJobRunner {
return new Job(service, runId, accountId, region, releaseLabel, engine, imageTemplate, customImage,
dockerNetwork, executionRole, sparkDefaults, application, command, timeout, logFolder,
cloudWatchLogs, environment, archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j,
- hadoopEnvironment, executors, platform, listenPort, true);
+ hadoopEnvironment, executors, platform, listenPort, true, interruptible);
+ }
+
+ /**
+ * This job, its driver's process sent the signals its container gets by an init process, as Docker's
+ * {@code --init} runs one, so that {@link SparkJobRunner#interrupt} reaches it: a container's own first process
+ * ignores SIGTERM unless it handles it.
+ */
+ public Job asInterruptible() {
+ return new Job(service, runId, accountId, region, releaseLabel, engine, imageTemplate, customImage,
+ dockerNetwork, executionRole, sparkDefaults, application, command, timeout, logFolder,
+ cloudWatchLogs, environment, archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j,
+ hadoopEnvironment, executors, platform, listenPort, keepsEventLogs, true);
}
/** This job, its containers run for {@code platform} (null for the Docker host's own). */
@@ -227,7 +249,7 @@ public interface SparkJobRunner {
return new Job(service, runId, accountId, region, releaseLabel, engine, imageTemplate, customImage,
dockerNetwork, executionRole, sparkDefaults, application, command, timeout, logFolder,
cloudWatchLogs, environment, archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j,
- hadoopEnvironment, executors, platform, listenPort, keepsEventLogs);
+ hadoopEnvironment, executors, platform, listenPort, keepsEventLogs, interruptible);
}
}
diff --git a/src/test/java/io/floci/aws/services/emr/EmrDockerRunnerNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/emr/EmrDockerRunnerNightlyIntegrationTest.java
index 3e8d1c89cb..ed8e4b82ec 100644
--- a/src/test/java/io/floci/aws/services/emr/EmrDockerRunnerNightlyIntegrationTest.java
+++ b/src/test/java/io/floci/aws/services/emr/EmrDockerRunnerNightlyIntegrationTest.java
@@ -2,6 +2,7 @@ package io.floci.aws.services.emr;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.github.dockerjava.api.command.TopContainerResponse;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.docker.ContainerExec;
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
@@ -37,6 +38,7 @@ import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
@@ -134,6 +136,59 @@ class EmrDockerRunnerNightlyIntegrationTest {
assertEquals(WORD_COUNTS, counts("out/"));
}
+ /**
+ * CancelSteps' options (Management Guide, "Cancel steps"): SEND_INTERRUPT "sends a SIGTERM signal to the step",
+ * which a handler may catch to clean up, and TERMINATE_PROCESS "a SIGKILL signal to the step and all its descendant
+ * processes". Each step's command traps SIGTERM to print a line and exit; only the interrupted one's log holds it.
+ */
+ @Test
+ void aSendInterruptCancelLetsTheStepHandleSigtermWhereTerminateProcessKillsIt() {
+ startCluster("[]", s3Uri("logs/"));
+ String script = "trap 'echo interrupted-cleanly; exit 0' TERM; echo started; sleep 300 & wait";
+
+ for (String option : List.of("SEND_INTERRUPT", "TERMINATE_PROCESS")) {
+ String stepId = EmrRequests.addStep(clusterId, option, "command-runner.jar", "bash", "-c", script);
+ awaitSleeping(stepId);
+ emr("CancelSteps", "{\"ClusterId\":\"" + clusterId + "\",\"StepIds\":[\"" + stepId + "\"],"
+ + "\"StepCancellationOption\":\"" + option + "\"}").then().statusCode(200);
+
+ assertEquals("CANCELLED", awaitCancelEnded(stepId));
+ String stdout = S3TestClients.gunzipped(s3, bucket,
+ "logs/" + clusterId + "/steps/" + stepId + "/stdout.gz");
+ assertTrue(stdout.contains("started"), stdout);
+ assertEquals("SEND_INTERRUPT".equals(option), stdout.contains("interrupted-cleanly"),
+ option + ": " + stdout);
+ }
+ }
+
+ // Waits until the step is no longer RUNNING nor CANCEL_PENDING, its driver gone, and gives its state then.
+ private String awaitCancelEnded(String stepId) {
+ return await("step " + stepId + "'s cancel to end").atMost(Duration.ofMinutes(5))
+ .pollInterval(Duration.ofSeconds(1))
+ .until(() -> emr("DescribeStep", "{\"ClusterId\":\"" + clusterId + "\",\"StepId\":\"" + stepId + "\"}")
+ .then().statusCode(200).extract().jsonPath().getString("Step.Status.State"),
+ state -> !"RUNNING".equals(state) && !"CANCEL_PENDING".equals(state));
+ }
+
+ // Waits until the step's command sleeps in its container, its SIGTERM handler set before that.
+ private void awaitSleeping(String stepId) {
+ // Named as the runner names a step's driver: its service, "emr", and its id.
+ String container = ContainerStorageHelper.dockerName(config, "emr-" + stepId);
+ await("step " + stepId + "'s command to sleep").atMost(Duration.ofMinutes(5))
+ .pollInterval(Duration.ofSeconds(1))
+ .until(() -> sleeping(container));
+ }
+
+ private boolean sleeping(String container) {
+ try {
+ TopContainerResponse top = lifecycle.getDockerClient().topContainerCmd(container).exec();
+ return top.getProcesses() != null && Arrays.stream(top.getProcesses())
+ .anyMatch(process -> String.join(" ", process).contains("sleep 300"));
+ } catch (RuntimeException notRunningYet) {
+ return false;
+ }
+ }
+
@Test
void aStreamingJobsMapperAndReducerRunInYarnContainersOnItsClustersCoreAndTaskNodes() {
// Each says the host it ran on, after the words it counted.
diff --git a/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java b/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java
index 857dd61e51..178b655b2b 100644
--- a/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java
+++ b/src/test/java/io/floci/aws/services/emr/EmrServiceContainerStepsTest.java
@@ -1146,7 +1146,8 @@ class EmrServiceContainerStepsTest {
// The next step starts once the driver is gone, before anything reads the cluster.
assertEquals(1, fixture.stepThreadsWaiting());
- assertEquals(Set.of(stoppedId), runner.stopped);
+ // SEND_INTERRUPT, the default, sends it SIGTERM, which ends it.
+ assertEquals(Set.of(stoppedId), runner.interrupted);
// "Canceling a running step does not allow a pending step to start running" while its driver stops.
assertEquals(List.of("RUNNING", "CANCEL_PENDING", "PENDING", "PENDING"), whileStopping);
// "CancelSteps is idempotent".
@@ -1159,6 +1160,69 @@ class EmrServiceContainerStepsTest {
"PENDING added", "CANCELLED stopped", "RUNNING next"), fixture.states());
}
+ /**
+ * SEND_INTERRUPT, the default: "EMR sends a SIGTERM signal to the step", which may "terminate descendant step
+ * processes or wait for them to complete". The step is CANCEL_PENDING while its driver goes on, and CANCELLED,
+ * without its ActionOnFailure, once the driver has ended on its own.
+ */
+ @Test
+ void aSendInterruptCancelSignalsTheStepAndLetsItsDriverEndOnItsOwn() {
+ EmrCluster cluster = service.runJobFlow(cluster("interrupted", true,
+ sparkStep("interrupted", "TERMINATE_CLUSTER"), sparkStep("next", "CONTINUE")), REGION);
+ String interruptedId = cluster.getSteps().get(0).getId();
+ List whileInterrupted = new ArrayList<>();
+ // A driver ended by SIGTERM: 128 + 15.
+ runner.outcome = SparkJobRunner.Outcome.exitedWith(143);
+ runner.whileRunning = () -> {
+ service.cancelSteps(cluster.getId(), List.of(interruptedId));
+ whileInterrupted.add(service.describeCluster(cluster.getId()).getSteps().get(0).getState());
+ };
+
+ fixture.runStepThread();
+
+ assertEquals(Set.of(interruptedId), runner.interrupted);
+ assertEquals(Set.of(), runner.stopped);
+ assertEquals(List.of(false, false), runner.cancelledAsRunning, "the driver may go on until it ends");
+ assertEquals(List.of("CANCEL_PENDING"), whileInterrupted);
+ EmrCluster running = service.describeCluster(cluster.getId());
+ assertEquals("RUNNING", running.getState());
+ assertEquals(List.of("CANCELLED", "RUNNING"), stepStates(running.getSteps()));
+ assertNull(running.getSteps().get(0).getFailureMessage());
+ }
+
+ /** TERMINATE_PROCESS: "EMR sends a SIGKILL signal to the step and all its descendant processes". */
+ @Test
+ void aTerminateProcessCancelKillsTheStepAtOnce() {
+ EmrCluster cluster = service.runJobFlow(cluster("killed", true, sparkStep("killed", "CONTINUE")), REGION);
+ String killedId = cluster.getSteps().get(0).getId();
+ runner.whileRunning = () -> service.cancelSteps(cluster.getId(), List.of(killedId), "TERMINATE_PROCESS");
+
+ fixture.runStepThread();
+
+ assertEquals(Set.of(killedId), runner.stopped);
+ assertEquals(Set.of(), runner.interrupted);
+ assertEquals(List.of(false, true), runner.cancelledAsRunning);
+ assertEquals("CANCELLED", service.describeCluster(cluster.getId()).getSteps().get(0).getState());
+ }
+
+ @Test
+ void aTerminateProcessCancelKillsAStepAnInterruptLeftRunning() {
+ EmrCluster cluster = service.runJobFlow(cluster("escalated", true, sparkStep("escalated", "CONTINUE")),
+ REGION);
+ String escalatedId = cluster.getSteps().get(0).getId();
+ runner.whileRunning = () -> {
+ service.cancelSteps(cluster.getId(), List.of(escalatedId), "SEND_INTERRUPT");
+ service.cancelSteps(cluster.getId(), List.of(escalatedId), "TERMINATE_PROCESS");
+ };
+
+ fixture.runStepThread();
+
+ assertEquals(Set.of(escalatedId), runner.interrupted);
+ assertEquals(Set.of(escalatedId), runner.stopped);
+ assertEquals(List.of(false, true), runner.cancelledAsRunning);
+ assertEquals("CANCELLED", service.describeCluster(cluster.getId()).getSteps().get(0).getState());
+ }
+
@Test
void aStepWhoseDriverEndsByItselfWhileItsCancelIsPendingIsCancelledAndTakesNoAction() {
EmrCluster cluster = service.runJobFlow(cluster("raced", true,
@@ -2445,6 +2509,8 @@ class EmrServiceContainerStepsTest {
private static final class FakeRunner implements SparkJobRunner {
final List jobs = new ArrayList<>();
final Set stopped = new HashSet<>();
+ // Runs sent SIGTERM: a driver that ignores it runs on.
+ final Set interrupted = new HashSet<>();
final List driversStarted = new ArrayList<>();
// What progress.cancelled() said once the driver ran, and again after whileRunning.
final List cancelledAsRunning = new ArrayList<>();
@@ -2455,7 +2521,7 @@ class EmrServiceContainerStepsTest {
public Outcome run(Job job, Progress progress) {
jobs.add(job);
// As the Docker runner, a stop counts only for a run in progress, so a cancel before then is read here.
- if (progress.cancelled()) {
+ if (progress.cancelled() || stopped.contains(job.runId())) {
return Outcome.halted();
}
driversStarted.add(job.runId());
@@ -2471,6 +2537,14 @@ class EmrServiceContainerStepsTest {
stopped.add(runId);
}
+ // As the Docker runner, only a run whose driver runs is interrupted; one before then reads as cancelled.
+ @Override
+ public void interrupt(String runId) {
+ if (driversStarted.contains(runId)) {
+ interrupted.add(runId);
+ }
+ }
+
@Override
public void removeLeftoverDrivers(String service) {
// A test's drivers live no longer than its runs.
diff --git a/src/test/java/io/floci/aws/services/emr/EmrServiceTest.java b/src/test/java/io/floci/aws/services/emr/EmrServiceTest.java
index a45815d718..a952d6eae5 100644
--- a/src/test/java/io/floci/aws/services/emr/EmrServiceTest.java
+++ b/src/test/java/io/floci/aws/services/emr/EmrServiceTest.java
@@ -301,13 +301,36 @@ class EmrServiceTest {
+ " and cluster " + oldId + " runs emr-4.7.2.", older.getMessage());
assertThrows(AwsException.class, () -> service.cancelSteps(firstId, List.of("s-1")));
assertEquals(1, service.cancelSteps(patchedId, List.of("s-1")).size());
- // "A maximum of 256 steps are allowed in each CancelSteps request."
+ // "With earlier releases, the maximum is 256 steps per request."
List ids = Collections.nCopies(257, "s-1");
AwsException tooMany = assertThrows(AwsException.class, () -> service.cancelSteps(patchedId, ids));
- assertEquals("A CancelSteps request can cancel at most 256 steps, and this one names 257.",
+ assertEquals("A CancelSteps request can cancel at most 256 steps on release emr-5.0.3, and this one names 257.",
tooMany.getMessage());
}
+ /** "With Amazon EMR releases 7.14.0 and later, the maximum number of steps you can cancel per request is 100." */
+ @Test
+ void cancelStepsTakesAtMost100StepsFromRelease714AndOnlyTheTwoOptions() {
+ EmrService service = new EmrServiceFixture(0, 60, 0).service;
+ EmrCluster current = cluster("current", true);
+ current.setReleaseLabel("emr-7.14.0");
+ String currentId = service.runJobFlow(current, REGION).getId();
+ EmrCluster earlier = cluster("earlier", true);
+ earlier.setReleaseLabel("emr-7.13.0");
+ String earlierId = service.runJobFlow(earlier, REGION).getId();
+ List ids = Collections.nCopies(101, "s-1");
+
+ AwsException tooMany = assertThrows(AwsException.class, () -> service.cancelSteps(currentId, ids));
+ assertEquals("A CancelSteps request can cancel at most 100 steps on release emr-7.14.0, and this one names"
+ + " 101.", tooMany.getMessage());
+ assertEquals(101, service.cancelSteps(earlierId, ids).size());
+ assertEquals(1, service.cancelSteps(currentId, List.of("s-1"), "TERMINATE_PROCESS").size());
+ AwsException option = assertThrows(AwsException.class,
+ () -> service.cancelSteps(currentId, List.of("s-1"), "SIGKILL"));
+ assertEquals("ValidationException", option.getErrorCode());
+ assertTrue(option.getMessage().contains("'stepCancellationOption'"), option.getMessage());
+ }
+
@Test
void stepsAddedWhileAClusterStartsRunOnceItIsReady() {
EmrServiceFixture fixture = new EmrServiceFixture(10, 60, 0);
diff --git a/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorEmrSyncTest.java b/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorEmrSyncTest.java
index 6740aa7a04..e45c2569da 100644
--- a/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorEmrSyncTest.java
+++ b/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorEmrSyncTest.java
@@ -94,13 +94,13 @@ class AslExecutorEmrSyncTest {
assertEquals("FAILED", execution.getStatus());
assertEquals("States.Timeout", execution.getError());
- verify(emrService).cancelSteps(CLUSTER_ID, List.of(STEP_ID));
+ verify(emrService).cancelSteps(CLUSTER_ID, List.of(STEP_ID), null);
}
@Test
void addStepSyncStillTimesOutWhenEmrNoLongerHasTheCluster() {
when(emrService.describeStep(CLUSTER_ID, STEP_ID)).thenReturn(step("RUNNING"));
- when(emrService.cancelSteps(CLUSTER_ID, List.of(STEP_ID))).thenThrow(new AwsException(
+ when(emrService.cancelSteps(CLUSTER_ID, List.of(STEP_ID), null)).thenThrow(new AwsException(
"InvalidRequestException", "Cluster id 'j-SYNCTEST00001' is not valid.", 400));
Execution execution = run("""
@@ -110,13 +110,13 @@ class AslExecutorEmrSyncTest {
// Best effort: nothing left to cancel leaves the Task ending as it was.
assertEquals("States.Timeout", execution.getError());
- verify(emrService).cancelSteps(CLUSTER_ID, List.of(STEP_ID));
+ verify(emrService).cancelSteps(CLUSTER_ID, List.of(STEP_ID), null);
}
@Test
void addStepSyncStillTimesOutWhenEmrWillNotCancelTheStep() {
when(emrService.describeStep(CLUSTER_ID, STEP_ID)).thenReturn(step("RUNNING"));
- when(emrService.cancelSteps(CLUSTER_ID, List.of(STEP_ID))).thenReturn(List.of(
+ when(emrService.cancelSteps(CLUSTER_ID, List.of(STEP_ID), null)).thenReturn(List.of(
new EmrService.CancelStepInfo(STEP_ID, "FAILED", "Step is not in a cancellable state: RUNNING")));
Execution execution = run("""
@@ -126,13 +126,13 @@ class AslExecutorEmrSyncTest {
// A step EMR will not cancel comes back FAILED in an answer that succeeds, which the cleanup passes over.
assertEquals("States.Timeout", execution.getError());
- verify(emrService).cancelSteps(CLUSTER_ID, List.of(STEP_ID));
+ verify(emrService).cancelSteps(CLUSTER_ID, List.of(STEP_ID), null);
}
@Test
void anInternalErrorCancellingTheStepFailsTheTaskWithIt() {
when(emrService.describeStep(CLUSTER_ID, STEP_ID)).thenReturn(step("RUNNING"));
- when(emrService.cancelSteps(CLUSTER_ID, List.of(STEP_ID)))
+ when(emrService.cancelSteps(CLUSTER_ID, List.of(STEP_ID), null))
.thenThrow(new AwsException("InternalServerException", "Request processing failed", 500));
Execution execution = run("""
@@ -157,7 +157,7 @@ class AslExecutorEmrSyncTest {
JsonNode cause = objectMapper.readTree(execution.getCause());
assertEquals(STEP_ID, cause.path("Step").path("Id").asText());
assertEquals("FAILED", cause.path("Step").path("Status").path("State").asText());
- verify(emrService, never()).cancelSteps(any(), any());
+ verify(emrService, never()).cancelSteps(any(), any(), any());
}
@Test