mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(emr): honour CancelSteps' StepCancellationOption, SIGTERM by default (#9139)
CancelSteps took no StepCancellationOption: a cancelled RUNNING step's container was killed at once, which is TERMINATE_PROCESS. The Management Guide's "Cancel steps" makes 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 TERMINATE_PROCESS "EMR sends a SIGKILL signal to the step and all its descendant processes which terminates them immediately". With SEND_INTERRUPT the step's container now gets SIGTERM and the step stays CANCEL_PENDING until its command ends on its own, CANCELLED then, without its ActionOnFailure. A step's container runs under an init process, as Docker's --init runs one, so that the signal reaches its command: a container's first process ignores SIGTERM unless it handles it. A step whose container is not running yet has nothing to interrupt, and is stopped as before. TERMINATE_PROCESS kills it at once, as every cancel did, with SIGKILL alone, as Docker's own stop would send SIGTERM first and the init would pass it on; it also kills a step a SEND_INTERRUPT cancel left running, and a cluster's end kills such a step too. An option that is neither gets the framework's enum message. A CancelSteps request takes at most 100 steps from release 7.14.0, and 256 before it, as "With Amazon EMR releases 7.14.0 and later, the maximum number of steps you can cancel per request is 100".
This commit is contained in:
1 parent
82bc86f7f3
commit
8a0112d9c5
11 files changed
+344
-43
No files matched your search
@@ -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.
|
||||
|
||||
@@ -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<String> 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<Job> jobs = new ArrayList<>();
|
||||
final Set<String> stopped = new HashSet<>();
|
||||
// Runs sent SIGTERM: a driver that ignores it runs on.
|
||||
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<>();
|
||||
@@ -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.
|
||||
|
||||
@@ -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<String> 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<String> 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);
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user