mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
test(emr): run steps and job runs through the Docker runner (#7349)
No EMR test ran a step or a job run through Floci's Docker runner: the runner's wrappers and settings were unit tested and run by hand in the images. EmrDockerRunnerDockerIntegrationTest, a Docker-gated @QuarkusTest on ContainerDataPlaneProfile (which now sets both runner modes to docker), runs them for real in the emr-7.5.0 image, reaching Floci's S3 from the container: - a hadoop-streaming word count step, its mapper and reducer from S3, writing its counts to S3; - the same word count as a custom JAR at EMR's streaming jar path; - s3-dist-cp from S3 into the cluster's HDFS and back; - a cluster's spark-env export, read by a Spark step's driver; - an EMR Serverless run on the user guide's virtual environment recipe, spark.archives with #environment and the driver's and executors' Python in it, from an archive that needs no package index. EmrRequests.awaitStep and EmrServerlessRequests' createSparkApplication, startJobRun and awaitJobRun are shared helpers, each wait checking that its call answered 200 before reading the state, and RetryingTarCopier.putEntry, pulled out of singleFileTar, writes the archive's entries. The CI prefetch queues the 3.5 GB image for the shard that runs the class, last, behind the Lambda runtimes, and the prefetch results step no longer warns about an EMR Serverless image on ECR Public, the only place AWS publishes them.
This commit is contained in:
1 parent
cfd7e83776
commit
b63e4a5bb9
7 files changed
+358
-15
No files matched your search
+259
@@ -0,0 +1,259 @@
|
||||
package io.github.hectorvent.floci.services.emr;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.docker.RetryingTarCopier;
|
||||
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.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.Response;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
|
||||
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
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.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static io.github.hectorvent.floci.testing.EmrRequests.awaitStep;
|
||||
import static io.github.hectorvent.floci.testing.EmrRequests.emr;
|
||||
import static io.github.hectorvent.floci.testing.EmrServerlessRequests.awaitJobRun;
|
||||
import static io.github.hectorvent.floci.testing.EmrServerlessRequests.createSparkApplication;
|
||||
import static io.github.hectorvent.floci.testing.EmrServerlessRequests.startJobRun;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
|
||||
/**
|
||||
* EMR steps and EMR Serverless job runs through Floci's Docker runner for real: a cluster in the {@code docker}
|
||||
* runner mode runs each step, and an application each job run, in a container of the release's EMR Serverless image,
|
||||
* which reaches Floci's S3 from there. The cached {@code emr-7.5.0} image keeps a local run from pulling; CI pulls it
|
||||
* (3.5 GB) the first time.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(ContainerDataPlaneProfile.class)
|
||||
class EmrDockerRunnerDockerIntegrationTest {
|
||||
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String WORDS = "a b a\nc b a\n";
|
||||
private static final Map<String, Integer> WORD_COUNTS = Map.of("a", 3, "b", 2, "c", 1);
|
||||
private static final String MAPPER = """
|
||||
import sys
|
||||
for line in sys.stdin:
|
||||
for word in line.split():
|
||||
print(word + "\\t1")
|
||||
""";
|
||||
private static final String REDUCER = """
|
||||
import sys
|
||||
counts = {}
|
||||
for line in sys.stdin:
|
||||
word, count = line.rstrip("\\n").split("\\t")
|
||||
counts[word] = counts.get(word, 0) + int(count)
|
||||
for word in sorted(counts):
|
||||
print(word + "\\t" + str(counts[word]))
|
||||
""";
|
||||
|
||||
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 Docker runner tests");
|
||||
s3 = AwsTestClients.create(S3Client.builder().forcePathStyle(true), "000000000000", Region.US_EAST_1);
|
||||
bucket = "emr-docker-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
s3.createBucket(request -> request.bucket(bucket));
|
||||
put("in/words.txt", WORDS);
|
||||
put("side/mapper.py", MAPPER);
|
||||
put("side/reducer.py", REDUCER);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void terminateCluster() {
|
||||
if (clusterId != null) {
|
||||
emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + clusterId + "\"]}").then().statusCode(200);
|
||||
}
|
||||
if (s3 != null) {
|
||||
s3.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStreamingWordCountStepReadsItsInputAndWritesItsCountsInFlocisS3() {
|
||||
startCluster("[]");
|
||||
|
||||
assertEquals("COMPLETED", runStep("command-runner.jar", "hadoop-streaming",
|
||||
"-files", side("mapper.py", "reducer.py"), "-mapper", "python3 mapper.py",
|
||||
"-reducer", "python3 reducer.py", "-input", s3Uri("in/"), "-output", s3Uri("out/")));
|
||||
assertEquals(WORD_COUNTS, counts("out/"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCustomJarAtEmrsStreamingJarPathRunsItsWordCountInTheDriver() {
|
||||
startCluster("[]");
|
||||
|
||||
assertEquals("COMPLETED", runStep("/usr/lib/hadoop-mapreduce/hadoop-streaming.jar",
|
||||
"-files", side("mapper.py", "reducer.py"), "-mapper", "python3 mapper.py",
|
||||
"-reducer", "python3 reducer.py", "-input", s3Uri("in/"), "-output", s3Uri("jar-out/")));
|
||||
assertEquals(WORD_COUNTS, counts("jar-out/"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void s3DistCpCopiesFromFlocisS3IntoTheClustersHdfsAndBack() {
|
||||
startCluster("[]");
|
||||
|
||||
assertEquals("COMPLETED", runStep("command-runner.jar", "s3-dist-cp",
|
||||
"--src", s3Uri("in/"), "--dest", "hdfs:///input/"));
|
||||
assertEquals("COMPLETED", runStep("command-runner.jar", "s3-dist-cp",
|
||||
"--src", "hdfs:///input/", "--dest", s3Uri("copied/")));
|
||||
assertEquals(WORDS,
|
||||
s3.getObjectAsBytes(request -> request.bucket(bucket).key("copied/words.txt")).asUtf8String());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClustersSparkEnvExportReachesItsSparkStepsDriver() {
|
||||
put("side/env.py", """
|
||||
import os, sys
|
||||
from pyspark.sql import SparkSession
|
||||
spark = SparkSession.builder.getOrCreate()
|
||||
value = os.environ.get("FLOCI_PROBE", "unset")
|
||||
spark.createDataFrame([(value,)], ["value"]).coalesce(1).write.text(sys.argv[1])
|
||||
""");
|
||||
startCluster("""
|
||||
[{"Classification": "spark-env", "Configurations": [
|
||||
{"Classification": "export", "Properties": {"FLOCI_PROBE": "from spark-env"}}]}]
|
||||
""");
|
||||
|
||||
assertEquals("COMPLETED", runStep("command-runner.jar", "spark-submit",
|
||||
s3Uri("side/env.py"), s3Uri("env-out/")));
|
||||
assertEquals("from spark-env\n", partFiles("env-out/"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmrServerlessRunsPythonIsTheOneInTheArchiveItsSparkArchivesUnpack() throws IOException {
|
||||
put("side/job.py", """
|
||||
import os, sys
|
||||
import floci_probe
|
||||
from pyspark.sql import SparkSession
|
||||
spark = SparkSession.builder.getOrCreate()
|
||||
folder = os.path.basename(os.path.dirname(os.path.dirname(floci_probe.__file__)))
|
||||
spark.createDataFrame([(floci_probe.VALUE + " " + folder,)], ["value"]) \\
|
||||
.coalesce(1).write.text(sys.argv[1])
|
||||
""");
|
||||
s3.putObject(request -> request.bucket(bucket).key("envs/pyspark_venv.tar.gz"),
|
||||
RequestBody.fromBytes(environmentArchive()));
|
||||
String applicationId = createSparkApplication(REGION, "emr-7.5.0");
|
||||
// The user guide's recipe for a virtual environment: the archive, and the driver's and executors' Python in it.
|
||||
String python = "./environment/bin/python";
|
||||
ObjectNode run = JSON.createObjectNode().put("clientToken", UUID.randomUUID().toString())
|
||||
.put("executionRoleArn", "arn:aws:iam::000000000000:role/emr-serverless-job");
|
||||
ObjectNode sparkSubmit = run.putObject("jobDriver").putObject("sparkSubmit")
|
||||
.put("entryPoint", s3Uri("side/job.py"))
|
||||
.put("sparkSubmitParameters", "--conf spark.archives=" + s3Uri("envs/pyspark_venv.tar.gz#environment")
|
||||
+ " --conf spark.emr-serverless.driverEnv.PYSPARK_DRIVER_PYTHON=" + python
|
||||
+ " --conf spark.emr-serverless.driverEnv.PYSPARK_PYTHON=" + python
|
||||
+ " --conf spark.executorEnv.PYSPARK_PYTHON=" + python);
|
||||
sparkSubmit.putArray("entryPointArguments").add(s3Uri("venv-out/"));
|
||||
String jobRunId = startJobRun(REGION, applicationId, run.toString());
|
||||
|
||||
Response ended = awaitJobRun(REGION, applicationId, jobRunId);
|
||||
|
||||
assertEquals("SUCCESS", ended.jsonPath().getString("jobRun.state"));
|
||||
assertEquals("from the archive environment\n", partFiles("venv-out/"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A stand-in for the guide's packed virtual environment that needs no package index: its {@code bin/python}
|
||||
* runs the image's Python with the archive's own {@code lib} on the path, where the module the job imports is.
|
||||
*/
|
||||
private static byte[] environmentArchive() throws IOException {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
try (TarArchiveOutputStream tar = RetryingTarCopier.newTarStream(new GzipCompressorOutputStream(out))) {
|
||||
RetryingTarCopier.putEntry(tar, "bin/python", """
|
||||
#!/bin/sh
|
||||
here="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
PYTHONPATH="$here/lib${PYTHONPATH:+:$PYTHONPATH}" exec /usr/bin/python3 "$@"
|
||||
""".getBytes(StandardCharsets.UTF_8), 0755);
|
||||
RetryingTarCopier.putEntry(tar, "lib/floci_probe.py",
|
||||
"VALUE = \"from the archive\"\n".getBytes(StandardCharsets.UTF_8), 0644);
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
/** A one-primary cluster of the cached release, with {@code configurations} as its Configurations. */
|
||||
private void startCluster(String configurations) {
|
||||
clusterId = emr("RunJobFlow", "{\"Name\":\"docker-runner\",\"ReleaseLabel\":\"emr-7.5.0\","
|
||||
+ "\"Applications\":[{\"Name\":\"Hadoop\"},{\"Name\":\"Spark\"}],"
|
||||
+ "\"Configurations\":" + configurations + ","
|
||||
+ "\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true,\"InstanceGroups\":[{\"Name\":\"primary\","
|
||||
+ "\"InstanceRole\":\"MASTER\",\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":1}]}}")
|
||||
.then().statusCode(200).extract().jsonPath().getString("JobFlowId");
|
||||
}
|
||||
|
||||
/** Adds one step to the cluster and returns the state it ended in. */
|
||||
private String runStep(String jar, String... args) {
|
||||
ObjectNode request = JSON.createObjectNode().put("JobFlowId", clusterId);
|
||||
ObjectNode step = request.putArray("Steps").addObject().put("Name", jar).put("ActionOnFailure", "CONTINUE");
|
||||
ObjectNode hadoopJarStep = step.putObject("HadoopJarStep").put("Jar", jar);
|
||||
List.of(args).forEach(hadoopJarStep.putArray("Args")::add);
|
||||
String stepId = emr("AddJobFlowSteps", request.toString())
|
||||
.then().statusCode(200).extract().jsonPath().getString("StepIds[0]");
|
||||
return awaitStep(clusterId, stepId).jsonPath().getString("Step.Status.State");
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
private String side(String... names) {
|
||||
return Stream.of(names).map(name -> s3Uri("side/" + name)).collect(Collectors.joining(","));
|
||||
}
|
||||
|
||||
/** The word counts a streaming job wrote, one {@code word<TAB>count} line each, over all its part files. */
|
||||
private Map<String, Integer> counts(String prefix) {
|
||||
Map<String, Integer> counts = new TreeMap<>();
|
||||
for (String line : partFiles(prefix).split("\n")) {
|
||||
if (!line.isBlank()) {
|
||||
String[] fields = line.split("\t");
|
||||
counts.merge(fields[0], Integer.parseInt(fields[1].trim()), Integer::sum);
|
||||
}
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
|
||||
/** What a job wrote under {@code prefix}: its part files, in key order, one after the other. */
|
||||
private String partFiles(String prefix) {
|
||||
StringBuilder text = new StringBuilder();
|
||||
for (S3Object object : s3.listObjectsV2(request -> request.bucket(bucket).prefix(prefix)).contents()) {
|
||||
if (object.key().substring(prefix.length()).startsWith("part-")) {
|
||||
text.append(s3.getObjectAsBytes(request -> request.bucket(bucket).key(object.key())).asUtf8String());
|
||||
}
|
||||
}
|
||||
return text.toString();
|
||||
}
|
||||
}
|
||||
@@ -18,13 +18,17 @@ import java.util.Map;
|
||||
* <li>{@code floci.services.eks.imds=true} and {@code floci.services.eks.imds-pod-network=true}
|
||||
* program the link-local IMDS endpoint into a cluster's container, for the node and for its pods.
|
||||
* {@code EksImdsDockerIntegrationTest} relies on them.</li>
|
||||
* <li>{@code floci.services.emr.runner-mode=docker} and {@code floci.services.emrserverless.runner-mode=docker}
|
||||
* run a cluster's steps and an EMR Serverless application's job runs in containers of the release's image.
|
||||
* {@code EmrDockerRunnerDockerIntegrationTest} relies on them.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>Each override is inert for the other class. An InfluxDB container only starts when a DB
|
||||
* <p>Each override is inert for the other classes. An InfluxDB container only starts when a DB
|
||||
* instance is created, which the IMDS test never does. The IMDS settings only act when a cluster's
|
||||
* container starts, and the test defaults keep EKS mocked, so only {@code EksImdsDockerIntegrationTest},
|
||||
* which configures the endpoint on its own container, reaches them. The metadata server it starts
|
||||
* stays up for the Timestream test, on a port that test does not use.
|
||||
* stays up for the Timestream test, on a port that test does not use. The EMR runner modes only act
|
||||
* when a cluster runs a step or an application runs a job, which neither of the other classes does.
|
||||
*
|
||||
* <p>The ELBv2 data-plane classes stay on {@link RealElbV2DataPlaneProfile}: one of them,
|
||||
* {@code ElbV2WebSocketIntegrationTest}, injects a spy, and a class that does is not merged into
|
||||
@@ -39,6 +43,8 @@ public class ContainerDataPlaneProfile implements QuarkusTestProfile {
|
||||
"floci.services.timestream-influxdb.host-port-base", "18186",
|
||||
"floci.services.timestream-influxdb.host-port-max", "18285",
|
||||
"floci.services.eks.imds", "true",
|
||||
"floci.services.eks.imds-pod-network", "true");
|
||||
"floci.services.eks.imds-pod-network", "true",
|
||||
"floci.services.emr.runner-mode", "docker",
|
||||
"floci.services.emrserverless.runner-mode", "docker");
|
||||
}
|
||||
}
|
||||
@@ -2,10 +2,19 @@ package io.github.hectorvent.floci.testing;
|
||||
|
||||
import io.restassured.response.Response;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Set;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
|
||||
/** One EMR JSON-protocol call, in the default Region or a named one. */
|
||||
public final class EmrRequests {
|
||||
|
||||
private static final Set<String> UNFINISHED_STEP_STATES = Set.of("PENDING", "RUNNING");
|
||||
private static final Duration STEP_TIMEOUT = Duration.ofMinutes(5);
|
||||
private static final Duration POLL_INTERVAL = Duration.ofMillis(500);
|
||||
|
||||
private EmrRequests() {}
|
||||
|
||||
public static Response emr(String action, String body) {
|
||||
@@ -21,4 +30,21 @@ public final class EmrRequests {
|
||||
.header("X-Amz-Target", "ElasticMapReduce." + action)
|
||||
.body(body).when().post("/");
|
||||
}
|
||||
|
||||
/**
|
||||
* Polls DescribeStep until the step leaves PENDING and RUNNING and returns that response, whatever the state it
|
||||
* ended in: asserting which one is the caller's business. A DescribeStep that fails ends the wait there. A step in
|
||||
* the {@code docker} runner mode starts a container of the release's image, so it is given minutes rather than
|
||||
* seconds.
|
||||
*/
|
||||
public static Response awaitStep(String clusterId, String stepId) {
|
||||
return await("step " + stepId + " to leave PENDING and RUNNING")
|
||||
.atMost(STEP_TIMEOUT)
|
||||
.pollInterval(POLL_INTERVAL)
|
||||
.until(() -> emr("DescribeStep",
|
||||
"{\"ClusterId\":\"" + clusterId + "\",\"StepId\":\"" + stepId + "\"}")
|
||||
.then().statusCode(200).extract().response(),
|
||||
response -> !UNFINISHED_STEP_STATES.contains(
|
||||
response.jsonPath().getString("Step.Status.State")));
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,24 @@
|
||||
package io.github.hectorvent.floci.testing;
|
||||
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
|
||||
/** One EMR Serverless REST JSON request, signed for a named Region. */
|
||||
public final class EmrServerlessRequests {
|
||||
|
||||
private static final Set<String> FINAL_JOB_RUN_STATES = Set.of("SUCCESS", "FAILED", "CANCELLED");
|
||||
private static final Duration JOB_RUN_TIMEOUT = Duration.ofMinutes(5);
|
||||
private static final Duration POLL_INTERVAL = Duration.ofMillis(500);
|
||||
|
||||
private EmrServerlessRequests() {}
|
||||
|
||||
public static RequestSpecification emrServerless(String region) {
|
||||
@@ -18,6 +28,39 @@ public final class EmrServerlessRequests {
|
||||
.contentType("application/json");
|
||||
}
|
||||
|
||||
/** Creates a SPARK application on {@code releaseLabel} in {@code region} and returns its id. */
|
||||
public static String createSparkApplication(String region, String releaseLabel) {
|
||||
return emrServerless(region)
|
||||
.body("""
|
||||
{"name": "app-%s", "releaseLabel": "%s", "type": "SPARK", "clientToken": "%s"}
|
||||
""".formatted(UUID.randomUUID(), releaseLabel, UUID.randomUUID()))
|
||||
.when().post("/applications")
|
||||
.then().statusCode(200).extract().path("applicationId");
|
||||
}
|
||||
|
||||
/** Starts a job run of {@code body} on the application and returns its id. */
|
||||
public static String startJobRun(String region, String applicationId, String body) {
|
||||
return emrServerless(region).body(body)
|
||||
.when().post("/applications/" + applicationId + "/jobruns")
|
||||
.then().statusCode(200).extract().path("jobRunId");
|
||||
}
|
||||
|
||||
/**
|
||||
* Polls GetJobRun until the run is SUCCESS, FAILED or CANCELLED and returns that response, whatever the state:
|
||||
* asserting which one is the caller's business. A GetJobRun that fails ends the wait there. A run in the
|
||||
* {@code docker} runner mode starts a container of the release's image, so it is given minutes rather than
|
||||
* seconds.
|
||||
*/
|
||||
public static Response awaitJobRun(String region, String applicationId, String jobRunId) {
|
||||
return await("job run " + jobRunId + " to end")
|
||||
.atMost(JOB_RUN_TIMEOUT)
|
||||
.pollInterval(POLL_INTERVAL)
|
||||
.until(() -> emrServerless(region).when()
|
||||
.get("/applications/" + applicationId + "/jobruns/" + jobRunId)
|
||||
.then().statusCode(200).extract().response(),
|
||||
response -> FINAL_JOB_RUN_STATES.contains(response.jsonPath().getString("jobRun.state")));
|
||||
}
|
||||
|
||||
/**
|
||||
* The tagging path for an ARN, sent as the SDK sends it: one path segment with ':' and '/'
|
||||
* percent-encoded. Send it with {@code urlEncodingEnabled(false)}, or it is encoded twice.
|
||||
|
||||
Reference in new issue
Block a user