mirror of
https://github.com/floci-io/floci.git
synced 2026-11-30 17:05:21 -05:00
feat(emr): run Spark steps in containers in a docker runner mode (#6578)
Classic EMR steps never ran: each one completed after step-duration-seconds, so a step could not fail, a failed step's ActionOnFailure never applied, and no cluster ever ended TERMINATED_WITH_ERRORS. A new floci.services.emr.runner-mode, immediate by default (today's timed lifecycle), runs each step in docker mode: - One container per step, from when the step goes RUNNING until its Spark driver exits, through the runner EMR Serverless's docker mode uses: spark-submit in local mode in the release's EMR Serverless image, with S3A and Glue pointed at Floci. The cluster gets no container. - command-runner.jar running spark-submit gets the arguments after it, without --master and --deploy-mode; a custom JAR runs its MainClass, or its manifest's, with the JAR and its Args. Other steps (Hive, Pig, script-runner.jar, other commands) fail without running. - The step is COMPLETED on exit code 0 and FAILED otherwise, with FailureDetails: Reason "Unknown Error", which the API reference says EMR gives when it cannot find the root cause, and Floci's message. - ActionOnFailure as the API reference and the Management Guide give it: TERMINATE_CLUSTER ends the cluster unless it waits after its steps and is protected; CANCEL_AND_WAIT cancels the pending steps and waits, or ends a cluster set to end after its steps; CONTINUE goes on; none applies above concurrency level 1, nor CANCEL_AND_WAIT with other steps running. A cluster a failure ends is TERMINATED_WITH_ERRORS with STEP_FAILURE and "Shut down as step failed". - Step FAILED (ERROR) and cluster TERMINATED_WITH_ERRORS (CRITICAL) events, with the messages of the guide's event tables. - CancelSteps and TerminateJobFlows stop a running step's driver. A driver Floci's shutdown or a reset stops leaves its step as it is, so no other step starts once the teardown has passed: a step Floci was running is FAILED once Floci is back, and a reset's threads write nothing after it. Leftover drivers are removed when the service starts, before any step can, unless reconcile-containers-on-startup is off. - The driver runs as the step's ExecutionRoleArn, or else the role of the cluster's JobFlowRole instance profile, and gets the spark-defaults of the cluster's Configurations. New settings: runner-mode, docker-network, image-template and reconcile-containers-on-startup, as EMR Serverless has. The shared runner now reads Progress.cancelled() at every look at a running driver, so a driver whose run a reset removed is stopped, and removeLeftoverDrivers is on SparkJobRunner. EMR Serverless's job run service counts a RUNNING run as not cancelled accordingly.
This commit is contained in:
1 parent
5c7c84374b
commit
4b33002784
18 files changed
+1236
-56
No files matched your search
@@ -1979,6 +1979,33 @@ public interface EmulatorConfig {
|
||||
/** How long a cluster stays TERMINATING before it is TERMINATED; 0 ends it at once. */
|
||||
@WithDefault("0")
|
||||
int clusterTerminationDelaySeconds();
|
||||
|
||||
/**
|
||||
* {@code immediate} completes each step by time without running anything; {@code docker} runs each
|
||||
* Spark step's {@code spark-submit} in a container of the release's EMR Serverless image.
|
||||
*/
|
||||
@WithDefault("immediate")
|
||||
String runnerMode();
|
||||
|
||||
Optional<String> dockerNetwork();
|
||||
|
||||
/**
|
||||
* The image a {@code docker} step uses, with {@code %s} standing for the cluster's release label,
|
||||
* for example "registry.internal/emr-serverless/spark/%s:20250425". If omitted, Floci uses the
|
||||
* release's public EMR Serverless image on Amazon ECR Public.
|
||||
*/
|
||||
Optional<String> imageTemplate();
|
||||
|
||||
/**
|
||||
* When true, Floci removes, in the {@code docker} runner mode, every EMR step driver a previous run
|
||||
* of <em>this same</em> Floci left on the daemon (matched by the {@code io.floci.owner} label) when
|
||||
* the EMR service starts. Turn it off when two Floci instances share a daemon with the same port
|
||||
* and no resource namespace, so one does not remove the other's drivers.
|
||||
*
|
||||
* Env var: FLOCI_SERVICES_EMR_RECONCILE_CONTAINERS_ON_STARTUP
|
||||
*/
|
||||
@WithDefault("true")
|
||||
boolean reconcileContainersOnStartup();
|
||||
}
|
||||
|
||||
interface WafV2ServiceConfig {
|
||||
|
||||
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.services.emr.model.EmrStep;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
@@ -16,11 +17,12 @@ import java.util.regex.Pattern;
|
||||
* A cluster's and its steps' lifecycle, as the Management Guide gives it in "Understanding the cluster
|
||||
* lifecycle" and "Running steps to process data". A cluster is STARTING, then BOOTSTRAPPING, then
|
||||
* RUNNING while it runs its steps, in the order they were added and at most its StepConcurrencyLevel
|
||||
* at a time, then WAITING, or TERMINATING and TERMINATED when it ends after them. Nothing runs: each
|
||||
* change falls due at a time worked out from three durations and the times already recorded, and
|
||||
* {@link #advance} makes every change due by a given time, in the order they fall due, queuing the
|
||||
* event of each state the guide's event tables report. With the durations at 0, every change falls
|
||||
* due at the time of the call that leads to it.
|
||||
* at a time, then WAITING, or TERMINATING and TERMINATED when it ends after them. Each change falls due
|
||||
* at a time worked out from three durations and the times already recorded, and {@link #advance} makes
|
||||
* every change due by a given time, in the order they fall due, queuing the event of each state the
|
||||
* guide's event tables report. With the durations at 0, every change falls due at the time of the call
|
||||
* that leads to it. Without a {@link StepExecution} nothing runs and a step completes by time; with one,
|
||||
* a step runs for real, and ends, COMPLETED or FAILED, when {@link #stepEnded} says so.
|
||||
*/
|
||||
final class EmrClusterLifecycle {
|
||||
|
||||
@@ -33,19 +35,44 @@ final class EmrClusterLifecycle {
|
||||
static final String PENDING = "PENDING";
|
||||
static final String COMPLETED = "COMPLETED";
|
||||
static final String CANCELLED = "CANCELLED";
|
||||
static final String FAILED = "FAILED";
|
||||
static final String TERMINATED_WITH_ERRORS = "TERMINATED_WITH_ERRORS";
|
||||
// FailureDetails.Reason: "In the case where the service cannot successfully determine the root cause of
|
||||
// the failure, it returns "Unknown Error" as a reason." Floci never determines it.
|
||||
private static final String UNKNOWN_ERROR = "Unknown Error";
|
||||
private static final String STEP_FAILURE = "STEP_FAILURE";
|
||||
// The reason a cluster a failed step ends gives: the console's for a Snowplow cluster on its forum, and
|
||||
// mrjob's mock EMR.
|
||||
private static final String SHUT_DOWN_AS_STEP_FAILED = "Shut down as step failed";
|
||||
private static final Pattern RELEASE_LABEL = Pattern.compile("emr-(\\d{1,6})\\.(\\d{1,6})(?:\\..*)?");
|
||||
|
||||
private final Duration startup;
|
||||
private final Duration stepRun;
|
||||
private final Duration termination;
|
||||
private final EmrEventPublisher events;
|
||||
// Null when steps complete by time.
|
||||
private final StepExecution execution;
|
||||
|
||||
/**
|
||||
* Runs the steps a cluster starts, in the {@code docker} runner mode. Each call only sets work going
|
||||
* and returns: a step's end comes back later through {@link #stepEnded}, never from inside the call.
|
||||
*/
|
||||
interface StepExecution {
|
||||
|
||||
/** {@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);
|
||||
}
|
||||
|
||||
EmrClusterLifecycle(int startupDelaySeconds, int stepDurationSeconds, int terminationDelaySeconds,
|
||||
EmrEventPublisher events) {
|
||||
EmrEventPublisher events, StepExecution execution) {
|
||||
this.startup = seconds("cluster-startup-delay-seconds", startupDelaySeconds);
|
||||
this.stepRun = seconds("step-duration-seconds", stepDurationSeconds);
|
||||
this.termination = seconds("cluster-termination-delay-seconds", terminationDelaySeconds);
|
||||
this.events = events;
|
||||
this.execution = execution;
|
||||
}
|
||||
|
||||
private static Duration seconds(String setting, int value) {
|
||||
@@ -144,7 +171,7 @@ final class EmrClusterLifecycle {
|
||||
case STARTING -> cluster.getCreationDateTime().plus(startup.dividedBy(2));
|
||||
case BOOTSTRAPPING -> cluster.getCreationDateTime().plus(startup);
|
||||
case RUNNING -> cluster.getSteps().stream()
|
||||
.filter(step -> RUNNING.equals(step.getState()))
|
||||
.filter(step -> RUNNING.equals(step.getState()) && timed(step))
|
||||
.map(step -> step.getStartDateTime().plus(stepRun))
|
||||
.min(Comparator.naturalOrder())
|
||||
.orElse(null);
|
||||
@@ -163,7 +190,8 @@ final class EmrClusterLifecycle {
|
||||
}
|
||||
case RUNNING -> {
|
||||
for (EmrStep step : cluster.getSteps()) {
|
||||
if (RUNNING.equals(step.getState()) && !step.getStartDateTime().plus(stepRun).isAfter(at)) {
|
||||
if (RUNNING.equals(step.getState()) && timed(step)
|
||||
&& !step.getStartDateTime().plus(stepRun).isAfter(at)) {
|
||||
step.setState(COMPLETED);
|
||||
step.setEndDateTime(at);
|
||||
events.queue(events.stepStatusChange(cluster, step, COMPLETED), region);
|
||||
@@ -172,10 +200,14 @@ final class EmrClusterLifecycle {
|
||||
runSteps(cluster, at, region);
|
||||
}
|
||||
case TERMINATING -> {
|
||||
cluster.setState(TERMINATED);
|
||||
// "If a cluster terminates because of a failure, ... the cluster state is set to
|
||||
// TERMINATED_WITH_ERRORS."
|
||||
String ended = STEP_FAILURE.equals(cluster.getStateChangeReasonCode())
|
||||
? TERMINATED_WITH_ERRORS : TERMINATED;
|
||||
cluster.setState(ended);
|
||||
cluster.setEndDateTime(at);
|
||||
releaseInstanceCapacity(cluster);
|
||||
events.queue(events.clusterStateChange(cluster, TERMINATED, at), region);
|
||||
events.queue(events.clusterStateChange(cluster, ended, at), region);
|
||||
}
|
||||
default -> throw new IllegalStateException("Nothing falls due for a " + cluster.getState() + " cluster");
|
||||
}
|
||||
@@ -190,6 +222,7 @@ final class EmrClusterLifecycle {
|
||||
long running = cluster.getSteps().stream().filter(step -> RUNNING.equals(step.getState())).count();
|
||||
// The model allows 1 to 256; Floci stores any level it is given, and a lower one would never start a step.
|
||||
int level = Math.max(1, cluster.getStepConcurrencyLevel());
|
||||
List<EmrStep> started = new ArrayList<>();
|
||||
for (EmrStep step : cluster.getSteps()) {
|
||||
if (running >= level) {
|
||||
break;
|
||||
@@ -197,7 +230,9 @@ final class EmrClusterLifecycle {
|
||||
if (PENDING.equals(step.getState())) {
|
||||
step.setState(RUNNING);
|
||||
step.setStartDateTime(at);
|
||||
step.setRunInContainer(execution != null);
|
||||
events.queue(events.stepStatusChange(cluster, step, RUNNING), region);
|
||||
started.add(step);
|
||||
running++;
|
||||
}
|
||||
}
|
||||
@@ -209,6 +244,63 @@ final class EmrClusterLifecycle {
|
||||
} else {
|
||||
finish(cluster, at, region);
|
||||
}
|
||||
if (execution != null) {
|
||||
started.forEach(step -> execution.start(cluster, step, region));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A step run for real has ended: COMPLETED when {@code failure} is null, otherwise FAILED, with
|
||||
* {@code failure} as its FailureDetails message, and its ActionOnFailure taken. Either way the
|
||||
* cluster goes on as it would once a step is done.
|
||||
*/
|
||||
void stepEnded(EmrCluster cluster, EmrStep step, String failure, Instant at, String region) {
|
||||
step.setEndDateTime(at);
|
||||
if (failure == null) {
|
||||
step.setState(COMPLETED);
|
||||
events.queue(events.stepStatusChange(cluster, step, COMPLETED), region);
|
||||
runSteps(cluster, at, region);
|
||||
return;
|
||||
}
|
||||
step.setState(FAILED);
|
||||
step.setFailureReason(UNKNOWN_ERROR);
|
||||
step.setFailureMessage(failure);
|
||||
events.queue(events.stepStatusChange(cluster, step, FAILED), region);
|
||||
actOnFailure(cluster, step, at, region);
|
||||
}
|
||||
|
||||
/**
|
||||
* A failed step's ActionOnFailure, as the API reference's Step and the Management Guide give it.
|
||||
* TERMINATE_CLUSTER (TERMINATE_JOB_FLOW before it) ends the cluster, unless it is set to wait after
|
||||
* its steps and protected from termination: then it "continues". CANCEL_AND_WAIT "Cancels any pending
|
||||
* steps and returns the cluster to the WAITING state", and on a cluster set to end after its steps
|
||||
* "the cluster terminates without executing subsequent steps". CONTINUE "Continues to the next step in
|
||||
* the queue". "If the step concurrency level of a cluster is greater than one, step ActionOnFailure
|
||||
* feature will not activate", and with level 1 but other steps still running (the level was lowered
|
||||
* while they ran) "TERMINATE_CLUSTER ActionOnFailure may activate, but CANCEL_AND_WAIT ActionOnFailure
|
||||
* will not".
|
||||
*/
|
||||
private void actOnFailure(EmrCluster cluster, EmrStep step, Instant at, String region) {
|
||||
String action = step.getActionOnFailure();
|
||||
boolean activates = cluster.getStepConcurrencyLevel() <= 1;
|
||||
boolean terminates = "TERMINATE_CLUSTER".equals(action) || "TERMINATE_JOB_FLOW".equals(action);
|
||||
if (activates && terminates && (cluster.isAutoTerminate() || !cluster.isTerminationProtected())) {
|
||||
terminate(cluster, STEP_FAILURE, SHUT_DOWN_AS_STEP_FAILED, at, region);
|
||||
return;
|
||||
}
|
||||
boolean othersRunning = cluster.getSteps().stream().anyMatch(other -> RUNNING.equals(other.getState()));
|
||||
if (activates && "CANCEL_AND_WAIT".equals(action) && !othersRunning) {
|
||||
if (cluster.isAutoTerminate()) {
|
||||
terminate(cluster, STEP_FAILURE, SHUT_DOWN_AS_STEP_FAILED, at, region);
|
||||
return;
|
||||
}
|
||||
for (EmrStep pending : cluster.getSteps()) {
|
||||
if (PENDING.equals(pending.getState())) {
|
||||
cancelStep(cluster, pending, at, region);
|
||||
}
|
||||
}
|
||||
}
|
||||
runSteps(cluster, at, region);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -227,9 +319,26 @@ final class EmrClusterLifecycle {
|
||||
}
|
||||
|
||||
private void cancelStep(EmrCluster cluster, EmrStep step, Instant at, String region) {
|
||||
boolean running = RUNNING.equals(step.getState());
|
||||
step.setState(CANCELLED);
|
||||
step.setEndDateTime(at);
|
||||
events.queue(events.stepStatusChange(cluster, step, CANCELLED), region);
|
||||
if (running && !timed(step)) {
|
||||
execution.stop(step);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a RUNNING step completes by time: every step without a {@link StepExecution}, including one
|
||||
* a {@code docker} runner mode started before a restart into the {@code immediate} one.
|
||||
*/
|
||||
private boolean timed(EmrStep step) {
|
||||
return execution == null || !step.isRunInContainer();
|
||||
}
|
||||
|
||||
/** TERMINATED, or TERMINATED_WITH_ERRORS: the cluster has ended. */
|
||||
static boolean isTerminated(String state) {
|
||||
return TERMINATED.equals(state) || TERMINATED_WITH_ERRORS.equals(state);
|
||||
}
|
||||
|
||||
private static void releaseInstanceCapacity(EmrCluster cluster) {
|
||||
|
||||
@@ -59,12 +59,15 @@ public class EmrEventPublisher {
|
||||
this.regionResolver = regionResolver;
|
||||
}
|
||||
|
||||
/** {@code cluster} entering {@code state} at {@code at}: STARTING, WAITING or TERMINATED. */
|
||||
/**
|
||||
* {@code cluster} entering {@code state} at {@code at}: STARTING, WAITING, TERMINATED or
|
||||
* TERMINATED_WITH_ERRORS.
|
||||
*/
|
||||
Event clusterStateChange(EmrCluster cluster, String state, Instant at) {
|
||||
boolean terminated = "TERMINATED".equals(state);
|
||||
boolean terminated = EmrClusterLifecycle.isTerminated(state);
|
||||
String code = cluster.getStateChangeReasonCode();
|
||||
// The examples' reason is a JSON string: {"code":""} for a WAITING cluster, and the reason's code
|
||||
// and message for a TERMINATED one.
|
||||
// and message for a terminated one.
|
||||
ObjectNode reason = objectMapper.createObjectNode().put("code", terminated && code != null ? code : "");
|
||||
if (terminated && cluster.getStateChangeMessage() != null) {
|
||||
reason.put("message", cluster.getStateChangeMessage());
|
||||
@@ -80,10 +83,17 @@ public class EmrEventPublisher {
|
||||
return new Event(CLUSTER_STATE_CHANGE, detail.toString());
|
||||
}
|
||||
|
||||
/** {@code step} of {@code cluster} entering {@code state}: PENDING, RUNNING, COMPLETED or CANCELLED. */
|
||||
/**
|
||||
* {@code step} of {@code cluster} entering {@code state}: PENDING, RUNNING, COMPLETED, CANCELLED or
|
||||
* FAILED.
|
||||
*/
|
||||
Event stepStatusChange(EmrCluster cluster, EmrStep step, String state) {
|
||||
ObjectNode detail = objectMapper.createObjectNode();
|
||||
detail.put("severity", "CANCELLED".equals(state) ? "WARN" : "INFO");
|
||||
detail.put("severity", switch (state) {
|
||||
case "CANCELLED" -> "WARN";
|
||||
case "FAILED" -> "ERROR";
|
||||
default -> "INFO";
|
||||
});
|
||||
detail.put("actionOnFailure", step.getActionOnFailure());
|
||||
detail.put("stepId", step.getId());
|
||||
detail.put("name", step.getName());
|
||||
@@ -136,6 +146,8 @@ public class EmrEventPublisher {
|
||||
: "Amazon EMR cluster " + named + " finished running all pending steps at " + time(at) + ".";
|
||||
case "TERMINATED" -> "Amazon EMR Cluster " + named + " has terminated at " + time(at)
|
||||
+ " with a reason of " + cluster.getStateChangeReasonCode() + ".";
|
||||
case "TERMINATED_WITH_ERRORS" -> "Amazon EMR Cluster " + named + " has terminated with errors at "
|
||||
+ time(at) + " with a reason of " + cluster.getStateChangeReasonCode() + ".";
|
||||
default -> throw new IllegalArgumentException("No cluster event for state " + state);
|
||||
};
|
||||
}
|
||||
@@ -156,6 +168,8 @@ public class EmrEventPublisher {
|
||||
case "CANCELLED" -> "Cancellation request has succeeded for cluster step " + stepNamed
|
||||
+ " in Amazon EMR cluster " + clusterNamed + " at " + time(step.getEndDateTime())
|
||||
+ ", and the step is now cancelled.";
|
||||
case "FAILED" -> "Step " + stepNamed + " in Amazon EMR cluster " + clusterNamed + " failed at "
|
||||
+ time(step.getEndDateTime()) + ".";
|
||||
default -> throw new IllegalArgumentException("No step event for state " + state);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -317,7 +317,7 @@ public class EmrHandler {
|
||||
EmrCluster cluster = service.getClusterForInstances(text(request, "ClusterId"));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode arr = response.putArray("Instances");
|
||||
boolean terminated = "TERMINATED".equals(cluster.getState());
|
||||
boolean terminated = EmrClusterLifecycle.isTerminated(cluster.getState());
|
||||
List<String> states = stringList(request.path("InstanceStates"));
|
||||
if ((!states.isEmpty() && !states.contains(terminated ? "TERMINATED" : "RUNNING"))
|
||||
|| (terminated && !withinTerminatedInstanceRetention(cluster.getEndDateTime(), Instant.now()))) {
|
||||
@@ -666,6 +666,12 @@ public class EmrHandler {
|
||||
if (step.getStateChangeReason() != null) {
|
||||
status.putObject("StateChangeReason").put("Message", step.getStateChangeReason());
|
||||
}
|
||||
if (step.getFailureReason() != null) {
|
||||
ObjectNode failure = status.putObject("FailureDetails").put("Reason", step.getFailureReason());
|
||||
if (step.getFailureMessage() != null) {
|
||||
failure.put("Message", step.getFailureMessage());
|
||||
}
|
||||
}
|
||||
ObjectNode timeline = status.putObject("Timeline");
|
||||
putEpoch(timeline, "CreationDateTime", step.getCreationDateTime());
|
||||
putEpoch(timeline, "StartDateTime", step.getStartDateTime());
|
||||
|
||||
@@ -11,6 +11,7 @@ import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
import io.github.hectorvent.floci.core.common.Pagination;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
@@ -21,6 +22,10 @@ import io.github.hectorvent.floci.services.emr.model.EmrInstanceFleet;
|
||||
import io.github.hectorvent.floci.services.emr.model.EmrInstanceGroup;
|
||||
import io.github.hectorvent.floci.services.emr.model.EmrStep;
|
||||
import io.github.hectorvent.floci.services.emr.model.SecurityConfiguration;
|
||||
import io.github.hectorvent.floci.services.emrserverless.EmrServerlessSparkRunner;
|
||||
import io.github.hectorvent.floci.services.emrserverless.SparkJobRunner;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamRole;
|
||||
import io.quarkus.runtime.StartupEvent;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
@@ -35,6 +40,7 @@ import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -42,6 +48,7 @@ import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
@@ -50,16 +57,21 @@ import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* EMR management-plane business logic. Nothing runs: clusters and steps go through the states of
|
||||
* EMR management-plane business logic. Clusters and steps go through the states of
|
||||
* {@link EmrClusterLifecycle}, timed by {@code cluster-startup-delay-seconds},
|
||||
* {@code step-duration-seconds} and {@code cluster-termination-delay-seconds}, all 0 by default, which
|
||||
* makes a cluster ready, and a step complete, before the call that started it returns. A call brings
|
||||
* each cluster it reads up to the time it is made, and the service wakes at each cluster's next
|
||||
* change, so the change's event goes out without anyone asking. Events are published once the call
|
||||
* that made the change no longer holds the service.
|
||||
*
|
||||
* <p>In the default {@code immediate} runner mode nothing runs. In the {@code docker} one each step
|
||||
* runs, in a container of its own, from when it goes RUNNING until its Spark driver exits, on a thread
|
||||
* of its own that ends the step under the service's lock: COMPLETED on exit code 0, FAILED otherwise,
|
||||
* with its ActionOnFailure taken.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class EmrService {
|
||||
public class EmrService implements Resettable {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(EmrService.class);
|
||||
private static final String UPPER_ALNUM = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||
@@ -69,6 +81,9 @@ public class EmrService {
|
||||
private static final String JOB_FLOW_SHUT_DOWN =
|
||||
"A job flow that is shutting down, terminated, or finished may not be modified.";
|
||||
private static final ObjectMapper SNAPSHOT_MAPPER = new ObjectMapper().registerModule(new JavaTimeModule());
|
||||
private static final String RUNNER_DOCKER = "docker";
|
||||
// The service a step's driver belongs to, which names it and labels it.
|
||||
private static final String SERVICE = "emr";
|
||||
|
||||
private final AccountAwareStorageBackend<EmrCluster> clusterStore;
|
||||
private final StorageBackend<String, SecurityConfiguration> secConfigStore;
|
||||
@@ -81,6 +96,18 @@ public class EmrService {
|
||||
private final Wakeups wakeups;
|
||||
// Each cluster's next wakeup, by account and id, so a call that reads a cluster does not add another.
|
||||
private final Map<String, Instant> wakeupsDue = new ConcurrentHashMap<>();
|
||||
// The docker runner mode's; null in the immediate one.
|
||||
private final SparkJobRunner sparkRunner;
|
||||
private final Executor stepExecutor;
|
||||
private final IamService iamService;
|
||||
// Where a step's driver runs: image-template, with the release label for %s, and docker-network; null when
|
||||
// not set.
|
||||
private final String imageTemplate;
|
||||
private final String dockerNetwork;
|
||||
// The steps a thread is running, by account and id; a RUNNING container step not here was left by a restart.
|
||||
private final Set<String> executing = new HashSet<>();
|
||||
// Raised by each reset, so a step's thread from before it writes nothing back after the wipe.
|
||||
private long generation;
|
||||
|
||||
private static final Set<String> COMPUTE_LIMITS_UNIT_TYPES = Set.of("InstanceFleetUnits", "Instances", "VCPU");
|
||||
private static final Set<String> SCALING_STRATEGIES = Set.of("DEFAULT", "ADVANCED");
|
||||
@@ -142,13 +169,22 @@ public class EmrService {
|
||||
|
||||
@Inject
|
||||
public EmrService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver,
|
||||
EmrEventPublisher eventPublisher) {
|
||||
EmrEventPublisher eventPublisher, EmrServerlessSparkRunner sparkRunner, IamService iamService) {
|
||||
this(storageFactory, config, regionResolver, eventPublisher, Clock.systemUTC(),
|
||||
Wakeups.timer(Clock.systemUTC()));
|
||||
Wakeups.timer(Clock.systemUTC()),
|
||||
RUNNER_DOCKER.equalsIgnoreCase(config.services().emr().runnerMode()) ? sparkRunner : null,
|
||||
Executors.newCachedThreadPool(Thread.ofPlatform().daemon().name("emr-step-", 0).factory()),
|
||||
iamService);
|
||||
}
|
||||
|
||||
EmrService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver,
|
||||
EmrEventPublisher eventPublisher, Clock clock, Wakeups wakeups) {
|
||||
this(storageFactory, config, regionResolver, eventPublisher, clock, wakeups, null, Runnable::run, null);
|
||||
}
|
||||
|
||||
EmrService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver,
|
||||
EmrEventPublisher eventPublisher, Clock clock, Wakeups wakeups, SparkJobRunner sparkRunner,
|
||||
Executor stepExecutor, IamService iamService) {
|
||||
this.clusterStore = storageFactory.create("emr", "emr-clusters.json",
|
||||
new TypeReference<Map<String, EmrCluster>>() {});
|
||||
this.secConfigStore = storageFactory.create("emr", "emr-security-configs.json",
|
||||
@@ -158,15 +194,29 @@ public class EmrService {
|
||||
this.regionResolver = regionResolver;
|
||||
this.eventPublisher = eventPublisher;
|
||||
this.defaultReleaseLabel = config.services().emr().defaultReleaseLabel();
|
||||
this.sparkRunner = sparkRunner;
|
||||
this.stepExecutor = stepExecutor;
|
||||
this.iamService = iamService;
|
||||
this.imageTemplate = config.services().emr().imageTemplate().orElse(null);
|
||||
this.dockerNetwork = config.services().emr().dockerNetwork().orElse(null);
|
||||
this.lifecycle = new EmrClusterLifecycle(config.services().emr().clusterStartupDelaySeconds(),
|
||||
config.services().emr().stepDurationSeconds(),
|
||||
config.services().emr().clusterTerminationDelaySeconds(), eventPublisher);
|
||||
config.services().emr().clusterTerminationDelaySeconds(), eventPublisher,
|
||||
sparkRunner != null ? new ContainerSteps() : null);
|
||||
this.clock = clock;
|
||||
this.wakeups = wakeups;
|
||||
// After a restart, a stored cluster with a change still to come wakes the service as before.
|
||||
// Before any step of this process can start, the next step a restarted cluster's wakeup below starts
|
||||
// included: a driver an earlier process left belongs to a step read as FAILED, and the sweep removes
|
||||
// every driver of this deployment it finds.
|
||||
if (sparkRunner != null && config.services().emr().reconcileContainersOnStartup()) {
|
||||
sparkRunner.removeLeftoverDrivers(SERVICE);
|
||||
}
|
||||
// After a restart, a stored cluster with a change still to come wakes the service as before, and one
|
||||
// with a step a container ran, which no thread runs any more, wakes it at once to fail that step.
|
||||
for (AccountAwareStorageBackend.AccountEntry<EmrCluster> entry
|
||||
: clusterStore.scanAllAccountEntries(k -> true)) {
|
||||
Instant due = lifecycle.nextChange(entry.value());
|
||||
Instant due = sparkRunner != null && hasContainerStepRunning(entry.value())
|
||||
? clock.instant() : lifecycle.nextChange(entry.value());
|
||||
if (due != null) {
|
||||
wakeAt(entry.accountId(), entry.value(), due);
|
||||
}
|
||||
@@ -182,6 +232,24 @@ public class EmrService {
|
||||
@PreDestroy
|
||||
void shutdown() {
|
||||
wakeups.close();
|
||||
if (stepExecutor instanceof ExecutorService executor) {
|
||||
executor.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A reset has begun: the steps' threads from before it write nothing more, so the storage wipe that
|
||||
* follows leaves none of their clusters behind. Its teardown has already stopped their drivers.
|
||||
*/
|
||||
@Override
|
||||
public synchronized void beforeReset() {
|
||||
generation++;
|
||||
executing.clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
// The clusters live in storage, which the reset has already wiped.
|
||||
}
|
||||
|
||||
// ──────────────────────────── Cluster lifecycle ────────────────────────────
|
||||
@@ -933,7 +1001,7 @@ public class EmrService {
|
||||
if (EmrClusterLifecycle.TERMINATING.equals(cluster.getState())) {
|
||||
throw shuttingDown.get();
|
||||
}
|
||||
if (EmrClusterLifecycle.TERMINATED.equals(cluster.getState())) {
|
||||
if (EmrClusterLifecycle.isTerminated(cluster.getState())) {
|
||||
throw invalid("Cluster " + cluster.getId() + " is terminated.");
|
||||
}
|
||||
}
|
||||
@@ -978,7 +1046,7 @@ public class EmrService {
|
||||
/** Shutting down or ended: "A job flow that is shutting down, terminated, or finished may not be modified." */
|
||||
private static boolean isShutDown(EmrCluster cluster) {
|
||||
return EmrClusterLifecycle.TERMINATING.equals(cluster.getState())
|
||||
|| EmrClusterLifecycle.TERMINATED.equals(cluster.getState());
|
||||
|| EmrClusterLifecycle.isTerminated(cluster.getState());
|
||||
}
|
||||
|
||||
/** The only states in which a cluster's instance groups and fleets may be modified. */
|
||||
@@ -1017,15 +1085,194 @@ public class EmrService {
|
||||
return SNAPSHOT_MAPPER.convertValue(cluster, EmrCluster.class);
|
||||
}
|
||||
|
||||
/** The cluster as it stands now: every change due by now made, stored if there was one. */
|
||||
/**
|
||||
* The cluster as it stands now: every change due by now made, stored if there was one. A step a
|
||||
* container ran that no thread runs any more, since Floci stopped while it ran, is FAILED.
|
||||
*/
|
||||
private EmrCluster settle(EmrCluster cluster) {
|
||||
if (lifecycle.advance(cluster, now(), regionOf(cluster))) {
|
||||
boolean interrupted = failInterruptedSteps(cluster);
|
||||
if (lifecycle.advance(cluster, now(), regionOf(cluster)) || interrupted) {
|
||||
clusterStore.put(cluster.getId(), cluster);
|
||||
}
|
||||
wakeForNextChange(cluster);
|
||||
return cluster;
|
||||
}
|
||||
|
||||
private boolean failInterruptedSteps(EmrCluster cluster) {
|
||||
if (sparkRunner == null) {
|
||||
return false;
|
||||
}
|
||||
boolean failed = false;
|
||||
for (EmrStep step : List.copyOf(cluster.getSteps())) {
|
||||
if (runsInContainer(step) && !executing.contains(stepKey(regionResolver.getAccountId(), step.getId()))) {
|
||||
lifecycle.stepEnded(cluster, step, EmrSparkSteps.INTERRUPTED, now(), regionOf(cluster));
|
||||
failed = true;
|
||||
}
|
||||
}
|
||||
return failed;
|
||||
}
|
||||
|
||||
private static boolean hasContainerStepRunning(EmrCluster cluster) {
|
||||
return cluster.getSteps().stream().anyMatch(EmrService::runsInContainer);
|
||||
}
|
||||
|
||||
private static boolean runsInContainer(EmrStep step) {
|
||||
return EmrClusterLifecycle.RUNNING.equals(step.getState()) && step.isRunInContainer();
|
||||
}
|
||||
|
||||
private static String stepKey(String accountId, String stepId) {
|
||||
return accountId + "/" + stepId;
|
||||
}
|
||||
|
||||
/**
|
||||
* The role a step's driver runs as: the step's runtime role, or else the role of the cluster's EC2
|
||||
* instance profile, its {@code JobFlowRole}, given by name or ARN; null when IAM knows neither, and the
|
||||
* driver then has the account's placeholder credentials. The guide's "Runtime roles for Amazon EMR
|
||||
* steps": without them, clusters "ran Amazon EMR jobs or queries with permissions based on the IAM
|
||||
* policy attached to the instance profile that you used to launch the cluster".
|
||||
*/
|
||||
private String executionRole(EmrCluster cluster, EmrStep step, String accountId) {
|
||||
if (step.getExecutionRoleArn() != null) {
|
||||
return step.getExecutionRoleArn();
|
||||
}
|
||||
String profile = cluster.getJobFlowRole();
|
||||
if (profile == null || iamService == null) {
|
||||
return null;
|
||||
}
|
||||
return iamService.findInstanceProfile(accountId, profile.substring(profile.lastIndexOf('/') + 1))
|
||||
.filter(found -> found.getRoleNames() != null && found.getRoleNames().size() == 1)
|
||||
.flatMap(found -> iamService.findRole(accountId, found.getRoleNames().getFirst()))
|
||||
.map(IamRole::getArn)
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ends a step its thread ran, COMPLETED when {@code failure} is null and FAILED otherwise, unless a
|
||||
* reset came since it started or the step is no longer RUNNING: cancelled, or on a cluster that ended.
|
||||
*/
|
||||
private void stepEnded(StepLaunch launch, String failure) {
|
||||
if (launch.launchedIn() != generation) {
|
||||
return;
|
||||
}
|
||||
// Read while the step still counts as running, so it is not taken for one a restart left.
|
||||
Optional<EmrCluster> found = findCluster(launch.clusterId());
|
||||
executing.remove(stepKey(launch.accountId(), launch.stepId()));
|
||||
EmrStep step = found.flatMap(cluster -> cluster.getSteps().stream()
|
||||
.filter(candidate -> launch.stepId().equals(candidate.getId())).findFirst()).orElse(null);
|
||||
if (step == null || !EmrClusterLifecycle.RUNNING.equals(step.getState())) {
|
||||
return;
|
||||
}
|
||||
EmrCluster cluster = found.get();
|
||||
lifecycle.stepEnded(cluster, step, failure, now(), regionOf(cluster));
|
||||
store(cluster);
|
||||
LOG.infov("EMR step {0} of cluster {1} ended {2}", step.getId(), cluster.getId(), step.getState());
|
||||
}
|
||||
|
||||
/**
|
||||
* A step's driver was stopped. A cancel, or its cluster's end, has ended the step already. One still
|
||||
* RUNNING was stopped by Floci itself, by a reset's teardown or its shutdown, and is left as it is, still
|
||||
* counted as running: the reset wipes it, a restart fails it, and its ActionOnFailure, which could start
|
||||
* the next step after the teardown has passed, is not taken now.
|
||||
*/
|
||||
private void driverStopped(StepLaunch launch) {
|
||||
if (!stillRunning(launch)) {
|
||||
executing.remove(stepKey(launch.accountId(), launch.stepId()));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Why a step whose driver ended this way, by itself or before it could start, failed, or null when it
|
||||
* did not. No source gives AWS's wording for these; they are Floci's.
|
||||
*/
|
||||
private static String failureOf(SparkJobRunner.Outcome outcome) {
|
||||
if (outcome.exitCode() != null) {
|
||||
return outcome.exitCode() == 0 ? null : "The Spark driver exited with code " + outcome.exitCode() + ".";
|
||||
}
|
||||
return "The step could not start: " + outcome.failure();
|
||||
}
|
||||
|
||||
// Whether a step's driver may still start, or go on: one cancelled, on a cluster that ended, or a reset
|
||||
// removed, is past it.
|
||||
private synchronized boolean stillRunning(StepLaunch launch) {
|
||||
return launch.launchedIn() == generation && clusterStore.get(launch.clusterId()).stream()
|
||||
.flatMap(cluster -> cluster.getSteps().stream())
|
||||
.anyMatch(step -> launch.stepId().equals(step.getId())
|
||||
&& EmrClusterLifecycle.RUNNING.equals(step.getState()));
|
||||
}
|
||||
|
||||
/** A step handed to a thread: whose it is, where, and under which reset. */
|
||||
private record StepLaunch(String accountId, String region, String clusterId, String stepId, long launchedIn) {}
|
||||
|
||||
/** Starts each step a cluster runs on a thread of its own, which ends the step once it is done. */
|
||||
private final class ContainerSteps implements EmrClusterLifecycle.StepExecution {
|
||||
|
||||
@Override
|
||||
public void start(EmrCluster cluster, EmrStep step, String region) {
|
||||
String accountId = regionResolver.getAccountId();
|
||||
List<String> application = EmrSparkSteps.application(step);
|
||||
SparkJobRunner.Job job = application == null ? null : new SparkJobRunner.Job(SERVICE, step.getId(),
|
||||
accountId, region, cluster.getReleaseLabel(), imageTemplate, dockerNetwork,
|
||||
executionRole(cluster, step, accountId),
|
||||
EmrSparkSteps.sparkDefaults(cluster.getConfigurations(), SNAPSHOT_MAPPER), application,
|
||||
Duration.ZERO);
|
||||
StepLaunch launch = new StepLaunch(accountId, region, cluster.getId(), step.getId(), generation);
|
||||
executing.add(stepKey(accountId, step.getId()));
|
||||
stepExecutor.execute(() -> runStep(job, launch));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop(EmrStep step) {
|
||||
sparkRunner.stop(step.getId());
|
||||
}
|
||||
}
|
||||
|
||||
// A step's thread: its driver runs to its end, or the step fails at once when Floci does not run its kind.
|
||||
private void runStep(SparkJobRunner.Job job, StepLaunch launch) {
|
||||
String failure;
|
||||
if (job == null) {
|
||||
failure = EmrSparkSteps.NOT_RUN;
|
||||
} else {
|
||||
SparkJobRunner.Outcome outcome;
|
||||
try {
|
||||
outcome = sparkRunner.run(job, new StepProgress(launch));
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "EMR step {0} could not run", launch.stepId());
|
||||
outcome = SparkJobRunner.Outcome.couldNotStart(e.getMessage());
|
||||
}
|
||||
if (outcome.stopped()) {
|
||||
RequestScopes.runAs(launch.accountId(), launch.region(), () -> run(() -> driverStopped(launch)));
|
||||
return;
|
||||
}
|
||||
failure = failureOf(outcome);
|
||||
}
|
||||
RequestScopes.runAs(launch.accountId(), launch.region(), () -> run(() -> stepEnded(launch, failure)));
|
||||
}
|
||||
|
||||
/** What a step's thread asks the service while its driver goes: a step has no timeout to report. */
|
||||
private final class StepProgress implements SparkJobRunner.Progress {
|
||||
|
||||
private final StepLaunch launch;
|
||||
|
||||
StepProgress(StepLaunch launch) {
|
||||
this.launch = launch;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void started() {
|
||||
// The step has been RUNNING since it started; the driver's start changes nothing a caller sees.
|
||||
}
|
||||
|
||||
@Override
|
||||
public void timedOut() {
|
||||
// A step runs until its driver ends.
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean cancelled() {
|
||||
return !RequestScopes.callAs(launch.accountId(), launch.region(), () -> stillRunning(launch));
|
||||
}
|
||||
}
|
||||
|
||||
/** Stores a cluster a call changed, once every change that falls due by now is made. */
|
||||
private void store(EmrCluster cluster) {
|
||||
lifecycle.advance(cluster, now(), regionOf(cluster));
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
package io.github.hectorvent.floci.services.emr;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.services.emr.model.EmrStep;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* What a step runs in the {@code docker} runner mode, which runs Spark steps only, each through
|
||||
* {@code spark-submit} in local mode: a {@code command-runner.jar} step running {@code spark-submit}, as
|
||||
* the Management Guide's Spark steps are written, and a custom JAR step, whose main class
|
||||
* {@code spark-submit} runs with the JAR on its class path.
|
||||
*/
|
||||
final class EmrSparkSteps {
|
||||
|
||||
// No source gives AWS's wording for these; they are Floci's.
|
||||
static final String NOT_RUN = "Floci runs Spark steps only: spark-submit through command-runner.jar, or a"
|
||||
+ " custom JAR.";
|
||||
static final String INTERRUPTED = "Floci stopped while the step was running.";
|
||||
|
||||
private static final String COMMAND_RUNNER = "command-runner.jar";
|
||||
private static final String SCRIPT_RUNNER = "script-runner.jar";
|
||||
private static final String SPARK_SUBMIT = "spark-submit";
|
||||
// Local mode is Floci's, so a step's own master and deploy mode are dropped.
|
||||
private static final Set<String> DROPPED_OPTIONS = Set.of("--master", "--deploy-mode");
|
||||
// spark-submit's options that take no value (SparkSubmitOptionParser's switches); every other takes one.
|
||||
private static final Set<String> SWITCHES = Set.of("--help", "-h", "--supervise", "--usage-error", "--verbose",
|
||||
"-v", "--version");
|
||||
private static final String SPARK_DEFAULTS = "spark-defaults";
|
||||
|
||||
private EmrSparkSteps() {
|
||||
}
|
||||
|
||||
/**
|
||||
* What follows Floci's own settings on {@code spark-submit}'s command line for {@code step}, or null for
|
||||
* a step Floci does not run. For {@code command-runner.jar spark-submit ...}, the arguments after
|
||||
* {@code spark-submit}, without its {@code --master} and {@code --deploy-mode}: options come before the
|
||||
* application, so one after it is the application's own and kept. For a custom JAR, its main class, if
|
||||
* the step names one (otherwise {@code spark-submit} reads the JAR's manifest), the JAR and the step's
|
||||
* arguments.
|
||||
*/
|
||||
static List<String> application(EmrStep step) {
|
||||
String jar = step.getJar();
|
||||
if (jar == null || jar.isBlank() || named(jar, SCRIPT_RUNNER)) {
|
||||
return null;
|
||||
}
|
||||
List<String> args = step.getArgs() != null ? step.getArgs() : List.of();
|
||||
if (named(jar, COMMAND_RUNNER)) {
|
||||
return !args.isEmpty() && named(args.getFirst(), SPARK_SUBMIT)
|
||||
? withoutMasterOrDeployMode(args.subList(1, args.size())) : null;
|
||||
}
|
||||
List<String> application = new ArrayList<>();
|
||||
if (step.getMainClass() != null && !step.getMainClass().isBlank()) {
|
||||
application.add("--class");
|
||||
application.add(step.getMainClass());
|
||||
}
|
||||
application.add(jar);
|
||||
application.addAll(args);
|
||||
return application;
|
||||
}
|
||||
|
||||
/**
|
||||
* The {@code spark-defaults} properties of a cluster's {@code Configurations}, the JSON array
|
||||
* {@code RunJobFlow} was given, or none.
|
||||
*/
|
||||
static Map<String, String> sparkDefaults(String configurations, ObjectMapper objectMapper) {
|
||||
Map<String, String> properties = new LinkedHashMap<>();
|
||||
if (configurations == null) {
|
||||
return properties;
|
||||
}
|
||||
try {
|
||||
for (JsonNode configuration : objectMapper.readTree(configurations)) {
|
||||
if (SPARK_DEFAULTS.equals(configuration.path("Classification").asText())) {
|
||||
configuration.path("Properties").properties()
|
||||
.forEach(property -> properties.put(property.getKey(), property.getValue().asText()));
|
||||
}
|
||||
}
|
||||
} catch (JsonProcessingException ignored) {
|
||||
// RunJobFlow stored the array as it came; one that does not parse holds no properties to apply.
|
||||
return properties;
|
||||
}
|
||||
return properties;
|
||||
}
|
||||
|
||||
private static List<String> withoutMasterOrDeployMode(List<String> arguments) {
|
||||
List<String> kept = new ArrayList<>();
|
||||
int i = 0;
|
||||
while (i < arguments.size() && arguments.get(i).startsWith("-")) {
|
||||
String option = arguments.get(i);
|
||||
int equals = option.indexOf('=');
|
||||
String name = option.startsWith("--") && equals > 0 ? option.substring(0, equals) : option;
|
||||
// A switch, or an option written --name=value, is one argument; any other option takes the next.
|
||||
int length = SWITCHES.contains(option) || !name.equals(option) ? 1 : 2;
|
||||
List<String> words = arguments.subList(i, Math.min(i + length, arguments.size()));
|
||||
if (!DROPPED_OPTIONS.contains(name)) {
|
||||
kept.addAll(words);
|
||||
}
|
||||
i += words.size();
|
||||
}
|
||||
kept.addAll(arguments.subList(i, arguments.size()));
|
||||
return kept;
|
||||
}
|
||||
|
||||
// command-runner.jar is named alone; a path such as /usr/bin/spark-submit names spark-submit too.
|
||||
private static boolean named(String path, String name) {
|
||||
return path.equals(name) || path.endsWith("/" + name);
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import java.util.Map;
|
||||
/**
|
||||
* An EMR cluster (job flow). State machine:
|
||||
* STARTING → BOOTSTRAPPING → RUNNING → WAITING (and back to RUNNING for added steps), then
|
||||
* → TERMINATING → TERMINATED.
|
||||
* → TERMINATING → TERMINATED, or TERMINATED_WITH_ERRORS when a failed step ended it.
|
||||
* Steps, instance groups and fleets are stored as nested lists. Complex sub-structures
|
||||
* (ec2 attributes, applications, configurations) are stored as raw JSON strings.
|
||||
*/
|
||||
|
||||
@@ -8,7 +8,10 @@ import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** An EMR job-flow step. State machine: PENDING → RUNNING → COMPLETED (or CANCELLED/FAILED). */
|
||||
/**
|
||||
* An EMR job-flow step. State machine: PENDING → RUNNING → COMPLETED (or CANCELLED/FAILED). A step the
|
||||
* {@code docker} runner mode started runs in a container, and a FAILED one carries its FailureDetails.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
public class EmrStep {
|
||||
|
||||
@@ -22,6 +25,9 @@ public class EmrStep {
|
||||
private String state;
|
||||
private String stateChangeReason;
|
||||
private String executionRoleArn;
|
||||
private boolean runInContainer;
|
||||
private String failureReason;
|
||||
private String failureMessage;
|
||||
private Instant creationDateTime;
|
||||
private Instant startDateTime;
|
||||
private Instant endDateTime;
|
||||
@@ -58,6 +64,15 @@ public class EmrStep {
|
||||
public String getExecutionRoleArn() { return executionRoleArn; }
|
||||
public void setExecutionRoleArn(String executionRoleArn) { this.executionRoleArn = executionRoleArn; }
|
||||
|
||||
public boolean isRunInContainer() { return runInContainer; }
|
||||
public void setRunInContainer(boolean runInContainer) { this.runInContainer = runInContainer; }
|
||||
|
||||
public String getFailureReason() { return failureReason; }
|
||||
public void setFailureReason(String failureReason) { this.failureReason = failureReason; }
|
||||
|
||||
public String getFailureMessage() { return failureMessage; }
|
||||
public void setFailureMessage(String failureMessage) { this.failureMessage = failureMessage; }
|
||||
|
||||
public Instant getCreationDateTime() { return creationDateTime; }
|
||||
public void setCreationDateTime(Instant creationDateTime) { this.creationDateTime = creationDateTime; }
|
||||
|
||||
|
||||
+6
-4
@@ -507,10 +507,12 @@ public class EmrServerlessJobRunService implements Resettable {
|
||||
// The runs live in storage, which the reset has already wiped.
|
||||
}
|
||||
|
||||
// Whether a run's driver may still start: a cancelled run is past it, and so is one a reset removed.
|
||||
private synchronized boolean waitingToStart(String jobRunId, long launchedIn) {
|
||||
// Whether a run's driver may still start, or go on: a cancelled run is past it, and so is one a reset removed.
|
||||
private synchronized boolean stillGoing(String jobRunId, long launchedIn) {
|
||||
return launchedIn == generation && store.get(jobRunId)
|
||||
.map(record -> STATE_SCHEDULED.equals(record.getJobRun().getState())).orElse(false);
|
||||
.map(record -> STATE_SCHEDULED.equals(record.getJobRun().getState())
|
||||
|| STATE_RUNNING.equals(record.getJobRun().getState()))
|
||||
.orElse(false);
|
||||
}
|
||||
|
||||
private synchronized void driverStarted(String jobRunId, long launchedIn) {
|
||||
@@ -859,7 +861,7 @@ public class EmrServerlessJobRunService implements Resettable {
|
||||
@Override
|
||||
public boolean cancelled() {
|
||||
return !RequestScopes.callAs(job.accountId(), job.region(),
|
||||
() -> waitingToStart(job.runId(), launchedIn));
|
||||
() -> stillGoing(job.runId(), launchedIn));
|
||||
}
|
||||
}
|
||||
}
|
||||
+7
-5
@@ -179,6 +179,7 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
|
||||
* service calls this before it hands a run to {@link #run}, so every driver of this deployment it
|
||||
* finds is a leftover.
|
||||
*/
|
||||
@Override
|
||||
public void removeLeftoverDrivers(String service) {
|
||||
String owner = ContainerStorageHelper.ownerIdentity(config);
|
||||
ContainerStorageHelper.LabelAliases aliases = ContainerStorageHelper.CONTAINER_LABEL_ALIASES;
|
||||
@@ -301,15 +302,16 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
|
||||
|
||||
/**
|
||||
* How the running driver ends: with its exit code, by a stop, or at the run's timeout, which
|
||||
* {@code progress} hears before the driver is stopped. A stop is read at every look, so it ends the
|
||||
* run whether or not the driver would ever exit by itself, as a STREAMING run's does not, and run()
|
||||
* then removes the driver. Each look at the container is one short control-plane call, so a run
|
||||
* holds no Docker connection while its driver runs.
|
||||
* {@code progress} hears before the driver is stopped. A stop, and a run {@code progress} reports
|
||||
* cancelled or gone, are read at every look, so they end the run whether or not the driver would ever
|
||||
* exit by itself, as a STREAMING run's does not, and run() then removes the driver: one a run started
|
||||
* while a reset's teardown was passing is stopped once the reset has removed its run. Each look at the
|
||||
* container is one short control-plane call, so a run holds no Docker connection while its driver runs.
|
||||
*/
|
||||
private Outcome awaitEnd(String containerId, Job job, Launch launch, Progress progress)
|
||||
throws InterruptedException {
|
||||
Instant deadline = job.timeout().isZero() ? null : clock.instant().plus(job.timeout());
|
||||
while (!launch.stopRequested) {
|
||||
while (!launch.stopRequested && !progress.cancelled()) {
|
||||
InspectContainerResponse.ContainerState state =
|
||||
lifecycleManager.getDockerClient().inspectContainerCmd(containerId).exec().getState();
|
||||
if (!Boolean.TRUE.equals(state.getRunning())) {
|
||||
|
||||
+10
-1
@@ -25,6 +25,12 @@ public interface SparkJobRunner {
|
||||
*/
|
||||
void stop(String runId);
|
||||
|
||||
/**
|
||||
* Removes the drivers of {@code service}'s runs an earlier Floci process left running, which no thread
|
||||
* follows any more. The service calls it before any run of its own can start.
|
||||
*/
|
||||
void removeLeftoverDrivers(String service);
|
||||
|
||||
/** What a run tells the service, and asks it, while it goes. */
|
||||
interface Progress {
|
||||
|
||||
@@ -34,7 +40,10 @@ public interface SparkJobRunner {
|
||||
/** The run has passed its timeout, and its driver is about to be stopped. */
|
||||
void timedOut();
|
||||
|
||||
/** Whether the run was cancelled, or is gone, so that its driver must not start. */
|
||||
/**
|
||||
* Whether the run was cancelled, or is gone, as after a reset: its driver must not start, and one
|
||||
* that runs is stopped.
|
||||
*/
|
||||
boolean cancelled();
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user