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,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));
}
}
@@ -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());
}
}
@@ -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
@@ -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
@@ -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<Frame> 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<Frame> 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<byte[]> 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<String> application, Map<String, String> sparkDefaults) {
return job(application, sparkDefaults, Duration.ZERO);
}
private static SparkJobRunner.Job job(List<String> application, Map<String, String> sparkDefaults,
Duration timeout) {
return job(null, application, sparkDefaults, timeout);
return job(null, application, sparkDefaults, timeout, null);
}
private static SparkJobRunner.Job job(String imageTemplate, List<String> application,
Map<String, String> sparkDefaults, Duration timeout) {
return job(imageTemplate, application, sparkDefaults, timeout, null);
}
private static SparkJobRunner.Job job(String imageTemplate, List<String> application,
Map<String, String> 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);
}
}