diff --git a/.github/ci/prefetch-images.sh b/.github/ci/prefetch-images.sh index 9efb2cccb0..9a41f458e0 100755 --- a/.github/ci/prefetch-images.sh +++ b/.github/ci/prefetch-images.sh @@ -113,8 +113,9 @@ 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. -starts EmrDockerRunnerDockerIntegrationTest EmrHiveStepsDockerIntegrationTest \ +# EmrHiveStepsDockerIntegrationTest runs a cluster's other steps in it, and the nightly +# EmrServerlessCustomImageNightlyIntegrationTest builds its custom image on it. +starts EmrDockerRunnerDockerIntegrationTest EmrHiveStepsDockerIntegrationTest EmrServerlessCustomImageNightlyIntegrationTest \ && 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 diff --git a/.github/workflows/nightly-checks.yml b/.github/workflows/nightly-checks.yml index b778063713..547075c6f3 100644 --- a/.github/workflows/nightly-checks.yml +++ b/.github/workflows/nightly-checks.yml @@ -1,10 +1,11 @@ name: Nightly checks # Runs the test classes named *NightlyIntegrationTest: checks that pull or push images too large, or run too long, -# for every pull request's shards. Each such class skips unless the JVM has -Dfloci.nightly=true, so the CI shards, -# which pick every *Test class, see it skip at no cost; this workflow sets the property. It runs once a day on -# main, on demand, and on a pull request that adds or changes a nightly check, so the check is seen to pass before -# it merges. GitHub-hosted runners only, which a public repository runs at no charge. +# for every pull request's shards. Each such class skips unless the JVM has -Dnightly.checks.enabled=true, so the +# CI shards, which pick every *Test class, see it skip at no cost; this workflow sets the property. Its name is +# outside floci.*, whose names Floci's configuration validates: a Quarkus test given -Dfloci.nightly refuses to +# start. It runs once a day on main, on demand, and on a pull request that adds or changes a nightly check, so the +# check is seen to pass before it merges. GitHub-hosted runners only, which a public repository runs at no charge. on: schedule: # 08:00 UTC, after Nightly (23:00 America/Chicago) and away from the daytime merges' CI runs. @@ -93,7 +94,7 @@ jobs: ./mvnw surefire:test -B -Dsurefire.includesFile="$GITHUB_WORKSPACE/nightly.txt" -Dsurefire.failIfNoTests=true - -Dfloci.nightly=true + -Dnightly.checks.enabled=true - name: Image prefetch results if: always() && steps.list.outputs.count != '0' diff --git a/AGENTS.md b/AGENTS.md index 654d9e67bb..94c844aefd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -254,7 +254,7 @@ Guidelines: - Unit tests: `*ServiceTest.java` - Integration tests: `*IntegrationTest.java` - Nightly checks: `*NightlyIntegrationTest.java`, for a check too heavy for every pull request's shards - (multi-gigabyte images, long runs). It skips unless the JVM has `-Dfloci.nightly=true`, which + (multi-gigabyte images, long runs). It skips unless the JVM has `-Dnightly.checks.enabled=true`, which `.github/workflows/nightly-checks.yml` sets once a day and on a pull request that adds or changes one. Its images go in `.github/ci/prefetch-images.sh` keyed on its own class name, which only that workflow's list carries 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 4f69d36440..277397c89c 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrDockerRunnerDockerIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrDockerRunnerDockerIntegrationTest.java @@ -530,14 +530,7 @@ class EmrDockerRunnerDockerIntegrationTest { .toList(); } - /** 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(); + return S3TestClients.partFiles(s3, bucket, prefix); } } diff --git a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessCustomImageNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessCustomImageNightlyIntegrationTest.java new file mode 100644 index 0000000000..b6cc06a266 --- /dev/null +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessCustomImageNightlyIntegrationTest.java @@ -0,0 +1,241 @@ +package io.floci.aws.services.emrserverless; + +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.CreateContainerResponse; +import com.github.dockerjava.api.command.PullImageResultCallback; +import com.github.dockerjava.api.exception.NotFoundException; +import com.github.dockerjava.api.model.PushResponseItem; +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.DockerAvailability; +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.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +import io.restassured.response.Response; +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.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.ecr.EcrClient; +import software.amazon.awssdk.services.s3.S3Client; + +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import static io.floci.aws.testing.EmrServerlessRequests.awaitJobRun; +import static io.floci.aws.testing.EmrServerlessRequests.deleteApplication; +import static io.floci.aws.testing.EmrServerlessRequests.emrServerless; +import static io.floci.aws.testing.EmrServerlessRequests.startJobRun; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * An EMR Serverless application on a custom image in Floci's ECR, run for real: the image is the release's base + * image with a build marker, pushed to Floci's registry, and the job runs pull it from there. Then a second build is + * pushed under the same tag. An application that resolves its image as it starts, the default on EMR 7.13 and earlier, + * keeps the first build until it starts again ("Custom images are resolved to a digest at application start; that + * digest is used for all jobs until the application restarts"); one that resolves it for each run takes the second at + * once. + * + *

A nightly check: the first push copies the whole 3.5 GB base image into the registry. + */ +@QuarkusTest +@TestProfile(EmrServerlessCustomImageNightlyIntegrationTest.Profile.class) +@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true") +class EmrServerlessCustomImageNightlyIntegrationTest { + + /** + * Job runs in containers, and Floci on a fixed port: the registry address the runner hands the Docker daemon for an + * ECR image is {@code localhost:}, so it has to be the port Floci listens on. + */ + public static final class Profile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of( + "floci.services.emrserverless.runner-mode", "docker", + "quarkus.http.test-port", String.valueOf(PORT), + "floci.port", String.valueOf(PORT), + "floci.base-url", "http://localhost:" + PORT); + } + } + + private static final int PORT = 4599; + private static final String ACCOUNT = "000000000000"; + private static final String REGION = "us-east-1"; + private static final String RELEASE = "emr-7.5.0"; + private static final String TAG = "7.5.0"; + // The release's EMR Serverless image, which the runner's default template names and a custom image is built on. + private static final String BASE_IMAGE = "public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest"; + private static final ObjectMapper JSON = new ObjectMapper(); + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @Inject + DockerClient docker; + + private S3Client s3; + private EcrClient ecr; + private String bucket; + private String repository; + + @BeforeAll + static void configure() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @BeforeEach + void setUp() throws InterruptedException { + // Enabled, the check needs Docker: without a daemon it fails rather than pass having run nothing. + assertTrue(DockerAvailability.isAvailable(), "the nightly check needs a Docker daemon"); + s3 = AwsTestClients.create(S3Client.builder().forcePathStyle(true), ACCOUNT, Region.US_EAST_1); + cleanup.register(s3::close); + bucket = "emr-image-" + UUID.randomUUID().toString().substring(0, 8); + s3.createBucket(request -> request.bucket(bucket)); + cleanup.register(() -> S3TestClients.deleteBucket(s3, bucket)); + s3.putObject(request -> request.bucket(bucket).key("job.py"), RequestBody.fromString(""" + import os, sys + from pyspark.sql import SparkSession + spark = SparkSession.builder.getOrCreate() + spark.createDataFrame([(os.environ.get("FLOCI_IMAGE_BUILD", "none"),)], ["value"]) \\ + .coalesce(1).write.text(sys.argv[1]) + """)); + ecr = AwsTestClients.create(EcrClient.builder(), ACCOUNT, Region.US_EAST_1); + cleanup.register(ecr::close); + repository = "emr-custom-" + UUID.randomUUID().toString().substring(0, 8); + ecr.createRepository(request -> request.repositoryName(repository)); + cleanup.register(() -> ecr.deleteRepository(request -> request.repositoryName(repository).force(true))); + docker.pullImageCmd(BASE_IMAGE).exec(new PullImageResultCallback()).awaitCompletion(20, TimeUnit.MINUTES); + } + + @Test + void anApplicationKeepsTheImageItResolvedAsItStartedUntilItStartsAgain() throws InterruptedException { + String first = pushBuild("first"); + String resolvedAtStart = createApplication(null); + String resolvedPerRun = createApplication(false); + + assertEquals("first", run(resolvedAtStart, "start-1/")); + assertEquals(first, imageDigest(resolvedAtStart), "the digest the application resolved as it started"); + assertEquals("first", run(resolvedPerRun, "run-1/")); + + String second = pushBuild("second"); + assertNotEquals(first, second, "the second build must have moved the tag"); + + assertEquals("first", run(resolvedAtStart, "start-2/"), + "a started application keeps the image it resolved until it starts again"); + assertEquals("second", run(resolvedPerRun, "run-2/"), + "an application resolving for each run takes the tag's new image at once"); + + emrServerless(REGION).when().post("/applications/" + resolvedAtStart + "/stop").then().statusCode(200); + emrServerless(REGION).when().post("/applications/" + resolvedAtStart + "/start").then().statusCode(200); + + assertEquals(second, imageDigest(resolvedAtStart), "the digest it resolved as it started again"); + assertEquals("second", run(resolvedAtStart, "start-3/")); + } + + /** + * Pushes the base image with {@code FLOCI_IMAGE_BUILD=build} to the repository's tag in Floci's ECR and returns the + * digest ECR gives it. The local copy goes, so a run pulls the image from Floci's registry. + */ + private String pushBuild(String build) throws InterruptedException { + // A container's environment is the image's with its own added, and a commit keeps the container's. + CreateContainerResponse container = docker.createContainerCmd(BASE_IMAGE) + .withCmd("true") + .withEnv("FLOCI_IMAGE_BUILD=" + build) + .exec(); + String image; + try { + image = docker.commitCmd(container.getId()).exec(); + } finally { + docker.removeContainerCmd(container.getId()).withForce(true).exec(); + } + String reference = "localhost:" + PORT + "/" + ACCOUNT + "/" + REGION + "/" + repository; + docker.tagImageCmd(image, reference, TAG).exec(); + try { + AtomicReference error = new AtomicReference<>(); + boolean finished = docker.pushImageCmd(reference).withTag(TAG) + .exec(new ResultCallback.Adapter() { + @Override + public void onNext(PushResponseItem item) { + if (item.isErrorIndicated()) { + error.set(String.valueOf(item.getErrorDetail())); + } + } + }) + .awaitCompletion(30, TimeUnit.MINUTES); + assertTrue(finished, "the push of build " + build + " must finish"); + assertNull(error.get(), "the push of build " + build + " must succeed"); + } finally { + removeImage(reference + ":" + TAG); + removeImage(image); + } + return ecr.describeImages(request -> request.repositoryName(repository) + .imageIds(id -> id.imageTag(TAG))) + .imageDetails().getFirst().imageDigest(); + } + + private void removeImage(String image) { + try { + docker.removeImageCmd(image).withForce(true).exec(); + } catch (NotFoundException expected) { + // Removing one reference to an image can take the others with it. + } + } + + /** + * Creates an application on the repository's tag and returns its id; a null + * {@code applicationLevelDigestResolution} leaves it to the release. + */ + private String createApplication(Boolean applicationLevelDigestResolution) { + ObjectNode request = JSON.createObjectNode() + .put("name", "custom-" + UUID.randomUUID().toString().substring(0, 8)) + .put("releaseLabel", RELEASE) + .put("type", "SPARK") + .put("clientToken", UUID.randomUUID().toString()); + ObjectNode image = request.putObject("imageConfiguration") + .put("imageUri", ACCOUNT + ".dkr.ecr." + REGION + ".amazonaws.com/" + repository + ":" + TAG); + if (applicationLevelDigestResolution != null) { + image.put("applicationLevelDigestResolution", applicationLevelDigestResolution); + } + String applicationId = emrServerless(REGION).body(request.toString()) + .when().post("/applications") + .then().statusCode(200).extract().path("applicationId"); + cleanup.register(() -> deleteApplication(REGION, applicationId)); + return applicationId; + } + + /** Runs the job on the application, which starts it if it has not started, and returns the build marker it saw. */ + private String run(String applicationId, String output) { + ObjectNode request = JSON.createObjectNode() + .put("clientToken", UUID.randomUUID().toString()) + .put("executionRoleArn", "arn:aws:iam::" + ACCOUNT + ":role/emr-serverless-job"); + request.putObject("jobDriver").putObject("sparkSubmit") + .put("entryPoint", "s3://" + bucket + "/job.py") + .putArray("entryPointArguments").add("s3://" + bucket + "/" + output); + String jobRunId = startJobRun(REGION, applicationId, request.toString()); + + Response ended = awaitJobRun(REGION, applicationId, jobRunId); + + assertEquals("SUCCESS", ended.jsonPath().getString("jobRun.state"), + ended.jsonPath().getString("jobRun.stateDetails")); + return S3TestClients.partFiles(s3, bucket, output).strip(); + } + + private String imageDigest(String applicationId) { + return emrServerless(REGION).when().get("/applications/" + applicationId) + .then().statusCode(200).extract().path("application.imageConfiguration.resolvedImageDigest"); + } +} diff --git a/src/test/java/io/floci/aws/testing/S3TestClients.java b/src/test/java/io/floci/aws/testing/S3TestClients.java index a6b260850b..edd60aee6a 100644 --- a/src/test/java/io/floci/aws/testing/S3TestClients.java +++ b/src/test/java/io/floci/aws/testing/S3TestClients.java @@ -6,6 +6,7 @@ import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient; 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; @@ -37,6 +38,20 @@ public final class S3TestClients { s3.deleteBucket(request -> request.bucket(bucket)); } + /** + * What a Spark or MapReduce job wrote under {@code prefix} in {@code bucket}: its part files, in key order, one after + * the other. + */ + public static String partFiles(S3Client s3, String bucket, 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(); + } + /** The object at {@code key} in {@code bucket}, gunzipped, as a test reads back a log Floci wrote there. */ public static String gunzipped(S3Client s3, String bucket, String key) { try (GZIPInputStream in = new GZIPInputStream(s3.getObject(request -> request.bucket(bucket).key(key)))) {