From b63e4a5bb907e06f944e6c85589a6db385e49a56 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Mon, 2 Nov 2026 19:31:59 -0400 Subject: [PATCH] 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. --- .github/ci/prefetch-images.sh | 7 +- .github/workflows/ci.yml | 8 +- .../core/common/docker/RetryingTarCopier.java | 18 +- .../EmrDockerRunnerDockerIntegrationTest.java | 259 ++++++++++++++++++ .../testing/ContainerDataPlaneProfile.java | 12 +- .../hectorvent/floci/testing/EmrRequests.java | 26 ++ .../floci/testing/EmrServerlessRequests.java | 43 +++ 7 files changed, 358 insertions(+), 15 deletions(-) create mode 100644 src/test/java/io/github/hectorvent/floci/services/emr/EmrDockerRunnerDockerIntegrationTest.java diff --git a/.github/ci/prefetch-images.sh b/.github/ci/prefetch-images.sh index 76f1210858..25f56a4419 100755 --- a/.github/ci/prefetch-images.sh +++ b/.github/ci/prefetch-images.sh @@ -83,8 +83,8 @@ starts ContainerCaBundleDockerIntegrationTest && [ -n "$CORRETTO_8_IMAGE" ] && p # The Firelens test names the log router image itself rather than taking it from config. FLUENT_BIT_IMAGE="$(test_image FLUENT_BIT)" starts EcsContainerManagerFirelensDockerIntegrationTest && [ -n "$FLUENT_BIT_IMAGE" ] && pull "$FLUENT_BIT_IMAGE" -# ECR Public images, in queue order: the Lambda runtimes by size. They are the only images left -# on ECR Public; everything Docker Hub also carries is pulled from there (see TestImages). +# ECR Public images, in queue order: the Lambda runtimes by size, then EMR's. They are the only images +# left on ECR Public; everything Docker Hub also carries is pulled from there (see TestImages). # Lambda runtimes, measured from a full four-shard run by pairing each ImageCacheService # "Pulling image" / "Image already present locally" line with the class that logged it. # nodejs:20 is the runtime the API Gateway, ELBv2 and Lambda integration tests resolve and every @@ -94,6 +94,9 @@ grep -qE '/apigateway/|/apigatewayv2/|/lambda/' "$SHARD_FILE" && ecr public.ecr. grep -qE '/lambdaweb/' "$SHARD_FILE" && ecr public.ecr.aws/lambda/nodejs:24 starts SwfLambdaIntegrationTest && ecr public.ecr.aws/lambda/python:3.12 starts ElbV2LambdaTargetDataPlaneIntegrationTest && ecr public.ecr.aws/lambda/python:3.14 +# EmrDockerRunnerDockerIntegrationTest runs EMR steps and EMR Serverless job runs in the emr-7.5.0 image the runner's +# default template names (EmrServerlessSparkRunner), 3.5 GB, so it is queued last, behind the Lambda runtimes. +starts EmrDockerRunnerDockerIntegrationTest && ecr public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest # package token in shard.txt -> images its tests are known to launch # (measured inline pulls; update alongside image-catalog changes) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 34ff14c093..0be88660d8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -143,8 +143,8 @@ jobs: # here (after an early exit) has no result line yet, so list it. The # prefetch is best-effort by design, so a key that no longer matches a # class, a pin the script could not read, or an image back on ECR Public - # that Docker Hub also carries (only the Lambda runtimes belong there) is - # an annotation, not a failure. + # that Docker Hub also carries (only the Lambda runtimes and the EMR + # Serverless images belong there) is an annotation, not a failure. - name: Image prefetch results if: always() run: | @@ -153,8 +153,8 @@ jobs: grep -E 'stale prefetch key|prefetch skipped' prefetch-images.log 2>/dev/null \ | sed 's/^/::warning title=prefetch-images.sh::/' || true grep -E '(prefetched|prefetch failed) public\.ecr\.aws/' prefetch-images.log 2>/dev/null \ - | grep -vE 'public\.ecr\.aws/lambda/' \ - | sed 's/^/::warning title=prefetch-images.sh::not a Lambda runtime, pull it from Docker Hub: /' || true + | grep -vE 'public\.ecr\.aws/(lambda|emr-serverless)/' \ + | sed 's/^/::warning title=prefetch-images.sh::pull it from Docker Hub, not ECR Public: /' || true # Save from main only, and from shard 1 only. Actions caches are ref-scoped: # a pull_request run's write lands in refs/pull/N/merge where no other PR can diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/RetryingTarCopier.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/RetryingTarCopier.java index 7046916776..ac2ecf9caa 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/docker/RetryingTarCopier.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/RetryingTarCopier.java @@ -189,12 +189,7 @@ public final class RetryingTarCopier { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); try (TarArchiveOutputStream tar = newTarStream(out)) { - TarArchiveEntry entry = new TarArchiveEntry(entryName); - entry.setSize(content.length); - entry.setMode(mode); - tar.putArchiveEntry(entry); - tar.write(content); - tar.closeArchiveEntry(); + putEntry(tar, entryName, content, mode); } return out.toByteArray(); } catch (IOException e) { @@ -202,6 +197,17 @@ public final class RetryingTarCopier { } } + /** Writes {@code content} as the file {@code entryName}, with {@code mode}, such as 0755 for a script. */ + public static void putEntry(TarArchiveOutputStream tar, String entryName, byte[] content, int mode) + throws IOException { + TarArchiveEntry entry = new TarArchiveEntry(entryName); + entry.setSize(content.length); + entry.setMode(mode); + tar.putArchiveEntry(entry); + tar.write(content); + tar.closeArchiveEntry(); + } + /** GNU long names + star big numbers so any path length and file size survive the archive. */ public static TarArchiveOutputStream newTarStream(OutputStream out) { TarArchiveOutputStream tar = new TarArchiveOutputStream(out); diff --git a/src/test/java/io/github/hectorvent/floci/services/emr/EmrDockerRunnerDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/emr/EmrDockerRunnerDockerIntegrationTest.java new file mode 100644 index 0000000000..4e1050947d --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/emr/EmrDockerRunnerDockerIntegrationTest.java @@ -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 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 wordcount} line each, over all its part files. */ + private Map counts(String prefix) { + Map 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(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/testing/ContainerDataPlaneProfile.java b/src/test/java/io/github/hectorvent/floci/testing/ContainerDataPlaneProfile.java index f0cea61cc6..3ca99d97a3 100644 --- a/src/test/java/io/github/hectorvent/floci/testing/ContainerDataPlaneProfile.java +++ b/src/test/java/io/github/hectorvent/floci/testing/ContainerDataPlaneProfile.java @@ -18,13 +18,17 @@ import java.util.Map; *
  • {@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.
  • + *
  • {@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.
  • * * - *

    Each override is inert for the other class. An InfluxDB container only starts when a DB + *

    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. * *

    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"); } } diff --git a/src/test/java/io/github/hectorvent/floci/testing/EmrRequests.java b/src/test/java/io/github/hectorvent/floci/testing/EmrRequests.java index f16f262530..d7498e966a 100644 --- a/src/test/java/io/github/hectorvent/floci/testing/EmrRequests.java +++ b/src/test/java/io/github/hectorvent/floci/testing/EmrRequests.java @@ -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 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"))); + } } diff --git a/src/test/java/io/github/hectorvent/floci/testing/EmrServerlessRequests.java b/src/test/java/io/github/hectorvent/floci/testing/EmrServerlessRequests.java index 26cd7a2374..235f07ab41 100644 --- a/src/test/java/io/github/hectorvent/floci/testing/EmrServerlessRequests.java +++ b/src/test/java/io/github/hectorvent/floci/testing/EmrServerlessRequests.java @@ -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 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.