feat(emr): run Pig steps on Apache Pig, an opt-in download added to the cluster's image (#8636)

No AWS image carries Pig, so a Pig step failed without running. With
floci.services.emr.pig.enabled on (off by default), a docker cluster
whose Applications name Pig gets Apache Pig 0.18.0 in its image:
downloaded to a temporary file from the first of
floci.services.emr.pig.urls that gives it whole with the checksum
floci.services.emr.pig.sha256 names (a URL that fails, stalls for a
minute or gives another checksum passes to the next), then streamed
into /usr/lib/pig as EmrReleaseImages makes the image, with Tez from
the release's Hive image and a /usr/bin/pig that EMR's own pig-script
runs.

Pig runs on the image's Tez, its bundled Tez and protobuf 3 left out,
on the cluster's YARN or in local mode, with exectype=tez, a working
directory without a scheme, which S3A takes, and no task reports and
one try for counters from the MapReduce JobHistory server the cluster
does not run, then the cluster's tez-site and pig-properties, in a
pig.properties of the step's own; pig-log4j and pig-env reach Pig too. A command step's new
tez-site.xml shares Hive's Tez-on-YARN settings.

Without the setting, a Pig step on a cluster that installs Pig still
fails without running, its message naming the setting; on one that
does not, EMR's pig-script says "Pig isn't installed." as on EMR.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-16 16:25:21 -04:00
1 parent d2bca16023
commit 30f8a9985e
17 files changed
+1355 -109

No files matched your search

+7 -5
View File
@@ -114,16 +114,18 @@ starts ElbV2LambdaTargetDataPlaneIntegrationTest && ecr public.ecr.aws/lambda/py
# 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;
# EmrHiveStepsDockerIntegrationTest runs a cluster's other steps in it. Of the nightly checks,
# EmrServerlessCustomImageNightlyIntegrationTest builds its custom image on it, and
# EmrFlociContainerNightlyIntegrationTest runs a cluster's steps in it from Floci in a container.
# EmrServerlessCustomImageNightlyIntegrationTest builds its custom image on it,
# EmrFlociContainerNightlyIntegrationTest runs a cluster's steps in it from Floci in a container, and
# EmrPigStepsNightlyIntegrationTest a cluster's Pig steps.
starts EmrDockerRunnerDockerIntegrationTest EmrHiveStepsDockerIntegrationTest EmrServerlessCustomImageNightlyIntegrationTest \
EmrFlociContainerNightlyIntegrationTest \
EmrFlociContainerNightlyIntegrationTest EmrPigStepsNightlyIntegrationTest \
&& 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; every EMR cluster runs its
# HDFS in it, EmrDockerRunnerDockerIntegrationTest's and the nightly EmrFlociContainerNightlyIntegrationTest's included.
# HDFS in it, EmrDockerRunnerDockerIntegrationTest's and the nightly EmrFlociContainerNightlyIntegrationTest's and
# EmrPigStepsNightlyIntegrationTest's included.
starts EmrServerlessHiveDockerIntegrationTest EmrHiveStepsDockerIntegrationTest EmrDockerRunnerDockerIntegrationTest \
EmrFlociContainerNightlyIntegrationTest \
EmrFlociContainerNightlyIntegrationTest EmrPigStepsNightlyIntegrationTest \
&& ecr public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest
# package token in shard.txt -> images its tests are known to launch
+50 -3
View File
@@ -207,8 +207,9 @@ holding the driver and its executors, or a command or a script. The cluster itse
runs in the release's image, and says what EMR's does without Hive, "Hive isn't installed.", and the step fails. An
`emr-spark-*` release includes neither ("This release includes the following applications: AmazonCloudWatchAgent,
Delta, Hudi, Iceberg, JupyterEnterpriseGateway, Livy, and Spark."), so a cluster of one has neither, whatever its
`Applications` name: no image with Hive, no metastore service. `pig-script`, which the image does not have, is
`FAILED` without running.
`Applications` name: no image with Hive, no metastore service. A Pig step runs only where Floci adds Pig (see
**Pig steps**); on a cluster that does not install it, EMR's `pig-script`, which the image has, says "Pig isn't
installed.", and the step fails.
* **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
@@ -417,6 +418,41 @@ holding the driver and its executors, or a command or a script. The cluster itse
the Glue Data Catalog. 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.
* **Pig steps**: no AWS image carries Pig, so Floci adds Apache Pig to a cluster whose `Applications` name it only
with `pig.enabled` on (`FLOCI_SERVICES_EMR_PIG_ENABLED=true`), off by default. The cluster's image (see **Hive
steps**) then gets the Tez of its EMR Serverless Hive image, which Pig runs its scripts on, with the HDFS, MapReduce
and YARN every cluster's has, and Apache Pig in `/usr/lib/pig`, where EMR keeps it, with a `/usr/bin/pig` that runs
it: Floci downloads Apache's binary distribution, about 470 MB, to a temporary file, from the first of `pig.urls`
that gives it whole with the checksum `pig.sha256` names, Apache's download CDN then its archive, a URL that cannot
be reached, answers otherwise, sends nothing for a minute or gives another checksum passing to the next. It then
writes the 200 MB Pig runs from into the image as it makes it, leaving out the docs, the sources and the jars of Pig
on Spark, and removes the file. No URL giving it fails the step that needed the image ("The step could not start:
Could not download Apache Pig: ...", with what each URL gave), and nothing goes into an image unchecked. The image's
name holds the checksum, so a cluster with Pig has an image of its own, made once for its release and kept, as one
with Hive has. EMR's releases ship Pig 0.17.0, whose Apache build is "compatible with Hadoop 2.5+ releases", so
Floci's default is Pig 0.18.0, whose `pig-0.18.0.tar.gz` "is compatible with Hadoop 3, Spark 3, Hive 3 and HBase 2",
the Hadoop the images hold; a script that relies on what changed between the two can behave otherwise. Pig runs on
the image's Tez, as EMR's runs on EMR's, in place of the Tez its distribution bundles, whose classes need another
protobuf. Then the AWS CLI's `Type=PIG` step, `command-runner.jar` running `pig-script --run-pig-script --args` and
the step's `Args`, runs EMR's own `pig-script`, which the image has: it runs `pig` with the arguments after
`--args`, as the image's `hadoop` user in `/home/hadoop`, on the cluster's storage, so `-f s3://...` reads its
script from Floci's S3 and `-p` sets its parameters. "Pig 0.16.0 and later use Apache Tez", so Pig runs on Tez, on
the cluster's YARN with the stock Tez classes and the sizes Hive's Tez gets (see **Hive steps**), or, where it runs
none, in local mode in its JVM; `-x mapreduce`, or `exectype=mapreduce` in `pig-properties`, as the Release Guide's
Pig considerations put it, runs MapReduce instead (see **Hadoop streaming and MapReduce**). Pig reads a
configuration of its own, a copy of its `conf` folder whose `pig.properties` ends with Floci's `exectype=tez` and
`mapreduce.job.working.dir=/user/${user.name}`, then the cluster's `tez-site` and `pig-properties`, a later key
winning, Pig passing the Hadoop and Tez ones on to its jobs. Pig sets the working directory of each input's file
system to it, which S3A, Floci's `s3://`, refuses when it names another file system, as Hadoop's own default, the
HDFS home with its scheme, does; without a scheme, it is the same HDFS folder. The cluster runs no MapReduce
JobHistory server, which a job client asks about a job whose application master has ended, as Pig does for each
MapReduce job's task reports and counters, so Floci's lines also set `pig.stats.notaskreport=true` and
`yarn.app.mapreduce.client.max-retries=1`: Pig asks for no task reports, and asks once for the counters, which costs
about ten seconds a job. A `pig-log4j` adds its lines to the `log4j.properties` Pig then reads, and the exports of
`pig-env` start its `pig-env.sh`. Any command a step runs on such a cluster, `command-runner.jar pig ...` or a
script's, gets the same. With `pig.enabled` off, a Pig step on a cluster whose `Applications` name Pig is `FAILED`
without running ("Floci does not run this step: Pig is not in the image steps run in. floci.services.emr.pig.enabled
adds Apache Pig to it.").
* **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
@@ -622,7 +658,15 @@ holding the driver and its executors, or a command or a script. The cluster itse
`container:<id>`, YARN's daemons would listen on every interface of the namespace, and with `none` the steps could not
reach them, so the cluster's Spark runs in local mode.
- **MapReduce and Tez in local mode where there is no YARN.** Only a cluster that runs YARN (see **YARN**) runs them on
it; on any other, `hadoop-streaming`, a custom JAR's MapReduce and Hive's Tez run in the step's container.
it; on any other, `hadoop-streaming`, a custom JAR's MapReduce and Hive's and Pig's Tez run in the step's
container.
- **No MapReduce JobHistory server.** EMR runs one (a release's `mapred-site` classification "Restarts Hadoop
MapReduce-HistoryServer"); Floci's primary node does not, so a client asking about a MapReduce job whose application
master has ended waits for it, and gets no counters or task reports. Pig, which asks after each of its MapReduce
jobs, is set to ask once (see **Pig steps**).
- **Pig is Apache's 0.18.0, and only with `pig.enabled`.** EMR's 7.x releases ship Pig 0.17.0, whose Apache build is
for Hadoop 2; no AWS image carries Pig, so Floci downloads Apache's 0.18.0, for Hadoop 3, when it is enabled, and
runs it on the image's Tez (see **Pig steps**).
- **Tez's intermediate data is not compressed on YARN.** The images name the LZO codec for it, whose native library they
lack, so Floci turns that compression off, which a `tez-site` classification can turn back on with a codec they have.
- **No Hive metastore service in a network namespace the steps share.** With `docker-network` set to `host` or
@@ -686,6 +730,9 @@ its `STARTING` event, has its events sent after the rest of that call's.
| `FLOCI_SERVICES_EMR_YARN_NODE_MEMORY_MB` | `4096` | The memory a `docker` cluster's NodeManager offers the YARN containers its Spark executors run in (see [Running steps](#running-steps)) |
| `FLOCI_SERVICES_EMR_YARN_NODE_VCORES` | `4` | The virtual cores it offers them |
| `FLOCI_SERVICES_EMR_YARN_MAX_WORKER_NODES` | `4` | The most core and task nodes a `docker` cluster runs as containers of their own, core nodes first; 0 keeps a cluster on its primary node |
| `FLOCI_SERVICES_EMR_PIG_ENABLED` | `false` | Add Apache Pig, downloaded once per release's image, to a `docker` cluster whose `Applications` name Pig, so its Pig steps run (see [Running steps](#running-steps)) |
| `FLOCI_SERVICES_EMR_PIG_URLS` | `https://dlcdn.apache.org/pig/pig-0.18.0/pig-0.18.0.tar.gz,https://archive.apache.org/dist/pig/pig-0.18.0/pig-0.18.0.tar.gz` | Where Floci downloads Pig's binary distribution from, the first that answers; a mirror names its own |
| `FLOCI_SERVICES_EMR_PIG_SHA256` | `6845adb936a3c3bcc71451765953cae4103e410ba2f6c5a47cc9becade0a434a`, `pig-0.18.0.tar.gz`'s | The SHA-256 the download must have; set it with another distribution |
| `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
@@ -2250,6 +2250,9 @@ public interface EmulatorConfig {
@WithDefault("4")
int yarnMaxWorkerNodes();
/** Apache Pig for a {@code docker} cluster's Pig steps, which no AWS image carries; off unless enabled. */
EmrPigConfig pig();
/**
* 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
@@ -2263,6 +2266,37 @@ public interface EmulatorConfig {
boolean reconcileContainersOnStartup();
}
interface EmrPigConfig {
/**
* When true, a {@code docker} cluster whose {@code Applications} name Pig has Apache Pig in the image its steps
* run in, downloaded from {@link #urls()} when Floci makes that image, and its Pig steps run it. Off by default,
* as the download is Apache's, not AWS's, and about 470 MB.
*
* Env var: FLOCI_SERVICES_EMR_PIG_ENABLED
*/
@WithDefault("false")
boolean enabled();
/**
* Where Floci downloads Apache Pig's binary distribution from, the first that answers: Apache's download CDN,
* which serves current releases, then its archive, which keeps every release.
*
* Env var: FLOCI_SERVICES_EMR_PIG_URLS
*/
@WithDefault("https://dlcdn.apache.org/pig/pig-0.18.0/pig-0.18.0.tar.gz,"
+ "https://archive.apache.org/dist/pig/pig-0.18.0/pig-0.18.0.tar.gz")
List<String> urls();
/**
* The SHA-256 of the distribution {@link #urls()} name; one downloaded with another fails the step, and no
* image is made of it.
*
* Env var: FLOCI_SERVICES_EMR_PIG_SHA256
*/
@WithDefault("6845adb936a3c3bcc71451765953cae4103e410ba2f6c5a47cc9becade0a434a")
String sha256();
}
interface WafV2ServiceConfig {
@WithDefault("true")
boolean enabled();
@@ -23,6 +23,10 @@ import org.jboss.logging.Logger;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
@@ -43,7 +47,9 @@ import java.util.concurrent.ConcurrentHashMap;
* kept for the release's next cluster; the one a newer pull makes replaces those of its kind made before
* ({@link #KIND_LABEL}). A release of the AWS runtime for Apache Spark has no Hive image, and another
* release's HDFS and YARN do not run on its newer Hadoop, so its image gets the whole of that release's Hadoop, in a
* folder apart, which only its primary node's daemons run from.
* folder apart, which only its primary node's daemons run from. For a cluster with Pig, which no AWS image carries,
* the image gets Tez, as Pig's scripts run on it, and Apache Pig, downloaded as it is made ({@link PigDistribution}),
* whose checksum its name holds.
*/
@ApplicationScoped
public class EmrReleaseImages implements ReleaseImages {
@@ -82,6 +88,12 @@ public class EmrReleaseImages implements ReleaseImages {
new Copy("/usr/bin/s3-dist-cp", "/usr/bin"),
Copy.to("/etc/hadoop/conf", EmrServerlessSparkRunner.HIVE_HADOOP_CONF),
new Copy(GOODIES, EMR_SHARE, HIVE_GOODIES));
// What a cluster with Pig and without Hive adds to those Hadoop services: Tez, which Pig runs its scripts on, with
// its configuration and the goodies its links lead to, kept apart as for Hive.
static final List<Copy> TEZ_COPIES = List.of(
new Copy("/usr/lib/tez", "/usr/lib"),
new Copy("/etc/tez", "/etc"),
new Copy(GOODIES, EMR_SHARE, HIVE_GOODIES));
private static final String HADOOP_APART = "/opt";
// What it adds for a release of the AWS runtime for Apache Spark: another release's Hadoop, whole and kept apart.
static final List<Copy> HADOOP_APART_COPIES = List.of(
@@ -102,14 +114,17 @@ public class EmrReleaseImages implements ReleaseImages {
private final ContainerBuilder containerBuilder;
private final ImageCacheService imageCacheService;
private final EmulatorConfig config;
private final PigDistribution pigDistribution;
@Inject
public EmrReleaseImages(ContainerLifecycleManager lifecycleManager, ContainerBuilder containerBuilder,
ImageCacheService imageCacheService, EmulatorConfig config) {
ImageCacheService imageCacheService, EmulatorConfig config,
PigDistribution pigDistribution) {
this.lifecycleManager = lifecycleManager;
this.containerBuilder = containerBuilder;
this.imageCacheService = imageCacheService;
this.config = config;
this.pigDistribution = pigDistribution;
}
/** The folder of a release's image holding the Hadoop its primary node's daemons run from, or null for its own. */
@@ -124,25 +139,28 @@ public class EmrReleaseImages implements ReleaseImages {
* it to a registry for an image only this daemon has.
*/
@Override
public String image(String releaseLabel, String sparkImage, String hiveImage, boolean withHive) {
List<Copy> copies = hadoopFolder(releaseLabel) != null ? HADOOP_APART_COPIES
: withHive ? COPIES : HADOOP_COPIES;
public String image(String releaseLabel, String sparkImage, String hiveImage, boolean withHive,
boolean withPig) {
List<Copy> copies = copies(releaseLabel, withHive, withPig);
PigDistribution pig = withPig && hadoopFolder(releaseLabel) == null ? pigDistribution : null;
// What is copied, and the Pig written after it, by its checksum.
String content = copies + (pig != null ? "\n" + pig.identity() : "");
String spark = containerBuilder.resolveImage(sparkImage);
String hive = containerBuilder.resolveImage(hiveImage);
String repository = ContainerStorageHelper.dockerName(config, COMPONENT);
String kind = Digests.sha256Hex(releaseLabel + "\n" + spark + "\n" + hive + "\n" + copies).substring(0, 12);
String kind = Digests.sha256Hex(releaseLabel + "\n" + spark + "\n" + hive + "\n" + content).substring(0, 12);
synchronized (making.computeIfAbsent(repository + ":" + kind, name -> new Object())) {
String sparkId = imageCacheService.resolveForLaunch(spark, ImagePullBehavior.PREFER_CACHED, null)
.imageId();
String hiveId = imageCacheService.resolveForLaunch(hive, ImagePullBehavior.PREFER_CACHED, null).imageId();
String tag = releaseLabel + "-"
+ Digests.sha256Hex(sparkId + "\n" + hiveId + "\n" + copies).substring(0, 12);
+ Digests.sha256Hex(sparkId + "\n" + hiveId + "\n" + content).substring(0, 12);
DockerClient docker = lifecycleManager.getDockerClient();
try {
return hold(docker.inspectImageCmd(repository + ":" + tag).exec().getId());
} catch (NotFoundException e) {
LOG.infov("Making {0}:{1} for EMR clusters {2}, from {3} and {4}", repository, tag,
withHive ? "with Hive" : "without Hive", spark, hive);
(withHive ? "with Hive" : "without Hive") + (pig != null ? ", with Pig" : ""), spark, hive);
}
String user = docker.inspectImageCmd(sparkId).exec().getConfig().getUser();
Map<String, String> labels = new LinkedHashMap<>();
@@ -150,6 +168,13 @@ public class EmrReleaseImages implements ReleaseImages {
labels.put(ContainerStorageHelper.COMPONENT_LABEL, COMPONENT);
labels.put(ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config));
labels.put(KIND_LABEL, kind);
// Downloaded and checked before any container is made, and read again by a copy Docker makes retry.
Path pigArchive;
try {
pigArchive = pig != null ? pig.download() : null;
} catch (IOException e) {
throw new UncheckedIOException(e.getMessage(), e);
}
String made;
List<String> containers = new ArrayList<>();
try {
@@ -161,6 +186,12 @@ public class EmrReleaseImages implements ReleaseImages {
RetryingTarCopier.copyStreamed(docker, target, copy.into(), copy.from(),
out -> copy(docker.copyArchiveFromContainerCmd(source, copy.from()).exec(), out, copy));
}
if (pigArchive != null) {
RetryingTarCopier.copyStreamed(docker, target, PigDistribution.FOLDER, PigDistribution.HOME,
out -> PigDistribution.write(pigArchive, out));
RetryingTarCopier.copyBytes(docker, target, PigDistribution.COMMAND_FOLDER, PigDistribution.NAME,
PigDistribution.COMMAND.getBytes(StandardCharsets.UTF_8), 0755);
}
made = lifecycleManager.commit(target, repository, tag,
user == null || user.isBlank() ? "root" : user, labels);
} finally {
@@ -172,12 +203,37 @@ public class EmrReleaseImages implements ReleaseImages {
repository, tag, e.getMessage());
}
}
if (pigArchive != null) {
try {
Files.deleteIfExists(pigArchive);
} catch (IOException e) {
LOG.warnv("Could not remove {0}, the Apache Pig downloaded for {1}:{2}: {3}", pigArchive,
repository, tag, e.getMessage());
}
}
}
removeReplaced(docker, labels, made, repository + ":" + tag);
return hold(made);
}
}
// Another release's Hadoop for an emr-spark-* release, which has neither Hive nor Pig; Hive, Tez and those Hadoop
// services for a cluster with Hive; Tez and those services for one with Pig alone; those services alone otherwise.
static List<Copy> copies(String releaseLabel, boolean withHive, boolean withPig) {
if (hadoopFolder(releaseLabel) != null) {
return HADOOP_APART_COPIES;
}
if (withHive) {
return COPIES;
}
if (withPig) {
List<Copy> copies = new ArrayList<>(HADOOP_COPIES);
copies.addAll(TEZ_COPIES);
return List.copyOf(copies);
}
return HADOOP_COPIES;
}
@Override
public void released(String imageId) {
held.computeIfPresent(imageId, (id, holders) -> holders > 1 ? holders - 1 : null);
@@ -149,6 +149,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
private final String imageTemplate;
private final String hiveImageTemplate;
private final String dockerNetwork;
// Whether a cluster whose Applications name Pig gets Apache Pig in its image (floci.services.emr.pig.enabled).
private final boolean pigEnabled;
// What the NodeManager of a cluster that runs YARN offers its containers.
private final ClusterStorage.Yarn nodeManager;
private final int maxWorkerNodes;
@@ -290,6 +292,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
this.imageTemplate = config.services().emr().imageTemplate().orElse(null);
this.hiveImageTemplate = config.services().emr().hiveImageTemplate().orElse(null);
this.dockerNetwork = config.services().emr().dockerNetwork().orElse(null);
this.pigEnabled = config.services().emr().pig().enabled();
this.nodeManager = new ClusterStorage.Yarn(config.services().emr().yarnNodeMemoryMb(),
config.services().emr().yarnNodeVcores());
this.maxWorkerNodes = config.services().emr().yarnMaxWorkerNodes();
@@ -1683,8 +1686,12 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
EmrSparkSteps.HiveCommand hive = EmrSparkSteps.hive(step, cluster.getReleaseLabel(),
cluster.getApplications(), cluster.getConfigurations(), SNAPSHOT_MAPPER);
boolean yarn = runsYarn(cluster);
boolean pig = withPig(cluster);
boolean pigMissing = !pig && EmrSparkSteps.installsPig(cluster.getReleaseLabel(), cluster.getApplications(),
SNAPSHOT_MAPPER);
List<String> application = hive == null ? EmrSparkSteps.application(step, yarn) : null;
List<String> command = hive == null && application == null ? EmrSparkSteps.command(step) : null;
List<String> command = hive == null && application == null ? EmrSparkSteps.command(step, pigMissing)
: null;
SparkJobRunner.Storage storage = null;
if ((hive != null || application != null || command != null) && clusterStorage != null) {
storage = clusterStorage.volumes(cluster.getId());
@@ -1730,7 +1737,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
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(),
stepEnvironment(step, cluster, command != null && pig), List.of(),
storage, EmrSparkSteps.coreSite(cluster.getConfigurations(), SNAPSHOT_MAPPER),
EmrSparkSteps.sparkLog4j2(cluster.getConfigurations(), SNAPSHOT_MAPPER),
EmrSparkSteps.mapredSite(cluster.getConfigurations(), SNAPSHOT_MAPPER),
@@ -1895,13 +1902,30 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
}
boolean withHive = EmrSparkSteps.installsHive(cluster.getReleaseLabel(), cluster.getApplications(),
SNAPSHOT_MAPPER);
if (!withHive && !runsYarn(cluster)) {
boolean withPig = withPig(cluster);
if (!withHive && !withPig && !runsYarn(cluster)) {
return null;
}
String release = cluster.getReleaseLabel();
String spark = EmrServerlessSparkRunner.image(imageTemplate, release);
String hive = hdfsImage(release);
return () -> releaseImages.image(release, spark, hive, withHive);
return () -> releaseImages.image(release, spark, hive, withHive, withPig);
}
// Whether a cluster's image has Floci's Pig: it installs Pig, and floci.services.emr.pig.enabled adds it.
private boolean withPig(EmrCluster cluster) {
return pigEnabled && EmrSparkSteps.installsPig(cluster.getReleaseLabel(), cluster.getApplications(),
SNAPSHOT_MAPPER);
}
// The variables a step that is not a Hive step runs with: its cluster's spark-env exports and its own Properties
// (see EmrSparkSteps.environment), and for a command on a cluster with Floci's Pig, its Pig configuration.
private static Map<String, String> stepEnvironment(EmrStep step, EmrCluster cluster, boolean pig) {
Map<String, String> variables = EmrSparkSteps.environment(step, cluster.getConfigurations(), SNAPSHOT_MAPPER);
if (pig) {
variables.putAll(EmrSparkSteps.pigEnvironment(cluster.getConfigurations(), SNAPSHOT_MAPPER));
}
return variables;
}
/**
@@ -27,12 +27,14 @@ import java.util.Set;
* {@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. 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.
* runs Hive. One running {@code pig-script}, as the AWS CLI writes a Pig step, runs EMR's, which runs the
* {@code pig} Floci adds to a cluster with Pig, with Pig's configuration of its own ({@link #pigEnvironment}).
*/
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: pig-script is not in the image steps run in.";
static final String NOT_RUN = "Floci does not run this step: Pig is not in the image steps run in."
+ " floci.services.emr.pig.enabled adds Apache Pig to it.";
static final String INTERRUPTED = "Floci stopped while the step was running.";
private static final String COMMAND_RUNNER = "command-runner.jar";
@@ -65,8 +67,34 @@ 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 images do not have.
private static final Set<String> UNAVAILABLE_TOOLS = Set.of("pig-script");
// The AWS CLI's Pig step on a release is command-runner.jar running "pig-script --run-pig-script --args" and the
// step's arguments; the image has EMR's pig-script, which runs pig with them, or says "Pig isn't installed.", as
// the image has no pig unless Floci adds it.
private static final String PIG_SCRIPT = "pig-script";
private static final String PIG = "pig";
// The Release Guide's Pig classifications: pig-properties will "Change values in Pig's pig.properties file",
// pig-log4j "Change values in Pig's log4j.properties file", and pig-env "Change values in the Pig environment",
// through its export classification. Pig 0.16.0 and later "use Apache Tez", the Release Guide's Pig considerations
// say: "You can explicitly set exectype=mapreduce in the pig-properties configuration classification to use
// MapReduce." A cluster's tez-site is Tez's, which Pig takes as it does a Hadoop property, ahead of pig-properties.
private static final String PIG_PROPERTIES = "pig-properties";
private static final String PIG_LOG4J = "pig-log4j";
private static final String PIG_ENV = "pig-env";
private static final String TEZ_SITE = "tez-site";
private static final String PIG_EXECTYPE = "exectype";
private static final String PIG_TEZ = "tez";
// Pig's setting for the log4j.properties it reads, which then is the one the cluster's pig-log4j changes.
private static final String PIG_LOG4J_CONF = "log4jconf";
// Pig sets the file system of each of a script's inputs to the job's working directory, the default file system's
// home of the user it runs as, which S3A, Floci's s3://, refuses when it names another file system. Named without
// one, it is the same folder in HDFS, and Hadoop fills in the user.
private static final String WORKING_DIR = "mapreduce.job.working.dir";
private static final String USER_HOME = "/user/${user.name}";
// A cluster runs no MapReduce JobHistory server, which a job client asks for a job once its application master has
// gone, as Pig does for each MapReduce job's task reports and counters: Pig asks for no task reports, and its
// client asks the server once rather than three times, each attempt waiting about ten seconds to connect.
private static final String PIG_NO_TASK_REPORT = "pig.stats.notaskreport";
private static final String CLIENT_RETRIES = "yarn.app.mapreduce.client.max-retries";
// 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";
@@ -78,7 +106,7 @@ final class EmrSparkSteps {
// 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 String HIVE_SITE = "hive-site";
private static final List<String> HIVE_CLASSIFICATIONS = List.of(CORE_SITE, "tez-site", HIVE_SITE);
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.
@@ -145,11 +173,12 @@ final class EmrSparkSteps {
/**
* The command a step that is not a Spark step runs, or null for one Floci does not run: a
* {@code command-runner.jar} step's arguments, its command first, unless it names a tool the image does
* not have; Floci's S3DistCp with the arguments of an {@code s3-dist-cp} one; a {@code script-runner.jar}
* step's script, the first of its arguments, with the rest.
* {@code command-runner.jar} step's arguments, its command first, unless it runs {@code pig-script} on a cluster
* that installs Pig, which Floci has not added ({@code pigMissing}), where EMR's would run it; on one that does not,
* EMR's {@code pig-script} runs and finds no {@code pig}, as it does there. Floci's S3DistCp with the arguments of an
* {@code s3-dist-cp} one; a {@code script-runner.jar} step's script, the first of its arguments, with the rest.
*/
static List<String> command(EmrStep step) {
static List<String> command(EmrStep step, boolean pigMissing) {
String jar = step.getJar();
List<String> args = step.getArgs() != null ? step.getArgs() : List.of();
if (jar == null || args.isEmpty()) {
@@ -161,7 +190,7 @@ final class EmrSparkSteps {
command.addAll(args.subList(1, args.size()));
return command;
}
return named(args.getFirst(), SPARK_SUBMIT) || UNAVAILABLE_TOOLS.contains(args.getFirst())
return named(args.getFirst(), SPARK_SUBMIT) || pigMissing && named(args.getFirst(), PIG_SCRIPT)
? null : List.copyOf(args);
}
if (named(jar, SCRIPT_RUNNER)) {
@@ -234,18 +263,68 @@ final class EmrSparkSteps {
* Spark."
*/
static boolean installsHive(String releaseLabel, String applications, ObjectMapper objectMapper) {
return installs(releaseLabel, applications, objectMapper, HIVE, HCATALOG);
}
/**
* Whether a cluster installs Pig: its {@code Applications} name it, unless its release is of the AWS runtime for
* Apache Spark, whose release notes say "Pig and Oozie are not included".
*/
static boolean installsPig(String releaseLabel, String applications, ObjectMapper objectMapper) {
return installs(releaseLabel, applications, objectMapper, PIG);
}
// Whether a cluster's Applications name any of names, in any case, unless its release is of the AWS runtime for
// Apache Spark, which installs neither Hive, HCatalog nor Pig.
private static boolean installs(String releaseLabel, String applications, ObjectMapper objectMapper,
String... names) {
if (releaseLabel != null && EmrServerlessSparkRunner.sparkRuntime(releaseLabel)) {
return false;
}
for (JsonNode application : stored(applications, objectMapper)) {
String name = application.path("Name").asText();
if (HIVE.equalsIgnoreCase(name) || HCATALOG.equalsIgnoreCase(name)) {
return true;
for (String installed : names) {
if (installed.equalsIgnoreCase(name)) {
return true;
}
}
}
return false;
}
/**
* The variables a step's command gets on a cluster with Floci's Pig, which make its {@code pig} read a Pig
* configuration of its own: {@code pig.properties} lines that run Pig on Tez, as EMR's does, from a working
* directory S3A takes, with no wait on a JobHistory server the cluster does not run, then the cluster's
* {@code tez-site} and {@code pig-properties}, a later one winning, and,
* with a {@code pig-log4j}, Pig's setting to read the {@code log4j.properties} that gets its lines;
* {@code pig-env}'s exports start its {@code pig-env.sh}.
*/
static Map<String, String> pigEnvironment(String configurations, ObjectMapper objectMapper) {
Map<String, String> properties = new LinkedHashMap<>();
properties.put(PIG_EXECTYPE, PIG_TEZ);
properties.put(WORKING_DIR, USER_HOME);
properties.put(PIG_NO_TASK_REPORT, "true");
properties.put(CLIENT_RETRIES, "1");
Map<String, String> log4j = properties(configurations, objectMapper, PIG_LOG4J);
if (!log4j.isEmpty()) {
properties.put(PIG_LOG4J_CONF, EmrServerlessSparkRunner.PIG_CONF + "/log4j.properties");
}
properties.putAll(properties(configurations, objectMapper, TEZ_SITE));
properties.putAll(properties(configurations, objectMapper, PIG_PROPERTIES));
Map<String, String> variables = new LinkedHashMap<>();
variables.put(EmrServerlessSparkRunner.PIG_PROPERTIES_VARIABLE,
EmrServerlessSparkRunner.propertiesLines(properties));
if (!log4j.isEmpty()) {
variables.put(EmrServerlessSparkRunner.PIG_LOG4J_VARIABLE, EmrServerlessSparkRunner.propertiesLines(log4j));
}
Map<String, String> exports = exports(configurations, objectMapper, PIG_ENV);
if (!exports.isEmpty()) {
variables.put(EmrServerlessSparkRunner.PIG_ENV_VARIABLE, EmrServerlessSparkRunner.exportLines(exports));
}
return variables;
}
/**
* The S3 folder its YARN applications' logs go to, or null when a cluster has no {@code LogUri}: the Management
* Guide's {@code /cluster-id/containers}, "Application container logs. The logs for each YARN application are
@@ -0,0 +1,214 @@
package io.floci.aws.services.emr;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.docker.RetryingTarCopier;
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 java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.List;
import java.util.Set;
import java.util.zip.GZIPInputStream;
/**
* Apache Pig for the image of a cluster that installs it, when {@code floci.services.emr.pig.enabled} is on: no AWS
* image carries Pig, so Floci downloads Apache's binary distribution from the first of its URLs that gives it with its
* SHA-256, and writes what Pig runs from as the archive of {@link #HOME}, EMR's folder for it. EMR 7.x
* releases ship Pig 0.17.0, whose Apache build is "compatible with Hadoop 2.5+ releases"; Floci's default is 0.18.0,
* whose {@code pig-0.18.0.tar.gz} "is compatible with Hadoop 3, Spark 3, Hive 3 and HBase 2", the Hadoop the images
* hold. Pig runs on the image's Tez, as EMR's runs on EMR's: the Tez 0.10.3 its distribution bundles needs protobuf 3,
* which it bundles too, and the image's Tez 0.10.2 protobuf 2.5, so the two would meet on one class path. Both of its own
* stay out, and its {@code pig-env.sh} puts the image's Tez on Pig's class path ({@link #ENVIRONMENT}).
*/
@ApplicationScoped
public class PigDistribution {
/** The folder Pig goes in, under its own name. */
static final String FOLDER = "/usr/lib";
static final String NAME = "pig";
static final String HOME = FOLDER + "/" + NAME;
/** The folder of the {@code pig} a step runs, as EMR's {@code pig-script} does the one it finds. */
static final String COMMAND_FOLDER = "/usr/bin";
/**
* That {@code pig}, which runs Pig's launcher by the launcher's own path: the launcher takes Pig's folder from the
* path it was run by, so a link would lead it to {@code /usr} instead.
*/
static final String COMMAND = "#!/bin/bash\nexec " + HOME + "/bin/" + NAME + " \"$@\"\n";
// What Pig runs from: its launcher, its configuration, its jars and its licence. The docs, the sources, the tests,
// the jars of Pig on Spark, which EMR does not run, the Hadoop it bundles for a machine without one, and its Tez and
// the protobuf that Tez needs stay out, as does a pig-env.sh, Floci writing its own.
private static final Set<String> KEPT_FOLDERS = Set.of("bin", "conf", "lib");
private static final List<String> LEFT_OUT = List.of("lib/spark/", "lib/hadoop2-runtime/", "lib/hadoop3-runtime/",
"lib/h3/tez-", "lib/protobuf-java-", "conf/pig-env.sh");
/**
* Pig's {@code conf/pig-env.sh}, which its launcher reads before it builds its class path: the image's Tez, with
* its protobuf 2.5, then the class path a cluster's {@code pig-env} sets, whose exports come first.
*/
static final String ENVIRONMENT = "export PIG_CLASSPATH=\"/usr/lib/tez/*:/usr/lib/tez/lib/*"
+ "${PIG_CLASSPATH:+:$PIG_CLASSPATH}\"\n";
private static final String ENVIRONMENT_FILE = NAME + "/conf/pig-env.sh";
private static final Set<String> KEPT_FILES = Set.of("LICENSE.txt", "NOTICE.txt");
private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(30);
// A download that sends nothing for this long has stalled, and the next URL is tried.
private static final Duration READ_TIMEOUT = Duration.ofSeconds(60);
private static final int BUFFER_BYTES = 64 * 1024;
private final List<URI> urls;
private final String sha256;
private final Duration connectTimeout;
private final Duration readTimeout;
private final Path downloads;
@Inject
public PigDistribution(EmulatorConfig config) {
this(config.services().emr().pig().urls(), config.services().emr().pig().sha256(), CONNECT_TIMEOUT,
READ_TIMEOUT, Path.of(System.getProperty("java.io.tmpdir")));
}
PigDistribution(List<String> urls, String sha256, Duration connectTimeout, Duration readTimeout,
Path downloads) {
this.urls = urls.stream().map(String::trim).filter(url -> !url.isEmpty()).map(URI::create).toList();
this.sha256 = sha256.trim();
this.connectTimeout = connectTimeout;
this.readTimeout = readTimeout;
this.downloads = downloads;
}
/** What the image's name says it holds: the distribution, by its checksum. */
String identity() {
return "pig " + sha256.toLowerCase();
}
/**
* Downloads the distribution to a temporary file, which the caller deletes, from the first URL that gives it whole
* with its SHA-256: one that cannot be reached, answers otherwise, stalls for {@link #READ_TIMEOUT} or gives another
* checksum passes to the next, so nothing goes into an image before it has been checked.
*/
Path download() throws IOException {
List<String> failures = new ArrayList<>();
for (URI url : urls) {
Path file = Files.createTempFile(downloads, "floci-pig-", ".tar.gz");
try {
fetch(url, file);
return file;
} catch (IOException e) {
Files.deleteIfExists(file);
failures.add(url + ": " + e.getMessage());
}
}
throw new IOException("Could not download Apache Pig: " + (failures.isEmpty() ? "no URL is set"
: String.join("; ", failures)));
}
private void fetch(URI url, Path file) throws IOException {
MessageDigest digest = sha256Digest();
HttpURLConnection connection = (HttpURLConnection) url.toURL().openConnection();
connection.setConnectTimeout((int) connectTimeout.toMillis());
connection.setReadTimeout((int) readTimeout.toMillis());
try {
int status = connection.getResponseCode();
if (status != HttpURLConnection.HTTP_OK) {
throw new IOException("answered " + status);
}
try (InputStream in = new DigestInputStream(connection.getInputStream(), digest);
OutputStream out = Files.newOutputStream(file)) {
in.transferTo(out);
}
} finally {
connection.disconnect();
}
String found = HexFormat.of().formatHex(digest.digest());
if (!found.equalsIgnoreCase(sha256)) {
throw new IOException("has the SHA-256 " + found + ", not the " + sha256
+ " floci.services.emr.pig.sha256 names");
}
}
/**
* Writes the folders and files Pig runs from, of the gzipped archive {@code download}, to {@code out} as an archive
* of {@link #FOLDER}, under {@link #NAME} in place of the distribution's own folder, owned by root, and
* {@link #ENVIRONMENT} as its {@code pig-env.sh}.
*/
static void write(Path download, OutputStream out) throws IOException {
try (InputStream raw = Files.newInputStream(download);
GZIPInputStream gzip = new GZIPInputStream(raw, BUFFER_BYTES);
TarArchiveInputStream in = new TarArchiveInputStream(gzip);
TarArchiveOutputStream tar = RetryingTarCopier.newTarStream(out)) {
TarArchiveEntry entry;
while ((entry = in.getNextEntry()) != null) {
String path = kept(entry.getName());
if (path == null || entry.isLink() && kept(entry.getLinkName()) == null) {
continue;
}
entry.setName(path);
if (entry.isLink()) {
entry.setLinkName(kept(entry.getLinkName()));
}
entry.setIds(0, 0);
entry.setNames("root", "root");
tar.putArchiveEntry(entry);
in.transferTo(tar);
tar.closeArchiveEntry();
}
TarArchiveEntry environment = new TarArchiveEntry(ENVIRONMENT_FILE);
byte[] lines = ENVIRONMENT.getBytes(StandardCharsets.UTF_8);
environment.setSize(lines.length);
environment.setMode(0644);
environment.setIds(0, 0);
environment.setNames("root", "root");
tar.putArchiveEntry(environment);
tar.write(lines);
tar.closeArchiveEntry();
}
}
private static MessageDigest sha256Digest() {
try {
return MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}
// A path of the distribution, its own folder first, under NAME, or null for one Pig does not run from, or that
// leaves the folder.
static String kept(String path) {
if (path == null || path.startsWith("/")) {
return null;
}
int slash = path.indexOf('/');
if (slash < 0) {
return null;
}
String rest = path.substring(slash + 1);
for (String segment : rest.split("/")) {
if (segment.equals("..")) {
return null;
}
}
if (rest.isEmpty()) {
return NAME + "/";
}
int folderEnd = rest.indexOf('/');
boolean kept = folderEnd < 0
? KEPT_FILES.contains(rest) || rest.endsWith(".jar")
: KEPT_FOLDERS.contains(rest.substring(0, folderEnd)) && LEFT_OUT.stream().noneMatch(rest::startsWith);
return kept ? NAME + "/" + rest : null;
}
}
@@ -1,20 +1,20 @@
package io.floci.aws.services.emr;
/**
* The images a cluster runs in, in the EMR {@code docker} runner mode: two per release, its EMR Serverless image with
* its EMR Serverless Hive image's HDFS, MapReduce and YARN added, and for a cluster with Hive its Hive too, as an EMR
* cluster's nodes hold every application it installs; a release of the AWS runtime for Apache Spark, which has no Hive
* image, has one, with the Hadoop of another release's kept apart. {@link EmrReleaseImages} is the Docker implementation,
* and a test supplies its own.
* The images a cluster runs in, in the EMR {@code docker} runner mode: its release's EMR Serverless image with its EMR
* Serverless Hive image's HDFS, MapReduce and YARN added, and for a cluster with Hive its Hive too, for one with Pig
* Tez and Apache Pig, as an EMR cluster's nodes hold every application it installs. A release of the AWS runtime for
* Apache Spark, which has no Hive image, has one, with the Hadoop of another release's kept apart.
* {@link EmrReleaseImages} is the Docker implementation, and a test supplies its own.
*/
public interface ReleaseImages {
/**
* The id of the image of {@code releaseLabel} made of {@code sparkImage} and {@code hiveImage}, with Hive or with
* Hadoop's services alone, made first when the Docker daemon does not have it, which may take as long as pulling
* the two; a failure is thrown.
* Hadoop's services alone, and with Pig or without, made first when the Docker daemon does not have it, which may
* take as long as pulling the two, and downloading Pig; a failure is thrown.
*/
String image(String releaseLabel, String sparkImage, String hiveImage, boolean withHive);
String image(String releaseLabel, String sparkImage, String hiveImage, boolean withHive, boolean withPig);
/**
* The step or the bootstrap that {@link #image} gave {@code imageId} to has ended, so a newer image of its kind may
@@ -101,6 +101,8 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
// Where a step on its cluster's YARN finds the ResourceManager, as a yarn-site.xml property, a Hadoop client reading
// yarn-site.xml after core-site.xml.
private static final String YARN_SITE_VARIABLE = "FLOCI_YARN_SITE";
// How a command's Tez, Pig's among them, runs its DAGs, as tez-site.xml properties (see tezSite).
private static final String TEZ_SITE_VARIABLE = "FLOCI_TEZ_SITE";
// The folder of a step's image holding the Hadoop its cluster's nodes run from, which its hadoop command runs from
// on YARN, as the MapReduce home the local job runner uses has no YARN client to speak of.
private static final String HADOOP_ROOT_VARIABLE = "FLOCI_HADOOP_ROOT";
@@ -219,18 +221,19 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
"fi",
"export SPARK_CONF_DIR=\"$conf\"");
// On a cluster, the hadoop command, and MapReduce in a step's spark-submit, get its HDFS and Floci's S3 too,
// through a copy of its Hadoop configuration (the image's, or the folder a spark-env export names), links
// followed, whose core-site.xml takes in the original's through Hadoop's XInclude, whatever its XML, by a name
// relative to the folder, which Spark ships to YARN's containers on a cluster that runs it, then
// HADOOP_SITE_VARIABLE's properties, which win (see hadoopSite), and whose mapred-site.xml runs MapReduce in local
// mode the same way (see mapredSite). The cluster's hadoop-log4j lines follow the log4j.properties, on a line of
// their own, a later key winning, and its hadoop-env exports start the hadoop-env.sh the hadoop command reads,
// ahead of the image's own lines, which add to HADOOP_CLASSPATH rather than set it, so a HADOOP_CLASSPATH the
// cluster sets keeps the LZO codec the image's core-site.xml names. The hadoop script runs only once its HDFS,
// MapReduce and YARN homes name folders that are there, and the image has /usr/lib/hadoop alone, without
// MapReduce, so the MapReduce home is Floci's (see MAPRED_HOME). The image's hdfs command cannot run, so hdfs dfs
// runs as hadoop fs, and its hadoop-streaming names a jar it does not have, so the one it has runs. A step's
// command can run sudo, as on EMR, which the image does not have, so it finds Floci's first (see SUDO).
// through a copy of its Hadoop configuration (the image's, or the folder a spark-env export names), links followed,
// whose core-site.xml takes in the original's through Hadoop's XInclude, whatever its XML, by a name relative to
// the folder, which Spark ships to YARN's containers on a cluster that runs it, then HADOOP_SITE_VARIABLE's
// properties, which win (see hadoopSite), and whose mapred-site.xml runs MapReduce in local mode the same way (see
// mapredSite), as a command's tez-site.xml does Tez (see tezSite). The cluster's hadoop-log4j lines follow the
// log4j.properties, on a line of their own, a later key winning, and its hadoop-env exports start the hadoop-env.sh
// the hadoop command reads, ahead of the image's own lines, which add to HADOOP_CLASSPATH rather than set it, so a
// HADOOP_CLASSPATH the cluster sets keeps the LZO codec the image's core-site.xml names. The hadoop script runs
// only once its HDFS, MapReduce and YARN homes name folders that are there, and the image has /usr/lib/hadoop
// alone, without MapReduce, so the MapReduce home is Floci's (see MAPRED_HOME). The image's hdfs command cannot
// run, so hdfs dfs runs as hadoop fs, and its hadoop-streaming names a jar it does not have, so the one it has
// runs. A step's command can run sudo, as on EMR, which the image does not have, so it finds Floci's first (see
// SUDO).
private static final List<String> HADOOP_CONF_SETUP = List.of(
"if [ -n \"${" + HADOOP_SITE_VARIABLE + ":-}\" ]; then",
" hadoop_conf=/tmp/floci-hadoop-conf source_conf=\"${HADOOP_CONF_DIR:-/etc/hadoop/conf}\"",
@@ -253,6 +256,9 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
" if [ -n \"${" + YARN_SITE_VARIABLE + ":-}\" ]; then",
" site yarn-site.xml \"$" + YARN_SITE_VARIABLE + "\"",
" fi",
" if [ -n \"${" + TEZ_SITE_VARIABLE + ":-}\" ]; then",
" site tez-site.xml \"$" + TEZ_SITE_VARIABLE + "\"",
" fi",
" if [ ! -s \"$hadoop_conf/log4j.properties\" ]; then",
" printf '%s\\n' '" + String.join("' '", HADOOP_CONSOLE_LOG) + "' > \"$hadoop_conf/log4j.properties\"",
" fi",
@@ -294,6 +300,38 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
" chmod +x /tmp/floci-bin/hadoop /tmp/floci-bin/hadoop-streaming",
" fi",
"fi");
/**
* The lines a step's command gets after those of Pig's own {@code pig.properties}, a later key winning, in a Pig
* configuration of the container's own ({@link #PIG_CONF}), which {@code PIG_CONF_DIR} names; set for a cluster
* with Pig.
*/
public static final String PIG_PROPERTIES_VARIABLE = "FLOCI_PIG_PROPERTIES";
/** The lines that follow those of that configuration's {@code log4j.properties}, its template's where it has none. */
public static final String PIG_LOG4J_VARIABLE = "FLOCI_PIG_LOG4J";
/** The lines that start that configuration's {@code pig-env.sh}, which Pig's launcher reads. */
public static final String PIG_ENV_VARIABLE = "FLOCI_PIG_ENV";
/** Where a step's command has its Pig configuration. */
public static final String PIG_CONF = "/tmp/floci-pig-conf";
// On a cluster with Pig, a command's pig reads a configuration of its own: a copy of the one PIG_CONF_DIR names, or
// Pig's, links followed, whose pig.properties, log4j.properties and pig-env.sh get the cluster's lines.
private static final List<String> PIG_CONF_SETUP = List.of(
"if [ -n \"${" + PIG_PROPERTIES_VARIABLE + ":-}\" ]; then",
" mkdir -p " + PIG_CONF,
" cp -rL \"${PIG_CONF_DIR:-/usr/lib/pig/conf}/.\" " + PIG_CONF + " 2>/dev/null",
" printf '\\n%s\\n' \"$" + PIG_PROPERTIES_VARIABLE + "\" >> " + PIG_CONF + "/pig.properties",
" if [ -n \"${" + PIG_LOG4J_VARIABLE + ":-}\" ]; then",
" if [ ! -f " + PIG_CONF + "/log4j.properties ]; then",
" cp " + PIG_CONF + "/log4j.properties.template " + PIG_CONF + "/log4j.properties 2>/dev/null",
" fi",
" printf '\\n%s\\n' \"$" + PIG_LOG4J_VARIABLE + "\" >> " + PIG_CONF + "/log4j.properties",
" fi",
" if [ -n \"${" + PIG_ENV_VARIABLE + ":-}\" ]; then",
" { printf '%s\\n' \"$" + PIG_ENV_VARIABLE + "\"; cat " + PIG_CONF + "/pig-env.sh 2>/dev/null; }"
+ " > " + PIG_CONF + "/floci-pig-env.sh",
" mv " + PIG_CONF + "/floci-pig-env.sh " + PIG_CONF + "/pig-env.sh",
" fi",
" export PIG_CONF_DIR=" + PIG_CONF,
"fi");
// A step on a cluster, or one whose job has log4j2.properties lines, runs spark-submit after this.
private static final String SPARK_CONF_WRAPPER = wrapper(SPARK_CONF_COPY, HADOOP_CONF_SETUP);
// A command runs after this sets up a Spark configuration of its own, so a spark-submit it starts runs
@@ -305,7 +343,7 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
"sed -i -e '/^spark\\.master[[:space:]]/d' -e '/^spark\\.submit\\.deployMode[[:space:]]/d'"
+ " -e '/^spark\\.submit\\.customResourceManager/d' \"$conf/spark-defaults.conf\"",
"printf '\\n%s\\n' \"$" + SPARK_DEFAULTS_VARIABLE + "\" >> \"$conf/spark-defaults.conf\""),
HADOOP_CONF_SETUP);
HADOOP_CONF_SETUP, PIG_CONF_SETUP);
// The archives a driver needs in its working directory are put in this folder of its container, each in a
// numbered folder of its own, which the copy creates.
private static final String ARCHIVES_FOLDER = "/tmp/floci-archives";
@@ -342,6 +380,12 @@ 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"));
// A command's Tez where there is no YARN: in local mode, in the JVM that starts it, which has Tez's jars already,
// its tasks' output read where it is written, as Pig's own Tez local mode has it.
private static final List<SparkSetting> TEZ_LOCAL_SETTINGS = List.of(
new SparkSetting("tez.local.mode", "true"),
new SparkSetting("tez.ignore.lib.uris", "true"),
new SparkSetting("tez.runtime.optimize.local.fetch", "true"));
// On a cluster, Hive's metastore is the cluster's own, as "Hive records metastore information in a MySQL database
// on the primary node's file system": the metastore service on its primary node (see EmrClusterStorage), in place
// of the Glue Data Catalog client the image's hive-site names, or, where that does not run, an embedded Derby
@@ -558,6 +602,9 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
.withEnv(YARN_SITE_VARIABLE, siteProperty("yarn.resourcemanager.hostname",
job.storage().resourceManager()));
}
if (job.command() != null) {
container.withEnv(TEZ_SITE_VARIABLE, tezSite(job, executorEnvironment));
}
if (job.storage() != null && job.storage().replication() > 0) {
container.withEnv(HDFS_SITE_VARIABLE, siteProperty("dfs.replication",
String.valueOf(job.storage().replication())));
@@ -1225,19 +1272,51 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
new SparkSetting("mapreduce.reduce.memory.mb", "768"));
}
// Hive's Tez on the cluster's YARN. The image's tez-site.xml names EMR Serverless's own plugins, whose stock
// counterparts are in the same jars, named here as Tez's own defaults are; its port ranges and addresses are
// placeholders EMR Serverless fills, its compression needs a native library the image lacks, and a task's two
// virtual cores never match the one YARN's default scheduler grants, so Tez would give each container back. An
// application master says where it is by ${env.NM_HOST}, which is left for its own node to fill in: the settings
// are read on the step's side first, and $NM_HOST or an env of the step's would be filled in there.
/**
* The {@code tez-site.xml} properties a step's command gets, so that Tez, which Pig runs a script on by default,
* runs its DAGs on its cluster's YARN, as Hive's does there, or, where there is no YARN to run them on, in the JVM
* that starts them, without the jars a YARN container is given.
*/
static String tezSite(Job job, List<String> executorEnvironment) {
List<SparkSetting> settings = new ArrayList<>();
if (onYarn(job)) {
settings.addAll(tezOnYarnSettings(job, executorEnvironment, List.of()));
settings.add(new SparkSetting("tez.task.resource.memory.mb", "768"));
} else {
settings.addAll(TEZ_LOCAL_SETTINGS);
}
List<String> properties = new ArrayList<>();
settings.forEach(setting -> properties.add(siteProperty(setting.key(), setting.value())));
return String.join("\n", properties);
}
// Hive's Tez on the cluster's YARN, sized as its tasks are by Hive's own settings: a task's two virtual cores never
// match the one YARN's default scheduler grants, so Tez would give each container back.
private static List<SparkSetting> hiveOnYarnSettings(Job job, List<String> executorEnvironment) {
String root = hadoopRoot(job);
List<String> classPath = new ArrayList<>(List.of("$PWD/*", root + "/hive/lib/hive-exec.jar", root + "/tez/*",
root + "/tez/lib/*"));
classPath.addAll(hadoopLayout(root));
String environment = containerEnvironment(executorEnvironment, "HIVE_HOME=" + root + "/hive",
"TEZ_HOME=" + root + "/tez");
List<SparkSetting> settings = new ArrayList<>(tezOnYarnSettings(job, executorEnvironment,
List.of(root + "/hive/lib/hive-exec.jar"), "HIVE_HOME=" + root + "/hive"));
settings.add(new SparkSetting("hive.tez.container.size", "768"));
settings.add(new SparkSetting("hive.tez.cpu.vcores", "1"));
return settings;
}
// Tez on the cluster's YARN, its containers given classPath, then Tez's and Hadoop's jars, and variables, then
// TEZ_HOME. The image's tez-site.xml names EMR Serverless's own plugins, whose stock counterparts are in the same
// jars, named here as Tez's own defaults are; its port ranges and addresses are placeholders EMR Serverless fills,
// and its compression needs a native library the image lacks. An application master says where it is by
// ${env.NM_HOST}, which is left for its own node to fill in: the settings are read on the step's side first, and
// $NM_HOST or an env of the step's would be filled in there.
private static List<SparkSetting> tezOnYarnSettings(Job job, List<String> executorEnvironment,
List<String> classPath, String... variables) {
String root = hadoopRoot(job);
List<String> containerClassPath = new ArrayList<>(List.of("$PWD/*"));
containerClassPath.addAll(classPath);
containerClassPath.addAll(List.of(root + "/tez/*", root + "/tez/lib/*"));
containerClassPath.addAll(hadoopLayout(root));
List<String> containerVariables = new ArrayList<>(List.of(variables));
containerVariables.add("TEZ_HOME=" + root + "/tez");
String environment = containerEnvironment(executorEnvironment, containerVariables.toArray(String[]::new));
return List.of(
new SparkSetting("yarn.resourcemanager.hostname", job.storage().resourceManager()),
new SparkSetting("tez.local.mode", "false"),
@@ -1258,12 +1337,10 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
new SparkSetting("tez.shuffle.bind-host", "0.0.0.0"),
new SparkSetting("tez.lib.uris", "file://" + root + "/tez/,file://" + root + "/tez/lib/"),
new SparkSetting("tez.use.cluster.hadoop-libs", "false"),
new SparkSetting("tez.cluster.additional.classpath.prefix", String.join(":", classPath)),
new SparkSetting("tez.cluster.additional.classpath.prefix", String.join(":", containerClassPath)),
new SparkSetting("tez.am.launch.env", environment),
new SparkSetting("tez.task.launch.env", environment),
new SparkSetting("tez.am.resource.memory.mb", "1024"),
new SparkSetting("hive.tez.container.size", "768"),
new SparkSetting("hive.tez.cpu.vcores", "1"),
new SparkSetting("tez.runtime.intermediate-output.should-compress", "false"),
new SparkSetting("tez.runtime.intermediate-input.is-compressed", "false"));
}
@@ -1307,8 +1384,16 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
* is left out, as its line would run what it holds.
*/
static String hadoopEnvFile(Job job) {
return exportLines(job.hadoopEnvironment());
}
/**
* An export of each of {@code variables}, as given, in single quotes, with no shell expansion. A name a shell cannot
* export is left out, as its line would run what it holds.
*/
public static String exportLines(Map<String, String> variables) {
List<String> lines = new ArrayList<>();
job.hadoopEnvironment().forEach((name, value) -> {
variables.forEach((name, value) -> {
if (SHELL_NAME.matcher(name).matches()) {
lines.add("export " + name + "='" + value.replace("'", "'\\''") + "'");
}
@@ -1316,8 +1401,8 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
return String.join("\n", lines);
}
// Each property as a line Properties.load reads back as it is.
private static String propertiesLines(Map<String, String> properties) {
/** Each property as a line {@code Properties.load} reads back as it is. */
public static String propertiesLines(Map<String, String> properties) {
List<String> lines = new ArrayList<>();
properties.forEach((key, value) ->
lines.add(propertiesEscaped(key, true) + " = " + propertiesEscaped(value, false)));
+4
View File
@@ -662,6 +662,10 @@ floci:
yarn-node-memory-mb: 4096 # memory a cluster's NodeManager offers its YARN containers
yarn-node-vcores: 4 # virtual cores it offers them
yarn-max-worker-nodes: 4 # the most core and task nodes a cluster runs as containers of their own
pig:
enabled: false # true = add Apache Pig, downloaded, to a docker cluster that installs Pig
# urls: https://dlcdn.apache.org/pig/pig-0.18.0/pig-0.18.0.tar.gz,https://archive.apache.org/dist/pig/pig-0.18.0/pig-0.18.0.tar.gz
# sha256: 6845adb936a3c3bcc71451765953cae4103e410ba2f6c5a47cc9becade0a434a
# 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,174 @@
package io.floci.aws.services.emr;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.ContainerDataPlaneProfile;
import io.floci.aws.testing.DockerAvailability;
import io.floci.aws.testing.EmrRequests;
import io.floci.aws.testing.PartitionCleanup;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.floci.aws.testing.S3TestClients;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
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.s3.S3Client;
import software.amazon.awssdk.services.s3.model.S3Object;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import static io.floci.aws.testing.EmrRequests.awaitStep;
import static io.floci.aws.testing.EmrRequests.emr;
import static io.floci.aws.testing.EmrRequests.terminateClusterAndAwaitCleanup;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* EMR Pig steps through Floci's Docker runner for real, with {@code floci.services.emr.pig.enabled} on: a cluster
* whose {@code Applications} name Pig runs the AWS CLI's Pig step, EMR's {@code pig-script} in the image, with Apache
* Pig, which Floci downloads and adds to the image as it makes it, on Tez on the cluster's YARN, as EMR's Pig runs by
* default, and on MapReduce when a step asks for it.
*
* <p>A nightly check: it downloads Apache Pig (470 MB) and pulls the release's Spark and Hive images.
*/
@QuarkusTest
@TestProfile(EmrPigStepsNightlyIntegrationTest.PigProfile.class)
@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true")
// Bounded waits: the image made with Pig, then two steps of up to five minutes each, past the default two.
@Timeout(value = 30, unit = TimeUnit.MINUTES)
class EmrPigStepsNightlyIntegrationTest {
private static final ObjectMapper JSON = new ObjectMapper();
private static final String PIG = "[{\"Name\":\"Hadoop\"},{\"Name\":\"Pig\"}]";
private static final String ROWS = "a,1\nb,2\nc,3\na,4\n";
// Sums each key's values through a shuffle, then orders the sums through another, as Pig's GROUP and ORDER do.
private static final String SCRIPT = """
rows = LOAD '$INPUT' USING PigStorage(',') AS (k:chararray, v:int);
grouped = GROUP rows BY k;
sums = FOREACH grouped GENERATE group, SUM(rows.v) * 10;
ordered = ORDER sums BY group;
STORE ordered INTO '$OUTPUT' USING PigStorage(',');
""";
private static final String SUMS = "a,50\nb,20\nc,30\n";
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Inject
EmrService emrService;
private S3Client s3;
private String bucket;
private String clusterId;
/** The Docker data planes, with Floci's Pig on. */
public static class PigProfile extends ContainerDataPlaneProfile {
@Override
public Map<String, String> getConfigOverrides() {
Map<String, String> overrides = new HashMap<>(super.getConfigOverrides());
overrides.put("floci.services.emr.pig.enabled", "true");
return overrides;
}
}
@BeforeAll
static void configure() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@BeforeEach
void putInputs() throws InterruptedException {
assertTrue(DockerAvailability.isAvailable(), "the nightly check needs a Docker daemon");
s3 = AwsTestClients.create(S3Client.builder().forcePathStyle(true), "000000000000", Region.US_EAST_1);
cleanup.register(s3::close);
bucket = "emr-pig-" + UUID.randomUUID().toString().substring(0, 8);
s3.createBucket(request -> request.bucket(bucket));
cleanup.register(() -> S3TestClients.deleteBucket(s3, bucket));
put("data/rows/rows.csv", ROWS);
put("scripts/sums.pig", SCRIPT);
}
@Test
void theAwsClisPigStepRunsItsScriptFromS3OnTezThenOnMapReduce() {
startCluster();
// The Release Guide's Pig step, Type=PIG,Args=[-f,...,-p,INPUT=...,-p,OUTPUT=...], as the AWS CLI sends it.
String tez = pigStep("-f", s3Uri("scripts/sums.pig"), "-p", "INPUT=" + s3Uri("data/rows/"),
"-p", "OUTPUT=" + s3Uri("out/tez/"));
assertEquals("COMPLETED", state(tez), () -> logs(tez));
assertEquals(SUMS, objects("out/tez/"));
// Pig 0.16.0 and later "use Apache Tez", as Floci's Pig does unless told otherwise.
assertTrue(logs(tez).contains("TezLauncher"), () -> logs(tez));
String mapReduce = pigStep("-x", "mapreduce", "-f", s3Uri("scripts/sums.pig"),
"-p", "INPUT=" + s3Uri("data/rows/"), "-p", "OUTPUT=" + s3Uri("out/mapreduce/"));
assertEquals("COMPLETED", state(mapReduce), () -> logs(mapReduce));
assertEquals(SUMS, objects("out/mapreduce/"));
assertTrue(logs(mapReduce).contains("MapReduceLauncher"), () -> logs(mapReduce));
}
private void startCluster() {
ObjectNode request = JSON.createObjectNode().put("Name", "pig-steps").put("ReleaseLabel", "emr-7.5.0")
.put("LogUri", s3Uri("logs/"));
try {
request.set("Applications", JSON.readTree(PIG));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
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(() -> terminateClusterAndAwaitCleanup(clusterId, emrService));
}
private String pigStep(String... args) {
String[] command = new String[args.length + 3];
command[0] = "pig-script";
command[1] = "--run-pig-script";
command[2] = "--args";
System.arraycopy(args, 0, command, 3, args.length);
return EmrRequests.addStep(clusterId, "pig", "command-runner.jar", command);
}
private String state(String stepId) {
return awaitStep(clusterId, stepId).jsonPath().getString("Step.Status.State");
}
// What a step wrote, Pig's log included, to its standard output, then its standard error.
private String logs(String stepId) {
String folder = "logs/" + clusterId + "/steps/" + stepId + "/";
return S3TestClients.gunzipped(s3, bucket, folder + "stdout.gz") + "\n"
+ S3TestClients.gunzipped(s3, bucket, folder + "stderr.gz");
}
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();
}
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;
}
}
@@ -31,12 +31,15 @@ import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.archivers.tar.TarConstants;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.ArgumentCaptor;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
@@ -48,8 +51,10 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.zip.GZIPOutputStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -81,7 +86,9 @@ class EmrReleaseImagesTest {
// The images of the made image's kind the daemon lists, and the command listing them.
private final List<Image> listed = new ArrayList<>();
private final ListImagesCmd listImages = mock(ListImagesCmd.class, RETURNS_SELF);
private final EmrReleaseImages images = new EmrReleaseImages(lifecycle, containerBuilder, imageCache, config);
private final PigDistribution pig = mock(PigDistribution.class);
private final EmrReleaseImages images = new EmrReleaseImages(lifecycle, containerBuilder, imageCache, config,
pig);
@Test
void aCopyPutsItsSourceUnderItsNameInItsFolderAndTezsGoodiesLinksLeadToTheHiveImagesCopy() throws IOException {
@@ -140,6 +147,48 @@ class EmrReleaseImagesTest {
verify(docker).removeContainerCmd("source");
}
@Test
void anImageForAClusterWithPigHasTezThenPigAndANameOfItsOwn(@TempDir Path folder) throws IOException {
when(pig.identity()).thenReturn("pig " + "6".repeat(64));
Path downloaded = folder.resolve("floci-pig-1.tar.gz");
ByteArrayOutputStream empty = new ByteArrayOutputStream();
try (TarArchiveOutputStream tar = new TarArchiveOutputStream(new GZIPOutputStream(empty))) {
tar.finish();
}
Files.write(downloaded, empty.toByteArray());
when(pig.download()).thenReturn(downloaded);
List<String> copied = makesMissing("emr-7.5.0", false, true);
// Pig runs its scripts on Tez, which a cluster with Pig and without Hive gets, Hive staying out.
assertEquals(List.of("/usr/lib/hadoop-hdfs", "/usr/lib/hadoop-mapreduce", "/usr/lib/hadoop-yarn",
"/usr/lib/tez", "/etc/tez", "/usr/share/aws/emr/serverless-goodies/lib"), copied);
verify(pig).download();
// The download goes once the image is made of it.
assertFalse(Files.exists(downloaded));
ArgumentCaptor<String> tags = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<Map<String, String>> labels = mapCaptor();
images.image("emr-7.5.0", SPARK, HIVE, false, false);
verify(lifecycle, times(2)).commit(eq("target"), anyString(), tags.capture(), anyString(), labels.capture());
assertNotEquals(tags.getAllValues().get(0), tags.getAllValues().get(1));
assertNotEquals(labels.getAllValues().get(0).get(EmrReleaseImages.KIND_LABEL),
labels.getAllValues().get(1).get(EmrReleaseImages.KIND_LABEL));
// A cluster with Hive has Tez already.
List<EmrReleaseImages.Copy> withHive = EmrReleaseImages.copies("emr-7.5.0", true, true);
assertEquals(EmrReleaseImages.COPIES, withHive);
assertTrue(withHive.containsAll(EmrReleaseImages.TEZ_COPIES));
}
@Test
void aReleaseOfTheAwsRuntimeForSparkGetsNoPig() throws IOException {
// "Pig and Oozie are not included."
List<String> copied = makesMissing("emr-spark-8.1.0", false, true);
assertEquals(EmrReleaseImages.HADOOP_APART_COPIES.stream().map(EmrReleaseImages.Copy::from).toList(), copied);
verify(pig, never()).download();
verify(pig, never()).identity();
}
@Test
void anImageForAClusterWithoutHiveHasHadoopsServicesAloneAndANameOfItsOwn() {
List<String> copied = makesMissing(false);
@@ -149,7 +198,7 @@ class EmrReleaseImagesTest {
assertTrue(EmrReleaseImages.COPIES.containsAll(EmrReleaseImages.HADOOP_COPIES));
ArgumentCaptor<String> tags = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<Map<String, String>> labels = mapCaptor();
images.image("emr-7.5.0", SPARK, HIVE, true);
images.image("emr-7.5.0", SPARK, HIVE, true, false);
verify(lifecycle, times(2)).commit(eq("target"), anyString(), tags.capture(), anyString(), labels.capture());
assertNotEquals(tags.getAllValues().get(0), tags.getAllValues().get(1));
// Nor does either replace the other: they are of two kinds.
@@ -214,7 +263,7 @@ class EmrReleaseImagesTest {
when(docker.inspectImageCmd(argThat((String image) -> image != null && image.startsWith(repository + ":"))))
.thenReturn(there);
// A step is given the image there, and has no container of it yet when a newer pull makes another.
assertEquals("sha256:given", images.image("emr-7.5.0", SPARK, HIVE, true));
assertEquals("sha256:given", images.image("emr-7.5.0", SPARK, HIVE, true, false));
listed.add(image("sha256:given", repository + ":emr-7.5.0-000000000000"));
when(docker.removeImageCmd("sha256:given")).thenReturn(mock(RemoveImageCmd.class, RETURNS_SELF));
@@ -274,11 +323,11 @@ class EmrReleaseImagesTest {
return "sha256:newer";
});
AtomicReference<String> first = new AtomicReference<>();
Thread older = Thread.ofPlatform().start(() -> first.set(images.image("emr-7.5.0", SPARK, HIVE, true)));
Thread older = Thread.ofPlatform().start(() -> first.set(images.image("emr-7.5.0", SPARK, HIVE, true, false)));
assertTrue(committing.await(10, TimeUnit.SECONDS));
AtomicReference<String> second = new AtomicReference<>();
Thread newer = Thread.ofPlatform().start(() -> second.set(images.image("emr-7.5.0", SPARK, HIVE, true)));
Thread newer = Thread.ofPlatform().start(() -> second.set(images.image("emr-7.5.0", SPARK, HIVE, true, false)));
ThreadStates.awaitBlockedOrDone(newer);
// It waits for the image of its kind being made before it reads where the two names lead.
verify(imageCache, times(1)).resolveForLaunch(HIVE, ImagePullBehavior.PREFER_CACHED, null);
@@ -337,11 +386,11 @@ class EmrReleaseImagesTest {
made.set(true);
return "sha256:made";
});
Thread first = Thread.ofPlatform().start(() -> images.image("emr-7.5.0", SPARK, HIVE, true));
Thread first = Thread.ofPlatform().start(() -> images.image("emr-7.5.0", SPARK, HIVE, true, false));
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, true)));
Thread second = Thread.ofPlatform().start(() -> found.set(images.image("emr-7.5.0", SPARK, HIVE, true, false)));
ThreadStates.awaitBlockedOrDone(second);
committed.countDown();
first.join(10_000);
@@ -364,7 +413,7 @@ class EmrReleaseImagesTest {
when(docker.inspectImageCmd(anyString())).thenReturn(there);
resolvesEachToItself();
assertEquals("sha256:made", images.image("emr-7.5.0", SPARK, HIVE, true));
assertEquals("sha256:made", images.image("emr-7.5.0", SPARK, HIVE, true, false));
verify(docker, never()).createContainerCmd(anyString());
verify(lifecycle, never()).commit(any(), anyString(), anyString(), any(), any());
@@ -387,9 +436,9 @@ class EmrReleaseImagesTest {
return there;
});
images.image("emr-7.5.0", SPARK, HIVE, true);
images.image("emr-7.5.0", SPARK, HIVE, true);
images.image("emr-7.5.0", SPARK, HIVE, true);
images.image("emr-7.5.0", SPARK, HIVE, true, false);
images.image("emr-7.5.0", SPARK, HIVE, true, false);
images.image("emr-7.5.0", SPARK, HIVE, true, false);
assertEquals(asked.get(0), asked.get(1));
assertNotEquals(asked.get(0), asked.get(2));
@@ -429,12 +478,12 @@ class EmrReleaseImagesTest {
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);
new ImageCacheService(daemon, cacheConfig), config, pig);
cached.image("emr-7.5.0", SPARK, HIVE, true);
cached.image("emr-7.5.0", SPARK, HIVE, true, false);
tags.put(HIVE, "sha256:newer-hive");
images.add("sha256:newer-hive");
cached.image("emr-7.5.0", SPARK, HIVE, true);
cached.image("emr-7.5.0", SPARK, HIVE, true, false);
assertNotEquals(asked.get(0), asked.get(1));
}
@@ -447,6 +496,10 @@ class EmrReleaseImagesTest {
}
private List<String> makesMissing(String release, boolean withHive) {
return makesMissing(release, withHive, false);
}
private List<String> makesMissing(String release, boolean withHive, boolean withPig) {
when(lifecycle.getDockerClient()).thenReturn(docker);
String repository = ContainerStorageHelper.dockerName(config, "emr-release");
// The two are pulled as a container's image would be, from the image-registry-base it names.
@@ -482,7 +535,7 @@ class EmrReleaseImagesTest {
when(listImages.exec()).thenAnswer(invocation -> listed);
when(docker.listImagesCmd()).thenReturn(listImages);
assertEquals("sha256:made", images.image(release, SPARK, HIVE, withHive));
assertEquals("sha256:made", images.image(release, SPARK, HIVE, withHive, withPig));
return copied;
}
@@ -67,6 +67,7 @@ class EmrServiceContainerStepsTest {
private static final String REPORT = "s3://bucket/jobs/report.py";
private static final String DRIVER_FAILED = "The Spark driver exited with code 1.";
private static final String INSTALL = "s3://bucket/bootstrap/install.sh";
private static final String PIG = "[{\"Name\": \"Hadoop\"}, {\"Name\": \"Pig\"}]";
private static final String ERROR_CODE_PAGES = "https://docs.aws.amazon.com/emr/latest/ManagementGuide/";
// The id of the image a bootstrap kept, which the cluster's steps run in.
private static final String IMAGE = "sha256:" + "2".repeat(64);
@@ -599,7 +600,7 @@ class EmrServiceContainerStepsTest {
// Its release's image with Hadoop's services, as it has no Hive, made on the step's thread: its steps and its
// primary node's HDFS and YARN run in it, the NodeManager offering what Floci gives it.
assertEquals(List.of(List.of("emr-7.5.0", "public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest",
"public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest", "false")), fixture.releaseImages.asked);
"public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest", "false", "false")), fixture.releaseImages.asked);
SparkJobRunner.Job job = runner.jobs.get(0);
assertEquals(EmrServiceFixture.RecordingReleaseImages.IMAGE, job.imageTemplate());
assertEquals(EmrServiceFixture.RecordingReleaseImages.IMAGE, fixture.clusterStorage.hdfs.get(0).get(2));
@@ -779,7 +780,7 @@ class EmrServiceContainerStepsTest {
// Its release has no Hive image, so emr-7.5.0's gives the Hadoop its image holds for the node's daemons.
assertEquals(List.of(List.of("emr-spark-8.1.0", "public.ecr.aws/emr-serverless/spark4/emr-spark-8.1.0:latest",
"public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest", "false")), fixture.releaseImages.asked);
"public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest", "false", "false")), fixture.releaseImages.asked);
SparkJobRunner.Job job = runner.jobs.get(0);
assertEquals(EmrServiceFixture.RecordingReleaseImages.IMAGE, job.imageTemplate());
assertEquals(EmrServiceFixture.RecordingReleaseImages.IMAGE, fixture.clusterStorage.hdfs.get(0).get(2));
@@ -815,7 +816,7 @@ class EmrServiceContainerStepsTest {
SparkJobRunner.Job job = runner.jobs.get(0);
assertEquals(SparkJobRunner.Engine.HIVE, job.engine());
assertEquals(List.of(List.of("emr-7.5.0", "public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest",
"public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest", "true")), fixture.releaseImages.asked);
"public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest", "true", "false")), fixture.releaseImages.asked);
assertEquals(EmrServiceFixture.RecordingReleaseImages.IMAGE, job.imageTemplate());
assertEquals(hdfsStorage(cluster).withHiveMetastore("thrift://ip-10-0-0-1.ec2.internal:9083"), job.storage());
}
@@ -984,7 +985,9 @@ class EmrServiceContainerStepsTest {
void aStepFlociDoesNotRunHandedOffBeforeATeardownEndsAsAStoppedDriverAndStartsNoOther() {
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, sparkStep("next", "CONTINUE")), REGION);
EmrCluster requested = cluster("pig", true, pig, sparkStep("next", "CONTINUE"));
requested.setApplications(PIG);
EmrCluster cluster = service.runJobFlow(requested, REGION);
service.stopManagedContainers();
fixture.runStepThread();
@@ -1015,9 +1018,12 @@ class EmrServiceContainerStepsTest {
@Test
void aStepFlociDoesNotRunFailsWithoutRunning() {
// A cluster that installs Pig, which Floci adds only with floci.services.emr.pig.enabled.
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);
EmrCluster requested = cluster("pig", true, pig);
requested.setApplications(PIG);
EmrCluster cluster = service.runJobFlow(requested, REGION);
fixture.runStepThread();
@@ -1025,6 +1031,46 @@ class EmrServiceContainerStepsTest {
assertEquals("FAILED", failed.getState());
assertEquals(EmrSparkSteps.NOT_RUN, failed.getFailureMessage());
assertEquals(List.of(), runner.jobs);
assertEquals(List.of(), fixture.releaseImages.asked);
}
@Test
void aPigStepOnAClusterWithoutPigRunsEmrsPigScriptWhichFindsNoPig() {
EmrStep pig = sparkStep("query", "CONTINUE");
List<String> args = List.of("pig-script", "--run-pig-script", "--args", "-f", "s3://bucket/query.pig");
pig.setArgs(args);
service.runJobFlow(cluster("no-pig", true, pig), REGION);
fixture.runStepThread();
// EMR's pig-script says "Pig isn't installed." there, and the step fails with its exit code.
assertEquals(args, runner.jobs.get(0).command());
assertFalse(runner.jobs.get(0).environment().containsKey("FLOCI_PIG_PROPERTIES"));
}
@Test
void aPigStepWithFlocisPigRunsEmrsPigScriptOnTezInTheReleasesImageWithPig() {
EmrService withPig = fixture.withPig();
EmrStep pig = sparkStep("query", "CONTINUE");
List<String> args = List.of("pig-script", "--run-pig-script", "--args", "-f", "s3://bucket/query.pig");
pig.setArgs(args);
EmrCluster requested = cluster("pig", true, pig);
requested.setApplications(PIG);
requested.setConfigurations("[{\"Classification\": \"pig-properties\", \"Properties\": "
+ "{\"pig.exec.reducers.max\": \"8\"}}]");
withPig.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",
"public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest", "false", "true")),
fixture.releaseImages.asked);
SparkJobRunner.Job job = runner.jobs.get(0);
assertEquals(args, job.command());
assertEquals(EmrServiceFixture.RecordingReleaseImages.IMAGE, job.imageTemplate());
assertEquals("exectype = tez\nmapreduce.job.working.dir = /user/${user.name}\npig.stats.notaskreport = true\n"
+ "yarn.app.mapreduce.client.max-retries = 1\npig.exec.reducers.max = 8",
job.environment().get("FLOCI_PIG_PROPERTIES"));
}
@Test
@@ -1495,7 +1541,7 @@ class EmrServiceContainerStepsTest {
assertEquals(stepId, job.runId());
// The release's EMR Serverless image with its EMR Serverless Hive image's Hive, made on the step's thread.
assertEquals(List.of(List.of("emr-7.5.0", "public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest",
"public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest", "true")), fixture.releaseImages.asked);
"public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest", "true", "false")), fixture.releaseImages.asked);
assertEquals(EmrServiceFixture.RecordingReleaseImages.IMAGE, job.imageTemplate());
assertNull(job.customImage());
assertEquals(List.of("hive-script", "--run-hive-script", "--args"), job.command());
@@ -1539,7 +1585,8 @@ class EmrServiceContainerStepsTest {
fixture.runStepThread();
assertEquals(List.of(List.of("emr-7.5.0", "public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest",
"registry.internal/emr-serverless/hive/emr-7.5.0:20250425", "true")), fixture.releaseImages.asked);
"registry.internal/emr-serverless/hive/emr-7.5.0:20250425", "true", "false")),
fixture.releaseImages.asked);
assertEquals(SparkJobRunner.Engine.SPARK, runner.jobs.get(0).engine());
assertEquals(EmrServiceFixture.RecordingReleaseImages.IMAGE, runner.jobs.get(0).imageTemplate());
}
@@ -2216,7 +2263,9 @@ class EmrServiceContainerStepsTest {
void aClusterWhoseStepsNoContainerRanHasNoStorage() {
EmrStep query = sparkStep("query", "CONTINUE");
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);
EmrCluster requested = cluster("unrun", true, query);
requested.setApplications(PIG);
EmrCluster cluster = service.runJobFlow(requested, REGION);
fixture.runStepThread();
service.terminateJobFlows(List.of(cluster.getId()));
@@ -197,15 +197,16 @@ 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, then whether it has Hive.
// Each image asked for: its release, then the two it is made of, then whether it has Hive, and Pig.
final List<List<String>> asked = new ArrayList<>();
// Each image released, by id.
final List<String> released = new ArrayList<>();
RuntimeException failure;
@Override
public String image(String releaseLabel, String sparkImage, String hiveImage, boolean withHive) {
asked.add(List.of(releaseLabel, sparkImage, hiveImage, String.valueOf(withHive)));
public String image(String releaseLabel, String sparkImage, String hiveImage, boolean withHive,
boolean withPig) {
asked.add(List.of(releaseLabel, sparkImage, hiveImage, String.valueOf(withHive), String.valueOf(withPig)));
if (failure != null) {
throw failure;
}
@@ -329,6 +330,18 @@ final class EmrServiceFixture {
iam);
}
/**
* A new service on the same storage and clock, as {@link #restart} builds, with Floci's Pig on, its steps' threads
* this fixture's, and its events not delivered.
*/
EmrService withPig() {
EmulatorConfig config = config(false);
when(config.services().emr().pig().enabled()).thenReturn(true);
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) {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().emr().defaultReleaseLabel()).thenReturn("emr-7.5.0");
@@ -13,6 +13,7 @@ import java.nio.file.Path;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -24,6 +25,9 @@ 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 static final String RELEASE = "emr-7.5.0";
// The pig.properties lines Floci gives every Pig after its exectype, ahead of the cluster's.
private static final String FLOCIS_PIG_LINES = "mapreduce.job.working.dir = /user/${user.name}\n"
+ "pig.stats.notaskreport = true\nyarn.app.mapreduce.client.max-retries = 1";
private final ObjectMapper objectMapper = new ObjectMapper();
@@ -80,18 +84,19 @@ class EmrSparkStepsTest {
"aws s3 cp s3://bucket/my-script.sh /home/hadoop; chmod u+x /home/hadoop/my-script.sh;"
+ " cd /home/hadoop; ./my-script.sh");
assertEquals(bash, EmrSparkSteps.command(step("command-runner.jar", null, bash.toArray(String[]::new))));
assertEquals(bash, EmrSparkSteps.command(step("command-runner.jar", null, bash.toArray(String[]::new)), false));
assertEquals(List.of("python3", "-c", "print(1)"),
EmrSparkSteps.command(step("command-runner.jar", null, "python3", "-c", "print(1)")));
EmrSparkSteps.command(step("command-runner.jar", null, "python3", "-c", "print(1)"), false));
assertNull(EmrSparkSteps.command(
step("command-runner.jar", null, "spark-submit", "s3://bucket/jobs/report.py")));
step("command-runner.jar", null, "spark-submit", "s3://bucket/jobs/report.py"), false));
}
@Test
void aScriptRunnerStepFetchesItsScriptAndRunsItWithItsArguments() {
for (String jar : List.of("script-runner.jar",
"s3://us-east-1.elasticmapreduce/libs/script-runner/script-runner.jar")) {
List<String> command = EmrSparkSteps.command(step(jar, null, "s3://bucket/my-script.sh", "--day", "1"));
List<String> command = EmrSparkSteps.command(step(jar, null, "s3://bucket/my-script.sh", "--day", "1"),
false);
assertEquals(List.of("bash", "-c"), command.subList(0, 2));
assertTrue(command.get(2).contains("aws s3 cp --only-show-errors"));
@@ -105,7 +110,8 @@ class EmrSparkStepsTest {
throws Exception {
// Not executable yet: script-runner makes it so, as it does a script it fetched from S3.
Files.writeString(workingDirectory.resolve("my-script.sh"), "#!/bin/sh\nprintf 'ran:%s|' \"$@\"\n");
List<String> command = EmrSparkSteps.command(step("script-runner.jar", null, "my-script.sh", "--day", "1 2"));
List<String> command = EmrSparkSteps.command(step("script-runner.jar", null, "my-script.sh", "--day", "1 2"),
false);
BootstrapProcess.Result ended =
BootstrapProcess.run(new ProcessBuilder(command).directory(workingDirectory.toFile()));
@@ -118,7 +124,7 @@ class EmrSparkStepsTest {
// The Release Guide's own S3DistCp step.
List<String> command = EmrSparkSteps.command(step("command-runner.jar", null, "s3-dist-cp",
"--s3Endpoint=s3.amazonaws.com", "--src=s3://bucket/logs/j-3GYXXXXXX9IOJ/node/",
"--dest=hdfs:///output", "--srcPattern=.*[a-zA-Z,]+"));
"--dest=hdfs:///output", "--srcPattern=.*[a-zA-Z,]+"), false);
// A spark-submit that shows what it was given and keeps the program, in place of the image's.
Path sparkSubmit = folder.resolve("spark-submit");
Files.writeString(sparkSubmit, "#!/bin/sh\nprintf '%s|' \"$@\"\ncp \"$3\" " + folder.resolve("kept.py") + "\n");
@@ -150,16 +156,88 @@ class EmrSparkStepsTest {
"-cacheFile", "s3://bucket/sample_dataset.dat#sample_dataset_cached.dat"};
String[] indexer = {"hadoop-lzo", "com.hadoop.compression.lzo.DistributedLzoIndexer", "s3://bucket/logs/"};
assertEquals(List.of(streaming), EmrSparkSteps.command(step("command-runner.jar", null, streaming)));
assertEquals(List.of(indexer), EmrSparkSteps.command(step("command-runner.jar", null, indexer)));
assertEquals(List.of(streaming), EmrSparkSteps.command(step("command-runner.jar", null, streaming), false));
assertEquals(List.of(indexer), EmrSparkSteps.command(step("command-runner.jar", null, indexer), false));
}
@Test
void aPigStepRunsEmrsPigScriptUnlessItsClusterLacksTheOneItInstalls() {
// The Release Guide's Pig step, as the AWS CLI turns Type=PIG into one.
String[] pig = {"pig-script", "--run-pig-script", "--args", "-f", "s3://bucket/do-reports2.pig", "-p",
"INPUT=s3://bucket/input", "-p", "OUTPUT=s3://bucket/output"};
assertEquals(List.of(pig), EmrSparkSteps.command(step("command-runner.jar", null, pig), false));
// On a cluster that installs Pig, which Floci has not added, EMR would run it.
assertNull(EmrSparkSteps.command(step("command-runner.jar", null, pig), true));
// pig itself is a command like any other, there or not.
assertEquals(List.of("pig", "-e", "fs -ls /"),
EmrSparkSteps.command(step("command-runner.jar", null, "pig", "-e", "fs -ls /"), false));
}
@Test
void aClusterInstallsPigWhenItsApplicationsNameIt() {
assertTrue(EmrSparkSteps.installsPig(RELEASE, "[{\"Name\": \"Hadoop\"}, {\"Name\": \"Pig\"}]", objectMapper));
assertTrue(EmrSparkSteps.installsPig(RELEASE, "[{\"Name\": \"pig\"}]", objectMapper));
for (String applications : new String[]{HIVE_AND_SPARK, "[]", null, "[{"}) {
assertFalse(EmrSparkSteps.installsPig(RELEASE, applications, objectMapper));
}
// "Pig and Oozie are not included" in a release of the AWS runtime for Apache Spark.
assertFalse(EmrSparkSteps.installsPig("emr-spark-8.1.0", "[{\"Name\": \"Pig\"}]", objectMapper));
}
@Test
void aPigCommandRunsOnTezWithTheClustersTezSiteThenItsPigProperties() {
String configurations = """
[{"Classification": "pig-properties", "Properties": {"pig.exec.reducers.max": "8"}},
{"Classification": "tez-site", "Properties": {"tez.grouping.max-size": "268435456",
"tez.am.resource.memory.mb": "2048"}},
{"Classification": "pig-properties", "Properties": {"tez.am.resource.memory.mb": "1536"}},
{"Classification": "hive-site", "Properties": {"hive.exec.reducers.max": "4"}}]""";
Map<String, String> variables = EmrSparkSteps.pigEnvironment(configurations, objectMapper);
// Tez, as EMR's Pig 0.16.0 and later, from a working directory S3A takes as HDFS does, then tez-site's, then
// pig-properties', a later line winning.
assertEquals(String.join("\n", "exectype = tez", "mapreduce.job.working.dir = /user/${user.name}",
"pig.stats.notaskreport = true", "yarn.app.mapreduce.client.max-retries = 1",
"tez.grouping.max-size = 268435456",
"tez.am.resource.memory.mb = 1536", "pig.exec.reducers.max = 8"),
variables.get("FLOCI_PIG_PROPERTIES"));
assertEquals(Set.of("FLOCI_PIG_PROPERTIES"), variables.keySet());
}
@Test
void aClustersPigPropertiesCanRunPigOnMapReduce() {
// "You can explicitly set exectype=mapreduce in the pig-properties configuration classification".
String configurations = """
[{"Classification": "pig-properties", "Properties": {"exectype": "mapreduce"}}]""";
assertEquals("exectype = mapreduce\n" + FLOCIS_PIG_LINES,
EmrSparkSteps.pigEnvironment(configurations, objectMapper).get("FLOCI_PIG_PROPERTIES"));
}
@Test
void aClustersPigLog4jAndPigEnvReachItsPigsConfiguration() {
String configurations = """
[{"Classification": "pig-log4j", "Properties": {"log4j.logger.org.apache.pig": "DEBUG, A"}},
{"Classification": "pig-env", "Configurations": [
{"Classification": "export", "Properties": {"PIG_HEAPSIZE": "2048", "BAD NAME": "x"}}]}]""";
Map<String, String> variables = EmrSparkSteps.pigEnvironment(configurations, objectMapper);
// Pig reads the log4j.properties its log4jconf names, which gets pig-log4j's lines.
assertEquals("exectype = tez\n" + FLOCIS_PIG_LINES + "\nlog4jconf = /tmp/floci-pig-conf/log4j.properties",
variables.get("FLOCI_PIG_PROPERTIES"));
assertEquals("log4j.logger.org.apache.pig = DEBUG, A", variables.get("FLOCI_PIG_LOG4J"));
assertEquals("export PIG_HEAPSIZE='2048'", variables.get("FLOCI_PIG_ENV"));
}
@Test
void toolsTheImageDoesNotHaveAreNotRun() {
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")));
assertNull(EmrSparkSteps.command(step("command-runner.jar", null, "pig-script", "--run-pig-script"), true));
assertNull(EmrSparkSteps.command(step("command-runner.jar", null), false));
assertNull(EmrSparkSteps.command(step("script-runner.jar", null), false));
assertNull(EmrSparkSteps.command(step("s3://bucket/jars/app.jar", null, "1"), false));
}
@Test
@@ -211,7 +289,7 @@ class EmrSparkStepsTest {
assertNull(EmrSparkSteps.hive(query, RELEASE, 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));
assertEquals(query.getArgs(), EmrSparkSteps.command(query, false));
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"),
@@ -0,0 +1,285 @@
package io.floci.aws.services.emr;
import com.sun.net.httpserver.HttpServer;
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.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import java.util.zip.GZIPOutputStream;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
class PigDistributionTest {
private static final Duration TIMEOUT = Duration.ofSeconds(5);
private static final Duration STALL = Duration.ofMillis(300);
private static final byte[] OTHER = "another file".getBytes(StandardCharsets.UTF_8);
// Releases the stalled download's server thread once the test is done with it.
private final CountDownLatch released = new CountDownLatch(1);
// A thread for each request, so the stalled one holds up no other.
private final ExecutorService handlers = Executors.newCachedThreadPool();
@TempDir
Path downloads;
private HttpServer server;
private byte[] distribution;
@BeforeEach
void serve() throws IOException {
distribution = distribution();
server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
server.setExecutor(handlers);
server.createContext("/missing", exchange -> {
exchange.sendResponseHeaders(404, -1);
exchange.close();
});
server.createContext("/pig.tar.gz", exchange -> {
exchange.sendResponseHeaders(200, distribution.length);
try (OutputStream body = exchange.getResponseBody()) {
body.write(distribution);
}
});
server.createContext("/other.tar.gz", exchange -> {
exchange.sendResponseHeaders(200, OTHER.length);
try (OutputStream body = exchange.getResponseBody()) {
body.write(OTHER);
}
});
// Sends its headers and its first bytes, then nothing until the test is done.
server.createContext("/stalled.tar.gz", exchange -> {
exchange.sendResponseHeaders(200, distribution.length);
OutputStream body = exchange.getResponseBody();
body.write(distribution, 0, 16);
body.flush();
try {
released.await(1, TimeUnit.MINUTES);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
exchange.close();
});
server.start();
}
@AfterEach
void stop() {
released.countDown();
server.stop(0);
handlers.shutdownNow();
}
@Test
void theFirstUrlThatGivesTheDistributionWithItsChecksumIsTheOneDownloaded() throws Exception {
Path downloaded = pig(TIMEOUT, "/missing", "/other.tar.gz", "/pig.tar.gz").download();
try {
assertArrayEquals(distribution, Files.readAllBytes(downloaded));
} finally {
Files.deleteIfExists(downloaded);
}
}
@Test
void aDownloadThatStallsPassesToTheNextUrl() throws Exception {
Path downloaded = pig(STALL, "/stalled.tar.gz", "/pig.tar.gz").download();
try {
assertArrayEquals(distribution, Files.readAllBytes(downloaded));
} finally {
Files.deleteIfExists(downloaded);
}
}
@Test
void noUrlGivingItFailsWithWhatEachGaveAndLeavesNoFile() throws Exception {
PigDistribution pig = pig(STALL, "/missing", "/other.tar.gz", "/stalled.tar.gz");
IOException failure = assertThrows(IOException.class, pig::download);
assertEquals("Could not download Apache Pig: " + url("/missing") + ": answered 404; " + url("/other.tar.gz")
+ ": has the SHA-256 " + sha256(OTHER) + ", not the " + sha256(distribution)
+ " floci.services.emr.pig.sha256 names; " + url("/stalled.tar.gz") + ": Read timed out",
failure.getMessage());
assertEquals(List.of(), leftovers());
}
@Test
void noUrlAtAllFails() {
IOException failure = assertThrows(IOException.class,
() -> new PigDistribution(List.of(" "), "0".repeat(64), TIMEOUT, TIMEOUT, downloads).download());
assertEquals("Could not download Apache Pig: no URL is set", failure.getMessage());
}
@Test
void whatPigRunsFromGoesUnderItsFolderOwnedByRootAndTheRestStaysOut(@TempDir Path folder) throws Exception {
Path archive = Files.write(folder.resolve("pig.tar.gz"), distribution);
// Its Tez and that Tez's protobuf stay out, the image's taking their place through Floci's pig-env.sh.
assertEquals(List.of("pig/ dir", "pig/bin/ dir", "pig/bin/pig 755", "pig/conf/pig.properties 644",
"pig/lib/ dir", "pig/lib/jython.jar 644", "pig/lib/h3/orc-core.jar 644",
"pig/pig-0.18.0-core-h3.jar 644", "pig/LICENSE.txt 644", "pig/conf/pig-env.sh 644"),
entries(written(archive)));
}
@Test
void pigsEnvironmentPutsTheImagesTezAheadOfTheClassPathAClusterSets(@TempDir Path folder) throws Exception {
Path archive = Files.write(folder.resolve("pig.tar.gz"), distribution);
assertEquals("export PIG_CLASSPATH=\"/usr/lib/tez/*:/usr/lib/tez/lib/*${PIG_CLASSPATH:+:$PIG_CLASSPATH}\"\n",
content(written(archive), "pig/conf/pig-env.sh"));
}
@Test
void theImagesNameHoldsTheDistributionsChecksum() {
assertEquals("pig " + "a".repeat(64),
new PigDistribution(List.of("https://downloads.example/pig.tar.gz"), "A".repeat(64), TIMEOUT, TIMEOUT,
downloads).identity());
}
@Test
void pigOnThePathRunsItsLauncherByItsOwnPath() {
assertEquals("#!/bin/bash\nexec /usr/lib/pig/bin/pig \"$@\"\n", PigDistribution.COMMAND);
}
@Test
void aPathOutsideTheDistributionsFolderStaysOut() {
assertEquals("pig/lib/a.jar", PigDistribution.kept("pig-0.18.0/lib/a.jar"));
for (String path : new String[]{"/etc/passwd", "pig-0.18.0/lib/../../etc/passwd", "README.txt",
"pig-0.18.0/lib/spark/spark-core.jar", "pig-0.18.0/lib/hadoop3-runtime/hadoop-common.jar",
"pig-0.18.0/lib/h3/tez-api-0.10.3.jar", "pig-0.18.0/lib/protobuf-java-3.21.1.jar",
"pig-0.18.0/docs/index.html", "pig-0.18.0/build.xml", null}) {
assertNull(PigDistribution.kept(path), path);
}
}
private PigDistribution pig(Duration readTimeout, String... paths) throws Exception {
List<String> urls = new ArrayList<>();
for (String path : paths) {
urls.add(url(path));
}
return new PigDistribution(urls, sha256(distribution), TIMEOUT, readTimeout, downloads);
}
private String url(String path) {
return "http://" + server.getAddress().getHostString() + ":" + server.getAddress().getPort() + path;
}
// The files downloads left in their folder.
private List<Path> leftovers() throws IOException {
try (Stream<Path> files = Files.list(downloads)) {
return files.toList();
}
}
// A distribution as Apache's is laid out: its own folder, what Pig runs from, and what it does not.
private static byte[] distribution() throws IOException {
ByteArrayOutputStream gzipped = new ByteArrayOutputStream();
try (TarArchiveOutputStream tar = new TarArchiveOutputStream(new GZIPOutputStream(gzipped))) {
tar.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
directory(tar, "pig-0.18.0/");
directory(tar, "pig-0.18.0/bin/");
file(tar, "pig-0.18.0/bin/pig", 0755);
file(tar, "pig-0.18.0/conf/pig.properties", 0644);
directory(tar, "pig-0.18.0/docs/");
file(tar, "pig-0.18.0/docs/index.html", 0644);
directory(tar, "pig-0.18.0/lib/");
file(tar, "pig-0.18.0/lib/jython.jar", 0644);
file(tar, "pig-0.18.0/lib/h3/tez-api-0.10.3.jar", 0644);
file(tar, "pig-0.18.0/lib/h3/orc-core.jar", 0644);
file(tar, "pig-0.18.0/lib/protobuf-java-3.21.1.jar", 0644);
file(tar, "pig-0.18.0/conf/pig-env.sh", 0644);
file(tar, "pig-0.18.0/lib/spark/spark-core.jar", 0644);
file(tar, "pig-0.18.0/lib/hadoop3-runtime/hadoop-common.jar", 0644);
file(tar, "pig-0.18.0/src/org/apache/pig/Main.java", 0644);
file(tar, "pig-0.18.0/pig-0.18.0-core-h3.jar", 0644);
file(tar, "pig-0.18.0/LICENSE.txt", 0644);
file(tar, "pig-0.18.0/build.xml", 0644);
}
return gzipped.toByteArray();
}
private static void directory(TarArchiveOutputStream tar, String name) throws IOException {
TarArchiveEntry entry = new TarArchiveEntry(name);
entry.setIds(1000, 1000);
tar.putArchiveEntry(entry);
tar.closeArchiveEntry();
}
private static void file(TarArchiveOutputStream tar, String name, int mode) throws IOException {
byte[] content = name.getBytes(StandardCharsets.UTF_8);
TarArchiveEntry entry = new TarArchiveEntry(name);
entry.setSize(content.length);
entry.setMode(mode);
entry.setIds(1000, 1000);
entry.setNames("builder", "builder");
tar.putArchiveEntry(entry);
tar.write(content);
tar.closeArchiveEntry();
}
private static byte[] written(Path archive) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
PigDistribution.write(archive, out);
return out.toByteArray();
}
// Each entry: its name, then "dir" or its mode in octal; every one is root's, and none is a 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) {
assertEquals("root:root:0:0", entry.getUserName() + ":" + entry.getGroupName() + ":"
+ entry.getLongUserId() + ":" + entry.getLongGroupId(), entry.getName());
assertFalse(entry.isSymbolicLink(), entry.getName());
entries.add(entry.getName() + " " + (entry.isDirectory() ? "dir"
: Integer.toOctalString(entry.getMode() & 0777)));
}
}
return entries;
}
private static String content(byte[] archive, String name) throws IOException {
try (TarArchiveInputStream in = new TarArchiveInputStream(new ByteArrayInputStream(archive))) {
TarArchiveEntry entry;
while ((entry = in.getNextEntry()) != null) {
if (entry.getName().equals(name)) {
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
}
}
}
return null;
}
private static String sha256(byte[] content) throws Exception {
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(content));
}
}
@@ -1115,6 +1115,55 @@ class EmrServerlessSparkRunnerTest {
assertTrue(site.contains(",HADOOP_MAPRED_HOME=/opt/hadoop-mapreduce</value>"), site);
}
@Test
void aCommandsTezOnItsClustersYarnRunsStockTezThereAsHivesDoes() {
String site = EmrServerlessSparkRunner.tezSite(stepJob(Map.of()).onStorage(ON_YARN), AWS_ENVIRONMENT);
for (String setting : List.of("tez.local.mode</name><value>false",
"yarn.resourcemanager.hostname</name><value>ip-10-0-0-1.ec2.internal",
"tez.framework.client</name><value>org.apache.tez.client.TezYarnClient",
"tez.am.yarn.scheduler.class</name><value>org.apache.tez.dag.app.rm.YarnTaskSchedulerService",
"tez.am.shuffle.auxiliary-service.id</name><value>mapreduce_shuffle",
"tez.lib.uris</name><value>file:///usr/lib/tez/,file:///usr/lib/tez/lib/",
"tez.use.cluster.hadoop-libs</name><value>false",
"tez.am.resource.memory.mb</name><value>1024",
"tez.task.resource.memory.mb</name><value>768",
"tez.runtime.intermediate-output.should-compress</name><value>false")) {
assertTrue(site.contains("<name>" + setting + "</value>"), setting + " in " + site);
}
// Without Hive's jar or home, which a command's Tez does not run.
assertTrue(site.contains("<name>tez.cluster.additional.classpath.prefix</name><value>$PWD/*:/usr/lib/tez/*:"
+ "/usr/lib/tez/lib/*:/usr/lib/hadoop-mapreduce/*:/usr/lib/hadoop-mapreduce/lib/*:/usr/lib/hadoop/*:"
+ "/usr/lib/hadoop/lib/*:/usr/lib/hadoop-hdfs/*:/usr/lib/hadoop-hdfs/lib/*:/usr/lib/hadoop-yarn/*:"
+ "/usr/lib/hadoop-yarn/lib/*:/usr/lib/hadoop-lzo/lib/*</value>"), site);
String environment = "</name><value>JDK_JAVA_OPTIONS=" + EmrServerlessSparkRunner.yarnJavaOptions()
+ ",TEZ_HOME=/usr/lib/tez,AWS_ACCESS_KEY_ID=ASIASTEP,AWS_ENDPOINT_URL=http://floci:4566</value>";
assertTrue(site.contains("<name>tez.am.launch.env" + environment), site);
assertTrue(site.contains("<name>tez.task.launch.env" + environment), site);
assertFalse(site.contains("hive"), site);
}
@Test
void aCommandsTezWhereThereIsNoYarnRunsInLocalModeWithoutTheJarsAContainerIsGiven() {
String site = EmrServerlessSparkRunner.tezSite(stepJob(Map.of()).onStorage(STORAGE), List.of());
assertEquals("<property><name>tez.local.mode</name><value>true</value></property>\n"
+ "<property><name>tez.ignore.lib.uris</name><value>true</value></property>\n"
+ "<property><name>tez.runtime.optimize.local.fetch</name><value>true</value></property>", site);
}
@Test
void aCommandOnItsClusterGetsItsTezSite() {
ContainerBuilder builder = mock(ContainerBuilder.class);
ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(builder.newContainer(anyString())).thenReturn(spec);
runner(builder).run(commandJob(List.of("pig", "-e", "fs -ls /"), Map.of(), STORAGE), progress);
verify(spec).withEnv(eq("FLOCI_TEZ_SITE"), argThat(site -> site.contains(
"<name>tez.local.mode</name><value>true</value>")));
}
@Test
void aClustersMapredSiteReplacesFlocisSettingsOnYarn() {
String site = EmrServerlessSparkRunner.mapredSite(hadoopJob(null,