feat(emr): run Hive steps in the docker runner mode (#7459)

In the docker runner mode a Hive step failed without running ("hive-script
and pig-script are not in the image steps run in"). On a cluster whose
Applications name Hive, a command-runner.jar step running hive-script, as
the AWS CLI writes a Type=Hive step ("hive-script --run-hive-script
--args" and the step's Args), or hive itself, now runs: the image's
hive-script runs hive with the arguments after --args, with Tez in local
mode, on the cluster's storage and Floci's S3.

- An EMR cluster's nodes hold every application it installs, so a
  cluster with Hive bootstraps and runs every step in one image: the
  release's EMR Serverless image with the Hive, Tez, HDFS, MapReduce and
  YARN of its EMR Serverless Hive image (or the new hive-image-template).
  EmrReleaseImages makes it the first time a release's cluster needs it:
  a container of the EMR Serverless image, created and never started,
  gets the Hive image's folders streamed in from a container of that
  image, and is committed, as a bootstrap's container is, with no image
  builder involved. The two images ship different builds of
  emr-serverless-goodies-common under one name, so Tez keeps the Hive
  image's in a folder of its own, its links rewritten to lead there, and
  the Hive image's Hadoop configuration, which puts Tez on the class
  path, goes to /etc/hadoop/conf.hive, which Hive runs with.
- The image is named after the release, the ids of the two images as a
  container would run them (an image-registry-base included) and what
  is copied, so a newer pull of either makes another; it is kept for the
  release's next cluster, and made once at a time. The bootstrap and the
  steps get its id, as they get a bootstrap image's, from their own
  thread, which makes it first, unless the cluster has ended by then; a
  failure to make it fails the step, or ends a bootstrapping cluster with
  INTERNAL_ERROR.
- hive gets Floci's settings, then the cluster's core-site, tez-site and
  hive-site properties as --hiveconf settings, then the step's own
  arguments, so a step's --hiveconf wins as it does over hive-site.xml;
  the cluster's hive-env exports are its environment.
- Its metastore is the cluster's own, as "Hive records metastore
  information in a MySQL database on the primary node's file system": an
  embedded Derby database in the cluster's /mnt, so a table one Hive step
  makes is there for the next until the cluster ends. A hive-site naming
  the Glue Data Catalog's client factory uses Floci's Glue instead.
- Hive reaches the cluster's HDFS through the same view of /mnt/hdfs
  under the viewfs scheme: Hive looks up the HDFS encryption zone of any
  hdfs:// path, which only an HDFS NameNode answers. A table without a
  LOCATION is in /user/hive/warehouse there, which other steps read as
  hdfs://.
- On a cluster without Hive, hive-script runs in the release's image, as
  EMR's does without Hive ("Hive isn't installed."); NOT_RUN is
  pig-script's alone.

The Docker-gated EmrHiveStepsDockerIntegrationTest runs the AWS CLI's
Hive steps on a cluster's metastore and HDFS, a hive-site for the Glue
Data Catalog, a cluster without Hive, and a bootstrapped cluster whose
installs a Hive step and a later step both find, in the emr-7.5.0
images, which the CI prefetch pulls for its shard.
EmrServerlessSparkRunner's hiveSettings now builds both services'
--hiveconf settings.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-03 23:18:20 -06:00
1 parent a90b812cc6
commit 5a4632229e
18 files changed
+1418 -88

No files matched your search

+8 -5
View File
@@ -95,11 +95,14 @@ grep -qE '/lambdaweb/' "$SHARD_FILE" && ecr public.ecr.aws/lambda/nodejs:24
starts SwfLambdaIntegrationTest && ecr public.ecr.aws/lambda/python:3.12
starts ElbV2LambdaTargetDataPlaneIntegrationTest && ecr public.ecr.aws/lambda/python:3.14
# EmrDockerRunnerDockerIntegrationTest runs EMR steps and EMR Serverless job runs in the emr-7.5.0 image the runner's
# default template names (EmrServerlessSparkRunner), 3.5 GB, so it is queued last, behind the Lambda runtimes.
starts EmrDockerRunnerDockerIntegrationTest && ecr public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest
# EmrServerlessHiveDockerIntegrationTest runs EMR Serverless Hive job runs in the emr-7.5.0 Hive image the runner's
# default Hive template names, 2.7 GB.
starts EmrServerlessHiveDockerIntegrationTest && ecr public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest
# default template names (EmrServerlessSparkRunner), 3.5 GB, so it is queued last, behind the Lambda runtimes;
# EmrHiveStepsDockerIntegrationTest runs a cluster's other steps in it.
starts EmrDockerRunnerDockerIntegrationTest EmrHiveStepsDockerIntegrationTest \
&& ecr public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest
# EmrServerlessHiveDockerIntegrationTest runs EMR Serverless Hive job runs, and EmrHiveStepsDockerIntegrationTest EMR
# Hive steps, in the emr-7.5.0 Hive image the runner's default Hive template names, 2.7 GB.
starts EmrServerlessHiveDockerIntegrationTest EmrHiveStepsDockerIntegrationTest \
&& ecr public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest
# package token in shard.txt -> images its tests are known to launch
# (measured inline pulls; update alongside image-catalog changes)
+44 -4
View File
@@ -125,8 +125,10 @@ but for its bootstrap actions and its storage.
`s3://<region>.elasticmapreduce/libs/script-runner/script-runner.jar` URI) its script, as the Release
Guide's "Run commands and scripts on an Amazon EMR cluster" describes them. An `s3-dist-cp` step runs
Floci's own S3DistCp (see **S3DistCp**), and `hadoop-streaming` and `hadoop-lzo` steps the image's
Hadoop (see **Hadoop streaming and MapReduce**). `hive-script` and `pig-script`, which the image does not
have, are `FAILED` without running.
Hadoop (see **Hadoop streaming and MapReduce**). On a cluster whose `Applications` name Hive, a Hive step
runs Hive (see **Hive steps**); on one without, `hive-script` runs in the release's image, and says
what EMR's does without Hive, "Hive isn't installed.", and the step fails. `pig-script`, which the image
does not have, is `FAILED` without running.
* **Commands and scripts**: they run as the image's `hadoop` user in `/home/hadoop`, with `bash`, Python
3, Java, `curl` and the AWS CLI v2, which reaches Floci through `AWS_ENDPOINT_URL`. A
`script-runner.jar` step's script is fetched from S3 with the AWS CLI and the step's credentials, then
@@ -190,6 +192,41 @@ but for its bootstrap actions and its storage.
shell cannot export is left out. A custom JAR step's `spark-submit` reads neither `hadoop-env.sh` nor
Hadoop's `log4j.properties`, so those two do not reach it: a `hadoop-env` `HADOOP_CLASSPATH`, say, is not on
its class path, and it logs as Spark does.
* **Hive steps**: an EMR cluster's nodes hold every application it installs, so a cluster whose `Applications` name
Hive runs its bootstrap actions and all its steps in an image of the release's with Hive added: the release's EMR
Serverless image with the Hive, Tez, HDFS, MapReduce and YARN of its EMR Serverless Hive image
(`public.ecr.aws/emr-serverless/hive/<release>`, 2.7 GB unpacked, pulled to make it; `hive-image-template` names
another). Floci makes it the first time one of the release's clusters needs it: a container of the release's
image, never started, gets the Hive image's folders, and is committed, as a bootstrap's is, as
`floci-aws-emr-release:<release>-<hash>`, 0.6 GB more than the release's image, and kept for the release's next
cluster (`docker image rm` removes it); a newer pull of either image makes another. A failure to make it, a Hive
image that cannot be pulled say, fails the step that needed it ("The step could not start: ..."), or, for a
bootstrap, ends the cluster with `INTERNAL_ERROR`. The two images ship different builds of one goodies JAR under
one name, so Tez keeps the Hive image's, and Hive runs with the Hive image's Hadoop configuration, which puts Tez
on its class path, while the cluster's other steps keep the release image's. Then a `command-runner.jar` step
running `hive-script`, as the AWS CLI writes a `Type=Hive` step (`hive-script --run-hive-script --args` and the
step's `Args`), or `hive` itself, runs Hive: `hive-script` runs `hive` with the arguments after `--args`, as the
image's `hadoop` user in `/home/hadoop`, with Tez in local mode in its JVM, as an [EMR Serverless Hive job
run](emr-serverless.md#running-hive-job-runs)'s does, on the cluster's storage. It gets the cluster's
`core-site`, `tez-site` and `hive-site` properties, each a `--hiveconf`, then the step's own arguments, so a
`--hiveconf` of the step's wins over a classification's, as it does over `hive-site.xml`; the cluster's
`hive-env` exports are its environment. Floci's settings come before them all, and any of them replaces one: S3A
on Floci's S3 for `s3://`, Tez in local mode, the cluster's HDFS, and its metastore. "By default, Hive records
metastore information in a MySQL database on the primary node's file system", which Floci keeps as an embedded
Derby database in the cluster's `/mnt`, so a table one Hive step makes is there for the next, until the cluster
ends. The `hive-site` setting of `hive.metastore.client.factory.class` the Release Guide gives for the Glue Data
Catalog uses Floci's Glue instead, with the cluster's account as its `hive.metastore.glue.catalogid`, which a
`hive-site` one replaces. A table without a `LOCATION` is in the cluster's HDFS, `/user/hive/warehouse` ("By
default, this is a location in HDFS"). Hive reaches that HDFS folder under the `viewfs` scheme: it looks up the
HDFS encryption zone of every `hdfs://` path it writes or reads a table at, which only an HDFS NameNode can
answer. So a table's location reads `viewfs:/user/hive/warehouse/<table>`, the folder other steps name
`hdfs:///user/hive/warehouse/<table>`, and a Hive statement on an `hdfs://` path fails ("Unable to determine if
hdfs:... is encrypted"). Spark steps do not use the cluster's Hive metastore, so they see a Hive step's tables
only through the Glue Data Catalog. Only one Hive step at a time can use the cluster's metastore: with
`StepConcurrencyLevel` above 1, a Hive step that starts while another runs fails ("Another instance of Derby may
have already booted the database"). What the bootstrap actions installed is there for every step, Hive's
included. A script or command that starts `hive` itself gets none of these settings: only a Hive step runs Hive.
Hive's own log stays in the container.
* **S3DistCp**: the image has no `s3-dist-cp`, so a `command-runner.jar` step whose
first argument is `s3-dist-cp`, the Release Guide's form, runs Floci's own program instead, through
`spark-submit` in the step's container, copying through Hadoop's file systems: `--src` and `--dest` take
@@ -231,7 +268,8 @@ but for its bootstrap actions and its storage.
[EMR Serverless job run](emr-serverless.md#running-spark-job-runs)'s do, so Java code reaches Floci
over HTTPS too, and through AWS's own endpoint names with `FLOCI_DNS_SPOOF_AWS_ENDPOINTS`.
* **Bootstrap actions**: a cluster with `BootstrapActions` is `BOOTSTRAPPING` until they have run, one
after the other, in one container of the release's image, whatever the second half of
after the other, in one container of the release's image (with Hive added for a cluster with Hive, see
**Hive steps**), whatever the second half of
`cluster-startup-delay-seconds`. Each action's script is read from Floci's S3 (an `s3n://` or `s3a://`
path names the same bucket, and another path is the image's own) and runs with its `Args` in
`/home/hadoop`, with the credentials of the cluster's `JobFlowRole` instance profile, as a step would.
@@ -315,7 +353,8 @@ but for its bootstrap actions and its storage.
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
image: `registry.internal/emr-serverless/spark/%s:20250425`. A release with no EMR Serverless image
image: `registry.internal/emr-serverless/spark/%s:20250425`, and `hive-image-template` another Hive image:
`registry.internal/emr-serverless/hive/%s:20250425`. A release with no EMR Serverless image
fails its steps with "The step could not start: Could not pull image".
## EventBridge events
@@ -368,6 +407,7 @@ 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 |
| `FLOCI_SERVICES_EMR_HIVE_IMAGE_TEMPLATE` | `public.ecr.aws/emr-serverless/hive/%s:latest` | The EMR Serverless Hive image a `docker` cluster with Hive takes Hive from, `%s` standing for the cluster's release label; see [Hive steps](#running-steps) |
| `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
@@ -2049,7 +2049,8 @@ public interface EmulatorConfig {
/**
* {@code immediate} completes each step by time without running anything; {@code docker} runs each
* Spark step's {@code spark-submit} in a container of the release's EMR Serverless image.
* Spark step's {@code spark-submit} in a container of the release's EMR Serverless image, which a cluster
* with Hive has Hive added to, and that cluster's Hive steps' {@code hive} too.
*/
@WithDefault("immediate")
String runnerMode();
@@ -2063,6 +2064,14 @@ public interface EmulatorConfig {
*/
Optional<String> imageTemplate();
/**
* The EMR Serverless Hive image a {@code docker} cluster with Hive takes Hive from, into the image its
* bootstrap and steps run in, as {@link #imageTemplate()} names the image Hive is added to, for example
* "registry.internal/emr-serverless/hive/%s:20250425". If omitted, Floci uses the release's public EMR
* Serverless Hive image on Amazon ECR Public.
*/
Optional<String> hiveImageTemplate();
/**
* 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
@@ -43,6 +43,12 @@ public interface BootstrapRunner {
*/
record Bootstrap(String clusterId, String accountId, String region, String releaseLabel, String imageTemplate,
String dockerNetwork, String role, List<Action> actions, String logFolder) {
/** This bootstrap, run in {@code image}. */
Bootstrap inImage(String image) {
return new Bootstrap(clusterId, accountId, region, releaseLabel, image, dockerNetwork, role, actions,
logFolder);
}
}
/** A bootstrap action: its name, the script it runs, and that script's arguments. */
@@ -0,0 +1,187 @@
package io.github.hectorvent.floci.services.emr;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.exception.NotFoundException;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.EmulatorConfig.EcsServiceConfig.ImagePullBehavior;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
import io.github.hectorvent.floci.core.common.docker.RetryingTarCopier;
import io.github.hectorvent.floci.services.emrserverless.EmrServerlessSparkRunner;
import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService;
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.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
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.
* 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.
*/
@ApplicationScoped
public class EmrReleaseImages implements ReleaseImages {
private static final Logger LOG = Logger.getLogger(EmrReleaseImages.class);
private static final String SERVICE = "emr";
private static final String COMPONENT = "emr-release";
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.
static final List<Copy> COPIES = List.of(
new Copy("/usr/lib/hive", "/usr/lib"),
new Copy("/usr/lib/tez", "/usr/lib"),
new Copy("/usr/lib/hadoop-hdfs", "/usr/lib"),
new Copy("/usr/lib/hadoop-mapreduce", "/usr/lib"),
new Copy("/usr/lib/hadoop-yarn", "/usr/lib"),
new Copy("/usr/lib/bigtop-groovy", "/usr/lib"),
new Copy("/etc/hive", "/etc"),
new Copy("/etc/tez", "/etc"),
new Copy("/etc/tez-ui", "/etc"),
new Copy(EMR_SHARE + "/s3-dist-cp", EMR_SHARE),
new Copy("/usr/bin/hive", "/usr/bin"),
new Copy("/usr/bin/beeline", "/usr/bin"),
new Copy("/usr/bin/hiveserver2", "/usr/bin"),
new Copy("/usr/bin/hplsql", "/usr/bin"),
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));
// 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<>();
private final ContainerLifecycleManager lifecycleManager;
private final ContainerBuilder containerBuilder;
private final ImageCacheService imageCacheService;
private final EmulatorConfig config;
@Inject
public EmrReleaseImages(ContainerLifecycleManager lifecycleManager, ContainerBuilder containerBuilder,
ImageCacheService imageCacheService, EmulatorConfig config) {
this.lifecycleManager = lifecycleManager;
this.containerBuilder = containerBuilder;
this.imageCacheService = imageCacheService;
this.config = config;
}
/**
* 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
* the id, as it gets a bootstrap image's, so the image-registry-base Floci prefixes image names with does not send
* it to a registry for an image only this daemon has.
*/
@Override
public String image(String releaseLabel, String sparkImage, String hiveImage) {
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);
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);
}
String user = docker.inspectImageCmd(sparkId).exec().getConfig().getUser();
Map<String, String> labels = new LinkedHashMap<>();
labels.put(ContainerStorageHelper.SERVICE_LABEL, SERVICE);
labels.put(ContainerStorageHelper.COMPONENT_LABEL, COMPONENT);
labels.put(ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config));
List<String> containers = new ArrayList<>();
try {
String target = docker.createContainerCmd(sparkId).withLabels(labels).exec().getId();
containers.add(target);
String source = docker.createContainerCmd(hiveId).withLabels(labels).exec().getId();
containers.add(source);
for (Copy copy : COPIES) {
RetryingTarCopier.copyStreamed(docker, target, copy.into(), copy.from(),
out -> copy(docker.copyArchiveFromContainerCmd(source, copy.from()).exec(), out, copy));
}
return lifecycleManager.commit(target, repository, tag,
user == null || user.isBlank() ? "root" : user, labels);
} finally {
for (String container : containers) {
try {
docker.removeContainerCmd(container).withForce(true).exec();
} catch (RuntimeException e) {
LOG.warnv("Could not remove container {0}, left from making {1}:{2}: {3}", container,
repository, tag, e.getMessage());
}
}
}
}
}
/**
* Writes the archive Docker gave of {@code copy}'s source, whose entries start with its name, to {@code out} as
* {@code copy} puts it in its folder: under its own name, after the folders of one made of several, and with a
* link into the EMR Serverless image's goodies leading to the Hive image's copy of them instead.
*/
static void copy(InputStream archive, OutputStream out, Copy copy) throws IOException {
String name = copy.from().substring(copy.from().lastIndexOf('/') + 1);
try (InputStream source = archive;
TarArchiveInputStream in = new TarArchiveInputStream(source);
TarArchiveOutputStream tar = RetryingTarCopier.newTarStream(out)) {
for (int slash = copy.as().indexOf('/'); slash > 0; slash = copy.as().indexOf('/', slash + 1)) {
tar.putArchiveEntry(new TarArchiveEntry(copy.as().substring(0, slash + 1)));
tar.closeArchiveEntry();
}
TarArchiveEntry entry;
while ((entry = in.getNextEntry()) != null) {
entry.setName(renamed(entry.getName(), name, copy.as()));
if (entry.isLink()) {
entry.setLinkName(renamed(entry.getLinkName(), name, copy.as()));
} else if (entry.isSymbolicLink() && entry.getLinkName().startsWith(GOODIES + "/")) {
entry.setLinkName(EMR_SHARE + "/" + HIVE_GOODIES + entry.getLinkName().substring(GOODIES.length()));
}
tar.putArchiveEntry(entry);
in.transferTo(tar);
tar.closeArchiveEntry();
}
}
}
// An archive's path under the name it was made with, under the copy's instead.
private static String renamed(String path, String name, String as) {
return path.equals(name) || path.startsWith(name + "/") ? as + path.substring(name.length()) : path;
}
/** A path of the Hive image, a file or a folder, copied into the image made's folder {@code into} as {@code as}. */
record Copy(String from, String into, String as) {
/** {@code from} copied into a folder of the image made under its own name. */
Copy(String from, String into) {
this(from, into, from.substring(from.lastIndexOf('/') + 1));
}
/** {@code from} copied to the path {@code to}, whose folder the image made has. */
static Copy to(String from, String to) {
return new Copy(from, to.substring(0, to.lastIndexOf('/')), to.substring(to.lastIndexOf('/') + 1));
}
}
}
@@ -55,6 +55,7 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
@@ -113,11 +114,13 @@ public class EmrService implements Resettable, StoredResourceArns {
private final SparkJobRunner sparkRunner;
private final BootstrapRunner bootstrapRunner;
private final ClusterStorage clusterStorage;
private final ReleaseImages releaseImages;
private final Executor stepExecutor;
private final IamService iamService;
// Where a step's driver runs: image-template, with the release label for %s, and docker-network; null when
// not set.
private final String imageTemplate;
private final String hiveImageTemplate;
private final String dockerNetwork;
// The steps a thread is running, by account and id; a RUNNING container step not here was left by a restart.
private final Set<String> executing = new HashSet<>();
@@ -192,26 +195,28 @@ public class EmrService implements Resettable, StoredResourceArns {
@Inject
public EmrService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver,
EmrEventPublisher eventPublisher, EmrServerlessSparkRunner sparkRunner,
EmrBootstrapRunner bootstrapRunner, EmrClusterStorage clusterStorage, IamService iamService) {
EmrBootstrapRunner bootstrapRunner, EmrClusterStorage clusterStorage,
EmrReleaseImages releaseImages, IamService iamService) {
this(storageFactory, config, regionResolver, eventPublisher, Clock.systemUTC(),
Wakeups.timer(Clock.systemUTC()),
RUNNER_DOCKER.equalsIgnoreCase(config.services().emr().runnerMode()) ? sparkRunner : null,
RUNNER_DOCKER.equalsIgnoreCase(config.services().emr().runnerMode()) ? bootstrapRunner : null,
RUNNER_DOCKER.equalsIgnoreCase(config.services().emr().runnerMode()) ? clusterStorage : null,
RUNNER_DOCKER.equalsIgnoreCase(config.services().emr().runnerMode()) ? releaseImages : null,
Executors.newCachedThreadPool(Thread.ofPlatform().daemon().name("emr-step-", 0).factory()),
iamService);
}
EmrService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver,
EmrEventPublisher eventPublisher, Clock clock, Wakeups wakeups) {
this(storageFactory, config, regionResolver, eventPublisher, clock, wakeups, null, null, null, Runnable::run,
null);
this(storageFactory, config, regionResolver, eventPublisher, clock, wakeups, null, null, null, null,
Runnable::run, null);
}
EmrService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver,
EmrEventPublisher eventPublisher, Clock clock, Wakeups wakeups, SparkJobRunner sparkRunner,
BootstrapRunner bootstrapRunner, ClusterStorage clusterStorage, Executor stepExecutor,
IamService iamService) {
BootstrapRunner bootstrapRunner, ClusterStorage clusterStorage, ReleaseImages releaseImages,
Executor stepExecutor, IamService iamService) {
this.clusterStore = storageFactory.create("emr", "emr-clusters.json",
new TypeReference<Map<String, EmrCluster>>() {});
this.secConfigStore = storageFactory.create("emr", "emr-security-configs.json",
@@ -224,9 +229,11 @@ public class EmrService implements Resettable, StoredResourceArns {
this.sparkRunner = sparkRunner;
this.bootstrapRunner = bootstrapRunner;
this.clusterStorage = clusterStorage;
this.releaseImages = releaseImages;
this.stepExecutor = stepExecutor;
this.iamService = iamService;
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.lifecycle = new EmrClusterLifecycle(config.services().emr().clusterStartupDelaySeconds(),
config.services().emr().stepDurationSeconds(),
@@ -1407,30 +1414,46 @@ public class EmrService implements Resettable, StoredResourceArns {
@Override
public void start(EmrCluster cluster, EmrStep step, String region) {
String accountId = regionResolver.getAccountId();
List<String> application = EmrSparkSteps.application(step);
List<String> command = application == null ? EmrSparkSteps.command(step) : null;
EmrSparkSteps.HiveCommand hive = EmrSparkSteps.hive(step, cluster.getApplications(),
cluster.getConfigurations(), SNAPSHOT_MAPPER);
List<String> application = hive == null ? EmrSparkSteps.application(step) : null;
List<String> command = hive == null && application == null ? EmrSparkSteps.command(step) : null;
SparkJobRunner.Storage storage = null;
if ((application != null || command != null) && clusterStorage != null) {
if ((hive != null || application != null || command != null) && clusterStorage != null) {
storage = clusterStorage.volumes(cluster.getId());
cluster.setStorageCreated(true);
}
SparkJobRunner.Job job = application == null && command == null ? null
: new SparkJobRunner.Job(SERVICE, step.getId(), accountId, region, cluster.getReleaseLabel(),
SparkJobRunner.Engine.SPARK,
cluster.getBootstrapImage() != null ? cluster.getBootstrapImage() : imageTemplate, null,
dockerNetwork, executionRole(cluster, step, accountId),
EmrSparkSteps.sparkDefaults(cluster.getConfigurations(), SNAPSHOT_MAPPER),
application != null ? application : List.of(), command, Duration.ZERO,
EmrSparkSteps.logFolder(cluster, step), null,
EmrSparkSteps.environment(step, cluster.getConfigurations(), SNAPSHOT_MAPPER), List.of(),
storage, EmrSparkSteps.coreSite(cluster.getConfigurations(), SNAPSHOT_MAPPER),
EmrSparkSteps.sparkLog4j2(cluster.getConfigurations(), SNAPSHOT_MAPPER),
EmrSparkSteps.mapredSite(cluster.getConfigurations(), SNAPSHOT_MAPPER),
EmrSparkSteps.hadoopLog4j(cluster.getConfigurations(), SNAPSHOT_MAPPER),
EmrSparkSteps.hadoopEnvironment(cluster.getConfigurations(), SNAPSHOT_MAPPER));
// 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.
String image = cluster.getBootstrapImage() != null ? cluster.getBootstrapImage() : imageTemplate;
Supplier<String> releaseImage = cluster.getBootstrapImage() == null ? releaseImage(cluster) : null;
SparkJobRunner.Job job;
if (hive != null) {
job = new SparkJobRunner.Job(SERVICE, step.getId(), accountId, region, cluster.getReleaseLabel(),
SparkJobRunner.Engine.HIVE, image, null, dockerNetwork,
executionRole(cluster, step, accountId), Map.of(), hive.arguments(), hive.runner(),
Duration.ZERO, EmrSparkSteps.logFolder(cluster, step), null,
EmrSparkSteps.hiveEnvironment(cluster.getConfigurations(), SNAPSHOT_MAPPER), List.of(),
storage, Map.of(), Map.of(), Map.of(), Map.of(), Map.of());
} else if (application == null && command == null) {
job = null;
} else {
job = new SparkJobRunner.Job(SERVICE, step.getId(), accountId, region, cluster.getReleaseLabel(),
SparkJobRunner.Engine.SPARK, image, null, dockerNetwork,
executionRole(cluster, step, accountId),
EmrSparkSteps.sparkDefaults(cluster.getConfigurations(), SNAPSHOT_MAPPER),
application != null ? application : List.of(), command, Duration.ZERO,
EmrSparkSteps.logFolder(cluster, step), null,
EmrSparkSteps.environment(step, cluster.getConfigurations(), SNAPSHOT_MAPPER), List.of(),
storage, EmrSparkSteps.coreSite(cluster.getConfigurations(), SNAPSHOT_MAPPER),
EmrSparkSteps.sparkLog4j2(cluster.getConfigurations(), SNAPSHOT_MAPPER),
EmrSparkSteps.mapredSite(cluster.getConfigurations(), SNAPSHOT_MAPPER),
EmrSparkSteps.hadoopLog4j(cluster.getConfigurations(), SNAPSHOT_MAPPER),
EmrSparkSteps.hadoopEnvironment(cluster.getConfigurations(), SNAPSHOT_MAPPER));
}
StepLaunch launch = new StepLaunch(accountId, region, cluster.getId(), step.getId(), generation);
executing.add(stepKey(accountId, step.getId()));
stepExecutor.execute(() -> runStep(job, launch));
stepExecutor.execute(() -> runStep(job, launch, releaseImage));
}
@Override
@@ -1439,8 +1462,9 @@ public class EmrService implements Resettable, StoredResourceArns {
}
}
// A step's thread: its driver runs to its end, or the step fails at once when Floci does not run its kind.
private void runStep(SparkJobRunner.Job job, StepLaunch launch) {
// 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.
private void runStep(SparkJobRunner.Job job, StepLaunch launch, Supplier<String> releaseImage) {
String failure;
if (job == null) {
failure = EmrSparkSteps.NOT_RUN;
@@ -1448,12 +1472,14 @@ public class EmrService implements Resettable, StoredResourceArns {
SparkJobRunner.Outcome outcome;
StepProgress progress = new StepProgress(launch);
try {
SparkJobRunner.Job running = releaseImage != null && !progress.cancelled()
? job.inImage(releaseImage.get()) : job;
// The cluster's storage is there before its first step's container mounts it. A step 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());
}
outcome = sparkRunner.run(job, progress);
outcome = sparkRunner.run(running, progress);
} catch (RuntimeException e) {
LOG.warnv(e, "EMR step {0} could not run", launch.stepId());
outcome = SparkJobRunner.Outcome.couldNotStart(e.getMessage());
@@ -1488,8 +1514,9 @@ public class EmrService implements Resettable, StoredResourceArns {
cluster.getReleaseLabel(), imageTemplate, dockerNetwork, instanceProfileRole(cluster, accountId),
bootstrapActions(cluster), logFolder);
BootstrapLaunch launch = new BootstrapLaunch(accountId, region, cluster.getId(), generation);
Supplier<String> releaseImage = releaseImage(cluster);
bootstrapping.add(clusterKey(accountId, cluster.getId()));
stepExecutor.execute(() -> runBootstrap(bootstrap, launch));
stepExecutor.execute(() -> runBootstrap(bootstrap, launch, releaseImage));
}
@Override
@@ -1500,6 +1527,22 @@ public class EmrService implements Resettable, StoredResourceArns {
}
}
/**
* 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.
*/
private Supplier<String> releaseImage(EmrCluster cluster) {
if (releaseImages == null || !EmrSparkSteps.installsHive(cluster.getApplications(), SNAPSHOT_MAPPER)) {
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);
}
// A cluster's BootstrapActionConfig list, as RunJobFlow stored it once it had checked it.
private static List<BootstrapRunner.Action> bootstrapActions(EmrCluster cluster) {
List<BootstrapRunner.Action> actions = new ArrayList<>();
@@ -1517,12 +1560,17 @@ public class EmrService implements Resettable, StoredResourceArns {
return actions;
}
// A cluster's bootstrap thread: its actions run to their end, which then ends its BOOTSTRAPPING.
private void runBootstrap(BootstrapRunner.Bootstrap bootstrap, BootstrapLaunch launch) {
// A cluster's bootstrap thread: its actions run to their end, which then ends its BOOTSTRAPPING. They run in
// a cluster with Hive's image, which is made first when it is not there yet, unless the cluster ended, or a reset
// removed it, before the thread ran; a failure to make it ends the cluster as one to run the bootstrap does.
private void runBootstrap(BootstrapRunner.Bootstrap bootstrap, BootstrapLaunch launch,
Supplier<String> releaseImage) {
BooleanSupplier cancelled = () -> !RequestScopes.callAs(launch.accountId(), launch.region(),
() -> stillBootstrapping(launch));
BootstrapRunner.Outcome outcome;
try {
outcome = bootstrapRunner.run(bootstrap, () -> !RequestScopes.callAs(launch.accountId(), launch.region(),
() -> stillBootstrapping(launch)));
outcome = bootstrapRunner.run(releaseImage != null && !cancelled.getAsBoolean()
? bootstrap.inImage(releaseImage.get()) : bootstrap, cancelled);
} catch (RuntimeException e) {
LOG.warnv(e, "The bootstrap actions of EMR cluster {0} could not run", launch.clusterId());
outcome = BootstrapRunner.Outcome.couldNotRun(e.getMessage());
@@ -25,13 +25,14 @@ import java.util.Set;
* {@code command-runner.jar} step runs its command, and a {@code script-runner.jar} step its script, as the
* Release Guide's "Run commands and scripts on an Amazon EMR cluster" describes them, a
* {@code hadoop-streaming} or {@code hadoop-lzo} one through the image's {@code hadoop}, with MapReduce in local
* mode; an {@code s3-dist-cp} one runs Floci's own S3DistCp.
* mode; an {@code s3-dist-cp} one runs Floci's own S3DistCp. On a cluster with Hive, whose image holds Hive too, a
* {@code command-runner.jar} step running {@code hive-script}, as the AWS CLI writes a Hive step, or {@code hive}
* runs Hive.
*/
final class EmrSparkSteps {
// No source gives AWS's wording for these; they are Floci's.
static final String NOT_RUN = "Floci does not run this step: hive-script and pig-script are not in the image"
+ " steps run in.";
static final String NOT_RUN = "Floci does not run this step: pig-script is not in the image steps run in.";
static final String INTERRUPTED = "Floci stopped while the step was running.";
private static final String COMMAND_RUNNER = "command-runner.jar";
@@ -63,8 +64,19 @@ final class EmrSparkSteps {
private static final String SPARK_HADOOP_PREFIX = "spark.hadoop.";
// spark-submit gives the JVM it runs an application's main class in the Java options of this variable.
private static final String SPARK_SUBMIT_OPTS = "SPARK_SUBMIT_OPTS";
// The Release Guide's command-runner.jar tools that the EMR Serverless image does not have.
private static final Set<String> UNAVAILABLE_TOOLS = Set.of("hive-script", "pig-script");
// The Release Guide's command-runner.jar tools that the EMR Serverless images do not have.
private static final Set<String> UNAVAILABLE_TOOLS = Set.of("pig-script");
// The AWS CLI's Hive step on a release is command-runner.jar running "hive-script --run-hive-script --args"
// and the step's arguments, the ones the image's hive-script runs hive with; a step can also run hive itself.
private static final String HIVE_SCRIPT = "hive-script";
private static final String HIVE_SCRIPT_ARGS = "--args";
private static final String HIVE = "hive";
// The Hive classifications a Hive step's hive gets, each property a --hiveconf, in the order Hive reads their
// files, a later one winning: core-site, tez-site, which will "Change values in Tez's tez-site.xml file", and
// hive-site, which will "Change values in Hive's hive-site.xml"; and hive-env's exports, which will "Change
// values in the Hive environment".
private static final List<String> HIVE_CLASSIFICATIONS = List.of(CORE_SITE, "tez-site", "hive-site");
private static final String HIVE_ENV = "hive-env";
// EMR's MapReduce jars are in /usr/lib/hadoop-mapreduce, as the image's own hadoop-streaming script has it,
// which the image does not have; its streaming jar is in /usr/lib/hadoop.
private static final Map<String, String> IMAGE_JARS = Map.of(
@@ -155,6 +167,68 @@ final class EmrSparkSteps {
return null;
}
/**
* How a step runs Hive, or null for a step that does not, or whose cluster does not install Hive (see
* {@link #installsHive}), where {@code hive-script} finds no {@code hive} as EMR's does without it: a
* {@code command-runner.jar} step running {@code hive-script}, up to its {@code --args} (added at the end of one
* without), or {@code hive}, and what its {@code hive} gets after
* Floci's settings: the cluster's Hive classifications, then the step's own arguments, so that a
* {@code --hiveconf} of the step's replaces a classification's property, as it replaces a hive-site.xml one.
*/
static HiveCommand hive(EmrStep step, String applications, String configurations, ObjectMapper objectMapper) {
String jar = step.getJar();
List<String> args = step.getArgs() != null ? step.getArgs() : List.of();
if (jar == null || !named(jar, COMMAND_RUNNER) || args.isEmpty()
|| !installsHive(applications, objectMapper)) {
return null;
}
List<String> runner;
List<String> own;
if (named(args.getFirst(), HIVE_SCRIPT)) {
int split = args.indexOf(HIVE_SCRIPT_ARGS);
runner = new ArrayList<>(split < 0 ? args : args.subList(0, split));
runner.add(HIVE_SCRIPT_ARGS);
own = split < 0 ? List.of() : args.subList(split + 1, args.size());
} else if (named(args.getFirst(), HIVE)) {
runner = List.of(args.getFirst());
own = args.subList(1, args.size());
} else {
return null;
}
List<String> arguments = new ArrayList<>();
for (String classification : HIVE_CLASSIFICATIONS) {
arguments.addAll(EmrServerlessSparkRunner.hiveSettings(properties(configurations, objectMapper,
classification)));
}
arguments.addAll(own);
return new HiveCommand(List.copyOf(runner), arguments);
}
/**
* A step's Hive: {@code runner}, what runs in place of {@code hive}, and {@code arguments}, what follows Floci's
* settings.
*/
record HiveCommand(List<String> runner, List<String> arguments) {
}
/** The variables a cluster's {@code hive-env} exports, which its Hive steps get. */
static Map<String, String> hiveEnvironment(String configurations, ObjectMapper objectMapper) {
return exports(configurations, objectMapper, HIVE_ENV);
}
/**
* Whether a cluster's {@code Applications}, the JSON array RunJobFlow was given, name Hive ("A case-insensitive
* list of applications for Amazon EMR to install").
*/
static boolean installsHive(String applications, ObjectMapper objectMapper) {
for (JsonNode application : stored(applications, objectMapper)) {
if (HIVE.equalsIgnoreCase(application.path("Name").asText())) {
return true;
}
}
return false;
}
/**
* 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
@@ -273,22 +347,27 @@ final class EmrSparkSteps {
private static List<JsonNode> classified(String configurations, ObjectMapper objectMapper,
String classification) {
List<JsonNode> matching = new ArrayList<>();
if (configurations == null) {
return matching;
}
try {
for (JsonNode configuration : objectMapper.readTree(configurations)) {
if (classification.equals(configuration.path("Classification").asText())) {
matching.add(configuration);
}
for (JsonNode configuration : stored(configurations, objectMapper)) {
if (classification.equals(configuration.path("Classification").asText())) {
matching.add(configuration);
}
} catch (JsonProcessingException ignored) {
// RunJobFlow stored the array as it came; one that does not parse holds no properties to apply.
return matching;
}
return matching;
}
// A JSON array of a cluster's, which RunJobFlow stored as it came, or an empty one for none: one that does not
// parse holds no properties to apply and names no application.
private static JsonNode stored(String json, ObjectMapper objectMapper) {
if (json == null) {
return objectMapper.createArrayNode();
}
try {
return objectMapper.readTree(json);
} catch (JsonProcessingException ignored) {
return objectMapper.createArrayNode();
}
}
private static List<String> withoutMasterOrDeployMode(List<String> arguments) {
List<String> kept = new ArrayList<>();
int i = 0;
@@ -0,0 +1,15 @@
package io.github.hectorvent.floci.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.
*/
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.
*/
String image(String releaseLabel, String sparkImage, String hiveImage);
}
@@ -579,10 +579,7 @@ public class EmrServerlessJobRunService implements Resettable {
static List<String> hiveArguments(Application app, JobRun run, JobDriver.Hive hive) {
List<String> arguments = new ArrayList<>();
for (String classification : HIVE_CLASSIFICATIONS) {
classificationProperties(app, run, classification).forEach((name, value) -> {
arguments.add(EmrServerlessSparkRunner.HIVECONF_OPTION);
arguments.add(name + "=" + value);
});
arguments.addAll(EmrServerlessSparkRunner.hiveSettings(classificationProperties(app, run, classification)));
}
if (hive.getInitQueryFile() != null) {
arguments.add("-i");
@@ -66,7 +66,8 @@ import java.util.zip.GZIPOutputStream;
* step's {@code hadoop} command, and a MapReduce job its {@code spark-submit} starts, reach Floci's S3 and run
* MapReduce in local mode, with the cluster's Hadoop configuration. A Hive run starts {@code hive} in a container of
* the release's EMR Serverless Hive image instead, with Tez in local mode in Hive's JVM, S3A on Floci's S3 and the
* Glue Data Catalog client, the image's metastore, on Floci's Glue.
* Glue Data Catalog client, the image's metastore, on Floci's Glue; an EMR step's in the image of its cluster, which
* holds Spark and Hive, on its storage, with the cluster's HDFS and the cluster's own metastore.
*/
@ApplicationScoped
public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardown {
@@ -75,7 +76,7 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
private static final String SPARK_SUBMIT = "/usr/lib/spark/bin/spark-submit";
private static final String HIVE = "/usr/bin/hive";
// hive's option for a setting, and its single-dash form.
static final String HIVECONF_OPTION = "--hiveconf";
private static final String HIVECONF_OPTION = "--hiveconf";
private static final String HIVECONF_SHORT_OPTION = "-hiveconf";
private static final String SPARK_DEFAULTS_VARIABLE = "FLOCI_SPARK_DEFAULTS";
private static final String HADOOP_SITE_VARIABLE = "FLOCI_HADOOP_SITE";
@@ -242,10 +243,30 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
private static final List<SparkSetting> HIVE_SETTINGS = List.of(
new SparkSetting("tez.local.mode", "true"),
new SparkSetting("tez.am.client.am.port-range", "40000-40100"));
// On a cluster, after the HDFS settings, Hive's file system is their view of the cluster's HDFS under the viewfs
// scheme: Hive looks up the HDFS encryption zone of a path of the hdfs scheme, which only HDFS answers, as its
// shim takes that path's file system for HDFS's own, so a table Hive makes in the cluster's HDFS is at a viewfs:
// path, the folder an hdfs:// path leads to in other steps. Its metastore is the cluster's own, as "Hive records
// metastore information in a MySQL database on the primary node's file system": an embedded Derby database in
// the cluster's /mnt, whose tables DataNucleus creates on first use. A cluster's hive-site replaces them, with
// the Glue Data Catalog's client factory for one.
private static final List<SparkSetting> HIVE_CLUSTER_SETTINGS = List.of(
new SparkSetting("fs.defaultFS", "viewfs:///"),
new SparkSetting("hive.metastore.client.factory.class",
"org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClientFactory"),
new SparkSetting("javax.jdo.option.ConnectionURL",
"jdbc:derby:;databaseName=/mnt/var/lib/hive/metastore_db;create=true"),
new SparkSetting("hive.metastore.schema.verification", "false"),
new SparkSetting("datanucleus.schema.autoCreateAll", "true"));
// Hive logs to a file in the folder EMR Serverless names in LOGS_DIR, its HIVE_LOG, apart from the driver's standard
// output and error.
private static final List<String> HIVE_ENVIRONMENT = List.of("LOGS_DIR=/tmp/floci-hive-logs");
private static final String HIVE_SCRATCH_VARIABLE = "FLOCI_HIVE_SCRATCH";
/**
* Where an EMR cluster's image with Hive keeps its Hive image's Hadoop configuration, which puts Tez on the class
* path, apart from the one its other steps' Hadoop reads; Hive runs with it where an image has it.
*/
public static final String HIVE_HADOOP_CONF = "/etc/hadoop/conf.hive";
private static final String HIVE_SCRATCHDIR = "hive.exec.scratchdir";
// The user every EMR Serverless image runs as: a custom one sets "the USER back to hadoop:hadoop".
private static final String IMAGE_USER = "hadoop";
@@ -256,7 +277,8 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
// file system (LocalClient), a copy that silently does nothing where the image's user cannot create that path, at
// the root of the container for one; so the container starts as root, makes that path its user's, then runs hive
// as that user, in that user's home, as a Spark image's working directory is: Tez in local mode puts each task's
// files in the working directory, and the Hive image names none, which leaves the root.
// files in the working directory, and the Hive image names none, which leaves the root. In an EMR cluster's image
// with Hive, Hive reads its own Hadoop configuration (HIVE_HADOOP_CONF).
private static final String HIVE_WRAPPER = String.join("\n",
"host=$(hostname)",
"export CLIENT_AM_BIND_ADDRESS=0.0.0.0 TASK_AM_BIND_ADDRESS=0.0.0.0 SHUFFLE_BIND_ADDRESS=0.0.0.0",
@@ -265,6 +287,7 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
" mkdir -p \"$" + HIVE_SCRATCH_VARIABLE + "\" && chown " + IMAGE_USER + ":" + IMAGE_USER + " \"$"
+ HIVE_SCRATCH_VARIABLE + "\" || exit",
"fi",
"if [ -d " + HIVE_HADOOP_CONF + " ]; then export HADOOP_CONF_DIR=" + HIVE_HADOOP_CONF + "; fi",
"export HOME=~" + IMAGE_USER,
"cd \"$HOME\" || exit",
// The image's user has no other group, as Docker starts it.
@@ -344,8 +367,10 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
// bash -c's script gets "floci" as its $0, and what runs after it as its arguments, "$@".
if (job.engine() == Engine.HIVE) {
List<String> hive = hiveArguments(job, endpoint);
List<String> entrypoint = new ArrayList<>(List.of("/bin/bash", "-c", HIVE_WRAPPER, "floci"));
entrypoint.addAll(job.command() != null ? job.command() : List.of(HIVE));
container.withUser("root")
.withEntrypoint(List.of("/bin/bash", "-c", HIVE_WRAPPER, "floci", HIVE))
.withEntrypoint(entrypoint)
.withCmd(hive)
.withEnv(HIVE_ENVIRONMENT);
String scratch = hiveScratchMirror(hive);
@@ -367,8 +392,11 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
}
if (job.storage() != null) {
container.withNamedVolume(job.storage().home(), "/home/hadoop")
.withNamedVolume(job.storage().mnt(), "/mnt")
.withEnv(HADOOP_SITE_VARIABLE, hadoopSite(job, endpoint))
.withNamedVolume(job.storage().mnt(), "/mnt");
}
// Hive's settings reach it as --hiveconf settings, so only a Spark job's container sets up Hadoop.
if (job.storage() != null && job.engine() == Engine.SPARK) {
container.withEnv(HADOOP_SITE_VARIABLE, hadoopSite(job, endpoint))
.withEnv(MAPRED_SITE_VARIABLE, mapredSite(job));
if (!job.hadoopLog4j().isEmpty()) {
container.withEnv(HADOOP_LOG4J_VARIABLE, hadoopLog4jFile(job));
@@ -533,7 +561,7 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
}
/** The image a release's runs on {@code engine} use, as the other {@code image} says, Hive's for Hive. */
static String image(String imageTemplate, String releaseLabel, Engine engine) {
public static String image(String imageTemplate, String releaseLabel, Engine engine) {
String template = imageTemplate != null ? imageTemplate
: engine == Engine.HIVE ? HIVE_DEFAULT_IMAGE
: releaseLabel.startsWith("emr-spark-") ? SPARK_RUNTIME_DEFAULT_IMAGE : DEFAULT_IMAGE;
@@ -701,21 +729,36 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
}
/**
* {@code hive}'s arguments: Floci's S3 and Glue, as a Spark run gets them, and Tez in local mode, each a
* {@code --hiveconf}, which a later one replaces, then the run's own arguments.
* {@code hive}'s arguments: Floci's S3 and Glue, as a Spark run gets them, Tez in local mode, and on a cluster its
* HDFS and metastore, each a {@code --hiveconf}, which a later one replaces, then the run's own arguments.
*/
static List<String> hiveArguments(Job job, String flociEndpoint) {
List<SparkSetting> settings = new ArrayList<>(hadoopSettings(job, flociEndpoint));
settings.addAll(HIVE_SETTINGS);
if (job.storage() != null) {
settings.addAll(HDFS_SETTINGS);
settings.addAll(HIVE_CLUSTER_SETTINGS);
}
List<String> arguments = new ArrayList<>();
for (SparkSetting setting : settings) {
arguments.add(HIVECONF_OPTION);
arguments.add(setting.key() + "=" + setting.value());
addHiveSetting(arguments, setting.key(), setting.value());
}
arguments.addAll(job.application());
return arguments;
}
/** Each of {@code properties} as {@code hive}'s {@code --hiveconf name=value}, in their order. */
public static List<String> hiveSettings(Map<String, String> properties) {
List<String> arguments = new ArrayList<>();
properties.forEach((name, value) -> addHiveSetting(arguments, name, value));
return arguments;
}
private static void addHiveSetting(List<String> arguments, String name, String value) {
arguments.add(HIVECONF_OPTION);
arguments.add(name + "=" + value);
}
/**
* The local folder Tez in local mode needs for a Hive session's staging folder, or null when there is none to make:
* where the path of {@code hive}'s scratch folder, the last {@code hive.exec.scratchdir} its arguments set, leads
@@ -66,7 +66,8 @@ public interface SparkJobRunner {
* (its settings, then its query files and parameters); or {@code command}, when not
* null, what the container runs in place of {@code spark-submit}, where a {@code spark-submit} it starts
* gets Floci's settings and the {@code spark-defaults} as defaults (its {@code application} is then
* empty); how long it may run
* empty), or, for a Hive run, what runs in place of {@code hive}, followed by Floci's settings and the
* {@code application} (an EMR step's {@code hive-script ... --args}); how long it may run
* ({@link Duration#ZERO} for no limit); the S3 folder its driver's {@code stdout.gz} and
* {@code stderr.gz} go to once it ends, ending in a slash (null for none); where in CloudWatch Logs
* its driver's output goes while it runs (null for nowhere but Floci's log); the environment variables
@@ -88,6 +89,13 @@ public interface SparkJobRunner {
List<String> archives, Storage storage, Map<String, String> coreSite,
Map<String, String> sparkLog4j2, Map<String, String> mapredSite, Map<String, String> hadoopLog4j,
Map<String, String> hadoopEnvironment) {
/** This job, run in {@code image}. */
public Job inImage(String image) {
return new Job(service, runId, accountId, region, releaseLabel, engine, image, customImage, dockerNetwork,
executionRole, sparkDefaults, application, command, timeout, logFolder, cloudWatchLogs, environment,
archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j, hadoopEnvironment);
}
}
/**
+1
View File
@@ -623,6 +623,7 @@ floci:
runner-mode: immediate # docker = run bootstrap actions and steps in containers
# 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" # Hive for clusters with Hive
# 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,226 @@
package io.github.hectorvent.floci.services.emr;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.testing.AwsTestClients;
import io.github.hectorvent.floci.testing.ContainerDataPlaneProfile;
import io.github.hectorvent.floci.testing.DockerAvailability;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.github.hectorvent.floci.testing.S3TestClients;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.glue.GlueClient;
import software.amazon.awssdk.services.glue.model.Table;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.S3Object;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.zip.GZIPInputStream;
import static io.github.hectorvent.floci.testing.EmrRequests.awaitStep;
import static io.github.hectorvent.floci.testing.EmrRequests.emr;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
/**
* EMR Hive steps through Floci's Docker runner for real: on a cluster with Hive in the {@code docker} runner mode, the
* AWS CLI's Hive step runs {@code hive-script} in a container of the cluster's image, the release's EMR Serverless
* image with its EMR Serverless Hive image's Hive, which Floci makes once, on the cluster's storage, its HDFS and
* metastore, and on Floci's S3. The cached {@code emr-7.5.0} images keep a local run from pulling; CI pulls the Hive
* one (2.7 GB) and the Spark one (3.5 GB) the first time.
*/
@QuarkusTest
@TestProfile(ContainerDataPlaneProfile.class)
class EmrHiveStepsDockerIntegrationTest {
private static final ObjectMapper JSON = new ObjectMapper();
private static final String REGION = "us-east-1";
private static final String ROWS = "a,1\nb,2\nc,3\n";
private static final String HIVE_AND_SPARK = "[{\"Name\":\"Hadoop\"},{\"Name\":\"Hive\"},{\"Name\":\"Spark\"}]";
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
private S3Client s3;
private String bucket;
private String clusterId;
@BeforeAll
static void configure() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@BeforeEach
void putInputs() throws InterruptedException {
assumeTrue(DockerAvailability.isAvailable(), "Docker daemon must be available for EMR's Hive steps");
s3 = AwsTestClients.create(S3Client.builder().forcePathStyle(true), "000000000000", Region.US_EAST_1);
cleanup.register(s3::close);
bucket = "emr-hive-" + UUID.randomUUID().toString().substring(0, 8);
s3.createBucket(request -> request.bucket(bucket));
cleanup.register(() -> S3TestClients.deleteBucket(s3, bucket));
put("data/rows/rows.csv", ROWS);
}
@Test
void hiveStepsKeepTheirTablesInTheClustersMetastoreAndHdfsForTheStepsAfterThem() {
startCluster(HIVE_AND_SPARK, "[]", null);
put("queries/load.q", """
create external table kv (k string, v int)
row format delimited fields terminated by ',' location '${INPUT}';
create table scaled as select k, v * 10 as v from kv;
""");
put("queries/report.q", """
insert overwrite directory '${OUTPUT}' row format delimited fields terminated by ','
select k, v from scaled order by k;
select k, v from scaled order by k;
""");
assertEquals("COMPLETED", hiveStep("-f", s3Uri("queries/load.q"), "-d", "INPUT=" + s3Uri("data/rows/")));
// The table the first step made is in the cluster's metastore for the second.
String report = addStep("command-runner.jar", "hive-script", "--run-hive-script", "--args",
"-f", s3Uri("queries/report.q"), "-d", "OUTPUT=" + s3Uri("out/report/"));
assertEquals("COMPLETED", state(report));
assertEquals("a,10\nb,20\nc,30\n", objects("out/report/"));
assertTrue(stepLog(report, "stdout.gz").contains("a\t10\nb\t20\nc\t30\n"));
// Its data is in the cluster's HDFS, which a step in the Spark image reads as hdfs://.
String cat = addStep("command-runner.jar", "hadoop", "fs", "-cat", "hdfs:///user/hive/warehouse/scaled/*");
assertEquals("COMPLETED", state(cat));
assertEquals("a\u000110\nb\u000120\nc\u000130\n", stepLog(cat, "stdout.gz"));
// The metastore is the cluster's own, a database in its /mnt.
assertEquals("COMPLETED", state(addStep("command-runner.jar", "test", "-d", "/mnt/var/lib/hive/metastore_db")));
}
@Test
void aClustersHiveSiteForTheGlueDataCatalogKeepsItsHiveStepsTablesInFlocisGlue() {
String database = bucket.replace('-', '_');
GlueClient glue = AwsTestClients.create(GlueClient.builder(), "000000000000", Region.US_EAST_1);
cleanup.register(glue::close);
cleanup.register(() -> glue.deleteDatabase(request -> request.name(database)));
// The Release Guide's hive-site for the Glue Data Catalog.
startCluster(HIVE_AND_SPARK, """
[{"Classification": "hive-site", "Properties": {"hive.metastore.client.factory.class":
"com.amazonaws.glue.catalog.metastore.AWSGlueDataCatalogHiveClientFactory"}}]""", null);
assertEquals("COMPLETED", hiveStep("-e", "create database " + database + " location '"
+ s3Uri("warehouse/") + "'; create external table " + database + ".kv (k string, v int) row format"
+ " delimited fields terminated by ',' location '" + s3Uri("data/rows/") + "';"));
assertEquals(List.of("kv"), glue.getTables(request -> request.databaseName(database)).tableList()
.stream().map(Table::name).toList());
}
@Test
void aHiveStepOnAClusterWithoutHiveFailsAsEmrsHiveScriptDoes() {
startCluster("[{\"Name\":\"Hadoop\"},{\"Name\":\"Spark\"}]", "[]", null);
String query = addStep("command-runner.jar", "hive-script", "--run-hive-script", "--args", "-e", "select 1");
assertEquals("FAILED", state(query));
assertTrue(stepLog(query, "stdout.gz").contains("Hive isn't installed."));
}
@Test
void whatABootstrapInstalledIsThereForTheClustersHiveAndOtherSteps() {
// One action, as the Management Guide's "Run custom bootstrap actions" has them: a file in the hadoop user's
// home, and a command installed with sudo.
put("bootstrap/install.sh", String.join("\n", "#!/bin/bash",
"echo bootstrapped > /home/hadoop/marker.txt",
"printf '%s\\n' '#!/bin/bash' 'echo installed' | sudo tee /usr/local/bin/floci-probe > /dev/null",
"sudo chmod +x /usr/local/bin/floci-probe", ""));
startCluster(HIVE_AND_SPARK, "[]", s3Uri("bootstrap/install.sh"));
String query = addStep("command-runner.jar", "hive-script", "--run-hive-script", "--args",
"-e", "!cat /home/hadoop/marker.txt; !/usr/local/bin/floci-probe;");
assertEquals("COMPLETED", state(query));
assertTrue(stepLog(query, "stdout.gz").contains("bootstrapped\ninstalled\n"));
String probe = addStep("command-runner.jar", "floci-probe");
assertEquals("COMPLETED", state(probe));
assertEquals("installed\n", stepLog(probe, "stdout.gz"));
}
/** A cluster with {@code applications}, {@code configurations} and a bootstrap action's script, if not null. */
private void startCluster(String applications, String configurations, String bootstrapScript) {
ObjectNode request = JSON.createObjectNode().put("Name", "hive-steps").put("ReleaseLabel", "emr-7.5.0")
.put("LogUri", s3Uri("logs/"));
try {
request.set("Applications", JSON.readTree(applications));
request.set("Configurations", JSON.readTree(configurations));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
if (bootstrapScript != null) {
ArrayNode actions = request.putArray("BootstrapActions");
actions.addObject().put("Name", "marker").putObject("ScriptBootstrapAction").put("Path", bootstrapScript);
}
request.putObject("Instances").put("KeepJobFlowAliveWhenNoSteps", true).putArray("InstanceGroups")
.addObject().put("Name", "primary").put("InstanceRole", "MASTER").put("InstanceType", "m5.xlarge")
.put("InstanceCount", 1);
clusterId = emr("RunJobFlow", request.toString()).then().statusCode(200).extract().jsonPath()
.getString("JobFlowId");
cleanup.register(() -> emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + clusterId + "\"]}")
.then().statusCode(200));
}
/** Runs the AWS CLI's Hive step with {@code args} and returns the state it ended in. */
private String hiveStep(String... args) {
List<String> command = new ArrayList<>(List.of("hive-script", "--run-hive-script", "--args"));
command.addAll(List.of(args));
return state(addStep("command-runner.jar", command.toArray(String[]::new)));
}
/** Adds one step to the cluster and returns its id. */
private String addStep(String jar, String... args) {
ObjectNode request = JSON.createObjectNode().put("JobFlowId", clusterId);
ObjectNode step = request.putArray("Steps").addObject().put("Name", args[0]).put("ActionOnFailure", "CONTINUE");
ObjectNode hadoopJarStep = step.putObject("HadoopJarStep").put("Jar", jar);
List.of(args).forEach(hadoopJarStep.putArray("Args")::add);
return emr("AddJobFlowSteps", request.toString()).then().statusCode(200).extract().jsonPath()
.getString("StepIds[0]");
}
private String state(String stepId) {
Response ended = awaitStep(clusterId, stepId);
return ended.jsonPath().getString("Step.Status.State");
}
/** A log of the step's, in the step log folder of the Management Guide's "Log locations". */
private String stepLog(String stepId, String name) {
String key = "logs/" + clusterId + "/steps/" + stepId + "/" + name;
try (GZIPInputStream in = new GZIPInputStream(s3.getObject(request -> request.bucket(bucket).key(key)))) {
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private void put(String key, String text) {
s3.putObject(request -> request.bucket(bucket).key(key), RequestBody.fromString(text));
}
private String s3Uri(String key) {
return "s3://" + bucket + "/" + key;
}
/** The objects under {@code prefix}, in key order, one after the other. */
private String objects(String prefix) {
StringBuilder text = new StringBuilder();
for (S3Object object : s3.listObjectsV2(request -> request.bucket(bucket).prefix(prefix)).contents()) {
text.append(s3.getObjectAsBytes(request -> request.bucket(bucket).key(object.key())).asUtf8String());
}
return text.toString();
}
}
@@ -0,0 +1,377 @@
package io.github.hectorvent.floci.services.emr;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CopyArchiveFromContainerCmd;
import com.github.dockerjava.api.command.CopyArchiveToContainerCmd;
import com.github.dockerjava.api.command.CreateContainerCmd;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.command.InfoCmd;
import com.github.dockerjava.api.command.InspectImageCmd;
import com.github.dockerjava.api.command.InspectImageResponse;
import com.github.dockerjava.api.command.RemoveContainerCmd;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.ContainerConfig;
import com.github.dockerjava.api.model.Info;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.EmulatorConfig.EcsServiceConfig.ImagePullBehavior;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
import io.github.hectorvent.floci.core.common.docker.RetryingTarCopier;
import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService;
import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService.LaunchImage;
import io.github.hectorvent.floci.testing.ThreadStates;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
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 java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
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.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** The image a release's clusters with Hive run in, made of its EMR Serverless and EMR Serverless Hive images. */
class EmrReleaseImagesTest {
private static final String SPARK = "public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest";
private static final String HIVE = "public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest";
private final EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
private final DockerClient docker = mock(DockerClient.class);
private final ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
private final ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
private final ImageCacheService imageCache = mock(ImageCacheService.class);
private final EmrReleaseImages images = new EmrReleaseImages(lifecycle, containerBuilder, imageCache, config);
@Test
void aCopyPutsItsSourceUnderItsNameInItsFolderAndTezsGoodiesLinksLeadToTheHiveImagesCopy() throws IOException {
byte[] tez = tar(
directory("tez/"),
symlink("tez/tez-emr-serverless.jar",
"/usr/share/aws/emr/serverless-goodies/lib/tez-emr-serverless.jar"),
symlink("tez/conf", "/etc/tez/conf"),
file("tez/tez-api.jar", "api"),
hardLink("tez/tez-api-copy.jar", "tez/tez-api.jar"));
byte[] goodies = tar(directory("lib/"), file("lib/goodies.jar", "hive's"),
symlink("lib/latest.jar", "goodies.jar"));
byte[] conf = tar(directory("conf/"), file("conf/hadoop-env.sh", "TEZ"),
hardLink("conf/env", "conf/hadoop-env.sh"));
assertEquals(List.of("tez/ dir", "tez/tez-emr-serverless.jar -> "
+ "/usr/share/aws/emr/serverless-goodies-hive/lib/tez-emr-serverless.jar",
"tez/conf -> /etc/tez/conf", "tez/tez-api.jar = api", "tez/tez-api-copy.jar => tez/tez-api.jar"),
entries(copied(tez, new EmrReleaseImages.Copy("/usr/lib/tez", "/usr/lib"))));
// The Hive image's goodies go to a folder of their own, which the EMR Serverless image does not have.
assertEquals(List.of("serverless-goodies-hive/ dir", "serverless-goodies-hive/lib/ dir",
"serverless-goodies-hive/lib/goodies.jar = hive's",
"serverless-goodies-hive/lib/latest.jar -> goodies.jar"),
entries(copied(goodies, new EmrReleaseImages.Copy("/usr/share/aws/emr/serverless-goodies/lib",
"/usr/share/aws/emr", "serverless-goodies-hive/lib"))));
assertEquals(List.of("conf.hive/ dir", "conf.hive/hadoop-env.sh = TEZ",
"conf.hive/env => conf.hive/hadoop-env.sh"),
entries(copied(conf, EmrReleaseImages.Copy.to("/etc/hadoop/conf", "/etc/hadoop/conf.hive"))));
}
@Test
void theHiveImagesHadoopConfigurationGoesWhereHiveRunsWithIt() {
assertTrue(EmrReleaseImages.COPIES.contains(new EmrReleaseImages.Copy("/etc/hadoop/conf", "/etc/hadoop",
"conf.hive")));
}
@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));
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.
verify(lifecycle).commit(eq("target"), eq(repository),
argThat(tag -> tag.matches("emr-7\\.5\\.0-[0-9a-f]{12}")), eq("hadoop:hadoop"),
argThat((Map<String, String> labels) ->
"emr-release".equals(labels.get(ContainerStorageHelper.COMPONENT_LABEL))));
verify(docker).removeContainerCmd("target");
verify(docker).removeContainerCmd("source");
}
@Test
void aSecondThreadAskingWhileTheImageIsMadeWaitsThenFindsItThere() throws InterruptedException {
when(lifecycle.getDockerClient()).thenReturn(docker);
when(containerBuilder.resolveImage(anyString())).thenAnswer(invocation -> invocation.getArgument(0));
resolvesEachToItself();
String repository = ContainerStorageHelper.dockerName(config, "emr-release");
AtomicBoolean made = new AtomicBoolean();
when(docker.inspectImageCmd(anyString())).thenAnswer(invocation -> {
String image = invocation.getArgument(0);
InspectImageCmd inspect = mock(InspectImageCmd.class);
InspectImageResponse response = mock(InspectImageResponse.class, RETURNS_DEEP_STUBS);
when(response.getId()).thenReturn("sha256:made");
if (image.startsWith(repository + ":") && !made.get()) {
when(inspect.exec()).thenThrow(new NotFoundException("missing"));
} else {
when(inspect.exec()).thenReturn(response);
}
return inspect;
});
CreateContainerCmd create = mock(CreateContainerCmd.class, RETURNS_SELF);
when(create.exec()).thenReturn(mock(CreateContainerResponse.class));
when(docker.createContainerCmd(anyString())).thenReturn(create);
when(docker.copyArchiveFromContainerCmd(any(), anyString())).thenAnswer(invocation -> {
CopyArchiveFromContainerCmd from = mock(CopyArchiveFromContainerCmd.class);
when(from.exec()).thenAnswer(read -> new ByteArrayInputStream(new byte[0]));
return from;
});
when(docker.copyArchiveToContainerCmd(any())).thenReturn(mock(CopyArchiveToContainerCmd.class, RETURNS_SELF));
when(docker.removeContainerCmd(any())).thenReturn(mock(RemoveContainerCmd.class, RETURNS_SELF));
CountDownLatch committing = new CountDownLatch(1);
CountDownLatch committed = new CountDownLatch(1);
when(lifecycle.commit(any(), anyString(), anyString(), any(), any())).thenAnswer(invocation -> {
committing.countDown();
assertTrue(committed.await(10, TimeUnit.SECONDS));
made.set(true);
return "sha256:made";
});
Thread first = Thread.ofPlatform().start(() -> images.image("emr-7.5.0", SPARK, HIVE));
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)));
ThreadStates.awaitBlockedOrDone(second);
committed.countDown();
first.join(10_000);
second.join(10_000);
// One container of each image, one commit: the second found the image the first made.
verify(docker, times(2)).createContainerCmd(anyString());
verify(lifecycle, times(1)).commit(any(), anyString(), anyString(), any(), any());
assertEquals("sha256:made", found.get());
}
@Test
void anImageThatIsThereIsUsedAsItIs() {
when(lifecycle.getDockerClient()).thenReturn(docker);
when(containerBuilder.resolveImage(anyString())).thenAnswer(invocation -> invocation.getArgument(0));
InspectImageCmd there = mock(InspectImageCmd.class);
InspectImageResponse made = mock(InspectImageResponse.class);
when(made.getId()).thenReturn("sha256:made");
when(there.exec()).thenReturn(made);
when(docker.inspectImageCmd(anyString())).thenReturn(there);
resolvesEachToItself();
assertEquals("sha256:made", images.image("emr-7.5.0", SPARK, HIVE));
verify(docker, never()).createContainerCmd(anyString());
verify(lifecycle, never()).commit(any(), anyString(), anyString(), any(), any());
}
@Test
void anImageIsNamedAfterTheIdsOfTheImagesItIsMadeOfSoANewerPullMakesAnother() {
when(lifecycle.getDockerClient()).thenReturn(docker);
when(containerBuilder.resolveImage(anyString())).thenAnswer(invocation -> invocation.getArgument(0));
resolves(SPARK, "sha256:spark");
// The Hive image's name leads to another id once a newer image is pulled under it.
when(imageCache.resolveForLaunch(HIVE, ImagePullBehavior.PREFER_CACHED, null)).thenReturn(
new LaunchImage("sha256:hive", null), new LaunchImage("sha256:hive", null),
new LaunchImage("sha256:newer-hive", null));
List<String> asked = new ArrayList<>();
when(docker.inspectImageCmd(anyString())).thenAnswer(invocation -> {
asked.add(invocation.getArgument(0));
InspectImageCmd there = mock(InspectImageCmd.class);
when(there.exec()).thenReturn(mock(InspectImageResponse.class));
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);
assertEquals(asked.get(0), asked.get(1));
assertNotEquals(asked.get(0), asked.get(2));
}
@Test
void aNewerPullOfAnImageItIsMadeOfMakesAnotherThroughTheImageCache() {
// A daemon whose local tags a test moves, as a docker pull would, keeping the image a tag leaves, behind a real
// image cache.
Map<String, String> tags = new HashMap<>(Map.of(SPARK, "sha256:spark", HIVE, "sha256:hive"));
Set<String> images = new HashSet<>(tags.values());
String repository = ContainerStorageHelper.dockerName(config, "emr-release");
List<String> asked = new ArrayList<>();
DockerClient daemon = mock(DockerClient.class);
InfoCmd info = mock(InfoCmd.class);
when(info.exec()).thenReturn(new Info().withOsType("linux").withArchitecture("amd64"));
when(daemon.infoCmd()).thenReturn(info);
when(daemon.inspectImageCmd(anyString())).thenAnswer(invocation -> {
String reference = invocation.getArgument(0);
InspectImageCmd inspect = mock(InspectImageCmd.class);
if (reference.startsWith(repository + ":")) {
// The image made of them, there whatever its name.
asked.add(reference);
when(inspect.exec()).thenReturn(new InspectImageResponse().withId("sha256:made"));
} else if (tags.containsKey(reference) || images.contains(reference)) {
when(inspect.exec()).thenReturn(new InspectImageResponse()
.withId(tags.getOrDefault(reference, reference)).withOs("linux").withArch("amd64")
.withRepoDigests(List.of()));
} else {
when(inspect.exec()).thenThrow(new NotFoundException("No such image: " + reference));
}
return inspect;
});
EmulatorConfig cacheConfig = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(cacheConfig.docker().registryCredentials()).thenReturn(List.of());
when(cacheConfig.docker().imagePullTimeoutSeconds()).thenReturn(300);
when(lifecycle.getDockerClient()).thenReturn(daemon);
when(containerBuilder.resolveImage(anyString())).thenAnswer(invocation -> invocation.getArgument(0));
EmrReleaseImages cached = new EmrReleaseImages(lifecycle, containerBuilder,
new ImageCacheService(daemon, cacheConfig), config);
cached.image("emr-7.5.0", SPARK, HIVE);
tags.put(HIVE, "sha256:newer-hive");
images.add("sha256:newer-hive");
cached.image("emr-7.5.0", SPARK, HIVE);
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.
private void resolves(String image, String id) {
when(imageCache.resolveForLaunch(image, ImagePullBehavior.PREFER_CACHED, null))
.thenReturn(new LaunchImage(id, null));
}
private void resolvesEachToItself() {
when(imageCache.resolveForLaunch(anyString(), eq(ImagePullBehavior.PREFER_CACHED), isNull()))
.thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null));
}
private void container(String image, String id) {
CreateContainerCmd create = mock(CreateContainerCmd.class, RETURNS_SELF);
CreateContainerResponse created = mock(CreateContainerResponse.class);
when(created.getId()).thenReturn(id);
when(create.exec()).thenReturn(created);
when(docker.createContainerCmd(image)).thenReturn(create);
}
private static byte[] copied(byte[] archive, EmrReleaseImages.Copy copy) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
EmrReleaseImages.copy(new ByteArrayInputStream(archive), out, copy);
return out.toByteArray();
}
// Each entry as one line: a folder, a file and its text, a symbolic link and where it leads, or a hard link.
private static List<String> entries(byte[] archive) throws IOException {
List<String> entries = new ArrayList<>();
try (TarArchiveInputStream in = new TarArchiveInputStream(new ByteArrayInputStream(archive))) {
TarArchiveEntry entry;
while ((entry = in.getNextEntry()) != null) {
if (entry.isDirectory()) {
entries.add(entry.getName() + " dir");
} else if (entry.isSymbolicLink()) {
entries.add(entry.getName() + " -> " + entry.getLinkName());
} else if (entry.isLink()) {
entries.add(entry.getName() + " => " + entry.getLinkName());
} else {
entries.add(entry.getName() + " = " + new String(in.readAllBytes(), StandardCharsets.UTF_8));
}
}
}
return entries;
}
private static byte[] tar(Entry... entries) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (TarArchiveOutputStream tar = RetryingTarCopier.newTarStream(out)) {
for (Entry entry : entries) {
tar.putArchiveEntry(entry.header());
tar.write(entry.content());
tar.closeArchiveEntry();
}
}
return out.toByteArray();
}
private static Entry directory(String name) {
return new Entry(new TarArchiveEntry(name), new byte[0]);
}
private static Entry file(String name, String text) {
byte[] content = text.getBytes(StandardCharsets.UTF_8);
TarArchiveEntry header = new TarArchiveEntry(name);
header.setSize(content.length);
return new Entry(header, content);
}
private static Entry symlink(String name, String target) {
TarArchiveEntry header = new TarArchiveEntry(name, TarConstants.LF_SYMLINK);
header.setLinkName(target);
return new Entry(header, new byte[0]);
}
private static Entry hardLink(String name, String target) {
TarArchiveEntry header = new TarArchiveEntry(name, TarConstants.LF_LINK);
header.setLinkName(target);
return new Entry(header, new byte[0]);
}
private record Entry(TarArchiveEntry header, byte[] content) {
}
}
@@ -317,9 +317,9 @@ class EmrServiceContainerStepsTest {
@Test
void aStepFlociDoesNotRunFailsWithoutRunning() {
EmrStep hive = sparkStep("query", "CONTINUE");
hive.setArgs(List.of("hive-script", "--run-hive-script", "--args", "-f", "s3://bucket/query.q"));
EmrCluster cluster = service.runJobFlow(cluster("hive", true, hive), REGION);
EmrStep pig = sparkStep("query", "CONTINUE");
pig.setArgs(List.of("pig-script", "--run-pig-script", "--args", "-f", "s3://bucket/query.pig"));
EmrCluster cluster = service.runJobFlow(cluster("pig", true, pig), REGION);
fixture.runStepThread();
@@ -545,7 +545,8 @@ class EmrServiceContainerStepsTest {
new EmrService(new InMemoryStorageFactory(ACCOUNT), config, regionResolver,
new EmrEventPublisher(mock(EventBridgeService.class), new ObjectMapper(), regionResolver),
sparkRunner, bootstrapRunner, clusterStorage, mock(IamService.class)).shutdown();
sparkRunner, bootstrapRunner, clusterStorage, mock(EmrReleaseImages.class), mock(IamService.class))
.shutdown();
verify(sparkRunner, times(reconcile ? 1 : 0)).removeLeftoverDrivers("emr");
verify(bootstrapRunner, times(reconcile ? 1 : 0)).removeImages(Set.of());
@@ -587,6 +588,8 @@ class EmrServiceContainerStepsTest {
bootstrapping.runStepThread();
assertEquals(IMAGE, runner.jobs.get(0).imageTemplate());
// A cluster without Hive runs in the release's EMR Serverless image, which none makes.
assertEquals(List.of(), bootstrapping.releaseImages.asked);
assertEquals("COMPLETED", bootstrapping.service.describeStep(cluster.getId(), stepId).getState());
assertEquals(List.of("STARTING", "PENDING report", "RUNNING report", "COMPLETED report", "WAITING"),
bootstrapping.states());
@@ -605,6 +608,126 @@ class EmrServiceContainerStepsTest {
assertNull(runner.jobs.get(0).imageTemplate());
}
@Test
void aHiveStepOnAClusterWithHiveRunsHiveScriptsHiveOnTheClustersStorage() {
EmrStep query = hiveStep("report", "-f", "s3://bucket/queries/report.q", "-d", "INPUT=s3://bucket/in/");
EmrCluster requested = cluster("hive", true, query);
requested.setApplications("[{\"Name\": \"Hive\"}, {\"Name\": \"Spark\"}]");
requested.setLogUri("s3://logs/emr/");
requested.setConfigurations("""
[{"Classification": "hive-site", "Properties": {"hive.exec.reducers.max": "8"}},
{"Classification": "hive-env", "Configurations": [
{"Classification": "export", "Properties": {"HADOOP_HEAPSIZE": "2048"}}]},
{"Classification": "spark-defaults", "Properties": {"spark.executor.cores": "2"}},
{"Classification": "spark-env", "Configurations": [
{"Classification": "export", "Properties": {"PYSPARK_PYTHON": "/usr/bin/python3.11"}}]}]""");
EmrCluster cluster = service.runJobFlow(requested, REGION);
String stepId = cluster.getSteps().get(0).getId();
fixture.runStepThread();
SparkJobRunner.Job job = runner.jobs.get(0);
assertEquals(SparkJobRunner.Engine.HIVE, job.engine());
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);
assertEquals(EmrServiceFixture.RecordingReleaseImages.IMAGE, job.imageTemplate());
assertNull(job.customImage());
assertEquals(List.of("hive-script", "--run-hive-script", "--args"), job.command());
assertEquals(List.of("--hiveconf", "hive.exec.reducers.max=8", "-f", "s3://bucket/queries/report.q", "-d",
"INPUT=s3://bucket/in/"), job.application());
// Its cluster's Spark settings are not Hive's.
assertEquals(Map.of(), job.sparkDefaults());
assertEquals(Map.of("HADOOP_HEAPSIZE", "2048"), job.environment());
assertEquals(new SparkJobRunner.Storage(cluster.getId() + "-home", cluster.getId() + "-mnt"), job.storage());
assertEquals("s3://logs/emr/" + cluster.getId() + "/steps/" + stepId + "/", job.logFolder());
assertEquals(List.of(cluster.getId()), fixture.clusterStorage.created);
assertEquals("COMPLETED", service.describeStep(cluster.getId(), stepId).getState());
}
@Test
void aClusterWithHivesImageIsMadeOfTheImagesTheTemplatesNameAndItsSparkStepsRunInItToo() {
EmrService templated = fixture.withHiveImageTemplate("registry.internal/emr-serverless/hive/%s:20250425");
EmrCluster requested = cluster("templated", true, sparkStep("report", "CONTINUE"));
requested.setApplications("[{\"Name\": \"Hive\"}, {\"Name\": \"Spark\"}]");
templated.runJobFlow(requested, REGION);
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);
assertEquals(SparkJobRunner.Engine.SPARK, runner.jobs.get(0).engine());
assertEquals(EmrServiceFixture.RecordingReleaseImages.IMAGE, runner.jobs.get(0).imageTemplate());
}
@Test
void aBootstrappedClusterWithHiveBootstrapsInItsImageAndItsStepsRunInTheImageTheBootstrapLeft() {
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
EmrCluster requested = bootstrapped(cluster("bootstrapped-hive", true, hiveStep("report", "-e", "select 1")));
requested.setApplications("[{\"Name\": \"Hive\"}]");
bootstrapping.service.runJobFlow(requested, REGION);
bootstrapping.runStepThread();
bootstrapping.runStepThread();
assertEquals(EmrServiceFixture.RecordingReleaseImages.IMAGE, bootstrap.bootstraps.get(0).imageTemplate());
assertEquals(SparkJobRunner.Engine.HIVE, runner.jobs.get(0).engine());
assertEquals(IMAGE, runner.jobs.get(0).imageTemplate());
// Made once, for the bootstrap: the image it left holds it.
assertEquals(1, bootstrapping.releaseImages.asked.size());
}
@Test
void aClusterWithHiveThatEndsBeforeItsBootstrapOrStepRunsMakesNoImage() {
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
EmrCluster unbooted = bootstrapped(cluster("ended-bootstrapping", true));
unbooted.setApplications("[{\"Name\": \"Hive\"}]");
String unbootedId = bootstrapping.service.runJobFlow(unbooted, REGION).getId();
EmrCluster unrun = cluster("ended-running", true, hiveStep("report", "-e", "select 1"));
unrun.setApplications("[{\"Name\": \"Hive\"}]");
String unrunId = service.runJobFlow(unrun, REGION).getId();
bootstrapping.service.terminateJobFlows(List.of(unbootedId));
service.terminateJobFlows(List.of(unrunId));
bootstrapping.runStepThread();
fixture.runStepThread();
// Each image would be pulled, several GB, and made: a thread that comes after the cluster's end makes none.
assertEquals(List.of(), bootstrapping.releaseImages.asked);
assertEquals(List.of(), fixture.releaseImages.asked);
}
@Test
void anImageWithHiveThatCannotBeMadeFailsTheStepOrEndsTheBootstrappingCluster() {
fixture.releaseImages.failure = new IllegalStateException("Could not pull the Hive image");
EmrCluster requested = cluster("unmade", true, hiveStep("report", "-e", "select 1"));
requested.setApplications("[{\"Name\": \"Hive\"}]");
EmrCluster cluster = service.runJobFlow(requested, REGION);
fixture.runStepThread();
EmrStep failed = service.describeStep(cluster.getId(), cluster.getSteps().get(0).getId());
assertEquals("FAILED", failed.getState());
assertEquals("The step could not start: Could not pull the Hive image", failed.getFailureMessage());
assertEquals(List.of(), runner.jobs);
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
bootstrapping.releaseImages.failure = new IllegalStateException("Could not pull the Hive image");
EmrCluster unbooted = bootstrapped(cluster("unbooted", true));
unbooted.setApplications("[{\"Name\": \"Hive\"}]");
String unbootedId = bootstrapping.service.runJobFlow(unbooted, REGION).getId();
bootstrapping.runStepThread();
EmrCluster ended = bootstrapping.service.describeCluster(unbootedId);
assertEquals("TERMINATED_WITH_ERRORS", ended.getState());
assertEquals(List.of("INTERNAL_ERROR",
"Floci could not run the bootstrap actions: Could not pull the Hive image"),
List.of(ended.getStateChangeReasonCode(), ended.getStateChangeMessage()));
assertEquals(List.of(), bootstrap.bootstraps);
}
@Test
void aFailedBootstrapActionEndsTheClusterWithErrorsBeforeAnyStepRuns() {
bootstrap.outcome = BootstrapRunner.Outcome.actionFailed(2, 1);
@@ -789,7 +912,7 @@ class EmrServiceContainerStepsTest {
@Test
void aClusterWhoseStepsNoContainerRanHasNoStorage() {
EmrStep query = sparkStep("query", "CONTINUE");
query.setArgs(new ArrayList<>(List.of("hive-script", "--run-hive-script", "--args", "-f", "s3://bucket/q.q")));
query.setArgs(new ArrayList<>(List.of("pig-script", "--run-pig-script", "--args", "-f", "s3://bucket/q.pig")));
EmrCluster cluster = service.runJobFlow(cluster("unrun", true, query), REGION);
fixture.runStepThread();
@@ -863,6 +986,18 @@ class EmrServiceContainerStepsTest {
}
// A spark-submit step through command-runner.jar, written for a cluster with YARN.
// The AWS CLI's Hive step: command-runner.jar running hive-script with the step's arguments after its --args.
private static EmrStep hiveStep(String name, String... args) {
EmrStep step = new EmrStep();
step.setName(name);
step.setActionOnFailure("CONTINUE");
step.setJar("command-runner.jar");
List<String> command = new ArrayList<>(List.of("hive-script", "--run-hive-script", "--args"));
command.addAll(List.of(args));
step.setArgs(command);
return step;
}
private static EmrStep sparkStep(String name, String actionOnFailure) {
EmrStep step = new EmrStep();
step.setName(name);
@@ -82,6 +82,23 @@ 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.
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));
if (failure != null) {
throw failure;
}
return IMAGE;
}
}
final ObjectMapper objectMapper = new ObjectMapper();
final List<JsonNode> published = new ArrayList<>();
final MutableClock clock;
@@ -99,6 +116,7 @@ final class EmrServiceFixture {
private final BootstrapRunner bootstrap;
// The docker runner mode's; null in the immediate one.
final RecordingStorage clusterStorage;
final RecordingReleaseImages releaseImages;
private final IamService iam;
private final int[] durations;
@@ -108,7 +126,7 @@ final class EmrServiceFixture {
}
EmrServiceFixture(int startupDelaySeconds, int stepDurationSeconds, int terminationDelaySeconds) {
this(new InMemoryStorageFactory(ACCOUNT), new MutableClock(), null, null, null, null,
this(new InMemoryStorageFactory(ACCOUNT), new MutableClock(), null, null, null, null, null,
startupDelaySeconds, stepDurationSeconds, terminationDelaySeconds);
}
@@ -120,17 +138,18 @@ final class EmrServiceFixture {
/** As {@link #docker(SparkJobRunner, IamService)}, its clusters' bootstrap actions run by {@code bootstrap}. */
static EmrServiceFixture docker(SparkJobRunner runner, BootstrapRunner bootstrap, IamService iam) {
return new EmrServiceFixture(new InMemoryStorageFactory(ACCOUNT), new MutableClock(), runner, bootstrap,
new RecordingStorage(), iam, 0, 0, 0);
new RecordingStorage(), new RecordingReleaseImages(), iam, 0, 0, 0);
}
private EmrServiceFixture(InMemoryStorageFactory storage, MutableClock clock, SparkJobRunner runner,
BootstrapRunner bootstrap, RecordingStorage clusterStorage, IamService iam,
int... durations) {
BootstrapRunner bootstrap, RecordingStorage clusterStorage,
RecordingReleaseImages releaseImages, IamService iam, int... durations) {
this.storage = storage;
this.clock = clock;
this.runner = runner;
this.bootstrap = bootstrap;
this.clusterStorage = clusterStorage;
this.releaseImages = releaseImages;
this.iam = iam;
this.durations = durations;
EventBridgeService eventBridge = mock(EventBridgeService.class);
@@ -157,12 +176,12 @@ final class EmrServiceFixture {
public void deliver(Runnable delivery) {
deliveries.add(delivery);
}
}, runner, bootstrap, clusterStorage, stepThreads::add, iam);
}, runner, bootstrap, clusterStorage, releaseImages, stepThreads::add, iam);
}
/** A new service on the same storage and clock, as after a restart of Floci with persistent storage. */
EmrServiceFixture restart() {
return new EmrServiceFixture(storage, clock, runner, bootstrap, clusterStorage, iam, durations);
return new EmrServiceFixture(storage, clock, runner, bootstrap, clusterStorage, releaseImages, iam, durations);
}
/**
@@ -171,7 +190,19 @@ final class EmrServiceFixture {
*/
EmrService restartReconciling(SparkJobRunner runner, EmrService.Wakeups wakeups) {
return new EmrService(storage, config(true), new RegionResolver(REGION, ACCOUNT), publisher, clock, wakeups,
runner, bootstrap, clusterStorage, stepThreads::add, iam);
runner, bootstrap, clusterStorage, releaseImages, stepThreads::add, iam);
}
/**
* A new service on the same storage and clock, as {@link #restart} builds, whose Hive steps run in the image
* {@code hiveImageTemplate} names, its steps' threads this fixture's, and its events not delivered.
*/
EmrService withHiveImageTemplate(String hiveImageTemplate) {
EmulatorConfig config = config(false);
when(config.services().emr().hiveImageTemplate()).thenReturn(Optional.of(hiveImageTemplate));
return new EmrService(storage, config, new RegionResolver(REGION, ACCOUNT), publisher, clock,
mock(EmrService.Wakeups.class), runner, bootstrap, clusterStorage, releaseImages, stepThreads::add,
iam);
}
private EmulatorConfig config(boolean reconcile) {
@@ -181,6 +212,7 @@ final class EmrServiceFixture {
when(config.services().emr().stepDurationSeconds()).thenReturn(durations[1]);
when(config.services().emr().clusterTerminationDelaySeconds()).thenReturn(durations[2]);
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().reconcileContainersOnStartup()).thenReturn(reconcile);
return config;
@@ -21,6 +21,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
class EmrSparkStepsTest {
// A cluster's Applications, as RunJobFlow stores them, in a case of their own.
private static final String HIVE_AND_SPARK = "[{\"Name\": \"Spark\"}, {\"Name\": \"hive\"}]";
private final ObjectMapper objectMapper = new ObjectMapper();
@Test
@@ -149,14 +152,81 @@ class EmrSparkStepsTest {
@Test
void toolsTheImageDoesNotHaveAreNotRun() {
for (String tool : List.of("hive-script", "pig-script")) {
assertNull(EmrSparkSteps.command(step("command-runner.jar", null, tool, "--src", "s3://bucket/in/")));
}
assertNull(EmrSparkSteps.command(step("command-runner.jar", null, "pig-script", "--run-pig-script")));
assertNull(EmrSparkSteps.command(step("command-runner.jar", null)));
assertNull(EmrSparkSteps.command(step("script-runner.jar", null)));
assertNull(EmrSparkSteps.command(step("s3://bucket/jars/app.jar", null, "1")));
}
@Test
void aHiveStepsHiveGetsTheClustersHiveClassificationsThenTheArgumentsAfterHiveScriptsArgs() {
// The AWS CLI's Hive step, Type=Hive,Args=[-f,...,-d,...], on a cluster with Hive.
String configurations = """
[{"Classification": "hive-site", "Properties": {"hive.exec.reducers.max": "8"}},
{"Classification": "spark-defaults", "Properties": {"spark.executor.cores": "2"}},
{"Classification": "tez-site", "Properties": {"tez.grouping.max-size": "268435456"}},
{"Classification": "core-site", "Properties": {"fs.s3a.connection.maximum": "50"}},
{"Classification": "hive-site", "Properties": {"hive.metastore.client.factory.class":
"com.amazonaws.glue.catalog.metastore.AWSGlueDataCatalogHiveClientFactory"}}]""";
EmrSparkSteps.HiveCommand hive = EmrSparkSteps.hive(step("command-runner.jar", null, "hive-script",
"--run-hive-script", "--args", "-f", "s3://bucket/queries/report.q", "-d", "INPUT=s3://bucket/in/",
"--hiveconf", "hive.exec.reducers.max=4"), HIVE_AND_SPARK, configurations, objectMapper);
assertEquals(List.of("hive-script", "--run-hive-script", "--args"), hive.runner());
// core-site, then tez-site, then hive-site, as Hive reads them, and the step's own --hiveconf last.
assertEquals(List.of("--hiveconf", "fs.s3a.connection.maximum=50",
"--hiveconf", "tez.grouping.max-size=268435456",
"--hiveconf", "hive.exec.reducers.max=8",
"--hiveconf", "hive.metastore.client.factory.class="
+ "com.amazonaws.glue.catalog.metastore.AWSGlueDataCatalogHiveClientFactory",
"-f", "s3://bucket/queries/report.q", "-d", "INPUT=s3://bucket/in/",
"--hiveconf", "hive.exec.reducers.max=4"), hive.arguments());
}
@Test
void aHiveScriptStepWithoutArgsGetsThemAtItsEndAndAStepCanRunHiveItself() {
EmrSparkSteps.HiveCommand script = EmrSparkSteps.hive(step("command-runner.jar", null, "hive-script",
"--run-hive-script"), HIVE_AND_SPARK, null, objectMapper);
EmrSparkSteps.HiveCommand hive = EmrSparkSteps.hive(step("command-runner.jar", null, "/usr/bin/hive",
"-e", "select 1"), HIVE_AND_SPARK, null, objectMapper);
assertEquals(List.of("hive-script", "--run-hive-script", "--args"), script.runner());
assertEquals(List.of(), script.arguments());
assertEquals(List.of("/usr/bin/hive-script", "--run-hive-script", "--args"), EmrSparkSteps.hive(step(
"command-runner.jar", null, "/usr/bin/hive-script", "--run-hive-script", "--args", "-e", "select 1"),
HIVE_AND_SPARK, null, objectMapper).runner());
assertEquals(List.of("/usr/bin/hive"), hive.runner());
assertEquals(List.of("-e", "select 1"), hive.arguments());
}
@Test
void aStepRunsHiveOnlyWhenItsClustersApplicationsNameHive() {
EmrStep query = step("command-runner.jar", null, "hive-script", "--run-hive-script", "--args", "-f",
"s3://bucket/queries/report.q");
for (String applications : new String[]{"[{\"Name\": \"Spark\"}]", "[]", null, "[{"}) {
assertNull(EmrSparkSteps.hive(query, applications, null, objectMapper));
}
// Where hive-script then runs, it says what EMR's says without Hive: "Hive isn't installed."
assertEquals(query.getArgs(), EmrSparkSteps.command(query));
for (EmrStep other : List.of(step("command-runner.jar", null, "spark-submit", "s3://bucket/app.py"),
step("command-runner.jar", null, "hive-scripts"),
step("script-runner.jar", null, "s3://bucket/hive.sh"),
step("s3://bucket/jars/hive.jar", null, "hive"))) {
assertNull(EmrSparkSteps.hive(other, HIVE_AND_SPARK, null, objectMapper));
}
}
@Test
void theClustersHiveEnvExportsAreItsHiveStepsEnvironment() {
String configurations = """
[{"Classification": "hive-env", "Configurations": [
{"Classification": "export", "Properties": {"HADOOP_HEAPSIZE": "2048"}}]},
{"Classification": "spark-env", "Configurations": [
{"Classification": "export", "Properties": {"PYSPARK_PYTHON": "/usr/bin/python3"}}]}]""";
assertEquals(Map.of("HADOOP_HEAPSIZE", "2048"), EmrSparkSteps.hiveEnvironment(configurations, objectMapper));
}
@Test
void theClustersSparkDefaultsComeFromItsConfigurations() {
String configurations = """
@@ -222,6 +222,52 @@ class EmrServerlessSparkRunnerTest {
verify(spec, never()).withEnv(eq("FLOCI_SPARK_LOG4J2"), anyString());
}
@Test
void anEmrHiveStepRunsItsCommandOnItsClustersStorageWithItsHdfsAndMetastore() {
ContainerBuilder builder = mock(ContainerBuilder.class);
ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(builder.newContainer(anyString())).thenReturn(spec);
SparkJobRunner.Job step = hiveStep(List.of("-f", "s3://bucket/queries/report.q"));
runner(builder).run(step, progress);
verify(builder).newContainer("public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest");
// hive-script in place of hive, as the image's user, with Floci's settings after its --args.
verify(spec).withEntrypoint(argThat((List<String> entrypoint) -> entrypoint.size() == 7
&& List.of("floci", "hive-script", "--run-hive-script", "--args")
.equals(entrypoint.subList(3, 7))));
verify(spec).withCmd(EmrServerlessSparkRunner.hiveArguments(step, ENDPOINT));
verify(spec).withNamedVolume("j-1-home", "/home/hadoop");
verify(spec).withNamedVolume("j-1-mnt", "/mnt");
// In its cluster's image, which holds Spark too, Hive reads its own Hadoop configuration.
verify(spec).withEntrypoint(argThat((List<String> entrypoint) -> entrypoint.get(2).contains(
"if [ -d /etc/hadoop/conf.hive ]; then export HADOOP_CONF_DIR=/etc/hadoop/conf.hive; fi")));
verify(spec, never()).withEnv(eq("FLOCI_HADOOP_SITE"), anyString());
verify(spec, never()).withEnv(eq("FLOCI_MAPRED_SITE"), anyString());
}
@Test
void anEmrHiveStepsHiveReachesItsClustersHdfsAsViewfsAndKeepsItsMetastoreInItsMnt() {
List<String> arguments = EmrServerlessSparkRunner.hiveArguments(
hiveStep(List.of("--hiveconf", "hive.exec.reducers.max=8", "-f", "s3://bucket/queries/report.q")),
ENDPOINT);
int tez = arguments.indexOf("tez.am.client.am.port-range=40000-40100");
assertEquals(List.of(
"--hiveconf", "fs.defaultFS=hdfs:///",
"--hiveconf", "fs.hdfs.impl=org.apache.hadoop.fs.viewfs.ViewFileSystemOverloadScheme",
"--hiveconf", "fs.viewfs.mounttable.default.linkFallback=file:///mnt/hdfs",
"--hiveconf", "fs.defaultFS=viewfs:///",
"--hiveconf", "hive.metastore.client.factory.class="
+ "org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClientFactory",
"--hiveconf", "javax.jdo.option.ConnectionURL="
+ "jdbc:derby:;databaseName=/mnt/var/lib/hive/metastore_db;create=true",
"--hiveconf", "hive.metastore.schema.verification=false",
"--hiveconf", "datanucleus.schema.autoCreateAll=true",
"--hiveconf", "hive.exec.reducers.max=8", "-f", "s3://bucket/queries/report.q"),
arguments.subList(tez + 1, arguments.size()));
}
@Test
void aHiveScratchFolderInS3LeadsToTheSamePathLocallyThenItsUsersFolder() {
assertEquals("/hive/scratch/hadoop", EmrServerlessSparkRunner.hiveScratchMirror(
@@ -1359,6 +1405,14 @@ class EmrServerlessSparkRunnerTest {
Duration.ZERO, null, null, Map.of(), List.of(), null, Map.of(), Map.of(), Map.of(), Map.of(), Map.of());
}
// An EMR Hive step: hive-script's --args, then application, on cluster j-1's storage.
private static SparkJobRunner.Job hiveStep(List<String> application) {
return new SparkJobRunner.Job("emr", "s-1", "123456789012", "eu-west-1", "emr-7.5.0", HIVE, null, null,
"floci-network", "arn:aws:iam::123456789012:role/emr-ec2", Map.of(), application,
List.of("hive-script", "--run-hive-script", "--args"), Duration.ZERO, null, null, Map.of(), List.of(),
new SparkJobRunner.Storage("j-1-home", "j-1-mnt"), Map.of(), Map.of(), Map.of(), Map.of(), Map.of());
}
private static SparkJobRunner.Job customImageJob(String customImage) {
return new SparkJobRunner.Job("emr-serverless", "00f0000000000001", "123456789012", "eu-west-1", "emr-7.5.0",
SPARK, null, customImage, "floci-network", "arn:aws:iam::123456789012:role/job", Map.of(),