feat(emr): run a cluster's Spark steps on YARN on its primary node (#7864)

A docker cluster's Spark steps ran in local mode, in one container, so a
script's own spark-submit --master yarn failed and a step's --deploy-mode
was dropped. On EMR "the primary node runs the YARN ResourceManager
service" and a core node "YARN NodeManager daemons, Hadoop MapReduce
tasks, and Spark executors".

- On a Docker network of the cluster's own, the primary node's container
  also runs a ResourceManager and a NodeManager, whose capacity is
  yarn-node-memory-mb and yarn-node-vcores.
- The node needs Spark, Python and what the bootstrap actions installed,
  so it runs from the image the steps run in: the bootstrap's, else the
  release's EMR Serverless image with its Hive image's HDFS, MapReduce
  and YARN, and Hive on a cluster with Hive. A cluster without Hive gets
  no hive, so its Hive step still says "Hive isn't installed.".
- Spark steps submit with --master yarn, keeping the step's own --master
  and --deploy-mode; a command's own spark-submit reads the same from its
  spark-defaults. Executors and a cluster-mode driver are sized for the
  NodeManager, which the cluster's spark-defaults replace, get the step's
  AWS environment, and reach Floci at its address on the cluster's
  network; a client-mode driver is reached at its container's name there.
- A YARN application's container logs go to
  <LogUri>/<cluster-id>/containers/<application>/<container>/ when a step
  ends, as a cluster-mode driver's output is there and not in the step's,
  without launch_container.sh, which holds the step's session.

A node that does not become ready leaves the last of its output in
Floci's log, as the container goes with its cluster.

YARN's Java 17 options go through JDK_JAVA_OPTIONS, which the Java 8 of
an emr-6.x image ignores.

An emr-spark-* release has no 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, and
Spark keeps the release's own. Those daemons are Hadoop 3.4.0's, where
the Release Guide lists 3.4.2 for these releases.

Clusters in a namespace the steps share or with no network stay in local
mode, as do MapReduce and Tez, and core and task instances get no
NodeManager yet.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-10 22:22:16 -06:00
1 parent ba28970a94
commit 874493c446
21 files changed
+1447 -228

No files matched your search

+59 -14
View File
@@ -69,7 +69,10 @@ duration at its default of 0, a cluster is ready, and its steps complete, before
them returns.
`CancelSteps` cancels a `PENDING` step, and a `RUNNING` one from release `emr-5.28.0`, as its API
reference says. A cancelled `RUNNING` step makes room for the next `PENDING` one. On an earlier release
reference says. A cancelled `RUNNING` step makes room for the next `PENDING` one. Its container stops, and what the
applications it started on YARN have logged goes to `containers/` (see **Output**), while an application in
`--deploy-mode cluster` runs on to its end: EMR's cancel signals the step and its descendant processes, and
"asynchronous processes are not affected", as the Management Guide puts it. On an earlier release
a `RUNNING` step answers `FAILED` with "Step is not in a cancellable state: RUNNING".
A cluster created with `Instances.KeepJobFlowAliveWhenNoSteps` set to `false` terminates after its
@@ -112,13 +115,13 @@ included; see [Step Functions: Amazon EMR tasks](step-functions.md#amazon-emr-ta
With `runner-mode` set to `docker` (`FLOCI_SERVICES_EMR_RUNNER_MODE=docker`), a step runs. Floci starts
one container per step from the cluster's release image, the one EMR Serverless's `docker` mode uses
(`public.ecr.aws/emr-serverless/spark/<release>`), and runs the step in it: a Spark step's
`spark-submit` in local mode, the container holding the driver and its executors, or a command or a
script. The cluster itself gets no container, and goes through its lifecycle as in the `immediate` mode,
but for its bootstrap actions and its storage.
`spark-submit` on the YARN its primary node runs (see **YARN**), or in local mode where it runs none, the container
holding the driver and its executors, or a command or a script. The cluster itself goes through its lifecycle as in the
`immediate` mode, but for its bootstrap actions and its primary node (see **Storage**).
* **Which steps run**: a `command-runner.jar` step whose first argument is `spark-submit`, the way the
Management Guide writes Spark steps, runs the arguments after it, without its `--master` and
`--deploy-mode`. A custom JAR step runs its `MainClass`, or else the one its manifest names, through
Management Guide writes Spark steps, runs the arguments after it, with its `--master` and `--deploy-mode` as
given where the cluster runs YARN (see **YARN**) and without them where it does not. A custom JAR step runs its `MainClass`, or else the one its manifest names, through
`spark-submit`, with the JAR and the step's `Args`; a MapReduce job it starts, such as the Management
Guide's `wordcount` of Hadoop's examples JAR, runs in local mode (see **Hadoop streaming and MapReduce**).
A `Jar` of `/usr/lib/hadoop-mapreduce/hadoop-streaming.jar`, where EMR has it, runs the image's
@@ -139,18 +142,20 @@ but for its bootstrap actions and its storage.
`script-runner.jar` step's script is fetched from S3 with the AWS CLI and the step's credentials, then
run with the step's other arguments; a path not in S3 is run as it is, a bare name from `/home/hadoop`
when a file there has it, one a former step left there included. `hadoop fs` and `hdfs dfs` reach the
cluster's HDFS (see **Storage**) and Floci's S3. A `spark-submit` they start runs in local mode on Floci's S3 with the
cluster's HDFS (see **Storage**) and Floci's S3. A `spark-submit` they start runs on the cluster's YARN, or in local
mode where it runs none, on Floci's S3 with the
cluster's `spark-defaults`, `core-site`, `spark-hive-site` and `spark-log4j2`, which Floci puts in a Spark
configuration of its own, a copy of the folder a `spark-env` export of `SPARK_CONF_DIR` names, else of the
image's, ahead of the image's EMR Serverless master; its own `--master yarn` or `--deploy-mode cluster`
fails, as there is no YARN.
image's, ahead of the image's EMR Serverless master; where the cluster runs no YARN, its own `--master yarn` or
`--deploy-mode cluster` fails.
* **Storage**: a cluster's primary node keeps its disks while the cluster lives, and so does Floci: each step's
container mounts the cluster's two Docker volumes, one at `/home/hadoop` and one at `/mnt`, so what a step leaves
there is there for the steps after it, and for steps running at the same time. What the bootstrap actions left in
`/home/hadoop` or `/mnt` comes with the image the steps run in, and Docker copies it into the volumes when the
first step starts. Every cluster runs HDFS, "best used for caching the results produced by intermediate job-flow
steps", as the Management Guide puts it: a NameNode and a DataNode on its primary node, which Floci runs in a
container of their own, `emr-<cluster-id>-hdfs`, from the release's EMR Serverless Hive image, which has HDFS
container of their own, `emr-<cluster-id>-hdfs`, from the image the cluster's steps run in where it runs YARN (see
**YARN**), else from the release's EMR Serverless Hive image, which has HDFS
where the release's image has only its client (`hive-image-template` names another), or, for an `emr-spark-*`
release, which has no Hive image, from `emr-7.5.0`'s, with their data in a third volume, one copy of each block,
and permissions off. On a cluster with Hive or HCatalog (see **Which steps run**), the same container runs Hive's
@@ -192,8 +197,32 @@ but for its bootstrap actions and its storage.
cluster"), on a state reset, and, for clusters that are gone or have ended, when the EMR service starts, unless
`reconcile-containers-on-startup` is off. A shutdown of Floci removes the HDFS containers of the clusters that are
still up, and their next step starts them again, on the data their volume keeps. `/tmp` is each container's own.
* **Hadoop streaming and MapReduce**: a step's `hadoop` command runs MapReduce in local mode, in its own JVM,
as there is no YARN: the image has MapReduce only in Spark's shaded Hadoop client, which Floci makes the
* **YARN**: on a Docker network of the cluster's own, the default, "the primary node runs the YARN ResourceManager
service", as the Management Guide puts it, and, as on a
cluster of one node, a NodeManager, both in the primary node's container, and the cluster's Spark runs on them. A
Spark step or custom JAR step submits to it, with `--master yarn` unless it names another master, and in the deploy
mode it asks for, `client` when it names none, and so does a `spark-submit` a command or script starts. In client
mode the driver stays in the step's container and its output in the step's logs, and the executors run in YARN's
containers on the node; in cluster mode the driver runs on the node too, its output in the application's container
logs (see **Output**) and only the client's in the step's.
The node needs Spark, Python and what the bootstrap actions installed, as an EMR cluster's nodes hold every
application it installs, so it 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
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
offers `yarn-node-memory-mb` and `yarn-node-vcores`, 4096 MB and 4 by default, and an executor is 1 GB and one core
and a driver 2 GB and one core, which the cluster's `spark-defaults` and a step's own options replace. A container
larger than the NodeManager offers is refused by YARN, and its step fails. Dynamic allocation is on, as it is on
EMR, through Spark's shuffle tracking: the images have no external shuffle service. Executors reach Floci's S3 at
Floci's address on the cluster's network, which Floci's container joins as for the metastore (see **Storage**), over
HTTP, which Floci serves beside HTTPS with TLS on, so no certificate is involved, with the step's AWS credentials,
and find the driver at its container's name on that network.
* **Hadoop streaming and MapReduce**: a step's `hadoop` command runs MapReduce in local mode, in its own JVM, on the
YARN clusters too (see **Known limitations**): the image has MapReduce only in Spark's shaded Hadoop client, which
Floci makes the
command's MapReduce home (`HADOOP_MAPRED_HOME`, unless a `spark-env` export names one), so it is on the
command's class path whatever `HADOOP_CLASSPATH` a command sets, and a copy of its `mapred-site.xml` sets
`mapreduce.framework.name` to `local`. This has run on the `emr-7.5.0` and `emr-7.10.0` images; on another,
@@ -390,7 +419,11 @@ but for its bootstrap actions and its storage.
`stdout.gz` and `stderr.gz` under `<LogUri>/<cluster-id>/steps/<step-id>/`, the step log folder of the
Management Guide's "Log locations" (an `s3n://` or `s3a://` `LogUri` names the same bucket). A
cancelled step's logs hold what its driver wrote until it was stopped. Logs that cannot be written,
to a bucket that does not exist say, leave the step as it ended. The `controller` and `syslog` logs
to a bucket that does not exist say, leave the step as it ended. On a cluster that runs YARN, the logs of its
applications' containers, a cluster-mode driver's output among them, go gzipped to
`<LogUri>/<cluster-id>/containers/<application>/<container>/` when a step ends, "Application container logs. The logs
for each YARN application are stored in these locations", but for the `launch_container.sh` that holds a container's
credentials. The `controller` and `syslog` logs
and the other log folders are not written, nothing is copied while a step runs (EMR copies its logs
every five minutes), and `FailureDetails` has no `LogFile`.
* **Image**: `image-template` names another image, such as a mirror or a dated tag of the release's
@@ -402,6 +435,16 @@ but for its bootstrap actions and its storage.
### Known limitations
- **One NodeManager, on the primary node.** A cluster's core and task instance groups get no NodeManager of their own,
so its executors all run on the primary node, however many instances the cluster names.
- **An `emr-spark-*` cluster's HDFS and YARN are `emr-7.5.0`'s.** The Release Guide lists both at Hadoop 3.4.2 for
`emr-spark-8.0.0` and `emr-spark-8.1.0`, and EMR Serverless publishes no image holding them, so the primary node runs
Hadoop 3.4.0's. Spark and its Hadoop client are the release's own.
- **No YARN in a network namespace the steps share, or with no network.** With `docker-network` set to `host` or
`container:<id>`, YARN's daemons would listen on every interface of the namespace, and with `none` the steps could not
reach them, so the cluster's Spark runs in local mode.
- **MapReduce and Tez in local mode.** On a cluster that runs YARN too, `hadoop-streaming`, a custom JAR's MapReduce and
Hive's Tez run in the step's container.
- **No Hive metastore service in a network namespace the steps share.** With `docker-network` set to `host` or
`container:<id>`, the primary node runs HDFS but not Hive's metastore service: Hive 3's has no setting for the
address it listens on, so it would serve its tables, and the files under them, on every interface of the
@@ -459,7 +502,9 @@ its `STARTING` event, has its events sent after the rest of that call's.
| `FLOCI_SERVICES_EMR_RUNNER_MODE` | `immediate` | `immediate` completes steps by time without running anything; `docker` runs each step in a container, after the cluster's bootstrap actions (see [Running steps](#running-steps)) |
| `FLOCI_SERVICES_EMR_DOCKER_NETWORK` | the global default | Docker network for step containers |
| `FLOCI_SERVICES_EMR_IMAGE_TEMPLATE` | `public.ecr.aws/emr-serverless/spark/%s:latest`, or `spark4/` in place of `spark/` for an `emr-spark-*` release | Image for a `docker` step, `%s` standing for the cluster's release label; a mirror sets `FLOCI_SERVICES_EMR_HIVE_IMAGE_TEMPLATE` too |
| `FLOCI_SERVICES_EMR_HIVE_IMAGE_TEMPLATE` | `public.ecr.aws/emr-serverless/hive/%s:latest` | The EMR Serverless Hive image every `docker` cluster runs its HDFS in, and a cluster with Hive takes Hive from, `%s` standing for the cluster's release label, or `emr-7.5.0` for the HDFS of an `emr-spark-*` release; see [Storage and Hive steps](#running-steps) |
| `FLOCI_SERVICES_EMR_HIVE_IMAGE_TEMPLATE` | `public.ecr.aws/emr-serverless/hive/%s:latest` | The EMR Serverless Hive image a `docker` cluster takes HDFS and YARN from, and a cluster with Hive takes Hive from, `%s` standing for the cluster's release label, or `emr-7.5.0` for the Hadoop of an `emr-spark-*` release; see [Storage and Hive steps](#running-steps) |
| `FLOCI_SERVICES_EMR_YARN_NODE_MEMORY_MB` | `4096` | The memory a `docker` cluster's NodeManager offers the YARN containers its Spark executors run in (see [Running steps](#running-steps)) |
| `FLOCI_SERVICES_EMR_YARN_NODE_VCORES` | `4` | The virtual cores it offers them |
| `FLOCI_SERVICES_EMR_RECONCILE_CONTAINERS_ON_STARTUP` | `true` | Remove the step drivers and bootstrap containers a previous run of this Floci left on the Docker daemon, and the images bootstrap actions left for clusters that are gone or have ended, when the EMR service starts; turn it off when two Floci instances share a daemon with the same port and no resource namespace |
## Release catalogue
@@ -2106,6 +2106,23 @@ public interface EmulatorConfig {
*/
Optional<String> hiveImageTemplate();
/**
* The memory, in MB, a {@code docker} cluster's NodeManager offers the YARN containers its steps' Spark
* executors run in. EMR sizes it by the instance type; Floci's node shares the machine it runs on.
*
* Env var: FLOCI_SERVICES_EMR_YARN_NODE_MEMORY_MB
*/
@WithDefault("4096")
int yarnNodeMemoryMb();
/**
* The virtual cores a {@code docker} cluster's NodeManager offers YARN's containers.
*
* Env var: FLOCI_SERVICES_EMR_YARN_NODE_VCORES
*/
@WithDefault("4")
int yarnNodeVcores();
/**
* When true, Floci removes, in the {@code docker} runner mode, every EMR step driver and bootstrap
* container a previous run of <em>this same</em> Floci left on the daemon (matched by the
@@ -2,6 +2,7 @@ package io.floci.aws.core.common.docker;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.CreateContainerCmd;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.command.InspectContainerResponse;
@@ -18,6 +19,7 @@ import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.ContainerConfig;
import com.github.dockerjava.api.model.ContainerNetwork;
import com.github.dockerjava.api.model.ExposedPort;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.HostConfig;
import com.github.dockerjava.api.model.Mount;
import com.github.dockerjava.api.model.MountType;
@@ -37,8 +39,10 @@ import org.jboss.logging.Logger;
import java.io.Closeable;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -1050,6 +1054,30 @@ public class ContainerLifecycleManager {
LOG.debugv("Connected {0} to network {1} as {2}", containerId, networkName, alias);
}
/**
* The last {@code lines} lines the container {@code containerId} wrote, standard output and error together, or as
* much of them as Docker gave within {@code timeout}; empty when it gave none. For the message of a container that
* failed, which a failure to read them should not replace, so that is only logged.
*/
public String lastLogLines(String containerId, int lines, Duration timeout) {
StringBuffer output = new StringBuffer();
ResultCallback.Adapter<Frame> reader = new ResultCallback.Adapter<>() {
@Override
public void onNext(Frame frame) {
output.append(new String(frame.getPayload(), StandardCharsets.UTF_8));
}
};
try (reader) {
dockerClient.logContainerCmd(containerId).withStdOut(true).withStdErr(true).withTail(lines).exec(reader)
.awaitCompletion(timeout.toMillis(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (IOException | RuntimeException e) {
LOG.debugv(e, "Could not read the log of container {0}: {1}", containerId, e.getMessage());
}
return output.toString().strip();
}
/**
* Disconnects the container {@code containerId} from {@code networkName} when it is on it: true once it is not,
* false when Docker kept it there.
@@ -20,17 +20,33 @@ public interface ClusterStorage {
/** Makes the volumes of {@code clusterId}'s storage, in its account and Region, when they are not there. */
void create(String clusterId, String accountId, String region);
/**
* Whether a cluster's primary node runs on a Docker network of the cluster's own with its steps on
* {@code dockerNetwork}: not on one with no network, nor in a namespace the steps share, where a service on it
* would serve every interface of the namespace.
*/
boolean ownNetwork(String dockerNetwork);
/**
* Starts {@code clusterId}'s HDFS, a NameNode and a DataNode keeping their data in a volume of their own, and,
* unless {@code hiveMetastore} is null, Hive's metastore service, in a container of {@code image} on a Docker
* network of the cluster's own, or on the host's when its steps run there, unless it is running, and returns the
* cluster's storage with them: its primary node's {@code host} name, which a step's container resolves to the
* address given, on the network given, and the metastore's URI, null in a namespace the steps share, where it
* does not run. A failure to start them is thrown, and {@link Stopped} once {@code stopped} says the step is past
* unless {@code hiveMetastore} is null, Hive's metastore service, and unless {@code yarn} is null, YARN, in a
* container of {@code image} on a Docker network of the cluster's own, or on the host's when its steps run there,
* unless it is running, and returns the cluster's storage with them: its primary node's {@code host} name, which a
* step's container resolves to the address given, on the network given, the metastore's URI, and YARN's
* ResourceManager with the address Floci has on that network, the metastore and YARN only on a network of the
* cluster's own. A failure to start them is thrown, and {@link Stopped} once {@code stopped} says the step is past
* starting, or a teardown has stopped the HDFS.
*/
SparkJobRunner.Storage hdfs(String clusterId, String accountId, String region, String host, String image,
String dockerNetwork, HiveMetastore hiveMetastore, BooleanSupplier stopped);
String dockerNetwork, HiveMetastore hiveMetastore, Yarn yarn, BooleanSupplier stopped);
/**
* Puts the logs of the YARN applications on {@code clusterId}'s primary node in {@code logFolder}, an S3 folder
* ending in a slash, each container's files gzipped in {@code <application>/<container>/}, those already there
* and unchanged left as they are. Logs that cannot be read or written leave the step as it ended, and are only
* logged.
*/
void archiveContainerLogs(String clusterId, String accountId, String region, String logFolder);
/**
* Hive's metastore service on a cluster's primary node, which reaches S3 as the cluster's EC2 instance profile's
@@ -40,6 +56,23 @@ public interface ClusterStorage {
record HiveMetastore(String role, Map<String, String> settings) {
}
/**
* YARN on a cluster's primary node: a ResourceManager, and a NodeManager offering its containers
* {@code memoryMb} of memory and {@code vcores} virtual cores, which run its steps' Spark executors, and the folder
* of the node's image holding the Hadoop its daemons run from, or null for the image's own.
*/
record Yarn(int memoryMb, int vcores, String hadoopFolder) {
Yarn(int memoryMb, int vcores) {
this(memoryMb, vcores, null);
}
/** This YARN with its daemons run from the Hadoop in {@code folder}. */
Yarn withHadoopFolder(String folder) {
return new Yarn(memoryMb, vcores, folder);
}
}
/**
* Removes {@code clusterId}'s HDFS and the volumes of its storage once it no longer needs them: true when the
* volumes are gone, false when Docker refused, so the caller can try again.
@@ -1,5 +1,6 @@
package io.floci.aws.services.emr;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.command.InspectVolumeResponse;
import com.github.dockerjava.api.command.ListVolumesResponse;
import com.github.dockerjava.api.model.Container;
@@ -8,6 +9,7 @@ import com.github.dockerjava.api.model.Network;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.config.EmulatorConfig.EcsServiceConfig.ImagePullBehavior;
import io.floci.aws.core.common.ContainerTeardown;
import io.floci.aws.core.common.S3Uri;
import io.floci.aws.core.common.docker.ContainerBuilder;
import io.floci.aws.core.common.docker.ContainerExec;
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
@@ -19,12 +21,21 @@ import io.floci.aws.services.emrserverless.EmrServerlessSparkRunner;
import io.floci.aws.services.emrserverless.SparkJobRunner;
import io.floci.aws.services.iam.model.SessionCreds;
import io.floci.aws.services.lambda.launcher.LambdaExecutionRoleCredentials;
import io.floci.aws.services.s3.S3Service;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -35,6 +46,8 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BooleanSupplier;
import java.util.function.LongSupplier;
import java.util.stream.Collectors;
import java.util.zip.GZIPOutputStream;
/**
* Keeps each EMR cluster's storage in Docker volumes, one for its primary node's {@code /home/hadoop} and one for its
@@ -76,12 +89,35 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
// image's hive.user.install.directory: the primary node puts it there first, as two sessions uploading it at once
// can leave one with a jar that changed under it, whose Tez tasks then fail to launch.
private static final String HIVE_JARS = "/tmp/hadoop/.hiveJars";
// The name Floci's own container has on a cluster's network, which it joins for the metastore service to reach it.
// The memory, in MB, and the virtual cores a cluster's NodeManager offers YARN's containers; set only on a cluster
// whose primary node runs YARN.
private static final String YARN_MEMORY_VARIABLE = "FLOCI_YARN_MEMORY_MB";
private static final String YARN_VCORES_VARIABLE = "FLOCI_YARN_VCORES";
// The folder of the image holding the Hadoop the node's daemons run from; set only when that is not the image's own.
private static final String HADOOP_FOLDER_VARIABLE = "FLOCI_HADOOP_FOLDER";
// The ResourceManager's cluster metrics on its web port, which say when the NodeManager has registered.
private static final String RESOURCE_MANAGER_METRICS = "http://127.0.0.1:8088/ws/v1/cluster/metrics";
// The java.base packages Hadoop 3.4's YARN daemons reach into, which Java 17 opens only when told, through
// JDK_JAVA_OPTIONS, which Java 9 on reads and Java 8, on which a release may run and which refuses the options
// themselves, ignores.
private static final List<String> YARN_OPENED_PACKAGES = List.of("java.lang", "java.lang.reflect",
"java.lang.invoke", "java.util", "java.util.concurrent", "java.util.regex", "java.net", "java.io",
"java.nio", "sun.nio.ch", "sun.nio.cs", "sun.security.action", "sun.util.calendar");
// Where a NodeManager keeps its containers' logs, on the node's volume, as <application>/<container>/<file>.
private static final String YARN_LOGS = "/mnt/yarn/logs";
private static final int LOG_LISTING_SECONDS = 30;
// A container's launch script holds its environment, the step's AWS session among it, so it stays on the node.
private static final String CONTAINER_LAUNCH_SCRIPT = "launch_container.sh";
// The name Floci's own container has on a cluster's network, which it joins for the metastore service and YARN's
// executors to reach it.
private static final String FLOCI_ALIAS = "floci";
// How long a cluster's HDFS and metastore may take to start, the NameNode formatted the first time, before a step
// gives up.
private static final Duration HDFS_START_TIMEOUT = Duration.ofSeconds(120);
private static final Duration HDFS_POLL_INTERVAL = Duration.ofMillis(500);
// How much of a node's output is logged when it does not become ready, and how long reading it may take.
private static final int NODE_LOG_LINES = 40;
private static final Duration NODE_LOG_READ = Duration.ofSeconds(5);
// The primary node's HDFS, started as root: its daemons log their warnings and errors to the container's output,
// which docker logs shows; its host name, FLOCI_HDFS_HOST, leads to this container's address, where the DataNode
// registers, so steps reach both by it; /mnt, its data's volume, becomes the image's user's, which runs a NameNode
@@ -93,13 +129,17 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
// its ClusterId the one its format gave it, rather than another cluster's in that namespace, the DataNode has
// joined and the NameNode has left safe mode, which on a restart waits for the blocks the volume holds, the
// folders EMR's HDFS has for steps, /tmp and the hadoop user's home, are made. With HIVE_METASTORE_VARIABLE set,
// Hive's metastore service starts too, with the image's Hadoop configuration, as Hive steps run, its settings after
// it: "Hive records metastore information in a MySQL database on the primary node's file system", kept as a Derby
// Hive's metastore service starts too, with the Hive image's Hadoop configuration, which the node's image keeps at
// HIVE_HADOOP_CONF, as Hive steps run, its settings after it: "Hive records metastore information in a MySQL database on the primary node's file system", kept as a Derby
// database in /mnt, which only the service opens, so any number of steps share it, its log in /tmp, and its
// warehouse in the HDFS, Hive's exec jar in HIVE_JARS; the cluster's core-site and hive-site, last, replace any of
// them, as on EMR's primary node. HDFS_READY then says the node is ready. A daemon that exits,
// them, as on EMR's primary node. With YARN_MEMORY_VARIABLE set, YARN starts last, as "the primary node runs the
// YARN ResourceManager service": a ResourceManager and, as on a cluster of one node, a NodeManager, which offers
// that much memory and YARN_VCORES_VARIABLE's cores to the containers it runs the steps' Spark executors in, its
// local and log folders in /mnt, Java 17 opening to both the packages they reach into, and the node is ready once
// the NodeManager has registered. HDFS_READY then says the node is ready. A daemon that exits,
// before or after, the metastore among them, ends the container, its readiness gone, so the next step starts it
// again on its data.
// again on its data. With HADOOP_FOLDER_VARIABLE set, every daemon runs from the Hadoop in that folder.
private static final String HDFS_SCRIPT = String.join("\n",
"address=$FLOCI_HDFS_BIND; [ \"$address\" != 0.0.0.0 ] || address=$(hostname -i | awk '{print $1}')",
"echo \"$address $FLOCI_HDFS_HOST\" >> /etc/hosts || exit",
@@ -122,10 +162,40 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
+ " \"<property><name>dfs.datanode.ipc.address</name>"
+ "<value>$FLOCI_HDFS_BIND:9867</value></property>\""
+ " '</configuration>' > " + HDFS_CONF + "/hdfs-site.xml",
"if [ -n \"$" + YARN_MEMORY_VARIABLE + "\" ]; then",
" printf '%s\\n' '<configuration>'" + yarnProperties(List.of(
"yarn.resourcemanager.hostname", "$FLOCI_HDFS_HOST",
"yarn.resourcemanager.bind-host", "$FLOCI_HDFS_BIND",
"yarn.nodemanager.bind-host", "$FLOCI_HDFS_BIND",
"yarn.nodemanager.resource.memory-mb", "$" + YARN_MEMORY_VARIABLE,
"yarn.nodemanager.resource.cpu-vcores", "$" + YARN_VCORES_VARIABLE,
"yarn.scheduler.minimum-allocation-mb", "256",
"yarn.scheduler.maximum-allocation-mb", "$" + YARN_MEMORY_VARIABLE,
"yarn.scheduler.maximum-allocation-vcores", "$" + YARN_VCORES_VARIABLE,
"yarn.nodemanager.vmem-check-enabled", "false",
"yarn.nodemanager.pmem-check-enabled", "false",
"yarn.nodemanager.local-dirs", "/mnt/yarn/local",
"yarn.nodemanager.log-dirs", "/mnt/yarn/logs",
"yarn.nodemanager.disk-health-checker.max-disk-utilization-per-disk-percentage", "100",
"yarn.nodemanager.aux-services", "mapreduce_shuffle"))
+ " '</configuration>' > " + HDFS_CONF + "/yarn-site.xml || exit",
" printf '%s\\n' '<configuration>'" + yarnProperties(List.of(
"yarn.scheduler.capacity.root.queues", "default",
"yarn.scheduler.capacity.root.default.capacity", "100",
"yarn.scheduler.capacity.root.default.maximum-capacity", "100",
"yarn.scheduler.capacity.maximum-am-resource-percent", "0.5"))
+ " '</configuration>' > " + HDFS_CONF + "/capacity-scheduler.xml || exit",
"fi",
"printf '%s\\n' 'log4j.rootLogger=WARN,console' 'log4j.appender.console=org.apache.log4j.ConsoleAppender'"
+ " 'log4j.appender.console.layout=org.apache.log4j.PatternLayout'"
+ " 'log4j.appender.console.layout.ConversionPattern=%d %p %c: %m%n'"
+ " > " + HDFS_CONF + "/log4j.properties",
"if [ -n \"$" + HADOOP_FOLDER_VARIABLE + "\" ]; then",
" h=$" + HADOOP_FOLDER_VARIABLE,
" export HADOOP_HOME=$h/hadoop HADOOP_COMMON_HOME=$h/hadoop HADOOP_LIBEXEC_DIR=$h/hadoop/libexec"
+ " HADOOP_HDFS_HOME=$h/hadoop-hdfs HADOOP_MAPRED_HOME=$h/hadoop-mapreduce"
+ " HADOOP_YARN_HOME=$h/hadoop-yarn PATH=$h/hadoop-hdfs/bin:$h/hadoop-yarn/bin:$h/hadoop/bin:$PATH",
"fi",
"exec setpriv --reuid=hadoop --regid=hadoop --clear-groups bash -c '"
+ "[ -d /mnt/namenode/current ] || hdfs namenode -format -nonInteractive || exit; "
+ "cid=$(sed -n \"s/^clusterID=//p\" /mnt/namenode/current/VERSION); "
@@ -147,7 +217,8 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
+ "/$(basename \"$jar\" .jar)-$(sha256sum \"$jar\" | cut -d\" \" -f1).jar || exit 1; "
+ "[ -z \"$" + HIVE_METASTORE_SITE_VARIABLE + "\" ] || mapfile -t site <<< \"$"
+ HIVE_METASTORE_SITE_VARIABLE + "\"; "
+ "cd /tmp; LOGS_DIR=/tmp/floci-hive-logs HADOOP_CONF_DIR=/etc/hadoop/conf"
+ "cd /tmp; LOGS_DIR=/tmp/floci-hive-logs HADOOP_CONF_DIR="
+ EmrServerlessSparkRunner.HIVE_HADOOP_CONF
+ " hive --service metastore -p " + HIVE_METASTORE_PORT
+ " --hiveconf fs.defaultFS=hdfs://$FLOCI_HDFS_HOST:8020 $"
+ HIVE_METASTORE_VARIABLE
@@ -160,6 +231,12 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
+ "until (exec 3<>/dev/tcp/127.0.0.1/" + HIVE_METASTORE_PORT + ") 2>/dev/null; do "
+ "[ \"$(jobs -rp | wc -l)\" = $n ] || exit 1; sleep 0.2; done; "
+ "fi; "
+ "if [ -n \"$" + YARN_MEMORY_VARIABLE + "\" ]; then "
+ "JDK_JAVA_OPTIONS=\"" + yarnOpens() + "\" yarn resourcemanager & "
+ "JDK_JAVA_OPTIONS=\"" + yarnOpens() + "\" yarn nodemanager & n=$((n + 2)); "
+ "until curl -sf -m 5 " + RESOURCE_MANAGER_METRICS + " | grep -q \"\\\"activeNodes\\\":1,\"; do "
+ "[ \"$(jobs -rp | wc -l)\" = $n ] || exit 1; sleep 0.2; done; "
+ "fi; "
+ "touch " + HDFS_READY + "; "
// Not wait -n: an emr-6.x image's bash, 4.2, does not have it.
+ "while [ \"$(jobs -rp | wc -l)\" = $n ]; do sleep 1; done; rm -f " + HDFS_READY
@@ -172,6 +249,8 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
// The metastore services this process started, by container name: the session each reaches S3 with, if any, and
// the address of Floci's it was given.
private final Map<String, MetastoreSession> sessions = new ConcurrentHashMap<>();
// For each node, the size of each container log already in S3, by its path under YARN_LOGS.
private final Map<String, Map<String, Long>> archivedLogs = new ConcurrentHashMap<>();
// The HDFS containers this process has started or found running, by name, which a reset or a shutdown removes.
private final Set<String> running = ConcurrentHashMap.newKeySet();
private final ContainerLifecycleManager lifecycleManager;
@@ -180,6 +259,7 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
private final LambdaExecutionRoleCredentials roleCredentials;
private final CurrentContainerNetworkResolver currentContainer;
private final EmulatorConfig config;
private final S3Service s3Service;
private final Duration hdfsStartTimeout;
private final LongSupplier nanoTime;
// How many teardowns, by a reset or a shutdown, have run: a step waiting for its cluster's HDFS through one stops.
@@ -188,14 +268,15 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
@Inject
public EmrClusterStorage(ContainerLifecycleManager lifecycleManager, ContainerBuilder containerBuilder,
LaunchedContainerAwsEnv awsEnv, LambdaExecutionRoleCredentials roleCredentials,
CurrentContainerNetworkResolver currentContainer, EmulatorConfig config) {
this(lifecycleManager, containerBuilder, awsEnv, roleCredentials, currentContainer, config, HDFS_START_TIMEOUT,
System::nanoTime);
CurrentContainerNetworkResolver currentContainer, EmulatorConfig config,
S3Service s3Service) {
this(lifecycleManager, containerBuilder, awsEnv, roleCredentials, currentContainer, config, s3Service,
HDFS_START_TIMEOUT, System::nanoTime);
}
EmrClusterStorage(ContainerLifecycleManager lifecycleManager, ContainerBuilder containerBuilder,
LaunchedContainerAwsEnv awsEnv, LambdaExecutionRoleCredentials roleCredentials,
CurrentContainerNetworkResolver currentContainer, EmulatorConfig config,
CurrentContainerNetworkResolver currentContainer, EmulatorConfig config, S3Service s3Service,
Duration hdfsStartTimeout, LongSupplier nanoTime) {
this.lifecycleManager = lifecycleManager;
this.containerBuilder = containerBuilder;
@@ -203,6 +284,7 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
this.roleCredentials = roleCredentials;
this.currentContainer = currentContainer;
this.config = config;
this.s3Service = s3Service;
this.hdfsStartTimeout = hdfsStartTimeout;
this.nanoTime = nanoTime;
}
@@ -222,9 +304,84 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
lifecycleManager.ensureVolume(storage.mnt(), labels);
}
@Override
public void archiveContainerLogs(String clusterId, String accountId, String region, String logFolder) {
String name = hdfsName(clusterId);
Map<String, Long> archived = archivedLogs.computeIfAbsent(name, node -> new ConcurrentHashMap<>());
// One step's end at a time for a node, so of two reading a log that is still growing the later is written last.
synchronized (archived) {
try {
S3Uri folder = S3Uri.parseAnyScheme(logFolder);
for (String log : changedLogs(name, archived)) {
archiveLog(name, log, archived, accountId, region, folder);
}
} catch (IOException | RuntimeException e) {
LOG.warnv(e, "Could not write the container logs of EMR cluster {0} to {1}: {2}", clusterId, logFolder,
e.getMessage());
}
}
}
// The node's container logs whose size is not the one already in S3, as <application>/<container>/<file>, but the
// launch scripts: only those are read from Docker, so a step's end does not bring every earlier application's again.
private List<String> changedLogs(String name, Map<String, Long> archived) {
ContainerExec.Result listed = ContainerExec.run(lifecycleManager.getDockerClient(), name,
new String[]{"find", YARN_LOGS, "-mindepth", "3", "-maxdepth", "3", "-type", "f", "-printf", "%s %P\\n"},
LOG_LISTING_SECONDS);
if (listed.exitCode() != 0) {
throw new IllegalStateException("Could not list them: " + listed.stderr());
}
List<String> changed = new ArrayList<>();
for (String line : listed.stdout().split("\n")) {
int space = line.indexOf(' ');
if (space > 0 && !line.endsWith("/" + CONTAINER_LAUNCH_SCRIPT)
&& !Long.valueOf(line.substring(0, space)).equals(archived.get(line.substring(space + 1)))) {
changed.add(line.substring(space + 1));
}
}
return changed;
}
private void archiveLog(String name, String log, Map<String, Long> archived, String accountId, String region,
S3Uri folder) throws IOException {
try (InputStream archive = lifecycleManager.getDockerClient()
.copyArchiveFromContainerCmd(name, YARN_LOGS + "/" + log).exec();
TarArchiveInputStream entries = new TarArchiveInputStream(archive)) {
TarArchiveEntry entry = entries.getNextEntry();
if (entry != null && entry.isFile()) {
putContainerLog(entries, accountId, region, folder.bucket(), folder.key() + log + ".gz");
// The size Docker gave, which the next look compares, as the log may have grown since it was listed.
archived.put(log, entry.getSize());
}
}
}
// Spooled to a file while it is gzipped, as a container's log can be larger than memory should hold.
private void putContainerLog(InputStream log, String accountId, String region, String bucket, String key)
throws IOException {
Path spool = Files.createTempFile("floci-emr-container-log", ".gz");
try {
try (OutputStream gzip = new GZIPOutputStream(Files.newOutputStream(spool))) {
log.transferTo(gzip);
}
try (InputStream gzipped = Files.newInputStream(spool)) {
EmrServerlessSparkRunner.putLog(s3Service, accountId, region, bucket, key, gzipped);
}
} finally {
Files.deleteIfExists(spool);
}
}
@Override
public boolean ownNetwork(String dockerNetwork) {
String network = network(dockerNetwork);
return !NO_NETWORK.equals(network) && !sharesNamespace(network);
}
@Override
public SparkJobRunner.Storage hdfs(String clusterId, String accountId, String region, String host, String image,
String dockerNetwork, HiveMetastore hiveMetastore, BooleanSupplier stopped) {
String dockerNetwork, HiveMetastore hiveMetastore, Yarn yarn,
BooleanSupplier stopped) {
String name = hdfsName(clusterId);
String network = network(dockerNetwork);
if (NO_NETWORK.equals(network)) {
@@ -252,16 +409,17 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
+ " runs");
}
boolean found = liveness == ContainerLiveness.RUNNING && attempt == 0
&& inStepsNamespace(name, shared ? network : name)
&& inStepsNamespace(name, shared ? network : name, imageId)
&& (shared || hiveMetastore == null || metastoreCurrent(name));
// Known before it starts, so a teardown while it starts removes it.
running.add(name);
String candidate = found ? name
: start(clusterId, accountId, region, host, imageId, dockerNetwork, hiveMetastore);
: start(clusterId, accountId, region, host, imageId, dockerNetwork, hiveMetastore, yarn);
if (awaitReady(clusterId, candidate, deadline, teardown, stopped)) {
containerId = candidate;
} else if (!found) {
stopIfStopped(clusterId, teardown, stopped);
logNodeOutput(clusterId, candidate);
throw new IllegalStateException("The HDFS of EMR cluster " + clusterId
+ " stopped before it was ready");
}
@@ -270,8 +428,11 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
return volumes(clusterId).withHdfs(host, LOOPBACK, null);
}
SparkJobRunner.Storage storage = volumes(clusterId).withHdfs(host, address(clusterId, containerId), name);
return hiveMetastore != null
? storage.withHiveMetastore("thrift://" + host + ":" + HIVE_METASTORE_PORT) : storage;
if (hiveMetastore != null) {
storage = storage.withHiveMetastore("thrift://" + host + ":" + HIVE_METASTORE_PORT);
}
// Its executors reach Floci's S3 from the node, at Floci's address on the cluster's network.
return yarn != null ? storage.withYarn(host, flociEndpointOn(name)) : storage;
}
}
@@ -296,12 +457,15 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
}
// Whether the HDFS container found running is in the namespace the steps run in, as its network mode says: the
// cluster's own network, the host's, or the same container's; one a process with another docker-network left
// goes, and starts again on its data.
private boolean inStepsNamespace(String name, String stepsNetwork) {
HostConfig hostConfig = lifecycleManager.getDockerClient().inspectContainerCmd(name).exec().getHostConfig();
// cluster's own network, the host's, or the same container's, and of the image they run in; one a process with
// another docker-network left, or one of another image, an earlier Floci's in the Hive image, goes, and starts
// again on its data.
private boolean inStepsNamespace(String name, String stepsNetwork, String imageId) {
InspectContainerResponse container = lifecycleManager.getDockerClient().inspectContainerCmd(name).exec();
HostConfig hostConfig = container.getHostConfig();
String networkMode = hostConfig != null ? hostConfig.getNetworkMode() : null;
return Objects.equals(namespaceOf(networkMode), namespaceOf(stepsNetwork));
return Objects.equals(namespaceOf(networkMode), namespaceOf(stepsNetwork))
&& imageId.equals(container.getImageId());
}
// The namespace a network mode puts a container in, the same for a container's name and its id: the network,
@@ -330,6 +494,23 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
return HOST_NETWORK.equals(network) || network != null && network.startsWith(CONTAINER_NETWORK_PREFIX);
}
// Each name and value as a Hadoop property, an argument of the script's printf in double quotes, so a value may
// name one of the container's variables.
private static String yarnProperties(List<String> namesAndValues) {
StringBuilder properties = new StringBuilder();
for (int i = 0; i < namesAndValues.size(); i += 2) {
properties.append(" \"<property><name>").append(namesAndValues.get(i)).append("</name><value>")
.append(namesAndValues.get(i + 1)).append("</value></property>\"");
}
return properties.toString();
}
// The JVM options that open YARN_OPENED_PACKAGES to Hadoop's classes.
private static String yarnOpens() {
return YARN_OPENED_PACKAGES.stream().map(name -> "--add-opens=java.base/" + name + "=ALL-UNNAMED")
.collect(Collectors.joining(" "));
}
// A cluster's HDFS container, started anew on the HDFS data its volume holds, which goes with the cluster's other
// two, with its metastore service when asked; one a restart, a stop or a daemon's exit left goes first. It runs on
// a Docker network of the cluster's own, which only the cluster's steps join, as its HDFS and its metastore serve
@@ -337,10 +518,10 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
// not. In a namespace the steps share it listens on the loopback alone, and the metastore does not run, as Hive 3's
// has no setting for the address it listens on: it would serve every interface, the host's own for one.
private String start(String clusterId, String accountId, String region, String host, String imageId,
String dockerNetwork, HiveMetastore hiveMetastore) {
String dockerNetwork, HiveMetastore hiveMetastore, Yarn yarn) {
String network = network(dockerNetwork);
if (!sharesNamespace(network)) {
return createContainer(clusterId, accountId, region, host, imageId, network, false, hiveMetastore);
return createContainer(clusterId, accountId, region, host, imageId, network, false, hiveMetastore, yarn);
}
// One namespace holds one HDFS's ports, whose daemons would answer this one's readiness and its steps: the look
// for another cluster's and this one's start go together, so two clusters' steps cannot both pass it.
@@ -350,14 +531,14 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
throw new IllegalStateException("The HDFS of EMR cluster " + clusterId + " cannot start while that of"
+ " EMR cluster " + other + " runs in the network namespace they share");
}
return createContainer(clusterId, accountId, region, host, imageId, network, true, null);
return createContainer(clusterId, accountId, region, host, imageId, network, true, null, null);
}
}
// Creates and starts the container start() decided on, in the namespace the steps share or on a network of its
// cluster's own.
private String createContainer(String clusterId, String accountId, String region, String host, String imageId,
String network, boolean shared, HiveMetastore hiveMetastore) {
String network, boolean shared, HiveMetastore hiveMetastore, Yarn yarn) {
String name = hdfsName(clusterId);
// One left stopped goes first, and a removal Docker refuses fails the start as it is, not as a name clash.
lifecycleManager.removeIfExistsStrict(name);
@@ -378,6 +559,18 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
.withDockerNetwork(Optional.of(shared ? network : name))
.withLogRotation()
.withLabels(labels(clusterId, accountId, region, HDFS_COMPONENT));
if (yarn != null) {
spec.withEnv(YARN_MEMORY_VARIABLE, String.valueOf(yarn.memoryMb()))
.withEnv(YARN_VCORES_VARIABLE, String.valueOf(yarn.vcores()));
if (yarn.hadoopFolder() != null) {
spec.withEnv(HADOOP_FOLDER_VARIABLE, yarn.hadoopFolder());
}
}
// The metastore and the executors YARN runs reach Floci, Floci on the host by its address, Floci's own
// certificate trusted when it serves TLS.
if (hiveMetastore != null || yarn != null) {
spec.withHostDockerInternalOnLinux().withJavaTrustStore();
}
String containerId;
try {
if (hiveMetastore != null) {
@@ -389,9 +582,7 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
.withEnv(HIVE_METASTORE_VARIABLE, String.join(" ",
EmrServerlessSparkRunner.hiveMetastoreSettings(region, accountId, endpoint)))
.withEnv(HIVE_METASTORE_SITE_VARIABLE, String.join("\n",
EmrServerlessSparkRunner.hiveSettings(hiveMetastore.settings())))
.withHostDockerInternalOnLinux()
.withJavaTrustStore();
EmrServerlessSparkRunner.hiveSettings(hiveMetastore.settings())));
}
containerId = lifecycleManager.createAndStart(spec.build()).containerId();
} catch (RuntimeException e) {
@@ -492,6 +683,7 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
return true;
}
if (nanoTime.getAsLong() >= deadline) {
logNodeOutput(clusterId, containerId);
throw new IllegalStateException("The HDFS of EMR cluster " + clusterId + " did not start within "
+ hdfsStartTimeout.toSeconds() + " seconds");
}
@@ -505,6 +697,12 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
return false;
}
// What a node that did not become ready last wrote, in Floci's log, as the container goes with its cluster.
private void logNodeOutput(String clusterId, String containerId) {
LOG.warnv("The primary node of EMR cluster {0} did not become ready. It last wrote:\n{1}", clusterId,
lifecycleManager.lastLogLines(containerId, NODE_LOG_LINES, NODE_LOG_READ));
}
// A teardown since the step asked for its cluster's HDFS stops the step as it would its driver, and the container
// goes, one the step started after the teardown looked too; a step past starting otherwise, by a cancel, its
// cluster's end or a teardown that has not reached the HDFS yet, stops and leaves it to the cluster's other steps.
@@ -575,6 +773,7 @@ public class EmrClusterStorage implements ClusterStorage, ContainerTeardown {
return false;
}
running.remove(name);
archivedLogs.remove(name);
return true;
}
@@ -28,15 +28,18 @@ import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Makes, on the Docker daemon, the image a release's clusters with Hive run in: its EMR Serverless image with the
* Hive, Tez, HDFS, MapReduce and YARN of its EMR Serverless Hive image, the two being built on one Hadoop and one Java.
* Makes, on the Docker daemon, the images a release's clusters run in: its EMR Serverless image with the HDFS,
* MapReduce and YARN of its EMR Serverless Hive image, which the EMR Serverless image's Hadoop client lacks, and for a
* cluster with Hive the Hive image's Hive and Tez too, the two being built on one Hadoop and one Java.
* A container of the EMR Serverless image, never started, gets the Hive image's folders streamed in from another,
* never started either, and is committed, as a bootstrap's container is. The two images ship different builds of
* {@code emr-serverless-goodies-common} under one name, so Tez keeps the Hive image's in a folder of its own, its links
* leading there, and the Hive image's Hadoop configuration, which puts Tez on the class path, goes to
* {@link EmrServerlessSparkRunner#HIVE_HADOOP_CONF}, for Hive alone. The image is named after its release, the ids of
* the two images and what is copied, so a newer pull of either, or a change to what is copied, makes another, and it is
* kept for the release's next cluster.
* kept for the release's next cluster. A release of the AWS runtime for Apache Spark has no Hive image, and another
* release's HDFS and YARN do not run on its newer Hadoop, so its image gets the whole of that release's Hadoop, in a
* folder apart, which only its primary node's daemons run from.
*/
@ApplicationScoped
public class EmrReleaseImages implements ReleaseImages {
@@ -47,9 +50,14 @@ public class EmrReleaseImages implements ReleaseImages {
private static final String EMR_SHARE = "/usr/share/aws/emr";
private static final String GOODIES = EMR_SHARE + "/serverless-goodies/lib";
private static final String HIVE_GOODIES = "serverless-goodies-hive/lib";
// What the Hive image adds: Hive and Tez, the Hadoop services the EMR Serverless image lacks, which its own
// Hadoop's client links name, their configuration and commands, EMR's s3-dist-cp among them, and the two folders
// kept apart.
// What the Hive image adds for a cluster without Hive: the Hadoop services the EMR Serverless image lacks, which its
// own Hadoop's client links name.
static final List<Copy> HADOOP_COPIES = List.of(
new Copy("/usr/lib/hadoop-hdfs", "/usr/lib"),
new Copy("/usr/lib/hadoop-mapreduce", "/usr/lib"),
new Copy("/usr/lib/hadoop-yarn", "/usr/lib"));
// What it adds for a cluster with Hive: Hive and Tez, those Hadoop services, their configuration and commands,
// EMR's s3-dist-cp among them, and the two folders kept apart.
static final List<Copy> COPIES = List.of(
new Copy("/usr/lib/hive", "/usr/lib"),
new Copy("/usr/lib/tez", "/usr/lib"),
@@ -68,6 +76,13 @@ public class EmrReleaseImages implements ReleaseImages {
new Copy("/usr/bin/s3-dist-cp", "/usr/bin"),
Copy.to("/etc/hadoop/conf", EmrServerlessSparkRunner.HIVE_HADOOP_CONF),
new Copy(GOODIES, EMR_SHARE, HIVE_GOODIES));
private static final String HADOOP_APART = "/opt";
// What it adds for a release of the AWS runtime for Apache Spark: another release's Hadoop, whole and kept apart.
static final List<Copy> HADOOP_APART_COPIES = List.of(
new Copy("/usr/lib/hadoop", HADOOP_APART),
new Copy("/usr/lib/hadoop-hdfs", HADOOP_APART),
new Copy("/usr/lib/hadoop-mapreduce", HADOOP_APART),
new Copy("/usr/lib/hadoop-yarn", HADOOP_APART));
// One making at a time for each image; another thread asking for it waits, then finds it there.
private final Map<String, Object> making = new ConcurrentHashMap<>();
@@ -86,6 +101,11 @@ public class EmrReleaseImages implements ReleaseImages {
this.config = config;
}
/** The folder of a release's image holding the Hadoop its primary node's daemons run from, or null for its own. */
static String hadoopFolder(String releaseLabel) {
return EmrServerlessSparkRunner.sparkRuntime(releaseLabel) ? HADOOP_APART : null;
}
/**
* The image's id: the image is made from the two as a container of either would run them, pulled when missing, and
* the ids their names lead to now, so a newer pull of either, which moves its name, makes another. A step gets
@@ -93,19 +113,22 @@ public class EmrReleaseImages implements ReleaseImages {
* it to a registry for an image only this daemon has.
*/
@Override
public String image(String releaseLabel, String sparkImage, String hiveImage) {
public String image(String releaseLabel, String sparkImage, String hiveImage, boolean withHive) {
List<Copy> copies = hadoopFolder(releaseLabel) != null ? HADOOP_APART_COPIES
: withHive ? COPIES : HADOOP_COPIES;
String spark = containerBuilder.resolveImage(sparkImage);
String hive = containerBuilder.resolveImage(hiveImage);
String sparkId = imageCacheService.resolveForLaunch(spark, ImagePullBehavior.PREFER_CACHED, null).imageId();
String hiveId = imageCacheService.resolveForLaunch(hive, ImagePullBehavior.PREFER_CACHED, null).imageId();
String repository = ContainerStorageHelper.dockerName(config, COMPONENT);
String tag = releaseLabel + "-" + Digests.sha256Hex(sparkId + "\n" + hiveId + "\n" + COPIES).substring(0, 12);
String tag = releaseLabel + "-" + Digests.sha256Hex(sparkId + "\n" + hiveId + "\n" + copies).substring(0, 12);
synchronized (making.computeIfAbsent(repository + ":" + tag, name -> new Object())) {
DockerClient docker = lifecycleManager.getDockerClient();
try {
return docker.inspectImageCmd(repository + ":" + tag).exec().getId();
} catch (NotFoundException e) {
LOG.infov("Making {0}:{1} for EMR clusters with Hive, from {2} and {3}", repository, tag, spark, hive);
LOG.infov("Making {0}:{1} for EMR clusters {2}, from {3} and {4}", repository, tag,
withHive ? "with Hive" : "without Hive", spark, hive);
}
String user = docker.inspectImageCmd(sparkId).exec().getConfig().getUser();
Map<String, String> labels = new LinkedHashMap<>();
@@ -118,7 +141,7 @@ public class EmrReleaseImages implements ReleaseImages {
containers.add(target);
String source = docker.createContainerCmd(hiveId).withLabels(labels).exec().getId();
containers.add(source);
for (Copy copy : COPIES) {
for (Copy copy : copies) {
RetryingTarCopier.copyStreamed(docker, target, copy.into(), copy.from(),
out -> copy(docker.copyArchiveFromContainerCmd(source, copy.from()).exec(), out, copy));
}
@@ -58,6 +58,7 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiFunction;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import java.util.function.Function;
@@ -129,6 +130,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
private final String imageTemplate;
private final String hiveImageTemplate;
private final String dockerNetwork;
// What the NodeManager of a cluster that runs YARN offers its containers.
private final ClusterStorage.Yarn nodeManager;
// The steps a thread is running, by account and id; a RUNNING container step not here was left by a restart.
private final Set<String> executing = new HashSet<>();
// Likewise the clusters a thread is bootstrapping.
@@ -248,6 +251,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
this.imageTemplate = config.services().emr().imageTemplate().orElse(null);
this.hiveImageTemplate = config.services().emr().hiveImageTemplate().orElse(null);
this.dockerNetwork = config.services().emr().dockerNetwork().orElse(null);
this.nodeManager = new ClusterStorage.Yarn(config.services().emr().yarnNodeMemoryMb(),
config.services().emr().yarnNodeVcores());
this.lifecycle = new EmrClusterLifecycle(config.services().emr().clusterStartupDelaySeconds(),
config.services().emr().stepDurationSeconds(),
config.services().emr().clusterTerminationDelaySeconds(), eventPublisher,
@@ -1458,31 +1463,36 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
}
EmrSparkSteps.HiveCommand hive = EmrSparkSteps.hive(step, cluster.getReleaseLabel(),
cluster.getApplications(), cluster.getConfigurations(), SNAPSHOT_MAPPER);
List<String> application = hive == null ? EmrSparkSteps.application(step) : null;
boolean yarn = runsYarn(cluster);
List<String> application = hive == null ? EmrSparkSteps.application(step, yarn) : null;
List<String> command = hive == null && application == null ? EmrSparkSteps.command(step) : null;
SparkJobRunner.Storage storage = null;
if ((hive != null || application != null || command != null) && clusterStorage != null) {
storage = clusterStorage.volumes(cluster.getId());
cluster.setStorageCreated(true);
}
// The image a cluster's bootstrap left, which holds what its release's does; else a cluster with Hive's,
// which the step's thread makes, or the release's.
// The image a cluster's bootstrap left, which holds what its release's does; else a cluster with Hive's or
// YARN's, which the step's thread makes, or the release's.
String image = cluster.getBootstrapImage() != null ? cluster.getBootstrapImage() : imageTemplate;
Supplier<String> releaseImage = cluster.getBootstrapImage() == null ? releaseImage(cluster) : null;
// Every EMR cluster runs HDFS on its primary node, which the step's thread starts when it is not running:
// a NameNode and a DataNode, in a container of the release's Hive image, the one with HDFS's daemons, and
// on a cluster with Hive or HCatalog its metastore service.
// a NameNode and a DataNode, on a cluster with Hive or HCatalog its metastore service, and on one that runs
// YARN a ResourceManager and a NodeManager, in a container of the image its steps run in, as an EMR
// cluster's nodes hold every application it installs, or else of the release's Hive image, the one with
// HDFS's daemons.
String clusterId = cluster.getId();
String hdfsHost = masterPrivateDnsName(cluster);
String hdfsImage = hdfsImage(cluster.getReleaseLabel());
ClusterStorage.Yarn nodeYarn = yarn
? nodeManager.withHadoopFolder(EmrReleaseImages.hadoopFolder(cluster.getReleaseLabel())) : null;
ClusterStorage.HiveMetastore hiveMetastore = EmrSparkSteps.installsHive(cluster.getReleaseLabel(),
cluster.getApplications(), SNAPSHOT_MAPPER)
? new ClusterStorage.HiveMetastore(instanceProfileRole(cluster, accountId),
EmrSparkSteps.hiveMetastoreSettings(cluster.getConfigurations(), SNAPSHOT_MAPPER))
: null;
Function<BooleanSupplier, SparkJobRunner.Storage> hdfs = storage == null ? null
: stopped -> clusterStorage.hdfs(clusterId, accountId, region, hdfsHost, hdfsImage, dockerNetwork,
hiveMetastore, stopped);
BiFunction<String, BooleanSupplier, SparkJobRunner.Storage> hdfs = storage == null ? null
: (stepImage, stopped) -> clusterStorage.hdfs(clusterId, accountId, region, hdfsHost,
nodeYarn != null ? stepImage : hdfsImage, dockerNetwork, hiveMetastore, nodeYarn, stopped);
SparkJobRunner.Job job;
if (hive != null) {
job = new SparkJobRunner.Job(SERVICE, step.getId(), accountId, region, cluster.getReleaseLabel(),
@@ -1510,7 +1520,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
StepLaunch launch = new StepLaunch(accountId, region, cluster.getId(), step.getId(), generation,
teardowns.get());
executing.add(stepKey(accountId, step.getId()));
stepExecutor.execute(() -> runStep(job, launch, releaseImage, hdfs));
String containerLogs = yarn ? EmrSparkSteps.containerLogFolder(cluster) : null;
stepExecutor.execute(() -> runStep(job, launch, releaseImage, hdfs, containerLogs));
}
@Override
@@ -1520,9 +1531,10 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
}
// A step's thread: its driver runs to its end, or the step fails at once when Floci does not run its kind. A
// cluster with Hive's image is made first, when it is not there yet, so a failure to make it fails the step.
// cluster with Hive's or YARN's image is made first, when it is not there yet, so a failure to make it fails the
// step.
private void runStep(SparkJobRunner.Job job, StepLaunch launch, Supplier<String> releaseImage,
Function<BooleanSupplier, SparkJobRunner.Storage> hdfs) {
BiFunction<String, BooleanSupplier, SparkJobRunner.Storage> hdfs, String containerLogs) {
String failure;
if (job == null) {
failure = EmrSparkSteps.NOT_RUN;
@@ -1536,7 +1548,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
// a cancel, its cluster's end or a reset has passed does not start, so it makes none.
if (job.storage() != null && !progress.cancelled()) {
clusterStorage.create(launch.clusterId(), launch.accountId(), launch.region());
running = running.onStorage(hdfs.apply(progress::cancelled));
running = running.onStorage(hdfs.apply(running.imageTemplate(), progress::cancelled));
}
outcome = sparkRunner.run(running, progress);
} catch (ClusterStorage.Stopped e) {
@@ -1559,9 +1571,21 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
clusterStorage.remove(launch.clusterId());
}
if (outcome.stopped()) {
// A cancelled step's cluster-mode driver wrote only to its application's logs, which go in S3 before its
// cluster's storage can; one that never ran has none, and Floci's own teardown leaves them on the node.
if (containerLogs != null && progress.driverStarted && teardowns.get() == launch.teardownsBefore()) {
clusterStorage.archiveContainerLogs(launch.clusterId(), launch.accountId(), launch.region(),
containerLogs);
}
RequestScopes.runAs(launch.accountId(), launch.region(), () -> run(() -> driverStopped(launch)));
return;
}
// Before the step ends, so its cluster-mode driver's output is there once it has: only the client's is in
// its own stdout and stderr, as on EMR.
if (containerLogs != null && outcome.failure() == null) {
clusterStorage.archiveContainerLogs(launch.clusterId(), launch.accountId(), launch.region(),
containerLogs);
}
failure = failureOf(job, outcome);
}
// A teardown since the step was handed off ends it as it does a driver, whatever it ran to: ending it now
@@ -1613,20 +1637,37 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
}
/**
* What makes, on the thread that needs it, the image a cluster that installs Hive starts from, its release's EMR
* Serverless image with its EMR Serverless Hive image's Hive, and returns the image's id: an EMR cluster's nodes
* hold every application it installs, so its bootstrap actions and steps all run in it. Null for a cluster
* without Hive, which starts from the release's EMR Serverless image.
* What makes, on the thread that needs it, the image a cluster that installs Hive, or runs YARN, starts from, its
* release's EMR Serverless image with its EMR Serverless Hive image's HDFS, MapReduce and YARN, and Hive for a
* cluster with Hive, and returns the image's id: an EMR cluster's nodes hold every application it installs, so its
* bootstrap actions, its steps and its primary node's YARN all run in it. A release of the AWS runtime for Apache
* Spark has no EMR Serverless Hive image, so {@link #SPARK_RUNTIME_HDFS_RELEASE}'s gives its Hadoop. Null for a
* cluster with neither, which starts from the release's EMR Serverless image.
*/
private Supplier<String> releaseImage(EmrCluster cluster) {
if (releaseImages == null
|| !EmrSparkSteps.installsHive(cluster.getReleaseLabel(), cluster.getApplications(), SNAPSHOT_MAPPER)) {
if (releaseImages == null) {
return null;
}
boolean withHive = EmrSparkSteps.installsHive(cluster.getReleaseLabel(), cluster.getApplications(),
SNAPSHOT_MAPPER);
if (!withHive && !runsYarn(cluster)) {
return null;
}
String release = cluster.getReleaseLabel();
String spark = EmrServerlessSparkRunner.image(imageTemplate, release);
String hive = EmrServerlessSparkRunner.image(hiveImageTemplate, release, SparkJobRunner.Engine.HIVE);
return () -> releaseImages.image(release, spark, hive);
String hive = hdfsImage(release);
return () -> releaseImages.image(release, spark, hive, withHive);
}
/**
* Whether a cluster's primary node runs YARN, which its steps' Spark runs on: "the primary node runs the YARN
* ResourceManager service", and a core node "YARN NodeManager daemons, Hadoop MapReduce tasks, and Spark executors".
* It does on a network of the cluster's own, as its metastore does. A cluster bootstrapped by an earlier Floci runs
* from an image that may hold no YARN, so it keeps to local mode, its HDFS in the release's Hive image, as it did.
*/
private boolean runsYarn(EmrCluster cluster) {
return releaseImages != null && clusterStorage != null && clusterStorage.ownNetwork(dockerNetwork)
&& (cluster.getBootstrapImage() == null || cluster.isBootstrapImageRunsYarn());
}
/**
@@ -1725,6 +1766,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
if (outcome.image() != null) {
code = null;
message = null;
// Asked before the image is the cluster's, while it says only that the release's image made this one.
cluster.setBootstrapImageRunsYarn(runsYarn(cluster));
} else if (outcome.exitCode() != null) {
message = BOOTSTRAP_ACTION_FAILED.formatted(master, outcome.failedAction());
} else if (outcome.failedAction() != null) {
@@ -1768,6 +1811,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
private final class StepProgress implements SparkJobRunner.Progress {
private final StepLaunch launch;
// Whether the step's driver has started, so it may have left an application's logs on the cluster's nodes.
private volatile boolean driverStarted;
StepProgress(StepLaunch launch) {
this.launch = launch;
@@ -1776,6 +1821,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
@Override
public void started() {
// The step has been RUNNING since it started; the driver's start changes nothing a caller sees.
driverStarted = true;
}
@Override
@@ -38,7 +38,7 @@ final class EmrSparkSteps {
private static final String COMMAND_RUNNER = "command-runner.jar";
private static final String SCRIPT_RUNNER = "script-runner.jar";
private static final String SPARK_SUBMIT = "spark-submit";
// Local mode is Floci's, so a step's own master and deploy mode are dropped.
// Local mode is Floci's, so a step's own master and deploy mode are dropped, unless its cluster runs YARN.
private static final Set<String> DROPPED_OPTIONS = Set.of("--master", "--deploy-mode");
// spark-submit's options that take no value (SparkSubmitOptionParser's switches); every other takes one.
private static final Set<String> SWITCHES = Set.of("--help", "-h", "--supervise", "--usage-error", "--verbose",
@@ -115,12 +115,13 @@ final class EmrSparkSteps {
/**
* What follows Floci's own settings on {@code spark-submit}'s command line for {@code step}, or null for
* a step Floci does not run. For {@code command-runner.jar spark-submit ...}, the arguments after
* {@code spark-submit}, without its {@code --master} and {@code --deploy-mode}: options come before the
* application, so one after it is the application's own and kept. For a custom JAR, its main class, if
* {@code spark-submit}, without its {@code --master} and {@code --deploy-mode} unless its cluster runs YARN
* ({@code onYarn}), where they hold as on EMR: options come before the application, so one after it is the
* application's own and kept. For a custom JAR, its main class, if
* the step names one (otherwise {@code spark-submit} reads the JAR's manifest), the JAR and the step's
* arguments. A JAR EMR has in {@code /usr/lib/hadoop-mapreduce} is the image's copy of it.
*/
static List<String> application(EmrStep step) {
static List<String> application(EmrStep step, boolean onYarn) {
String jar = step.getJar();
if (jar == null || jar.isBlank() || named(jar, SCRIPT_RUNNER)) {
return null;
@@ -128,7 +129,8 @@ final class EmrSparkSteps {
List<String> args = step.getArgs() != null ? step.getArgs() : List.of();
if (named(jar, COMMAND_RUNNER)) {
return !args.isEmpty() && named(args.getFirst(), SPARK_SUBMIT)
? withoutMasterOrDeployMode(args.subList(1, args.size())) : null;
? onYarn ? List.copyOf(args.subList(1, args.size()))
: withoutMasterOrDeployMode(args.subList(1, args.size())) : null;
}
List<String> application = new ArrayList<>();
if (step.getMainClass() != null && !step.getMainClass().isBlank()) {
@@ -243,6 +245,15 @@ final class EmrSparkSteps {
return false;
}
/**
* The S3 folder its YARN applications' logs go to, or null when a cluster has no {@code LogUri}: the Management
* Guide's {@code /cluster-id/containers}, "Application container logs. The logs for each YARN application are
* stored in these locations".
*/
static String containerLogFolder(EmrCluster cluster) {
return EmrServerlessSparkRunner.logFolder(cluster.getLogUri(), cluster.getId() + "/containers/");
}
/**
* The S3 folder a step's logs go to, or null when its cluster has no {@code LogUri}: "If a value is not
* provided, logs are not created". The Management Guide's "Log locations" puts step logs at
@@ -1,15 +1,18 @@
package io.floci.aws.services.emr;
/**
* The images a cluster with Hive runs in, in the EMR {@code docker} runner mode: one per release, its EMR
* Serverless image with its EMR Serverless Hive image's Hive added, as an EMR cluster's nodes hold every
* application it installs. {@link EmrReleaseImages} is the Docker implementation, and a test supplies its own.
* The images a cluster runs in, in the EMR {@code docker} runner mode: two per release, its EMR Serverless image with
* its EMR Serverless Hive image's HDFS, MapReduce and YARN added, and for a cluster with Hive its Hive too, as an EMR
* cluster's nodes hold every application it installs; a release of the AWS runtime for Apache Spark, which has no Hive
* image, has one, with the Hadoop of another release's kept apart. {@link EmrReleaseImages} is the Docker implementation,
* and a test supplies its own.
*/
public interface ReleaseImages {
/**
* The id of the image of {@code releaseLabel} made of {@code sparkImage} and {@code hiveImage}, made first when the
* Docker daemon does not have it, which may take as long as pulling the two; a failure is thrown.
* The id of the image of {@code releaseLabel} made of {@code sparkImage} and {@code hiveImage}, with Hive or with
* Hadoop's services alone, made first when the Docker daemon does not have it, which may take as long as pulling
* the two; a failure is thrown.
*/
String image(String releaseLabel, String sparkImage, String hiveImage);
String image(String releaseLabel, String sparkImage, String hiveImage, boolean withHive);
}
@@ -51,6 +51,8 @@ public class EmrCluster {
// its steps run in; Floci's own, as the API has neither.
private boolean bootstrapInContainer;
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;
// 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;
@@ -180,6 +182,11 @@ public class EmrCluster {
public String getBootstrapImage() { return bootstrapImage; }
public void setBootstrapImage(String bootstrapImage) { this.bootstrapImage = bootstrapImage; }
public boolean isBootstrapImageRunsYarn() { return bootstrapImageRunsYarn; }
public void setBootstrapImageRunsYarn(boolean bootstrapImageRunsYarn) {
this.bootstrapImageRunsYarn = bootstrapImageRunsYarn;
}
public boolean isStorageCreated() { return storageCreated; }
public void setStorageCreated(boolean storageCreated) { this.storageCreated = storageCreated; }
@@ -44,6 +44,7 @@ import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
@@ -140,7 +141,8 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
"export SPARK_CONF_DIR=\"$conf\"");
// On a cluster, the hadoop command, and MapReduce in a step's spark-submit, get its HDFS and Floci's S3 too,
// through a copy of its Hadoop configuration (the image's, or the folder a spark-env export names), links
// followed, whose core-site.xml takes in the original's through Hadoop's XInclude, whatever its XML, then
// followed, whose core-site.xml takes in the original's through Hadoop's XInclude, whatever its XML, by a name
// relative to the folder, which Spark ships to YARN's containers on a cluster that runs it, then
// HADOOP_SITE_VARIABLE's properties, which win (see hadoopSite), and whose mapred-site.xml runs MapReduce in local
// mode the same way (see mapredSite). The cluster's hadoop-log4j lines follow the log4j.properties, on a line of
// their own, a later key winning, and its hadoop-env exports start the hadoop-env.sh the hadoop command reads,
@@ -158,7 +160,7 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
" include=",
" if [ -f \"$hadoop_conf/$1\" ]; then",
" mv \"$hadoop_conf/$1\" \"$hadoop_conf/floci-original-$1\"",
" include=\"<xi:include href=\\\"$hadoop_conf/floci-original-$1\\\"/>\"",
" include=\"<xi:include href=\\\"floci-original-$1\\\"/>\"",
" fi",
" printf '%s\\n' '<configuration xmlns:xi=\"http://www.w3.org/2001/XInclude\">' \"$include\" \"$2\""
+ " '</configuration>' > \"$hadoop_conf/$1\"",
@@ -348,7 +350,13 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
job.service(), job.runId(), job.accountId(), job.region()));
// The deployment that started the driver, which removeLeftoverDrivers() goes by.
labels.put(ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config));
String endpoint = awsEnv.flociEndpoint();
// A step on its cluster's YARN, whose executors run on the primary node, reaches Floci at Floci's address on
// the cluster's network, which its container joins too, and its executors get its AWS environment.
boolean onYarn = onYarn(job);
String endpoint = onYarn ? job.storage().flociEndpoint() : awsEnv.flociEndpoint();
List<String> executorEnvironment = onYarn
? awsEnv.sdkBaselineEnv(job.region(), Optional.empty(), endpoint, credentials, job.accountId())
: List.of();
List<Archive> archives = archives(job);
ContainerBuilder.Builder container = containerBuilder.newContainer(launchImage(job))
.withName(ContainerStorageHelper.dockerName(config, job.service() + "-" + job.runId()))
@@ -372,11 +380,11 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
List<String> sparkSubmit = job.sparkLog4j2().isEmpty() && job.storage() == null
? List.of(SPARK_SUBMIT) : List.of("/bin/bash", "-c", SPARK_CONF_WRAPPER, "floci", SPARK_SUBMIT);
container.withEntrypoint(unpackingFirst(archives, sparkSubmit))
.withCmd(sparkSubmitArguments(job, endpoint));
.withCmd(sparkSubmitArguments(job, endpoint, executorEnvironment));
} else {
container.withEntrypoint(unpackingFirst(archives, List.of("/bin/bash", "-c", COMMAND_WRAPPER, "floci")))
.withCmd(job.command())
.withEnv(SPARK_DEFAULTS_VARIABLE, sparkDefaultsFile(job, endpoint));
.withEnv(SPARK_DEFAULTS_VARIABLE, sparkDefaultsFile(job, endpoint, executorEnvironment));
}
if (!job.sparkLog4j2().isEmpty()) {
container.withEnv(SPARK_LOG4J2_VARIABLE, sparkLog4j2File(job));
@@ -410,8 +418,11 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
.build();
String containerId = lifecycleManager.create(spec);
launch.started(containerId);
// A cluster's HDFS is on a network of its own, which only its steps join.
if (job.storage() != null && job.storage().hdfsNetwork() != null) {
// A cluster's HDFS is on a network of its own, which only its steps join; on YARN the executors there reach
// the driver at the name its container has on it.
if (onYarn) {
lifecycleManager.ensureConnected(containerId, job.storage().hdfsNetwork(), driverHost(job));
} else if (job.storage() != null && job.storage().hdfsNetwork() != null) {
lifecycleManager.connectToNetwork(containerId, job.storage().hdfsNetwork());
}
// A stop, a reset or a shutdown while the image was pulled, the trust store copied or the archives put
@@ -555,6 +566,13 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
});
}
/** Puts one gzipped log, read from {@code gzipped}, at {@code key} in {@code bucket}, as {@code accountId}. */
public static void putLog(S3Service s3Service, String accountId, String region, String bucket, String key,
InputStream gzipped) {
RequestScopes.runAs(accountId, region,
() -> s3Service.putObjectFromStream(bucket, key, gzipped, GZIP, Map.of()));
}
/**
* The image a release's Spark runs use: {@code imageTemplate}, with {@code %s} standing for the release
* label, or, when it is null, the release's public EMR Serverless image.
@@ -703,8 +721,14 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
}
}
/** {@link #sparkSubmitArguments(Job, String, List)} for a job whose executors run in its driver's JVM. */
static List<String> sparkSubmitArguments(Job job, String flociEndpoint) {
return sparkSubmitArguments(job, flociEndpoint, List.of());
}
/**
* {@code spark-submit}'s arguments: local mode, S3A on Floci's S3 for {@code s3://} and {@code s3a://}
* {@code spark-submit}'s arguments: local mode, or YARN for a step on its cluster's (see {@link #yarnSettings}),
* S3A on Floci's S3 for {@code s3://} and {@code s3a://}
* paths, the cluster's HDFS for {@code hdfs://} paths and those without a scheme on a step, then the run's
* {@code spark-defaults} and its own options, which win over what comes before them, then its
* application and that application's arguments. Before release 7.10.0
@@ -712,24 +736,29 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
* are committed through commit data the writer keeps in memory, without which EMR's committer finds
* none and a write is silently lost.
*/
static List<String> sparkSubmitArguments(Job job, String flociEndpoint) {
List<String> arguments = new ArrayList<>(List.of("--master", "local[*]"));
for (SparkSetting setting : sparkSettings(job, flociEndpoint)) {
static List<String> sparkSubmitArguments(Job job, String flociEndpoint, List<String> executorEnvironment) {
List<String> arguments = new ArrayList<>(List.of("--master", master(job)));
for (SparkSetting setting : sparkSettings(job, flociEndpoint, executorEnvironment)) {
conf(arguments, setting.key(), setting.value());
}
arguments.addAll(job.application());
return arguments;
}
/** {@link #sparkDefaultsFile(Job, String, List)} for a job whose executors run in its driver's JVM. */
static String sparkDefaultsFile(Job job, String flociEndpoint) {
return sparkDefaultsFile(job, flociEndpoint, List.of());
}
/**
* The {@code spark-defaults.conf} lines a command's own {@code spark-submit} runs with: local mode, then
* The {@code spark-defaults.conf} lines a command's own {@code spark-submit} runs with: local mode, or YARN, then
* the settings {@link #sparkSubmitArguments} passes, a later line winning over an earlier one, and the
* submit's own options over them all. Spark reads the file as a {@code Properties} file, so each
* key and value is escaped for it, to reach Spark as the job gave it.
*/
static String sparkDefaultsFile(Job job, String flociEndpoint) {
StringBuilder file = new StringBuilder("spark.master local[*]");
for (SparkSetting setting : sparkSettings(job, flociEndpoint)) {
static String sparkDefaultsFile(Job job, String flociEndpoint, List<String> executorEnvironment) {
StringBuilder file = new StringBuilder("spark.master " + master(job));
for (SparkSetting setting : sparkSettings(job, flociEndpoint, executorEnvironment)) {
file.append('\n').append(propertiesEscaped(setting.key(), true)).append(' ')
.append(propertiesEscaped(String.valueOf(setting.value()), false));
}
@@ -983,7 +1012,7 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
// in HDFS only through it. On a cluster with Hive or HCatalog, Spark's Hive client uses the cluster's metastore
// too, as the Glue Data Catalog is the one to pick "when you require a persistent Hive metastore or a Hive
// metastore shared by different clusters"; a spark-hive-site naming its client factory still wins.
private static List<SparkSetting> sparkSettings(Job job, String flociEndpoint) {
private static List<SparkSetting> sparkSettings(Job job, String flociEndpoint, List<String> executorEnvironment) {
List<SparkSetting> hadoop = new ArrayList<>(hadoopSettings(job, flociEndpoint));
List<SparkSetting> hdfs = hdfsSettings(job.storage());
hadoop.addAll(hdfs);
@@ -998,10 +1027,52 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
if (job.storage() != null) {
settings.add(FILE_SYSTEM_CHECKPOINTS);
}
if (onYarn(job)) {
settings.addAll(yarnSettings(job, executorEnvironment));
}
job.sparkDefaults().forEach((key, value) -> settings.add(new SparkSetting(key, value)));
return settings;
}
/** Whether a job is a step on its cluster's YARN, which its primary node runs. */
static boolean onYarn(Job job) {
return job.storage() != null && job.storage().resourceManager() != null;
}
private static String master(Job job) {
return onYarn(job) ? "yarn" : "local[*]";
}
// The name a step's container has on its cluster's network, which a client-mode driver is reached at.
static String driverHost(Job job) {
return job.runId().toLowerCase(Locale.ROOT);
}
// A step's Spark on its cluster's YARN: the ResourceManager on the primary node; Spark's jars from the node's image,
// which is the step's; executors and a cluster-mode driver sized for the NodeManager rather than the image's 14 GB
// ("determined by the core and task instance types" on EMR), which the cluster's spark-defaults and the step's own
// options replace; a client-mode driver reached at the container's name on the cluster's network; and the step's
// AWS environment for each executor and a cluster-mode driver, as its container has it.
private static List<SparkSetting> yarnSettings(Job job, List<String> executorEnvironment) {
List<SparkSetting> settings = new ArrayList<>(List.of(
new SparkSetting("spark.hadoop.yarn.resourcemanager.hostname", job.storage().resourceManager()),
new SparkSetting("spark.yarn.jars", "local:/usr/lib/spark/jars/*"),
new SparkSetting("spark.executor.memory", "1g"),
new SparkSetting("spark.executor.cores", "1"),
new SparkSetting("spark.driver.memory", "2g"),
new SparkSetting("spark.driver.cores", "1"),
new SparkSetting("spark.driver.host", driverHost(job)),
new SparkSetting("spark.driver.bindAddress", "0.0.0.0")));
for (String variable : executorEnvironment) {
int equals = variable.indexOf('=');
String name = variable.substring(0, equals);
String value = variable.substring(equals + 1);
settings.add(new SparkSetting("spark.executorEnv." + name, value));
settings.add(new SparkSetting("spark.yarn.appMasterEnv." + name, value));
}
return settings;
}
private record SparkSetting(String key, String value) {
}
@@ -115,7 +115,7 @@ public interface SparkJobRunner {
* the Hive metastore service on that node, or null.
*/
record Storage(String home, String mnt, String hdfsHost, String hdfsAddress, String hdfsNetwork,
String hiveMetastore) {
String hiveMetastore, String resourceManager, String flociEndpoint) {
/**
* The component label of an EMR cluster's HDFS container, which carries its service's labels as a driver
@@ -125,17 +125,25 @@ public interface SparkJobRunner {
/** A cluster's volumes, before its HDFS runs. */
public Storage(String home, String mnt) {
this(home, mnt, null, null, null, null);
this(home, mnt, null, null, null, null, null, null);
}
/** This storage, its HDFS's NameNode on {@code host}, at {@code address} on {@code network}. */
public Storage withHdfs(String host, String address, String network) {
return new Storage(home, mnt, host, address, network, hiveMetastore);
return new Storage(home, mnt, host, address, network, hiveMetastore, resourceManager, flociEndpoint);
}
/** This storage, its Hive metastore service at {@code uri}. */
public Storage withHiveMetastore(String uri) {
return new Storage(home, mnt, hdfsHost, hdfsAddress, hdfsNetwork, uri);
return new Storage(home, mnt, hdfsHost, hdfsAddress, hdfsNetwork, uri, resourceManager, flociEndpoint);
}
/**
* This storage, YARN's ResourceManager on {@code host}, its executors reaching Floci at {@code flociEndpoint},
* Floci's address on the HDFS's network.
*/
public Storage withYarn(String host, String flociEndpoint) {
return new Storage(home, mnt, hdfsHost, hdfsAddress, hdfsNetwork, hiveMetastore, host, flociEndpoint);
}
}
+2
View File
@@ -629,6 +629,8 @@ floci:
# docker-network: floci-network
# image-template: "registry.internal/emr-serverless/spark/%s:20250425" # %s = the release label
# hive-image-template: "registry.internal/emr-serverless/hive/%s:20250425" # every cluster's HDFS, and Hive
yarn-node-memory-mb: 4096 # memory a cluster's NodeManager offers its YARN containers
yarn-node-vcores: 4 # virtual cores it offers them
# Remove the step drivers a previous run of this deployment left on the daemon, and the images
# bootstrap actions left for clusters that are gone or have ended, when the EMR service starts.
# Scoped to this deployment's own containers and images.
@@ -0,0 +1,77 @@
package io.floci.aws.core.common.docker;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.LogContainerCmd;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.StreamType;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.services.lambda.launcher.ImageCacheService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.time.Duration;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class ContainerLifecycleManagerLastLogLinesTest {
private static final Duration TIMEOUT = Duration.ofSeconds(5);
@Mock
private DockerClient dockerClient;
@Mock
private ImageCacheService imageCacheService;
@Mock
private ContainerDetector containerDetector;
@Mock
private EmulatorConfig config;
private final LogContainerCmd logs = mock(LogContainerCmd.class, RETURNS_SELF);
private ContainerLifecycleManager manager;
@BeforeEach
void setUp() {
manager = new ContainerLifecycleManager(dockerClient, imageCacheService, containerDetector, config);
when(dockerClient.logContainerCmd("c1")).thenReturn(logs);
}
@Test
void readsTheLastLinesOfBothStreams() {
when(logs.exec(any())).thenAnswer(reading -> {
ResultCallback.Adapter<Frame> reader = reading.getArgument(0);
reader.onNext(new Frame(StreamType.STDOUT, "one\n".getBytes(UTF_8)));
reader.onNext(new Frame(StreamType.STDERR, "two\n".getBytes(UTF_8)));
reader.onComplete();
return reader;
});
assertEquals("one\ntwo", manager.lastLogLines("c1", 40, TIMEOUT));
verify(logs).withStdOut(true);
verify(logs).withStdErr(true);
verify(logs).withTail(40);
}
@Test
void aLogDockerCannotGiveIsEmptyRatherThanAFailure() {
when(logs.exec(any())).thenThrow(new NotFoundException("gone"));
assertEquals("", manager.lastLogLines("c1", 40, TIMEOUT));
}
}
@@ -1,6 +1,7 @@
package io.floci.aws.services.emr;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CopyArchiveFromContainerCmd;
import com.github.dockerjava.api.command.ExecCreateCmd;
import com.github.dockerjava.api.command.InspectContainerCmd;
import com.github.dockerjava.api.command.InspectContainerResponse;
@@ -11,6 +12,7 @@ import com.github.dockerjava.api.command.ListVolumesCmd;
import com.github.dockerjava.api.command.ListVolumesResponse;
import com.github.dockerjava.api.exception.ConflictException;
import com.github.dockerjava.api.exception.DockerException;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.ContainerHostConfig;
import com.github.dockerjava.api.model.HostConfig;
@@ -30,11 +32,19 @@ import io.floci.aws.services.emrserverless.SparkJobRunner;
import io.floci.aws.services.iam.model.SessionCreds;
import io.floci.aws.services.lambda.launcher.ImageCacheService;
import io.floci.aws.services.lambda.launcher.LambdaExecutionRoleCredentials;
import io.floci.aws.services.s3.S3Service;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.Duration;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -51,7 +61,11 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BooleanSupplier;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
@@ -91,8 +105,9 @@ class EmrClusterStorageTest {
private final LaunchedContainerAwsEnv awsEnv = mock(LaunchedContainerAwsEnv.class);
private final LambdaExecutionRoleCredentials roleCredentials = mock(LambdaExecutionRoleCredentials.class);
private final CurrentContainerNetworkResolver currentContainer = mock(CurrentContainerNetworkResolver.class);
private final S3Service s3 = mock(S3Service.class);
private final EmrClusterStorage storage = new EmrClusterStorage(lifecycle, containerBuilder, awsEnv,
roleCredentials, currentContainer, config);
roleCredentials, currentContainer, config, s3);
private final String hdfsName = ContainerStorageHelper.dockerName(config, "emr-j-1-hdfs");
@BeforeEach
@@ -121,7 +136,7 @@ class EmrClusterStorageTest {
List<List<String>> looks = ContainerExecStubs.completeEveryExec(docker, "c-1", List.of(1L, 0L), "", "");
SparkJobRunner.Storage started = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE,
"floci-network", null, NOT_STOPPED);
"floci-network", null, null, NOT_STOPPED);
SparkJobRunner.Storage volumes = storage.volumes("j-1");
assertEquals(volumes.withHdfs(HOST, "172.18.0.5", hdfsName), started);
@@ -205,7 +220,7 @@ class EmrClusterStorageTest {
ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", "");
SparkJobRunner.Storage started = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE,
"host", null, NOT_STOPPED);
"host", null, null, NOT_STOPPED);
assertEquals("127.0.0.1", started.hdfsAddress());
// Steps share the host's network with it, so they join no other.
@@ -221,7 +236,7 @@ class EmrClusterStorageTest {
when(lifecycle.probeContainer("c-1")).thenReturn(ContainerLiveness.RUNNING);
ContainerExecStubs.completeEveryExec(docker, "c-1", 0L, "", "");
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "host", null, NOT_STOPPED);
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "host", null, null, NOT_STOPPED);
// The host's other interfaces would otherwise serve its files, without permissions, to anyone reaching them.
verify(spec).withEnv("FLOCI_HDFS_BIND", "127.0.0.1");
@@ -237,7 +252,7 @@ class EmrClusterStorageTest {
when(lifecycle.probeContainer("c-2")).thenReturn(ContainerLiveness.RUNNING);
ContainerExecStubs.completeEveryExec(docker, "c-2", 0L, "", "");
SparkJobRunner.Storage started = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, null, null,
SparkJobRunner.Storage started = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, null, null, null,
NOT_STOPPED);
// Docker joins a container placed in another's namespace to no other network, so its steps reach it there.
@@ -248,6 +263,234 @@ class EmrClusterStorageTest {
verify(lifecycle, never()).ensureNetwork(anyString(), any());
}
@Test
void aClusterThatRunsYarnHasItsPrimaryNodeRunAResourceManagerAndANodeManagerAfterItsHdfs() {
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING);
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-7", Map.of()));
when(lifecycle.probeContainer("c-7")).thenReturn(ContainerLiveness.RUNNING);
when(lifecycle.resolveContainerNetworkIp("c-7", hdfsName)).thenReturn("172.18.0.8");
ContainerExecStubs.completeEveryExec(docker, "c-7", 0L, "", "");
// Floci on the host, reached at the host's address.
when(awsEnv.flociEndpoint(false)).thenReturn("http://host.docker.internal:4566");
SparkJobRunner.Storage started = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE,
"floci-network", null, new ClusterStorage.Yarn(4096, 4), NOT_STOPPED);
// The steps' Spark submits to the ResourceManager on the primary node, its executors reaching Floci there.
assertEquals(HOST, started.resourceManager());
assertEquals("http://host.docker.internal:4566", started.flociEndpoint());
verify(spec).withEnv("FLOCI_YARN_MEMORY_MB", "4096");
verify(spec).withEnv("FLOCI_YARN_VCORES", "4");
verify(spec, never()).withEnv(eq("FLOCI_HADOOP_FOLDER"), any());
verify(spec).withHostDockerInternalOnLinux();
verify(spec).withJavaTrustStore();
verify(spec, never()).withEmbeddedDns();
// Its configuration names the primary node, listens where HDFS does and offers what it was given.
verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains(String.join(" ",
"\"<property><name>yarn.resourcemanager.hostname</name><value>$FLOCI_HDFS_HOST</value></property>\"",
"\"<property><name>yarn.resourcemanager.bind-host</name><value>$FLOCI_HDFS_BIND</value></property>\"",
"\"<property><name>yarn.nodemanager.bind-host</name><value>$FLOCI_HDFS_BIND</value></property>\"",
"\"<property><name>yarn.nodemanager.resource.memory-mb</name>"
+ "<value>$FLOCI_YARN_MEMORY_MB</value></property>\"",
"\"<property><name>yarn.nodemanager.resource.cpu-vcores</name>"
+ "<value>$FLOCI_YARN_VCORES</value></property>\""))
// Each daemon through a variable Java 8, which refuses these options, ignores.
&& Pattern.compile("JDK_JAVA_OPTIONS=\"--add-opens=java\\.base/java\\.lang=ALL-UNNAMED[^\"]*\""
+ " yarn resourcemanager & "
+ "JDK_JAVA_OPTIONS=\"--add-opens=java\\.base/java\\.lang=ALL-UNNAMED[^\"]*\""
+ " yarn nodemanager &").matcher(entrypoint.get(2)).find()));
// Ready once the NodeManager has registered, and the node gone if either daemon exits while starting.
verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains(
"yarn nodemanager & n=$((n + 2)); "
+ "until curl -sf -m 5 http://127.0.0.1:8088/ws/v1/cluster/metrics"
+ " | grep -q \"\\\"activeNodes\\\":1,\"; do "
+ "[ \"$(jobs -rp | wc -l)\" = $n ] || exit 1; sleep 0.2; done; fi;"
+ " touch /tmp/floci-hdfs-ready")));
}
@Test
void aNodeWhoseImageKeepsItsHadoopApartRunsEveryDaemonFromIt() {
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING);
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-9", Map.of()));
when(lifecycle.probeContainer("c-9")).thenReturn(ContainerLiveness.RUNNING);
when(lifecycle.resolveContainerNetworkIp("c-9", hdfsName)).thenReturn("172.18.0.9");
ContainerExecStubs.completeEveryExec(docker, "c-9", 0L, "", "");
when(awsEnv.flociEndpoint(false)).thenReturn("http://host.docker.internal:4566");
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null,
new ClusterStorage.Yarn(4096, 4, "/opt"), NOT_STOPPED);
verify(spec).withEnv("FLOCI_HADOOP_FOLDER", "/opt");
// Its homes and commands, before the daemons start as the image's user, who keeps the environment.
verify(spec).withEntrypoint(argThat(entrypoint -> {
String script = entrypoint.get(2);
int export = script.indexOf("export HADOOP_HOME=$h/hadoop HADOOP_COMMON_HOME=$h/hadoop"
+ " HADOOP_LIBEXEC_DIR=$h/hadoop/libexec HADOOP_HDFS_HOME=$h/hadoop-hdfs"
+ " HADOOP_MAPRED_HOME=$h/hadoop-mapreduce HADOOP_YARN_HOME=$h/hadoop-yarn"
+ " PATH=$h/hadoop-hdfs/bin:$h/hadoop-yarn/bin:$h/hadoop/bin:$PATH");
return script.contains(" h=$FLOCI_HADOOP_FOLDER") && export > 0 && export < script.indexOf("exec setpriv");
}));
}
@Test
void aClusterThatDoesNotRunYarnHasNoResourceManager() {
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING);
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-8", Map.of()));
when(lifecycle.probeContainer("c-8")).thenReturn(ContainerLiveness.RUNNING);
when(lifecycle.resolveContainerNetworkIp("c-8", hdfsName)).thenReturn("172.18.0.9");
ContainerExecStubs.completeEveryExec(docker, "c-8", 0L, "", "");
SparkJobRunner.Storage started = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE,
"floci-network", null, null, NOT_STOPPED);
assertNull(started.resourceManager());
assertNull(started.flociEndpoint());
verify(spec, never()).withEnv(eq("FLOCI_YARN_MEMORY_MB"), anyString());
verify(spec, never()).withHostDockerInternalOnLinux();
}
@Test
void aPrimaryNodeHasANetworkOfItsOwnUnlessItsStepsHaveNoneOrShareANamespace() {
when(containerBuilder.resolveDockerNetwork(Optional.of("host"))).thenReturn(Optional.of("host"));
when(containerBuilder.resolveDockerNetwork(Optional.of("container:floci")))
.thenReturn(Optional.of("container:floci"));
when(containerBuilder.resolveDockerNetwork(Optional.of("none"))).thenReturn(Optional.of("none"));
assertTrue(storage.ownNetwork("floci-network"));
assertFalse(storage.ownNetwork("host"));
assertFalse(storage.ownNetwork("container:floci"));
assertFalse(storage.ownNetwork("none"));
}
@Test
void aPrimaryNodeFoundRunningInAnotherImageThanItsStepsStartsAgain() {
// An earlier Floci's, from the Hive image, before the node ran in the steps' image.
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.RUNNING);
runningOn(hdfsName, hdfsName);
when(docker.inspectContainerCmd(hdfsName).exec().getImageId()).thenReturn("sha256:hive-image");
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-9", Map.of()));
when(lifecycle.probeContainer("c-9")).thenReturn(ContainerLiveness.RUNNING);
when(lifecycle.resolveContainerNetworkIp("c-9", hdfsName)).thenReturn("172.18.0.10");
ContainerExecStubs.completeEveryExec(docker, "c-9", 0L, "", "");
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, null, NOT_STOPPED);
verify(lifecycle).removeIfExistsStrict(hdfsName);
verify(lifecycle).createAndStart(any());
}
@Test
void aNodesContainerLogsGoToTheirS3FolderGzippedOnceEachAndNeverALaunchScript() throws IOException {
String container = "application_1_0001/container_1_0001_01_000001/";
nodeLogs(Map.of(container + "stdout", "Pi is roughly 3.14",
container + "launch_container.sh", "export AWS_SECRET_ACCESS_KEY=secret"));
List<String> put = new ArrayList<>();
when(s3.putObjectFromStream(eq("logs"), anyString(), any(), eq("application/x-gzip"), any()))
.thenAnswer(putting -> {
try (InputStream gzipped = new GZIPInputStream(putting.<InputStream>getArgument(2))) {
put.add(putting.getArgument(1) + "=" + new String(gzipped.readAllBytes(), UTF_8));
}
return null;
});
storage.archiveContainerLogs("j-1", "123456789012", "us-east-1", "s3://logs/emr/j-1/containers/");
storage.archiveContainerLogs("j-1", "123456789012", "us-east-1", "s3://logs/emr/j-1/containers/");
String key = "emr/j-1/containers/application_1_0001/container_1_0001_01_000001/stdout.gz=";
assertEquals(List.of(key + "Pi is roughly 3.14"), put);
verify(docker, never()).copyArchiveFromContainerCmd(hdfsName, "/mnt/yarn/logs/" + container + "launch_container.sh");
// A log that has grown goes again.
nodeLogs(Map.of(container + "stdout", "Pi is roughly 3.1415"));
storage.archiveContainerLogs("j-1", "123456789012", "us-east-1", "s3://logs/emr/j-1/containers/");
assertEquals(List.of(key + "Pi is roughly 3.14", key + "Pi is roughly 3.1415"), put);
}
@Test
void aStepsEndReadsOnlyTheLogsThatChangedAndListsThemWithTheirSizes() throws IOException {
String earlier = "application_1_0001/container_1_0001_01_000001/stdout";
String later = "application_1_0002/container_1_0002_01_000001/stdout";
List<List<String>> listings = nodeLogs(Map.of(earlier, "one"));
storage.archiveContainerLogs("j-1", "123456789012", "us-east-1", "s3://logs/j-1/containers/");
assertEquals(List.of(List.of("find", "/mnt/yarn/logs", "-mindepth", "3", "-maxdepth", "3", "-type", "f", "-printf",
"%s %P\\n")), listings);
nodeLogs(Map.of(earlier, "one", later, "two"));
storage.archiveContainerLogs("j-1", "123456789012", "us-east-1", "s3://logs/j-1/containers/");
verify(docker).copyArchiveFromContainerCmd(hdfsName, "/mnt/yarn/logs/" + earlier);
verify(docker).copyArchiveFromContainerCmd(hdfsName, "/mnt/yarn/logs/" + later);
verify(s3, times(2)).putObjectFromStream(anyString(), anyString(), any(), anyString(), any());
}
@Test
void twoStepsEndingAtOnceArchiveANodesLogsOneAfterTheOther() throws Exception {
nodeLogs(Map.of("application_1_0001/container_1_0001_01_000001/stdout", "older"));
CountDownLatch uploading = new CountDownLatch(1);
CountDownLatch finish = new CountDownLatch(1);
when(s3.putObjectFromStream(anyString(), anyString(), any(), anyString(), any())).thenAnswer(putting -> {
uploading.countDown();
assertTrue(finish.await(10, TimeUnit.SECONDS));
return null;
});
AtomicReference<Thread> second = new AtomicReference<>();
ExecutorService steps = Executors.newFixedThreadPool(2);
try {
Future<?> first = steps.submit(() -> storage.archiveContainerLogs("j-1", "123456789012", "us-east-1",
"s3://logs/j-1/containers/"));
assertTrue(uploading.await(10, TimeUnit.SECONDS));
Future<?> later = steps.submit(() -> {
second.set(Thread.currentThread());
storage.archiveContainerLogs("j-1", "123456789012", "us-east-1", "s3://logs/j-1/containers/");
});
awaitBlocked(second);
finish.countDown();
first.get(10, TimeUnit.SECONDS);
later.get(10, TimeUnit.SECONDS);
} finally {
finish.countDown();
steps.shutdownNow();
}
}
@Test
void aRemovedNodesContainerLogsAreForgotten() throws IOException {
nodeLogs(Map.of("application_1_0001/container_1_0001_01_000001/stdout", "out"));
storage.archiveContainerLogs("j-1", "123456789012", "us-east-1", "s3://logs/j-1/containers/");
storage.remove("j-1");
storage.archiveContainerLogs("j-1", "123456789012", "us-east-1", "s3://logs/j-1/containers/");
verify(s3, times(2)).putObjectFromStream(anyString(), anyString(), any(), anyString(), any());
}
@Test
void containerLogsThatCannotBeListedLeaveTheStepAsItEnded() {
// What it listed before it failed is not to be trusted to be all there is, or to be there at all.
String log = "application_1_0001/container_1_0001_01_000001/stdout";
ContainerExecStubs.completeEveryExec(docker, hdfsName, 1L, "3 " + log + "\n", "find: no such folder");
assertDoesNotThrow(() -> storage.archiveContainerLogs("j-1", "123456789012", "us-east-1",
"s3://logs/emr/j-1/containers/"));
verify(docker, never()).copyArchiveFromContainerCmd(hdfsName, "/mnt/yarn/logs/" + log);
}
@Test
void containerLogsThatCannotBeReadLeaveTheStepAsItEnded() {
String log = "application_1_0001/container_1_0001_01_000001/stdout";
ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "3 " + log + "\n", "");
when(docker.copyArchiveFromContainerCmd(hdfsName, "/mnt/yarn/logs/" + log)).thenThrow(new NotFoundException("gone"));
assertDoesNotThrow(() -> storage.archiveContainerLogs("j-1", "123456789012", "us-east-1",
"s3://logs/emr/j-1/containers/"));
verify(s3, never()).putObjectFromStream(anyString(), anyString(), any(), anyString(), any());
}
@Test
void aClusterWithHivesPrimaryNodeRunsItsMetastoreServiceToo() {
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING);
@@ -266,7 +509,7 @@ class EmrClusterStorageTest {
SparkJobRunner.Storage started = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE,
"floci-network",
new ClusterStorage.HiveMetastore("arn:aws:iam::123456789012:role/EMR_EC2_DefaultRole", Map.of()),
new ClusterStorage.HiveMetastore("arn:aws:iam::123456789012:role/EMR_EC2_DefaultRole", Map.of()), null,
NOT_STOPPED);
assertEquals("thrift://ip-10-0-0-1.ec2.internal:9083", started.hiveMetastore());
@@ -287,11 +530,11 @@ class EmrClusterStorageTest {
+ "jar=$(ls /usr/lib/hive/lib/hive-exec-[0-9]*.jar | head -1); hdfs dfs -put -f \"$jar\" "
+ "/tmp/hadoop/.hiveJars/$(basename \"$jar\" .jar)"
+ "-$(sha256sum \"$jar\" | cut -d\" \" -f1).jar")));
// With the image's Hadoop configuration, as Hive steps run; in a folder Derby can write its log in; its
// With the Hive image's Hadoop configuration, as Hive steps run; in a folder Derby can write its log in; its
// database on the primary node's own volume, its warehouse in the HDFS, ready only once it listens, and the
// node gone if it exits while starting.
verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.get(2).contains(
"cd /tmp; LOGS_DIR=/tmp/floci-hive-logs HADOOP_CONF_DIR=/etc/hadoop/conf"
"cd /tmp; LOGS_DIR=/tmp/floci-hive-logs HADOOP_CONF_DIR=/etc/hadoop/conf.hive"
+ " hive --service metastore -p 9083"
+ " --hiveconf fs.defaultFS=hdfs://$FLOCI_HDFS_HOST:8020 $FLOCI_HIVE_METASTORE"
+ " --hiveconf \"javax.jdo.option.ConnectionURL=jdbc:derby:;"
@@ -301,7 +544,7 @@ class EmrClusterStorageTest {
+ " \"${site[@]}\" & n=$((n + 1));")
&& entrypoint.get(2).contains("until (exec 3<>/dev/tcp/127.0.0.1/9083) 2>/dev/null; do "
+ "[ \"$(jobs -rp | wc -l)\" = $n ] || exit 1; sleep 0.2; done; "
+ "fi; touch /tmp/floci-hdfs-ready")));
+ "fi; if [ -n \"$FLOCI_YARN_MEMORY_MB\" ]; then")));
// The session goes with the container.
storage.remove("j-1");
@@ -322,12 +565,12 @@ class EmrClusterStorageTest {
when(lifecycle.probeContainer("c-8")).thenReturn(ContainerLiveness.RUNNING);
when(lifecycle.resolveContainerNetworkIp("c-8", hdfsName)).thenReturn("172.18.0.10");
ContainerExecStubs.completeEveryExec(docker, "c-8", 0L, "", "");
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", metastore, NOT_STOPPED);
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", metastore, null, NOT_STOPPED);
storage.stopManagedContainers();
verify(roleCredentials).unregister("123456789012", "ASIAONE");
assertThrows(IllegalStateException.class, () -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE,
"floci-network", metastore, NOT_STOPPED));
"floci-network", metastore, null, NOT_STOPPED));
verify(roleCredentials).unregister("123456789012", "ASIATWO");
}
@@ -349,10 +592,10 @@ class EmrClusterStorageTest {
when(lifecycle.resolveContainerNetworkIp("c-9", hdfsName)).thenReturn("172.18.0.11");
ContainerExecStubs.completeEveryExec(docker, "c-8", 0L, "", "");
ContainerExecStubs.completeEveryExec(docker, "c-9", 0L, "", "");
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", metastore, NOT_STOPPED);
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", metastore, null, NOT_STOPPED);
// Its metastore exited, which ended the container; the cluster's next step starts it again.
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", metastore, NOT_STOPPED);
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", metastore, null, NOT_STOPPED);
verify(roleCredentials).unregister("123456789012", "ASIAONE");
verify(roleCredentials, never()).unregister("123456789012", "ASIATWO");
@@ -370,7 +613,7 @@ class EmrClusterStorageTest {
when(lifecycle.probeContainer("c-8")).thenReturn(ContainerLiveness.RUNNING);
when(lifecycle.resolveContainerNetworkIp("c-8", hdfsName)).thenReturn("172.18.0.10");
ContainerExecStubs.completeEveryExec(docker, "c-8", 0L, "", "");
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", metastore, NOT_STOPPED);
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", metastore, null, NOT_STOPPED);
doThrow(new IllegalStateException("Failed to remove container " + hdfsName)).doNothing()
.when(lifecycle).removeIfExistsStrict(hdfsName);
@@ -391,7 +634,7 @@ class EmrClusterStorageTest {
ContainerExecStubs.completeEveryExec(docker, "c-1", 0L, "", "");
SparkJobRunner.Storage started = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "host",
METASTORE, NOT_STOPPED);
METASTORE, null, NOT_STOPPED);
// Hive steps keep a metastore of their own.
assertNull(started.hiveMetastore());
@@ -411,7 +654,7 @@ class EmrClusterStorageTest {
ContainerExecStubs.completeEveryExec(docker, "c-6", 0L, "", "");
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network",
METASTORE, NOT_STOPPED);
METASTORE, null, NOT_STOPPED);
// Docker keeps the cluster's network apart from Floci's, where Floci's address is.
InOrder start = inOrder(lifecycle);
@@ -445,7 +688,7 @@ class EmrClusterStorageTest {
ContainerExecStubs.completeEveryExec(docker, "c-6", 0L, "", "");
SparkJobRunner.Storage started = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE,
"floci-network", METASTORE, NOT_STOPPED);
"floci-network", METASTORE, null, NOT_STOPPED);
// The HDFS still starts, as do its steps' tables there.
assertEquals("172.18.0.7", started.hdfsAddress());
@@ -466,10 +709,10 @@ class EmrClusterStorageTest {
runningOn(hdfsName, hdfsName);
ContainerExecStubs.completeEveryExec(docker, "c-6", 0L, "", "");
ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", "");
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", METASTORE, NOT_STOPPED);
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", METASTORE, null, NOT_STOPPED);
SparkJobRunner.Storage found = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE,
"floci-network", METASTORE, NOT_STOPPED);
"floci-network", METASTORE, null, NOT_STOPPED);
assertEquals("thrift://ip-10-0-0-1.ec2.internal:9083", found.hiveMetastore());
verify(lifecycle, times(1)).createAndStart(any());
@@ -492,7 +735,7 @@ class EmrClusterStorageTest {
when(awsEnv.sdkBaselineEnv("us-east-1", Optional.empty(), "http://host.docker.internal:4566", session,
"123456789012")).thenReturn(List.of("AWS_ACCESS_KEY_ID=ASIANEW"));
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", METASTORE, NOT_STOPPED);
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", METASTORE, null, NOT_STOPPED);
InOrder order = inOrder(lifecycle);
order.verify(lifecycle).removeIfExistsStrict(hdfsName);
@@ -519,9 +762,9 @@ class EmrClusterStorageTest {
ContainerExecStubs.completeEveryExec(docker, "c-6", 0L, "", "");
ContainerExecStubs.completeEveryExec(docker, "c-7", 0L, "", "");
// Given Floci's address on Floci's network, which the cluster's does not reach.
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", METASTORE, NOT_STOPPED);
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", METASTORE, null, NOT_STOPPED);
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", METASTORE, NOT_STOPPED);
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", METASTORE, null, NOT_STOPPED);
// A join cannot change the address it was given, so it starts again with Floci's on its network.
verify(lifecycle, times(2)).createAndStart(any());
@@ -540,7 +783,7 @@ class EmrClusterStorageTest {
when(lifecycle.createAndStart(any())).thenThrow(new IllegalStateException("Could not start the container"));
assertThrows(IllegalStateException.class, () -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST,
IMAGE, "floci-network", METASTORE, NOT_STOPPED));
IMAGE, "floci-network", METASTORE, null, NOT_STOPPED));
InOrder order = inOrder(lifecycle);
order.verify(lifecycle).ensureConnected("floci-container", hdfsName, "floci");
@@ -555,7 +798,7 @@ class EmrClusterStorageTest {
when(lifecycle.resolveContainerNetworkIp(hdfsName, hdfsName)).thenReturn("172.18.0.9");
runningOn(hdfsName, hdfsName);
ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", "");
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, NOT_STOPPED);
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, null, NOT_STOPPED);
when(lifecycle.disconnectFromNetwork("floci-container", hdfsName)).thenReturn(false, true);
storage.stopManagedContainers();
@@ -585,7 +828,7 @@ class EmrClusterStorageTest {
settings.put("hive.metastore.warehouse.dir", "s3://bucket/warehouse dir");
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network",
new ClusterStorage.HiveMetastore("arn:aws:iam::123456789012:role/r", settings), NOT_STOPPED);
new ClusterStorage.HiveMetastore("arn:aws:iam::123456789012:role/r", settings), null, NOT_STOPPED);
// One to a line, so a value with a space stays one argument.
verify(spec).withEnv("FLOCI_HIVE_METASTORE_SITE", String.join("\n", "--hiveconf",
@@ -611,7 +854,7 @@ class EmrClusterStorageTest {
when(lifecycle.resolveContainerNetworkIp("c-1", hdfsName)).thenReturn("172.18.0.5");
ContainerExecStubs.completeEveryExec(docker, "c-1", 0L, "", "");
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, NOT_STOPPED);
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, null, NOT_STOPPED);
verify(containerBuilder).newContainer(id);
verify(containerBuilder, never()).newContainer(IMAGE);
@@ -628,7 +871,7 @@ class EmrClusterStorageTest {
when(lifecycle.probeContainer("c-1")).thenReturn(ContainerLiveness.RUNNING);
ContainerExecStubs.completeEveryExec(docker, "c-1", 0L, "", "");
assertEquals("127.0.0.1", storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "host", null,
assertEquals("127.0.0.1", storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "host", null, null,
NOT_STOPPED).hdfsAddress());
verify(lifecycle).removeIfExistsStrict(hdfsName);
@@ -670,11 +913,12 @@ class EmrClusterStorageTest {
return null;
}).when(lifecycle).ensureVolume(eq(hdfsName), any());
Future<SparkJobRunner.Storage> starting = steps.submit(
() -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "host", null, NOT_STOPPED));
() -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "host", null, null,
NOT_STOPPED));
assertTrue(firstLooked.await(10, TimeUnit.SECONDS));
Future<SparkJobRunner.Storage> waiting = steps.submit(() -> {
second.set(Thread.currentThread());
return storage.hdfs("j-2", "123456789012", "us-east-1", HOST, IMAGE, "host", null, NOT_STOPPED);
return storage.hdfs("j-2", "123456789012", "us-east-1", HOST, IMAGE, "host", null, null, NOT_STOPPED);
});
assertEquals("127.0.0.1", starting.get(10, TimeUnit.SECONDS).hdfsAddress());
@@ -704,7 +948,7 @@ class EmrClusterStorageTest {
when(lifecycle.probeContainer("c-1")).thenReturn(ContainerLiveness.RUNNING);
ContainerExecStubs.completeEveryExec(docker, "c-1", 0L, "", "");
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "host", null, NOT_STOPPED);
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "host", null, null, NOT_STOPPED);
verify(lifecycle).createAndStart(any());
}
@@ -717,7 +961,7 @@ class EmrClusterStorageTest {
IllegalStateException failure = assertThrows(IllegalStateException.class,
() -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE,
"floci-network", null, NOT_STOPPED));
"floci-network", null, null, NOT_STOPPED));
// Not a name clash on the create that follows.
assertEquals("Failed to remove stale container " + hdfsName, failure.getMessage());
@@ -734,7 +978,7 @@ class EmrClusterStorageTest {
IllegalStateException failure = assertThrows(IllegalStateException.class,
() -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE,
"floci-network", null, NOT_STOPPED));
"floci-network", null, null, NOT_STOPPED));
assertEquals("The HDFS of EMR cluster j-1 has no address on Docker network " + hdfsName,
failure.getMessage());
@@ -748,7 +992,7 @@ class EmrClusterStorageTest {
ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", "");
assertEquals("172.18.0.6", storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE,
"floci-network", null, NOT_STOPPED).hdfsAddress());
"floci-network", null, null, NOT_STOPPED).hdfsAddress());
verify(lifecycle, never()).createAndStart(any());
verify(lifecycle, never()).removeIfExists(anyString());
@@ -761,7 +1005,7 @@ class EmrClusterStorageTest {
IllegalStateException failure = assertThrows(IllegalStateException.class,
() -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE,
"floci-network", null, NOT_STOPPED));
"floci-network", null, null, NOT_STOPPED));
assertEquals("Could not tell whether the HDFS of EMR cluster j-1 runs", failure.getMessage());
verify(lifecycle, never()).removeIfExists(anyString());
@@ -780,7 +1024,7 @@ class EmrClusterStorageTest {
ContainerExecStubs.completeEveryExec(docker, "c-7", 0L, "", "");
assertEquals("172.18.0.8", storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE,
"floci-network", null, NOT_STOPPED).hdfsAddress());
"floci-network", null, null, NOT_STOPPED).hdfsAddress());
InOrder order = inOrder(lifecycle);
order.verify(lifecycle).removeIfExistsStrict(hdfsName);
@@ -797,16 +1041,18 @@ class EmrClusterStorageTest {
IllegalStateException failure = assertThrows(IllegalStateException.class,
() -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE,
"floci-network", null, NOT_STOPPED));
"floci-network", null, null, NOT_STOPPED));
assertEquals("The HDFS of EMR cluster j-1 stopped before it was ready", failure.getMessage());
assertEquals(List.of(), looks);
// What it last wrote is in Floci's log, as the container goes with its cluster.
verify(lifecycle).lastLogLines("c-3", 40, Duration.ofSeconds(5));
}
@Test
void aClustersHdfsThatIsNotReadyInTimeFailsToStart() {
EmrClusterStorage impatient = new EmrClusterStorage(lifecycle, containerBuilder, awsEnv,
roleCredentials, currentContainer, config, Duration.ZERO,
roleCredentials, currentContainer, config, s3, Duration.ZERO,
System::nanoTime);
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING);
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-4", Map.of()));
@@ -815,9 +1061,10 @@ class EmrClusterStorageTest {
IllegalStateException failure = assertThrows(IllegalStateException.class,
() -> impatient.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE,
"floci-network", null, NOT_STOPPED));
"floci-network", null, null, NOT_STOPPED));
assertEquals("The HDFS of EMR cluster j-1 did not start within 0 seconds", failure.getMessage());
verify(lifecycle).lastLogLines("c-4", 40, Duration.ofSeconds(5));
}
@Test
@@ -825,7 +1072,7 @@ class EmrClusterStorageTest {
AtomicLong clock = new AtomicLong();
long timeout = Duration.ofMinutes(2).toNanos();
EmrClusterStorage timed = new EmrClusterStorage(lifecycle, containerBuilder, awsEnv,
roleCredentials, currentContainer, config, Duration.ofMinutes(2),
roleCredentials, currentContainer, config, s3, Duration.ofMinutes(2),
clock::get);
// The first step starts it; the second, which waited for it, finds it running.
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING, ContainerLiveness.RUNNING);
@@ -848,11 +1095,12 @@ class EmrClusterStorageTest {
try {
Future<SparkJobRunner.Storage> first = steps.submit(
() -> timed.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE,
"floci-network", null, NOT_STOPPED));
"floci-network", null, null, NOT_STOPPED));
assertTrue(firstLooks.await(10, TimeUnit.SECONDS));
Future<SparkJobRunner.Storage> waiting = steps.submit(() -> {
second.set(Thread.currentThread());
return timed.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, NOT_STOPPED);
return timed.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, null,
NOT_STOPPED);
});
assertThrows(ExecutionException.class, () -> first.get(10, TimeUnit.SECONDS));
@@ -871,7 +1119,7 @@ class EmrClusterStorageTest {
void aStepWaitingForItsClustersHdfsThroughATeardownStopsAsItsDriverWouldAndStartsItNoMore() {
AtomicLong clock = new AtomicLong();
EmrClusterStorage timed = new EmrClusterStorage(lifecycle, containerBuilder, awsEnv,
roleCredentials, currentContainer, config, Duration.ofMinutes(2),
roleCredentials, currentContainer, config, s3, Duration.ofMinutes(2),
clock::get);
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING);
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-5", Map.of()));
@@ -884,7 +1132,8 @@ class EmrClusterStorageTest {
});
assertThrows(ClusterStorage.Stopped.class,
() -> timed.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, NOT_STOPPED));
() -> timed.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, null,
NOT_STOPPED));
verify(lifecycle, times(1)).createAndStart(any());
// As it starts, one left from before goes, and the teardown removes it; the step does again, in case it
@@ -898,7 +1147,8 @@ class EmrClusterStorageTest {
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING);
assertThrows(ClusterStorage.Stopped.class,
() -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, () -> true));
() -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, null,
() -> true));
verify(lifecycle, never()).createAndStart(any());
verify(lifecycle, never()).removeIfExists(anyString());
@@ -910,7 +1160,7 @@ class EmrClusterStorageTest {
void theFirstPullOfItsImageIsNoPartOfTheHdfsStartTimeout() {
AtomicLong clock = new AtomicLong();
EmrClusterStorage timed = new EmrClusterStorage(lifecycle, containerBuilder, awsEnv,
roleCredentials, currentContainer, config, Duration.ofMinutes(2),
roleCredentials, currentContainer, config, s3, Duration.ofMinutes(2),
clock::get);
// The Hive image is not there yet, and its pull takes five minutes.
when(lifecycle.resolveImageForLaunch(IMAGE, ImagePullBehavior.PREFER_CACHED, null)).thenAnswer(pull -> {
@@ -924,7 +1174,8 @@ class EmrClusterStorageTest {
// Not ready the first time it is looked at, then ready.
ContainerExecStubs.completeEveryExec(docker, "c-4", List.of(1L, 0L), "", "");
assertEquals("172.18.0.11", timed.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null,
assertEquals("172.18.0.11", timed.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network",
null, null,
NOT_STOPPED).hdfsAddress());
}
@@ -941,7 +1192,7 @@ class EmrClusterStorageTest {
when(running.exec()).thenReturn(List.of(other));
IllegalStateException failure = assertThrows(IllegalStateException.class,
() -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "host", null, NOT_STOPPED));
() -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "host", null, null, NOT_STOPPED));
// Its daemons, on the ports j-2's hold, would never bind, and j-2's would answer for them.
assertEquals("The HDFS of EMR cluster j-1 cannot start while that of EMR cluster j-2 runs in the network"
@@ -956,7 +1207,7 @@ class EmrClusterStorageTest {
AtomicBoolean cancelled = new AtomicBoolean();
AtomicLong clock = new AtomicLong();
EmrClusterStorage timed = new EmrClusterStorage(lifecycle, containerBuilder, awsEnv,
roleCredentials, currentContainer, config, Duration.ofMinutes(2),
roleCredentials, currentContainer, config, s3, Duration.ofMinutes(2),
clock::get);
when(lifecycle.probeContainer(hdfsName)).thenReturn(ContainerLiveness.NOT_RUNNING);
when(lifecycle.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo("c-8", Map.of()));
@@ -970,7 +1221,7 @@ class EmrClusterStorageTest {
assertThrows(ClusterStorage.Stopped.class,
() -> timed.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE,
"floci-network", null, cancelled::get));
"floci-network", null, null, cancelled::get));
// Only one left from before went, as it started; the one it started is the next step's.
verify(lifecycle, times(1)).removeIfExistsStrict(hdfsName);
@@ -989,7 +1240,7 @@ class EmrClusterStorageTest {
ContainerExecStubs.completeEveryExec(docker, "c-9", 0L, "", "");
assertEquals("172.18.0.10", storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE,
"floci-network", null, NOT_STOPPED).hdfsAddress());
"floci-network", null, null, NOT_STOPPED).hdfsAddress());
verify(lifecycle).createAndStart(any());
}
@@ -1002,7 +1253,7 @@ class EmrClusterStorageTest {
assertThrows(DockerException.class,
() -> storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE,
"floci-network", null, NOT_STOPPED));
"floci-network", null, null, NOT_STOPPED));
verify(lifecycle, never()).createAndStart(any());
verify(lifecycle, never()).removeIfExists(anyString());
@@ -1058,7 +1309,7 @@ class EmrClusterStorageTest {
when(lifecycle.resolveContainerNetworkIp(hdfsName, hdfsName)).thenReturn("172.18.0.9");
runningOn(hdfsName, hdfsName);
ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", "");
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, NOT_STOPPED);
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, null, NOT_STOPPED);
assertFalse(storage.remove("j-1"));
// The next reset or shutdown removes it.
@@ -1071,7 +1322,8 @@ class EmrClusterStorageTest {
void withNoNetworkItsStepsRunWithoutAnHdfs() {
when(containerBuilder.resolveDockerNetwork(Optional.of("none"))).thenReturn(Optional.of("none"));
SparkJobRunner.Storage storageOnly = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "none", null,
SparkJobRunner.Storage storageOnly = storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "none",
null, null,
NOT_STOPPED);
// Docker joins a container placed there to no network, the HDFS's included.
@@ -1092,7 +1344,7 @@ class EmrClusterStorageTest {
when(lifecycle.probeContainer("c-1")).thenReturn(ContainerLiveness.RUNNING);
ContainerExecStubs.completeEveryExec(docker, "c-1", 0L, "", "");
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "container:b", null, NOT_STOPPED);
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "container:b", null, null, NOT_STOPPED);
verify(lifecycle).createAndStart(any());
verify(spec).withDockerNetwork(Optional.of("container:b"));
@@ -1109,7 +1361,8 @@ class EmrClusterStorageTest {
containerIdOf("3333", "3333");
ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", "");
assertEquals("127.0.0.1", storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "container:floci", null,
assertEquals("127.0.0.1", storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "container:floci",
null, null,
NOT_STOPPED).hdfsAddress());
verify(lifecycle, never()).createAndStart(any());
@@ -1131,7 +1384,7 @@ class EmrClusterStorageTest {
when(lifecycle.probeContainer("c-1")).thenReturn(ContainerLiveness.RUNNING);
ContainerExecStubs.completeEveryExec(docker, "c-1", 0L, "", "");
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "container:b", null, NOT_STOPPED);
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "container:b", null, null, NOT_STOPPED);
verify(lifecycle).createAndStart(any());
}
@@ -1142,7 +1395,7 @@ class EmrClusterStorageTest {
when(lifecycle.resolveContainerNetworkIp(hdfsName, hdfsName)).thenReturn("172.18.0.9");
runningOn(hdfsName, hdfsName);
ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", "");
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, NOT_STOPPED);
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, null, NOT_STOPPED);
storage.stopManagedContainers();
storage.stopManagedContainers();
@@ -1158,7 +1411,7 @@ class EmrClusterStorageTest {
when(lifecycle.resolveContainerNetworkIp(hdfsName, hdfsName)).thenReturn("172.18.0.9");
runningOn(hdfsName, hdfsName);
ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, "", "");
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, NOT_STOPPED);
storage.hdfs("j-1", "123456789012", "us-east-1", HOST, IMAGE, "floci-network", null, null, NOT_STOPPED);
doThrow(new IllegalStateException("Failed to remove container " + hdfsName)).doNothing()
.when(lifecycle).removeIfExistsStrict(hdfsName);
@@ -1257,13 +1510,45 @@ class EmrClusterStorageTest {
verify(lifecycle, never()).disconnectFromNetwork("floci-container", "emr-j-up-hdfs");
}
// The container name runs with networkMode as its network mode, as Docker inspects it.
// The files, by their paths in the archive, as Docker archives a folder.
// The primary node's container logs, by their path under the NodeManager's folder, as it lists and gives them. What
// it is asked to list.
private List<List<String>> nodeLogs(Map<String, String> logs) throws IOException {
StringBuilder listing = new StringBuilder();
for (Map.Entry<String, String> log : logs.entrySet()) {
listing.append(log.getValue().length()).append(' ').append(log.getKey()).append('\n');
byte[] archive = tar(Map.of(log.getKey().substring(log.getKey().lastIndexOf('/') + 1), log.getValue()));
CopyArchiveFromContainerCmd copy = mock(CopyArchiveFromContainerCmd.class);
when(copy.exec()).thenAnswer(reading -> new ByteArrayInputStream(archive));
when(docker.copyArchiveFromContainerCmd(hdfsName, "/mnt/yarn/logs/" + log.getKey())).thenReturn(copy);
}
return ContainerExecStubs.completeEveryExec(docker, hdfsName, 0L, listing.toString(), "");
}
private static byte[] tar(Map<String, String> files) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (TarArchiveOutputStream out = new TarArchiveOutputStream(bytes)) {
for (Map.Entry<String, String> file : files.entrySet()) {
byte[] content = file.getValue().getBytes(UTF_8);
TarArchiveEntry entry = new TarArchiveEntry(file.getKey());
entry.setSize(content.length);
out.putArchiveEntry(entry);
out.write(content);
out.closeArchiveEntry();
}
}
return bytes.toByteArray();
}
// The container name runs with networkMode as its network mode, of the image the steps run in, as Docker inspects
// it.
private void runningOn(String name, String networkMode) {
InspectContainerCmd inspect = mock(InspectContainerCmd.class);
InspectContainerResponse response = mock(InspectContainerResponse.class);
when(docker.inspectContainerCmd(name)).thenReturn(inspect);
when(inspect.exec()).thenReturn(response);
when(response.getHostConfig()).thenReturn(HostConfig.newHostConfig().withNetworkMode(networkMode));
when(response.getImageId()).thenReturn(IMAGE);
}
// Docker inspects the container nameOrId as the one of id.
@@ -177,6 +177,31 @@ class EmrDockerRunnerDockerIntegrationTest {
assertEquals("COMPLETED", runStep("command-runner.jar", "hadoop", "fs", "-ls", "/"));
}
@Test
void aSparkStepRunsOnTheClustersYarnInEitherDeployMode() {
put("side/where.py", """
import socket
import sys
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
sc = spark.sparkContext
executors = sc.parallelize(range(4), 4).map(lambda _: socket.gethostname()).distinct().collect()
where = " ".join([sc.master, sc.getConf().get("spark.submit.deployMode"),
str(socket.gethostname() in executors)])
spark.createDataFrame([(where,)], ["value"]).coalesce(1).write.text(sys.argv[1])
""");
startCluster("[]");
// Its driver in the step's container, its executors on the primary node.
assertEquals("COMPLETED", runStep("command-runner.jar", "spark-submit",
s3Uri("side/where.py"), s3Uri("client/")));
assertEquals("yarn client False\n", partFiles("client/"));
// Its driver on the primary node too.
assertEquals("COMPLETED", runStep("command-runner.jar", "spark-submit", "--deploy-mode", "cluster",
s3Uri("side/where.py"), s3Uri("cluster/")));
assertEquals("yarn cluster True\n", partFiles("cluster/"));
}
@Test
void aClustersHdfsWhoseDataNodeExitsStartsAgainOnItsDataForTheNextStep() {
startCluster("[]");
@@ -26,6 +26,7 @@ import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.archivers.tar.TarConstants;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -44,6 +45,7 @@ import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
@@ -108,40 +110,8 @@ class EmrReleaseImagesTest {
@Test
void anImageThatIsMissingIsMadeInAContainerOfTheSparkImageNeverStartedThenCommitted() {
when(lifecycle.getDockerClient()).thenReturn(docker);
// The two are pulled as a container's image would be, from the image-registry-base it names.
when(containerBuilder.resolveImage(anyString()))
.thenAnswer(invocation -> "mirror/" + invocation.getArgument(0));
resolves("mirror/" + SPARK, "sha256:spark");
resolves("mirror/" + HIVE, "sha256:hive");
String repository = ContainerStorageHelper.dockerName(config, "emr-release");
InspectImageCmd missing = mock(InspectImageCmd.class);
when(missing.exec()).thenThrow(new NotFoundException("missing"));
when(docker.inspectImageCmd(argThat((String image) -> image.startsWith(repository + ":"))))
.thenReturn(missing);
InspectImageCmd spark = mock(InspectImageCmd.class);
InspectImageResponse sparkImage = mock(InspectImageResponse.class);
ContainerConfig sparkConfig = mock(ContainerConfig.class);
when(sparkConfig.getUser()).thenReturn("hadoop:hadoop");
when(sparkImage.getConfig()).thenReturn(sparkConfig);
when(spark.exec()).thenReturn(sparkImage);
when(docker.inspectImageCmd("sha256:spark")).thenReturn(spark);
container("sha256:spark", "target");
container("sha256:hive", "source");
List<String> copied = new ArrayList<>();
when(docker.copyArchiveFromContainerCmd(eq("source"), anyString())).thenAnswer(invocation -> {
copied.add(invocation.getArgument(1));
CopyArchiveFromContainerCmd from = mock(CopyArchiveFromContainerCmd.class);
when(from.exec()).thenAnswer(read -> new ByteArrayInputStream(new byte[0]));
return from;
});
when(docker.copyArchiveToContainerCmd("target"))
.thenReturn(mock(CopyArchiveToContainerCmd.class, RETURNS_SELF));
when(lifecycle.commit(eq("target"), eq(repository), anyString(), eq("hadoop:hadoop"), any()))
.thenReturn("sha256:made");
when(docker.removeContainerCmd(anyString())).thenReturn(mock(RemoveContainerCmd.class, RETURNS_SELF));
assertEquals("sha256:made", images.image("emr-7.5.0", SPARK, HIVE));
List<String> copied = makesMissing(true);
assertEquals(EmrReleaseImages.COPIES.stream().map(EmrReleaseImages.Copy::from).toList(), copied);
// Named after the release and what it is made of, and labelled as Floci's EMR release image.
@@ -153,6 +123,37 @@ class EmrReleaseImagesTest {
verify(docker).removeContainerCmd("source");
}
@Test
void anImageForAClusterWithoutHiveHasHadoopsServicesAloneAndANameOfItsOwn() {
List<String> copied = makesMissing(false);
// No Hive, so a Hive step there finds no hive, as EMR's hive-script does without it.
assertEquals(List.of("/usr/lib/hadoop-hdfs", "/usr/lib/hadoop-mapreduce", "/usr/lib/hadoop-yarn"), copied);
assertTrue(EmrReleaseImages.COPIES.containsAll(EmrReleaseImages.HADOOP_COPIES));
ArgumentCaptor<String> tags = ArgumentCaptor.forClass(String.class);
images.image("emr-7.5.0", SPARK, HIVE, true);
verify(lifecycle, times(2)).commit(eq("target"), anyString(), tags.capture(), anyString(), any());
assertNotEquals(tags.getAllValues().get(0), tags.getAllValues().get(1));
}
@Test
void anImageOfTheAwsRuntimeForSparkKeepsAnotherReleasesWholeHadoopApart() {
List<String> copied = makesMissing("emr-spark-8.0.0", false);
// Another release's services do not run on its newer Hadoop, so Spark's stays where it is.
assertEquals(List.of("/usr/lib/hadoop", "/usr/lib/hadoop-hdfs", "/usr/lib/hadoop-mapreduce",
"/usr/lib/hadoop-yarn"), copied);
assertEquals("/opt", EmrReleaseImages.hadoopFolder("emr-spark-8.0.0"));
assertTrue(EmrReleaseImages.HADOOP_APART_COPIES.stream().allMatch(copy -> "/opt".equals(copy.into())));
verify(lifecycle).commit(eq("target"), anyString(),
argThat(tag -> tag.matches("emr-spark-8\\.0\\.0-[0-9a-f]{12}")), eq("hadoop:hadoop"), any());
}
@Test
void anImageOfAReleaseWithAHiveImageRunsItsOwnHadoop() {
assertNull(EmrReleaseImages.hadoopFolder("emr-7.5.0"));
}
@Test
void aSecondThreadAskingWhileTheImageIsMadeWaitsThenFindsItThere() throws InterruptedException {
when(lifecycle.getDockerClient()).thenReturn(docker);
@@ -190,11 +191,11 @@ class EmrReleaseImagesTest {
made.set(true);
return "sha256:made";
});
Thread first = Thread.ofPlatform().start(() -> images.image("emr-7.5.0", SPARK, HIVE));
Thread first = Thread.ofPlatform().start(() -> images.image("emr-7.5.0", SPARK, HIVE, true));
assertTrue(committing.await(10, TimeUnit.SECONDS));
AtomicReference<String> found = new AtomicReference<>();
Thread second = Thread.ofPlatform().start(() -> found.set(images.image("emr-7.5.0", SPARK, HIVE)));
Thread second = Thread.ofPlatform().start(() -> found.set(images.image("emr-7.5.0", SPARK, HIVE, true)));
ThreadStates.awaitBlockedOrDone(second);
committed.countDown();
first.join(10_000);
@@ -217,7 +218,7 @@ class EmrReleaseImagesTest {
when(docker.inspectImageCmd(anyString())).thenReturn(there);
resolvesEachToItself();
assertEquals("sha256:made", images.image("emr-7.5.0", SPARK, HIVE));
assertEquals("sha256:made", images.image("emr-7.5.0", SPARK, HIVE, true));
verify(docker, never()).createContainerCmd(anyString());
verify(lifecycle, never()).commit(any(), anyString(), anyString(), any(), any());
@@ -240,9 +241,9 @@ class EmrReleaseImagesTest {
return there;
});
images.image("emr-7.5.0", SPARK, HIVE);
images.image("emr-7.5.0", SPARK, HIVE);
images.image("emr-7.5.0", SPARK, HIVE);
images.image("emr-7.5.0", SPARK, HIVE, true);
images.image("emr-7.5.0", SPARK, HIVE, true);
images.image("emr-7.5.0", SPARK, HIVE, true);
assertEquals(asked.get(0), asked.get(1));
assertNotEquals(asked.get(0), asked.get(2));
@@ -284,15 +285,59 @@ class EmrReleaseImagesTest {
EmrReleaseImages cached = new EmrReleaseImages(lifecycle, containerBuilder,
new ImageCacheService(daemon, cacheConfig), config);
cached.image("emr-7.5.0", SPARK, HIVE);
cached.image("emr-7.5.0", SPARK, HIVE, true);
tags.put(HIVE, "sha256:newer-hive");
images.add("sha256:newer-hive");
cached.image("emr-7.5.0", SPARK, HIVE);
cached.image("emr-7.5.0", SPARK, HIVE, true);
assertNotEquals(asked.get(0), asked.get(1));
}
// The two images are resolved as a launch would, their names read again each time, pulled only when missing.
// Makes a missing image, with Hive or without, from containers whose copies are recorded, and returns the paths
// copied from the Hive image's.
private List<String> makesMissing(boolean withHive) {
return makesMissing("emr-7.5.0", withHive);
}
private List<String> makesMissing(String release, boolean withHive) {
when(lifecycle.getDockerClient()).thenReturn(docker);
String repository = ContainerStorageHelper.dockerName(config, "emr-release");
// The two are pulled as a container's image would be, from the image-registry-base it names.
when(containerBuilder.resolveImage(anyString()))
.thenAnswer(invocation -> "mirror/" + invocation.getArgument(0));
resolves("mirror/" + SPARK, "sha256:spark");
resolves("mirror/" + HIVE, "sha256:hive");
InspectImageCmd missing = mock(InspectImageCmd.class);
when(missing.exec()).thenThrow(new NotFoundException("missing"));
when(docker.inspectImageCmd(argThat((String image) -> image.startsWith(repository + ":"))))
.thenReturn(missing);
InspectImageCmd spark = mock(InspectImageCmd.class);
InspectImageResponse sparkImage = mock(InspectImageResponse.class);
ContainerConfig sparkConfig = mock(ContainerConfig.class);
when(sparkConfig.getUser()).thenReturn("hadoop:hadoop");
when(sparkImage.getConfig()).thenReturn(sparkConfig);
when(spark.exec()).thenReturn(sparkImage);
when(docker.inspectImageCmd("sha256:spark")).thenReturn(spark);
container("sha256:spark", "target");
container("sha256:hive", "source");
List<String> copied = new ArrayList<>();
when(docker.copyArchiveFromContainerCmd(eq("source"), anyString())).thenAnswer(invocation -> {
copied.add(invocation.getArgument(1));
CopyArchiveFromContainerCmd from = mock(CopyArchiveFromContainerCmd.class);
when(from.exec()).thenAnswer(read -> new ByteArrayInputStream(new byte[0]));
return from;
});
when(docker.copyArchiveToContainerCmd("target"))
.thenReturn(mock(CopyArchiveToContainerCmd.class, RETURNS_SELF));
when(lifecycle.commit(eq("target"), eq(repository), anyString(), eq("hadoop:hadoop"), any()))
.thenReturn("sha256:made");
when(docker.removeContainerCmd(anyString())).thenReturn(mock(RemoveContainerCmd.class, RETURNS_SELF));
assertEquals("sha256:made", images.image(release, SPARK, HIVE, withHive));
return copied;
}
private void resolves(String image, String id) {
when(imageCache.resolveForLaunch(image, ImagePullBehavior.PREFER_CACHED, null))
.thenReturn(new LaunchImage(id, null));
@@ -342,6 +342,146 @@ class EmrServiceContainerStepsTest {
EmrServiceFixture.RecordingStorage.HDFS_NETWORK), runner.jobs.get(0).storage());
}
@Test
void aClusterOnANetworkOfItsOwnRunsYarnOnItsPrimaryNodeInTheImageItsStepsRunIn() {
fixture.clusterStorage.ownNetwork = true;
EmrCluster cluster = service.runJobFlow(cluster("yarn", true, sparkStep("report", "CONTINUE")), REGION);
fixture.runStepThread();
// Its release's image with Hadoop's services, as it has no Hive, made on the step's thread: its steps and its
// primary node's HDFS and YARN run in it, the NodeManager offering what Floci gives it.
assertEquals(List.of(List.of("emr-7.5.0", "public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest",
"public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest", "false")), fixture.releaseImages.asked);
SparkJobRunner.Job job = runner.jobs.get(0);
assertEquals(EmrServiceFixture.RecordingReleaseImages.IMAGE, job.imageTemplate());
assertEquals(EmrServiceFixture.RecordingReleaseImages.IMAGE, fixture.clusterStorage.hdfs.get(0).get(2));
assertEquals(List.of(new ClusterStorage.Yarn(4096, 4)), fixture.clusterStorage.yarns);
assertEquals(hdfsStorage(cluster).withYarn("ip-10-0-0-1.ec2.internal",
EmrServiceFixture.RecordingStorage.FLOCI_ON_NETWORK), job.storage());
}
@Test
void aStepOnYarnPutsItsClustersContainerLogsInItsLogUriBeforeItEnds() {
fixture.clusterStorage.ownNetwork = true;
EmrCluster requested = cluster("yarn", true, sparkStep("report", "CONTINUE"));
requested.setLogUri("s3://logs/emr/");
EmrCluster cluster = service.runJobFlow(requested, REGION);
fixture.runStepThread();
assertEquals(List.of(List.of(cluster.getId(), "s3://logs/emr/" + cluster.getId() + "/containers/")),
fixture.clusterStorage.containerLogs);
}
@Test
void aStepThatCouldNotStartPutsNoContainerLogs() {
fixture.clusterStorage.ownNetwork = true;
fixture.clusterStorage.hdfsFailure = new IllegalStateException("The HDFS did not start");
EmrCluster requested = cluster("yarn", true, sparkStep("report", "CONTINUE"));
requested.setLogUri("s3://logs/emr/");
service.runJobFlow(requested, REGION);
fixture.runStepThread();
assertEquals(List.of(), fixture.clusterStorage.containerLogs);
}
@Test
void aClusterWithoutALogUriOrWithoutYarnPutsNoContainerLogs() {
fixture.clusterStorage.ownNetwork = true;
EmrCluster noLogUri = cluster("yarn", true, sparkStep("report", "CONTINUE"));
noLogUri.setLogUri(null);
service.runJobFlow(noLogUri, REGION);
fixture.runStepThread();
fixture.clusterStorage.ownNetwork = false;
EmrCluster noYarn = cluster("local", true, sparkStep("report", "CONTINUE"));
noYarn.setLogUri("s3://logs/emr/");
service.runJobFlow(noYarn, REGION);
fixture.runStepThread();
assertEquals(List.of(), fixture.clusterStorage.containerLogs);
}
@Test
void aClusterBootstrappedOnYarnRunsItsStepsThereFromTheImageItsBootstrapLeft() {
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
bootstrapping.clusterStorage.ownNetwork = true;
bootstrapping.service.runJobFlow(bootstrapped(cluster("on-yarn", true, sparkStep("report", "CONTINUE"))), REGION);
bootstrapping.runStepThread();
bootstrapping.runStepThread();
assertEquals(1, bootstrapping.clusterStorage.yarns.size());
assertEquals(runner.jobs.get(0).imageTemplate(), bootstrapping.clusterStorage.hdfs.get(0).get(2));
assertEquals("ip-10-0-0-1.ec2.internal", runner.jobs.get(0).storage().resourceManager());
}
@Test
void aClusterBootstrappedByAnEarlierFlociKeepsToLocalModeAndItsHdfsToTheHiveImage() {
// As an earlier Floci left it: a bootstrap image with no YARN in it.
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
bootstrapping.clusterStorage.ownNetwork = false;
EmrCluster cluster = bootstrapping.service.runJobFlow(bootstrapped(cluster("from-before", true)), REGION);
bootstrapping.runStepThread();
bootstrapping.clusterStorage.ownNetwork = true;
bootstrapping.service.addJobFlowSteps(cluster.getId(), List.of(sparkStep("report", "CONTINUE")));
bootstrapping.runStepThread();
assertEquals(List.of(), bootstrapping.clusterStorage.yarns);
assertEquals("public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest",
bootstrapping.clusterStorage.hdfs.get(0).get(2));
assertEquals(null, runner.jobs.get(0).storage().resourceManager());
}
@Test
void aSparkStepOnAClusterThatRunsYarnKeepsItsOwnMasterAndDeployMode() {
fixture.clusterStorage.ownNetwork = true;
EmrStep step = sparkStep("report", "CONTINUE");
step.setArgs(new ArrayList<>(List.of("spark-submit", "--master", "yarn", "--deploy-mode", "cluster", REPORT)));
service.runJobFlow(cluster("yarn", true, step), REGION);
fixture.runStepThread();
// As EMR's spark-submit takes them: a cluster-mode driver runs on the cluster's YARN.
assertEquals(List.of("--master", "yarn", "--deploy-mode", "cluster", REPORT), runner.jobs.get(0).application());
}
@Test
void aClusterOfTheAwsRuntimeForSparkRunsYarnFromTheHadoopItsImageKeepsApart() {
fixture.clusterStorage.ownNetwork = true;
EmrCluster requested = cluster("spark-runtime", true, sparkStep("report", "CONTINUE"));
requested.setReleaseLabel("emr-spark-8.1.0");
EmrCluster cluster = service.runJobFlow(requested, REGION);
fixture.runStepThread();
// Its release has no Hive image, so emr-7.5.0's gives the Hadoop its image holds for the node's daemons.
assertEquals(List.of(List.of("emr-spark-8.1.0", "public.ecr.aws/emr-serverless/spark4/emr-spark-8.1.0:latest",
"public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest", "false")), fixture.releaseImages.asked);
SparkJobRunner.Job job = runner.jobs.get(0);
assertEquals(EmrServiceFixture.RecordingReleaseImages.IMAGE, job.imageTemplate());
assertEquals(EmrServiceFixture.RecordingReleaseImages.IMAGE, fixture.clusterStorage.hdfs.get(0).get(2));
assertEquals(List.of(new ClusterStorage.Yarn(4096, 4, "/opt")), fixture.clusterStorage.yarns);
assertEquals(hdfsStorage(cluster).withYarn("ip-10-0-0-1.ec2.internal",
EmrServiceFixture.RecordingStorage.FLOCI_ON_NETWORK), job.storage());
}
@Test
void aClusterOfTheAwsRuntimeForSparkOnYarnNamingHiveStillRunsNoHive() {
fixture.clusterStorage.ownNetwork = true;
EmrCluster requested = cluster("spark-runtime-hive", true, sparkStep("report", "CONTINUE"));
requested.setReleaseLabel("emr-spark-8.1.0");
requested.setApplications("[{\"Name\": \"Hive\"}, {\"Name\": \"Spark\"}]");
service.runJobFlow(requested, REGION);
fixture.runStepThread();
assertEquals("false", fixture.releaseImages.asked.get(0).get(3));
assertEquals("false", fixture.clusterStorage.hdfs.get(0).get(4));
}
@Test
void aHiveStepOnAClusterWithHCatalogRunsHiveInTheReleasesImageWithHive() {
EmrCluster requested = cluster("hcatalog", true, hiveStep("report", "-e", "show tables;"));
@@ -354,7 +494,7 @@ class EmrServiceContainerStepsTest {
SparkJobRunner.Job job = runner.jobs.get(0);
assertEquals(SparkJobRunner.Engine.HIVE, job.engine());
assertEquals(List.of(List.of("emr-7.5.0", "public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest",
"public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest")), fixture.releaseImages.asked);
"public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest", "true")), fixture.releaseImages.asked);
assertEquals(EmrServiceFixture.RecordingReleaseImages.IMAGE, job.imageTemplate());
assertEquals(hdfsStorage(cluster).withHiveMetastore("thrift://ip-10-0-0-1.ec2.internal:9083"), job.storage());
}
@@ -634,6 +774,51 @@ class EmrServiceContainerStepsTest {
assertEquals("RUNNING", running.getSteps().get(1).getState());
}
@Test
void aStepCancelledAsItRunsOnYarnLeavesItsApplicationsLogsInS3() {
fixture.clusterStorage.ownNetwork = true;
EmrCluster requested = cluster("cancel-logs", true, sparkStep("report", "CONTINUE"));
requested.setLogUri("s3://logs/emr/");
EmrCluster cluster = service.runJobFlow(requested, REGION);
String stepId = cluster.getSteps().get(0).getId();
runner.whileRunning = () -> service.cancelSteps(cluster.getId(), List.of(stepId));
fixture.runStepThread();
assertEquals("CANCELLED", service.describeStep(cluster.getId(), stepId).getState());
assertEquals(List.of(List.of(cluster.getId(), "s3://logs/emr/" + cluster.getId() + "/containers/")),
fixture.clusterStorage.containerLogs);
}
@Test
void aStepCancelledBeforeItsDriverStartedHasNoLogsToArchive() {
fixture.clusterStorage.ownNetwork = true;
EmrCluster requested = cluster("cancel-early", true, sparkStep("never", "CONTINUE"));
requested.setLogUri("s3://logs/emr/");
EmrCluster cluster = service.runJobFlow(requested, REGION);
service.cancelSteps(cluster.getId(), List.of(cluster.getSteps().get(0).getId()));
fixture.runStepThread();
assertEquals(List.of(), fixture.clusterStorage.containerLogs);
}
@Test
void aStepFlociStopsInATeardownLeavesItsApplicationsLogsOnTheNode() {
fixture.clusterStorage.ownNetwork = true;
EmrCluster requested = cluster("teardown-logs", true, sparkStep("cut", "CONTINUE"));
requested.setLogUri("s3://logs/emr/");
EmrCluster cluster = service.runJobFlow(requested, REGION);
runner.whileRunning = () -> {
service.stopManagedContainers();
runner.stop(cluster.getSteps().get(0).getId());
};
fixture.runStepThread();
assertEquals(List.of(), fixture.clusterStorage.containerLogs);
}
@Test
void aStepCancelledBeforeItsDriverStartsNeverStartsIt() {
EmrCluster cluster = service.runJobFlow(cluster("early", true, sparkStep("never", "CONTINUE")), REGION);
@@ -868,7 +1053,7 @@ class EmrServiceContainerStepsTest {
assertEquals(stepId, job.runId());
// The release's EMR Serverless image with its EMR Serverless Hive image's Hive, made on the step's thread.
assertEquals(List.of(List.of("emr-7.5.0", "public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest",
"public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest")), fixture.releaseImages.asked);
"public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest", "true")), fixture.releaseImages.asked);
assertEquals(EmrServiceFixture.RecordingReleaseImages.IMAGE, job.imageTemplate());
assertNull(job.customImage());
assertEquals(List.of("hive-script", "--run-hive-script", "--args"), job.command());
@@ -896,7 +1081,7 @@ class EmrServiceContainerStepsTest {
fixture.runStepThread();
assertEquals(List.of(List.of("emr-7.5.0", "public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest",
"registry.internal/emr-serverless/hive/emr-7.5.0:20250425")), fixture.releaseImages.asked);
"registry.internal/emr-serverless/hive/emr-7.5.0:20250425", "true")), fixture.releaseImages.asked);
assertEquals(SparkJobRunner.Engine.SPARK, runner.jobs.get(0).engine());
assertEquals(EmrServiceFixture.RecordingReleaseImages.IMAGE, runner.jobs.get(0).imageTemplate());
}
@@ -65,6 +65,14 @@ final class EmrServiceFixture {
final List<List<String>> hdfs = new ArrayList<>();
// Each HDFS's metastore service asked for.
final List<HiveMetastore> metastores = new ArrayList<>();
// Each HDFS's YARN asked for.
final List<Yarn> yarns = new ArrayList<>();
// Each cluster and S3 folder its YARN applications' logs were put in.
final List<List<String>> containerLogs = new ArrayList<>();
// Floci's address on a cluster's network, which a node running YARN gives its executors.
static final String FLOCI_ON_NETWORK = "http://floci:4566";
// Whether a cluster's primary node has a network of its own, as with a docker-network that is not shared.
boolean ownNetwork;
RuntimeException hdfsFailure;
// Runs as each HDFS starts, with what tells it the step is past starting.
Consumer<BooleanSupplier> whileStartingHdfs = stopped -> { };
@@ -84,21 +92,37 @@ final class EmrServiceFixture {
whileCreating.run();
}
@Override
public boolean ownNetwork(String dockerNetwork) {
return ownNetwork;
}
@Override
public void archiveContainerLogs(String clusterId, String accountId, String region, String logFolder) {
containerLogs.add(List.of(clusterId, logFolder));
}
@Override
public SparkJobRunner.Storage hdfs(String clusterId, String accountId, String region, String host,
String image, String dockerNetwork, HiveMetastore hiveMetastore,
String image, String dockerNetwork, HiveMetastore hiveMetastore, Yarn yarn,
BooleanSupplier stopped) {
hdfs.add(Arrays.asList(clusterId, host, image, dockerNetwork, String.valueOf(hiveMetastore != null),
hiveMetastore != null ? hiveMetastore.role() : null));
if (hiveMetastore != null) {
metastores.add(hiveMetastore);
}
if (yarn != null) {
yarns.add(yarn);
}
whileStartingHdfs.accept(stopped);
if (hdfsFailure != null) {
throw hdfsFailure;
}
SparkJobRunner.Storage storage = volumes(clusterId).withHdfs(host, HDFS_ADDRESS, HDFS_NETWORK);
return hiveMetastore != null ? storage.withHiveMetastore("thrift://" + host + ":9083") : storage;
if (hiveMetastore != null) {
storage = storage.withHiveMetastore("thrift://" + host + ":9083");
}
return yarn != null ? storage.withYarn(host, FLOCI_ON_NETWORK) : storage;
}
@Override
@@ -116,13 +140,13 @@ final class EmrServiceFixture {
/** Makes no image: answers {@link #IMAGE} for each, or throws {@link #failure} when it is set. */
static final class RecordingReleaseImages implements ReleaseImages {
static final String IMAGE = "sha256:" + "3".repeat(64);
// Each image asked for: its release, then the two it is made of.
// Each image asked for: its release, then the two it is made of, then whether it has Hive.
final List<List<String>> asked = new ArrayList<>();
RuntimeException failure;
@Override
public String image(String releaseLabel, String sparkImage, String hiveImage) {
asked.add(List.of(releaseLabel, sparkImage, hiveImage));
public String image(String releaseLabel, String sparkImage, String hiveImage, boolean withHive) {
asked.add(List.of(releaseLabel, sparkImage, hiveImage, String.valueOf(withHive)));
if (failure != null) {
throw failure;
}
@@ -245,6 +269,8 @@ final class EmrServiceFixture {
when(config.services().emr().imageTemplate()).thenReturn(Optional.empty());
when(config.services().emr().hiveImageTemplate()).thenReturn(Optional.empty());
when(config.services().emr().dockerNetwork()).thenReturn(Optional.empty());
when(config.services().emr().yarnNodeMemoryMb()).thenReturn(4096);
when(config.services().emr().yarnNodeVcores()).thenReturn(4);
when(config.services().emr().reconcileContainersOnStartup()).thenReturn(reconcile);
return config;
}
@@ -35,39 +35,42 @@ class EmrSparkStepsTest {
// Options come before the application, so --master after it is the application's own argument.
assertEquals(List.of("--verbose", "--conf", "spark.executor.cores=2", "--class", "com.example.Report",
"s3://bucket/jobs/report.jar", "--master", "kept"), EmrSparkSteps.application(step));
"s3://bucket/jobs/report.jar", "--master", "kept"), EmrSparkSteps.application(step, false));
}
@Test
void sparkSubmitMayBeNamedByItsPath() {
assertEquals(List.of("s3://bucket/jobs/report.py"), EmrSparkSteps.application(
step("command-runner.jar", null, "/usr/bin/spark-submit", "s3://bucket/jobs/report.py")));
step("command-runner.jar", null, "/usr/bin/spark-submit", "s3://bucket/jobs/report.py"), false));
}
@Test
void aCustomJarRunsItsMainClassOrElseItsManifests() {
assertEquals(List.of("--class", "com.example.Report", "s3://bucket/jobs/report.jar", "2026-10-25"),
EmrSparkSteps.application(step("s3://bucket/jobs/report.jar", "com.example.Report", "2026-10-25")));
EmrSparkSteps.application(step("s3://bucket/jobs/report.jar", "com.example.Report", "2026-10-25"),
false));
assertEquals(List.of("s3://bucket/jobs/report.jar"),
EmrSparkSteps.application(step("s3://bucket/jobs/report.jar", null)));
EmrSparkSteps.application(step("s3://bucket/jobs/report.jar", null), false));
}
@Test
void aCustomJarAtEmrsStreamingJarPathRunsTheImagesCopy() {
assertEquals(List.of("/usr/lib/hadoop/hadoop-streaming.jar", "-input", "s3://bucket/in/"),
EmrSparkSteps.application(step("/usr/lib/hadoop-mapreduce/hadoop-streaming.jar", null, "-input",
"s3://bucket/in/")));
"s3://bucket/in/"), false));
assertEquals(List.of("/home/hadoop/hadoop-streaming.jar"),
EmrSparkSteps.application(step("/home/hadoop/hadoop-streaming.jar", null)));
EmrSparkSteps.application(step("/home/hadoop/hadoop-streaming.jar", null), false));
}
@Test
void stepsOtherThanSparkAreNotRun() {
assertNull(EmrSparkSteps.application(step("command-runner.jar", null, "hive-script", "--run-hive-script")));
assertNull(EmrSparkSteps.application(step("command-runner.jar", null)));
assertNull(EmrSparkSteps.application(step("command-runner.jar", null, "hive-script", "--run-hive-script"),
false));
assertNull(EmrSparkSteps.application(step("command-runner.jar", null), false));
assertNull(EmrSparkSteps.application(
step("s3://us-east-1.elasticmapreduce/libs/script-runner/script-runner.jar", null, "s3://b/x.sh")));
assertNull(EmrSparkSteps.application(step(null, null)));
step("s3://us-east-1.elasticmapreduce/libs/script-runner/script-runner.jar", null, "s3://b/x.sh"),
false));
assertNull(EmrSparkSteps.application(step(null, null), false));
}
@Test
@@ -87,6 +87,7 @@ class EmrServerlessSparkRunnerTest {
private final EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
private final ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
private final LaunchedContainerAwsEnv awsEnv = mock(LaunchedContainerAwsEnv.class);
private final DockerClient docker = mock(DockerClient.class, RETURNS_DEEP_STUBS);
private final SparkJobRunner.Progress progress = mock(SparkJobRunner.Progress.class);
private final S3Service s3 = mock(S3Service.class);
@@ -613,6 +614,86 @@ class EmrServerlessSparkRunnerTest {
"s3://bucket/jobs/report.py"), arguments.subList(20, arguments.size()));
}
@Test
void aStepOnItsClustersYarnSubmitsToItsResourceManagerWithExecutorsSizedForItsNode() {
SparkJobRunner.Job job = stepJob(Map.of("spark.executor.memory", "2g"))
.onStorage(STORAGE.withYarn("ip-10-0-0-1.ec2.internal", "http://floci:4566"));
List<String> arguments = EmrServerlessSparkRunner.sparkSubmitArguments(job, "http://floci:4566",
List.of("AWS_ACCESS_KEY_ID=ASIASTEP", "AWS_ENDPOINT_URL=http://floci:4566"));
assertEquals(List.of("--master", "yarn"), arguments.subList(0, 2));
// The ResourceManager on the primary node; Spark's jars from the node's image, which is the step's.
assertTrue(arguments.contains("spark.hadoop.yarn.resourcemanager.hostname=ip-10-0-0-1.ec2.internal"));
assertTrue(arguments.contains("spark.yarn.jars=local:/usr/lib/spark/jars/*"));
// Floci's sizes for the NodeManager, which the cluster's spark-defaults replace.
int floci = arguments.indexOf("spark.executor.memory=1g");
assertTrue(floci > 0 && arguments.indexOf("spark.executor.memory=2g") > floci, arguments.toString());
assertTrue(arguments.contains("spark.executor.cores=1"));
assertTrue(arguments.contains("spark.driver.memory=2g"));
assertTrue(arguments.contains("spark.driver.cores=1"));
// A client-mode driver is reached at its container's name on the cluster's network.
assertTrue(arguments.contains("spark.driver.host=s-1a2b3c4d5e6f7"));
assertTrue(arguments.contains("spark.driver.bindAddress=0.0.0.0"));
// Each executor, and a cluster-mode driver, has the step's AWS environment.
assertTrue(arguments.contains("spark.executorEnv.AWS_ACCESS_KEY_ID=ASIASTEP"));
assertTrue(arguments.contains("spark.yarn.appMasterEnv.AWS_ACCESS_KEY_ID=ASIASTEP"));
assertTrue(arguments.contains("spark.executorEnv.AWS_ENDPOINT_URL=http://floci:4566"));
assertTrue(arguments.contains("spark.hadoop.fs.s3a.endpoint=http://floci:4566"));
assertTrue(EmrServerlessSparkRunner.sparkDefaultsFile(job, "http://floci:4566", List.of())
.startsWith("spark.master yarn\n"));
}
@Test
void aStepNotOnYarnRunsInLocalModeWithNoneOfYarnsSettings() {
List<String> arguments = EmrServerlessSparkRunner.sparkSubmitArguments(stepJob(Map.of()), ENDPOINT);
assertEquals(List.of("--master", "local[*]"), arguments.subList(0, 2));
assertFalse(arguments.stream().anyMatch(argument -> argument.startsWith("spark.yarn.")
|| argument.startsWith("spark.executorEnv.") || argument.startsWith("spark.driver.host=")),
arguments.toString());
}
@Test
void aStepOnItsClustersYarnJoinsItsNetworkByTheNameItsDriverIsReachedAtAndReachesFlociThere() {
ContainerBuilder builder = mock(ContainerBuilder.class);
ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(builder.newContainer(anyString())).thenReturn(spec);
SparkJobRunner.Job job = stepJob(Map.of())
.onStorage(STORAGE.withYarn("ip-10-0-0-1.ec2.internal", "http://floci-on-cluster:4566"));
when(awsEnv.sdkBaselineEnv("eu-west-1", Optional.empty(), "http://floci-on-cluster:4566", Optional.empty(),
"123456789012")).thenReturn(List.of("AWS_ACCESS_KEY_ID=ASIASTEP"));
runner(builder).run(job, progress);
InOrder order = inOrder(lifecycle);
order.verify(lifecycle).create(any());
order.verify(lifecycle).ensureConnected("driver", "floci-aws-emr-j-2AXXXXXXGAPLF-hdfs", "s-1a2b3c4d5e6f7");
order.verify(lifecycle).startCreated(eq("driver"), any());
verify(lifecycle, never()).connectToNetwork(anyString(), anyString());
// Floci's address on the cluster's network, where its executors reach it too, not on Floci's own.
verify(spec).withCmd(argThat((List<String> arguments) ->
arguments.contains("spark.hadoop.fs.s3a.endpoint=http://floci-on-cluster:4566")
&& arguments.contains("spark.executorEnv.AWS_ACCESS_KEY_ID=ASIASTEP")));
}
@Test
void aCommandsOwnSparkSubmitOnItsClustersYarnGetsItsSettingsInItsSparkDefaults() {
ContainerBuilder builder = mock(ContainerBuilder.class);
ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(builder.newContainer(anyString())).thenReturn(spec);
SparkJobRunner.Job job = commandJob(List.of("bash", "-c", "spark-submit s3://bucket/app.py"), Map.of())
.onStorage(STORAGE.withYarn("ip-10-0-0-1.ec2.internal", "http://floci-on-cluster:4566"));
when(awsEnv.sdkBaselineEnv(eq("eu-west-1"), eq(Optional.empty()), eq("http://floci-on-cluster:4566"), any(),
anyString())).thenReturn(List.of("AWS_ACCESS_KEY_ID=ASIASTEP"));
runner(builder).run(job, progress);
verify(spec).withEnv(eq("FLOCI_SPARK_DEFAULTS"), argThat(file -> file.startsWith("spark.master yarn\n")
&& file.contains("spark.hadoop.yarn.resourcemanager.hostname ip-10-0-0-1.ec2.internal")
&& file.contains("spark.executorEnv.AWS_ACCESS_KEY_ID ASIASTEP")));
}
@Test
void aSparkStepOnAClusterWithHiveUsesItsMetastoreServiceUnlessItsSparkHiveSiteNamesAnother() {
String glue = "spark.hadoop.hive.metastore.client.factory.class="
@@ -656,7 +737,7 @@ class EmrServerlessSparkRunnerTest {
&& entrypoint.get(2).contains(String.join("\n",
" if [ -f \"$hadoop_conf/$1\" ]; then",
" mv \"$hadoop_conf/$1\" \"$hadoop_conf/floci-original-$1\"",
" include=\"<xi:include href=\\\"$hadoop_conf/floci-original-$1\\\"/>\"",
" include=\"<xi:include href=\\\"floci-original-$1\\\"/>\"",
" fi",
" printf '%s\\n' '<configuration xmlns:xi=\"http://www.w3.org/2001/XInclude\">' \"$include\""
+ " \"$2\" '</configuration>' > \"$hadoop_conf/$1\""))
@@ -1362,7 +1443,6 @@ class EmrServerlessSparkRunnerTest {
when(lifecycle.create(any())).thenReturn("driver");
when(docker.inspectContainerCmd("driver").exec().getState().getRunning()).thenReturn(false);
when(docker.inspectContainerCmd("driver").exec().getState().getExitCodeLong()).thenReturn(0L);
LaunchedContainerAwsEnv awsEnv = mock(LaunchedContainerAwsEnv.class);
when(awsEnv.flociEndpoint()).thenReturn(ENDPOINT);
return new EmrServerlessSparkRunner(builder, lifecycle, logStreamer, awsEnv,
mock(LambdaExecutionRoleCredentials.class), s3, ecr, config, new MutableClock(), Duration.ZERO);