feat(emr,emr-serverless): write Spark driver logs to S3 (#6620)

In the docker runner mode a Spark driver's output went only to Floci's
log. Once a driver ends, the shared runner now reads its standard output
and error from Docker and puts them, gzipped, into Floci's S3 as
stdout.gz and stderr.gz in the run's log folder, while the container is
still the run's. A driver a cancel or its timeout ended is stopped
first, through a new ContainerLifecycleManager.stop that leaves the
container in place, so it changes nothing more while its output is read
and the logs hold all it wrote; a driver Floci's teardown took writes
nothing. Logs that cannot be written leave the run as it ended.

- EMR steps: under the cluster's LogUri, at
  <LogUri>/<cluster-id>/steps/<step-id>/ (Management Guide, "Log
  locations"); without a LogUri "logs are not created". An s3n:// or
  s3a:// LogUri names the same bucket.
- EMR Serverless job runs: under the run's s3MonitoringConfiguration
  logUri, or else the application's (the user guide merges them by
  configuration type, and an empty one at the run removes it), at
  applications/<applicationId>/jobs/<jobRunId>/SPARK_DRIVER/, with
  attempts/1/ before SPARK_DRIVER/ for a STREAMING run or a BATCH run
  whose retry policy allows more than one attempt, on 7.1.0 or later.

FailureDetails gets no LogFile: the Management Guide ties it to a root
cause EMR identifies, and Floci's Reason is always "Unknown Error".

core.common.S3Uri splits the folder's s3:// URI into bucket and key.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-26 19:16:40 -05:00
1 parent 13289b0aef
commit 0a47ddd5e4
14 files changed
+578 -35

No files matched your search

@@ -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));
}
}
@@ -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.
@@ -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));
@@ -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 <LogUri>/<cluster-id>/steps/<step-id>/}.
*/
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.
@@ -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/<applicationId>/jobs/<jobId>}, with
* {@code /attempts/<attemptNumber>} 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<String, String> properties, Map<?, ?> configuration) {
if (SPARK_DEFAULTS.equals(configuration.get("classification"))
&& configuration.get("properties") instanceof Map<?, ?> values) {
@@ -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<String, Launch> 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<Frame> {
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.
@@ -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<String, String> sparkDefaults,
List<String> application, Duration timeout) {
List<String> application, Duration timeout, String logFolder) {
}
/**