feat(emr): run a cluster's bootstrap actions on its core and task nodes (#8502)

Bootstrap actions "run on cluster after Amazon EMR launches the
instance", on every node, and "If you add nodes to a running cluster,
bootstrap actions also run on those nodes in the same way". Floci ran
them once, as on the primary node, and every node ran from the image they
left, so an action's branch for the core or task nodes never ran.

Where a cluster's core and task nodes run in containers of their own,
each now runs the actions too, in a bootstrap container of its own beside
the primary node's, as that node: its node files say CORE or TASK, the
cluster's relay answers its instance metadata as that node, its output
goes under its own instance id, and the container is kept as the image
the node runs from, so it holds what its own actions installed. A node a
resize adds runs them before it starts, and one that leaves takes its
image with it, so one added again runs them again.

AWS terminates a node whose action fails and says only that "If too many
instances fail their bootstrap actions, then Amazon EMR terminates the
cluster. If just a few instances fail, Amazon EMR attempts to reallocate
the failed instances and continue". Floci runs a node's actions again
once, in a fresh container, and a second failure ends the cluster with
BOOTSTRAP_FAILURE and a message of Floci's after the primary node's, as
no source gives AWS's words or an error code for a core or task node.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-15 17:41:55 -04:00
1 parent 84c06d59e7
commit ec9c19ff62
12 files changed
+891 -120

No files matched your search

+24 -9
View File
@@ -272,10 +272,11 @@ holding the driver and its executors, or a command or a script. The cluster itse
containers on the cluster's nodes; in cluster mode the driver runs on one of them too, its output in the application's
container logs (see **Output**) and only the client's in the step's.
A node needs Spark, Python and what the bootstrap actions installed, as an EMR cluster's nodes hold every
application it installs, so each runs from the image the steps run in: the bootstrap's, else the release's EMR
Serverless image with the HDFS, MapReduce and YARN of its EMR Serverless Hive image, and Hive on a cluster with
Hive, which Floci makes the first time one of the release's clusters needs it (see **Hive steps**), and in which the
cluster's bootstrap actions run. An `emr-spark-*` release has no EMR Serverless Hive image, and `emr-7.5.0`'s HDFS and
application it installs, so each runs from the image the steps run in, the release's EMR Serverless image with the
HDFS, MapReduce and YARN of its EMR Serverless Hive image, and Hive on a cluster with Hive, which Floci makes the
first time one of the release's clusters needs it (see **Hive steps**), or, on a cluster with bootstrap actions, from
the image its own bootstrap left on that image (see **Bootstrap actions**). An `emr-spark-*` release has no EMR
Serverless Hive image, and `emr-7.5.0`'s HDFS and
YARN do not run on its newer Hadoop, so its image holds the whole of `emr-7.5.0`'s Hadoop in `/opt`, which only the
node's daemons run from (see **Known limitations**). EMR sizes a NodeManager, and the executors' memory and cores ("determined by the
core and task instance types"), by the instance type; Floci's node shares the machine it runs on, so its NodeManager
@@ -452,9 +453,23 @@ holding the driver and its executors, or a command or a script. The cluster itse
`INTERNAL_ERROR`. `TerminateJobFlows` stops the actions at once, and a cluster Floci was bootstrapping
when it stopped ends with `INTERNAL_ERROR` once Floci is back. With a `LogUri`, each action's output
goes to `stdout.gz` and `stderr.gz` under `<LogUri>/<cluster-id>/node/<instance-id>/bootstrap-actions/<n>/`,
as the Management Guide's bootstrap failure pages give the folder. The actions run once, as on the
master, and every node of the cluster runs from the image they leave, so each holds what they installed. Shutdown
actions do not run. A cluster a failed action ended has a `Status.ErrorDetails` entry in `DescribeCluster` and
as the Management Guide's bootstrap failure pages give the folder. Bootstrap actions "run on cluster after
Amazon EMR launches the instance", on each node: where a cluster's core and task nodes run in containers of their
own (see **YARN**), each runs them too, in a container of its own beside the primary node's, as that node, its files
saying so (see **Node files**), its instance metadata its own (see **Instance metadata**), its output under its own
instance id, and is kept as the image that node runs from, so it holds what its own actions installed. A node a
resize adds runs them before it starts, as "If you add nodes to a running cluster, bootstrap actions also run on
those nodes in the same way", and one that leaves keeps its image only until the cluster ends, so one added again
runs them again; a bootstrap that cannot run for the nodes a resize adds ends the cluster with `INTERNAL_ERROR`, as
at its start. The nodes' bootstraps stop as the cluster ends, or as the primary node's actions fail. AWS
terminates a node whose action fails, and "If too many instances fail their bootstrap actions, then Amazon EMR
terminates the cluster. If just a few instances fail, Amazon EMR attempts to reallocate the failed instances and
continue", with no number given: Floci runs a node's actions again once, in a fresh container, and a second failure
ends the cluster with `BOOTSTRAP_FAILURE` and, as no source gives AWS's words or an error code for a core or task
node, a message of Floci's after the primary node's, "On the core instance (i-00000000000000002), bootstrap action 1
returned a non-zero return code", with no `ErrorDetails`. Elsewhere the actions run once, as on the primary node, and
every node runs from the image they leave. Shutdown actions do not run. A cluster a failed action ended has a
`Status.ErrorDetails` entry in `DescribeCluster` and
`ListClusters`, with the code and `ErrorData` keys of the Management Guide's error code pages:
`BOOTSTRAP_FAILURE_PRIMARY_WITH_NON_ZERO_CODE` with `primary-instance-id`, `bootstrap-action`, `return-code`,
`amazon-s3-path` and `public-doc` for an action that exits with another code than 0, and
@@ -469,8 +484,8 @@ holding the driver and its executors, or a command or a script. The cluster itse
`task`. AWS documents nothing else in either file, so Floci writes those two fields alone: `{"isMaster": true}` and
`{"instanceRole": "MASTER"}` in the bootstrap actions' container and each step's, which run as on the primary node,
and in the primary node's own, and `false` with `CORE` or `TASK` in each core or task node's, the roles as the API's
`InstanceRoleType` names them. The actions run once, as on the primary node, so an action's branch for the other
nodes does not run. Files that cannot be written fail the bootstrap, the step or the node they are for.
`InstanceRoleType` names them, and in each core or task node's bootstrap container its own (see **Bootstrap
actions**). Files that cannot be written fail the bootstrap, the step or the node they are for.
* **States**: a step is `RUNNING` from when it starts until its driver or command exits; `step-duration-seconds`
does not apply. The first step of a release also waits while its image is pulled (3.5 to 4.3 GB
unpacked; see [`floci.docker.image-pull-timeout-seconds`](../configuration/docker.md)). It is then
@@ -2,6 +2,7 @@ package io.floci.aws.core.common.docker;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Predicate;
/**
* The containers of the runs a component has in progress, by run id, so a stop, a reset or a shutdown can
@@ -32,9 +33,16 @@ public final class ContainerLaunches {
/** Stops every run in progress, as {@link Launch#stopNow} does, so a reset or a shutdown orphans none. */
public void stopAll(ContainerLifecycleManager lifecycleManager, int stopTimeoutSeconds) {
for (Launch launch : launches.values()) {
launch.stopNow(lifecycleManager, stopTimeoutSeconds);
}
stopEach(id -> true, lifecycleManager, stopTimeoutSeconds);
}
/** Stops each run in progress whose id {@code ids} takes, as {@link Launch#stopNow} does. */
public void stopEach(Predicate<String> ids, ContainerLifecycleManager lifecycleManager, int stopTimeoutSeconds) {
launches.forEach((id, launch) -> {
if (ids.test(id)) {
launch.stopNow(lifecycleManager, stopTimeoutSeconds);
}
});
}
/** A run in progress: its container, once up and until claimed, and whether it was asked to stop. */
@@ -5,10 +5,10 @@ import java.util.Set;
import java.util.function.BooleanSupplier;
/**
* Runs a cluster's bootstrap actions in the EMR {@code docker} runner mode: one after the other, in one
* container of the release's image, which is then kept as the image the cluster's steps run in. The
* service calls it off the request thread; {@link EmrBootstrapRunner} is the Docker implementation, and a
* test supplies its own.
* Runs a cluster's bootstrap actions on one of its nodes in the EMR {@code docker} runner mode: one after the other,
* in a container of the release's image, which is then kept as the image that node runs from, the primary node's being
* the one the cluster's steps run in. The service calls it off the request thread; {@link EmrBootstrapRunner} is the
* Docker implementation, and a test supplies its own.
*/
public interface BootstrapRunner {
@@ -19,7 +19,7 @@ public interface BootstrapRunner {
*/
Outcome run(Bootstrap bootstrap, BooleanSupplier cancelled);
/** Stops the bootstrap of {@code clusterId}, now or as soon as its container is up. */
/** Stops each bootstrap of {@code clusterId}, its primary node's and its other nodes', now or once it is up. */
void stop(String clusterId);
/**
@@ -35,35 +35,53 @@ public interface BootstrapRunner {
void removeImages(Set<String> kept);
/**
* A cluster's bootstrap: its id, which names its container and its image; its account and Region; its
* release, and the image template and Docker network to run it in (a null template is the release's
* public EMR Serverless image, a null network the global default); the role of its EC2 instance profile,
* whose credentials the actions get; its actions; and the S3 folder their logs go to, ending in a slash
* (null for none), each action's in a folder of its own named by its number.
* A cluster's bootstrap on one of its nodes: its cluster's id, which with the node names its container and its
* image; its account and Region; its release, and the image template and Docker network to run it in (a null
* template is the release's public EMR Serverless image, a null network the global default); the role of its EC2
* instance profile, whose credentials the actions get; its actions; the S3 folder their logs go to, ending in a
* slash (null for none), each action's in a folder of its own named by its number; where its instance metadata is
* served; and the node it runs on, null for the primary node, else a core or task node's id as
* {@link ClusterStorage.Node#id} has it, with that node's instance role, MASTER, CORE or TASK.
*/
record Bootstrap(String clusterId, String accountId, String region, String releaseLabel, String imageTemplate,
String dockerNetwork, String role, List<Action> actions, String logFolder,
String metadataNetwork, String metadataAddress) {
String metadataNetwork, String metadataAddress, String node, String instanceRole) {
/** The primary node's bootstrap. */
Bootstrap(String clusterId, String accountId, String region, String releaseLabel, String imageTemplate,
String dockerNetwork, String role, List<Action> actions, String logFolder) {
this(clusterId, accountId, region, releaseLabel, imageTemplate, dockerNetwork, role, actions, logFolder,
null, null);
null, null, null, "MASTER");
}
/** This bootstrap, run in {@code image}. */
Bootstrap inImage(String image) {
return new Bootstrap(clusterId, accountId, region, releaseLabel, image, dockerNetwork, role, actions,
logFolder, metadataNetwork, metadataAddress);
logFolder, metadataNetwork, metadataAddress, node, instanceRole);
}
/**
* This bootstrap, its container on {@code network}, its cluster's own, at {@code address}, a link-local one,
* where its cluster's instance metadata relay answers it as the primary node, and on its steps' network too.
* where its cluster's instance metadata relay answers it as its node, and on its steps' network too.
*/
Bootstrap onMetadata(String network, String address) {
return new Bootstrap(clusterId, accountId, region, releaseLabel, imageTemplate, dockerNetwork, role,
actions, logFolder, network, address);
actions, logFolder, network, address, node, instanceRole);
}
/**
* This bootstrap on the cluster's core or task node {@code id}, of instance role {@code nodeRole}, its logs in
* {@code folder}, as on that node's own instance, before the relay is told where it is (see
* {@link #onMetadata}).
*/
Bootstrap onNode(String id, String nodeRole, String folder) {
return new Bootstrap(clusterId, accountId, region, releaseLabel, imageTemplate, dockerNetwork, role,
actions, folder, null, null, id, nodeRole);
}
/** What tells this bootstrap's container, image and session from its cluster's others. */
String name() {
return node == null ? clusterId : clusterId + "-" + node;
}
}
@@ -147,9 +147,14 @@ public interface ClusterStorage {
/**
* A core or task node of a cluster: {@code id} tells its container from its cluster's others, {@code host} is its
* private DNS name, and a {@code core} node holds a DataNode beside its NodeManager.
* private DNS name, a {@code core} node holds a DataNode beside its NodeManager, and {@code image} is the image its
* own bootstrap left, which it runs from, null where it has none and runs from the steps' image.
*/
record Node(String id, String host, boolean core) {
record Node(String id, String host, boolean core, String image) {
Node(String id, String host, boolean core) {
this(id, host, core, null);
}
}
/**
@@ -33,6 +33,7 @@ import java.nio.file.Path;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
@@ -40,9 +41,11 @@ import java.util.function.BooleanSupplier;
import java.util.zip.GZIPOutputStream;
/**
* Runs a cluster's bootstrap actions in a container of the release's EMR Serverless image, the one its
* steps run in, then commits that container as the image the cluster's steps run in from then on, so what
* the actions installed or wrote is there for every step. "Bootstrap actions execute as the Hadoop user by
* Runs a cluster's bootstrap actions on one of its nodes in a container of the release's EMR Serverless image, the one
* its steps run in, then commits that container as the image that node runs from: the primary node's is the one the
* cluster's steps run in from then on, so what the actions installed or wrote is there for every step, and a core or
* task node's is its own, the container named, and its node's files written, for that node.
* "Bootstrap actions execute as the Hadoop user by
* default. You can execute a bootstrap action with root privileges by using sudo", but the image has no
* {@code sudo}: an action runs as root instead, in the {@code hadoop} user's home, with a {@code sudo} that
* runs its command as it is, and what it leaves in that home is the {@code hadoop} user's. Each action's
@@ -109,19 +112,19 @@ public class EmrBootstrapRunner implements BootstrapRunner, ContainerTeardown {
@Override
public Outcome run(Bootstrap bootstrap, BooleanSupplier cancelled) {
ContainerLaunches.Launch launch = launches.begin(bootstrap.clusterId());
ContainerLaunches.Launch launch = launches.begin(launchId(bootstrap));
Optional<SessionCreds> credentials = Optional.empty();
try {
if (cancelled.getAsBoolean()) {
return Outcome.halted();
}
credentials = roleCredentials.forRole(bootstrap.role(), bootstrap.accountId(),
bootstrap.clusterId() + "-bootstrap");
bootstrap.name() + "-bootstrap");
String image = EmrServerlessSparkRunner.image(bootstrap.imageTemplate(), bootstrap.releaseLabel());
Map<String, String> labels = labels(bootstrap);
ContainerBuilder.Builder container = containerBuilder.newContainer(image)
.withName(ContainerStorageHelper.dockerName(config,
SERVICE + "-" + bootstrap.clusterId() + "-bootstrap"))
.withName(ContainerStorageHelper.dockerName(config, SERVICE + "-" + bootstrap.clusterId()
+ "-bootstrap" + (bootstrap.node() == null ? "" : "-" + bootstrap.node())))
.withUser("root")
.withEntrypoint(List.of("sleep", "infinity"))
.withHostDockerInternalOnLinux()
@@ -149,7 +152,7 @@ public class EmrBootstrapRunner implements BootstrapRunner, ContainerTeardown {
return Outcome.halted();
}
// The actions run on the primary node, whose files say so, as the Management Guide's own action reads them.
writeNodeInfo(containerId);
writeNodeInfo(containerId, bootstrap.instanceRole());
List<String> env = awsEnv.sdkBaselineEnv(bootstrap.region(), Optional.empty(), credentials,
bootstrap.accountId());
for (int number = 1; number <= bootstrap.actions().size(); number++) {
@@ -173,7 +176,7 @@ public class EmrBootstrapRunner implements BootstrapRunner, ContainerTeardown {
LOG.warnv(e, "The bootstrap actions of EMR cluster {0} could not run", bootstrap.clusterId());
return Outcome.couldNotRun(e.getMessage());
} finally {
String unclaimed = launches.end(bootstrap.clusterId(), launch);
String unclaimed = launches.end(launchId(bootstrap), launch);
if (unclaimed != null) {
lifecycleManager.stopAndRemove(unclaimed, null, STOP_TIMEOUT_SECONDS);
}
@@ -182,13 +185,14 @@ public class EmrBootstrapRunner implements BootstrapRunner, ContainerTeardown {
}
}
private void writeNodeInfo(String containerId) {
private void writeNodeInfo(String containerId, String instanceRole) {
ContainerExec.Result written = ContainerExec.run(lifecycleManager.getDockerClient(), containerId,
new String[] {"env", EmrServerlessSparkRunner.INSTANCE_ROLE_VARIABLE + "=MASTER", "bash", "-c",
EmrServerlessSparkRunner.NODE_INFO}, NODE_INFO_TIMEOUT_SECONDS);
new String[] {"env", EmrServerlessSparkRunner.INSTANCE_ROLE_VARIABLE + "=" + instanceRole, "bash",
"-c", EmrServerlessSparkRunner.NODE_INFO}, NODE_INFO_TIMEOUT_SECONDS);
if (written.exitCode() != 0) {
String why = written.stderr().strip();
throw new IllegalStateException("Could not write the primary node's "
String node = "MASTER".equals(instanceRole) ? "primary" : instanceRole.toLowerCase(Locale.ROOT);
throw new IllegalStateException("Could not write the " + node + " node's "
+ EmrServerlessSparkRunner.INSTANCE_FILE + (why.isEmpty() ? "" : ": " + why));
}
}
@@ -323,21 +327,25 @@ public class EmrBootstrapRunner implements BootstrapRunner, ContainerTeardown {
String released = docker.inspectContainerCmd(containerId).exec().getImageId();
String user = docker.inspectImageCmd(released).exec().getConfig().getUser();
String repository = ContainerStorageHelper.dockerName(config, COMPONENT);
lifecycleManager.commit(containerId, repository, bootstrap.clusterId(),
lifecycleManager.commit(containerId, repository, bootstrap.name(),
user == null || user.isBlank() ? "root" : user, labels);
String tag = repository + ":" + bootstrap.clusterId();
String tag = repository + ":" + bootstrap.name();
String committed = docker.inspectImageCmd(tag).exec().getId();
LOG.infov("Kept the bootstrap of EMR cluster {0} as image {1} ({2})", bootstrap.clusterId(), tag, committed);
return committed;
}
// Removing a container ends the action running in it, which run() then reads as stopped: the primary node's and
// each core and task node's.
@Override
public void stop(String clusterId) {
ContainerLaunches.Launch launch = launches.get(clusterId);
if (launch != null) {
// Removing the container ends the action running in it, which run() then reads as stopped.
launch.stopNow(lifecycleManager, STOP_TIMEOUT_SECONDS);
}
launches.stopEach(id -> id.equals(clusterId) || id.startsWith(clusterId + "/"), lifecycleManager,
STOP_TIMEOUT_SECONDS);
}
// A cluster's primary node's bootstrap by the cluster's id, a core or task node's after it.
private static String launchId(Bootstrap bootstrap) {
return bootstrap.node() == null ? bootstrap.clusterId() : bootstrap.clusterId() + "/" + bootstrap.node();
}
/** Stops every bootstrap inside {@link #run}, so a reset or a shutdown orphans none. */
@@ -141,7 +141,10 @@ final class EmrClusterLifecycle {
* "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) {
if (BOOTSTRAPPING.equals(cluster.getState()) && !bootstrapTimed(cluster)) {
// Its bootstraps stop: the primary node's and its nodes', or, past BOOTSTRAPPING, those of the nodes a resize
// added, which run where its own ran in a container.
if (BOOTSTRAPPING.equals(cluster.getState()) ? !bootstrapTimed(cluster)
: bootstrapping != null && cluster.getBootstrapImage() != null) {
bootstrapping.stop(cluster);
}
cluster.setState(TERMINATING);
@@ -768,18 +768,18 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
changed |= leaving.remove(name) != null;
Container container = present.get(name);
if (container == null || !"running".equals(container.getState())
|| !request.imageId().equals(container.getImageId())
|| !imageOf(request, node).equals(container.getImageId())
|| !joins(container.getNetworkSettings() != null ? container.getNetworkSettings().getNetworks()
: null, clusterSubnet(clusterId) != null ? request.joinedNetwork() : null)
|| !metadataKnown(clusterId, name)) {
startNode(request, node.host(), node.core(), name, teardown);
startNode(request, node.host(), node.core(), imageOf(request, node), name, teardown);
} else {
runningNodes.add(name);
}
}
for (Map.Entry<String, Container> node : present.entrySet()) {
if (!wanted.contains(node.getKey()) && !leaving.containsKey(node.getKey())) {
leaving.put(node.getKey(), draining(node.getValue().getLabels()));
leaving.put(node.getKey(), draining(node.getValue().getLabels(), node.getValue().getImageId()));
runningNodes.add(node.getKey());
changed = true;
}
@@ -789,9 +789,11 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
if (wanted.contains(name) || present.containsKey(name) || leaving.containsKey(name)) {
continue;
}
Draining node = draining(volume.getValue());
// Its container, and the image it ran, gone with a shutdown: it starts from the steps' image, which holds
// HDFS too, and runs only until HDFS has moved its blocks.
Draining node = draining(volume.getValue(), null);
if (node.core()) {
startNode(request, node.host(), true, name, teardown);
startNode(request, node.host(), true, request.imageId(), name, teardown);
leaving.put(name, node);
changed = true;
} else {
@@ -807,16 +809,23 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
return wanted;
}
// A node being decommissioned, as its container's or its volume's labels say, with an hour and a minute to go in.
private Draining draining(Map<String, String> labels) {
// A node being decommissioned, as its container's or its volume's labels say, with an hour and a minute to go in,
// and the image its container ran, null where it has none.
private Draining draining(Map<String, String> labels, String imageId) {
Map<String, String> known = labels != null ? labels : Map.of();
return new Draining(known.get(NODE_HOST_LABEL), Boolean.parseBoolean(known.get(NODE_CORE_LABEL)),
nanoTime.getAsLong() + GRACEFUL_DECOMMISSION.plus(DECOMMISSION_MARGIN).toNanos());
nanoTime.getAsLong() + GRACEFUL_DECOMMISSION.plus(DECOMMISSION_MARGIN).toNanos(), imageId);
}
// A node's container, started on the data its volume keeps; one whose start a teardown passed goes, as the teardown's
// sweep may have looked before it was there.
private void startNode(NodeRequest request, String host, boolean core, String name, long teardown) {
// The image a node runs from: the one its own bootstrap left, else the steps'.
private static String imageOf(NodeRequest request, Node node) {
return node.image() != null ? node.image() : request.imageId();
}
// A node's container, started on the data its volume keeps, from imageId; one whose start a teardown passed goes,
// as the teardown's sweep may have looked before it was there.
private void startNode(NodeRequest request, String host, boolean core, String imageId, String name,
long teardown) {
String clusterId = request.clusterId();
Yarn yarn = request.yarn();
// Known before it starts, so a teardown while it starts removes it.
@@ -830,7 +839,7 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
Map<String, String> labels = labels(clusterId, request.accountId(), request.region(), NODE_COMPONENT);
labels.put(NODE_HOST_LABEL, host);
labels.put(NODE_CORE_LABEL, String.valueOf(core));
ContainerBuilder.Builder spec = containerBuilder.newContainer(request.imageId())
ContainerBuilder.Builder spec = containerBuilder.newContainer(imageId)
.withName(name)
.withUser("root")
.withEntrypoint(List.of("/bin/bash", "-c", NODE_SCRIPT))
@@ -1055,7 +1064,8 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
}
LOG.infov("The core node {0} of EMR cluster {1} stopped before HDFS moved its blocks, and starts again on"
+ " its data", node.host(), request.clusterId());
startNode(request, node.host(), true, name, teardown);
startNode(request, node.host(), true, node.imageId() != null ? node.imageId() : request.imageId(), name,
teardown);
return false;
}
return node.hdfsDone() && onPrimary(request.clusterId(), "curl -sf -m 5 \"" + RESOURCE_MANAGER_NODES
@@ -1117,13 +1127,15 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
// A node being decommissioned, which goes anyway at the nanoTime deadline, its own, so one a later resize adds has
// the whole time too. A core node goes to YARN's decommission only once HDFS has moved its blocks: a decommissioned
// NodeManager exits, which ends its container, the DataNode with it.
private record Draining(String host, boolean core, boolean hdfsDone, long deadline) {
Draining(String host, boolean core, long deadline) {
this(host, core, !core, deadline);
// It starts again, where it must, from imageId, the image it ran, its own bootstrap's say, or the steps' where it
// is not known.
private record Draining(String host, boolean core, boolean hdfsDone, long deadline, String imageId) {
Draining(String host, boolean core, long deadline, String imageId) {
this(host, core, !core, deadline, imageId);
}
Draining hdfsDecommissioned() {
return new Draining(host, core, true, deadline);
return new Draining(host, core, true, deadline, imageId);
}
}
@@ -48,6 +48,7 @@ import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
@@ -56,6 +57,7 @@ import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
@@ -104,9 +106,12 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
// (hashicorp/terraform-provider-aws#4378) and the Management Guide's VPC errors page quotes it.
private static final String BOOTSTRAP_ACTION_FAILED =
"On the master instance (%s), bootstrap action %d returned a non-zero return code";
// No source gives AWS's wording for these; they are Floci's.
// No source gives AWS's wording for these, nor for a core or task node's action that failed, which ends a cluster
// once "too many instances fail their bootstrap actions"; they are Floci's, the last after the primary node's.
private static final String BOOTSTRAP_ACTION_NOT_READ =
"On the master instance (%s), bootstrap action %d could not be read from %s: %s";
"On the %s instance (%s), bootstrap action %d could not be read from %s: %s";
private static final String NODE_ACTION_FAILED =
"On the %s instance (%s), bootstrap action %d returned a non-zero return code";
private static final String BOOTSTRAP_NOT_RUN = "Floci could not run the bootstrap actions: %s";
static final String BOOTSTRAP_INTERRUPTED = "Floci stopped while the cluster's bootstrap actions were running.";
// The ErrorDetail codes of an action that failed on the primary node and of one whose script it could not download,
@@ -152,8 +157,18 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
// The images of ended clusters a thread is removing. A cluster names its image until it is gone, so one
// Docker refused to remove is tried again the next time the cluster is read or stored.
private final Set<String> imagesBeingRemoved = new HashSet<>();
// A node whose actions fail runs them again once, in a fresh container (see bootstrapNode).
private static final int NODE_BOOTSTRAP_ATTEMPTS = 2;
// Each core and task node's bootstrap runs on a thread of its own, beside the primary node's, as on an instance of
// its own.
private static final Executor NODE_BOOTSTRAPS = Executors.newCachedThreadPool(
Thread.ofPlatform().daemon().name("emr-node-bootstrap-", 0).factory());
// Likewise the clusters, by account and id, whose storage a thread is removing.
private final Set<String> storageBeingRemoved = new HashSet<>();
// What one thread at a time holds, by account and cluster, to bootstrap the nodes a resize added to the cluster,
// and the clusters whose added nodes' bootstraps are running, which the cluster's end stops.
private final ConcurrentHashMap<String, Object> nodeBootstrapLocks = new ConcurrentHashMap<>();
private final Set<String> nodesBootstrapping = ConcurrentHashMap.newKeySet();
// Raised by each reset, so a step's thread from before it writes nothing back after the wipe.
private long generation;
// How many teardowns, by a reset or a shutdown, have begun: a step handed to its thread before one starts no HDFS
@@ -300,6 +315,9 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
if (cluster.getBootstrapImage() != null && !EmrClusterLifecycle.isTerminated(cluster.getState())) {
imagesInUse.add(cluster.getBootstrapImage());
}
if (!EmrClusterLifecycle.isTerminated(cluster.getState())) {
imagesInUse.addAll(cluster.getNodeBootstrapImages().values());
}
if (!EmrClusterLifecycle.isTerminated(cluster.getState())) {
clustersUp.add(cluster.getId());
}
@@ -1347,20 +1365,29 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
* is not removed again.
*/
private void releaseBootstrapImage(EmrCluster cluster) {
String image = cluster.getBootstrapImage();
if (image == null || bootstrapRunner == null || !EmrClusterLifecycle.isTerminated(cluster.getState())) {
List<String> images = new ArrayList<>(cluster.getNodeBootstrapImages().values());
images.addAll(cluster.getRetiredBootstrapImages());
if (cluster.getBootstrapImage() != null) {
images.add(cluster.getBootstrapImage());
}
if (images.isEmpty() || bootstrapRunner == null || !EmrClusterLifecycle.isTerminated(cluster.getState())) {
return;
}
String accountId = regionResolver.getAccountId();
if (stepsExecuting(cluster, accountId) || !imagesBeingRemoved.add(image)) {
if (stepsExecuting(cluster, accountId)) {
return;
}
String clusterId = cluster.getId();
String region = regionOf(cluster);
stepExecutor.execute(() -> {
boolean gone = bootstrapRunner.removeImage(image);
RequestScopes.runAs(accountId, region, () -> run(() -> bootstrapImageRemoved(clusterId, image, gone)));
});
for (String image : images) {
if (imagesBeingRemoved.add(image)) {
stepExecutor.execute(() -> {
boolean gone = bootstrapRunner.removeImage(image);
RequestScopes.runAs(accountId, region,
() -> run(() -> bootstrapImageRemoved(clusterId, image, gone)));
});
}
}
}
// A thread's removal of a cluster's image has ended: the cluster names it no more once it is gone.
@@ -1369,9 +1396,16 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
if (!gone) {
return;
}
clusterStore.get(clusterId).filter(cluster -> image.equals(cluster.getBootstrapImage())).ifPresent(cluster -> {
cluster.setBootstrapImage(null);
clusterStore.put(clusterId, cluster);
clusterStore.get(clusterId).ifPresent(cluster -> {
boolean primary = image.equals(cluster.getBootstrapImage());
if (primary) {
cluster.setBootstrapImage(null);
}
boolean node = cluster.getNodeBootstrapImages().values().removeIf(image::equals);
boolean retired = cluster.getRetiredBootstrapImages().remove(image);
if (primary || node || retired) {
clusterStore.put(clusterId, cluster);
}
});
}
@@ -1662,6 +1696,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
MetadataPlace place = metadataPlace(launch.clusterId(), launch.accountId(), launch.region(),
running.imageTemplate(), running.releaseLabel(), primary);
address = place != null ? place.address() : null;
// A node a resize added since the cluster's bootstrap runs its actions before it starts.
bootstrapAddedNodes(launch.clusterId(), launch.accountId(), launch.region());
SparkJobRunner.Storage storage = hdfs.apply(running.imageTemplate(), progress::cancelled);
running = running.onStorage(address != null ? storage.withMetadataAddress(address) : storage);
}
@@ -1739,9 +1775,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
bootstrapping.add(clusterKey(accountId, cluster.getId()));
return;
}
// "logs/<cluster-id>/node/<primary-instance-id>/bootstrap-actions/<action-number>/stdout.gz"
String logFolder = EmrServerlessSparkRunner.logFolder(cluster.getLogUri(),
cluster.getId() + "/node/" + masterInstanceId(cluster) + "/bootstrap-actions/");
String logFolder = bootstrapLogFolder(cluster, masterInstanceId(cluster));
BootstrapRunner.Bootstrap bootstrap = new BootstrapRunner.Bootstrap(cluster.getId(), accountId, region,
cluster.getReleaseLabel(), imageTemplate, dockerNetwork, instanceProfileRole(cluster, accountId),
bootstrapActions(cluster), logFolder);
@@ -1750,14 +1784,20 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
Supplier<String> releaseImage = releaseImage(cluster);
bootstrapping.add(clusterKey(accountId, cluster.getId()));
Instance primary = nodeInstance(cluster, accountId, 0, 1);
stepExecutor.execute(() -> runBootstrap(bootstrap, launch, releaseImage, primary));
// Its core and task nodes run them too, each as itself, where they run in containers of their own.
List<BootstrapNode> nodes = nodesToBootstrap(cluster, accountId);
stepExecutor.execute(() -> runBootstrap(bootstrap, launch, releaseImage, primary, nodes));
}
@Override
public void stop(EmrCluster cluster) {
// Off the service's lock, as stopping removes the container; the bootstrap reads the end itself too.
// Off the service's lock, as stopping removes the container; the bootstrap reads the end itself too. Past
// BOOTSTRAPPING only the bootstraps of the nodes a resize added may be running.
String id = cluster.getId();
stepExecutor.execute(() -> bootstrapRunner.stop(id));
if (EmrClusterLifecycle.BOOTSTRAPPING.equals(cluster.getState())
|| nodesBootstrapping.contains(clusterKey(regionResolver.getAccountId(), id))) {
stepExecutor.execute(() -> bootstrapRunner.stop(id));
}
}
}
@@ -1810,9 +1850,24 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
// on any other cluster the first step starts those it asks for then.
private void resizeNodes(EmrCluster cluster) {
if (cluster.isStorageCreated() && runsYarn(cluster)) {
Supplier<ClusterStorage.Yarn> yarn = currentYarn(cluster, regionResolver.getAccountId(), regionOf(cluster));
String accountId = regionResolver.getAccountId();
String region = regionOf(cluster);
Supplier<ClusterStorage.Yarn> yarn = currentYarn(cluster, accountId, region);
String clusterId = cluster.getId();
stepExecutor.execute(() -> clusterStorage.resize(clusterId, yarn));
stepExecutor.execute(() -> {
// A node it adds runs the cluster's bootstrap actions before it starts; one that failed them ends it.
try {
bootstrapAddedNodes(clusterId, accountId, region);
} catch (RuntimeException e) {
LOG.warnv(e, "Could not bootstrap the nodes added to EMR cluster {0}: {1}", clusterId,
e.getMessage());
return;
}
if (RequestScopes.callAs(accountId, region,
() -> call(() -> clusterStore.get(clusterId).filter(EmrService::nodesMayStart).isPresent()))) {
clusterStorage.resize(clusterId, yarn);
}
});
}
}
@@ -1853,8 +1908,10 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
private static void addNodes(EmrCluster cluster, int group, int count, boolean core,
List<ClusterStorage.Node> nodes) {
for (int ordinal = 1; ordinal <= count; ordinal++) {
nodes.add(new ClusterStorage.Node(group + "-" + ordinal,
AwsRegions.ec2PrivateIpDnsName(privateIpAddress(group, ordinal), cluster.getRegion()), core));
String id = group + "-" + ordinal;
nodes.add(new ClusterStorage.Node(id,
AwsRegions.ec2PrivateIpDnsName(privateIpAddress(group, ordinal), cluster.getRegion()), core,
cluster.getNodeBootstrapImages().get(id)));
}
}
@@ -1960,7 +2017,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
// a cluster with Hive's image, which is made first when it is not there yet, unless the cluster ended, or a reset
// removed it, before the thread ran; a failure to make it ends the cluster as one to run the bootstrap does.
private void runBootstrap(BootstrapRunner.Bootstrap bootstrap, BootstrapLaunch launch,
Supplier<String> releaseImage, Instance primary) {
Supplier<String> releaseImage, Instance primary, List<BootstrapNode> nodes) {
// A teardown since the bootstrap was handed off stops it as it does a step, before it runs or as it goes.
BooleanSupplier cancelled = () -> teardowns.get() != launch.teardownsBefore()
|| !RequestScopes.callAs(launch.accountId(), launch.region(), () -> stillBootstrapping(launch));
@@ -1968,24 +2025,39 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
String image = null;
String address = null;
boolean metadataMade = false;
List<CompletableFuture<NodeRun>> onNodes = List.of();
List<NodeRun> nodeRuns = List.of();
// Set once the primary node's actions have failed, which ends the cluster, so its nodes' stop then.
AtomicBoolean primaryFailed = new AtomicBoolean();
BooleanSupplier nodesCancelled = () -> primaryFailed.get() || cancelled.getAsBoolean();
try {
image = releaseImage != null && !cancelled.getAsBoolean() ? releaseImage.get() : null;
BootstrapRunner.Bootstrap running = image != null ? bootstrap.inImage(image) : bootstrap;
// The actions run as on the primary node, whose instance metadata they read.
MetadataPlace place = null;
if (!cancelled.getAsBoolean()) {
metadataMade = clusterStorage != null && primary != null
&& clusterStorage.metadataServed(dockerNetwork);
place = metadataPlace(running.clusterId(), running.accountId(), running.region(),
running.imageTemplate(), running.releaseLabel(), primary);
try {
image = releaseImage != null && !cancelled.getAsBoolean() ? releaseImage.get() : null;
BootstrapRunner.Bootstrap running = image != null ? bootstrap.inImage(image) : bootstrap;
// The actions run as on the primary node, whose instance metadata they read.
MetadataPlace place = null;
if (!cancelled.getAsBoolean()) {
metadataMade = clusterStorage != null && primary != null
&& clusterStorage.metadataServed(dockerNetwork);
place = metadataPlace(running.clusterId(), running.accountId(), running.region(),
running.imageTemplate(), running.releaseLabel(), primary);
}
address = place != null ? place.address() : null;
onNodes = startNodeBootstraps(running, nodes, place != null ? place.network() : null,
nodesCancelled);
outcome = bootstrapRunner.run(place != null ? running.onMetadata(place.network(), place.address())
: running, cancelled);
} catch (RuntimeException e) {
LOG.warnv(e, "The bootstrap actions of EMR cluster {0} could not run", launch.clusterId());
outcome = BootstrapRunner.Outcome.couldNotRun(e.getMessage());
}
if (outcome.image() == null && !outcome.stopped() && !onNodes.isEmpty()) {
primaryFailed.set(true);
bootstrapRunner.stop(launch.clusterId());
}
address = place != null ? place.address() : null;
outcome = bootstrapRunner.run(place != null ? running.onMetadata(place.network(), place.address())
: running, cancelled);
} catch (RuntimeException e) {
LOG.warnv(e, "The bootstrap actions of EMR cluster {0} could not run", launch.clusterId());
outcome = BootstrapRunner.Outcome.couldNotRun(e.getMessage());
} finally {
// The nodes' bootstraps end before the image they run in is let go.
nodeRuns = onNodes.stream().map(CompletableFuture::join).toList();
// An image it kept is built on this one, which Docker then keeps, so a newer one may remove it only as that
// image goes.
if (image != null) {
@@ -1997,20 +2069,263 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
}
BootstrapRunner.Outcome ended = outcome;
boolean storageMade = metadataMade;
List<NodeRun> runs = nodeRuns;
// One that ended, however, after a teardown began ends as one Floci stopped, which starts no step: the
// service's lock orders the two.
AtomicBoolean tornDownSince = new AtomicBoolean();
RequestScopes.runAs(launch.accountId(), launch.region(), () -> run(() -> {
tornDownSince.set(teardowns.get() != launch.teardownsBefore());
bootstrapEnded(bootstrap, launch, tornDownSince.get() ? BootstrapRunner.Outcome.halted() : ended,
storageMade);
storageMade, tornDownSince.get() ? List.of() : runs);
}));
// An image it committed as the teardown began goes, as no cluster starts from it.
if (tornDownSince.get() && ended.image() != null) {
bootstrapRunner.removeImage(ended.image());
// The images it committed as the teardown began go, as no cluster starts from them.
if (tornDownSince.get()) {
if (ended.image() != null) {
bootstrapRunner.removeImage(ended.image());
}
runs.stream().map(run -> run.outcome().image()).filter(Objects::nonNull)
.forEach(bootstrapRunner::removeImage);
}
}
// Under the service's lock: the images nodes' bootstraps left are the cluster's, each the one its node runs from
// where the cluster still has the node, else kept until the cluster ends, as one a resize took away while its
// bootstrap ran, so one added again in its place runs the actions again, as a new instance would.
private void recordNodeImages(EmrCluster cluster, Map<String, String> images) {
Set<String> wanted = new HashSet<>();
workerNodes(cluster).forEach(node -> wanted.add(node.id()));
images.forEach((node, image) -> {
if (!wanted.contains(node)) {
cluster.getRetiredBootstrapImages().add(image);
return;
}
String replaced = cluster.getNodeBootstrapImages().put(node, image);
if (replaced != null && !replaced.equals(image)) {
cluster.getRetiredBootstrapImages().add(replaced);
}
});
}
/** A core or task node a cluster's bootstrap actions run on: the node, the EC2 instance it is, its log folder. */
private record BootstrapNode(ClusterStorage.Node node, Instance instance, String logFolder) {}
/** How a core or task node's bootstrap ended. */
private record NodeRun(BootstrapNode node, BootstrapRunner.Outcome outcome) {}
/** Why a cluster ends: its reason's code and message. */
private record EndReason(String code, String message) {}
// "logs/<cluster-id>/node/<instance-id>/bootstrap-actions/<action-number>/stdout.gz", each node's under its own
// instance.
private static String bootstrapLogFolder(EmrCluster cluster, String instanceId) {
return EmrServerlessSparkRunner.logFolder(cluster.getLogUri(),
cluster.getId() + "/node/" + instanceId + "/bootstrap-actions/");
}
// A cluster's core and task nodes that run its bootstrap actions and have no image of their own yet: on a cluster
// whose nodes run in containers of their own (see runsYarn), none elsewhere.
private List<BootstrapNode> nodesToBootstrap(EmrCluster cluster, String accountId) {
if (!runsYarn(cluster)) {
return List.of();
}
List<BootstrapNode> nodes = new ArrayList<>();
for (ClusterStorage.Node node : workerNodes(cluster)) {
if (node.image() == null) {
int dash = node.id().indexOf('-');
Instance instance = nodeInstance(cluster, accountId, Integer.parseInt(node.id().substring(0, dash)),
Long.parseLong(node.id().substring(dash + 1)));
nodes.add(new BootstrapNode(node, instance, bootstrapLogFolder(cluster, instance.getInstanceId())));
}
}
return nodes;
}
// Each node's bootstrap, on a thread of its own, in running's image, as that node, on network where the cluster's
// relay serves its metadata.
private List<CompletableFuture<NodeRun>> startNodeBootstraps(BootstrapRunner.Bootstrap running,
List<BootstrapNode> nodes, String network,
BooleanSupplier cancelled) {
List<CompletableFuture<NodeRun>> started = new ArrayList<>();
for (BootstrapNode node : nodes) {
BootstrapRunner.Bootstrap onNode = running.onNode(node.node().id(), node.node().core() ? "CORE" : "TASK",
node.logFolder());
started.add(CompletableFuture.supplyAsync(
() -> new NodeRun(node, bootstrapNode(onNode, node.instance(), network, cancelled)),
NODE_BOOTSTRAPS));
}
return started;
}
// A node's bootstrap, at an address of its own on network, where the relay answers it as instance. One whose
// actions fail runs them again in a fresh container, as EMR "attempts to reallocate the failed instances".
private BootstrapRunner.Outcome bootstrapNode(BootstrapRunner.Bootstrap bootstrap, Instance instance,
String network, BooleanSupplier cancelled) {
BootstrapRunner.Outcome outcome = BootstrapRunner.Outcome.halted();
for (int attempt = 1; attempt <= NODE_BOOTSTRAP_ATTEMPTS && !cancelled.getAsBoolean(); attempt++) {
String address = null;
try {
address = network != null ? clusterStorage.metadataAddress(bootstrap.clusterId(), instance) : null;
outcome = bootstrapRunner.run(address != null ? bootstrap.onMetadata(network, address) : bootstrap,
cancelled);
} catch (RuntimeException e) {
LOG.warnv(e, "The bootstrap actions of node {0} of EMR cluster {1} could not run", bootstrap.node(),
bootstrap.clusterId());
outcome = BootstrapRunner.Outcome.couldNotRun(e.getMessage());
} finally {
if (address != null) {
clusterStorage.releaseMetadataAddress(address);
}
}
if (outcome.image() != null || outcome.stopped()) {
break;
}
LOG.infov("The bootstrap actions of node {0} of EMR cluster {1} failed (attempt {2})", bootstrap.node(),
bootstrap.clusterId(), attempt);
}
return outcome;
}
// The reason a cluster ends as a node's bootstrap failed, which AWS gives no words for: an action that exited with
// another code than 0, one whose script could not be read, or a bootstrap that could not run.
private static EndReason nodeFailure(NodeRun failed, BootstrapRunner.Bootstrap bootstrap) {
BootstrapRunner.Outcome outcome = failed.outcome();
String role = failed.node().node().core() ? "core" : "task";
String instance = failed.node().instance().getInstanceId();
if (outcome.exitCode() != null) {
return new EndReason(EmrClusterLifecycle.BOOTSTRAP_FAILURE,
NODE_ACTION_FAILED.formatted(role, instance, outcome.failedAction()));
}
if (outcome.failedAction() != null) {
return new EndReason(EmrClusterLifecycle.BOOTSTRAP_FAILURE, BOOTSTRAP_ACTION_NOT_READ.formatted(role,
instance, outcome.failedAction(), bootstrap.actions().get(outcome.failedAction() - 1).path(),
outcome.failure()));
}
return new EndReason(EmrClusterLifecycle.INTERNAL_ERROR, BOOTSTRAP_NOT_RUN.formatted(outcome.failure()));
}
// Removes images no cluster names, off the service's lock.
private void dropImages(String image, Collection<String> nodeImages) {
List<String> images = new ArrayList<>(nodeImages);
if (image != null) {
images.add(image);
}
for (String dropped : images) {
stepExecutor.execute(() -> bootstrapRunner.removeImage(dropped));
}
}
/**
* Runs a cluster's bootstrap actions on each of its core and task nodes that has no image of its own yet, one a
* resize added since its bootstrap, before it starts, as "If you add nodes to a running cluster, bootstrap actions
* also run on those nodes in the same way", each as at the cluster's start; and lets the images of the nodes it no
* longer has go, so one added again runs them again, as a new instance would. One whose actions fail twice ends the
* cluster, as at its start.
*/
private void bootstrapAddedNodes(String clusterId, String accountId, String region) {
if (bootstrapRunner == null) {
return;
}
synchronized (nodeBootstrapLocks.computeIfAbsent(clusterKey(accountId, clusterId), key -> new Object())) {
AddedNodes added = RequestScopes.callAs(accountId, region,
() -> call(() -> addedNodes(clusterId, accountId)));
if (added == null) {
return;
}
if (added.nodes().isEmpty()) {
return;
}
long teardown = teardowns.get();
BooleanSupplier cancelled = () -> teardowns.get() != teardown
|| !RequestScopes.callAs(accountId, region, () -> call(() -> clusterStore.get(clusterId)
.filter(EmrService::nodesMayStart).isPresent()));
String image = null;
List<NodeRun> runs;
String key = clusterKey(accountId, clusterId);
nodesBootstrapping.add(key);
try {
image = added.releaseImage() != null ? added.releaseImage().get() : null;
BootstrapRunner.Bootstrap running = image != null ? added.bootstrap().inImage(image)
: added.bootstrap();
String network = clusterStorage.metadataNetwork(clusterId, accountId, region,
EmrServerlessSparkRunner.image(running.imageTemplate(), running.releaseLabel()), dockerNetwork);
runs = startNodeBootstraps(running, added.nodes(), network, cancelled).stream()
.map(CompletableFuture::join).toList();
} catch (RuntimeException e) {
// As a bootstrap that cannot run at the cluster's start: the nodes cannot start, and the cluster ends.
LOG.warnv(e, "The bootstrap actions of the nodes added to EMR cluster {0} could not run", clusterId);
String why = e.getMessage();
runs = added.nodes().stream().map(node -> new NodeRun(node, BootstrapRunner.Outcome.couldNotRun(why)))
.toList();
} finally {
nodesBootstrapping.remove(key);
if (image != null) {
releaseImages.released(image);
}
}
List<NodeRun> ended = runs;
RequestScopes.runAs(accountId, region,
() -> run(() -> addedNodesBootstrapped(clusterId, ended, added.bootstrap())));
}
}
/** The nodes a cluster's bootstrap actions run on as a resize added them. */
private record AddedNodes(BootstrapRunner.Bootstrap bootstrap, Supplier<String> releaseImage,
List<BootstrapNode> nodes) {}
// Under the service's lock: the nodes bootstrapAddedNodes runs a cluster's bootstrap actions on; null for a cluster
// whose nodes run none of their own.
private AddedNodes addedNodes(String clusterId, String accountId) {
Optional<EmrCluster> found = clusterStore.get(clusterId).filter(EmrService::nodesMayStart);
if (found.isEmpty() || found.get().getBootstrapImage() == null || !runsYarn(found.get())) {
return null;
}
EmrCluster cluster = found.get();
// A node it no longer has keeps its image until the cluster ends, which one being decommissioned may run from.
Set<String> wanted = new HashSet<>();
workerNodes(cluster).forEach(node -> wanted.add(node.id()));
List<String> retired = cluster.getRetiredBootstrapImages();
if (cluster.getNodeBootstrapImages().entrySet().removeIf(entry -> !wanted.contains(entry.getKey())
&& retired.add(entry.getValue()))) {
clusterStore.put(clusterId, cluster);
}
BootstrapRunner.Bootstrap bootstrap = new BootstrapRunner.Bootstrap(clusterId, accountId, regionOf(cluster),
cluster.getReleaseLabel(), imageTemplate, dockerNetwork, instanceProfileRole(cluster, accountId),
bootstrapActions(cluster), null);
return new AddedNodes(bootstrap, releaseImage(cluster), nodesToBootstrap(cluster, accountId));
}
// Whether a cluster may still start nodes: not one that is ending or has ended.
private static boolean nodesMayStart(EmrCluster cluster) {
return !EmrClusterLifecycle.TERMINATING.equals(cluster.getState())
&& !EmrClusterLifecycle.isTerminated(cluster.getState());
}
// Under the service's lock: the images the added nodes' bootstraps left are the cluster's, and one whose actions
// failed twice ends it; a cluster that is gone keeps none.
private void addedNodesBootstrapped(String clusterId, List<NodeRun> runs, BootstrapRunner.Bootstrap bootstrap) {
Map<String, String> images = new LinkedHashMap<>();
NodeRun failed = null;
for (NodeRun run : runs) {
if (run.outcome().image() != null) {
images.put(run.node().node().id(), run.outcome().image());
} else if (failed == null && !run.outcome().stopped()) {
failed = run;
}
}
Optional<EmrCluster> found = clusterStore.get(clusterId);
if (found.isEmpty()) {
dropImages(null, images.values());
return;
}
EmrCluster cluster = found.get();
recordNodeImages(cluster, images);
if (failed != null && nodesMayStart(cluster)) {
EndReason reason = nodeFailure(failed, bootstrap);
lifecycle.terminate(cluster, reason.code(), reason.message(), now(), regionOf(cluster));
}
store(cluster);
}
// Whether a cluster's bootstrap may still start, or go on: one that ended, or a reset removed, is past it.
private synchronized boolean stillBootstrapping(BootstrapLaunch launch) {
return launch.launchedIn() == generation
@@ -2025,7 +2340,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
* wipes it, and a restart ends it.
*/
private void bootstrapEnded(BootstrapRunner.Bootstrap bootstrap, BootstrapLaunch launch,
BootstrapRunner.Outcome outcome, boolean storageMade) {
BootstrapRunner.Outcome outcome, boolean storageMade, List<NodeRun> nodeRuns) {
Optional<EmrCluster> current = launch.launchedIn() == generation
? findCluster(launch.clusterId()) : Optional.empty();
Optional<EmrCluster> found = current.filter(EmrService::bootstrapsInContainer);
@@ -2037,25 +2352,56 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
clusterStore.put(made.getId(), made);
releaseStorage(made);
}
if (outcome.stopped() && found.isPresent()) {
// The images the core and task nodes' bootstraps left, and the first of them whose actions failed.
Map<String, String> nodeImages = new LinkedHashMap<>();
NodeRun failedNode = null;
boolean nodeStopped = false;
for (NodeRun run : nodeRuns) {
if (run.outcome().image() != null) {
nodeImages.put(run.node().node().id(), run.outcome().image());
} else if (run.outcome().stopped()) {
nodeStopped = true;
} else if (failedNode == null) {
failedNode = run;
}
}
// A node's bootstrap stopped as the primary node's failed ends the cluster with the primary node's failure.
if ((outcome.stopped() || nodeStopped && outcome.image() != null) && found.isPresent()) {
dropImages(outcome.image(), nodeImages.values());
return;
}
bootstrapping.remove(clusterKey(launch.accountId(), launch.clusterId()));
if (found.isEmpty()) {
if (outcome.image() != null && current.isPresent()) {
// The cluster ended meanwhile: the image goes as an ended cluster's does.
current.get().setBootstrapImage(outcome.image());
if (current.isPresent() && (outcome.image() != null || !nodeImages.isEmpty())) {
// The cluster ended meanwhile: the images go as an ended cluster's do.
if (outcome.image() != null) {
current.get().setBootstrapImage(outcome.image());
}
recordNodeImages(current.get(), nodeImages);
store(current.get());
} else if (outcome.image() != null) {
stepExecutor.execute(() -> bootstrapRunner.removeImage(outcome.image()));
} else if (current.isEmpty()) {
dropImages(outcome.image(), nodeImages.values());
}
return;
}
EmrCluster cluster = found.get();
// Each node's image is the cluster's, which it runs from, or which goes as the cluster ends.
recordNodeImages(cluster, nodeImages);
String master = masterInstanceId(cluster);
String code = EmrClusterLifecycle.BOOTSTRAP_FAILURE;
String message;
List<EmrErrorDetail> errorDetails = List.of();
if (outcome.image() != null && failedNode != null) {
// A node failed where the primary node did not: the cluster ends, the primary node's image going with it.
cluster.setBootstrapImage(outcome.image());
EndReason reason = nodeFailure(failedNode, bootstrap);
lifecycle.bootstrapEnded(cluster, null, reason.code(), reason.message(), List.of(), now(),
regionOf(cluster));
store(cluster);
LOG.infov("The bootstrap actions of EMR cluster {0} failed on node {1}; it is {2}", cluster.getId(),
failedNode.node().node().id(), cluster.getState());
return;
}
if (outcome.image() != null) {
code = null;
message = null;
@@ -2066,7 +2412,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
errorDetails = List.of(bootstrapErrorDetail(BOOTSTRAP_FAILURE_PRIMARY_WITH_NON_ZERO_CODE, master,
outcome.failedAction(), outcome.exitCode(), bootstrap, message));
} else if (outcome.failedAction() != null) {
message = BOOTSTRAP_ACTION_NOT_READ.formatted(master, outcome.failedAction(),
message = BOOTSTRAP_ACTION_NOT_READ.formatted("master", master, outcome.failedAction(),
bootstrap.actions().get(outcome.failedAction() - 1).path(), outcome.failure());
errorDetails = List.of(bootstrapErrorDetail(BOOTSTRAP_FAILURE_BA_DOWNLOAD_FAILED_PRIMARY, master,
outcome.failedAction(), null, bootstrap, message));
@@ -53,6 +53,10 @@ public class EmrCluster {
private String bootstrapImage;
// Whether that image holds what a node needs to run YARN, which an image from an earlier Floci may not; Floci's own.
private boolean bootstrapImageRunsYarn;
// The image each core or task node's own bootstrap left, which it runs from, by node id, and those of the nodes the
// cluster no longer has, which one being decommissioned may still run from, until the cluster ends; Floci's own.
private Map<String, String> nodeBootstrapImages = new LinkedHashMap<>();
private List<String> retiredBootstrapImages = new ArrayList<>();
// Whether the docker runner mode has made the cluster's storage, which goes once the cluster has ended; Floci's
// own, as the API has none.
private boolean storageCreated;
@@ -187,6 +191,16 @@ public class EmrCluster {
public String getBootstrapImage() { return bootstrapImage; }
public void setBootstrapImage(String bootstrapImage) { this.bootstrapImage = bootstrapImage; }
public Map<String, String> getNodeBootstrapImages() { return nodeBootstrapImages; }
public void setNodeBootstrapImages(Map<String, String> nodeBootstrapImages) {
this.nodeBootstrapImages = nodeBootstrapImages != null ? nodeBootstrapImages : new LinkedHashMap<>();
}
public List<String> getRetiredBootstrapImages() { return retiredBootstrapImages; }
public void setRetiredBootstrapImages(List<String> retiredBootstrapImages) {
this.retiredBootstrapImages = retiredBootstrapImages != null ? retiredBootstrapImages : new ArrayList<>();
}
public boolean isBootstrapImageRunsYarn() { return bootstrapImageRunsYarn; }
public void setBootstrapImageRunsYarn(boolean bootstrapImageRunsYarn) {
this.bootstrapImageRunsYarn = bootstrapImageRunsYarn;
@@ -227,6 +227,46 @@ class EmrBootstrapRunnerTest {
verify(lifecycle, never()).commit(any(), any(), any(), any(), any());
}
@Test
void aCoreNodesBootstrapRunsInAContainerOfItsOwnAsThatNodeAndIsKeptAsItsImage() {
List<List<String>> commands = ContainerExecStubs.completeEveryExec(docker, CONTAINER, 0, "", "");
String repository = ContainerStorageHelper.dockerName(config, "emr-bootstrap");
String nodeImage = "sha256:" + "3".repeat(64);
when(docker.inspectImageCmd(repository + ":j-1-1-2").exec().getId()).thenReturn(nodeImage);
BootstrapRunner.Outcome outcome = runner.run(bootstrap(null, action("s3://bucket/bootstrap/install.sh"))
.onNode("1-2", "CORE", "s3://logs/j-1/node/i-00000000000000003/bootstrap-actions/"), () -> false);
// Apart from the primary node's, and from each other node's, with a session of its own.
assertEquals(BootstrapRunner.Outcome.succeeded(nodeImage), outcome);
verify(spec).withName(ContainerStorageHelper.dockerName(config, "emr-j-1-bootstrap-1-2"));
verify(roleCredentials).forRole("arn:aws:iam::" + ACCOUNT + ":role/emr-ec2", ACCOUNT, "j-1-1-2-bootstrap");
// Its files say which node it is.
assertEquals(List.of("env", "FLOCI_INSTANCE_ROLE=CORE", "bash", "-c", EmrServerlessSparkRunner.NODE_INFO),
commands.get(0));
verify(lifecycle).commit(eq(CONTAINER), eq(repository), eq("j-1-1-2"), eq("hadoop"), any());
assertTrue(uploaded.containsKey("logs/j-1/node/i-00000000000000003/bootstrap-actions/1/stdout.gz"),
uploaded.toString());
}
@Test
void stoppingAClustersBootstrapStopsEachOfItsNodesButNoOtherClusters() {
ContainerExecStubs.completeEveryExec(docker, CONTAINER, 0, "", "");
when(s3.getObject("bucket", "bootstrap/install.sh")).thenAnswer(read -> {
runner.stop("j-10");
runner.stop("j-1-1");
verify(lifecycle, never()).stopAndRemove(CONTAINER, null, 0);
runner.stop("j-1");
return content("#!/bin/bash\n");
});
BootstrapRunner.Outcome outcome = runner.run(bootstrap(null, action("s3://bucket/bootstrap/install.sh"))
.onNode("1-1", "CORE", null), () -> false);
assertEquals(BootstrapRunner.Outcome.halted(), outcome);
verify(lifecycle).stopAndRemove(CONTAINER, null, 0);
}
@Test
void thePrimaryNodesFilesAreWrittenBeforeTheFirstActionAndGoBeforeTheImageIsKept() {
List<List<String>> commands = ContainerExecStubs.completeEveryExec(docker, CONTAINER, 0, "", "");
@@ -255,6 +255,26 @@ class EmrClusterStorageTest {
verify(lifecycle, never()).removeIfExistsStrict(coreName);
}
@Test
void aNodeWithAnImageOfItsOwnRunsFromItAndStartsAgainWhereItRunsAnother() {
nodesStart(coreName, taskName);
runningNodes(node(coreName, "running", "sha256:core-node", CORE_HOST, true),
node(taskName, "running", IMAGE, TASK_HOST, false));
// Each from the image its own bootstrap left: the task node's is new, as a resize added it again.
ClusterStorage.Yarn ownImages = new ClusterStorage.Yarn(4096, 4).onNodes(List.of(
new ClusterStorage.Node("1-1", CORE_HOST, true, "sha256:core-node"),
new ClusterStorage.Node("2-1", TASK_HOST, false, "sha256:task-node")), 1, "s3://logs/j-1/containers/");
when(containerBuilder.newContainer("sha256:task-node")).thenReturn(spec);
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, () -> ownImages,
NOT_STOPPED);
verify(spec, never()).withName(coreName);
verify(spec).withName(taskName);
verify(containerBuilder).newContainer("sha256:task-node");
verify(containerBuilder, never()).newContainer("sha256:core-node");
}
@Test
void aNodeInAnotherImageOrStoppedStartsAgainOnItsData() {
nodesStart(coreName, taskName);
@@ -657,6 +677,30 @@ class EmrClusterStorageTest {
order.verify(lifecycle).removeVolume(coreName);
}
@Test
void aCoreNodeThatStopsWhileItLeavesStartsAgainFromTheImageItRan() {
AtomicLong clock = new AtomicLong();
EmrClusterStorage ticking = new EmrClusterStorage(lifecycle, containerBuilder, awsEnv, roleCredentials,
currentContainer, config, s3, Duration.ofSeconds(120),
() -> clock.getAndAdd(Duration.ofMinutes(30).toNanos()), Runnable::run, Duration.ZERO);
nodesStart(coreName, taskName);
ticking.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, () -> TWO_NODES,
NOT_STOPPED);
// It ran from the image its own bootstrap left.
runningNodes(node(coreName, "running", "sha256:core-node", CORE_HOST, true),
node(taskName, "running", IMAGE, TASK_HOST, false));
when(containerBuilder.newContainer("sha256:core-node")).thenReturn(spec);
ContainerExecStubs.completeEveryExec(docker, hdfsName, 1L, "", "");
when(lifecycle.probeContainer(coreName)).thenReturn(ContainerLiveness.NOT_RUNNING, ContainerLiveness.RUNNING);
clearInvocations(spec, lifecycle, containerBuilder);
ClusterStorage.Yarn taskOnly = new ClusterStorage.Yarn(4096, 4).onNodes(List.of(TASK_NODE), 1, null);
assertTimeoutPreemptively(Duration.ofSeconds(20), () -> ticking.resize("j-1", () -> taskOnly));
verify(containerBuilder).newContainer("sha256:core-node");
verify(spec).withName(coreName);
}
@Test
void aRoundThatFailsIsTriedAgainOnTheNext() {
nodesStart(coreName, taskName);
@@ -25,12 +25,17 @@ import org.mockito.InOrder;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BooleanSupplier;
import java.util.function.Function;
import static io.floci.aws.services.emr.EmrServiceFixture.ACCOUNT;
import static io.floci.aws.services.emr.EmrServiceFixture.REGION;
@@ -1606,6 +1611,256 @@ class EmrServiceContainerStepsTest {
assertEquals(List.of(cluster.getId()), bootstrapping.clusterStorage.removed);
}
@Test
void eachCoreAndTaskNodeRunsTheBootstrapActionsAsItselfBesideThePrimaryNodeAndRunsFromWhatTheyLeft() {
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
bootstrapping.clusterStorage.ownNetwork = true;
bootstrap.outcomes = ran -> BootstrapRunner.Outcome.succeeded("sha256:" + ran.name());
EmrCluster requested = bootstrapped(cluster("node-bootstraps", true, sparkStep("report", "CONTINUE")));
requested.setLogUri("s3://logs/emr/");
requested.setInstanceGroups(new ArrayList<>(List.of(group("MASTER", 1), group("CORE", 2), group("TASK", 1))));
EmrCluster cluster = bootstrapping.service.runJobFlow(requested, REGION);
String id = cluster.getId();
bootstrapping.runStepThread();
// The primary node's, and each node's as that node, in the same image, its output under its own instance.
Map<String, BootstrapRunner.Bootstrap> byNode = new HashMap<>();
bootstrap.bootstraps.forEach(ran -> byNode.put(String.valueOf(ran.node()), ran));
assertEquals(Set.of("null", "1-1", "1-2", "2-1"), byNode.keySet());
assertEquals("MASTER", byNode.get("null").instanceRole());
assertEquals("CORE", byNode.get("1-1").instanceRole());
assertEquals("CORE", byNode.get("1-2").instanceRole());
assertEquals("TASK", byNode.get("2-1").instanceRole());
assertEquals("s3://logs/emr/" + id + "/node/i-00000000000000001/bootstrap-actions/",
byNode.get("null").logFolder());
assertEquals("s3://logs/emr/" + id + "/node/i-00000000000000004/bootstrap-actions/",
byNode.get("2-1").logFolder());
assertEquals(byNode.get("null").imageTemplate(), byNode.get("2-1").imageTemplate());
assertEquals(byNode.get("null").actions(), byNode.get("1-2").actions());
EmrCluster ready = bootstrapping.service.describeCluster(id);
assertEquals("sha256:" + id, ready.getBootstrapImage());
assertEquals(Map.of("1-1", "sha256:" + id + "-1-1", "1-2", "sha256:" + id + "-1-2", "2-1",
"sha256:" + id + "-2-1"), ready.getNodeBootstrapImages());
bootstrapping.runStepThread();
// Each node runs from what its own actions left, the steps from the primary node's.
assertEquals(List.of("sha256:" + id + "-1-1", "sha256:" + id + "-1-2", "sha256:" + id + "-2-1"),
bootstrapping.clusterStorage.yarns.get(0).nodes().stream().map(ClusterStorage.Node::image).toList());
assertEquals("sha256:" + id, runner.jobs.get(0).imageTemplate());
}
@Test
void aClusterWhoseNodesRunInNoContainersOfTheirOwnRunsItsBootstrapOnThePrimaryNodeAlone() {
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
EmrCluster requested = bootstrapped(cluster("primary-bootstrap", true));
requested.setInstanceGroups(new ArrayList<>(List.of(group("MASTER", 1), group("CORE", 2))));
bootstrapping.service.runJobFlow(requested, REGION);
bootstrapping.runStepThread();
assertEquals(1, bootstrap.bootstraps.size());
assertNull(bootstrap.bootstraps.get(0).node());
}
@Test
void aNodeWhoseActionsFailRunsThemAgainInAFreshContainerAndTheClusterCarriesOn() {
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
bootstrapping.clusterStorage.ownNetwork = true;
AtomicInteger attempts = new AtomicInteger();
bootstrap.outcomes = ran -> "1-1".equals(ran.node()) && attempts.getAndIncrement() == 0
? BootstrapRunner.Outcome.actionFailed(2, 1)
: BootstrapRunner.Outcome.succeeded("sha256:" + ran.name());
EmrCluster requested = bootstrapped(cluster("node-retry", true));
requested.setInstanceGroups(new ArrayList<>(List.of(group("MASTER", 1), group("CORE", 1))));
EmrCluster cluster = bootstrapping.service.runJobFlow(requested, REGION);
bootstrapping.runStepThread();
// As EMR "attempts to reallocate the failed instances and continue".
assertEquals(2, bootstrap.bootstraps.stream().filter(ran -> "1-1".equals(ran.node())).count());
EmrCluster ready = bootstrapping.service.describeCluster(cluster.getId());
assertEquals("WAITING", ready.getState());
assertEquals(Map.of("1-1", "sha256:" + cluster.getId() + "-1-1"), ready.getNodeBootstrapImages());
}
@Test
void aNodeWhoseActionsFailTwiceEndsTheClusterInFlocisWordsAndItsImagesGo() {
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
bootstrapping.clusterStorage.ownNetwork = true;
bootstrap.outcomes = ran -> "2-1".equals(ran.node()) ? BootstrapRunner.Outcome.actionFailed(1, 3)
: BootstrapRunner.Outcome.succeeded("sha256:" + ran.name());
EmrCluster requested = bootstrapped(cluster("node-failure", true, sparkStep("report", "CONTINUE")));
requested.setInstanceGroups(new ArrayList<>(List.of(group("MASTER", 1), group("CORE", 1), group("TASK", 1))));
EmrCluster cluster = bootstrapping.service.runJobFlow(requested, REGION);
String id = cluster.getId();
bootstrapping.runStepThread();
assertEquals(2, bootstrap.bootstraps.stream().filter(ran -> "2-1".equals(ran.node())).count());
EmrCluster ended = bootstrapping.service.describeCluster(id);
assertEquals("TERMINATED_WITH_ERRORS", ended.getState());
assertEquals("BOOTSTRAP_FAILURE", ended.getStateChangeReasonCode());
assertEquals("On the task instance (i-00000000000000003), bootstrap action 1 returned a non-zero return code",
ended.getStateChangeMessage());
// No source gives an error code for a node that is not the primary.
assertEquals(List.of(), ended.getErrorDetails());
assertEquals("CANCELLED", bootstrapping.service.describeStep(id, cluster.getSteps().get(0).getId()).getState());
while (bootstrapping.stepThreadsWaiting() > 0) {
bootstrapping.runStepThread();
}
assertEquals(Set.of("sha256:" + id, "sha256:" + id + "-1-1"), Set.copyOf(bootstrap.removed));
}
@Test
void aNodeAResizeAddsRunsTheBootstrapActionsBeforeItStartsAndOneThatLeavesKeepsItsImageUntilTheClusterEnds() {
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
bootstrapping.clusterStorage.ownNetwork = true;
bootstrap.outcomes = ran -> BootstrapRunner.Outcome.succeeded("sha256:" + ran.name());
EmrCluster requested = bootstrapped(cluster("node-resize", true, sparkStep("report", "CONTINUE")));
requested.setInstanceGroups(new ArrayList<>(List.of(group("MASTER", 1), group("CORE", 1), group("TASK", 1))));
EmrCluster cluster = bootstrapping.service.runJobFlow(requested, REGION);
String id = cluster.getId();
bootstrapping.runStepThread();
bootstrapping.runStepThread();
String task = cluster.getInstanceGroups().get(2).getId();
bootstrapping.service.modifyInstanceGroups(id, REGION,
List.of(new EmrService.InstanceGroupModification(task, 2, null)));
bootstrapping.runStepThread();
// "If you add nodes to a running cluster, bootstrap actions also run on those nodes in the same way."
BootstrapRunner.Bootstrap added = bootstrap.bootstraps.get(bootstrap.bootstraps.size() - 1);
assertEquals("2-2", added.node());
assertEquals("TASK", added.instanceRole());
assertEquals("sha256:" + id + "-2-2", bootstrapping.clusterStorage.resizes.get(0).nodes().get(2).image());
bootstrapping.service.modifyInstanceGroups(id, REGION,
List.of(new EmrService.InstanceGroupModification(task, 1, null)));
bootstrapping.runStepThread();
// Added again, it would run them again, as a new instance does; being decommissioned, it may still run from
// its image, which goes as the cluster ends.
EmrCluster shrunk = bootstrapping.service.describeCluster(id);
assertFalse(shrunk.getNodeBootstrapImages().containsKey("2-2"));
assertEquals(List.of("sha256:" + id + "-2-2"), shrunk.getRetiredBootstrapImages());
assertFalse(bootstrap.removed.contains("sha256:" + id + "-2-2"));
bootstrapping.service.terminateJobFlows(List.of(id));
while (bootstrapping.stepThreadsWaiting() > 0) {
bootstrapping.runStepThread();
}
assertTrue(bootstrap.removed.contains("sha256:" + id + "-2-2"));
assertEquals(List.of(), bootstrapping.service.describeCluster(id).getRetiredBootstrapImages());
}
@Test
void aNodeAResizeTookAwayWhileItsBootstrapRanLeavesNoImageForOneAddedInItsPlace() {
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
bootstrapping.clusterStorage.ownNetwork = true;
EmrCluster requested = bootstrapped(cluster("node-gone", true, sparkStep("report", "CONTINUE")));
requested.setInstanceGroups(new ArrayList<>(List.of(group("MASTER", 1), group("CORE", 1), group("TASK", 1))));
EmrCluster cluster = bootstrapping.service.runJobFlow(requested, REGION);
String id = cluster.getId();
String task = cluster.getInstanceGroups().get(2).getId();
AtomicBoolean shrunk = new AtomicBoolean();
bootstrap.outcomes = ran -> {
if ("2-2".equals(ran.node()) && shrunk.compareAndSet(false, true)) {
bootstrapping.service.modifyInstanceGroups(id, REGION,
List.of(new EmrService.InstanceGroupModification(task, 1, null)));
}
return BootstrapRunner.Outcome.succeeded("sha256:" + ran.name());
};
bootstrapping.runStepThread();
bootstrapping.runStepThread();
bootstrapping.service.modifyInstanceGroups(id, REGION,
List.of(new EmrService.InstanceGroupModification(task, 2, null)));
bootstrapping.runStepThread();
EmrCluster now = bootstrapping.service.describeCluster(id);
assertFalse(now.getNodeBootstrapImages().containsKey("2-2"));
assertEquals(List.of("sha256:" + id + "-2-2"), now.getRetiredBootstrapImages());
}
@Test
void aBootstrapThatCannotRunForTheNodesAResizeAddsEndsTheClusterAsAtItsStart() {
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
bootstrapping.clusterStorage.ownNetwork = true;
bootstrapping.clusterStorage.metadata = true;
bootstrap.outcomes = ran -> BootstrapRunner.Outcome.succeeded("sha256:" + ran.name());
EmrCluster requested = bootstrapped(cluster("node-setup", true, sparkStep("report", "CONTINUE")));
requested.setInstanceGroups(new ArrayList<>(List.of(group("MASTER", 1), group("CORE", 1), group("TASK", 1))));
EmrCluster cluster = bootstrapping.service.runJobFlow(requested, REGION);
String id = cluster.getId();
bootstrapping.runStepThread();
bootstrapping.runStepThread();
bootstrapping.clusterStorage.metadataFailure = new IllegalStateException("The relay did not listen");
bootstrapping.service.modifyInstanceGroups(id, REGION,
List.of(new EmrService.InstanceGroupModification(cluster.getInstanceGroups().get(2).getId(), 2, null)));
bootstrapping.runStepThread();
EmrCluster ended = bootstrapping.service.describeCluster(id);
assertEquals("TERMINATED_WITH_ERRORS", ended.getState());
assertEquals("INTERNAL_ERROR", ended.getStateChangeReasonCode());
assertEquals("Floci could not run the bootstrap actions: The relay did not listen",
ended.getStateChangeMessage());
// Its nodes do not change.
assertEquals(List.of(), bootstrapping.clusterStorage.resizes);
}
@Test
void aPrimaryNodeWhoseActionsFailStopsItsNodesBootstrapsAndEndsTheClusterWithItsFailure() {
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
bootstrapping.clusterStorage.ownNetwork = true;
// A node's bootstrap ends stopped, as the stop removes its container.
bootstrap.outcomes = ran -> ran.node() == null ? BootstrapRunner.Outcome.actionFailed(1, 2)
: BootstrapRunner.Outcome.halted();
EmrCluster requested = bootstrapped(cluster("primary-failure", true));
requested.setInstanceGroups(new ArrayList<>(List.of(group("MASTER", 1), group("CORE", 2))));
EmrCluster cluster = bootstrapping.service.runJobFlow(requested, REGION);
bootstrapping.runStepThread();
assertEquals(List.of(cluster.getId()), bootstrap.stopped);
EmrCluster ended = bootstrapping.service.describeCluster(cluster.getId());
assertEquals("TERMINATED_WITH_ERRORS", ended.getState());
assertEquals("On the master instance (i-00000000000000001), bootstrap action 1 returned a non-zero return code",
ended.getStateChangeMessage());
}
@Test
void aClusterThatEndsWhileANodeAResizeAddedRunsItsBootstrapStopsIt() {
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
bootstrapping.clusterStorage.ownNetwork = true;
EmrCluster requested = bootstrapped(cluster("ends-resizing", true, sparkStep("report", "CONTINUE")));
requested.setInstanceGroups(new ArrayList<>(List.of(group("MASTER", 1), group("CORE", 1), group("TASK", 1))));
EmrCluster cluster = bootstrapping.service.runJobFlow(requested, REGION);
String id = cluster.getId();
AtomicBoolean ended = new AtomicBoolean();
bootstrap.outcomes = ran -> {
if ("2-2".equals(ran.node()) && ended.compareAndSet(false, true)) {
bootstrapping.service.terminateJobFlows(List.of(id));
// As the stop removes its container.
return BootstrapRunner.Outcome.halted();
}
return BootstrapRunner.Outcome.succeeded("sha256:" + ran.name());
};
bootstrapping.runStepThread();
bootstrapping.runStepThread();
bootstrapping.service.modifyInstanceGroups(id, REGION,
List.of(new EmrService.InstanceGroupModification(cluster.getInstanceGroups().get(2).getId(), 2, null)));
while (bootstrapping.stepThreadsWaiting() > 0) {
bootstrapping.runStepThread();
}
assertEquals(List.of(id), bootstrap.stopped);
assertEquals("TERMINATED", bootstrapping.service.describeCluster(id).getState());
assertEquals(List.of(), bootstrapping.clusterStorage.resizes);
}
@Test
void aClusterWithHiveThatEndsBeforeItsBootstrapOrStepRunsMakesNoImage() {
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
@@ -2096,11 +2351,14 @@ class EmrServiceContainerStepsTest {
* {@code outcome}, or stopped once {@link #stop} has been called for it.
*/
private static final class FakeBootstrap implements BootstrapRunner {
final List<Bootstrap> bootstraps = new ArrayList<>();
// A cluster's nodes' bootstraps run on threads of their own.
final List<Bootstrap> bootstraps = Collections.synchronizedList(new ArrayList<>());
final List<String> stopped = new ArrayList<>();
final List<String> removed = new ArrayList<>();
final List<String> removed = Collections.synchronizedList(new ArrayList<>());
final List<Set<String>> kept = new ArrayList<>();
Outcome outcome = Outcome.succeeded(IMAGE);
// How each bootstrap ends, where not as outcome says.
Function<Bootstrap, Outcome> outcomes;
Runnable whileRunning = () -> { };
// Whether Docker removes an image it is asked to.
boolean removes = true;
@@ -2112,7 +2370,7 @@ class EmrServiceContainerStepsTest {
return Outcome.halted();
}
whileRunning.run();
return outcome;
return outcomes != null ? outcomes.apply(bootstrap) : outcome;
}
@Override