diff --git a/docs/services/emr-serverless.md b/docs/services/emr-serverless.md index 48d542dfd6..871a097cd7 100644 --- a/docs/services/emr-serverless.md +++ b/docs/services/emr-serverless.md @@ -128,13 +128,20 @@ publishes for customizing EMR Serverless images (`public.ecr.aws/emr-serverless/ * **Credentials**: the container gets a session for the run's execution role when IAM knows the role, otherwise the account's placeholder credentials, and `AWS_ENDPOINT_URL` pointing at Floci, so the job's own SDK clients reach Floci too. -* **Output**: the driver's output goes to Floci's log, prefixed `emr-serverless:`. +* **Output**: the driver's output goes to Floci's log, prefixed `emr-serverless:`. With an S3 + log destination, the run's `s3MonitoringConfiguration` or else the application's, its standard output + and error also go to Floci's S3 once the run ends, gzipped, as `stdout.gz` and `stderr.gz` under + `/applications//jobs//SPARK_DRIVER/`, with `attempts/1/` before + `SPARK_DRIVER/` for a `STREAMING` run, or a `BATCH` run whose `retryPolicy` allows more than one + attempt, on release 7.1.0 or later. A cancelled run's logs hold what its driver wrote until it was + stopped. Logs that cannot be written, to a bucket that does not exist say, leave the run as it + ended. * **Image**: `image-template` names another image, such as a mirror or a dated tag of the release's image: `registry.internal/emr-serverless/spark/%s:20250425`. ## Limitations and Differences from AWS -* **Jobs do not execute by default**: in the `immediate` runner mode `StartJobRun` records a job run and moves it through its states, but nothing runs. In the `docker` mode a Spark run executes in local mode in one container, so worker counts and sizes, initial and maximum capacity are not applied; a Hive run is `FAILED` without running, in Floci's own wording, as is a driver's failure. The monitoring configuration's S3 and CloudWatch log destinations are not written to, and Floci's CA is not in the job's Java truststore, so a job reaches Floci over its HTTP endpoint only. +* **Jobs do not execute by default**: in the `immediate` runner mode `StartJobRun` records a job run and moves it through its states, but nothing runs. In the `docker` mode a Spark run executes in local mode in one container, so worker counts and sizes, initial and maximum capacity are not applied; a Hive run is `FAILED` without running, in Floci's own wording, as is a driver's failure. Of the monitoring configuration only the S3 log destination is written to, with the driver's `stdout.gz` and `stderr.gz` once a run ends (no event logs, rotated files or uploads while it runs), and Floci's CA is not in the job's Java truststore, so a job reaches Floci over its HTTP endpoint only. * **Unsourced errors**: AWS documents neither the error for a run submitted to an application whose auto-start is off nor the one for a run on a terminated application; Floci answers both with `ValidationException`. The same holds for a `BATCH` timeout outside 1 to 10080 minutes on `emr-7.11.0` or later (`ValidationException`) and for `GetJobRun` naming an attempt a run never made (`ResourceNotFoundException`), both in Floci's own wording. A run needs a `jobDriver`, as every `JobRun` carries one, and `jobDriver` is a union, so a run without a driver, or with one that sets both `sparkSubmit` and `hive` or neither, is refused with `ValidationException` too, in Floci's own wording. * **StopApplication with running jobs**: AWS requires running jobs to finish or be cancelled before an application stops. Floci does not enforce it; with the default duration of `0` no `BATCH` run is ever running. * **Not emulated**: retries (`retryPolicy` is stored and returned, but no run is retried), queuing (`QUEUED`), `totalResourceUtilization` and `billedResourceUtilization`, and `shutdownGracePeriodInSeconds` (accepted and ignored: a cancelled run's driver is stopped at once). diff --git a/docs/services/emr.md b/docs/services/emr.md index b04c97fdef..faa441a776 100644 --- a/docs/services/emr.md +++ b/docs/services/emr.md @@ -146,8 +146,14 @@ its lifecycle as in the `immediate` mode. * **Credentials**: the container gets a session for the step's `ExecutionRoleArn`, or else for the role of the cluster's `JobFlowRole` instance profile, when IAM knows it and the profile holds one role, and otherwise the account's placeholder credentials, with `AWS_ENDPOINT_URL` pointing at Floci. -* **Output**: the driver's output goes to Floci's log, prefixed `emr:`. Nothing is written - under `LogUri`. +* **Output**: the driver's output goes to Floci's log, prefixed `emr:`. With a `LogUri` on the + cluster, its standard output and error also go to Floci's S3 once the step ends, gzipped, as + `stdout.gz` and `stderr.gz` under `//steps//`, the step log folder of the + Management Guide's "Log locations" (an `s3n://` or `s3a://` `LogUri` names the same bucket). A + cancelled step's logs hold what its driver wrote until it was stopped. Logs that cannot be written, + to a bucket that does not exist say, leave the step as it ended. The `controller` and `syslog` logs + and the other log folders are not written, nothing is copied while a step runs (EMR copies its logs + every five minutes), and `FailureDetails` has no `LogFile`. * **Image**: `image-template` names another image, such as a mirror or a dated tag of the release's image: `registry.internal/emr-serverless/spark/%s:20250425`. A release with no EMR Serverless image fails its steps with "The step could not start: Could not pull image". diff --git a/src/main/java/io/github/hectorvent/floci/core/common/S3Uri.java b/src/main/java/io/github/hectorvent/floci/core/common/S3Uri.java new file mode 100644 index 0000000000..a3a0e30861 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/S3Uri.java @@ -0,0 +1,24 @@ +package io.github.hectorvent.floci.core.common; + +/** + * An {@code s3://bucket/key} URI, split into its bucket and its key. The key is empty when the URI names + * only a bucket, and keeps a trailing slash, as a key prefix does. + */ +public record S3Uri(String bucket, String key) { + + private static final String SCHEME = "s3://"; + + /** Splits {@code uri}; one that is not {@code s3://} or names no bucket is an IllegalArgumentException. */ + public static S3Uri parse(String uri) { + if (uri == null || !uri.startsWith(SCHEME)) { + throw new IllegalArgumentException("Not an s3:// URI: " + uri); + } + String rest = uri.substring(SCHEME.length()); + int slash = rest.indexOf('/'); + String bucket = slash < 0 ? rest : rest.substring(0, slash); + if (bucket.isEmpty()) { + throw new IllegalArgumentException("No bucket in " + uri); + } + return new S3Uri(bucket, slash < 0 ? "" : rest.substring(slash + 1)); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java index efbf66f303..bf55b508cb 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java @@ -516,22 +516,7 @@ public class ContainerLifecycleManager { } private void stopAndRemoveAdmitted(String containerId, Closeable logStream, int stopTimeoutSeconds) { - LOG.infov("Stopping container {0}", containerId); - - boolean stoppedOrMissing = false; - try { - dockerClient.stopContainerCmd(containerId).withTimeout(stopTimeoutSeconds).exec(); - stoppedOrMissing = true; - } catch (NotFoundException e) { - LOG.debugv("Container {0} not found (already removed)", containerId); - stoppedOrMissing = true; - } catch (NotModifiedException e) { - // HTTP 304: the container had already exited, which is the outcome the stop wanted. - LOG.debugv("Container {0} had already stopped", containerId); - stoppedOrMissing = true; - } catch (Exception e) { - LOG.warnv("Error stopping container {0}: {1}", containerId, e.getMessage()); - } + boolean stoppedOrMissing = stopAdmitted(containerId, stopTimeoutSeconds); // Force removal is the recovery path when Docker could not stop the container cleanly. It also // terminates the follow-log transport, allowing its terminal callback to drain the final tail. @@ -552,6 +537,35 @@ public class ContainerLifecycleManager { } } + /** + * Stops a container and leaves it in place, for its output to be read before it is removed: one that + * had already exited, or is gone, counts as stopped. + * + * @param stopTimeoutSeconds seconds to wait for the container to stop cleanly after + * SIGTERM before Docker sends SIGKILL. Must be a non-negative integer. + */ + public void stop(String containerId, int stopTimeoutSeconds) { + withTeardownSlot(() -> stopAdmitted(containerId, stopTimeoutSeconds)); + } + + private boolean stopAdmitted(String containerId, int stopTimeoutSeconds) { + LOG.infov("Stopping container {0}", containerId); + try { + dockerClient.stopContainerCmd(containerId).withTimeout(stopTimeoutSeconds).exec(); + return true; + } catch (NotFoundException e) { + LOG.debugv("Container {0} not found (already removed)", containerId); + return true; + } catch (NotModifiedException e) { + // HTTP 304: the container had already exited, which is the outcome the stop wanted. + LOG.debugv("Container {0} had already stopped", containerId); + return true; + } catch (Exception e) { + LOG.warnv("Error stopping container {0}: {1}", containerId, e.getMessage()); + return false; + } + } + /** * Releases lifecycle ownership of a log stream after its container has stopped. Docker's terminal * callback normally flushes the final tail; a bounded fallback handles a broken transport. diff --git a/src/main/java/io/github/hectorvent/floci/services/emr/EmrService.java b/src/main/java/io/github/hectorvent/floci/services/emr/EmrService.java index 55579c18bb..2df3636824 100644 --- a/src/main/java/io/github/hectorvent/floci/services/emr/EmrService.java +++ b/src/main/java/io/github/hectorvent/floci/services/emr/EmrService.java @@ -1214,7 +1214,7 @@ public class EmrService implements Resettable { accountId, region, cluster.getReleaseLabel(), imageTemplate, dockerNetwork, executionRole(cluster, step, accountId), EmrSparkSteps.sparkDefaults(cluster.getConfigurations(), SNAPSHOT_MAPPER), application, - Duration.ZERO); + Duration.ZERO, EmrSparkSteps.logFolder(cluster, step)); StepLaunch launch = new StepLaunch(accountId, region, cluster.getId(), step.getId(), generation); executing.add(stepKey(accountId, step.getId())); stepExecutor.execute(() -> runStep(job, launch)); diff --git a/src/main/java/io/github/hectorvent/floci/services/emr/EmrSparkSteps.java b/src/main/java/io/github/hectorvent/floci/services/emr/EmrSparkSteps.java index 1dbecf55a7..39588c1d80 100644 --- a/src/main/java/io/github/hectorvent/floci/services/emr/EmrSparkSteps.java +++ b/src/main/java/io/github/hectorvent/floci/services/emr/EmrSparkSteps.java @@ -3,7 +3,9 @@ package io.github.hectorvent.floci.services.emr; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.services.emr.model.EmrCluster; import io.github.hectorvent.floci.services.emr.model.EmrStep; +import io.github.hectorvent.floci.services.emrserverless.EmrServerlessSparkRunner; import java.util.ArrayList; import java.util.LinkedHashMap; @@ -65,6 +67,16 @@ final class EmrSparkSteps { return application; } + /** + * The S3 folder a step's logs go to, or null when its cluster has no {@code LogUri}: "If a value is not + * provided, logs are not created". The Management Guide's "Log locations" puts step logs at + * {@code //steps//}. + */ + static String logFolder(EmrCluster cluster, EmrStep step) { + return EmrServerlessSparkRunner.logFolder(cluster.getLogUri(), + cluster.getId() + "/steps/" + step.getId() + "/"); + } + /** * The {@code spark-defaults} properties of a cluster's {@code Configurations}, the JSON array * {@code RunJobFlow} was given, or none. diff --git a/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessJobRunService.java b/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessJobRunService.java index 5cbab6d897..a1203183d3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessJobRunService.java +++ b/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessJobRunService.java @@ -84,6 +84,7 @@ public class EmrServerlessJobRunService implements Resettable { // The service a container run's driver belongs to, which names it and labels it. private static final String SERVICE = "emr-serverless"; private static final String SPARK_DEFAULTS = "spark-defaults"; + private static final String S3_MONITORING = "s3MonitoringConfiguration"; // No source gives AWS's wording for these; they are Floci's. static final String HIVE_NOT_RUN = "Floci runs Spark job runs only, and this is a Hive job run."; static final String INTERRUPTED = "Floci stopped while the job run was in progress."; @@ -459,7 +460,7 @@ public class EmrServerlessJobRunService implements Resettable { ? Duration.ZERO : Duration.ofMinutes(minutes); SparkJobRunner.Job job = new SparkJobRunner.Job(SERVICE, run.getJobRunId(), arn.accountId(), arn.region(), run.getReleaseLabel(), imageTemplate, dockerNetwork, run.getExecutionRole(), sparkDefaults(app, run), - application(run.getJobDriver().getSparkSubmit()), timeout); + application(run.getJobDriver().getSparkSubmit()), timeout, driverLogFolder(app, run)); executing.add(run.getJobRunId()); long launchedIn = generation; runExecutor.execute(() -> execute(job, launchedIn)); @@ -611,6 +612,43 @@ public class EmrServerlessJobRunService implements Resettable { return properties; } + /** + * The S3 folder a run's driver logs go to, or null without an S3 log destination. The run's + * {@code s3MonitoringConfiguration} supersedes the application's ("MonitoringConfiguration - + * Configuration type"), and an empty one removes it. Under its {@code logUri} the user guide puts a + * run's logs at {@code /applications//jobs/}, with + * {@code /attempts/} after it for "all streaming jobs and any batch jobs that have retry + * enabled" from release 7.1.0, and the driver's in {@code SPARK_DRIVER/}. + */ + static String driverLogFolder(Application app, JobRun run) { + Object overrides = run.getConfigurationOverrides() != null + ? run.getConfigurationOverrides().get("monitoringConfiguration") : null; + Object s3; + if (overrides instanceof Map monitoring && monitoring.containsKey(S3_MONITORING)) { + s3 = monitoring.get(S3_MONITORING); + } else { + s3 = app.getMonitoringConfiguration() != null + ? app.getMonitoringConfiguration().getProperties().get(S3_MONITORING) : null; + } + String logUri = s3 instanceof Map configuration && configuration.get("logUri") instanceof String uri + ? uri : null; + String attempts = retried(run) && retriesAttempts(run.getReleaseLabel()) ? "attempts/" + ATTEMPT + "/" : ""; + return EmrServerlessSparkRunner.logFolder(logUri, "applications/" + run.getApplicationId() + "/jobs/" + + run.getJobRunId() + "/" + attempts + "SPARK_DRIVER/"); + } + + // A STREAMING run is retried, and a BATCH run whose retryPolicy allows more than one attempt. + private static boolean retried(JobRun run) { + Object maxAttempts = run.getRetryPolicy() != null ? run.getRetryPolicy().get("maxAttempts") : null; + return MODE_STREAMING.equals(run.getMode()) || maxAttempts instanceof Number number && number.intValue() > 1; + } + + // "EMR Serverless releases 7.1.0 and higher support retry attempts for streaming jobs and batch jobs." + private static boolean retriesAttempts(String releaseLabel) { + return releaseAtLeast(RELEASE_LABEL, releaseLabel, 7, 1) + || SPARK_RUNTIME_RELEASE_LABEL.matcher(releaseLabel != null ? releaseLabel : "").matches(); + } + private static void addSparkDefaults(Map properties, Map configuration) { if (SPARK_DEFAULTS.equals(configuration.get("classification")) && configuration.get("properties") instanceof Map values) { diff --git a/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunner.java b/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunner.java index c6413b3faa..3326548c86 100644 --- a/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunner.java +++ b/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunner.java @@ -1,9 +1,14 @@ package io.github.hectorvent.floci.services.emrserverless; +import com.github.dockerjava.api.async.ResultCallback; import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.api.model.Container; +import com.github.dockerjava.api.model.Frame; +import com.github.dockerjava.api.model.StreamType; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.ContainerTeardown; +import io.github.hectorvent.floci.core.common.RequestScopes; +import io.github.hectorvent.floci.core.common.S3Uri; import io.github.hectorvent.floci.core.common.docker.ContainerBuilder; import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager; import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer; @@ -12,11 +17,14 @@ import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper; import io.github.hectorvent.floci.core.common.docker.LaunchedContainerAwsEnv; import io.github.hectorvent.floci.services.iam.model.SessionCreds; import io.github.hectorvent.floci.services.lambda.launcher.LambdaExecutionRoleCredentials; +import io.github.hectorvent.floci.services.s3.S3Service; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import java.io.ByteArrayOutputStream; import java.io.Closeable; +import java.io.IOException; import java.time.Clock; import java.time.Duration; import java.time.Instant; @@ -26,7 +34,10 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; +import java.util.regex.Pattern; +import java.util.zip.GZIPOutputStream; /** * Runs a Spark application's {@code spark-submit} in a container of an EMR Serverless image, for an EMR @@ -34,7 +45,8 @@ import java.util.concurrent.atomic.AtomicReference; * supplies at run time, which the public image lacks, so the runner starts {@code spark-submit} itself, * in local mode: the container holds the driver and its executors. The container reaches Floci as the * other containers Floci launches do, with the run's execution role as its credentials, and S3A, which - * takes {@code s3://} on every release, is pointed at Floci's S3. + * takes {@code s3://} on every release, is pointed at Floci's S3. Once the driver ends, its standard output + * and error go, gzipped, to the run's log folder in Floci's S3, when it has one. */ @ApplicationScoped public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardown { @@ -52,6 +64,11 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo private static final String DOUBLE_QUOTE_ESCAPES = "\"\\$`\n"; // How often a running driver is looked at, as Batch's runner looks at its jobs. private static final Duration POLL_INTERVAL = Duration.ofMillis(250); + // A log folder may be given in a Hadoop scheme, as an EMR cluster's LogUri often is (s3n://). + private static final Pattern HADOOP_S3_SCHEME = Pattern.compile("^s3[an]://"); + private static final String GZIP = "application/x-gzip"; + // How long reading an ended driver's output may take; Docker's log rotation bounds its size. + private static final Duration LOG_READ_TIMEOUT = Duration.ofSeconds(60); // The runs inside run(); a stop for a run not here comes after its driver has gone, and is dropped. private final ConcurrentHashMap launches = new ConcurrentHashMap<>(); @@ -61,6 +78,7 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo private final ContainerLogStreamer logStreamer; private final LaunchedContainerAwsEnv awsEnv; private final LambdaExecutionRoleCredentials roleCredentials; + private final S3Service s3Service; private final EmulatorConfig config; private final Clock clock; private final Duration pollInterval; @@ -68,20 +86,22 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo @Inject public EmrServerlessSparkRunner(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager, ContainerLogStreamer logStreamer, LaunchedContainerAwsEnv awsEnv, - LambdaExecutionRoleCredentials roleCredentials, EmulatorConfig config, - Clock clock) { - this(containerBuilder, lifecycleManager, logStreamer, awsEnv, roleCredentials, config, clock, POLL_INTERVAL); + LambdaExecutionRoleCredentials roleCredentials, S3Service s3Service, + EmulatorConfig config, Clock clock) { + this(containerBuilder, lifecycleManager, logStreamer, awsEnv, roleCredentials, s3Service, config, clock, + POLL_INTERVAL); } EmrServerlessSparkRunner(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager, ContainerLogStreamer logStreamer, LaunchedContainerAwsEnv awsEnv, - LambdaExecutionRoleCredentials roleCredentials, EmulatorConfig config, Clock clock, - Duration pollInterval) { + LambdaExecutionRoleCredentials roleCredentials, S3Service s3Service, + EmulatorConfig config, Clock clock, Duration pollInterval) { this.containerBuilder = containerBuilder; this.lifecycleManager = lifecycleManager; this.logStreamer = logStreamer; this.awsEnv = awsEnv; this.roleCredentials = roleCredentials; + this.s3Service = s3Service; this.config = config; this.clock = clock; this.pollInterval = pollInterval; @@ -123,7 +143,9 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo } logHandle = logStreamer.attachConsoleOnly(containerId, job.service() + ":" + job.runId()); progress.started(); - return awaitEnd(containerId, job, launch, progress); + Outcome outcome = awaitEnd(containerId, job, launch, progress); + writeLogs(job, launch); + return outcome; } catch (InterruptedException e) { // Floci is shutting down: its teardown stops the driver. Thread.currentThread().interrupt(); @@ -206,6 +228,22 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo } } + /** + * The folder {@code path} names under {@code logUri}, the S3 location a service writes its logs to, or + * null when there is none: {@code path} follows {@code logUri} after one slash, whether or not + * {@code logUri} ends in one. + */ + public static String logFolder(String logUri, String path) { + if (logUri == null || logUri.isBlank()) { + return null; + } + int end = logUri.length(); + while (end > 0 && logUri.charAt(end - 1) == '/') { + end--; + } + return logUri.substring(0, end) + "/" + path; + } + /** * The image a release's runs use: {@code imageTemplate}, with {@code %s} standing for the release * label, or, when it is null, the release's public EMR Serverless image. @@ -332,6 +370,105 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo return Outcome.halted(); } + /** + * Writes the ended driver's standard output and error, each gzipped, to {@code stdout.gz} and + * {@code stderr.gz} in the job's log folder, while its container is still the run's. A driver a cancel or + * its timeout ended is still running, so it is stopped first, and then changes nothing more and leaves + * all it wrote; run() removes it after. One Floci's teardown took leaves nothing. Logs that cannot be + * written, to a bucket that does not exist say, leave the run as it ended. + */ + private void writeLogs(Job job, Launch launch) { + String containerId = launch.container.get(); + if (job.logFolder() == null || containerId == null) { + return; + } + // Closed however the read ends, which ends Docker's stream and the compressors. + try (DriverOutput output = new DriverOutput()) { + S3Uri folder = S3Uri.parse(HADOOP_S3_SCHEME.matcher(job.logFolder()).replaceFirst("s3://")); + lifecycleManager.stop(containerId, STOP_TIMEOUT_SECONDS); + lifecycleManager.getDockerClient().logContainerCmd(containerId) + .withStdOut(true) + .withStdErr(true) + .withFollowStream(false) + .withTimestamps(false) + .exec(output); + if (!output.awaitCompletion(LOG_READ_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS)) { + throw new IOException("reading the driver's output took longer than " + LOG_READ_TIMEOUT); + } + byte[] stdout = output.gzipped(StreamType.STDOUT); + byte[] stderr = output.gzipped(StreamType.STDERR); + RequestScopes.runAs(job.accountId(), job.region(), () -> { + s3Service.putObject(folder.bucket(), folder.key() + "stdout.gz", stdout, GZIP, Map.of()); + s3Service.putObject(folder.bucket(), folder.key() + "stderr.gz", stderr, GZIP, Map.of()); + }); + } catch (InterruptedException e) { + // Floci is shutting down: the run ends as its driver did, without its logs. + Thread.currentThread().interrupt(); + } catch (IOException | RuntimeException e) { + LOG.warnv("Could not write the logs of Spark run {0} of {1} to {2}: {3}", job.runId(), job.service(), + job.logFolder(), e.getMessage()); + } + } + + /** + * An ended driver's output as Docker gives it, each stream gzipped as it arrives: what is not + * standard error, as a container with a terminal gives, is standard output. Closing it, as Docker does + * once it has sent everything, or the reader does whichever way the read ends, ends Docker's stream and + * the compressors, and a frame that still comes after is dropped. + */ + private static final class DriverOutput extends ResultCallback.Adapter { + private final ByteArrayOutputStream stdout = new ByteArrayOutputStream(); + private final ByteArrayOutputStream stderr = new ByteArrayOutputStream(); + private final GZIPOutputStream stdoutGzip; + private final GZIPOutputStream stderrGzip; + // Guarded by this. + private boolean compressorsClosed; + + DriverOutput() throws IOException { + stdoutGzip = new GZIPOutputStream(stdout); + stderrGzip = new GZIPOutputStream(stderr); + } + + @Override + public synchronized void onNext(Frame frame) { + if (compressorsClosed) { + return; + } + try { + (frame.getStreamType() == StreamType.STDERR ? stderrGzip : stdoutGzip).write(frame.getPayload()); + } catch (IOException e) { + onError(e); + } + } + + // A stream's whole gzipped output, once Docker has sent everything. + synchronized byte[] gzipped(StreamType stream) throws IOException { + closeCompressors(); + return (stream == StreamType.STDERR ? stderr : stdout).toByteArray(); + } + + @Override + public void close() throws IOException { + try { + super.close(); + } finally { + synchronized (this) { + closeCompressors(); + } + } + } + + // Guarded by this. Closing a compressor writes its trailer and frees its deflater, once only. + private void closeCompressors() throws IOException { + compressorsClosed = true; + try { + stdoutGzip.close(); + } finally { + stderrGzip.close(); + } + } + } + /** * A run inside {@link #run}: whether it is to stop, and its driver's container once it has one, which * whoever stops the run first claims, run() itself or Floci's teardown. diff --git a/src/main/java/io/github/hectorvent/floci/services/emrserverless/SparkJobRunner.java b/src/main/java/io/github/hectorvent/floci/services/emrserverless/SparkJobRunner.java index 33baafce67..c355169353 100644 --- a/src/main/java/io/github/hectorvent/floci/services/emrserverless/SparkJobRunner.java +++ b/src/main/java/io/github/hectorvent/floci/services/emrserverless/SparkJobRunner.java @@ -53,12 +53,13 @@ public interface SparkJobRunner { * the release's public EMR Serverless image, a null network the global default); the execution role * whose credentials it gets; the {@code spark-defaults} properties that apply to it; * {@code application}, what follows Floci's own settings on {@code spark-submit}'s command line (the - * run's options, then its application and that application's arguments); and how long it may run - * ({@link Duration#ZERO} for no limit). + * run's options, then its application and that application's arguments); how long it may run + * ({@link Duration#ZERO} for no limit); and the S3 folder its driver's {@code stdout.gz} and + * {@code stderr.gz} go to once it ends, ending in a slash (null for none). */ record Job(String service, String runId, String accountId, String region, String releaseLabel, String imageTemplate, String dockerNetwork, String executionRole, Map sparkDefaults, - List application, Duration timeout) { + List application, Duration timeout, String logFolder) { } /** diff --git a/src/test/java/io/github/hectorvent/floci/core/common/S3UriTest.java b/src/test/java/io/github/hectorvent/floci/core/common/S3UriTest.java new file mode 100644 index 0000000000..0cc0894fd8 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/S3UriTest.java @@ -0,0 +1,33 @@ +package io.github.hectorvent.floci.core.common; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class S3UriTest { + + @Test + void splitsTheBucketFromTheKey() { + assertEquals(new S3Uri("logs", "emr/j-1/steps/s-1/stderr.gz"), + S3Uri.parse("s3://logs/emr/j-1/steps/s-1/stderr.gz")); + } + + @Test + void keepsAPrefixsTrailingSlash() { + assertEquals(new S3Uri("logs", "emr/"), S3Uri.parse("s3://logs/emr/")); + } + + @Test + void aBucketAloneHasAnEmptyKey() { + assertEquals(new S3Uri("logs", ""), S3Uri.parse("s3://logs")); + assertEquals(new S3Uri("logs", ""), S3Uri.parse("s3://logs/")); + } + + @Test + void refusesAnotherSchemeOrNoBucket() { + assertThrows(IllegalArgumentException.class, () -> S3Uri.parse("https://logs/emr/")); + assertThrows(IllegalArgumentException.class, () -> S3Uri.parse("s3:///emr/")); + assertThrows(IllegalArgumentException.class, () -> S3Uri.parse(null)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerTeardownTest.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerTeardownTest.java index e34a245665..1db50c6f28 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerTeardownTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerTeardownTest.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.core.common.docker; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.command.RemoveContainerCmd; import com.github.dockerjava.api.command.StopContainerCmd; +import com.github.dockerjava.api.exception.NotFoundException; import com.github.dockerjava.api.exception.NotModifiedException; import org.junit.jupiter.api.Test; @@ -24,8 +25,10 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -168,4 +171,24 @@ class ContainerLifecycleManagerTeardownTest { assertEquals(0, failure.getSuppressed().length); } + @Test + void aStopLeavesTheContainerInPlaceAndCountsAnExitedOrMissingOneAsStopped() { + DockerClient docker = mock(DockerClient.class); + ContainerLifecycleManager manager = new ContainerLifecycleManager(docker, null, null, null); + StopContainerCmd stop = mock(StopContainerCmd.class); + when(docker.stopContainerCmd(anyString())).thenReturn(stop); + when(stop.withTimeout(anyInt())).thenReturn(stop); + doAnswer(invocation -> null) + .doThrow(new NotModifiedException("Container already stopped")) + .doThrow(new NotFoundException("No such container")) + .when(stop).exec(); + + manager.stop("running", 0); + manager.stop("exited", 0); + manager.stop("gone", 0); + + verify(stop, times(3)).exec(); + verify(docker, never()).removeContainerCmd(anyString()); + } + } diff --git a/src/test/java/io/github/hectorvent/floci/services/emr/EmrServiceContainerStepsTest.java b/src/test/java/io/github/hectorvent/floci/services/emr/EmrServiceContainerStepsTest.java index 4c6de470b4..f9d4f5684d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/emr/EmrServiceContainerStepsTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/emr/EmrServiceContainerStepsTest.java @@ -81,6 +81,20 @@ class EmrServiceContainerStepsTest { assertEquals(List.of(REPORT, "s3://bucket/out/"), job.application()); assertEquals(Map.of("spark.executor.cores", "2"), job.sparkDefaults()); assertEquals(Duration.ZERO, job.timeout()); + assertNull(job.logFolder()); + } + + @Test + void aStepsLogsGoUnderItsClustersLogUri() { + EmrCluster requested = cluster("logged", true, sparkStep("report", "CONTINUE")); + // The DescribeCluster example in the Management Guide has a LogUri in the s3n:// scheme. + requested.setLogUri("s3n://aws-logs-" + ACCOUNT + "-" + REGION + "/elasticmapreduce/"); + EmrCluster cluster = service.runJobFlow(requested, REGION); + + fixture.runStepThread(); + + assertEquals("s3n://aws-logs-" + ACCOUNT + "-" + REGION + "/elasticmapreduce/" + cluster.getId() + "/steps/" + + cluster.getSteps().get(0).getId() + "/", runner.jobs.get(0).logFolder()); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessJobRunServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessJobRunServiceTest.java index 8011b27c59..bd5ffd05a1 100644 --- a/src/test/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessJobRunServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessJobRunServiceTest.java @@ -7,10 +7,12 @@ import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.emrserverless.model.Application; import io.github.hectorvent.floci.services.emrserverless.model.CreateApplicationRequest; import io.github.hectorvent.floci.services.emrserverless.model.JobDriver; import io.github.hectorvent.floci.services.emrserverless.model.JobRun; import io.github.hectorvent.floci.services.emrserverless.model.JobRunRecord; +import io.github.hectorvent.floci.services.emrserverless.model.MonitoringConfiguration; import io.github.hectorvent.floci.services.emrserverless.model.RuntimeConfiguration; import io.github.hectorvent.floci.services.emrserverless.model.StartJobRunRequest; import io.github.hectorvent.floci.services.iam.IamService; @@ -261,6 +263,71 @@ class EmrServerlessJobRunServiceTest { assertEquals(List.of("s3://bucket/jobs/app.jar"), job.application()); assertEquals(Duration.ofMinutes(30), job.timeout()); assertEquals(Duration.ZERO, runner.jobs.get(1).timeout()); + assertNull(job.logFolder()); + } + + @Test + void aRunsDriverLogsGoUnderItsOwnS3LogUriOrElseTheApplications() { + FakeRunner runner = new FakeRunner(); + EmrServerlessJobRunService service = dockerService(runner); + CreateApplicationRequest create = new CreateApplicationRequest(); + create.setName("logged"); + create.setReleaseLabel("emr-7.5.0"); + create.setType("SPARK"); + create.setClientToken(UUID.randomUUID().toString()); + create.setMonitoringConfiguration(s3LogUri("s3://logs/app-level")); + String logged = applications.createApplication(create).getApplicationId(); + StartJobRunRequest ownLogUri = request(null, null); + ownLogUri.setConfigurationOverrides(Map.of("monitoringConfiguration", + Map.of("s3MonitoringConfiguration", Map.of("logUri", "s3://logs/job-level/")))); + // "To remove s3MonitoringConfiguration, pass an empty declaration {} for the configuration." + StartJobRunRequest removed = request(null, null); + removed.setConfigurationOverrides(Map.of("monitoringConfiguration", + Map.of("s3MonitoringConfiguration", Map.of()))); + + String inherited = service.startJobRun(logged, request(null, null)).getJobRunId(); + String overridden = service.startJobRun(logged, ownLogUri).getJobRunId(); + service.startJobRun(logged, removed); + for (int i = 0; i < 3; i++) { + runNext(); + } + + assertEquals("s3://logs/app-level/applications/" + logged + "/jobs/" + inherited + "/SPARK_DRIVER/", + runner.jobs.get(0).logFolder()); + assertEquals("s3://logs/job-level/applications/" + logged + "/jobs/" + overridden + "/SPARK_DRIVER/", + runner.jobs.get(1).logFolder()); + assertNull(runner.jobs.get(2).logFolder()); + } + + @Test + void aRetriedRunsDriverLogsAreUnderItsAttemptFromRelease710() { + Application app = new Application(); + app.setMonitoringConfiguration(s3LogUri("s3://logs")); + + assertEquals("s3://logs/applications/app/jobs/run/attempts/1/SPARK_DRIVER/", + EmrServerlessJobRunService.driverLogFolder(app, run("emr-7.1.0", "STREAMING", null))); + assertEquals("s3://logs/applications/app/jobs/run/attempts/1/SPARK_DRIVER/", + EmrServerlessJobRunService.driverLogFolder(app, run("emr-spark-8.1.0", "BATCH", 3))); + assertEquals("s3://logs/applications/app/jobs/run/SPARK_DRIVER/", + EmrServerlessJobRunService.driverLogFolder(app, run("emr-7.1.0", "BATCH", 1))); + assertEquals("s3://logs/applications/app/jobs/run/SPARK_DRIVER/", + EmrServerlessJobRunService.driverLogFolder(app, run("emr-7.0.0", "STREAMING", null))); + } + + private static MonitoringConfiguration s3LogUri(String logUri) { + MonitoringConfiguration monitoring = new MonitoringConfiguration(); + monitoring.setProperty("s3MonitoringConfiguration", Map.of("logUri", logUri)); + return monitoring; + } + + private static JobRun run(String releaseLabel, String mode, Integer maxAttempts) { + JobRun run = new JobRun(); + run.setApplicationId("app"); + run.setJobRunId("run"); + run.setReleaseLabel(releaseLabel); + run.setMode(mode); + run.setRetryPolicy(maxAttempts != null ? Map.of("maxAttempts", maxAttempts) : null); + return run; } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunnerTest.java b/src/test/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunnerTest.java index 987bd6f922..6549a28722 100644 --- a/src/test/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunnerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunnerTest.java @@ -1,34 +1,47 @@ package io.github.hectorvent.floci.services.emrserverless; import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.async.ResultCallback; import com.github.dockerjava.api.exception.InternalServerErrorException; import com.github.dockerjava.api.model.Container; +import com.github.dockerjava.api.model.Frame; +import com.github.dockerjava.api.model.StreamType; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.docker.ContainerBuilder; import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager; import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer; import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper; import io.github.hectorvent.floci.core.common.docker.LaunchedContainerAwsEnv; import io.github.hectorvent.floci.services.lambda.launcher.LambdaExecutionRoleCredentials; +import io.github.hectorvent.floci.services.s3.S3Service; import io.github.hectorvent.floci.testing.MutableClock; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import org.mockito.InOrder; +import java.io.ByteArrayInputStream; +import java.io.Closeable; +import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.zip.GZIPInputStream; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.RETURNS_SELF; import static org.mockito.Mockito.atLeastOnce; @@ -46,6 +59,7 @@ class EmrServerlessSparkRunnerTest { private final ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class); private final DockerClient docker = mock(DockerClient.class, RETURNS_DEEP_STUBS); private final SparkJobRunner.Progress progress = mock(SparkJobRunner.Progress.class); + private final S3Service s3 = mock(S3Service.class); @Test void sparkSubmitRunsLocallyOnFlocisS3ThenTheRunsOwnSettings() { @@ -241,6 +255,124 @@ class EmrServerlessSparkRunnerTest { verify(docker, never()).waitContainerCmd(anyString()); } + @Test + void theDriversOutputGoesGzippedToTheRunsLogFolderOnceItEnds() throws IOException { + EmrServerlessSparkRunner runner = runner(); + driverWrote(new Frame(StreamType.STDERR, bytes("INFO SparkContext: Running Spark version 3.5.2\n")), + new Frame(StreamType.STDOUT, bytes("Pi is roughly 3.14\n")), + new Frame(StreamType.STDOUT, bytes("done\n"))); + + SparkJobRunner.Outcome outcome = runner.run(job("s3://logs/emr/j-1/steps/s-1/"), progress); + + assertEquals(0, outcome.exitCode()); + assertEquals("Pi is roughly 3.14\ndone\n", written("logs", "emr/j-1/steps/s-1/stdout.gz")); + assertEquals("INFO SparkContext: Running Spark version 3.5.2\n", + written("logs", "emr/j-1/steps/s-1/stderr.gz")); + } + + @Test + void aLogFolderInAHadoopSchemeIsInTheSameBucket() throws IOException { + EmrServerlessSparkRunner runner = runner(); + driverWrote(new Frame(StreamType.STDOUT, bytes("done\n"))); + + runner.run(job("s3n://logs/emr/j-1/steps/s-1/"), progress); + + assertEquals("done\n", written("logs", "emr/j-1/steps/s-1/stdout.gz")); + } + + @Test + void aCancelledRunsDriverIsStoppedBeforeItsLogsAreReadAndRemovedAfterThey() { + EmrServerlessSparkRunner runner = runner(); + SparkJobRunner.Job job = job("s3://logs/emr/j-1/steps/s-1/"); + driverWrote(new Frame(StreamType.STDOUT, bytes("sleeping\n"))); + when(docker.inspectContainerCmd("driver").exec().getState().getRunning()).thenAnswer(look -> { + runner.stop(job.runId()); + return true; + }); + + SparkJobRunner.Outcome outcome = runner.run(job, progress); + + // Stopped first, the driver changes nothing while its output is read, and all of that output is there. + assertTrue(outcome.stopped()); + InOrder order = inOrder(lifecycle, docker, s3); + order.verify(lifecycle).stop("driver", 0); + order.verify(docker).logContainerCmd("driver"); + order.verify(s3).putObject(eq("logs"), eq("emr/j-1/steps/s-1/stdout.gz"), any(), anyString(), anyMap()); + order.verify(lifecycle).stopAndRemove("driver", null, 0); + } + + @Test + void anInterruptedLogReadEndsDockersStreamAndWritesNothing() throws IOException { + EmrServerlessSparkRunner runner = runner(); + Closeable stream = mock(Closeable.class); + // Floci shuts down while the output is read: Docker has started sending it, and never finishes. + when(docker.logContainerCmd("driver").withStdOut(true).withStdErr(true).withFollowStream(false) + .withTimestamps(false).exec(any())).thenAnswer(read -> { + ResultCallback.Adapter output = read.getArgument(0); + output.onStart(stream); + output.onNext(new Frame(StreamType.STDOUT, bytes("Pi is "))); + Thread.currentThread().interrupt(); + return output; + }); + + try { + SparkJobRunner.Outcome outcome = runner.run(job("s3://logs/emr/j-1/steps/s-1/"), progress); + + assertEquals(0, outcome.exitCode()); + verify(stream).close(); + verify(s3, never()).putObject(anyString(), anyString(), any(), anyString(), anyMap()); + } finally { + assertTrue(Thread.interrupted()); + } + } + + @Test + void logsThatCannotBeWrittenLeaveTheRunAsItEnded() { + EmrServerlessSparkRunner runner = runner(); + driverWrote(new Frame(StreamType.STDOUT, bytes("done\n"))); + when(s3.putObject(anyString(), anyString(), any(), anyString(), anyMap())) + .thenThrow(new AwsException("NoSuchBucket", "The specified bucket does not exist", 404)); + + SparkJobRunner.Outcome outcome = runner.run(job("s3://missing/emr/j-1/steps/s-1/"), progress); + + assertEquals(0, outcome.exitCode()); + verify(lifecycle).stopAndRemove("driver", null, 0); + } + + @Test + void aDriverFlocisTeardownTookWritesNoLogs() { + EmrServerlessSparkRunner runner = runner(); + when(docker.inspectContainerCmd("driver").exec().getState().getRunning()).thenAnswer(look -> { + runner.stopManagedContainers(); + return true; + }); + + SparkJobRunner.Outcome outcome = runner.run(job("s3://logs/emr/j-1/steps/s-1/"), progress); + + assertTrue(outcome.stopped()); + verify(docker, never()).logContainerCmd(anyString()); + verify(s3, never()).putObject(anyString(), anyString(), any(), anyString(), anyMap()); + } + + @Test + void aRunWithoutALogFolderReadsNoOutput() { + runner().run(job(Duration.ZERO), progress); + + verify(docker, never()).logContainerCmd(anyString()); + verify(lifecycle, never()).stop(anyString(), anyInt()); + } + + @Test + void aLogFolderFollowsTheLogUriAfterOneSlash() { + assertEquals("s3://logs/emr/j-1/steps/s-1/", + EmrServerlessSparkRunner.logFolder("s3://logs/emr/", "j-1/steps/s-1/")); + assertEquals("s3://logs/emr/j-1/steps/s-1/", + EmrServerlessSparkRunner.logFolder("s3://logs/emr", "j-1/steps/s-1/")); + assertEquals("s3://logs/j-1/steps/s-1/", EmrServerlessSparkRunner.logFolder("s3://logs//", "j-1/steps/s-1/")); + assertNull(EmrServerlessSparkRunner.logFolder(null, "j-1/steps/s-1/")); + assertNull(EmrServerlessSparkRunner.logFolder(" ", "j-1/steps/s-1/")); + } + @Test void driversAnEarlierProcessOfThisDeploymentLeftAreRemoved() { EmrServerlessSparkRunner runner = runner(); @@ -265,10 +397,36 @@ class EmrServerlessSparkRunnerTest { when(docker.inspectContainerCmd("driver").exec().getState().getRunning()).thenReturn(false); when(docker.inspectContainerCmd("driver").exec().getState().getExitCodeLong()).thenReturn(0L); return new EmrServerlessSparkRunner(builder, lifecycle, mock(ContainerLogStreamer.class), - mock(LaunchedContainerAwsEnv.class), mock(LambdaExecutionRoleCredentials.class), config, + mock(LaunchedContainerAwsEnv.class), mock(LambdaExecutionRoleCredentials.class), s3, config, new MutableClock(), Duration.ZERO); } + // What the driver wrote, as Docker gives it once asked for an ended container's output. + private void driverWrote(Frame... frames) { + when(docker.logContainerCmd("driver").withStdOut(true).withStdErr(true).withFollowStream(false) + .withTimestamps(false).exec(any())).thenAnswer(read -> { + ResultCallback.Adapter output = read.getArgument(0); + for (Frame frame : frames) { + output.onNext(frame); + } + output.onComplete(); + return output; + }); + } + + // The object the runner put at key, gunzipped. + private String written(String bucket, String key) throws IOException { + ArgumentCaptor data = ArgumentCaptor.forClass(byte[].class); + verify(s3).putObject(eq(bucket), eq(key), data.capture(), eq("application/x-gzip"), eq(Map.of())); + try (GZIPInputStream gunzip = new GZIPInputStream(new ByteArrayInputStream(data.getValue()))) { + return new String(gunzip.readAllBytes(), StandardCharsets.UTF_8); + } + } + + private static byte[] bytes(String text) { + return text.getBytes(StandardCharsets.UTF_8); + } + private static Container driver(String id, String owner) { Container container = mock(Container.class); when(container.getId()).thenReturn(id); @@ -281,19 +439,28 @@ class EmrServerlessSparkRunnerTest { return job(List.of("s3://bucket/jobs/app.jar"), Map.of(), timeout); } + private static SparkJobRunner.Job job(String logFolder) { + return job(null, List.of("s3://bucket/jobs/app.jar"), Map.of(), Duration.ZERO, logFolder); + } + private static SparkJobRunner.Job job(List application, Map sparkDefaults) { return job(application, sparkDefaults, Duration.ZERO); } private static SparkJobRunner.Job job(List application, Map sparkDefaults, Duration timeout) { - return job(null, application, sparkDefaults, timeout); + return job(null, application, sparkDefaults, timeout, null); } private static SparkJobRunner.Job job(String imageTemplate, List application, Map sparkDefaults, Duration timeout) { + return job(imageTemplate, application, sparkDefaults, timeout, null); + } + + private static SparkJobRunner.Job job(String imageTemplate, List application, + Map sparkDefaults, Duration timeout, String logFolder) { return new SparkJobRunner.Job("emr-serverless", "00f0000000000001", "123456789012", "eu-west-1", "emr-7.5.0", imageTemplate, "floci-network", "arn:aws:iam::123456789012:role/job", sparkDefaults, application, - timeout); + timeout, logFolder); } }