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

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

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

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

No files matched your search

@@ -2049,7 +2049,8 @@ public interface EmulatorConfig {
/**
* {@code immediate} completes each step by time without running anything; {@code docker} runs each
* Spark step's {@code spark-submit} in a container of the release's EMR Serverless image.
* Spark step's {@code spark-submit} in a container of the release's EMR Serverless image, which a cluster
* with Hive has Hive added to, and that cluster's Hive steps' {@code hive} too.
*/
@WithDefault("immediate")
String runnerMode();
@@ -2063,6 +2064,14 @@ public interface EmulatorConfig {
*/
Optional<String> imageTemplate();
/**
* The EMR Serverless Hive image a {@code docker} cluster with Hive takes Hive from, into the image its
* bootstrap and steps run in, as {@link #imageTemplate()} names the image Hive is added to, for example
* "registry.internal/emr-serverless/hive/%s:20250425". If omitted, Floci uses the release's public EMR
* Serverless Hive image on Amazon ECR Public.
*/
Optional<String> hiveImageTemplate();
/**
* When true, Floci removes, in the {@code docker} runner mode, every EMR step driver and bootstrap
* container a previous run of <em>this same</em> Floci left on the daemon (matched by the
@@ -43,6 +43,12 @@ public interface BootstrapRunner {
*/
record Bootstrap(String clusterId, String accountId, String region, String releaseLabel, String imageTemplate,
String dockerNetwork, String role, List<Action> actions, String logFolder) {
/** This bootstrap, run in {@code image}. */
Bootstrap inImage(String image) {
return new Bootstrap(clusterId, accountId, region, releaseLabel, image, dockerNetwork, role, actions,
logFolder);
}
}
/** A bootstrap action: its name, the script it runs, and that script's arguments. */
@@ -0,0 +1,187 @@
package io.github.hectorvent.floci.services.emr;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.exception.NotFoundException;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.EmulatorConfig.EcsServiceConfig.ImagePullBehavior;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
import io.github.hectorvent.floci.core.common.docker.RetryingTarCopier;
import io.github.hectorvent.floci.services.emrserverless.EmrServerlessSparkRunner;
import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Makes, on the Docker daemon, the image a release's clusters with Hive run in: its EMR Serverless image with the
* Hive, Tez, HDFS, MapReduce and YARN of its EMR Serverless Hive image, the two being built on one Hadoop and one Java.
* A container of the EMR Serverless image, never started, gets the Hive image's folders streamed in from another,
* never started either, and is committed, as a bootstrap's container is. The two images ship different builds of
* {@code emr-serverless-goodies-common} under one name, so Tez keeps the Hive image's in a folder of its own, its links
* leading there, and the Hive image's Hadoop configuration, which puts Tez on the class path, goes to
* {@link EmrServerlessSparkRunner#HIVE_HADOOP_CONF}, for Hive alone. The image is named after its release, the ids of
* the two images and what is copied, so a newer pull of either, or a change to what is copied, makes another, and it is
* kept for the release's next cluster.
*/
@ApplicationScoped
public class EmrReleaseImages implements ReleaseImages {
private static final Logger LOG = Logger.getLogger(EmrReleaseImages.class);
private static final String SERVICE = "emr";
private static final String COMPONENT = "emr-release";
private static final String EMR_SHARE = "/usr/share/aws/emr";
private static final String GOODIES = EMR_SHARE + "/serverless-goodies/lib";
private static final String HIVE_GOODIES = "serverless-goodies-hive/lib";
// What the Hive image adds: Hive and Tez, the Hadoop services the EMR Serverless image lacks, which its own
// Hadoop's client links name, their configuration and commands, EMR's s3-dist-cp among them, and the two folders
// kept apart.
static final List<Copy> COPIES = List.of(
new Copy("/usr/lib/hive", "/usr/lib"),
new Copy("/usr/lib/tez", "/usr/lib"),
new Copy("/usr/lib/hadoop-hdfs", "/usr/lib"),
new Copy("/usr/lib/hadoop-mapreduce", "/usr/lib"),
new Copy("/usr/lib/hadoop-yarn", "/usr/lib"),
new Copy("/usr/lib/bigtop-groovy", "/usr/lib"),
new Copy("/etc/hive", "/etc"),
new Copy("/etc/tez", "/etc"),
new Copy("/etc/tez-ui", "/etc"),
new Copy(EMR_SHARE + "/s3-dist-cp", EMR_SHARE),
new Copy("/usr/bin/hive", "/usr/bin"),
new Copy("/usr/bin/beeline", "/usr/bin"),
new Copy("/usr/bin/hiveserver2", "/usr/bin"),
new Copy("/usr/bin/hplsql", "/usr/bin"),
new Copy("/usr/bin/s3-dist-cp", "/usr/bin"),
Copy.to("/etc/hadoop/conf", EmrServerlessSparkRunner.HIVE_HADOOP_CONF),
new Copy(GOODIES, EMR_SHARE, HIVE_GOODIES));
// One making at a time for each image; another thread asking for it waits, then finds it there.
private final Map<String, Object> making = new ConcurrentHashMap<>();
private final ContainerLifecycleManager lifecycleManager;
private final ContainerBuilder containerBuilder;
private final ImageCacheService imageCacheService;
private final EmulatorConfig config;
@Inject
public EmrReleaseImages(ContainerLifecycleManager lifecycleManager, ContainerBuilder containerBuilder,
ImageCacheService imageCacheService, EmulatorConfig config) {
this.lifecycleManager = lifecycleManager;
this.containerBuilder = containerBuilder;
this.imageCacheService = imageCacheService;
this.config = config;
}
/**
* The image's id: the image is made from the two as a container of either would run them, pulled when missing, and
* the ids their names lead to now, so a newer pull of either, which moves its name, makes another. A step gets
* the id, as it gets a bootstrap image's, so the image-registry-base Floci prefixes image names with does not send
* it to a registry for an image only this daemon has.
*/
@Override
public String image(String releaseLabel, String sparkImage, String hiveImage) {
String spark = containerBuilder.resolveImage(sparkImage);
String hive = containerBuilder.resolveImage(hiveImage);
String sparkId = imageCacheService.resolveForLaunch(spark, ImagePullBehavior.PREFER_CACHED, null).imageId();
String hiveId = imageCacheService.resolveForLaunch(hive, ImagePullBehavior.PREFER_CACHED, null).imageId();
String repository = ContainerStorageHelper.dockerName(config, COMPONENT);
String tag = releaseLabel + "-" + Digests.sha256Hex(sparkId + "\n" + hiveId + "\n" + COPIES).substring(0, 12);
synchronized (making.computeIfAbsent(repository + ":" + tag, name -> new Object())) {
DockerClient docker = lifecycleManager.getDockerClient();
try {
return docker.inspectImageCmd(repository + ":" + tag).exec().getId();
} catch (NotFoundException e) {
LOG.infov("Making {0}:{1} for EMR clusters with Hive, from {2} and {3}", repository, tag, spark, hive);
}
String user = docker.inspectImageCmd(sparkId).exec().getConfig().getUser();
Map<String, String> labels = new LinkedHashMap<>();
labels.put(ContainerStorageHelper.SERVICE_LABEL, SERVICE);
labels.put(ContainerStorageHelper.COMPONENT_LABEL, COMPONENT);
labels.put(ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config));
List<String> containers = new ArrayList<>();
try {
String target = docker.createContainerCmd(sparkId).withLabels(labels).exec().getId();
containers.add(target);
String source = docker.createContainerCmd(hiveId).withLabels(labels).exec().getId();
containers.add(source);
for (Copy copy : COPIES) {
RetryingTarCopier.copyStreamed(docker, target, copy.into(), copy.from(),
out -> copy(docker.copyArchiveFromContainerCmd(source, copy.from()).exec(), out, copy));
}
return lifecycleManager.commit(target, repository, tag,
user == null || user.isBlank() ? "root" : user, labels);
} finally {
for (String container : containers) {
try {
docker.removeContainerCmd(container).withForce(true).exec();
} catch (RuntimeException e) {
LOG.warnv("Could not remove container {0}, left from making {1}:{2}: {3}", container,
repository, tag, e.getMessage());
}
}
}
}
}
/**
* Writes the archive Docker gave of {@code copy}'s source, whose entries start with its name, to {@code out} as
* {@code copy} puts it in its folder: under its own name, after the folders of one made of several, and with a
* link into the EMR Serverless image's goodies leading to the Hive image's copy of them instead.
*/
static void copy(InputStream archive, OutputStream out, Copy copy) throws IOException {
String name = copy.from().substring(copy.from().lastIndexOf('/') + 1);
try (InputStream source = archive;
TarArchiveInputStream in = new TarArchiveInputStream(source);
TarArchiveOutputStream tar = RetryingTarCopier.newTarStream(out)) {
for (int slash = copy.as().indexOf('/'); slash > 0; slash = copy.as().indexOf('/', slash + 1)) {
tar.putArchiveEntry(new TarArchiveEntry(copy.as().substring(0, slash + 1)));
tar.closeArchiveEntry();
}
TarArchiveEntry entry;
while ((entry = in.getNextEntry()) != null) {
entry.setName(renamed(entry.getName(), name, copy.as()));
if (entry.isLink()) {
entry.setLinkName(renamed(entry.getLinkName(), name, copy.as()));
} else if (entry.isSymbolicLink() && entry.getLinkName().startsWith(GOODIES + "/")) {
entry.setLinkName(EMR_SHARE + "/" + HIVE_GOODIES + entry.getLinkName().substring(GOODIES.length()));
}
tar.putArchiveEntry(entry);
in.transferTo(tar);
tar.closeArchiveEntry();
}
}
}
// An archive's path under the name it was made with, under the copy's instead.
private static String renamed(String path, String name, String as) {
return path.equals(name) || path.startsWith(name + "/") ? as + path.substring(name.length()) : path;
}
/** A path of the Hive image, a file or a folder, copied into the image made's folder {@code into} as {@code as}. */
record Copy(String from, String into, String as) {
/** {@code from} copied into a folder of the image made under its own name. */
Copy(String from, String into) {
this(from, into, from.substring(from.lastIndexOf('/') + 1));
}
/** {@code from} copied to the path {@code to}, whose folder the image made has. */
static Copy to(String from, String to) {
return new Copy(from, to.substring(0, to.lastIndexOf('/')), to.substring(to.lastIndexOf('/') + 1));
}
}
}
@@ -55,6 +55,7 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
@@ -113,11 +114,13 @@ public class EmrService implements Resettable, StoredResourceArns {
private final SparkJobRunner sparkRunner;
private final BootstrapRunner bootstrapRunner;
private final ClusterStorage clusterStorage;
private final ReleaseImages releaseImages;
private final Executor stepExecutor;
private final IamService iamService;
// Where a step's driver runs: image-template, with the release label for %s, and docker-network; null when
// not set.
private final String imageTemplate;
private final String hiveImageTemplate;
private final String dockerNetwork;
// The steps a thread is running, by account and id; a RUNNING container step not here was left by a restart.
private final Set<String> executing = new HashSet<>();
@@ -192,26 +195,28 @@ public class EmrService implements Resettable, StoredResourceArns {
@Inject
public EmrService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver,
EmrEventPublisher eventPublisher, EmrServerlessSparkRunner sparkRunner,
EmrBootstrapRunner bootstrapRunner, EmrClusterStorage clusterStorage, IamService iamService) {
EmrBootstrapRunner bootstrapRunner, EmrClusterStorage clusterStorage,
EmrReleaseImages releaseImages, IamService iamService) {
this(storageFactory, config, regionResolver, eventPublisher, Clock.systemUTC(),
Wakeups.timer(Clock.systemUTC()),
RUNNER_DOCKER.equalsIgnoreCase(config.services().emr().runnerMode()) ? sparkRunner : null,
RUNNER_DOCKER.equalsIgnoreCase(config.services().emr().runnerMode()) ? bootstrapRunner : null,
RUNNER_DOCKER.equalsIgnoreCase(config.services().emr().runnerMode()) ? clusterStorage : null,
RUNNER_DOCKER.equalsIgnoreCase(config.services().emr().runnerMode()) ? releaseImages : null,
Executors.newCachedThreadPool(Thread.ofPlatform().daemon().name("emr-step-", 0).factory()),
iamService);
}
EmrService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver,
EmrEventPublisher eventPublisher, Clock clock, Wakeups wakeups) {
this(storageFactory, config, regionResolver, eventPublisher, clock, wakeups, null, null, null, Runnable::run,
null);
this(storageFactory, config, regionResolver, eventPublisher, clock, wakeups, null, null, null, null,
Runnable::run, null);
}
EmrService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver,
EmrEventPublisher eventPublisher, Clock clock, Wakeups wakeups, SparkJobRunner sparkRunner,
BootstrapRunner bootstrapRunner, ClusterStorage clusterStorage, Executor stepExecutor,
IamService iamService) {
BootstrapRunner bootstrapRunner, ClusterStorage clusterStorage, ReleaseImages releaseImages,
Executor stepExecutor, IamService iamService) {
this.clusterStore = storageFactory.create("emr", "emr-clusters.json",
new TypeReference<Map<String, EmrCluster>>() {});
this.secConfigStore = storageFactory.create("emr", "emr-security-configs.json",
@@ -224,9 +229,11 @@ public class EmrService implements Resettable, StoredResourceArns {
this.sparkRunner = sparkRunner;
this.bootstrapRunner = bootstrapRunner;
this.clusterStorage = clusterStorage;
this.releaseImages = releaseImages;
this.stepExecutor = stepExecutor;
this.iamService = iamService;
this.imageTemplate = config.services().emr().imageTemplate().orElse(null);
this.hiveImageTemplate = config.services().emr().hiveImageTemplate().orElse(null);
this.dockerNetwork = config.services().emr().dockerNetwork().orElse(null);
this.lifecycle = new EmrClusterLifecycle(config.services().emr().clusterStartupDelaySeconds(),
config.services().emr().stepDurationSeconds(),
@@ -1407,30 +1414,46 @@ public class EmrService implements Resettable, StoredResourceArns {
@Override
public void start(EmrCluster cluster, EmrStep step, String region) {
String accountId = regionResolver.getAccountId();
List<String> application = EmrSparkSteps.application(step);
List<String> command = application == null ? EmrSparkSteps.command(step) : null;
EmrSparkSteps.HiveCommand hive = EmrSparkSteps.hive(step, cluster.getApplications(),
cluster.getConfigurations(), SNAPSHOT_MAPPER);
List<String> application = hive == null ? EmrSparkSteps.application(step) : null;
List<String> command = hive == null && application == null ? EmrSparkSteps.command(step) : null;
SparkJobRunner.Storage storage = null;
if ((application != null || command != null) && clusterStorage != null) {
if ((hive != null || application != null || command != null) && clusterStorage != null) {
storage = clusterStorage.volumes(cluster.getId());
cluster.setStorageCreated(true);
}
SparkJobRunner.Job job = application == null && command == null ? null
: new SparkJobRunner.Job(SERVICE, step.getId(), accountId, region, cluster.getReleaseLabel(),
SparkJobRunner.Engine.SPARK,
cluster.getBootstrapImage() != null ? cluster.getBootstrapImage() : imageTemplate, null,
dockerNetwork, executionRole(cluster, step, accountId),
EmrSparkSteps.sparkDefaults(cluster.getConfigurations(), SNAPSHOT_MAPPER),
application != null ? application : List.of(), command, Duration.ZERO,
EmrSparkSteps.logFolder(cluster, step), null,
EmrSparkSteps.environment(step, cluster.getConfigurations(), SNAPSHOT_MAPPER), List.of(),
storage, EmrSparkSteps.coreSite(cluster.getConfigurations(), SNAPSHOT_MAPPER),
EmrSparkSteps.sparkLog4j2(cluster.getConfigurations(), SNAPSHOT_MAPPER),
EmrSparkSteps.mapredSite(cluster.getConfigurations(), SNAPSHOT_MAPPER),
EmrSparkSteps.hadoopLog4j(cluster.getConfigurations(), SNAPSHOT_MAPPER),
EmrSparkSteps.hadoopEnvironment(cluster.getConfigurations(), SNAPSHOT_MAPPER));
// The image a cluster's bootstrap left, which holds what its release's does; else a cluster with Hive's,
// which the step's thread makes, or the release's.
String image = cluster.getBootstrapImage() != null ? cluster.getBootstrapImage() : imageTemplate;
Supplier<String> releaseImage = cluster.getBootstrapImage() == null ? releaseImage(cluster) : null;
SparkJobRunner.Job job;
if (hive != null) {
job = new SparkJobRunner.Job(SERVICE, step.getId(), accountId, region, cluster.getReleaseLabel(),
SparkJobRunner.Engine.HIVE, image, null, dockerNetwork,
executionRole(cluster, step, accountId), Map.of(), hive.arguments(), hive.runner(),
Duration.ZERO, EmrSparkSteps.logFolder(cluster, step), null,
EmrSparkSteps.hiveEnvironment(cluster.getConfigurations(), SNAPSHOT_MAPPER), List.of(),
storage, Map.of(), Map.of(), Map.of(), Map.of(), Map.of());
} else if (application == null && command == null) {
job = null;
} else {
job = new SparkJobRunner.Job(SERVICE, step.getId(), accountId, region, cluster.getReleaseLabel(),
SparkJobRunner.Engine.SPARK, image, null, dockerNetwork,
executionRole(cluster, step, accountId),
EmrSparkSteps.sparkDefaults(cluster.getConfigurations(), SNAPSHOT_MAPPER),
application != null ? application : List.of(), command, Duration.ZERO,
EmrSparkSteps.logFolder(cluster, step), null,
EmrSparkSteps.environment(step, cluster.getConfigurations(), SNAPSHOT_MAPPER), List.of(),
storage, EmrSparkSteps.coreSite(cluster.getConfigurations(), SNAPSHOT_MAPPER),
EmrSparkSteps.sparkLog4j2(cluster.getConfigurations(), SNAPSHOT_MAPPER),
EmrSparkSteps.mapredSite(cluster.getConfigurations(), SNAPSHOT_MAPPER),
EmrSparkSteps.hadoopLog4j(cluster.getConfigurations(), SNAPSHOT_MAPPER),
EmrSparkSteps.hadoopEnvironment(cluster.getConfigurations(), SNAPSHOT_MAPPER));
}
StepLaunch launch = new StepLaunch(accountId, region, cluster.getId(), step.getId(), generation);
executing.add(stepKey(accountId, step.getId()));
stepExecutor.execute(() -> runStep(job, launch));
stepExecutor.execute(() -> runStep(job, launch, releaseImage));
}
@Override
@@ -1439,8 +1462,9 @@ public class EmrService implements Resettable, StoredResourceArns {
}
}
// A step's thread: its driver runs to its end, or the step fails at once when Floci does not run its kind.
private void runStep(SparkJobRunner.Job job, StepLaunch launch) {
// A step's thread: its driver runs to its end, or the step fails at once when Floci does not run its kind. A
// cluster with Hive's image is made first, when it is not there yet, so a failure to make it fails the step.
private void runStep(SparkJobRunner.Job job, StepLaunch launch, Supplier<String> releaseImage) {
String failure;
if (job == null) {
failure = EmrSparkSteps.NOT_RUN;
@@ -1448,12 +1472,14 @@ public class EmrService implements Resettable, StoredResourceArns {
SparkJobRunner.Outcome outcome;
StepProgress progress = new StepProgress(launch);
try {
SparkJobRunner.Job running = releaseImage != null && !progress.cancelled()
? job.inImage(releaseImage.get()) : job;
// The cluster's storage is there before its first step's container mounts it. A step a cancel,
// its cluster's end or a reset has passed does not start, so it makes none.
if (job.storage() != null && !progress.cancelled()) {
clusterStorage.create(launch.clusterId(), launch.accountId(), launch.region());
}
outcome = sparkRunner.run(job, progress);
outcome = sparkRunner.run(running, progress);
} catch (RuntimeException e) {
LOG.warnv(e, "EMR step {0} could not run", launch.stepId());
outcome = SparkJobRunner.Outcome.couldNotStart(e.getMessage());
@@ -1488,8 +1514,9 @@ public class EmrService implements Resettable, StoredResourceArns {
cluster.getReleaseLabel(), imageTemplate, dockerNetwork, instanceProfileRole(cluster, accountId),
bootstrapActions(cluster), logFolder);
BootstrapLaunch launch = new BootstrapLaunch(accountId, region, cluster.getId(), generation);
Supplier<String> releaseImage = releaseImage(cluster);
bootstrapping.add(clusterKey(accountId, cluster.getId()));
stepExecutor.execute(() -> runBootstrap(bootstrap, launch));
stepExecutor.execute(() -> runBootstrap(bootstrap, launch, releaseImage));
}
@Override
@@ -1500,6 +1527,22 @@ public class EmrService implements Resettable, StoredResourceArns {
}
}
/**
* What makes, on the thread that needs it, the image a cluster that installs Hive starts from, its release's EMR
* Serverless image with its EMR Serverless Hive image's Hive, and returns the image's id: an EMR cluster's nodes
* hold every application it installs, so its bootstrap actions and steps all run in it. Null for a cluster
* without Hive, which starts from the release's EMR Serverless image.
*/
private Supplier<String> releaseImage(EmrCluster cluster) {
if (releaseImages == null || !EmrSparkSteps.installsHive(cluster.getApplications(), SNAPSHOT_MAPPER)) {
return null;
}
String release = cluster.getReleaseLabel();
String spark = EmrServerlessSparkRunner.image(imageTemplate, release);
String hive = EmrServerlessSparkRunner.image(hiveImageTemplate, release, SparkJobRunner.Engine.HIVE);
return () -> releaseImages.image(release, spark, hive);
}
// A cluster's BootstrapActionConfig list, as RunJobFlow stored it once it had checked it.
private static List<BootstrapRunner.Action> bootstrapActions(EmrCluster cluster) {
List<BootstrapRunner.Action> actions = new ArrayList<>();
@@ -1517,12 +1560,17 @@ public class EmrService implements Resettable, StoredResourceArns {
return actions;
}
// A cluster's bootstrap thread: its actions run to their end, which then ends its BOOTSTRAPPING.
private void runBootstrap(BootstrapRunner.Bootstrap bootstrap, BootstrapLaunch launch) {
// A cluster's bootstrap thread: its actions run to their end, which then ends its BOOTSTRAPPING. They run in
// a cluster with Hive's image, which is made first when it is not there yet, unless the cluster ended, or a reset
// removed it, before the thread ran; a failure to make it ends the cluster as one to run the bootstrap does.
private void runBootstrap(BootstrapRunner.Bootstrap bootstrap, BootstrapLaunch launch,
Supplier<String> releaseImage) {
BooleanSupplier cancelled = () -> !RequestScopes.callAs(launch.accountId(), launch.region(),
() -> stillBootstrapping(launch));
BootstrapRunner.Outcome outcome;
try {
outcome = bootstrapRunner.run(bootstrap, () -> !RequestScopes.callAs(launch.accountId(), launch.region(),
() -> stillBootstrapping(launch)));
outcome = bootstrapRunner.run(releaseImage != null && !cancelled.getAsBoolean()
? bootstrap.inImage(releaseImage.get()) : bootstrap, cancelled);
} catch (RuntimeException e) {
LOG.warnv(e, "The bootstrap actions of EMR cluster {0} could not run", launch.clusterId());
outcome = BootstrapRunner.Outcome.couldNotRun(e.getMessage());
@@ -25,13 +25,14 @@ import java.util.Set;
* {@code command-runner.jar} step runs its command, and a {@code script-runner.jar} step its script, as the
* Release Guide's "Run commands and scripts on an Amazon EMR cluster" describes them, a
* {@code hadoop-streaming} or {@code hadoop-lzo} one through the image's {@code hadoop}, with MapReduce in local
* mode; an {@code s3-dist-cp} one runs Floci's own S3DistCp.
* mode; an {@code s3-dist-cp} one runs Floci's own S3DistCp. On a cluster with Hive, whose image holds Hive too, a
* {@code command-runner.jar} step running {@code hive-script}, as the AWS CLI writes a Hive step, or {@code hive}
* runs Hive.
*/
final class EmrSparkSteps {
// No source gives AWS's wording for these; they are Floci's.
static final String NOT_RUN = "Floci does not run this step: hive-script and pig-script are not in the image"
+ " steps run in.";
static final String NOT_RUN = "Floci does not run this step: pig-script is not in the image steps run in.";
static final String INTERRUPTED = "Floci stopped while the step was running.";
private static final String COMMAND_RUNNER = "command-runner.jar";
@@ -63,8 +64,19 @@ final class EmrSparkSteps {
private static final String SPARK_HADOOP_PREFIX = "spark.hadoop.";
// spark-submit gives the JVM it runs an application's main class in the Java options of this variable.
private static final String SPARK_SUBMIT_OPTS = "SPARK_SUBMIT_OPTS";
// The Release Guide's command-runner.jar tools that the EMR Serverless image does not have.
private static final Set<String> UNAVAILABLE_TOOLS = Set.of("hive-script", "pig-script");
// The Release Guide's command-runner.jar tools that the EMR Serverless images do not have.
private static final Set<String> UNAVAILABLE_TOOLS = Set.of("pig-script");
// The AWS CLI's Hive step on a release is command-runner.jar running "hive-script --run-hive-script --args"
// and the step's arguments, the ones the image's hive-script runs hive with; a step can also run hive itself.
private static final String HIVE_SCRIPT = "hive-script";
private static final String HIVE_SCRIPT_ARGS = "--args";
private static final String HIVE = "hive";
// The Hive classifications a Hive step's hive gets, each property a --hiveconf, in the order Hive reads their
// files, a later one winning: core-site, tez-site, which will "Change values in Tez's tez-site.xml file", and
// hive-site, which will "Change values in Hive's hive-site.xml"; and hive-env's exports, which will "Change
// values in the Hive environment".
private static final List<String> HIVE_CLASSIFICATIONS = List.of(CORE_SITE, "tez-site", "hive-site");
private static final String HIVE_ENV = "hive-env";
// EMR's MapReduce jars are in /usr/lib/hadoop-mapreduce, as the image's own hadoop-streaming script has it,
// which the image does not have; its streaming jar is in /usr/lib/hadoop.
private static final Map<String, String> IMAGE_JARS = Map.of(
@@ -155,6 +167,68 @@ final class EmrSparkSteps {
return null;
}
/**
* How a step runs Hive, or null for a step that does not, or whose cluster does not install Hive (see
* {@link #installsHive}), where {@code hive-script} finds no {@code hive} as EMR's does without it: a
* {@code command-runner.jar} step running {@code hive-script}, up to its {@code --args} (added at the end of one
* without), or {@code hive}, and what its {@code hive} gets after
* Floci's settings: the cluster's Hive classifications, then the step's own arguments, so that a
* {@code --hiveconf} of the step's replaces a classification's property, as it replaces a hive-site.xml one.
*/
static HiveCommand hive(EmrStep step, String applications, String configurations, ObjectMapper objectMapper) {
String jar = step.getJar();
List<String> args = step.getArgs() != null ? step.getArgs() : List.of();
if (jar == null || !named(jar, COMMAND_RUNNER) || args.isEmpty()
|| !installsHive(applications, objectMapper)) {
return null;
}
List<String> runner;
List<String> own;
if (named(args.getFirst(), HIVE_SCRIPT)) {
int split = args.indexOf(HIVE_SCRIPT_ARGS);
runner = new ArrayList<>(split < 0 ? args : args.subList(0, split));
runner.add(HIVE_SCRIPT_ARGS);
own = split < 0 ? List.of() : args.subList(split + 1, args.size());
} else if (named(args.getFirst(), HIVE)) {
runner = List.of(args.getFirst());
own = args.subList(1, args.size());
} else {
return null;
}
List<String> arguments = new ArrayList<>();
for (String classification : HIVE_CLASSIFICATIONS) {
arguments.addAll(EmrServerlessSparkRunner.hiveSettings(properties(configurations, objectMapper,
classification)));
}
arguments.addAll(own);
return new HiveCommand(List.copyOf(runner), arguments);
}
/**
* A step's Hive: {@code runner}, what runs in place of {@code hive}, and {@code arguments}, what follows Floci's
* settings.
*/
record HiveCommand(List<String> runner, List<String> arguments) {
}
/** The variables a cluster's {@code hive-env} exports, which its Hive steps get. */
static Map<String, String> hiveEnvironment(String configurations, ObjectMapper objectMapper) {
return exports(configurations, objectMapper, HIVE_ENV);
}
/**
* Whether a cluster's {@code Applications}, the JSON array RunJobFlow was given, name Hive ("A case-insensitive
* list of applications for Amazon EMR to install").
*/
static boolean installsHive(String applications, ObjectMapper objectMapper) {
for (JsonNode application : stored(applications, objectMapper)) {
if (HIVE.equalsIgnoreCase(application.path("Name").asText())) {
return true;
}
}
return false;
}
/**
* The S3 folder a step's logs go to, or null when its cluster has no {@code LogUri}: "If a value is not
* provided, logs are not created". The Management Guide's "Log locations" puts step logs at
@@ -273,22 +347,27 @@ final class EmrSparkSteps {
private static List<JsonNode> classified(String configurations, ObjectMapper objectMapper,
String classification) {
List<JsonNode> matching = new ArrayList<>();
if (configurations == null) {
return matching;
}
try {
for (JsonNode configuration : objectMapper.readTree(configurations)) {
if (classification.equals(configuration.path("Classification").asText())) {
matching.add(configuration);
}
for (JsonNode configuration : stored(configurations, objectMapper)) {
if (classification.equals(configuration.path("Classification").asText())) {
matching.add(configuration);
}
} catch (JsonProcessingException ignored) {
// RunJobFlow stored the array as it came; one that does not parse holds no properties to apply.
return matching;
}
return matching;
}
// A JSON array of a cluster's, which RunJobFlow stored as it came, or an empty one for none: one that does not
// parse holds no properties to apply and names no application.
private static JsonNode stored(String json, ObjectMapper objectMapper) {
if (json == null) {
return objectMapper.createArrayNode();
}
try {
return objectMapper.readTree(json);
} catch (JsonProcessingException ignored) {
return objectMapper.createArrayNode();
}
}
private static List<String> withoutMasterOrDeployMode(List<String> arguments) {
List<String> kept = new ArrayList<>();
int i = 0;
@@ -0,0 +1,15 @@
package io.github.hectorvent.floci.services.emr;
/**
* The images a cluster with Hive runs in, in the EMR {@code docker} runner mode: one per release, its EMR
* Serverless image with its EMR Serverless Hive image's Hive added, as an EMR cluster's nodes hold every
* application it installs. {@link EmrReleaseImages} is the Docker implementation, and a test supplies its own.
*/
public interface ReleaseImages {
/**
* The id of the image of {@code releaseLabel} made of {@code sparkImage} and {@code hiveImage}, made first when the
* Docker daemon does not have it, which may take as long as pulling the two; a failure is thrown.
*/
String image(String releaseLabel, String sparkImage, String hiveImage);
}
@@ -579,10 +579,7 @@ public class EmrServerlessJobRunService implements Resettable {
static List<String> hiveArguments(Application app, JobRun run, JobDriver.Hive hive) {
List<String> arguments = new ArrayList<>();
for (String classification : HIVE_CLASSIFICATIONS) {
classificationProperties(app, run, classification).forEach((name, value) -> {
arguments.add(EmrServerlessSparkRunner.HIVECONF_OPTION);
arguments.add(name + "=" + value);
});
arguments.addAll(EmrServerlessSparkRunner.hiveSettings(classificationProperties(app, run, classification)));
}
if (hive.getInitQueryFile() != null) {
arguments.add("-i");
@@ -66,7 +66,8 @@ import java.util.zip.GZIPOutputStream;
* step's {@code hadoop} command, and a MapReduce job its {@code spark-submit} starts, reach Floci's S3 and run
* MapReduce in local mode, with the cluster's Hadoop configuration. A Hive run starts {@code hive} in a container of
* the release's EMR Serverless Hive image instead, with Tez in local mode in Hive's JVM, S3A on Floci's S3 and the
* Glue Data Catalog client, the image's metastore, on Floci's Glue.
* Glue Data Catalog client, the image's metastore, on Floci's Glue; an EMR step's in the image of its cluster, which
* holds Spark and Hive, on its storage, with the cluster's HDFS and the cluster's own metastore.
*/
@ApplicationScoped
public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardown {
@@ -75,7 +76,7 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
private static final String SPARK_SUBMIT = "/usr/lib/spark/bin/spark-submit";
private static final String HIVE = "/usr/bin/hive";
// hive's option for a setting, and its single-dash form.
static final String HIVECONF_OPTION = "--hiveconf";
private static final String HIVECONF_OPTION = "--hiveconf";
private static final String HIVECONF_SHORT_OPTION = "-hiveconf";
private static final String SPARK_DEFAULTS_VARIABLE = "FLOCI_SPARK_DEFAULTS";
private static final String HADOOP_SITE_VARIABLE = "FLOCI_HADOOP_SITE";
@@ -242,10 +243,30 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
private static final List<SparkSetting> HIVE_SETTINGS = List.of(
new SparkSetting("tez.local.mode", "true"),
new SparkSetting("tez.am.client.am.port-range", "40000-40100"));
// On a cluster, after the HDFS settings, Hive's file system is their view of the cluster's HDFS under the viewfs
// scheme: Hive looks up the HDFS encryption zone of a path of the hdfs scheme, which only HDFS answers, as its
// shim takes that path's file system for HDFS's own, so a table Hive makes in the cluster's HDFS is at a viewfs:
// path, the folder an hdfs:// path leads to in other steps. Its metastore is the cluster's own, as "Hive records
// metastore information in a MySQL database on the primary node's file system": an embedded Derby database in
// the cluster's /mnt, whose tables DataNucleus creates on first use. A cluster's hive-site replaces them, with
// the Glue Data Catalog's client factory for one.
private static final List<SparkSetting> HIVE_CLUSTER_SETTINGS = List.of(
new SparkSetting("fs.defaultFS", "viewfs:///"),
new SparkSetting("hive.metastore.client.factory.class",
"org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClientFactory"),
new SparkSetting("javax.jdo.option.ConnectionURL",
"jdbc:derby:;databaseName=/mnt/var/lib/hive/metastore_db;create=true"),
new SparkSetting("hive.metastore.schema.verification", "false"),
new SparkSetting("datanucleus.schema.autoCreateAll", "true"));
// Hive logs to a file in the folder EMR Serverless names in LOGS_DIR, its HIVE_LOG, apart from the driver's standard
// output and error.
private static final List<String> HIVE_ENVIRONMENT = List.of("LOGS_DIR=/tmp/floci-hive-logs");
private static final String HIVE_SCRATCH_VARIABLE = "FLOCI_HIVE_SCRATCH";
/**
* Where an EMR cluster's image with Hive keeps its Hive image's Hadoop configuration, which puts Tez on the class
* path, apart from the one its other steps' Hadoop reads; Hive runs with it where an image has it.
*/
public static final String HIVE_HADOOP_CONF = "/etc/hadoop/conf.hive";
private static final String HIVE_SCRATCHDIR = "hive.exec.scratchdir";
// The user every EMR Serverless image runs as: a custom one sets "the USER back to hadoop:hadoop".
private static final String IMAGE_USER = "hadoop";
@@ -256,7 +277,8 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
// file system (LocalClient), a copy that silently does nothing where the image's user cannot create that path, at
// the root of the container for one; so the container starts as root, makes that path its user's, then runs hive
// as that user, in that user's home, as a Spark image's working directory is: Tez in local mode puts each task's
// files in the working directory, and the Hive image names none, which leaves the root.
// files in the working directory, and the Hive image names none, which leaves the root. In an EMR cluster's image
// with Hive, Hive reads its own Hadoop configuration (HIVE_HADOOP_CONF).
private static final String HIVE_WRAPPER = String.join("\n",
"host=$(hostname)",
"export CLIENT_AM_BIND_ADDRESS=0.0.0.0 TASK_AM_BIND_ADDRESS=0.0.0.0 SHUFFLE_BIND_ADDRESS=0.0.0.0",
@@ -265,6 +287,7 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
" mkdir -p \"$" + HIVE_SCRATCH_VARIABLE + "\" && chown " + IMAGE_USER + ":" + IMAGE_USER + " \"$"
+ HIVE_SCRATCH_VARIABLE + "\" || exit",
"fi",
"if [ -d " + HIVE_HADOOP_CONF + " ]; then export HADOOP_CONF_DIR=" + HIVE_HADOOP_CONF + "; fi",
"export HOME=~" + IMAGE_USER,
"cd \"$HOME\" || exit",
// The image's user has no other group, as Docker starts it.
@@ -344,8 +367,10 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
// bash -c's script gets "floci" as its $0, and what runs after it as its arguments, "$@".
if (job.engine() == Engine.HIVE) {
List<String> hive = hiveArguments(job, endpoint);
List<String> entrypoint = new ArrayList<>(List.of("/bin/bash", "-c", HIVE_WRAPPER, "floci"));
entrypoint.addAll(job.command() != null ? job.command() : List.of(HIVE));
container.withUser("root")
.withEntrypoint(List.of("/bin/bash", "-c", HIVE_WRAPPER, "floci", HIVE))
.withEntrypoint(entrypoint)
.withCmd(hive)
.withEnv(HIVE_ENVIRONMENT);
String scratch = hiveScratchMirror(hive);
@@ -367,8 +392,11 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
}
if (job.storage() != null) {
container.withNamedVolume(job.storage().home(), "/home/hadoop")
.withNamedVolume(job.storage().mnt(), "/mnt")
.withEnv(HADOOP_SITE_VARIABLE, hadoopSite(job, endpoint))
.withNamedVolume(job.storage().mnt(), "/mnt");
}
// Hive's settings reach it as --hiveconf settings, so only a Spark job's container sets up Hadoop.
if (job.storage() != null && job.engine() == Engine.SPARK) {
container.withEnv(HADOOP_SITE_VARIABLE, hadoopSite(job, endpoint))
.withEnv(MAPRED_SITE_VARIABLE, mapredSite(job));
if (!job.hadoopLog4j().isEmpty()) {
container.withEnv(HADOOP_LOG4J_VARIABLE, hadoopLog4jFile(job));
@@ -533,7 +561,7 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
}
/** The image a release's runs on {@code engine} use, as the other {@code image} says, Hive's for Hive. */
static String image(String imageTemplate, String releaseLabel, Engine engine) {
public static String image(String imageTemplate, String releaseLabel, Engine engine) {
String template = imageTemplate != null ? imageTemplate
: engine == Engine.HIVE ? HIVE_DEFAULT_IMAGE
: releaseLabel.startsWith("emr-spark-") ? SPARK_RUNTIME_DEFAULT_IMAGE : DEFAULT_IMAGE;
@@ -701,21 +729,36 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
}
/**
* {@code hive}'s arguments: Floci's S3 and Glue, as a Spark run gets them, and Tez in local mode, each a
* {@code --hiveconf}, which a later one replaces, then the run's own arguments.
* {@code hive}'s arguments: Floci's S3 and Glue, as a Spark run gets them, Tez in local mode, and on a cluster its
* HDFS and metastore, each a {@code --hiveconf}, which a later one replaces, then the run's own arguments.
*/
static List<String> hiveArguments(Job job, String flociEndpoint) {
List<SparkSetting> settings = new ArrayList<>(hadoopSettings(job, flociEndpoint));
settings.addAll(HIVE_SETTINGS);
if (job.storage() != null) {
settings.addAll(HDFS_SETTINGS);
settings.addAll(HIVE_CLUSTER_SETTINGS);
}
List<String> arguments = new ArrayList<>();
for (SparkSetting setting : settings) {
arguments.add(HIVECONF_OPTION);
arguments.add(setting.key() + "=" + setting.value());
addHiveSetting(arguments, setting.key(), setting.value());
}
arguments.addAll(job.application());
return arguments;
}
/** Each of {@code properties} as {@code hive}'s {@code --hiveconf name=value}, in their order. */
public static List<String> hiveSettings(Map<String, String> properties) {
List<String> arguments = new ArrayList<>();
properties.forEach((name, value) -> addHiveSetting(arguments, name, value));
return arguments;
}
private static void addHiveSetting(List<String> arguments, String name, String value) {
arguments.add(HIVECONF_OPTION);
arguments.add(name + "=" + value);
}
/**
* The local folder Tez in local mode needs for a Hive session's staging folder, or null when there is none to make:
* where the path of {@code hive}'s scratch folder, the last {@code hive.exec.scratchdir} its arguments set, leads
@@ -66,7 +66,8 @@ public interface SparkJobRunner {
* (its settings, then its query files and parameters); or {@code command}, when not
* null, what the container runs in place of {@code spark-submit}, where a {@code spark-submit} it starts
* gets Floci's settings and the {@code spark-defaults} as defaults (its {@code application} is then
* empty); how long it may run
* empty), or, for a Hive run, what runs in place of {@code hive}, followed by Floci's settings and the
* {@code application} (an EMR step's {@code hive-script ... --args}); how long it may run
* ({@link Duration#ZERO} for no limit); the S3 folder its driver's {@code stdout.gz} and
* {@code stderr.gz} go to once it ends, ending in a slash (null for none); where in CloudWatch Logs
* its driver's output goes while it runs (null for nowhere but Floci's log); the environment variables
@@ -88,6 +89,13 @@ public interface SparkJobRunner {
List<String> archives, Storage storage, Map<String, String> coreSite,
Map<String, String> sparkLog4j2, Map<String, String> mapredSite, Map<String, String> hadoopLog4j,
Map<String, String> hadoopEnvironment) {
/** This job, run in {@code image}. */
public Job inImage(String image) {
return new Job(service, runId, accountId, region, releaseLabel, engine, image, customImage, dockerNetwork,
executionRole, sparkDefaults, application, command, timeout, logFolder, cloudWatchLogs, environment,
archives, storage, coreSite, sparkLog4j2, mapredSite, hadoopLog4j, hadoopEnvironment);
}
}
/**