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

@@ -0,0 +1,226 @@
package io.github.hectorvent.floci.services.emr;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.testing.AwsTestClients;
import io.github.hectorvent.floci.testing.ContainerDataPlaneProfile;
import io.github.hectorvent.floci.testing.DockerAvailability;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.github.hectorvent.floci.testing.S3TestClients;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.glue.GlueClient;
import software.amazon.awssdk.services.glue.model.Table;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.S3Object;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.zip.GZIPInputStream;
import static io.github.hectorvent.floci.testing.EmrRequests.awaitStep;
import static io.github.hectorvent.floci.testing.EmrRequests.emr;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
/**
* EMR Hive steps through Floci's Docker runner for real: on a cluster with Hive in the {@code docker} runner mode, the
* AWS CLI's Hive step runs {@code hive-script} in a container of the cluster's image, the release's EMR Serverless
* image with its EMR Serverless Hive image's Hive, which Floci makes once, on the cluster's storage, its HDFS and
* metastore, and on Floci's S3. The cached {@code emr-7.5.0} images keep a local run from pulling; CI pulls the Hive
* one (2.7 GB) and the Spark one (3.5 GB) the first time.
*/
@QuarkusTest
@TestProfile(ContainerDataPlaneProfile.class)
class EmrHiveStepsDockerIntegrationTest {
private static final ObjectMapper JSON = new ObjectMapper();
private static final String REGION = "us-east-1";
private static final String ROWS = "a,1\nb,2\nc,3\n";
private static final String HIVE_AND_SPARK = "[{\"Name\":\"Hadoop\"},{\"Name\":\"Hive\"},{\"Name\":\"Spark\"}]";
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
private S3Client s3;
private String bucket;
private String clusterId;
@BeforeAll
static void configure() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@BeforeEach
void putInputs() throws InterruptedException {
assumeTrue(DockerAvailability.isAvailable(), "Docker daemon must be available for EMR's Hive steps");
s3 = AwsTestClients.create(S3Client.builder().forcePathStyle(true), "000000000000", Region.US_EAST_1);
cleanup.register(s3::close);
bucket = "emr-hive-" + UUID.randomUUID().toString().substring(0, 8);
s3.createBucket(request -> request.bucket(bucket));
cleanup.register(() -> S3TestClients.deleteBucket(s3, bucket));
put("data/rows/rows.csv", ROWS);
}
@Test
void hiveStepsKeepTheirTablesInTheClustersMetastoreAndHdfsForTheStepsAfterThem() {
startCluster(HIVE_AND_SPARK, "[]", null);
put("queries/load.q", """
create external table kv (k string, v int)
row format delimited fields terminated by ',' location '${INPUT}';
create table scaled as select k, v * 10 as v from kv;
""");
put("queries/report.q", """
insert overwrite directory '${OUTPUT}' row format delimited fields terminated by ','
select k, v from scaled order by k;
select k, v from scaled order by k;
""");
assertEquals("COMPLETED", hiveStep("-f", s3Uri("queries/load.q"), "-d", "INPUT=" + s3Uri("data/rows/")));
// The table the first step made is in the cluster's metastore for the second.
String report = addStep("command-runner.jar", "hive-script", "--run-hive-script", "--args",
"-f", s3Uri("queries/report.q"), "-d", "OUTPUT=" + s3Uri("out/report/"));
assertEquals("COMPLETED", state(report));
assertEquals("a,10\nb,20\nc,30\n", objects("out/report/"));
assertTrue(stepLog(report, "stdout.gz").contains("a\t10\nb\t20\nc\t30\n"));
// Its data is in the cluster's HDFS, which a step in the Spark image reads as hdfs://.
String cat = addStep("command-runner.jar", "hadoop", "fs", "-cat", "hdfs:///user/hive/warehouse/scaled/*");
assertEquals("COMPLETED", state(cat));
assertEquals("a\u000110\nb\u000120\nc\u000130\n", stepLog(cat, "stdout.gz"));
// The metastore is the cluster's own, a database in its /mnt.
assertEquals("COMPLETED", state(addStep("command-runner.jar", "test", "-d", "/mnt/var/lib/hive/metastore_db")));
}
@Test
void aClustersHiveSiteForTheGlueDataCatalogKeepsItsHiveStepsTablesInFlocisGlue() {
String database = bucket.replace('-', '_');
GlueClient glue = AwsTestClients.create(GlueClient.builder(), "000000000000", Region.US_EAST_1);
cleanup.register(glue::close);
cleanup.register(() -> glue.deleteDatabase(request -> request.name(database)));
// The Release Guide's hive-site for the Glue Data Catalog.
startCluster(HIVE_AND_SPARK, """
[{"Classification": "hive-site", "Properties": {"hive.metastore.client.factory.class":
"com.amazonaws.glue.catalog.metastore.AWSGlueDataCatalogHiveClientFactory"}}]""", null);
assertEquals("COMPLETED", hiveStep("-e", "create database " + database + " location '"
+ s3Uri("warehouse/") + "'; create external table " + database + ".kv (k string, v int) row format"
+ " delimited fields terminated by ',' location '" + s3Uri("data/rows/") + "';"));
assertEquals(List.of("kv"), glue.getTables(request -> request.databaseName(database)).tableList()
.stream().map(Table::name).toList());
}
@Test
void aHiveStepOnAClusterWithoutHiveFailsAsEmrsHiveScriptDoes() {
startCluster("[{\"Name\":\"Hadoop\"},{\"Name\":\"Spark\"}]", "[]", null);
String query = addStep("command-runner.jar", "hive-script", "--run-hive-script", "--args", "-e", "select 1");
assertEquals("FAILED", state(query));
assertTrue(stepLog(query, "stdout.gz").contains("Hive isn't installed."));
}
@Test
void whatABootstrapInstalledIsThereForTheClustersHiveAndOtherSteps() {
// One action, as the Management Guide's "Run custom bootstrap actions" has them: a file in the hadoop user's
// home, and a command installed with sudo.
put("bootstrap/install.sh", String.join("\n", "#!/bin/bash",
"echo bootstrapped > /home/hadoop/marker.txt",
"printf '%s\\n' '#!/bin/bash' 'echo installed' | sudo tee /usr/local/bin/floci-probe > /dev/null",
"sudo chmod +x /usr/local/bin/floci-probe", ""));
startCluster(HIVE_AND_SPARK, "[]", s3Uri("bootstrap/install.sh"));
String query = addStep("command-runner.jar", "hive-script", "--run-hive-script", "--args",
"-e", "!cat /home/hadoop/marker.txt; !/usr/local/bin/floci-probe;");
assertEquals("COMPLETED", state(query));
assertTrue(stepLog(query, "stdout.gz").contains("bootstrapped\ninstalled\n"));
String probe = addStep("command-runner.jar", "floci-probe");
assertEquals("COMPLETED", state(probe));
assertEquals("installed\n", stepLog(probe, "stdout.gz"));
}
/** A cluster with {@code applications}, {@code configurations} and a bootstrap action's script, if not null. */
private void startCluster(String applications, String configurations, String bootstrapScript) {
ObjectNode request = JSON.createObjectNode().put("Name", "hive-steps").put("ReleaseLabel", "emr-7.5.0")
.put("LogUri", s3Uri("logs/"));
try {
request.set("Applications", JSON.readTree(applications));
request.set("Configurations", JSON.readTree(configurations));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
if (bootstrapScript != null) {
ArrayNode actions = request.putArray("BootstrapActions");
actions.addObject().put("Name", "marker").putObject("ScriptBootstrapAction").put("Path", bootstrapScript);
}
request.putObject("Instances").put("KeepJobFlowAliveWhenNoSteps", true).putArray("InstanceGroups")
.addObject().put("Name", "primary").put("InstanceRole", "MASTER").put("InstanceType", "m5.xlarge")
.put("InstanceCount", 1);
clusterId = emr("RunJobFlow", request.toString()).then().statusCode(200).extract().jsonPath()
.getString("JobFlowId");
cleanup.register(() -> emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + clusterId + "\"]}")
.then().statusCode(200));
}
/** Runs the AWS CLI's Hive step with {@code args} and returns the state it ended in. */
private String hiveStep(String... args) {
List<String> command = new ArrayList<>(List.of("hive-script", "--run-hive-script", "--args"));
command.addAll(List.of(args));
return state(addStep("command-runner.jar", command.toArray(String[]::new)));
}
/** Adds one step to the cluster and returns its id. */
private String addStep(String jar, String... args) {
ObjectNode request = JSON.createObjectNode().put("JobFlowId", clusterId);
ObjectNode step = request.putArray("Steps").addObject().put("Name", args[0]).put("ActionOnFailure", "CONTINUE");
ObjectNode hadoopJarStep = step.putObject("HadoopJarStep").put("Jar", jar);
List.of(args).forEach(hadoopJarStep.putArray("Args")::add);
return emr("AddJobFlowSteps", request.toString()).then().statusCode(200).extract().jsonPath()
.getString("StepIds[0]");
}
private String state(String stepId) {
Response ended = awaitStep(clusterId, stepId);
return ended.jsonPath().getString("Step.Status.State");
}
/** A log of the step's, in the step log folder of the Management Guide's "Log locations". */
private String stepLog(String stepId, String name) {
String key = "logs/" + clusterId + "/steps/" + stepId + "/" + name;
try (GZIPInputStream in = new GZIPInputStream(s3.getObject(request -> request.bucket(bucket).key(key)))) {
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private void put(String key, String text) {
s3.putObject(request -> request.bucket(bucket).key(key), RequestBody.fromString(text));
}
private String s3Uri(String key) {
return "s3://" + bucket + "/" + key;
}
/** The objects under {@code prefix}, in key order, one after the other. */
private String objects(String prefix) {
StringBuilder text = new StringBuilder();
for (S3Object object : s3.listObjectsV2(request -> request.bucket(bucket).prefix(prefix)).contents()) {
text.append(s3.getObjectAsBytes(request -> request.bucket(bucket).key(object.key())).asUtf8String());
}
return text.toString();
}
}
@@ -0,0 +1,377 @@
package io.github.hectorvent.floci.services.emr;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CopyArchiveFromContainerCmd;
import com.github.dockerjava.api.command.CopyArchiveToContainerCmd;
import com.github.dockerjava.api.command.CreateContainerCmd;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.command.InfoCmd;
import com.github.dockerjava.api.command.InspectImageCmd;
import com.github.dockerjava.api.command.InspectImageResponse;
import com.github.dockerjava.api.command.RemoveContainerCmd;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.ContainerConfig;
import com.github.dockerjava.api.model.Info;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.EmulatorConfig.EcsServiceConfig.ImagePullBehavior;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
import io.github.hectorvent.floci.core.common.docker.RetryingTarCopier;
import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService;
import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService.LaunchImage;
import io.github.hectorvent.floci.testing.ThreadStates;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.archivers.tar.TarConstants;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** The image a release's clusters with Hive run in, made of its EMR Serverless and EMR Serverless Hive images. */
class EmrReleaseImagesTest {
private static final String SPARK = "public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest";
private static final String HIVE = "public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest";
private final EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
private final DockerClient docker = mock(DockerClient.class);
private final ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
private final ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
private final ImageCacheService imageCache = mock(ImageCacheService.class);
private final EmrReleaseImages images = new EmrReleaseImages(lifecycle, containerBuilder, imageCache, config);
@Test
void aCopyPutsItsSourceUnderItsNameInItsFolderAndTezsGoodiesLinksLeadToTheHiveImagesCopy() throws IOException {
byte[] tez = tar(
directory("tez/"),
symlink("tez/tez-emr-serverless.jar",
"/usr/share/aws/emr/serverless-goodies/lib/tez-emr-serverless.jar"),
symlink("tez/conf", "/etc/tez/conf"),
file("tez/tez-api.jar", "api"),
hardLink("tez/tez-api-copy.jar", "tez/tez-api.jar"));
byte[] goodies = tar(directory("lib/"), file("lib/goodies.jar", "hive's"),
symlink("lib/latest.jar", "goodies.jar"));
byte[] conf = tar(directory("conf/"), file("conf/hadoop-env.sh", "TEZ"),
hardLink("conf/env", "conf/hadoop-env.sh"));
assertEquals(List.of("tez/ dir", "tez/tez-emr-serverless.jar -> "
+ "/usr/share/aws/emr/serverless-goodies-hive/lib/tez-emr-serverless.jar",
"tez/conf -> /etc/tez/conf", "tez/tez-api.jar = api", "tez/tez-api-copy.jar => tez/tez-api.jar"),
entries(copied(tez, new EmrReleaseImages.Copy("/usr/lib/tez", "/usr/lib"))));
// The Hive image's goodies go to a folder of their own, which the EMR Serverless image does not have.
assertEquals(List.of("serverless-goodies-hive/ dir", "serverless-goodies-hive/lib/ dir",
"serverless-goodies-hive/lib/goodies.jar = hive's",
"serverless-goodies-hive/lib/latest.jar -> goodies.jar"),
entries(copied(goodies, new EmrReleaseImages.Copy("/usr/share/aws/emr/serverless-goodies/lib",
"/usr/share/aws/emr", "serverless-goodies-hive/lib"))));
assertEquals(List.of("conf.hive/ dir", "conf.hive/hadoop-env.sh = TEZ",
"conf.hive/env => conf.hive/hadoop-env.sh"),
entries(copied(conf, EmrReleaseImages.Copy.to("/etc/hadoop/conf", "/etc/hadoop/conf.hive"))));
}
@Test
void theHiveImagesHadoopConfigurationGoesWhereHiveRunsWithIt() {
assertTrue(EmrReleaseImages.COPIES.contains(new EmrReleaseImages.Copy("/etc/hadoop/conf", "/etc/hadoop",
"conf.hive")));
}
@Test
void anImageThatIsMissingIsMadeInAContainerOfTheSparkImageNeverStartedThenCommitted() {
when(lifecycle.getDockerClient()).thenReturn(docker);
// The two are pulled as a container's image would be, from the image-registry-base it names.
when(containerBuilder.resolveImage(anyString()))
.thenAnswer(invocation -> "mirror/" + invocation.getArgument(0));
resolves("mirror/" + SPARK, "sha256:spark");
resolves("mirror/" + HIVE, "sha256:hive");
String repository = ContainerStorageHelper.dockerName(config, "emr-release");
InspectImageCmd missing = mock(InspectImageCmd.class);
when(missing.exec()).thenThrow(new NotFoundException("missing"));
when(docker.inspectImageCmd(argThat((String image) -> image.startsWith(repository + ":"))))
.thenReturn(missing);
InspectImageCmd spark = mock(InspectImageCmd.class);
InspectImageResponse sparkImage = mock(InspectImageResponse.class);
ContainerConfig sparkConfig = mock(ContainerConfig.class);
when(sparkConfig.getUser()).thenReturn("hadoop:hadoop");
when(sparkImage.getConfig()).thenReturn(sparkConfig);
when(spark.exec()).thenReturn(sparkImage);
when(docker.inspectImageCmd("sha256:spark")).thenReturn(spark);
container("sha256:spark", "target");
container("sha256:hive", "source");
List<String> copied = new ArrayList<>();
when(docker.copyArchiveFromContainerCmd(eq("source"), anyString())).thenAnswer(invocation -> {
copied.add(invocation.getArgument(1));
CopyArchiveFromContainerCmd from = mock(CopyArchiveFromContainerCmd.class);
when(from.exec()).thenAnswer(read -> new ByteArrayInputStream(new byte[0]));
return from;
});
when(docker.copyArchiveToContainerCmd("target"))
.thenReturn(mock(CopyArchiveToContainerCmd.class, RETURNS_SELF));
when(lifecycle.commit(eq("target"), eq(repository), anyString(), eq("hadoop:hadoop"), any()))
.thenReturn("sha256:made");
when(docker.removeContainerCmd(anyString())).thenReturn(mock(RemoveContainerCmd.class, RETURNS_SELF));
assertEquals("sha256:made", images.image("emr-7.5.0", SPARK, HIVE));
assertEquals(EmrReleaseImages.COPIES.stream().map(EmrReleaseImages.Copy::from).toList(), copied);
// Named after the release and what it is made of, and labelled as Floci's EMR release image.
verify(lifecycle).commit(eq("target"), eq(repository),
argThat(tag -> tag.matches("emr-7\\.5\\.0-[0-9a-f]{12}")), eq("hadoop:hadoop"),
argThat((Map<String, String> labels) ->
"emr-release".equals(labels.get(ContainerStorageHelper.COMPONENT_LABEL))));
verify(docker).removeContainerCmd("target");
verify(docker).removeContainerCmd("source");
}
@Test
void aSecondThreadAskingWhileTheImageIsMadeWaitsThenFindsItThere() throws InterruptedException {
when(lifecycle.getDockerClient()).thenReturn(docker);
when(containerBuilder.resolveImage(anyString())).thenAnswer(invocation -> invocation.getArgument(0));
resolvesEachToItself();
String repository = ContainerStorageHelper.dockerName(config, "emr-release");
AtomicBoolean made = new AtomicBoolean();
when(docker.inspectImageCmd(anyString())).thenAnswer(invocation -> {
String image = invocation.getArgument(0);
InspectImageCmd inspect = mock(InspectImageCmd.class);
InspectImageResponse response = mock(InspectImageResponse.class, RETURNS_DEEP_STUBS);
when(response.getId()).thenReturn("sha256:made");
if (image.startsWith(repository + ":") && !made.get()) {
when(inspect.exec()).thenThrow(new NotFoundException("missing"));
} else {
when(inspect.exec()).thenReturn(response);
}
return inspect;
});
CreateContainerCmd create = mock(CreateContainerCmd.class, RETURNS_SELF);
when(create.exec()).thenReturn(mock(CreateContainerResponse.class));
when(docker.createContainerCmd(anyString())).thenReturn(create);
when(docker.copyArchiveFromContainerCmd(any(), anyString())).thenAnswer(invocation -> {
CopyArchiveFromContainerCmd from = mock(CopyArchiveFromContainerCmd.class);
when(from.exec()).thenAnswer(read -> new ByteArrayInputStream(new byte[0]));
return from;
});
when(docker.copyArchiveToContainerCmd(any())).thenReturn(mock(CopyArchiveToContainerCmd.class, RETURNS_SELF));
when(docker.removeContainerCmd(any())).thenReturn(mock(RemoveContainerCmd.class, RETURNS_SELF));
CountDownLatch committing = new CountDownLatch(1);
CountDownLatch committed = new CountDownLatch(1);
when(lifecycle.commit(any(), anyString(), anyString(), any(), any())).thenAnswer(invocation -> {
committing.countDown();
assertTrue(committed.await(10, TimeUnit.SECONDS));
made.set(true);
return "sha256:made";
});
Thread first = Thread.ofPlatform().start(() -> images.image("emr-7.5.0", SPARK, HIVE));
assertTrue(committing.await(10, TimeUnit.SECONDS));
AtomicReference<String> found = new AtomicReference<>();
Thread second = Thread.ofPlatform().start(() -> found.set(images.image("emr-7.5.0", SPARK, HIVE)));
ThreadStates.awaitBlockedOrDone(second);
committed.countDown();
first.join(10_000);
second.join(10_000);
// One container of each image, one commit: the second found the image the first made.
verify(docker, times(2)).createContainerCmd(anyString());
verify(lifecycle, times(1)).commit(any(), anyString(), anyString(), any(), any());
assertEquals("sha256:made", found.get());
}
@Test
void anImageThatIsThereIsUsedAsItIs() {
when(lifecycle.getDockerClient()).thenReturn(docker);
when(containerBuilder.resolveImage(anyString())).thenAnswer(invocation -> invocation.getArgument(0));
InspectImageCmd there = mock(InspectImageCmd.class);
InspectImageResponse made = mock(InspectImageResponse.class);
when(made.getId()).thenReturn("sha256:made");
when(there.exec()).thenReturn(made);
when(docker.inspectImageCmd(anyString())).thenReturn(there);
resolvesEachToItself();
assertEquals("sha256:made", images.image("emr-7.5.0", SPARK, HIVE));
verify(docker, never()).createContainerCmd(anyString());
verify(lifecycle, never()).commit(any(), anyString(), anyString(), any(), any());
}
@Test
void anImageIsNamedAfterTheIdsOfTheImagesItIsMadeOfSoANewerPullMakesAnother() {
when(lifecycle.getDockerClient()).thenReturn(docker);
when(containerBuilder.resolveImage(anyString())).thenAnswer(invocation -> invocation.getArgument(0));
resolves(SPARK, "sha256:spark");
// The Hive image's name leads to another id once a newer image is pulled under it.
when(imageCache.resolveForLaunch(HIVE, ImagePullBehavior.PREFER_CACHED, null)).thenReturn(
new LaunchImage("sha256:hive", null), new LaunchImage("sha256:hive", null),
new LaunchImage("sha256:newer-hive", null));
List<String> asked = new ArrayList<>();
when(docker.inspectImageCmd(anyString())).thenAnswer(invocation -> {
asked.add(invocation.getArgument(0));
InspectImageCmd there = mock(InspectImageCmd.class);
when(there.exec()).thenReturn(mock(InspectImageResponse.class));
return there;
});
images.image("emr-7.5.0", SPARK, HIVE);
images.image("emr-7.5.0", SPARK, HIVE);
images.image("emr-7.5.0", SPARK, HIVE);
assertEquals(asked.get(0), asked.get(1));
assertNotEquals(asked.get(0), asked.get(2));
}
@Test
void aNewerPullOfAnImageItIsMadeOfMakesAnotherThroughTheImageCache() {
// A daemon whose local tags a test moves, as a docker pull would, keeping the image a tag leaves, behind a real
// image cache.
Map<String, String> tags = new HashMap<>(Map.of(SPARK, "sha256:spark", HIVE, "sha256:hive"));
Set<String> images = new HashSet<>(tags.values());
String repository = ContainerStorageHelper.dockerName(config, "emr-release");
List<String> asked = new ArrayList<>();
DockerClient daemon = mock(DockerClient.class);
InfoCmd info = mock(InfoCmd.class);
when(info.exec()).thenReturn(new Info().withOsType("linux").withArchitecture("amd64"));
when(daemon.infoCmd()).thenReturn(info);
when(daemon.inspectImageCmd(anyString())).thenAnswer(invocation -> {
String reference = invocation.getArgument(0);
InspectImageCmd inspect = mock(InspectImageCmd.class);
if (reference.startsWith(repository + ":")) {
// The image made of them, there whatever its name.
asked.add(reference);
when(inspect.exec()).thenReturn(new InspectImageResponse().withId("sha256:made"));
} else if (tags.containsKey(reference) || images.contains(reference)) {
when(inspect.exec()).thenReturn(new InspectImageResponse()
.withId(tags.getOrDefault(reference, reference)).withOs("linux").withArch("amd64")
.withRepoDigests(List.of()));
} else {
when(inspect.exec()).thenThrow(new NotFoundException("No such image: " + reference));
}
return inspect;
});
EmulatorConfig cacheConfig = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(cacheConfig.docker().registryCredentials()).thenReturn(List.of());
when(cacheConfig.docker().imagePullTimeoutSeconds()).thenReturn(300);
when(lifecycle.getDockerClient()).thenReturn(daemon);
when(containerBuilder.resolveImage(anyString())).thenAnswer(invocation -> invocation.getArgument(0));
EmrReleaseImages cached = new EmrReleaseImages(lifecycle, containerBuilder,
new ImageCacheService(daemon, cacheConfig), config);
cached.image("emr-7.5.0", SPARK, HIVE);
tags.put(HIVE, "sha256:newer-hive");
images.add("sha256:newer-hive");
cached.image("emr-7.5.0", SPARK, HIVE);
assertNotEquals(asked.get(0), asked.get(1));
}
// The two images are resolved as a launch would, their names read again each time, pulled only when missing.
private void resolves(String image, String id) {
when(imageCache.resolveForLaunch(image, ImagePullBehavior.PREFER_CACHED, null))
.thenReturn(new LaunchImage(id, null));
}
private void resolvesEachToItself() {
when(imageCache.resolveForLaunch(anyString(), eq(ImagePullBehavior.PREFER_CACHED), isNull()))
.thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null));
}
private void container(String image, String id) {
CreateContainerCmd create = mock(CreateContainerCmd.class, RETURNS_SELF);
CreateContainerResponse created = mock(CreateContainerResponse.class);
when(created.getId()).thenReturn(id);
when(create.exec()).thenReturn(created);
when(docker.createContainerCmd(image)).thenReturn(create);
}
private static byte[] copied(byte[] archive, EmrReleaseImages.Copy copy) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
EmrReleaseImages.copy(new ByteArrayInputStream(archive), out, copy);
return out.toByteArray();
}
// Each entry as one line: a folder, a file and its text, a symbolic link and where it leads, or a hard link.
private static List<String> entries(byte[] archive) throws IOException {
List<String> entries = new ArrayList<>();
try (TarArchiveInputStream in = new TarArchiveInputStream(new ByteArrayInputStream(archive))) {
TarArchiveEntry entry;
while ((entry = in.getNextEntry()) != null) {
if (entry.isDirectory()) {
entries.add(entry.getName() + " dir");
} else if (entry.isSymbolicLink()) {
entries.add(entry.getName() + " -> " + entry.getLinkName());
} else if (entry.isLink()) {
entries.add(entry.getName() + " => " + entry.getLinkName());
} else {
entries.add(entry.getName() + " = " + new String(in.readAllBytes(), StandardCharsets.UTF_8));
}
}
}
return entries;
}
private static byte[] tar(Entry... entries) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (TarArchiveOutputStream tar = RetryingTarCopier.newTarStream(out)) {
for (Entry entry : entries) {
tar.putArchiveEntry(entry.header());
tar.write(entry.content());
tar.closeArchiveEntry();
}
}
return out.toByteArray();
}
private static Entry directory(String name) {
return new Entry(new TarArchiveEntry(name), new byte[0]);
}
private static Entry file(String name, String text) {
byte[] content = text.getBytes(StandardCharsets.UTF_8);
TarArchiveEntry header = new TarArchiveEntry(name);
header.setSize(content.length);
return new Entry(header, content);
}
private static Entry symlink(String name, String target) {
TarArchiveEntry header = new TarArchiveEntry(name, TarConstants.LF_SYMLINK);
header.setLinkName(target);
return new Entry(header, new byte[0]);
}
private static Entry hardLink(String name, String target) {
TarArchiveEntry header = new TarArchiveEntry(name, TarConstants.LF_LINK);
header.setLinkName(target);
return new Entry(header, new byte[0]);
}
private record Entry(TarArchiveEntry header, byte[] content) {
}
}
@@ -317,9 +317,9 @@ class EmrServiceContainerStepsTest {
@Test
void aStepFlociDoesNotRunFailsWithoutRunning() {
EmrStep hive = sparkStep("query", "CONTINUE");
hive.setArgs(List.of("hive-script", "--run-hive-script", "--args", "-f", "s3://bucket/query.q"));
EmrCluster cluster = service.runJobFlow(cluster("hive", true, hive), REGION);
EmrStep pig = sparkStep("query", "CONTINUE");
pig.setArgs(List.of("pig-script", "--run-pig-script", "--args", "-f", "s3://bucket/query.pig"));
EmrCluster cluster = service.runJobFlow(cluster("pig", true, pig), REGION);
fixture.runStepThread();
@@ -545,7 +545,8 @@ class EmrServiceContainerStepsTest {
new EmrService(new InMemoryStorageFactory(ACCOUNT), config, regionResolver,
new EmrEventPublisher(mock(EventBridgeService.class), new ObjectMapper(), regionResolver),
sparkRunner, bootstrapRunner, clusterStorage, mock(IamService.class)).shutdown();
sparkRunner, bootstrapRunner, clusterStorage, mock(EmrReleaseImages.class), mock(IamService.class))
.shutdown();
verify(sparkRunner, times(reconcile ? 1 : 0)).removeLeftoverDrivers("emr");
verify(bootstrapRunner, times(reconcile ? 1 : 0)).removeImages(Set.of());
@@ -587,6 +588,8 @@ class EmrServiceContainerStepsTest {
bootstrapping.runStepThread();
assertEquals(IMAGE, runner.jobs.get(0).imageTemplate());
// A cluster without Hive runs in the release's EMR Serverless image, which none makes.
assertEquals(List.of(), bootstrapping.releaseImages.asked);
assertEquals("COMPLETED", bootstrapping.service.describeStep(cluster.getId(), stepId).getState());
assertEquals(List.of("STARTING", "PENDING report", "RUNNING report", "COMPLETED report", "WAITING"),
bootstrapping.states());
@@ -605,6 +608,126 @@ class EmrServiceContainerStepsTest {
assertNull(runner.jobs.get(0).imageTemplate());
}
@Test
void aHiveStepOnAClusterWithHiveRunsHiveScriptsHiveOnTheClustersStorage() {
EmrStep query = hiveStep("report", "-f", "s3://bucket/queries/report.q", "-d", "INPUT=s3://bucket/in/");
EmrCluster requested = cluster("hive", true, query);
requested.setApplications("[{\"Name\": \"Hive\"}, {\"Name\": \"Spark\"}]");
requested.setLogUri("s3://logs/emr/");
requested.setConfigurations("""
[{"Classification": "hive-site", "Properties": {"hive.exec.reducers.max": "8"}},
{"Classification": "hive-env", "Configurations": [
{"Classification": "export", "Properties": {"HADOOP_HEAPSIZE": "2048"}}]},
{"Classification": "spark-defaults", "Properties": {"spark.executor.cores": "2"}},
{"Classification": "spark-env", "Configurations": [
{"Classification": "export", "Properties": {"PYSPARK_PYTHON": "/usr/bin/python3.11"}}]}]""");
EmrCluster cluster = service.runJobFlow(requested, REGION);
String stepId = cluster.getSteps().get(0).getId();
fixture.runStepThread();
SparkJobRunner.Job job = runner.jobs.get(0);
assertEquals(SparkJobRunner.Engine.HIVE, job.engine());
assertEquals(stepId, job.runId());
// The release's EMR Serverless image with its EMR Serverless Hive image's Hive, made on the step's thread.
assertEquals(List.of(List.of("emr-7.5.0", "public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest",
"public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest")), fixture.releaseImages.asked);
assertEquals(EmrServiceFixture.RecordingReleaseImages.IMAGE, job.imageTemplate());
assertNull(job.customImage());
assertEquals(List.of("hive-script", "--run-hive-script", "--args"), job.command());
assertEquals(List.of("--hiveconf", "hive.exec.reducers.max=8", "-f", "s3://bucket/queries/report.q", "-d",
"INPUT=s3://bucket/in/"), job.application());
// Its cluster's Spark settings are not Hive's.
assertEquals(Map.of(), job.sparkDefaults());
assertEquals(Map.of("HADOOP_HEAPSIZE", "2048"), job.environment());
assertEquals(new SparkJobRunner.Storage(cluster.getId() + "-home", cluster.getId() + "-mnt"), job.storage());
assertEquals("s3://logs/emr/" + cluster.getId() + "/steps/" + stepId + "/", job.logFolder());
assertEquals(List.of(cluster.getId()), fixture.clusterStorage.created);
assertEquals("COMPLETED", service.describeStep(cluster.getId(), stepId).getState());
}
@Test
void aClusterWithHivesImageIsMadeOfTheImagesTheTemplatesNameAndItsSparkStepsRunInItToo() {
EmrService templated = fixture.withHiveImageTemplate("registry.internal/emr-serverless/hive/%s:20250425");
EmrCluster requested = cluster("templated", true, sparkStep("report", "CONTINUE"));
requested.setApplications("[{\"Name\": \"Hive\"}, {\"Name\": \"Spark\"}]");
templated.runJobFlow(requested, REGION);
fixture.runStepThread();
assertEquals(List.of(List.of("emr-7.5.0", "public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest",
"registry.internal/emr-serverless/hive/emr-7.5.0:20250425")), fixture.releaseImages.asked);
assertEquals(SparkJobRunner.Engine.SPARK, runner.jobs.get(0).engine());
assertEquals(EmrServiceFixture.RecordingReleaseImages.IMAGE, runner.jobs.get(0).imageTemplate());
}
@Test
void aBootstrappedClusterWithHiveBootstrapsInItsImageAndItsStepsRunInTheImageTheBootstrapLeft() {
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
EmrCluster requested = bootstrapped(cluster("bootstrapped-hive", true, hiveStep("report", "-e", "select 1")));
requested.setApplications("[{\"Name\": \"Hive\"}]");
bootstrapping.service.runJobFlow(requested, REGION);
bootstrapping.runStepThread();
bootstrapping.runStepThread();
assertEquals(EmrServiceFixture.RecordingReleaseImages.IMAGE, bootstrap.bootstraps.get(0).imageTemplate());
assertEquals(SparkJobRunner.Engine.HIVE, runner.jobs.get(0).engine());
assertEquals(IMAGE, runner.jobs.get(0).imageTemplate());
// Made once, for the bootstrap: the image it left holds it.
assertEquals(1, bootstrapping.releaseImages.asked.size());
}
@Test
void aClusterWithHiveThatEndsBeforeItsBootstrapOrStepRunsMakesNoImage() {
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
EmrCluster unbooted = bootstrapped(cluster("ended-bootstrapping", true));
unbooted.setApplications("[{\"Name\": \"Hive\"}]");
String unbootedId = bootstrapping.service.runJobFlow(unbooted, REGION).getId();
EmrCluster unrun = cluster("ended-running", true, hiveStep("report", "-e", "select 1"));
unrun.setApplications("[{\"Name\": \"Hive\"}]");
String unrunId = service.runJobFlow(unrun, REGION).getId();
bootstrapping.service.terminateJobFlows(List.of(unbootedId));
service.terminateJobFlows(List.of(unrunId));
bootstrapping.runStepThread();
fixture.runStepThread();
// Each image would be pulled, several GB, and made: a thread that comes after the cluster's end makes none.
assertEquals(List.of(), bootstrapping.releaseImages.asked);
assertEquals(List.of(), fixture.releaseImages.asked);
}
@Test
void anImageWithHiveThatCannotBeMadeFailsTheStepOrEndsTheBootstrappingCluster() {
fixture.releaseImages.failure = new IllegalStateException("Could not pull the Hive image");
EmrCluster requested = cluster("unmade", true, hiveStep("report", "-e", "select 1"));
requested.setApplications("[{\"Name\": \"Hive\"}]");
EmrCluster cluster = service.runJobFlow(requested, REGION);
fixture.runStepThread();
EmrStep failed = service.describeStep(cluster.getId(), cluster.getSteps().get(0).getId());
assertEquals("FAILED", failed.getState());
assertEquals("The step could not start: Could not pull the Hive image", failed.getFailureMessage());
assertEquals(List.of(), runner.jobs);
EmrServiceFixture bootstrapping = EmrServiceFixture.docker(runner, bootstrap, null);
bootstrapping.releaseImages.failure = new IllegalStateException("Could not pull the Hive image");
EmrCluster unbooted = bootstrapped(cluster("unbooted", true));
unbooted.setApplications("[{\"Name\": \"Hive\"}]");
String unbootedId = bootstrapping.service.runJobFlow(unbooted, REGION).getId();
bootstrapping.runStepThread();
EmrCluster ended = bootstrapping.service.describeCluster(unbootedId);
assertEquals("TERMINATED_WITH_ERRORS", ended.getState());
assertEquals(List.of("INTERNAL_ERROR",
"Floci could not run the bootstrap actions: Could not pull the Hive image"),
List.of(ended.getStateChangeReasonCode(), ended.getStateChangeMessage()));
assertEquals(List.of(), bootstrap.bootstraps);
}
@Test
void aFailedBootstrapActionEndsTheClusterWithErrorsBeforeAnyStepRuns() {
bootstrap.outcome = BootstrapRunner.Outcome.actionFailed(2, 1);
@@ -789,7 +912,7 @@ class EmrServiceContainerStepsTest {
@Test
void aClusterWhoseStepsNoContainerRanHasNoStorage() {
EmrStep query = sparkStep("query", "CONTINUE");
query.setArgs(new ArrayList<>(List.of("hive-script", "--run-hive-script", "--args", "-f", "s3://bucket/q.q")));
query.setArgs(new ArrayList<>(List.of("pig-script", "--run-pig-script", "--args", "-f", "s3://bucket/q.pig")));
EmrCluster cluster = service.runJobFlow(cluster("unrun", true, query), REGION);
fixture.runStepThread();
@@ -863,6 +986,18 @@ class EmrServiceContainerStepsTest {
}
// A spark-submit step through command-runner.jar, written for a cluster with YARN.
// The AWS CLI's Hive step: command-runner.jar running hive-script with the step's arguments after its --args.
private static EmrStep hiveStep(String name, String... args) {
EmrStep step = new EmrStep();
step.setName(name);
step.setActionOnFailure("CONTINUE");
step.setJar("command-runner.jar");
List<String> command = new ArrayList<>(List.of("hive-script", "--run-hive-script", "--args"));
command.addAll(List.of(args));
step.setArgs(command);
return step;
}
private static EmrStep sparkStep(String name, String actionOnFailure) {
EmrStep step = new EmrStep();
step.setName(name);
@@ -82,6 +82,23 @@ final class EmrServiceFixture {
}
}
/** Makes no image: answers {@link #IMAGE} for each, or throws {@link #failure} when it is set. */
static final class RecordingReleaseImages implements ReleaseImages {
static final String IMAGE = "sha256:" + "3".repeat(64);
// Each image asked for: its release, then the two it is made of.
final List<List<String>> asked = new ArrayList<>();
RuntimeException failure;
@Override
public String image(String releaseLabel, String sparkImage, String hiveImage) {
asked.add(List.of(releaseLabel, sparkImage, hiveImage));
if (failure != null) {
throw failure;
}
return IMAGE;
}
}
final ObjectMapper objectMapper = new ObjectMapper();
final List<JsonNode> published = new ArrayList<>();
final MutableClock clock;
@@ -99,6 +116,7 @@ final class EmrServiceFixture {
private final BootstrapRunner bootstrap;
// The docker runner mode's; null in the immediate one.
final RecordingStorage clusterStorage;
final RecordingReleaseImages releaseImages;
private final IamService iam;
private final int[] durations;
@@ -108,7 +126,7 @@ final class EmrServiceFixture {
}
EmrServiceFixture(int startupDelaySeconds, int stepDurationSeconds, int terminationDelaySeconds) {
this(new InMemoryStorageFactory(ACCOUNT), new MutableClock(), null, null, null, null,
this(new InMemoryStorageFactory(ACCOUNT), new MutableClock(), null, null, null, null, null,
startupDelaySeconds, stepDurationSeconds, terminationDelaySeconds);
}
@@ -120,17 +138,18 @@ final class EmrServiceFixture {
/** As {@link #docker(SparkJobRunner, IamService)}, its clusters' bootstrap actions run by {@code bootstrap}. */
static EmrServiceFixture docker(SparkJobRunner runner, BootstrapRunner bootstrap, IamService iam) {
return new EmrServiceFixture(new InMemoryStorageFactory(ACCOUNT), new MutableClock(), runner, bootstrap,
new RecordingStorage(), iam, 0, 0, 0);
new RecordingStorage(), new RecordingReleaseImages(), iam, 0, 0, 0);
}
private EmrServiceFixture(InMemoryStorageFactory storage, MutableClock clock, SparkJobRunner runner,
BootstrapRunner bootstrap, RecordingStorage clusterStorage, IamService iam,
int... durations) {
BootstrapRunner bootstrap, RecordingStorage clusterStorage,
RecordingReleaseImages releaseImages, IamService iam, int... durations) {
this.storage = storage;
this.clock = clock;
this.runner = runner;
this.bootstrap = bootstrap;
this.clusterStorage = clusterStorage;
this.releaseImages = releaseImages;
this.iam = iam;
this.durations = durations;
EventBridgeService eventBridge = mock(EventBridgeService.class);
@@ -157,12 +176,12 @@ final class EmrServiceFixture {
public void deliver(Runnable delivery) {
deliveries.add(delivery);
}
}, runner, bootstrap, clusterStorage, stepThreads::add, iam);
}, runner, bootstrap, clusterStorage, releaseImages, stepThreads::add, iam);
}
/** A new service on the same storage and clock, as after a restart of Floci with persistent storage. */
EmrServiceFixture restart() {
return new EmrServiceFixture(storage, clock, runner, bootstrap, clusterStorage, iam, durations);
return new EmrServiceFixture(storage, clock, runner, bootstrap, clusterStorage, releaseImages, iam, durations);
}
/**
@@ -171,7 +190,19 @@ final class EmrServiceFixture {
*/
EmrService restartReconciling(SparkJobRunner runner, EmrService.Wakeups wakeups) {
return new EmrService(storage, config(true), new RegionResolver(REGION, ACCOUNT), publisher, clock, wakeups,
runner, bootstrap, clusterStorage, stepThreads::add, iam);
runner, bootstrap, clusterStorage, releaseImages, stepThreads::add, iam);
}
/**
* A new service on the same storage and clock, as {@link #restart} builds, whose Hive steps run in the image
* {@code hiveImageTemplate} names, its steps' threads this fixture's, and its events not delivered.
*/
EmrService withHiveImageTemplate(String hiveImageTemplate) {
EmulatorConfig config = config(false);
when(config.services().emr().hiveImageTemplate()).thenReturn(Optional.of(hiveImageTemplate));
return new EmrService(storage, config, new RegionResolver(REGION, ACCOUNT), publisher, clock,
mock(EmrService.Wakeups.class), runner, bootstrap, clusterStorage, releaseImages, stepThreads::add,
iam);
}
private EmulatorConfig config(boolean reconcile) {
@@ -181,6 +212,7 @@ final class EmrServiceFixture {
when(config.services().emr().stepDurationSeconds()).thenReturn(durations[1]);
when(config.services().emr().clusterTerminationDelaySeconds()).thenReturn(durations[2]);
when(config.services().emr().imageTemplate()).thenReturn(Optional.empty());
when(config.services().emr().hiveImageTemplate()).thenReturn(Optional.empty());
when(config.services().emr().dockerNetwork()).thenReturn(Optional.empty());
when(config.services().emr().reconcileContainersOnStartup()).thenReturn(reconcile);
return config;
@@ -21,6 +21,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
class EmrSparkStepsTest {
// A cluster's Applications, as RunJobFlow stores them, in a case of their own.
private static final String HIVE_AND_SPARK = "[{\"Name\": \"Spark\"}, {\"Name\": \"hive\"}]";
private final ObjectMapper objectMapper = new ObjectMapper();
@Test
@@ -149,14 +152,81 @@ class EmrSparkStepsTest {
@Test
void toolsTheImageDoesNotHaveAreNotRun() {
for (String tool : List.of("hive-script", "pig-script")) {
assertNull(EmrSparkSteps.command(step("command-runner.jar", null, tool, "--src", "s3://bucket/in/")));
}
assertNull(EmrSparkSteps.command(step("command-runner.jar", null, "pig-script", "--run-pig-script")));
assertNull(EmrSparkSteps.command(step("command-runner.jar", null)));
assertNull(EmrSparkSteps.command(step("script-runner.jar", null)));
assertNull(EmrSparkSteps.command(step("s3://bucket/jars/app.jar", null, "1")));
}
@Test
void aHiveStepsHiveGetsTheClustersHiveClassificationsThenTheArgumentsAfterHiveScriptsArgs() {
// The AWS CLI's Hive step, Type=Hive,Args=[-f,...,-d,...], on a cluster with Hive.
String configurations = """
[{"Classification": "hive-site", "Properties": {"hive.exec.reducers.max": "8"}},
{"Classification": "spark-defaults", "Properties": {"spark.executor.cores": "2"}},
{"Classification": "tez-site", "Properties": {"tez.grouping.max-size": "268435456"}},
{"Classification": "core-site", "Properties": {"fs.s3a.connection.maximum": "50"}},
{"Classification": "hive-site", "Properties": {"hive.metastore.client.factory.class":
"com.amazonaws.glue.catalog.metastore.AWSGlueDataCatalogHiveClientFactory"}}]""";
EmrSparkSteps.HiveCommand hive = EmrSparkSteps.hive(step("command-runner.jar", null, "hive-script",
"--run-hive-script", "--args", "-f", "s3://bucket/queries/report.q", "-d", "INPUT=s3://bucket/in/",
"--hiveconf", "hive.exec.reducers.max=4"), HIVE_AND_SPARK, configurations, objectMapper);
assertEquals(List.of("hive-script", "--run-hive-script", "--args"), hive.runner());
// core-site, then tez-site, then hive-site, as Hive reads them, and the step's own --hiveconf last.
assertEquals(List.of("--hiveconf", "fs.s3a.connection.maximum=50",
"--hiveconf", "tez.grouping.max-size=268435456",
"--hiveconf", "hive.exec.reducers.max=8",
"--hiveconf", "hive.metastore.client.factory.class="
+ "com.amazonaws.glue.catalog.metastore.AWSGlueDataCatalogHiveClientFactory",
"-f", "s3://bucket/queries/report.q", "-d", "INPUT=s3://bucket/in/",
"--hiveconf", "hive.exec.reducers.max=4"), hive.arguments());
}
@Test
void aHiveScriptStepWithoutArgsGetsThemAtItsEndAndAStepCanRunHiveItself() {
EmrSparkSteps.HiveCommand script = EmrSparkSteps.hive(step("command-runner.jar", null, "hive-script",
"--run-hive-script"), HIVE_AND_SPARK, null, objectMapper);
EmrSparkSteps.HiveCommand hive = EmrSparkSteps.hive(step("command-runner.jar", null, "/usr/bin/hive",
"-e", "select 1"), HIVE_AND_SPARK, null, objectMapper);
assertEquals(List.of("hive-script", "--run-hive-script", "--args"), script.runner());
assertEquals(List.of(), script.arguments());
assertEquals(List.of("/usr/bin/hive-script", "--run-hive-script", "--args"), EmrSparkSteps.hive(step(
"command-runner.jar", null, "/usr/bin/hive-script", "--run-hive-script", "--args", "-e", "select 1"),
HIVE_AND_SPARK, null, objectMapper).runner());
assertEquals(List.of("/usr/bin/hive"), hive.runner());
assertEquals(List.of("-e", "select 1"), hive.arguments());
}
@Test
void aStepRunsHiveOnlyWhenItsClustersApplicationsNameHive() {
EmrStep query = step("command-runner.jar", null, "hive-script", "--run-hive-script", "--args", "-f",
"s3://bucket/queries/report.q");
for (String applications : new String[]{"[{\"Name\": \"Spark\"}]", "[]", null, "[{"}) {
assertNull(EmrSparkSteps.hive(query, applications, null, objectMapper));
}
// Where hive-script then runs, it says what EMR's says without Hive: "Hive isn't installed."
assertEquals(query.getArgs(), EmrSparkSteps.command(query));
for (EmrStep other : List.of(step("command-runner.jar", null, "spark-submit", "s3://bucket/app.py"),
step("command-runner.jar", null, "hive-scripts"),
step("script-runner.jar", null, "s3://bucket/hive.sh"),
step("s3://bucket/jars/hive.jar", null, "hive"))) {
assertNull(EmrSparkSteps.hive(other, HIVE_AND_SPARK, null, objectMapper));
}
}
@Test
void theClustersHiveEnvExportsAreItsHiveStepsEnvironment() {
String configurations = """
[{"Classification": "hive-env", "Configurations": [
{"Classification": "export", "Properties": {"HADOOP_HEAPSIZE": "2048"}}]},
{"Classification": "spark-env", "Configurations": [
{"Classification": "export", "Properties": {"PYSPARK_PYTHON": "/usr/bin/python3"}}]}]""";
assertEquals(Map.of("HADOOP_HEAPSIZE", "2048"), EmrSparkSteps.hiveEnvironment(configurations, objectMapper));
}
@Test
void theClustersSparkDefaultsComeFromItsConfigurations() {
String configurations = """
@@ -222,6 +222,52 @@ class EmrServerlessSparkRunnerTest {
verify(spec, never()).withEnv(eq("FLOCI_SPARK_LOG4J2"), anyString());
}
@Test
void anEmrHiveStepRunsItsCommandOnItsClustersStorageWithItsHdfsAndMetastore() {
ContainerBuilder builder = mock(ContainerBuilder.class);
ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(builder.newContainer(anyString())).thenReturn(spec);
SparkJobRunner.Job step = hiveStep(List.of("-f", "s3://bucket/queries/report.q"));
runner(builder).run(step, progress);
verify(builder).newContainer("public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest");
// hive-script in place of hive, as the image's user, with Floci's settings after its --args.
verify(spec).withEntrypoint(argThat((List<String> entrypoint) -> entrypoint.size() == 7
&& List.of("floci", "hive-script", "--run-hive-script", "--args")
.equals(entrypoint.subList(3, 7))));
verify(spec).withCmd(EmrServerlessSparkRunner.hiveArguments(step, ENDPOINT));
verify(spec).withNamedVolume("j-1-home", "/home/hadoop");
verify(spec).withNamedVolume("j-1-mnt", "/mnt");
// In its cluster's image, which holds Spark too, Hive reads its own Hadoop configuration.
verify(spec).withEntrypoint(argThat((List<String> entrypoint) -> entrypoint.get(2).contains(
"if [ -d /etc/hadoop/conf.hive ]; then export HADOOP_CONF_DIR=/etc/hadoop/conf.hive; fi")));
verify(spec, never()).withEnv(eq("FLOCI_HADOOP_SITE"), anyString());
verify(spec, never()).withEnv(eq("FLOCI_MAPRED_SITE"), anyString());
}
@Test
void anEmrHiveStepsHiveReachesItsClustersHdfsAsViewfsAndKeepsItsMetastoreInItsMnt() {
List<String> arguments = EmrServerlessSparkRunner.hiveArguments(
hiveStep(List.of("--hiveconf", "hive.exec.reducers.max=8", "-f", "s3://bucket/queries/report.q")),
ENDPOINT);
int tez = arguments.indexOf("tez.am.client.am.port-range=40000-40100");
assertEquals(List.of(
"--hiveconf", "fs.defaultFS=hdfs:///",
"--hiveconf", "fs.hdfs.impl=org.apache.hadoop.fs.viewfs.ViewFileSystemOverloadScheme",
"--hiveconf", "fs.viewfs.mounttable.default.linkFallback=file:///mnt/hdfs",
"--hiveconf", "fs.defaultFS=viewfs:///",
"--hiveconf", "hive.metastore.client.factory.class="
+ "org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClientFactory",
"--hiveconf", "javax.jdo.option.ConnectionURL="
+ "jdbc:derby:;databaseName=/mnt/var/lib/hive/metastore_db;create=true",
"--hiveconf", "hive.metastore.schema.verification=false",
"--hiveconf", "datanucleus.schema.autoCreateAll=true",
"--hiveconf", "hive.exec.reducers.max=8", "-f", "s3://bucket/queries/report.q"),
arguments.subList(tez + 1, arguments.size()));
}
@Test
void aHiveScratchFolderInS3LeadsToTheSamePathLocallyThenItsUsersFolder() {
assertEquals("/hive/scratch/hadoop", EmrServerlessSparkRunner.hiveScratchMirror(
@@ -1359,6 +1405,14 @@ class EmrServerlessSparkRunnerTest {
Duration.ZERO, null, null, Map.of(), List.of(), null, Map.of(), Map.of(), Map.of(), Map.of(), Map.of());
}
// An EMR Hive step: hive-script's --args, then application, on cluster j-1's storage.
private static SparkJobRunner.Job hiveStep(List<String> application) {
return new SparkJobRunner.Job("emr", "s-1", "123456789012", "eu-west-1", "emr-7.5.0", HIVE, null, null,
"floci-network", "arn:aws:iam::123456789012:role/emr-ec2", Map.of(), application,
List.of("hive-script", "--run-hive-script", "--args"), Duration.ZERO, null, null, Map.of(), List.of(),
new SparkJobRunner.Storage("j-1-home", "j-1-mnt"), Map.of(), Map.of(), Map.of(), Map.of(), Map.of());
}
private static SparkJobRunner.Job customImageJob(String customImage) {
return new SparkJobRunner.Job("emr-serverless", "00f0000000000001", "123456789012", "eu-west-1", "emr-7.5.0",
SPARK, null, customImage, "floci-network", "arn:aws:iam::123456789012:role/job", Map.of(),