mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(emr): run Pig steps on Apache Pig, an opt-in download added to the cluster's image (#8636)
No AWS image carries Pig, so a Pig step failed without running. With floci.services.emr.pig.enabled on (off by default), a docker cluster whose Applications name Pig gets Apache Pig 0.18.0 in its image: downloaded to a temporary file from the first of floci.services.emr.pig.urls that gives it whole with the checksum floci.services.emr.pig.sha256 names (a URL that fails, stalls for a minute or gives another checksum passes to the next), then streamed into /usr/lib/pig as EmrReleaseImages makes the image, with Tez from the release's Hive image and a /usr/bin/pig that EMR's own pig-script runs. Pig runs on the image's Tez, its bundled Tez and protobuf 3 left out, on the cluster's YARN or in local mode, with exectype=tez, a working directory without a scheme, which S3A takes, and no task reports and one try for counters from the MapReduce JobHistory server the cluster does not run, then the cluster's tez-site and pig-properties, in a pig.properties of the step's own; pig-log4j and pig-env reach Pig too. A command step's new tez-site.xml shares Hive's Tez-on-YARN settings. Without the setting, a Pig step on a cluster that installs Pig still fails without running, its message naming the setting; on one that does not, EMR's pig-script says "Pig isn't installed." as on EMR.
This commit is contained in:
1 parent
d2bca16023
commit
30f8a9985e
17 files changed
+1355
-109
No files matched your search
@@ -0,0 +1,174 @@
|
||||
package io.floci.aws.services.emr;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.floci.aws.testing.ContainerDataPlaneProfile;
|
||||
import io.floci.aws.testing.DockerAvailability;
|
||||
import io.floci.aws.testing.EmrRequests;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.floci.aws.testing.S3TestClients;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import software.amazon.awssdk.core.sync.RequestBody;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.s3.S3Client;
|
||||
import software.amazon.awssdk.services.s3.model.S3Object;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static io.floci.aws.testing.EmrRequests.awaitStep;
|
||||
import static io.floci.aws.testing.EmrRequests.emr;
|
||||
import static io.floci.aws.testing.EmrRequests.terminateClusterAndAwaitCleanup;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* EMR Pig steps through Floci's Docker runner for real, with {@code floci.services.emr.pig.enabled} on: a cluster
|
||||
* whose {@code Applications} name Pig runs the AWS CLI's Pig step, EMR's {@code pig-script} in the image, with Apache
|
||||
* Pig, which Floci downloads and adds to the image as it makes it, on Tez on the cluster's YARN, as EMR's Pig runs by
|
||||
* default, and on MapReduce when a step asks for it.
|
||||
*
|
||||
* <p>A nightly check: it downloads Apache Pig (470 MB) and pulls the release's Spark and Hive images.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(EmrPigStepsNightlyIntegrationTest.PigProfile.class)
|
||||
@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true")
|
||||
// Bounded waits: the image made with Pig, then two steps of up to five minutes each, past the default two.
|
||||
@Timeout(value = 30, unit = TimeUnit.MINUTES)
|
||||
class EmrPigStepsNightlyIntegrationTest {
|
||||
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
private static final String PIG = "[{\"Name\":\"Hadoop\"},{\"Name\":\"Pig\"}]";
|
||||
private static final String ROWS = "a,1\nb,2\nc,3\na,4\n";
|
||||
// Sums each key's values through a shuffle, then orders the sums through another, as Pig's GROUP and ORDER do.
|
||||
private static final String SCRIPT = """
|
||||
rows = LOAD '$INPUT' USING PigStorage(',') AS (k:chararray, v:int);
|
||||
grouped = GROUP rows BY k;
|
||||
sums = FOREACH grouped GENERATE group, SUM(rows.v) * 10;
|
||||
ordered = ORDER sums BY group;
|
||||
STORE ordered INTO '$OUTPUT' USING PigStorage(',');
|
||||
""";
|
||||
private static final String SUMS = "a,50\nb,20\nc,30\n";
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@Inject
|
||||
EmrService emrService;
|
||||
|
||||
private S3Client s3;
|
||||
private String bucket;
|
||||
private String clusterId;
|
||||
|
||||
/** The Docker data planes, with Floci's Pig on. */
|
||||
public static class PigProfile extends ContainerDataPlaneProfile {
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
Map<String, String> overrides = new HashMap<>(super.getConfigOverrides());
|
||||
overrides.put("floci.services.emr.pig.enabled", "true");
|
||||
return overrides;
|
||||
}
|
||||
}
|
||||
|
||||
@BeforeAll
|
||||
static void configure() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void putInputs() throws InterruptedException {
|
||||
assertTrue(DockerAvailability.isAvailable(), "the nightly check needs a Docker daemon");
|
||||
s3 = AwsTestClients.create(S3Client.builder().forcePathStyle(true), "000000000000", Region.US_EAST_1);
|
||||
cleanup.register(s3::close);
|
||||
bucket = "emr-pig-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
s3.createBucket(request -> request.bucket(bucket));
|
||||
cleanup.register(() -> S3TestClients.deleteBucket(s3, bucket));
|
||||
put("data/rows/rows.csv", ROWS);
|
||||
put("scripts/sums.pig", SCRIPT);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theAwsClisPigStepRunsItsScriptFromS3OnTezThenOnMapReduce() {
|
||||
startCluster();
|
||||
|
||||
// The Release Guide's Pig step, Type=PIG,Args=[-f,...,-p,INPUT=...,-p,OUTPUT=...], as the AWS CLI sends it.
|
||||
String tez = pigStep("-f", s3Uri("scripts/sums.pig"), "-p", "INPUT=" + s3Uri("data/rows/"),
|
||||
"-p", "OUTPUT=" + s3Uri("out/tez/"));
|
||||
assertEquals("COMPLETED", state(tez), () -> logs(tez));
|
||||
assertEquals(SUMS, objects("out/tez/"));
|
||||
// Pig 0.16.0 and later "use Apache Tez", as Floci's Pig does unless told otherwise.
|
||||
assertTrue(logs(tez).contains("TezLauncher"), () -> logs(tez));
|
||||
|
||||
String mapReduce = pigStep("-x", "mapreduce", "-f", s3Uri("scripts/sums.pig"),
|
||||
"-p", "INPUT=" + s3Uri("data/rows/"), "-p", "OUTPUT=" + s3Uri("out/mapreduce/"));
|
||||
assertEquals("COMPLETED", state(mapReduce), () -> logs(mapReduce));
|
||||
assertEquals(SUMS, objects("out/mapreduce/"));
|
||||
assertTrue(logs(mapReduce).contains("MapReduceLauncher"), () -> logs(mapReduce));
|
||||
}
|
||||
|
||||
private void startCluster() {
|
||||
ObjectNode request = JSON.createObjectNode().put("Name", "pig-steps").put("ReleaseLabel", "emr-7.5.0")
|
||||
.put("LogUri", s3Uri("logs/"));
|
||||
try {
|
||||
request.set("Applications", JSON.readTree(PIG));
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
request.putObject("Instances").put("KeepJobFlowAliveWhenNoSteps", true).putArray("InstanceGroups")
|
||||
.addObject().put("Name", "primary").put("InstanceRole", "MASTER").put("InstanceType", "m5.xlarge")
|
||||
.put("InstanceCount", 1);
|
||||
clusterId = emr("RunJobFlow", request.toString()).then().statusCode(200).extract().jsonPath()
|
||||
.getString("JobFlowId");
|
||||
cleanup.register(() -> terminateClusterAndAwaitCleanup(clusterId, emrService));
|
||||
}
|
||||
|
||||
private String pigStep(String... args) {
|
||||
String[] command = new String[args.length + 3];
|
||||
command[0] = "pig-script";
|
||||
command[1] = "--run-pig-script";
|
||||
command[2] = "--args";
|
||||
System.arraycopy(args, 0, command, 3, args.length);
|
||||
return EmrRequests.addStep(clusterId, "pig", "command-runner.jar", command);
|
||||
}
|
||||
|
||||
private String state(String stepId) {
|
||||
return awaitStep(clusterId, stepId).jsonPath().getString("Step.Status.State");
|
||||
}
|
||||
|
||||
// What a step wrote, Pig's log included, to its standard output, then its standard error.
|
||||
private String logs(String stepId) {
|
||||
String folder = "logs/" + clusterId + "/steps/" + stepId + "/";
|
||||
return S3TestClients.gunzipped(s3, bucket, folder + "stdout.gz") + "\n"
|
||||
+ S3TestClients.gunzipped(s3, bucket, folder + "stderr.gz");
|
||||
}
|
||||
|
||||
private String objects(String prefix) {
|
||||
StringBuilder text = new StringBuilder();
|
||||
for (S3Object object : s3.listObjectsV2(request -> request.bucket(bucket).prefix(prefix)).contents()) {
|
||||
text.append(s3.getObjectAsBytes(request -> request.bucket(bucket).key(object.key())).asUtf8String());
|
||||
}
|
||||
return text.toString();
|
||||
}
|
||||
|
||||
private void put(String key, String text) {
|
||||
s3.putObject(request -> request.bucket(bucket).key(key), RequestBody.fromString(text));
|
||||
}
|
||||
|
||||
private String s3Uri(String key) {
|
||||
return "s3://" + bucket + "/" + key;
|
||||
}
|
||||
}
|
||||
@@ -31,12 +31,15 @@ import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
|
||||
import org.apache.commons.compress.archivers.tar.TarConstants;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
@@ -48,8 +51,10 @@ import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
@@ -81,7 +86,9 @@ class EmrReleaseImagesTest {
|
||||
// The images of the made image's kind the daemon lists, and the command listing them.
|
||||
private final List<Image> listed = new ArrayList<>();
|
||||
private final ListImagesCmd listImages = mock(ListImagesCmd.class, RETURNS_SELF);
|
||||
private final EmrReleaseImages images = new EmrReleaseImages(lifecycle, containerBuilder, imageCache, config);
|
||||
private final PigDistribution pig = mock(PigDistribution.class);
|
||||
private final EmrReleaseImages images = new EmrReleaseImages(lifecycle, containerBuilder, imageCache, config,
|
||||
pig);
|
||||
|
||||
@Test
|
||||
void aCopyPutsItsSourceUnderItsNameInItsFolderAndTezsGoodiesLinksLeadToTheHiveImagesCopy() throws IOException {
|
||||
@@ -140,6 +147,48 @@ class EmrReleaseImagesTest {
|
||||
verify(docker).removeContainerCmd("source");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anImageForAClusterWithPigHasTezThenPigAndANameOfItsOwn(@TempDir Path folder) throws IOException {
|
||||
when(pig.identity()).thenReturn("pig " + "6".repeat(64));
|
||||
Path downloaded = folder.resolve("floci-pig-1.tar.gz");
|
||||
ByteArrayOutputStream empty = new ByteArrayOutputStream();
|
||||
try (TarArchiveOutputStream tar = new TarArchiveOutputStream(new GZIPOutputStream(empty))) {
|
||||
tar.finish();
|
||||
}
|
||||
Files.write(downloaded, empty.toByteArray());
|
||||
when(pig.download()).thenReturn(downloaded);
|
||||
|
||||
List<String> copied = makesMissing("emr-7.5.0", false, true);
|
||||
|
||||
// Pig runs its scripts on Tez, which a cluster with Pig and without Hive gets, Hive staying out.
|
||||
assertEquals(List.of("/usr/lib/hadoop-hdfs", "/usr/lib/hadoop-mapreduce", "/usr/lib/hadoop-yarn",
|
||||
"/usr/lib/tez", "/etc/tez", "/usr/share/aws/emr/serverless-goodies/lib"), copied);
|
||||
verify(pig).download();
|
||||
// The download goes once the image is made of it.
|
||||
assertFalse(Files.exists(downloaded));
|
||||
ArgumentCaptor<String> tags = ArgumentCaptor.forClass(String.class);
|
||||
ArgumentCaptor<Map<String, String>> labels = mapCaptor();
|
||||
images.image("emr-7.5.0", SPARK, HIVE, false, false);
|
||||
verify(lifecycle, times(2)).commit(eq("target"), anyString(), tags.capture(), anyString(), labels.capture());
|
||||
assertNotEquals(tags.getAllValues().get(0), tags.getAllValues().get(1));
|
||||
assertNotEquals(labels.getAllValues().get(0).get(EmrReleaseImages.KIND_LABEL),
|
||||
labels.getAllValues().get(1).get(EmrReleaseImages.KIND_LABEL));
|
||||
// A cluster with Hive has Tez already.
|
||||
List<EmrReleaseImages.Copy> withHive = EmrReleaseImages.copies("emr-7.5.0", true, true);
|
||||
assertEquals(EmrReleaseImages.COPIES, withHive);
|
||||
assertTrue(withHive.containsAll(EmrReleaseImages.TEZ_COPIES));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aReleaseOfTheAwsRuntimeForSparkGetsNoPig() throws IOException {
|
||||
// "Pig and Oozie are not included."
|
||||
List<String> copied = makesMissing("emr-spark-8.1.0", false, true);
|
||||
|
||||
assertEquals(EmrReleaseImages.HADOOP_APART_COPIES.stream().map(EmrReleaseImages.Copy::from).toList(), copied);
|
||||
verify(pig, never()).download();
|
||||
verify(pig, never()).identity();
|
||||
}
|
||||
|
||||
@Test
|
||||
void anImageForAClusterWithoutHiveHasHadoopsServicesAloneAndANameOfItsOwn() {
|
||||
List<String> copied = makesMissing(false);
|
||||
@@ -149,7 +198,7 @@ class EmrReleaseImagesTest {
|
||||
assertTrue(EmrReleaseImages.COPIES.containsAll(EmrReleaseImages.HADOOP_COPIES));
|
||||
ArgumentCaptor<String> tags = ArgumentCaptor.forClass(String.class);
|
||||
ArgumentCaptor<Map<String, String>> labels = mapCaptor();
|
||||
images.image("emr-7.5.0", SPARK, HIVE, true);
|
||||
images.image("emr-7.5.0", SPARK, HIVE, true, false);
|
||||
verify(lifecycle, times(2)).commit(eq("target"), anyString(), tags.capture(), anyString(), labels.capture());
|
||||
assertNotEquals(tags.getAllValues().get(0), tags.getAllValues().get(1));
|
||||
// Nor does either replace the other: they are of two kinds.
|
||||
@@ -214,7 +263,7 @@ class EmrReleaseImagesTest {
|
||||
when(docker.inspectImageCmd(argThat((String image) -> image != null && image.startsWith(repository + ":"))))
|
||||
.thenReturn(there);
|
||||
// A step is given the image there, and has no container of it yet when a newer pull makes another.
|
||||
assertEquals("sha256:given", images.image("emr-7.5.0", SPARK, HIVE, true));
|
||||
assertEquals("sha256:given", images.image("emr-7.5.0", SPARK, HIVE, true, false));
|
||||
listed.add(image("sha256:given", repository + ":emr-7.5.0-000000000000"));
|
||||
when(docker.removeImageCmd("sha256:given")).thenReturn(mock(RemoveImageCmd.class, RETURNS_SELF));
|
||||
|
||||
@@ -274,11 +323,11 @@ class EmrReleaseImagesTest {
|
||||
return "sha256:newer";
|
||||
});
|
||||
AtomicReference<String> first = new AtomicReference<>();
|
||||
Thread older = Thread.ofPlatform().start(() -> first.set(images.image("emr-7.5.0", SPARK, HIVE, true)));
|
||||
Thread older = Thread.ofPlatform().start(() -> first.set(images.image("emr-7.5.0", SPARK, HIVE, true, false)));
|
||||
assertTrue(committing.await(10, TimeUnit.SECONDS));
|
||||
|
||||
AtomicReference<String> second = new AtomicReference<>();
|
||||
Thread newer = Thread.ofPlatform().start(() -> second.set(images.image("emr-7.5.0", SPARK, HIVE, true)));
|
||||
Thread newer = Thread.ofPlatform().start(() -> second.set(images.image("emr-7.5.0", SPARK, HIVE, true, false)));
|
||||
ThreadStates.awaitBlockedOrDone(newer);
|
||||
// It waits for the image of its kind being made before it reads where the two names lead.
|
||||
verify(imageCache, times(1)).resolveForLaunch(HIVE, ImagePullBehavior.PREFER_CACHED, null);
|
||||
@@ -337,11 +386,11 @@ class EmrReleaseImagesTest {
|
||||
made.set(true);
|
||||
return "sha256:made";
|
||||
});
|
||||
Thread first = Thread.ofPlatform().start(() -> images.image("emr-7.5.0", SPARK, HIVE, true));
|
||||
Thread first = Thread.ofPlatform().start(() -> images.image("emr-7.5.0", SPARK, HIVE, true, false));
|
||||
assertTrue(committing.await(10, TimeUnit.SECONDS));
|
||||
|
||||
AtomicReference<String> found = new AtomicReference<>();
|
||||
Thread second = Thread.ofPlatform().start(() -> found.set(images.image("emr-7.5.0", SPARK, HIVE, true)));
|
||||
Thread second = Thread.ofPlatform().start(() -> found.set(images.image("emr-7.5.0", SPARK, HIVE, true, false)));
|
||||
ThreadStates.awaitBlockedOrDone(second);
|
||||
committed.countDown();
|
||||
first.join(10_000);
|
||||
@@ -364,7 +413,7 @@ class EmrReleaseImagesTest {
|
||||
when(docker.inspectImageCmd(anyString())).thenReturn(there);
|
||||
resolvesEachToItself();
|
||||
|
||||
assertEquals("sha256:made", images.image("emr-7.5.0", SPARK, HIVE, true));
|
||||
assertEquals("sha256:made", images.image("emr-7.5.0", SPARK, HIVE, true, false));
|
||||
|
||||
verify(docker, never()).createContainerCmd(anyString());
|
||||
verify(lifecycle, never()).commit(any(), anyString(), anyString(), any(), any());
|
||||
@@ -387,9 +436,9 @@ class EmrReleaseImagesTest {
|
||||
return there;
|
||||
});
|
||||
|
||||
images.image("emr-7.5.0", SPARK, HIVE, true);
|
||||
images.image("emr-7.5.0", SPARK, HIVE, true);
|
||||
images.image("emr-7.5.0", SPARK, HIVE, true);
|
||||
images.image("emr-7.5.0", SPARK, HIVE, true, false);
|
||||
images.image("emr-7.5.0", SPARK, HIVE, true, false);
|
||||
images.image("emr-7.5.0", SPARK, HIVE, true, false);
|
||||
|
||||
assertEquals(asked.get(0), asked.get(1));
|
||||
assertNotEquals(asked.get(0), asked.get(2));
|
||||
@@ -429,12 +478,12 @@ class EmrReleaseImagesTest {
|
||||
when(lifecycle.getDockerClient()).thenReturn(daemon);
|
||||
when(containerBuilder.resolveImage(anyString())).thenAnswer(invocation -> invocation.getArgument(0));
|
||||
EmrReleaseImages cached = new EmrReleaseImages(lifecycle, containerBuilder,
|
||||
new ImageCacheService(daemon, cacheConfig), config);
|
||||
new ImageCacheService(daemon, cacheConfig), config, pig);
|
||||
|
||||
cached.image("emr-7.5.0", SPARK, HIVE, true);
|
||||
cached.image("emr-7.5.0", SPARK, HIVE, true, false);
|
||||
tags.put(HIVE, "sha256:newer-hive");
|
||||
images.add("sha256:newer-hive");
|
||||
cached.image("emr-7.5.0", SPARK, HIVE, true);
|
||||
cached.image("emr-7.5.0", SPARK, HIVE, true, false);
|
||||
|
||||
assertNotEquals(asked.get(0), asked.get(1));
|
||||
}
|
||||
@@ -447,6 +496,10 @@ class EmrReleaseImagesTest {
|
||||
}
|
||||
|
||||
private List<String> makesMissing(String release, boolean withHive) {
|
||||
return makesMissing(release, withHive, false);
|
||||
}
|
||||
|
||||
private List<String> makesMissing(String release, boolean withHive, boolean withPig) {
|
||||
when(lifecycle.getDockerClient()).thenReturn(docker);
|
||||
String repository = ContainerStorageHelper.dockerName(config, "emr-release");
|
||||
// The two are pulled as a container's image would be, from the image-registry-base it names.
|
||||
@@ -482,7 +535,7 @@ class EmrReleaseImagesTest {
|
||||
when(listImages.exec()).thenAnswer(invocation -> listed);
|
||||
when(docker.listImagesCmd()).thenReturn(listImages);
|
||||
|
||||
assertEquals("sha256:made", images.image(release, SPARK, HIVE, withHive));
|
||||
assertEquals("sha256:made", images.image(release, SPARK, HIVE, withHive, withPig));
|
||||
return copied;
|
||||
}
|
||||
|
||||
|
||||
@@ -67,6 +67,7 @@ class EmrServiceContainerStepsTest {
|
||||
private static final String REPORT = "s3://bucket/jobs/report.py";
|
||||
private static final String DRIVER_FAILED = "The Spark driver exited with code 1.";
|
||||
private static final String INSTALL = "s3://bucket/bootstrap/install.sh";
|
||||
private static final String PIG = "[{\"Name\": \"Hadoop\"}, {\"Name\": \"Pig\"}]";
|
||||
private static final String ERROR_CODE_PAGES = "https://docs.aws.amazon.com/emr/latest/ManagementGuide/";
|
||||
// The id of the image a bootstrap kept, which the cluster's steps run in.
|
||||
private static final String IMAGE = "sha256:" + "2".repeat(64);
|
||||
@@ -599,7 +600,7 @@ class EmrServiceContainerStepsTest {
|
||||
// Its release's image with Hadoop's services, as it has no Hive, made on the step's thread: its steps and its
|
||||
// primary node's HDFS and YARN run in it, the NodeManager offering what Floci gives it.
|
||||
assertEquals(List.of(List.of("emr-7.5.0", "public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest",
|
||||
"public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest", "false")), fixture.releaseImages.asked);
|
||||
"public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest", "false", "false")), fixture.releaseImages.asked);
|
||||
SparkJobRunner.Job job = runner.jobs.get(0);
|
||||
assertEquals(EmrServiceFixture.RecordingReleaseImages.IMAGE, job.imageTemplate());
|
||||
assertEquals(EmrServiceFixture.RecordingReleaseImages.IMAGE, fixture.clusterStorage.hdfs.get(0).get(2));
|
||||
@@ -779,7 +780,7 @@ class EmrServiceContainerStepsTest {
|
||||
|
||||
// Its release has no Hive image, so emr-7.5.0's gives the Hadoop its image holds for the node's daemons.
|
||||
assertEquals(List.of(List.of("emr-spark-8.1.0", "public.ecr.aws/emr-serverless/spark4/emr-spark-8.1.0:latest",
|
||||
"public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest", "false")), fixture.releaseImages.asked);
|
||||
"public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest", "false", "false")), fixture.releaseImages.asked);
|
||||
SparkJobRunner.Job job = runner.jobs.get(0);
|
||||
assertEquals(EmrServiceFixture.RecordingReleaseImages.IMAGE, job.imageTemplate());
|
||||
assertEquals(EmrServiceFixture.RecordingReleaseImages.IMAGE, fixture.clusterStorage.hdfs.get(0).get(2));
|
||||
@@ -815,7 +816,7 @@ class EmrServiceContainerStepsTest {
|
||||
SparkJobRunner.Job job = runner.jobs.get(0);
|
||||
assertEquals(SparkJobRunner.Engine.HIVE, job.engine());
|
||||
assertEquals(List.of(List.of("emr-7.5.0", "public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest",
|
||||
"public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest", "true")), fixture.releaseImages.asked);
|
||||
"public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest", "true", "false")), fixture.releaseImages.asked);
|
||||
assertEquals(EmrServiceFixture.RecordingReleaseImages.IMAGE, job.imageTemplate());
|
||||
assertEquals(hdfsStorage(cluster).withHiveMetastore("thrift://ip-10-0-0-1.ec2.internal:9083"), job.storage());
|
||||
}
|
||||
@@ -984,7 +985,9 @@ class EmrServiceContainerStepsTest {
|
||||
void aStepFlociDoesNotRunHandedOffBeforeATeardownEndsAsAStoppedDriverAndStartsNoOther() {
|
||||
EmrStep pig = sparkStep("query", "CONTINUE");
|
||||
pig.setArgs(List.of("pig-script", "--run-pig-script", "--args", "-f", "s3://bucket/query.pig"));
|
||||
EmrCluster cluster = service.runJobFlow(cluster("pig", true, pig, sparkStep("next", "CONTINUE")), REGION);
|
||||
EmrCluster requested = cluster("pig", true, pig, sparkStep("next", "CONTINUE"));
|
||||
requested.setApplications(PIG);
|
||||
EmrCluster cluster = service.runJobFlow(requested, REGION);
|
||||
service.stopManagedContainers();
|
||||
|
||||
fixture.runStepThread();
|
||||
@@ -1015,9 +1018,12 @@ class EmrServiceContainerStepsTest {
|
||||
|
||||
@Test
|
||||
void aStepFlociDoesNotRunFailsWithoutRunning() {
|
||||
// A cluster that installs Pig, which Floci adds only with floci.services.emr.pig.enabled.
|
||||
EmrStep pig = sparkStep("query", "CONTINUE");
|
||||
pig.setArgs(List.of("pig-script", "--run-pig-script", "--args", "-f", "s3://bucket/query.pig"));
|
||||
EmrCluster cluster = service.runJobFlow(cluster("pig", true, pig), REGION);
|
||||
EmrCluster requested = cluster("pig", true, pig);
|
||||
requested.setApplications(PIG);
|
||||
EmrCluster cluster = service.runJobFlow(requested, REGION);
|
||||
|
||||
fixture.runStepThread();
|
||||
|
||||
@@ -1025,6 +1031,46 @@ class EmrServiceContainerStepsTest {
|
||||
assertEquals("FAILED", failed.getState());
|
||||
assertEquals(EmrSparkSteps.NOT_RUN, failed.getFailureMessage());
|
||||
assertEquals(List.of(), runner.jobs);
|
||||
assertEquals(List.of(), fixture.releaseImages.asked);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPigStepOnAClusterWithoutPigRunsEmrsPigScriptWhichFindsNoPig() {
|
||||
EmrStep pig = sparkStep("query", "CONTINUE");
|
||||
List<String> args = List.of("pig-script", "--run-pig-script", "--args", "-f", "s3://bucket/query.pig");
|
||||
pig.setArgs(args);
|
||||
service.runJobFlow(cluster("no-pig", true, pig), REGION);
|
||||
|
||||
fixture.runStepThread();
|
||||
|
||||
// EMR's pig-script says "Pig isn't installed." there, and the step fails with its exit code.
|
||||
assertEquals(args, runner.jobs.get(0).command());
|
||||
assertFalse(runner.jobs.get(0).environment().containsKey("FLOCI_PIG_PROPERTIES"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPigStepWithFlocisPigRunsEmrsPigScriptOnTezInTheReleasesImageWithPig() {
|
||||
EmrService withPig = fixture.withPig();
|
||||
EmrStep pig = sparkStep("query", "CONTINUE");
|
||||
List<String> args = List.of("pig-script", "--run-pig-script", "--args", "-f", "s3://bucket/query.pig");
|
||||
pig.setArgs(args);
|
||||
EmrCluster requested = cluster("pig", true, pig);
|
||||
requested.setApplications(PIG);
|
||||
requested.setConfigurations("[{\"Classification\": \"pig-properties\", \"Properties\": "
|
||||
+ "{\"pig.exec.reducers.max\": \"8\"}}]");
|
||||
withPig.runJobFlow(requested, REGION);
|
||||
|
||||
fixture.runStepThread();
|
||||
|
||||
assertEquals(List.of(List.of("emr-7.5.0", "public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest",
|
||||
"public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest", "false", "true")),
|
||||
fixture.releaseImages.asked);
|
||||
SparkJobRunner.Job job = runner.jobs.get(0);
|
||||
assertEquals(args, job.command());
|
||||
assertEquals(EmrServiceFixture.RecordingReleaseImages.IMAGE, job.imageTemplate());
|
||||
assertEquals("exectype = tez\nmapreduce.job.working.dir = /user/${user.name}\npig.stats.notaskreport = true\n"
|
||||
+ "yarn.app.mapreduce.client.max-retries = 1\npig.exec.reducers.max = 8",
|
||||
job.environment().get("FLOCI_PIG_PROPERTIES"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1495,7 +1541,7 @@ class EmrServiceContainerStepsTest {
|
||||
assertEquals(stepId, job.runId());
|
||||
// The release's EMR Serverless image with its EMR Serverless Hive image's Hive, made on the step's thread.
|
||||
assertEquals(List.of(List.of("emr-7.5.0", "public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest",
|
||||
"public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest", "true")), fixture.releaseImages.asked);
|
||||
"public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest", "true", "false")), fixture.releaseImages.asked);
|
||||
assertEquals(EmrServiceFixture.RecordingReleaseImages.IMAGE, job.imageTemplate());
|
||||
assertNull(job.customImage());
|
||||
assertEquals(List.of("hive-script", "--run-hive-script", "--args"), job.command());
|
||||
@@ -1539,7 +1585,8 @@ class EmrServiceContainerStepsTest {
|
||||
fixture.runStepThread();
|
||||
|
||||
assertEquals(List.of(List.of("emr-7.5.0", "public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest",
|
||||
"registry.internal/emr-serverless/hive/emr-7.5.0:20250425", "true")), fixture.releaseImages.asked);
|
||||
"registry.internal/emr-serverless/hive/emr-7.5.0:20250425", "true", "false")),
|
||||
fixture.releaseImages.asked);
|
||||
assertEquals(SparkJobRunner.Engine.SPARK, runner.jobs.get(0).engine());
|
||||
assertEquals(EmrServiceFixture.RecordingReleaseImages.IMAGE, runner.jobs.get(0).imageTemplate());
|
||||
}
|
||||
@@ -2216,7 +2263,9 @@ class EmrServiceContainerStepsTest {
|
||||
void aClusterWhoseStepsNoContainerRanHasNoStorage() {
|
||||
EmrStep query = sparkStep("query", "CONTINUE");
|
||||
query.setArgs(new ArrayList<>(List.of("pig-script", "--run-pig-script", "--args", "-f", "s3://bucket/q.pig")));
|
||||
EmrCluster cluster = service.runJobFlow(cluster("unrun", true, query), REGION);
|
||||
EmrCluster requested = cluster("unrun", true, query);
|
||||
requested.setApplications(PIG);
|
||||
EmrCluster cluster = service.runJobFlow(requested, REGION);
|
||||
fixture.runStepThread();
|
||||
|
||||
service.terminateJobFlows(List.of(cluster.getId()));
|
||||
|
||||
@@ -197,15 +197,16 @@ final class EmrServiceFixture {
|
||||
/** Makes no image: answers {@link #IMAGE} for each, or throws {@link #failure} when it is set. */
|
||||
static final class RecordingReleaseImages implements ReleaseImages {
|
||||
static final String IMAGE = "sha256:" + "3".repeat(64);
|
||||
// Each image asked for: its release, then the two it is made of, then whether it has Hive.
|
||||
// Each image asked for: its release, then the two it is made of, then whether it has Hive, and Pig.
|
||||
final List<List<String>> asked = new ArrayList<>();
|
||||
// Each image released, by id.
|
||||
final List<String> released = new ArrayList<>();
|
||||
RuntimeException failure;
|
||||
|
||||
@Override
|
||||
public String image(String releaseLabel, String sparkImage, String hiveImage, boolean withHive) {
|
||||
asked.add(List.of(releaseLabel, sparkImage, hiveImage, String.valueOf(withHive)));
|
||||
public String image(String releaseLabel, String sparkImage, String hiveImage, boolean withHive,
|
||||
boolean withPig) {
|
||||
asked.add(List.of(releaseLabel, sparkImage, hiveImage, String.valueOf(withHive), String.valueOf(withPig)));
|
||||
if (failure != null) {
|
||||
throw failure;
|
||||
}
|
||||
@@ -329,6 +330,18 @@ final class EmrServiceFixture {
|
||||
iam);
|
||||
}
|
||||
|
||||
/**
|
||||
* A new service on the same storage and clock, as {@link #restart} builds, with Floci's Pig on, its steps' threads
|
||||
* this fixture's, and its events not delivered.
|
||||
*/
|
||||
EmrService withPig() {
|
||||
EmulatorConfig config = config(false);
|
||||
when(config.services().emr().pig().enabled()).thenReturn(true);
|
||||
return new EmrService(storage, config, new RegionResolver(REGION, ACCOUNT), publisher, clock,
|
||||
mock(EmrService.Wakeups.class), runner, bootstrap, clusterStorage, releaseImages, stepThreads::add,
|
||||
iam);
|
||||
}
|
||||
|
||||
private EmulatorConfig config(boolean reconcile) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.services().emr().defaultReleaseLabel()).thenReturn("emr-7.5.0");
|
||||
|
||||
@@ -13,6 +13,7 @@ import java.nio.file.Path;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
@@ -24,6 +25,9 @@ class EmrSparkStepsTest {
|
||||
// A cluster's Applications, as RunJobFlow stores them, in a case of their own.
|
||||
private static final String HIVE_AND_SPARK = "[{\"Name\": \"Spark\"}, {\"Name\": \"hive\"}]";
|
||||
private static final String RELEASE = "emr-7.5.0";
|
||||
// The pig.properties lines Floci gives every Pig after its exectype, ahead of the cluster's.
|
||||
private static final String FLOCIS_PIG_LINES = "mapreduce.job.working.dir = /user/${user.name}\n"
|
||||
+ "pig.stats.notaskreport = true\nyarn.app.mapreduce.client.max-retries = 1";
|
||||
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
@@ -80,18 +84,19 @@ class EmrSparkStepsTest {
|
||||
"aws s3 cp s3://bucket/my-script.sh /home/hadoop; chmod u+x /home/hadoop/my-script.sh;"
|
||||
+ " cd /home/hadoop; ./my-script.sh");
|
||||
|
||||
assertEquals(bash, EmrSparkSteps.command(step("command-runner.jar", null, bash.toArray(String[]::new))));
|
||||
assertEquals(bash, EmrSparkSteps.command(step("command-runner.jar", null, bash.toArray(String[]::new)), false));
|
||||
assertEquals(List.of("python3", "-c", "print(1)"),
|
||||
EmrSparkSteps.command(step("command-runner.jar", null, "python3", "-c", "print(1)")));
|
||||
EmrSparkSteps.command(step("command-runner.jar", null, "python3", "-c", "print(1)"), false));
|
||||
assertNull(EmrSparkSteps.command(
|
||||
step("command-runner.jar", null, "spark-submit", "s3://bucket/jobs/report.py")));
|
||||
step("command-runner.jar", null, "spark-submit", "s3://bucket/jobs/report.py"), false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aScriptRunnerStepFetchesItsScriptAndRunsItWithItsArguments() {
|
||||
for (String jar : List.of("script-runner.jar",
|
||||
"s3://us-east-1.elasticmapreduce/libs/script-runner/script-runner.jar")) {
|
||||
List<String> command = EmrSparkSteps.command(step(jar, null, "s3://bucket/my-script.sh", "--day", "1"));
|
||||
List<String> command = EmrSparkSteps.command(step(jar, null, "s3://bucket/my-script.sh", "--day", "1"),
|
||||
false);
|
||||
|
||||
assertEquals(List.of("bash", "-c"), command.subList(0, 2));
|
||||
assertTrue(command.get(2).contains("aws s3 cp --only-show-errors"));
|
||||
@@ -105,7 +110,8 @@ class EmrSparkStepsTest {
|
||||
throws Exception {
|
||||
// Not executable yet: script-runner makes it so, as it does a script it fetched from S3.
|
||||
Files.writeString(workingDirectory.resolve("my-script.sh"), "#!/bin/sh\nprintf 'ran:%s|' \"$@\"\n");
|
||||
List<String> command = EmrSparkSteps.command(step("script-runner.jar", null, "my-script.sh", "--day", "1 2"));
|
||||
List<String> command = EmrSparkSteps.command(step("script-runner.jar", null, "my-script.sh", "--day", "1 2"),
|
||||
false);
|
||||
|
||||
BootstrapProcess.Result ended =
|
||||
BootstrapProcess.run(new ProcessBuilder(command).directory(workingDirectory.toFile()));
|
||||
@@ -118,7 +124,7 @@ class EmrSparkStepsTest {
|
||||
// The Release Guide's own S3DistCp step.
|
||||
List<String> command = EmrSparkSteps.command(step("command-runner.jar", null, "s3-dist-cp",
|
||||
"--s3Endpoint=s3.amazonaws.com", "--src=s3://bucket/logs/j-3GYXXXXXX9IOJ/node/",
|
||||
"--dest=hdfs:///output", "--srcPattern=.*[a-zA-Z,]+"));
|
||||
"--dest=hdfs:///output", "--srcPattern=.*[a-zA-Z,]+"), false);
|
||||
// A spark-submit that shows what it was given and keeps the program, in place of the image's.
|
||||
Path sparkSubmit = folder.resolve("spark-submit");
|
||||
Files.writeString(sparkSubmit, "#!/bin/sh\nprintf '%s|' \"$@\"\ncp \"$3\" " + folder.resolve("kept.py") + "\n");
|
||||
@@ -150,16 +156,88 @@ class EmrSparkStepsTest {
|
||||
"-cacheFile", "s3://bucket/sample_dataset.dat#sample_dataset_cached.dat"};
|
||||
String[] indexer = {"hadoop-lzo", "com.hadoop.compression.lzo.DistributedLzoIndexer", "s3://bucket/logs/"};
|
||||
|
||||
assertEquals(List.of(streaming), EmrSparkSteps.command(step("command-runner.jar", null, streaming)));
|
||||
assertEquals(List.of(indexer), EmrSparkSteps.command(step("command-runner.jar", null, indexer)));
|
||||
assertEquals(List.of(streaming), EmrSparkSteps.command(step("command-runner.jar", null, streaming), false));
|
||||
assertEquals(List.of(indexer), EmrSparkSteps.command(step("command-runner.jar", null, indexer), false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPigStepRunsEmrsPigScriptUnlessItsClusterLacksTheOneItInstalls() {
|
||||
// The Release Guide's Pig step, as the AWS CLI turns Type=PIG into one.
|
||||
String[] pig = {"pig-script", "--run-pig-script", "--args", "-f", "s3://bucket/do-reports2.pig", "-p",
|
||||
"INPUT=s3://bucket/input", "-p", "OUTPUT=s3://bucket/output"};
|
||||
|
||||
assertEquals(List.of(pig), EmrSparkSteps.command(step("command-runner.jar", null, pig), false));
|
||||
// On a cluster that installs Pig, which Floci has not added, EMR would run it.
|
||||
assertNull(EmrSparkSteps.command(step("command-runner.jar", null, pig), true));
|
||||
// pig itself is a command like any other, there or not.
|
||||
assertEquals(List.of("pig", "-e", "fs -ls /"),
|
||||
EmrSparkSteps.command(step("command-runner.jar", null, "pig", "-e", "fs -ls /"), false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterInstallsPigWhenItsApplicationsNameIt() {
|
||||
assertTrue(EmrSparkSteps.installsPig(RELEASE, "[{\"Name\": \"Hadoop\"}, {\"Name\": \"Pig\"}]", objectMapper));
|
||||
assertTrue(EmrSparkSteps.installsPig(RELEASE, "[{\"Name\": \"pig\"}]", objectMapper));
|
||||
for (String applications : new String[]{HIVE_AND_SPARK, "[]", null, "[{"}) {
|
||||
assertFalse(EmrSparkSteps.installsPig(RELEASE, applications, objectMapper));
|
||||
}
|
||||
// "Pig and Oozie are not included" in a release of the AWS runtime for Apache Spark.
|
||||
assertFalse(EmrSparkSteps.installsPig("emr-spark-8.1.0", "[{\"Name\": \"Pig\"}]", objectMapper));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPigCommandRunsOnTezWithTheClustersTezSiteThenItsPigProperties() {
|
||||
String configurations = """
|
||||
[{"Classification": "pig-properties", "Properties": {"pig.exec.reducers.max": "8"}},
|
||||
{"Classification": "tez-site", "Properties": {"tez.grouping.max-size": "268435456",
|
||||
"tez.am.resource.memory.mb": "2048"}},
|
||||
{"Classification": "pig-properties", "Properties": {"tez.am.resource.memory.mb": "1536"}},
|
||||
{"Classification": "hive-site", "Properties": {"hive.exec.reducers.max": "4"}}]""";
|
||||
|
||||
Map<String, String> variables = EmrSparkSteps.pigEnvironment(configurations, objectMapper);
|
||||
|
||||
// Tez, as EMR's Pig 0.16.0 and later, from a working directory S3A takes as HDFS does, then tez-site's, then
|
||||
// pig-properties', a later line winning.
|
||||
assertEquals(String.join("\n", "exectype = tez", "mapreduce.job.working.dir = /user/${user.name}",
|
||||
"pig.stats.notaskreport = true", "yarn.app.mapreduce.client.max-retries = 1",
|
||||
"tez.grouping.max-size = 268435456",
|
||||
"tez.am.resource.memory.mb = 1536", "pig.exec.reducers.max = 8"),
|
||||
variables.get("FLOCI_PIG_PROPERTIES"));
|
||||
assertEquals(Set.of("FLOCI_PIG_PROPERTIES"), variables.keySet());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClustersPigPropertiesCanRunPigOnMapReduce() {
|
||||
// "You can explicitly set exectype=mapreduce in the pig-properties configuration classification".
|
||||
String configurations = """
|
||||
[{"Classification": "pig-properties", "Properties": {"exectype": "mapreduce"}}]""";
|
||||
|
||||
assertEquals("exectype = mapreduce\n" + FLOCIS_PIG_LINES,
|
||||
EmrSparkSteps.pigEnvironment(configurations, objectMapper).get("FLOCI_PIG_PROPERTIES"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClustersPigLog4jAndPigEnvReachItsPigsConfiguration() {
|
||||
String configurations = """
|
||||
[{"Classification": "pig-log4j", "Properties": {"log4j.logger.org.apache.pig": "DEBUG, A"}},
|
||||
{"Classification": "pig-env", "Configurations": [
|
||||
{"Classification": "export", "Properties": {"PIG_HEAPSIZE": "2048", "BAD NAME": "x"}}]}]""";
|
||||
|
||||
Map<String, String> variables = EmrSparkSteps.pigEnvironment(configurations, objectMapper);
|
||||
|
||||
// Pig reads the log4j.properties its log4jconf names, which gets pig-log4j's lines.
|
||||
assertEquals("exectype = tez\n" + FLOCIS_PIG_LINES + "\nlog4jconf = /tmp/floci-pig-conf/log4j.properties",
|
||||
variables.get("FLOCI_PIG_PROPERTIES"));
|
||||
assertEquals("log4j.logger.org.apache.pig = DEBUG, A", variables.get("FLOCI_PIG_LOG4J"));
|
||||
assertEquals("export PIG_HEAPSIZE='2048'", variables.get("FLOCI_PIG_ENV"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void toolsTheImageDoesNotHaveAreNotRun() {
|
||||
assertNull(EmrSparkSteps.command(step("command-runner.jar", null, "pig-script", "--run-pig-script")));
|
||||
assertNull(EmrSparkSteps.command(step("command-runner.jar", null)));
|
||||
assertNull(EmrSparkSteps.command(step("script-runner.jar", null)));
|
||||
assertNull(EmrSparkSteps.command(step("s3://bucket/jars/app.jar", null, "1")));
|
||||
assertNull(EmrSparkSteps.command(step("command-runner.jar", null, "pig-script", "--run-pig-script"), true));
|
||||
assertNull(EmrSparkSteps.command(step("command-runner.jar", null), false));
|
||||
assertNull(EmrSparkSteps.command(step("script-runner.jar", null), false));
|
||||
assertNull(EmrSparkSteps.command(step("s3://bucket/jars/app.jar", null, "1"), false));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -211,7 +289,7 @@ class EmrSparkStepsTest {
|
||||
assertNull(EmrSparkSteps.hive(query, RELEASE, applications, null, objectMapper));
|
||||
}
|
||||
// Where hive-script then runs, it says what EMR's says without Hive: "Hive isn't installed."
|
||||
assertEquals(query.getArgs(), EmrSparkSteps.command(query));
|
||||
assertEquals(query.getArgs(), EmrSparkSteps.command(query, false));
|
||||
for (EmrStep other : List.of(step("command-runner.jar", null, "spark-submit", "s3://bucket/app.py"),
|
||||
step("command-runner.jar", null, "hive-scripts"),
|
||||
step("script-runner.jar", null, "s3://bucket/hive.sh"),
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
package io.floci.aws.services.emr;
|
||||
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Stream;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class PigDistributionTest {
|
||||
|
||||
private static final Duration TIMEOUT = Duration.ofSeconds(5);
|
||||
private static final Duration STALL = Duration.ofMillis(300);
|
||||
private static final byte[] OTHER = "another file".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
// Releases the stalled download's server thread once the test is done with it.
|
||||
private final CountDownLatch released = new CountDownLatch(1);
|
||||
// A thread for each request, so the stalled one holds up no other.
|
||||
private final ExecutorService handlers = Executors.newCachedThreadPool();
|
||||
@TempDir
|
||||
Path downloads;
|
||||
private HttpServer server;
|
||||
private byte[] distribution;
|
||||
|
||||
@BeforeEach
|
||||
void serve() throws IOException {
|
||||
distribution = distribution();
|
||||
server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
|
||||
server.setExecutor(handlers);
|
||||
server.createContext("/missing", exchange -> {
|
||||
exchange.sendResponseHeaders(404, -1);
|
||||
exchange.close();
|
||||
});
|
||||
server.createContext("/pig.tar.gz", exchange -> {
|
||||
exchange.sendResponseHeaders(200, distribution.length);
|
||||
try (OutputStream body = exchange.getResponseBody()) {
|
||||
body.write(distribution);
|
||||
}
|
||||
});
|
||||
server.createContext("/other.tar.gz", exchange -> {
|
||||
exchange.sendResponseHeaders(200, OTHER.length);
|
||||
try (OutputStream body = exchange.getResponseBody()) {
|
||||
body.write(OTHER);
|
||||
}
|
||||
});
|
||||
// Sends its headers and its first bytes, then nothing until the test is done.
|
||||
server.createContext("/stalled.tar.gz", exchange -> {
|
||||
exchange.sendResponseHeaders(200, distribution.length);
|
||||
OutputStream body = exchange.getResponseBody();
|
||||
body.write(distribution, 0, 16);
|
||||
body.flush();
|
||||
try {
|
||||
released.await(1, TimeUnit.MINUTES);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
exchange.close();
|
||||
});
|
||||
server.start();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void stop() {
|
||||
released.countDown();
|
||||
server.stop(0);
|
||||
handlers.shutdownNow();
|
||||
}
|
||||
|
||||
@Test
|
||||
void theFirstUrlThatGivesTheDistributionWithItsChecksumIsTheOneDownloaded() throws Exception {
|
||||
Path downloaded = pig(TIMEOUT, "/missing", "/other.tar.gz", "/pig.tar.gz").download();
|
||||
|
||||
try {
|
||||
assertArrayEquals(distribution, Files.readAllBytes(downloaded));
|
||||
} finally {
|
||||
Files.deleteIfExists(downloaded);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDownloadThatStallsPassesToTheNextUrl() throws Exception {
|
||||
Path downloaded = pig(STALL, "/stalled.tar.gz", "/pig.tar.gz").download();
|
||||
|
||||
try {
|
||||
assertArrayEquals(distribution, Files.readAllBytes(downloaded));
|
||||
} finally {
|
||||
Files.deleteIfExists(downloaded);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void noUrlGivingItFailsWithWhatEachGaveAndLeavesNoFile() throws Exception {
|
||||
PigDistribution pig = pig(STALL, "/missing", "/other.tar.gz", "/stalled.tar.gz");
|
||||
|
||||
IOException failure = assertThrows(IOException.class, pig::download);
|
||||
|
||||
assertEquals("Could not download Apache Pig: " + url("/missing") + ": answered 404; " + url("/other.tar.gz")
|
||||
+ ": has the SHA-256 " + sha256(OTHER) + ", not the " + sha256(distribution)
|
||||
+ " floci.services.emr.pig.sha256 names; " + url("/stalled.tar.gz") + ": Read timed out",
|
||||
failure.getMessage());
|
||||
assertEquals(List.of(), leftovers());
|
||||
}
|
||||
|
||||
@Test
|
||||
void noUrlAtAllFails() {
|
||||
IOException failure = assertThrows(IOException.class,
|
||||
() -> new PigDistribution(List.of(" "), "0".repeat(64), TIMEOUT, TIMEOUT, downloads).download());
|
||||
|
||||
assertEquals("Could not download Apache Pig: no URL is set", failure.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void whatPigRunsFromGoesUnderItsFolderOwnedByRootAndTheRestStaysOut(@TempDir Path folder) throws Exception {
|
||||
Path archive = Files.write(folder.resolve("pig.tar.gz"), distribution);
|
||||
|
||||
// Its Tez and that Tez's protobuf stay out, the image's taking their place through Floci's pig-env.sh.
|
||||
assertEquals(List.of("pig/ dir", "pig/bin/ dir", "pig/bin/pig 755", "pig/conf/pig.properties 644",
|
||||
"pig/lib/ dir", "pig/lib/jython.jar 644", "pig/lib/h3/orc-core.jar 644",
|
||||
"pig/pig-0.18.0-core-h3.jar 644", "pig/LICENSE.txt 644", "pig/conf/pig-env.sh 644"),
|
||||
entries(written(archive)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pigsEnvironmentPutsTheImagesTezAheadOfTheClassPathAClusterSets(@TempDir Path folder) throws Exception {
|
||||
Path archive = Files.write(folder.resolve("pig.tar.gz"), distribution);
|
||||
|
||||
assertEquals("export PIG_CLASSPATH=\"/usr/lib/tez/*:/usr/lib/tez/lib/*${PIG_CLASSPATH:+:$PIG_CLASSPATH}\"\n",
|
||||
content(written(archive), "pig/conf/pig-env.sh"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theImagesNameHoldsTheDistributionsChecksum() {
|
||||
assertEquals("pig " + "a".repeat(64),
|
||||
new PigDistribution(List.of("https://downloads.example/pig.tar.gz"), "A".repeat(64), TIMEOUT, TIMEOUT,
|
||||
downloads).identity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void pigOnThePathRunsItsLauncherByItsOwnPath() {
|
||||
assertEquals("#!/bin/bash\nexec /usr/lib/pig/bin/pig \"$@\"\n", PigDistribution.COMMAND);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPathOutsideTheDistributionsFolderStaysOut() {
|
||||
assertEquals("pig/lib/a.jar", PigDistribution.kept("pig-0.18.0/lib/a.jar"));
|
||||
for (String path : new String[]{"/etc/passwd", "pig-0.18.0/lib/../../etc/passwd", "README.txt",
|
||||
"pig-0.18.0/lib/spark/spark-core.jar", "pig-0.18.0/lib/hadoop3-runtime/hadoop-common.jar",
|
||||
"pig-0.18.0/lib/h3/tez-api-0.10.3.jar", "pig-0.18.0/lib/protobuf-java-3.21.1.jar",
|
||||
"pig-0.18.0/docs/index.html", "pig-0.18.0/build.xml", null}) {
|
||||
assertNull(PigDistribution.kept(path), path);
|
||||
}
|
||||
}
|
||||
|
||||
private PigDistribution pig(Duration readTimeout, String... paths) throws Exception {
|
||||
List<String> urls = new ArrayList<>();
|
||||
for (String path : paths) {
|
||||
urls.add(url(path));
|
||||
}
|
||||
return new PigDistribution(urls, sha256(distribution), TIMEOUT, readTimeout, downloads);
|
||||
}
|
||||
|
||||
private String url(String path) {
|
||||
return "http://" + server.getAddress().getHostString() + ":" + server.getAddress().getPort() + path;
|
||||
}
|
||||
|
||||
// The files downloads left in their folder.
|
||||
private List<Path> leftovers() throws IOException {
|
||||
try (Stream<Path> files = Files.list(downloads)) {
|
||||
return files.toList();
|
||||
}
|
||||
}
|
||||
|
||||
// A distribution as Apache's is laid out: its own folder, what Pig runs from, and what it does not.
|
||||
private static byte[] distribution() throws IOException {
|
||||
ByteArrayOutputStream gzipped = new ByteArrayOutputStream();
|
||||
try (TarArchiveOutputStream tar = new TarArchiveOutputStream(new GZIPOutputStream(gzipped))) {
|
||||
tar.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
|
||||
directory(tar, "pig-0.18.0/");
|
||||
directory(tar, "pig-0.18.0/bin/");
|
||||
file(tar, "pig-0.18.0/bin/pig", 0755);
|
||||
file(tar, "pig-0.18.0/conf/pig.properties", 0644);
|
||||
directory(tar, "pig-0.18.0/docs/");
|
||||
file(tar, "pig-0.18.0/docs/index.html", 0644);
|
||||
directory(tar, "pig-0.18.0/lib/");
|
||||
file(tar, "pig-0.18.0/lib/jython.jar", 0644);
|
||||
file(tar, "pig-0.18.0/lib/h3/tez-api-0.10.3.jar", 0644);
|
||||
file(tar, "pig-0.18.0/lib/h3/orc-core.jar", 0644);
|
||||
file(tar, "pig-0.18.0/lib/protobuf-java-3.21.1.jar", 0644);
|
||||
file(tar, "pig-0.18.0/conf/pig-env.sh", 0644);
|
||||
file(tar, "pig-0.18.0/lib/spark/spark-core.jar", 0644);
|
||||
file(tar, "pig-0.18.0/lib/hadoop3-runtime/hadoop-common.jar", 0644);
|
||||
file(tar, "pig-0.18.0/src/org/apache/pig/Main.java", 0644);
|
||||
file(tar, "pig-0.18.0/pig-0.18.0-core-h3.jar", 0644);
|
||||
file(tar, "pig-0.18.0/LICENSE.txt", 0644);
|
||||
file(tar, "pig-0.18.0/build.xml", 0644);
|
||||
}
|
||||
return gzipped.toByteArray();
|
||||
}
|
||||
|
||||
private static void directory(TarArchiveOutputStream tar, String name) throws IOException {
|
||||
TarArchiveEntry entry = new TarArchiveEntry(name);
|
||||
entry.setIds(1000, 1000);
|
||||
tar.putArchiveEntry(entry);
|
||||
tar.closeArchiveEntry();
|
||||
}
|
||||
|
||||
private static void file(TarArchiveOutputStream tar, String name, int mode) throws IOException {
|
||||
byte[] content = name.getBytes(StandardCharsets.UTF_8);
|
||||
TarArchiveEntry entry = new TarArchiveEntry(name);
|
||||
entry.setSize(content.length);
|
||||
entry.setMode(mode);
|
||||
entry.setIds(1000, 1000);
|
||||
entry.setNames("builder", "builder");
|
||||
tar.putArchiveEntry(entry);
|
||||
tar.write(content);
|
||||
tar.closeArchiveEntry();
|
||||
}
|
||||
|
||||
private static byte[] written(Path archive) throws IOException {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
PigDistribution.write(archive, out);
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
// Each entry: its name, then "dir" or its mode in octal; every one is root's, and none is a link.
|
||||
private static List<String> entries(byte[] archive) throws IOException {
|
||||
List<String> entries = new ArrayList<>();
|
||||
try (TarArchiveInputStream in = new TarArchiveInputStream(new ByteArrayInputStream(archive))) {
|
||||
TarArchiveEntry entry;
|
||||
while ((entry = in.getNextEntry()) != null) {
|
||||
assertEquals("root:root:0:0", entry.getUserName() + ":" + entry.getGroupName() + ":"
|
||||
+ entry.getLongUserId() + ":" + entry.getLongGroupId(), entry.getName());
|
||||
assertFalse(entry.isSymbolicLink(), entry.getName());
|
||||
entries.add(entry.getName() + " " + (entry.isDirectory() ? "dir"
|
||||
: Integer.toOctalString(entry.getMode() & 0777)));
|
||||
}
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
private static String content(byte[] archive, String name) throws IOException {
|
||||
try (TarArchiveInputStream in = new TarArchiveInputStream(new ByteArrayInputStream(archive))) {
|
||||
TarArchiveEntry entry;
|
||||
while ((entry = in.getNextEntry()) != null) {
|
||||
if (entry.getName().equals(name)) {
|
||||
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String sha256(byte[] content) throws Exception {
|
||||
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(content));
|
||||
}
|
||||
}
|
||||
@@ -1115,6 +1115,55 @@ class EmrServerlessSparkRunnerTest {
|
||||
assertTrue(site.contains(",HADOOP_MAPRED_HOME=/opt/hadoop-mapreduce</value>"), site);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCommandsTezOnItsClustersYarnRunsStockTezThereAsHivesDoes() {
|
||||
String site = EmrServerlessSparkRunner.tezSite(stepJob(Map.of()).onStorage(ON_YARN), AWS_ENVIRONMENT);
|
||||
|
||||
for (String setting : List.of("tez.local.mode</name><value>false",
|
||||
"yarn.resourcemanager.hostname</name><value>ip-10-0-0-1.ec2.internal",
|
||||
"tez.framework.client</name><value>org.apache.tez.client.TezYarnClient",
|
||||
"tez.am.yarn.scheduler.class</name><value>org.apache.tez.dag.app.rm.YarnTaskSchedulerService",
|
||||
"tez.am.shuffle.auxiliary-service.id</name><value>mapreduce_shuffle",
|
||||
"tez.lib.uris</name><value>file:///usr/lib/tez/,file:///usr/lib/tez/lib/",
|
||||
"tez.use.cluster.hadoop-libs</name><value>false",
|
||||
"tez.am.resource.memory.mb</name><value>1024",
|
||||
"tez.task.resource.memory.mb</name><value>768",
|
||||
"tez.runtime.intermediate-output.should-compress</name><value>false")) {
|
||||
assertTrue(site.contains("<name>" + setting + "</value>"), setting + " in " + site);
|
||||
}
|
||||
// Without Hive's jar or home, which a command's Tez does not run.
|
||||
assertTrue(site.contains("<name>tez.cluster.additional.classpath.prefix</name><value>$PWD/*:/usr/lib/tez/*:"
|
||||
+ "/usr/lib/tez/lib/*:/usr/lib/hadoop-mapreduce/*:/usr/lib/hadoop-mapreduce/lib/*:/usr/lib/hadoop/*:"
|
||||
+ "/usr/lib/hadoop/lib/*:/usr/lib/hadoop-hdfs/*:/usr/lib/hadoop-hdfs/lib/*:/usr/lib/hadoop-yarn/*:"
|
||||
+ "/usr/lib/hadoop-yarn/lib/*:/usr/lib/hadoop-lzo/lib/*</value>"), site);
|
||||
String environment = "</name><value>JDK_JAVA_OPTIONS=" + EmrServerlessSparkRunner.yarnJavaOptions()
|
||||
+ ",TEZ_HOME=/usr/lib/tez,AWS_ACCESS_KEY_ID=ASIASTEP,AWS_ENDPOINT_URL=http://floci:4566</value>";
|
||||
assertTrue(site.contains("<name>tez.am.launch.env" + environment), site);
|
||||
assertTrue(site.contains("<name>tez.task.launch.env" + environment), site);
|
||||
assertFalse(site.contains("hive"), site);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCommandsTezWhereThereIsNoYarnRunsInLocalModeWithoutTheJarsAContainerIsGiven() {
|
||||
String site = EmrServerlessSparkRunner.tezSite(stepJob(Map.of()).onStorage(STORAGE), List.of());
|
||||
|
||||
assertEquals("<property><name>tez.local.mode</name><value>true</value></property>\n"
|
||||
+ "<property><name>tez.ignore.lib.uris</name><value>true</value></property>\n"
|
||||
+ "<property><name>tez.runtime.optimize.local.fetch</name><value>true</value></property>", site);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCommandOnItsClusterGetsItsTezSite() {
|
||||
ContainerBuilder builder = mock(ContainerBuilder.class);
|
||||
ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
|
||||
when(builder.newContainer(anyString())).thenReturn(spec);
|
||||
|
||||
runner(builder).run(commandJob(List.of("pig", "-e", "fs -ls /"), Map.of(), STORAGE), progress);
|
||||
|
||||
verify(spec).withEnv(eq("FLOCI_TEZ_SITE"), argThat(site -> site.contains(
|
||||
"<name>tez.local.mode</name><value>true</value>")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClustersMapredSiteReplacesFlocisSettingsOnYarn() {
|
||||
String site = EmrServerlessSparkRunner.mapredSite(hadoopJob(null,
|
||||
|
||||
Reference in new issue
Block a user