diff --git a/.github/ci/prefetch-images.sh b/.github/ci/prefetch-images.sh index 9a41f458e0..fdf8e18a07 100755 --- a/.github/ci/prefetch-images.sh +++ b/.github/ci/prefetch-images.sh @@ -113,14 +113,17 @@ 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; -# EmrHiveStepsDockerIntegrationTest runs a cluster's other steps in it, and the nightly -# EmrServerlessCustomImageNightlyIntegrationTest builds its custom image on it. +# EmrHiveStepsDockerIntegrationTest runs a cluster's other steps in it. Of the nightly checks, +# EmrServerlessCustomImageNightlyIntegrationTest builds its custom image on it, and +# EmrFlociContainerNightlyIntegrationTest runs a cluster's steps in it from Floci in a container. starts EmrDockerRunnerDockerIntegrationTest EmrHiveStepsDockerIntegrationTest EmrServerlessCustomImageNightlyIntegrationTest \ + EmrFlociContainerNightlyIntegrationTest \ && ecr public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest # EmrServerlessHiveDockerIntegrationTest runs EMR Serverless Hive job runs, and EmrHiveStepsDockerIntegrationTest EMR # Hive steps, in the emr-7.5.0 Hive image the runner's default Hive template names, 2.7 GB; every EMR cluster runs its -# HDFS in it, EmrDockerRunnerDockerIntegrationTest's included. +# HDFS in it, EmrDockerRunnerDockerIntegrationTest's and the nightly EmrFlociContainerNightlyIntegrationTest's included. starts EmrServerlessHiveDockerIntegrationTest EmrHiveStepsDockerIntegrationTest EmrDockerRunnerDockerIntegrationTest \ + EmrFlociContainerNightlyIntegrationTest \ && ecr public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest # package token in shard.txt -> images its tests are known to launch diff --git a/.github/workflows/nightly-checks.yml b/.github/workflows/nightly-checks.yml index 547075c6f3..7bff687554 100644 --- a/.github/workflows/nightly-checks.yml +++ b/.github/workflows/nightly-checks.yml @@ -87,6 +87,14 @@ jobs: if: steps.list.outputs.count != '0' run: ./mvnw test-compile -B + # A check that runs Floci in a container, as a user's Docker setup does, runs this image: this commit's own + # build, made from the compiled application as docker/Dockerfile.jvm-package describes. + - name: Build the Floci image + if: steps.list.outputs.count != '0' + run: | + ./mvnw package -B -q -DskipTests + docker build -q -f docker/Dockerfile.jvm-package -t floci/floci:nightly-check . + # nightly.txt is never empty here: an empty includesFile would make surefire run the whole suite. - name: Run the nightly checks if: steps.list.outputs.count != '0' @@ -95,6 +103,7 @@ jobs: -Dsurefire.includesFile="$GITHUB_WORKSPACE/nightly.txt" -Dsurefire.failIfNoTests=true -Dnightly.checks.enabled=true + -Dnightly.checks.floci-image=floci/floci:nightly-check - name: Image prefetch results if: always() && steps.list.outputs.count != '0' diff --git a/src/test/java/io/floci/aws/services/emr/EmrDockerRunnerDockerIntegrationTest.java b/src/test/java/io/floci/aws/services/emr/EmrDockerRunnerDockerIntegrationTest.java index 277397c89c..5960f9486e 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrDockerRunnerDockerIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrDockerRunnerDockerIntegrationTest.java @@ -12,6 +12,7 @@ import io.floci.aws.core.common.docker.RetryingTarCopier; 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; @@ -487,12 +488,7 @@ class EmrDockerRunnerDockerIntegrationTest { /** 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]"); + String stepId = EmrRequests.addStep(clusterId, jar, jar, args); return awaitStep(clusterId, stepId).jsonPath().getString("Step.Status.State"); } diff --git a/src/test/java/io/floci/aws/services/emr/EmrFlociContainerNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/emr/EmrFlociContainerNightlyIntegrationTest.java new file mode 100644 index 0000000000..03b786f969 --- /dev/null +++ b/src/test/java/io/floci/aws/services/emr/EmrFlociContainerNightlyIntegrationTest.java @@ -0,0 +1,299 @@ +package io.floci.aws.services.emr; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.async.ResultCallback; +import com.github.dockerjava.api.command.InspectContainerResponse; +import com.github.dockerjava.api.exception.NotFoundException; +import com.github.dockerjava.api.exception.NotModifiedException; +import com.github.dockerjava.api.model.Bind; +import com.github.dockerjava.api.model.Container; +import com.github.dockerjava.api.model.ExposedPort; +import com.github.dockerjava.api.model.Frame; +import com.github.dockerjava.api.model.HostConfig; +import com.github.dockerjava.api.model.PortBinding; +import com.github.dockerjava.api.model.Ports; +import com.github.dockerjava.api.model.Volume; +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.DockerAvailability; +import io.floci.aws.testing.EmrRequests; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.floci.aws.testing.S3TestClients; +import io.floci.aws.testing.TestDockerClients; +import io.floci.aws.testutil.FreePorts; +import io.restassured.RestAssured; +import org.junit.jupiter.api.AfterEach; +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.function.Executable; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; + +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +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 org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * An EMR cluster with Hive and Spark, run by Floci in a container of its own with the Docker socket, as a user's + * Docker setup runs it. The cluster's nodes are the Floci container's siblings on a network of their own, so Floci's + * container joins that network for the cluster's metastore service to reach Floci's S3, and leaves it once the cluster + * has ended. A Hive step makes tables over rows in S3, a Spark step reads one through the metastore and makes another, + * and a later Hive step reads both. + * + *

A nightly check: it runs the image {@code nightly.checks.floci-image} names, which the nightly workflow builds from the + * pull request's own code, and pulls the release's Spark and Hive images. + */ +@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true") +// Bounded waits: three steps of up to five minutes each and five minutes for the cluster to end, past the default two. +@Timeout(value = 20, unit = TimeUnit.MINUTES) +class EmrFlociContainerNightlyIntegrationTest { + + private static final ObjectMapper JSON = new ObjectMapper(); + private static final String ACCOUNT = "000000000000"; + private static final int FLOCI_PORT = 4566; + private static final Set TERMINATED = Set.of("TERMINATED", "TERMINATED_WITH_ERRORS"); + private static final Duration FLOCI_START = Duration.ofMinutes(3); + private static final Duration CLUSTER_END = Duration.ofMinutes(5); + + private final List cleanup = new ArrayList<>(); + private DockerClient docker; + private String flociContainer; + private S3Client s3; + private String bucket; + private String clusterId; + + // Floci's health check alone may take FLOCI_START, three minutes. + @BeforeEach + @Timeout(value = 4, unit = TimeUnit.MINUTES) + void startFloci() throws InterruptedException, IOException { + // Enabled, the check needs both: without either it fails rather than pass having run nothing. + String image = System.getProperty("nightly.checks.floci-image"); + assertNotNull(image, "the nightly check needs -Dnightly.checks.floci-image naming the Floci image to run"); + assertTrue(DockerAvailability.isAvailable(), "the nightly check needs a Docker daemon"); + docker = TestDockerClients.local(); + cleanup.add(() -> { + try { + docker.close(); + } catch (IOException e) { + throw new IllegalStateException(e); + } + }); + + int hostPort = FreePorts.anyInterfacePort(); + ExposedPort flociPort = ExposedPort.tcp(FLOCI_PORT); + flociContainer = docker.createContainerCmd(image) + .withName("floci-nightly-emr-" + UUID.randomUUID().toString().substring(0, 8)) + .withEnv("FLOCI_SERVICES_EMR_RUNNER_MODE=docker") + .withExposedPorts(flociPort) + .withHostConfig(HostConfig.newHostConfig() + .withBinds(new Bind("/var/run/docker.sock", new Volume("/var/run/docker.sock"))) + .withPortBindings(new PortBinding(Ports.Binding.bindIpAndPort("127.0.0.1", hostPort), + flociPort))) + .exec() + .getId(); + cleanup.add(this::removeClusterLeftovers); + cleanup.add(this::stopFloci); + docker.startContainerCmd(flociContainer).exec(); + awaitHealthy(hostPort); + + // A plain JUnit class has no Quarkus test setup to point RestAssured at Floci and teach it the AWS JSON + // content type EMR's requests are sent as; the reset undoes both. + RestAssured.baseURI = "http://localhost"; + RestAssured.port = hostPort; + RestAssuredJsonUtils.configureAwsContentTypes(); + cleanup.add(RestAssured::reset); + s3 = AwsTestClients.create(S3Client.builder().forcePathStyle(true), ACCOUNT, Region.US_EAST_1, + URI.create("http://localhost:" + hostPort)); + cleanup.add(s3::close); + bucket = "emr-floci-" + UUID.randomUUID().toString().substring(0, 8); + s3.createBucket(request -> request.bucket(bucket)); + put("data/rows/rows.csv", HiveCatalogJobs.ROWS); + put("queries/load.q", HiveCatalogJobs.LOAD_QUERY); + put("queries/report.q", HiveCatalogJobs.REPORT_QUERY); + put("jobs/catalog.py", HiveCatalogJobs.CATALOG_JOB); + } + + // Every action runs even when one before it fails: a Floci that no longer answers still has its container, + // and the cluster's, removed. assertAll reports each failure. + @AfterEach + void tearDown() { + List actions = new ArrayList<>(); + for (int i = cleanup.size() - 1; i >= 0; i--) { + actions.add(cleanup.get(i)::run); + } + assertAll("cleanup", actions); + } + + @Test + void aClusterRunByFlociInAContainerSharesItsMetastoreOverFlocisS3AndLeavesNoNetworkBehind() { + startCluster(); + + assertEquals("COMPLETED", step("hive-script", "--run-hive-script", "--args", + "-f", s3Uri("queries/load.q"), "-d", "INPUT=" + s3Uri("data/rows/"))); + assertEquals("COMPLETED", step("spark-submit", s3Uri("jobs/catalog.py"), s3Uri("out/spark/"))); + assertEquals(HiveCatalogJobs.CATALOG_OUTPUT, objects("out/spark/")); + assertEquals("COMPLETED", step("hive-script", "--run-hive-script", "--args", + "-f", s3Uri("queries/report.q"), "-d", "OUTPUT=" + s3Uri("out/report/"))); + assertEquals(HiveCatalogJobs.REPORT_OUTPUT, objects("out/report/")); + assertTrue(clusterNetworks().size() > 0, "Floci's container must be on the cluster's network: " + networks()); + + emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + clusterId + "\"]}").then().statusCode(200); + await("cluster " + clusterId + " to end and Floci's container to leave its network") + .atMost(CLUSTER_END) + .pollInterval(Duration.ofSeconds(1)) + .until(() -> TERMINATED.contains(clusterState()) && clusterNetworks().isEmpty()); + } + + private void startCluster() { + ObjectNode request = JSON.createObjectNode().put("Name", "floci-in-a-container") + .put("ReleaseLabel", "emr-7.5.0").put("LogUri", s3Uri("logs/")); + ObjectNode[] applications = {JSON.createObjectNode().put("Name", "Hadoop"), + JSON.createObjectNode().put("Name", "Hive"), JSON.createObjectNode().put("Name", "Spark")}; + request.putArray("Applications").addAll(List.of(applications)); + 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.add(() -> emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + clusterId + "\"]}")); + } + + /** Runs one step on the cluster and returns the state it ended in, its stderr and Floci's log if it failed. */ + private String step(String... args) { + String stepId = EmrRequests.addStep(clusterId, args[0], "command-runner.jar", args); + String state = awaitStep(clusterId, stepId).jsonPath().getString("Step.Status.State"); + if (!"COMPLETED".equals(state)) { + return state + "\n" + stepLog(stepId) + "\n" + flociLog(); + } + return state; + } + + private String clusterState() { + return emr("DescribeCluster", "{\"ClusterId\":\"" + clusterId + "\"}").then().statusCode(200).extract() + .jsonPath().getString("Cluster.Status.State"); + } + + /** The networks Floci's container is on that are the cluster's: their names carry its id. */ + private List clusterNetworks() { + return networks().stream().filter(name -> name.contains(clusterId)).toList(); + } + + private List networks() { + InspectContainerResponse floci = docker.inspectContainerCmd(flociContainer).exec(); + return List.copyOf(floci.getNetworkSettings().getNetworks().keySet()); + } + + private void awaitHealthy(int hostPort) { + HttpClient http = HttpClient.newHttpClient(); + URI health = URI.create("http://localhost:" + hostPort + "/_floci/health"); + await("Floci's container to answer its health check") + .atMost(FLOCI_START) + .pollInterval(Duration.ofSeconds(1)) + .ignoreExceptions() + .until(() -> http.send(HttpRequest.newBuilder(health).build(), + HttpResponse.BodyHandlers.discarding()).statusCode() == 200); + } + + // Floci's container is stopped as a user stops it, which removes the containers and networks it made. + private void stopFloci() { + try { + docker.stopContainerCmd(flociContainer).withTimeout(60).exec(); + } catch (NotFoundException | NotModifiedException expected) { + // Gone, or stopped already: nothing to stop. + } finally { + try { + docker.removeContainerCmd(flociContainer).withForce(true).withRemoveVolumes(true).exec(); + } catch (NotFoundException expected) { + // Gone already. + } + } + } + + // The cluster's containers and networks a stop left, as one that timed out or a Floci that crashed leaves them, + // removed by name after Floci's own container. + private void removeClusterLeftovers() { + if (clusterId == null) { + return; + } + for (Container container : docker.listContainersCmd().withShowAll(true) + .withNameFilter(List.of(clusterId)).exec()) { + try { + docker.removeContainerCmd(container.getId()).withForce(true).exec(); + } catch (NotFoundException expected) { + // Removed meanwhile. + } + } + docker.listNetworksCmd().exec().stream() + .filter(network -> network.getName().contains(clusterId)) + .forEach(network -> { + try { + docker.removeNetworkCmd(network.getId()).exec(); + } catch (NotFoundException expected) { + // Removed meanwhile. + } + }); + } + + private String stepLog(String stepId) { + try { + return S3TestClients.gunzipped(s3, bucket, "logs/" + clusterId + "/steps/" + stepId + "/stderr.gz"); + } catch (RuntimeException e) { + return "(no step log: " + e.getMessage() + ")"; + } + } + + /** The last lines of Floci's container's log, for a failure's message. */ + private String flociLog() { + StringBuilder log = new StringBuilder(); + try { + docker.logContainerCmd(flociContainer).withStdOut(true).withStdErr(true).withTail(200) + .exec(new ResultCallback.Adapter() { + @Override + public void onNext(Frame frame) { + log.append(new String(frame.getPayload(), StandardCharsets.UTF_8)); + } + }) + .awaitCompletion(30, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return log.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; + } + + /** The objects under {@code prefix}, in key order, one after the other. */ + private String objects(String prefix) { + StringBuilder text = new StringBuilder(); + s3.listObjectsV2(request -> request.bucket(bucket).prefix(prefix)).contents().forEach(object -> + text.append(s3.getObjectAsBytes(request -> request.bucket(bucket).key(object.key())).asUtf8String())); + return text.toString(); + } +} diff --git a/src/test/java/io/floci/aws/services/emr/EmrHiveStepsDockerIntegrationTest.java b/src/test/java/io/floci/aws/services/emr/EmrHiveStepsDockerIntegrationTest.java index 0bf9683b27..979fb9ab98 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrHiveStepsDockerIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrHiveStepsDockerIntegrationTest.java @@ -6,6 +6,7 @@ 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; @@ -50,7 +51,6 @@ class EmrHiveStepsDockerIntegrationTest { private static final ObjectMapper JSON = new ObjectMapper(); private static final String REGION = "us-east-1"; - private static final String ROWS = "a,1\nb,2\nc,3\n"; private static final String HIVE_AND_SPARK = "[{\"Name\":\"Hadoop\"},{\"Name\":\"Hive\"},{\"Name\":\"Spark\"}]"; @RegisterExtension @@ -76,34 +76,16 @@ class EmrHiveStepsDockerIntegrationTest { bucket = "emr-hive-" + UUID.randomUUID().toString().substring(0, 8); s3.createBucket(request -> request.bucket(bucket)); cleanup.register(() -> S3TestClients.deleteBucket(s3, bucket)); - put("data/rows/rows.csv", ROWS); + put("data/rows/rows.csv", HiveCatalogJobs.ROWS); } @Test void hiveAndSparkStepsShareTheClustersMetastoreServiceAndHdfs() { // The two steps that read what the first one made, and need nothing from each other, run at once. startCluster(HIVE_AND_SPARK, "[]", null, 2); - put("queries/load.q", """ - create external table kv (k string, v int) - row format delimited fields terminated by ',' location '${INPUT}'; - create table scaled as select k, v * 10 as v from kv; - create table pinned (k string) location 'hdfs:///floci/pinned'; - insert into pinned select k from kv; - """); - put("queries/report.q", """ - insert overwrite directory '${OUTPUT}' row format delimited fields terminated by ',' - select k, v from scaled order by k; - select k, v from scaled order by k; - select k from from_spark order by k; - """); - put("jobs/catalog.py", """ - import sys - from pyspark.sql import SparkSession - spark = SparkSession.builder.enableHiveSupport().getOrCreate() - rows = sorted(f"{row.k}{row.v}" for row in spark.sql("select k, v from scaled").collect()) - spark.createDataFrame([(" ".join(rows),)], ["value"]).coalesce(1).write.text(sys.argv[1]) - spark.sql("create table from_spark stored as textfile as select upper(k) as k from scaled") - """); + put("queries/load.q", HiveCatalogJobs.LOAD_QUERY); + put("queries/report.q", HiveCatalogJobs.REPORT_QUERY); + put("jobs/catalog.py", HiveCatalogJobs.CATALOG_JOB); assertEquals("COMPLETED", hiveStep("-f", s3Uri("queries/load.q"), "-d", "INPUT=" + s3Uri("data/rows/"))); // Its data is in the cluster's HDFS, which a step in the Spark image reads as hdfs://, and so is an hdfs:// @@ -115,12 +97,12 @@ class EmrHiveStepsDockerIntegrationTest { assertEquals("COMPLETED", state(cat)); assertEquals("a\u000110\nb\u000120\nc\u000130\na\nb\nc\n", stepLog(cat, "stdout.gz")); assertEquals("COMPLETED", state(spark)); - assertEquals("a10 b20 c30\n", objects("out/spark/")); + assertEquals(HiveCatalogJobs.CATALOG_OUTPUT, objects("out/spark/")); // The tables the first step and the Spark step made are in the cluster's metastore for a later Hive step. String report = addStep("command-runner.jar", "hive-script", "--run-hive-script", "--args", "-f", s3Uri("queries/report.q"), "-d", "OUTPUT=" + s3Uri("out/report/")); assertEquals("COMPLETED", state(report)); - assertEquals("a,10\nb,20\nc,30\n", objects("out/report/")); + assertEquals(HiveCatalogJobs.REPORT_OUTPUT, objects("out/report/")); String reported = stepLog(report, "stdout.gz"); assertTrue(reported.contains("a\t10\nb\t20\nc\t30\n") && reported.contains("A\nB\nC\n"), reported); } @@ -246,14 +228,9 @@ class EmrHiveStepsDockerIntegrationTest { return state(addStep("command-runner.jar", command.toArray(String[]::new))); } - /** Adds one step to the cluster and returns its id. */ + /** Adds one step to the cluster, named after its first argument, and returns its id. */ private String addStep(String jar, String... args) { - ObjectNode request = JSON.createObjectNode().put("JobFlowId", clusterId); - ObjectNode step = request.putArray("Steps").addObject().put("Name", args[0]).put("ActionOnFailure", "CONTINUE"); - ObjectNode hadoopJarStep = step.putObject("HadoopJarStep").put("Jar", jar); - List.of(args).forEach(hadoopJarStep.putArray("Args")::add); - return emr("AddJobFlowSteps", request.toString()).then().statusCode(200).extract().jsonPath() - .getString("StepIds[0]"); + return EmrRequests.addStep(clusterId, args[0], jar, args); } private String state(String stepId) { diff --git a/src/test/java/io/floci/aws/services/emr/HiveCatalogJobs.java b/src/test/java/io/floci/aws/services/emr/HiveCatalogJobs.java new file mode 100644 index 0000000000..abdc4ec4aa --- /dev/null +++ b/src/test/java/io/floci/aws/services/emr/HiveCatalogJobs.java @@ -0,0 +1,47 @@ +package io.floci.aws.services.emr; + +/** + * Hive and Spark steps that share a cluster's metastore, for the tests that run them for real: a Hive step makes + * tables over CSV rows in S3 and in HDFS, a Spark step reads one and makes another, and a later Hive step reads both. + */ +final class HiveCatalogJobs { + + /** The rows the first Hive step reads, at {@code ${INPUT}}. */ + static final String ROWS = "a,1\nb,2\nc,3\n"; + + /** Makes {@code kv} over {@code ${INPUT}}, {@code scaled} from it in Hive's warehouse, and {@code pinned} in HDFS. */ + static final String LOAD_QUERY = """ + create external table kv (k string, v int) + row format delimited fields terminated by ',' location '${INPUT}'; + create table scaled as select k, v * 10 as v from kv; + create table pinned (k string) location 'hdfs:///floci/pinned'; + insert into pinned select k from kv; + """; + + /** Writes {@code scaled} to {@code ${OUTPUT}} and selects it and the Spark step's {@code from_spark}. */ + static final String REPORT_QUERY = """ + insert overwrite directory '${OUTPUT}' row format delimited fields terminated by ',' + select k, v from scaled order by k; + select k, v from scaled order by k; + select k from from_spark order by k; + """; + + /** Reads {@code scaled} through the metastore, writes its rows to its first argument, and makes {@code from_spark}. */ + static final String CATALOG_JOB = """ + import sys + from pyspark.sql import SparkSession + spark = SparkSession.builder.enableHiveSupport().getOrCreate() + rows = sorted(f"{row.k}{row.v}" for row in spark.sql("select k, v from scaled").collect()) + spark.createDataFrame([(" ".join(rows),)], ["value"]).coalesce(1).write.text(sys.argv[1]) + spark.sql("create table from_spark stored as textfile as select upper(k) as k from scaled") + """; + + /** What {@link #CATALOG_JOB} writes. */ + static final String CATALOG_OUTPUT = "a10 b20 c30\n"; + + /** What {@link #REPORT_QUERY} writes to {@code ${OUTPUT}}. */ + static final String REPORT_OUTPUT = "a,10\nb,20\nc,30\n"; + + private HiveCatalogJobs() { + } +} diff --git a/src/test/java/io/floci/aws/services/rds/container/RdsContainerManagerPostgresTest.java b/src/test/java/io/floci/aws/services/rds/container/RdsContainerManagerPostgresTest.java index deec3887d4..a7838044d2 100644 --- a/src/test/java/io/floci/aws/services/rds/container/RdsContainerManagerPostgresTest.java +++ b/src/test/java/io/floci/aws/services/rds/container/RdsContainerManagerPostgresTest.java @@ -7,9 +7,6 @@ import com.github.dockerjava.api.model.Container; import com.github.dockerjava.api.model.ExposedPort; import com.github.dockerjava.api.model.HostConfig; import com.github.dockerjava.api.model.Ports; -import com.github.dockerjava.core.DefaultDockerClientConfig; -import com.github.dockerjava.core.DockerClientImpl; -import com.github.dockerjava.httpclient5.ApacheDockerHttpClient; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.ServiceConfigAccess; @@ -18,6 +15,7 @@ import io.floci.aws.core.common.docker.ContainerDetector; import io.floci.aws.core.common.docker.ContainerExec; import io.floci.aws.core.common.docker.ContainerLifecycleManager; import io.floci.aws.core.common.docker.ContainerLogStreamer; +import io.floci.aws.testing.TestDockerClients; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Tag; @@ -25,7 +23,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import java.io.IOException; -import java.time.Duration; import java.util.List; import java.util.concurrent.TimeUnit; @@ -57,16 +54,7 @@ class RdsContainerManagerPostgresTest { @BeforeAll void setUp() { try { - DefaultDockerClientConfig clientConfig = DefaultDockerClientConfig - .createDefaultConfigBuilder() - .build(); - ApacheDockerHttpClient httpClient = new ApacheDockerHttpClient.Builder() - .dockerHost(clientConfig.getDockerHost()) - .maxConnections(10) - .connectionTimeout(Duration.ofSeconds(10)) - .responseTimeout(Duration.ofMinutes(5)) - .build(); - dockerClient = DockerClientImpl.getInstance(clientConfig, httpClient); + dockerClient = TestDockerClients.local(); dockerClient.pingCmd().exec(); } catch (Exception e) { assumeTrue(false, "Docker is not available: " + e.getMessage()); diff --git a/src/test/java/io/floci/aws/services/rdsdata/RdsBackendEndpointRefreshIntegrationTest.java b/src/test/java/io/floci/aws/services/rdsdata/RdsBackendEndpointRefreshIntegrationTest.java index bd7792a37a..edea3a108a 100644 --- a/src/test/java/io/floci/aws/services/rdsdata/RdsBackendEndpointRefreshIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/rdsdata/RdsBackendEndpointRefreshIntegrationTest.java @@ -10,9 +10,6 @@ import com.github.dockerjava.api.model.ContainerNetwork; import com.github.dockerjava.api.model.ExposedPort; import com.github.dockerjava.api.model.HostConfig; import com.github.dockerjava.api.model.Network; -import com.github.dockerjava.core.DefaultDockerClientConfig; -import com.github.dockerjava.core.DockerClientImpl; -import com.github.dockerjava.httpclient5.ApacheDockerHttpClient; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.docker.ContainerDetector; import io.floci.aws.core.common.docker.ContainerExec; @@ -26,6 +23,7 @@ import io.floci.aws.services.rds.proxy.RdsProxyTlsCertificates; import io.floci.aws.services.rds.proxy.RdsSigV4Validator; import io.floci.aws.services.secretsmanager.SecretsManagerService; import io.floci.aws.services.secretsmanager.model.SecretVersion; +import io.floci.aws.testing.TestDockerClients; import io.floci.aws.testutil.FreePorts; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; @@ -91,16 +89,7 @@ class RdsBackendEndpointRefreshIntegrationTest { @BeforeAll void connectToDocker() { try { - DefaultDockerClientConfig clientConfig = DefaultDockerClientConfig - .createDefaultConfigBuilder() - .build(); - ApacheDockerHttpClient httpClient = new ApacheDockerHttpClient.Builder() - .dockerHost(clientConfig.getDockerHost()) - .maxConnections(10) - .connectionTimeout(Duration.ofSeconds(10)) - .responseTimeout(Duration.ofMinutes(5)) - .build(); - dockerClient = DockerClientImpl.getInstance(clientConfig, httpClient); + dockerClient = TestDockerClients.local(); dockerClient.pingCmd().exec(); dockerClient.pullImageCmd(IMAGE).start().awaitCompletion(120, TimeUnit.SECONDS); } catch (Exception e) { diff --git a/src/test/java/io/floci/aws/testing/EmrRequests.java b/src/test/java/io/floci/aws/testing/EmrRequests.java index 59be89be81..fdd199fad0 100644 --- a/src/test/java/io/floci/aws/testing/EmrRequests.java +++ b/src/test/java/io/floci/aws/testing/EmrRequests.java @@ -1,10 +1,13 @@ package io.floci.aws.testing; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; import io.floci.aws.services.emr.EmrService; import io.floci.aws.services.emr.model.EmrCluster; import io.restassured.response.Response; import java.time.Duration; +import java.util.List; import java.util.Set; import static io.restassured.RestAssured.given; @@ -13,6 +16,7 @@ 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 ObjectMapper JSON = new ObjectMapper(); private static final Set UNFINISHED_STEP_STATES = Set.of("PENDING", "RUNNING"); private static final Set TERMINATED_CLUSTER_STATES = Set.of("TERMINATED", "TERMINATED_WITH_ERRORS"); private static final Duration STEP_TIMEOUT = Duration.ofMinutes(5); @@ -35,6 +39,19 @@ public final class EmrRequests { .body(body).when().post("/"); } + /** + * Adds one {@code CONTINUE} step named {@code name} to the cluster, running {@code jar} with {@code args}, and returns + * its id. + */ + public static String addStep(String clusterId, String name, String jar, String... args) { + ObjectNode request = JSON.createObjectNode().put("JobFlowId", clusterId); + ObjectNode step = request.putArray("Steps").addObject().put("Name", name).put("ActionOnFailure", "CONTINUE"); + ObjectNode hadoopJarStep = step.putObject("HadoopJarStep").put("Jar", jar); + List.of(args).forEach(hadoopJarStep.putArray("Args")::add); + return emr("AddJobFlowSteps", request.toString()).then().statusCode(200).extract().jsonPath() + .getString("StepIds[0]"); + } + /** * 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 diff --git a/src/test/java/io/floci/aws/testing/TestDockerClients.java b/src/test/java/io/floci/aws/testing/TestDockerClients.java new file mode 100644 index 0000000000..a285917124 --- /dev/null +++ b/src/test/java/io/floci/aws/testing/TestDockerClients.java @@ -0,0 +1,29 @@ +package io.floci.aws.testing; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.core.DefaultDockerClientConfig; +import com.github.dockerjava.core.DockerClientImpl; +import com.github.dockerjava.httpclient5.ApacheDockerHttpClient; + +import java.time.Duration; + +/** + * A Docker client for a test that has none from Floci's application, either because it runs outside it or because it + * starts containers Floci does not own: the daemon the environment names, as {@code docker} itself would reach it. + */ +public final class TestDockerClients { + + private TestDockerClients() { + } + + public static DockerClient local() { + DefaultDockerClientConfig clientConfig = DefaultDockerClientConfig.createDefaultConfigBuilder().build(); + ApacheDockerHttpClient httpClient = new ApacheDockerHttpClient.Builder() + .dockerHost(clientConfig.getDockerHost()) + .maxConnections(10) + .connectionTimeout(Duration.ofSeconds(10)) + .responseTimeout(Duration.ofMinutes(5)) + .build(); + return DockerClientImpl.getInstance(clientConfig, httpClient); + } +}