feat(emr): add an optional timed lifecycle for clusters and steps (#6441)

Three settings, all 0 by default, hold an EMR cluster and its steps in
the states of the Management Guide's cluster lifecycle.
cluster-startup-delay-seconds, declared before but read by nothing,
keeps a new cluster STARTING for its first half and BOOTSTRAPPING for
its second; step-duration-seconds keeps each step RUNNING; and
cluster-termination-delay-seconds keeps a cluster TERMINATING before it
is TERMINATED. A ready cluster is RUNNING while it runs its steps, in
the order they were added and at most its StepConcurrencyLevel at a
time, and WAITING once none is left; a transient one ends after them
without waiting. ModifyCluster starts the steps a higher level makes
room for. TerminateJobFlows cancels every step not yet completed, as
its API reference says, and CancelSteps cancels a RUNNING step from
release emr-5.28.0, which makes room for the next. A waiter or a step
sensor now has something to wait for, and CancelSteps something to
cancel.

A new EmrClusterLifecycle works out when each change falls due from the
settings and the times already recorded. Every call that reads a
cluster first makes the changes due by then, and the service wakes at
each cluster's next change, also after a restart, so the change's
aws.emr event goes out when it happens, read or not; a wakeup sends its
events on a thread of their own, in order, so a slow rule target holds
up no cluster's change. A step's RUNNING now sends the step events
table's event, and a WAITING cluster that runs added steps sends
WAITING again once they are done. Every call that reads a cluster now
holds the service and publishes its events after, as the four that
changed one did, and answers from a copy made while it holds it.

With the settings at 0, a cluster is ready, and its steps complete,
before the call returns, as before; the step RUNNING events and the
second WAITING are the only new events. ModifyInstanceGroups and
ModifyInstanceFleet refuse a cluster that is not RUNNING or WAITING, a
STARTING or BOOTSTRAPPING one included, as their AWS messages say, and
AddJobFlowSteps and ModifyInstanceFleet a TERMINATING one, whose AWS
message names a cluster "shutting down". AddInstanceFleet gives a
TERMINATING one ModifyInstanceFleet's answer too, and AddInstanceGroups
AddJobFlowSteps' ValidationException, since its model declares no
InvalidRequestException; an AddJobFlowSteps with no steps leaves the
cluster as it is.

Part of #6046 (part 4).
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-24 20:22:11 -05:00
1 parent 7d4caf2291
commit 55b060b891
13 files changed
+1716 -580

No files matched your search

@@ -1937,9 +1937,20 @@ public interface EmulatorConfig {
@WithDefault("emr-7.5.0")
String defaultReleaseLabel();
/** Delay before a cluster reaches WAITING; 0 = advance synchronously. */
/**
* How long a new cluster takes to be ready to run steps, the first half STARTING and the second
* BOOTSTRAPPING; 0 makes it ready as soon as it is created.
*/
@WithDefault("0")
int clusterStartupDelaySeconds();
/** How long a step stays RUNNING before it completes; 0 completes it as soon as it starts. */
@WithDefault("0")
int stepDurationSeconds();
/** How long a cluster stays TERMINATING before it is TERMINATED; 0 ends it at once. */
@WithDefault("0")
int clusterTerminationDelaySeconds();
}
interface WafV2ServiceConfig {
@@ -0,0 +1,258 @@
package io.github.hectorvent.floci.services.emr;
import io.github.hectorvent.floci.services.emr.model.EmrCluster;
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 java.time.Duration;
import java.time.Instant;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
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.
*/
final class EmrClusterLifecycle {
static final String STARTING = "STARTING";
static final String BOOTSTRAPPING = "BOOTSTRAPPING";
static final String RUNNING = "RUNNING";
static final String WAITING = "WAITING";
static final String TERMINATING = "TERMINATING";
static final String TERMINATED = "TERMINATED";
static final String PENDING = "PENDING";
static final String COMPLETED = "COMPLETED";
static final String CANCELLED = "CANCELLED";
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;
EmrClusterLifecycle(int startupDelaySeconds, int stepDurationSeconds, int terminationDelaySeconds,
EmrEventPublisher events) {
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;
}
private static Duration seconds(String setting, int value) {
if (value < 0) {
throw new IllegalArgumentException("floci.services.emr." + setting + " must not be negative: " + value);
}
return Duration.ofSeconds(value);
}
/** A new cluster, STARTING at {@code now}, with its steps PENDING. */
void start(EmrCluster cluster, Instant now, String region) {
cluster.setState(STARTING);
cluster.setCreationDateTime(now);
events.queue(events.clusterStateChange(cluster, STARTING, now), region);
submit(cluster, cluster.getSteps(), now, region);
}
/**
* {@code steps}, already on the cluster's list, added at {@code now}: "The state of all steps is set
* to PENDING", and a cluster that is ready starts what it has room for. Adding none changes nothing.
*/
void submit(EmrCluster cluster, List<EmrStep> steps, Instant now, String region) {
if (steps.isEmpty()) {
return;
}
for (EmrStep step : steps) {
step.setState(PENDING);
step.setCreationDateTime(now);
if (step.getActionOnFailure() == null) {
step.setActionOnFailure("TERMINATE_CLUSTER");
}
events.queue(events.stepStatusChange(cluster, step, PENDING), region);
}
if (RUNNING.equals(cluster.getState()) || WAITING.equals(cluster.getState())) {
runSteps(cluster, now, region);
}
}
/**
* Ends the cluster for {@code code}: TERMINATING from {@code now}, then TERMINATED. TerminateJobFlows:
* "When a job flow is shut down, any step not yet completed is canceled".
*/
void terminate(EmrCluster cluster, String code, String message, Instant now, String region) {
cluster.setState(TERMINATING);
cluster.setStateChangeReasonCode(code);
cluster.setStateChangeMessage(message);
cluster.setTerminatingDateTime(now);
for (EmrStep step : cluster.getSteps()) {
if (PENDING.equals(step.getState()) || RUNNING.equals(step.getState())) {
cancelStep(cluster, step, now, region);
}
}
}
/**
* CancelSteps for one step: null once it is cancelled, or why it cannot be. CancelSteps: "When you
* use Amazon EMR releases 5.28.0 and later, you can cancel steps that are in a PENDING or RUNNING
* state." A cancelled RUNNING step makes room for the next PENDING one.
*/
String cancel(EmrCluster cluster, EmrStep step, Instant now, String region) {
boolean running = RUNNING.equals(step.getState()) && cancelsRunningSteps(cluster.getReleaseLabel());
if (!running && !PENDING.equals(step.getState())) {
return "Step is not in a cancellable state: " + step.getState();
}
cancelStep(cluster, step, now, region);
if (running) {
runSteps(cluster, now, region);
}
return null;
}
/**
* The cluster's StepConcurrencyLevel changed: a RUNNING cluster starts what it now has room for. A
* lower level lets the steps already running complete, as the guide says EMR does.
*/
void concurrencyChanged(EmrCluster cluster, Instant now, String region) {
if (RUNNING.equals(cluster.getState())) {
runSteps(cluster, now, region);
}
}
/** Makes every change due by {@code now}, in the order they fall due; true when there was one. */
boolean advance(EmrCluster cluster, Instant now, String region) {
boolean changed = false;
Instant due;
while ((due = nextChange(cluster)) != null && !due.isAfter(now)) {
change(cluster, due, region);
changed = true;
}
return changed;
}
/** When the cluster's next change falls due, or null while it waits for a call. */
Instant nextChange(EmrCluster cluster) {
return switch (cluster.getState()) {
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()))
.map(step -> step.getStartDateTime().plus(stepRun))
.min(Comparator.naturalOrder())
.orElse(null);
case TERMINATING -> cluster.getTerminatingDateTime().plus(termination);
default -> null;
};
}
private void change(EmrCluster cluster, Instant at, String region) {
switch (cluster.getState()) {
case STARTING -> cluster.setState(BOOTSTRAPPING);
case BOOTSTRAPPING -> {
cluster.setReadyDateTime(at);
cluster.setState(RUNNING);
runSteps(cluster, at, region);
}
case RUNNING -> {
for (EmrStep step : cluster.getSteps()) {
if (RUNNING.equals(step.getState()) && !step.getStartDateTime().plus(stepRun).isAfter(at)) {
step.setState(COMPLETED);
step.setEndDateTime(at);
events.queue(events.stepStatusChange(cluster, step, COMPLETED), region);
}
}
runSteps(cluster, at, region);
}
case TERMINATING -> {
cluster.setState(TERMINATED);
cluster.setEndDateTime(at);
releaseInstanceCapacity(cluster);
events.queue(events.clusterStateChange(cluster, TERMINATED, at), region);
}
default -> throw new IllegalStateException("Nothing falls due for a " + cluster.getState() + " cluster");
}
}
/**
* Starts PENDING steps in the order they were added while the cluster has room: "pending steps in
* queue transition to running state in the order they were submitted". With none left, the
* cluster is done.
*/
private void runSteps(EmrCluster cluster, Instant at, String region) {
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());
for (EmrStep step : cluster.getSteps()) {
if (running >= level) {
break;
}
if (PENDING.equals(step.getState())) {
step.setState(RUNNING);
step.setStartDateTime(at);
events.queue(events.stepStatusChange(cluster, step, RUNNING), region);
running++;
}
}
if (running > 0) {
// A WAITING cluster's "ready to run steps" no longer holds; no source gives a RUNNING one's reason.
cluster.setState(RUNNING);
cluster.setStateChangeReasonCode(null);
cluster.setStateChangeMessage(null);
} else {
finish(cluster, at, region);
}
}
/**
* The cluster has no step left to run: it waits for more, or, set to end after its steps, ends
* without waiting. One created without steps waits either way.
*/
private void finish(EmrCluster cluster, Instant at, String region) {
if (cluster.isAutoTerminate() && !cluster.getSteps().isEmpty()) {
terminate(cluster, "ALL_STEPS_COMPLETED", "All steps completed.", at, region);
return;
}
cluster.setState(WAITING);
cluster.setStateChangeReasonCode(cluster.getSteps().isEmpty() ? null : "ALL_STEPS_COMPLETED");
cluster.setStateChangeMessage("Cluster ready to run steps.");
events.queue(events.clusterStateChange(cluster, WAITING, at), region);
}
private void cancelStep(EmrCluster cluster, EmrStep step, Instant at, String region) {
step.setState(CANCELLED);
step.setEndDateTime(at);
events.queue(events.stepStatusChange(cluster, step, CANCELLED), region);
}
private static void releaseInstanceCapacity(EmrCluster cluster) {
for (EmrInstanceGroup group : cluster.getInstanceGroups()) {
group.setState(TERMINATED);
group.setTerminatedInstanceCount(group.getRunningInstanceCount());
group.setRunningInstanceCount(0);
}
for (EmrInstanceFleet fleet : cluster.getInstanceFleets()) {
fleet.setState(TERMINATED);
fleet.setProvisionedOnDemandCapacity(0);
fleet.setProvisionedSpotCapacity(0);
}
}
/** Releases from 5.28.0 cancel RUNNING steps; a label not of the emr-x.y form is taken as current. */
static boolean cancelsRunningSteps(String releaseLabel) {
Matcher matcher = RELEASE_LABEL.matcher(releaseLabel == null ? "" : releaseLabel);
if (!matcher.matches()) {
return true;
}
int major = Integer.parseInt(matcher.group(1));
int minor = Integer.parseInt(matcher.group(2));
return major > 5 || (major == 5 && minor >= 28);
}
}
@@ -59,8 +59,8 @@ public class EmrEventPublisher {
this.regionResolver = regionResolver;
}
/** {@code cluster} entering {@code state}: STARTING, WAITING or TERMINATED. */
Event clusterStateChange(EmrCluster cluster, String state) {
/** {@code cluster} entering {@code state} at {@code at}: STARTING, WAITING or TERMINATED. */
Event clusterStateChange(EmrCluster cluster, String state, Instant at) {
boolean terminated = "TERMINATED".equals(state);
String code = cluster.getStateChangeReasonCode();
// The examples' reason is a JSON string: {"code":""} for a WAITING cluster, and the reason's code
@@ -76,11 +76,11 @@ public class EmrEventPublisher {
detail.put("name", cluster.getName());
detail.put("clusterId", cluster.getId());
detail.put("state", state);
detail.put("message", clusterMessage(cluster, state));
detail.put("message", clusterMessage(cluster, state, at));
return new Event(CLUSTER_STATE_CHANGE, detail.toString());
}
/** {@code step} of {@code cluster} entering {@code state}: PENDING, COMPLETED or CANCELLED. */
/** {@code step} of {@code cluster} entering {@code state}: PENDING, RUNNING, COMPLETED or CANCELLED. */
Event stepStatusChange(EmrCluster cluster, EmrStep step, String state) {
ObjectNode detail = objectMapper.createObjectNode();
detail.put("severity", "CANCELLED".equals(state) ? "WARN" : "INFO");
@@ -126,17 +126,15 @@ public class EmrEventPublisher {
SOURCE, queued.event().detailType(), queued.event().detail(), null, queued.region()));
}
private static String clusterMessage(EmrCluster cluster, String state) {
private static String clusterMessage(EmrCluster cluster, String state, Instant at) {
String named = cluster.getId() + " (" + cluster.getName() + ")";
return switch (state) {
case "STARTING" -> "Amazon EMR cluster " + named + " was requested at "
+ time(cluster.getCreationDateTime()) + " and is being created.";
case "STARTING" -> "Amazon EMR cluster " + named + " was requested at " + time(at)
+ " and is being created.";
case "WAITING" -> cluster.getSteps().isEmpty()
? "Amazon EMR cluster " + named + " was created at " + time(cluster.getReadyDateTime())
+ " and is ready for use."
: "Amazon EMR cluster " + named + " finished running all pending steps at "
+ time(cluster.getReadyDateTime()) + ".";
case "TERMINATED" -> "Amazon EMR Cluster " + named + " has terminated at " + time(cluster.getEndDateTime())
? "Amazon EMR cluster " + named + " was created at " + time(at) + " and is ready for use."
: "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() + ".";
default -> throw new IllegalArgumentException("No cluster event for state " + state);
};
@@ -148,6 +146,8 @@ public class EmrEventPublisher {
return switch (state) {
case "PENDING" -> "Step " + stepNamed + " was added to Amazon EMR cluster " + clusterNamed + " at "
+ time(step.getCreationDateTime()) + " and is pending execution.";
case "RUNNING" -> "Step " + stepNamed + " in Amazon EMR cluster " + clusterNamed + " started running at "
+ time(step.getStartDateTime()) + ".";
case "COMPLETED" -> "Step " + stepNamed + " in Amazon EMR cluster " + clusterNamed
+ " completed execution at " + time(step.getEndDateTime()) + ". The step started running at "
+ time(step.getStartDateTime())
File diff suppressed because it is too large. Load diff
@@ -10,7 +10,8 @@ import java.util.Map;
/**
* An EMR cluster (job flow). State machine:
* STARTING → BOOTSTRAPPING → RUNNING → WAITING, then → TERMINATING → TERMINATED.
* STARTING → BOOTSTRAPPING → RUNNING → WAITING (and back to RUNNING for added steps), then
* → TERMINATING → TERMINATED.
* Steps, instance groups and fleets are stored as nested lists. Complex sub-structures
* (ec2 attributes, applications, configurations) are stored as raw JSON strings.
*/
@@ -53,6 +54,8 @@ public class EmrCluster {
private Instant creationDateTime;
private Instant readyDateTime;
private Instant endDateTime;
// When the cluster began TERMINATING; Floci's own, as the API's Timeline has no such time.
private Instant terminatingDateTime;
private Map<String, String> tags = new LinkedHashMap<>();
private List<EmrStep> steps = new ArrayList<>();
private List<EmrInstanceGroup> instanceGroups = new ArrayList<>();
@@ -180,6 +183,9 @@ public class EmrCluster {
public Instant getEndDateTime() { return endDateTime; }
public void setEndDateTime(Instant endDateTime) { this.endDateTime = endDateTime; }
public Instant getTerminatingDateTime() { return terminatingDateTime; }
public void setTerminatingDateTime(Instant terminatingDateTime) { this.terminatingDateTime = terminatingDateTime; }
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags; }