feat(emr-containers): send a job run's driver logs to its S3 and CloudWatch destinations (#9208)

A docker job run's driver output went to Floci's log only, whatever its
monitoringConfiguration asked for.

- With an s3MonitoringConfiguration, the driver's stdout.gz and
  stderr.gz go to "/logUri/virtual-cluster-id/jobs/job-id/containers/
  spark-application-id/spark-job-id-driver/" once the run ends, as the
  development guide's "Configure a job run to use Amazon S3 logs" lays
  out a driver's logs.
- With a cloudWatchMonitoringConfiguration, its standard output and
  standard error go, as it writes them, to the streams
  "logStreamPrefix/virtual-cluster-id/jobs/job-id/containers/
  spark-application-id/spark-job-id-driver/(stderr/stdout)" in its
  logGroupName, the group and streams created if they do not exist.
- The spark-application-id has the form a Spark application on
  Kubernetes gets, spark- and 32 hexadecimal digits, and is Floci's own.
- A job template's configurationOverrides, whose parametric model need
  not name a destination's log group or log URI, are held to
  StartJobRun's ConfigurationOverrides, as a request's own are.
- The runner gzips a driver's output into temporary files rather than
  memory, and the per-stream CloudWatch forwarding EMR Serverless shares
  sends each line as written, but for an empty one, which CloudWatch
  Logs refuses, and each stream's lines of one emission in one call.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-22 14:08:25 -04:00
1 parent 0638a7f1d1
commit 5c62948838
11 files changed
+386 -46

No files matched your search

@@ -40,6 +40,7 @@ import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_SELF;
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;
@@ -209,6 +210,30 @@ class ContainerLogStreamerTest {
eq("us-east-1"));
}
@Test
void aByStreamAttachSendsAFramesLinesInOneCallEachAsWritten() {
DockerClient dockerClient = mock(DockerClient.class);
LogContainerCmd command = mock(LogContainerCmd.class, RETURNS_SELF);
when(dockerClient.logContainerCmd("container-1")).thenReturn(command);
CloudWatchLogsService cloudWatchLogsService = mock(CloudWatchLogsService.class);
ContainerLogStreamer streamer = new ContainerLogStreamer(dockerClient, cloudWatchLogsService);
streamer.attachByStreamForAccount("555555555555", "container-1", "/emr-on-eks/jobs", "driver/stdout",
"driver/stderr", "us-east-1", "emr-containers:1");
ArgumentCaptor<ContainerLogStreamer.LogReassemblyCallback> callback =
ArgumentCaptor.forClass(ContainerLogStreamer.LogReassemblyCallback.class);
verify(command).exec(callback.capture());
LogCapture.capture(ContainerLogStreamer.class, () -> callback.getValue()
.onNext(new Frame(StreamType.STDOUT, utf8("first\n \n indented \r\n\nlast\n"))));
// One call for the frame's lines, which keep their whitespace; the empty one, which CloudWatch Logs refuses
// as an event, is left out.
verify(cloudWatchLogsService, times(1)).putLogEventsForAccount(any(), any(), any(), anyList(), any());
verify(cloudWatchLogsService).putLogEventsForAccount(eq("555555555555"), eq("/emr-on-eks/jobs"),
eq("driver/stdout"), argThat(events -> events.stream().map(event -> event.get("message")).toList()
.equals(List.of("first", " ", " indented ", "last"))), eq("us-east-1"));
}
@Test
void aByStreamAttachForwardsAStreamWithoutALogStreamOnlyToTheConsole() {
DockerClient dockerClient = mock(DockerClient.class);
@@ -961,6 +961,64 @@ class EmrContainersServiceTest {
}
}
@Test
void dockerRunsDriverLogsGoUnderASparkApplicationIdOfItsOwn() {
FakeRunner runner = new FakeRunner();
QueuedExecutor executor = new QueuedExecutor();
EmrContainersService service = dockerService(runner, executor);
String clusterId = virtualCluster(service, EKS_CLUSTER);
String id = service.startJobRun(clusterId, json("""
{"clientToken": "logs", "executionRoleArn": "%s", "releaseLabel": "%s",
"jobDriver": {"sparkSubmitJobDriver": {"entryPoint": "s3://bucket/pi.py"}},
"configurationOverrides": {"monitoringConfiguration": {
"s3MonitoringConfiguration": {"logUri": "s3://logs"},
"cloudWatchMonitoringConfiguration": {"logGroupName": "jobs", "logStreamNamePrefix": "p"}}}}
""".formatted(ROLE, RELEASE))).get("id").textValue();
executor.runAll();
SparkJobRunner.Job job = runner.jobs.getFirst();
String driver = clusterId + "/jobs/" + id + "/containers/spark-[0-9a-f]{32}/spark-" + id + "-driver/";
assertTrue(job.logFolder().matches("s3://logs/" + driver), job.logFolder());
assertEquals("jobs", job.cloudWatchLogs().logGroup());
assertTrue(job.cloudWatchLogs().stdoutStream().matches("p/" + driver + "stdout"));
assertEquals(job.cloudWatchLogs().stdoutStream().replace("/stdout", "/stderr"),
job.cloudWatchLogs().stderrStream());
assertTrue(job.logFolder().endsWith(job.cloudWatchLogs().stdoutStream().substring(2).replace("stdout", "")),
"the same Spark application id names both");
}
@Test
void monitoringDestinationWithoutItsLogGroupOrUriIsRefusedFromATemplateAsFromARequest() {
EmrContainersService service = service(0);
String clusterId = virtualCluster(service, EKS_CLUSTER);
// The template's parametric model lets the destination leave its log group out.
String templateId = service.createJobTemplate(json("""
{"name": "t", "clientToken": "%s", "jobTemplateData": {
"executionRoleArn": "%s", "releaseLabel": "%s",
"jobDriver": {"sparkSubmitJobDriver": {"entryPoint": "s3://bucket/pi.py"}},
"configurationOverrides": {"monitoringConfiguration": {
"cloudWatchMonitoringConfiguration": {"logStreamNamePrefix": "p"}}}}}
""".formatted(UUID.randomUUID(), ROLE, RELEASE))).get("id").textValue();
AwsException fromTemplate = assertThrows(AwsException.class, () -> service.startJobRun(clusterId, json("""
{"clientToken": "%s", "jobTemplateId": "%s"}
""".formatted(UUID.randomUUID(), templateId))));
AwsException fromRequest = assertThrows(AwsException.class, () -> service.startJobRun(clusterId, json("""
{"clientToken": "%s", "executionRoleArn": "%s", "releaseLabel": "%s",
"jobDriver": {"sparkSubmitJobDriver": {"entryPoint": "s3://bucket/pi.py"}},
"configurationOverrides": {"monitoringConfiguration": {"s3MonitoringConfiguration": {}}}}
""".formatted(UUID.randomUUID(), ROLE, RELEASE))));
assertEquals("ValidationException", fromTemplate.getErrorCode());
assertTrue(fromTemplate.getMessage().contains(
"monitoringConfiguration.cloudWatchMonitoringConfiguration.logGroupName"), fromTemplate.getMessage());
assertEquals("ValidationException", fromRequest.getErrorCode());
assertTrue(fromRequest.getMessage().contains("logUri"), fromRequest.getMessage());
assertTrue(service.listJobRuns(clusterId, ListQuery.of(null, null, null, null, null), null)
.get("jobRuns").isEmpty(), "neither run is stored");
}
@Test
void immediateModeNeverStartsAContainer() {
EmrContainersService service = service(0);
@@ -18,12 +18,14 @@ class EmrContainersSparkJobsTest {
private static final String ARN =
"arn:aws:emr-containers:eu-west-1:123456789012:/virtualclusters/vc1/jobruns/run1";
private static final String ROLE = "arn:aws:iam::123456789012:role/emr-job";
private static final String APPLICATION = "spark-0123456789abcdef0123456789abcdef";
private final ObjectMapper mapper = new ObjectMapper();
private ObjectNode run(String jobDriver, String configurationOverrides) throws Exception {
ObjectNode run = (ObjectNode) mapper.readTree("""
{"id": "run1", "arn": "%s", "releaseLabel": "emr-7.2.0-20240610", "executionRoleArn": "%s",
{"id": "run1", "virtualClusterId": "vc1", "arn": "%s", "releaseLabel": "emr-7.2.0-20240610",
"executionRoleArn": "%s",
"jobDriver": %s}
""".formatted(ARN, ROLE, jobDriver));
if (configurationOverrides != null) {
@@ -63,7 +65,7 @@ class EmrContainersSparkJobsTest {
{"classification": "spark-defaults", "properties": {"spark.sql.shuffle.partitions": "4"}}]}
""");
SparkJobRunner.Job job = EmrContainersSparkJobs.job(run, null, "floci-net");
SparkJobRunner.Job job = EmrContainersSparkJobs.job(run, null, "floci-net", APPLICATION);
assertEquals("emr-containers", job.service());
assertEquals("run1", job.runId());
@@ -84,6 +86,49 @@ class EmrContainersSparkJobsTest {
assertEquals(List.of("s3://bucket/env.tar.gz#env"), job.archives());
assertTrue(job.environment().isEmpty());
assertNull(job.executors());
assertNull(job.logFolder(), "without an S3 monitoring configuration");
assertNull(job.cloudWatchLogs(), "without a CloudWatch monitoring configuration");
}
@Test
void driverLogsGoWhereTheRunsMonitoringConfigurationSendsThem() throws Exception {
ObjectNode run = run("""
{"sparkSubmitJobDriver": {"entryPoint": "s3://bucket/pi.py"}}
""", """
{"monitoringConfiguration": {
"s3MonitoringConfiguration": {"logUri": "s3://logs/emr/"},
"cloudWatchMonitoringConfiguration": {"logGroupName": "/emr-on-eks/jobs",
"logStreamNamePrefix": "nightly"}}}
""");
SparkJobRunner.Job job = EmrContainersSparkJobs.job(run, null, null, APPLICATION);
String driver = "vc1/jobs/run1/containers/" + APPLICATION + "/spark-run1-driver/";
assertEquals("s3://logs/emr/" + driver, job.logFolder());
assertEquals(new SparkJobRunner.CloudWatchLogs("/emr-on-eks/jobs", "nightly/" + driver + "stdout",
"nightly/" + driver + "stderr"), job.cloudWatchLogs());
}
@Test
void driverLogStreamsStartAtTheVirtualClusterWithoutAPrefix() throws Exception {
ObjectNode run = run("""
{"sparkSubmitJobDriver": {"entryPoint": "s3://bucket/pi.py"}}
""", """
{"monitoringConfiguration": {"s3MonitoringConfiguration": {"logUri": "s3://logs"},
"cloudWatchMonitoringConfiguration": {"logGroupName": "jobs"}}}
""");
SparkJobRunner.Job job = EmrContainersSparkJobs.job(run, null, null, APPLICATION);
String driver = "vc1/jobs/run1/containers/" + APPLICATION + "/spark-run1-driver/";
assertEquals("s3://logs/" + driver, job.logFolder());
assertEquals(new SparkJobRunner.CloudWatchLogs("jobs", driver + "stdout", driver + "stderr"),
job.cloudWatchLogs());
}
@Test
void sparkApplicationIdHasTheFormSparkOnKubernetesGivesIt() {
assertTrue(EmrContainersService.sparkApplicationId().matches("spark-[0-9a-f]{32}"));
}
@Test
@@ -93,7 +138,7 @@ class EmrContainersSparkJobsTest {
"sparkSqlParameters": "--conf spark.executor.instances=2 -hivevar table=reviews"}}
""", null);
SparkJobRunner.Job job = EmrContainersSparkJobs.job(run, null, null);
SparkJobRunner.Job job = EmrContainersSparkJobs.job(run, null, null, APPLICATION);
assertEquals(List.of("spark-sql", "--conf", "spark.executor.instances=2", "-hivevar", "table=reviews", "-f",
"s3://bucket/query.sql"), job.command());
@@ -112,7 +157,7 @@ class EmrContainersSparkJobsTest {
"properties": {"spark.kubernetes.container.image": "custom/all:1"}}]}
""");
SparkJobRunner.Job job = EmrContainersSparkJobs.job(run, null, null);
SparkJobRunner.Job job = EmrContainersSparkJobs.job(run, null, null, APPLICATION);
assertEquals("custom/driver:1", job.customImage(), "the driver's own image wins over the job's");
assertEquals(Map.of("PYSPARK_PYTHON", "./env/bin/python"), job.environment());
@@ -121,6 +166,6 @@ class EmrContainersSparkJobsTest {
{"sparkSubmitJobDriver": {"entryPoint": "local:///app/job.py",
"sparkSubmitParameters": "--conf spark.kubernetes.container.image=custom/all:2"}}
""", null);
assertEquals("custom/all:2", EmrContainersSparkJobs.job(onlyJobImage, null, null).customImage());
assertEquals("custom/all:2", EmrContainersSparkJobs.job(onlyJobImage, null, null, APPLICATION).customImage());
}
}
@@ -24,7 +24,10 @@ 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.cloudwatchlogs.CloudWatchLogsClient;
import software.amazon.awssdk.services.cloudwatchlogs.model.OutputLogEvent;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.S3Object;
import java.time.Duration;
import java.util.Set;
@@ -38,7 +41,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* EMR on EKS job runs, run for real in the {@code docker} runner mode: each runs its Spark job in a container of its
* release's base image from Amazon ECR Public, on Floci's S3, and ends as its driver does.
* release's base image from Amazon ECR Public, on Floci's S3, sends its driver's output where its monitoring
* configuration says, and ends as its driver does.
*
* <p>A nightly check: the release's base image is about 5 GB.
*/
@@ -70,6 +74,7 @@ class EmrContainersSparkNightlyIntegrationTest {
DockerClient docker;
private S3Client s3;
private CloudWatchLogsClient logs;
private String bucket;
private String virtualClusterId;
@@ -91,6 +96,8 @@ class EmrContainersSparkNightlyIntegrationTest {
void setUp() {
s3 = AwsTestClients.create(S3Client.builder().forcePathStyle(true), ACCOUNT, Region.US_EAST_1);
cleanup.register(s3::close);
logs = AwsTestClients.create(CloudWatchLogsClient.builder(), ACCOUNT, Region.US_EAST_1);
cleanup.register(logs::close);
bucket = "emr-eks-" + UUID.randomUUID().toString().substring(0, 8);
s3.createBucket(request -> request.bucket(bucket));
cleanup.register(() -> S3TestClients.deleteBucket(s3, bucket));
@@ -99,6 +106,7 @@ class EmrContainersSparkNightlyIntegrationTest {
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
spark.createDataFrame([(sys.argv[2],)], ["value"]).coalesce(1).write.text(sys.argv[1])
print("driver-wrote-" + sys.argv[2])
""");
put("fail.py", """
import sys
@@ -133,16 +141,34 @@ class EmrContainersSparkNightlyIntegrationTest {
@Test
void sparkSubmitJobRunWritesToS3AndCompletes() {
String logGroup = "/emr-on-eks/" + bucket;
// The run creates it, as EMR on EKS creates a log group that does not exist.
cleanup.register(() -> logs.deleteLogGroup(request -> request.logGroupName(logGroup)));
String id = startJobRun("""
{"sparkSubmitJobDriver": {"entryPoint": "s3://%s/write.py",
"entryPointArguments": ["s3://%s/out/", "from-submit"],
"sparkSubmitParameters": "--conf spark.sql.shuffle.partitions=1"}}
""".formatted(bucket, bucket));
""".formatted(bucket, bucket), """
{"monitoringConfiguration": {"s3MonitoringConfiguration": {"logUri": "s3://%s/logs/"},
"cloudWatchMonitoringConfiguration": {"logGroupName": "%s", "logStreamNamePrefix": "nightly"}}}
""".formatted(bucket, logGroup));
Response run = awaitFinished(id);
assertEquals("COMPLETED", run.jsonPath().getString("jobRun.state"), run.asString());
assertEquals("from-submit\n", S3TestClients.partFiles(s3, bucket, "out/"));
// logUri/virtual-cluster-id/jobs/job-id/containers/spark-application-id/spark-job-id-driver/stdout.gz
String containers = "logs/" + virtualClusterId + "/jobs/" + id + "/containers/";
String stdout = s3.listObjectsV2(request -> request.bucket(bucket).prefix(containers)).contents().stream()
.map(S3Object::key)
.filter(key -> key.matches(containers + "spark-[0-9a-f]{32}/spark-" + id + "-driver/stdout\\.gz"))
.findFirst().orElseThrow();
assertTrue(S3TestClients.gunzipped(s3, bucket, stdout).contains("driver-wrote-from-submit"));
String stream = "nightly/" + stdout.substring("logs/".length(), stdout.length() - ".gz".length());
await("the driver's output in CloudWatch Logs").atMost(Duration.ofSeconds(30)).pollInterval(POLL_INTERVAL)
.until(() -> logs.getLogEvents(request -> request.logGroupName(logGroup).logStreamName(stream))
.events().stream().map(OutputLogEvent::message)
.anyMatch(message -> message.contains("driver-wrote-from-submit")));
}
@Test
@@ -196,10 +222,14 @@ class EmrContainersSparkNightlyIntegrationTest {
}
private String startJobRun(String jobDriver) {
return startJobRun(jobDriver, "{}");
}
private String startJobRun(String jobDriver, String configurationOverrides) {
return emr().body("""
{"name": "nightly", "clientToken": "%s", "executionRoleArn": "%s", "releaseLabel": "%s",
"jobDriver": %s}
""".formatted(UUID.randomUUID(), ROLE, RELEASE, jobDriver))
"jobDriver": %s, "configurationOverrides": %s}
""".formatted(UUID.randomUUID(), ROLE, RELEASE, jobDriver, configurationOverrides))
.post("/virtualclusters/" + virtualClusterId + "/jobruns")
.then().statusCode(200)
.extract().path("id");
@@ -46,6 +46,7 @@ import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermissions;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
@@ -111,9 +112,22 @@ class EmrServerlessSparkRunnerTest {
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);
// What the runner put in S3 by bucket and key, read during each put.
private final Map<String, byte[]> put = new HashMap<>();
private final ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
private final EcrRegistryManager ecr = mock(EcrRegistryManager.class);
EmrServerlessSparkRunnerTest() {
when(s3.putObjectFromStream(any(), any(), any(), any(), any())).thenAnswer(putting -> {
// Null as a test stubs the put over again, which calls it with its matchers.
InputStream body = putting.getArgument(2);
if (body != null) {
put.put(putting.getArgument(0) + "/" + putting.getArgument(1), body.readAllBytes());
}
return null;
});
}
@Test
void sparkSubmitRunsLocallyOnFlocisS3ThenTheRunsOwnSettings() {
List<String> application = List.of("--conf", "spark.executor.cores=2", "--py-files", "s3://bucket/jobs/lib.zip",
@@ -2402,11 +2416,11 @@ class EmrServerlessSparkRunnerTest {
});
}
// The object the runner put at key, gunzipped.
// The object the runner put at key, gunzipped; read as S3 reads it, during the put, the runner closing its stream
// after.
private String written(String bucket, String key) throws IOException {
ArgumentCaptor<InputStream> data = ArgumentCaptor.forClass(InputStream.class);
verify(s3).putObjectFromStream(eq(bucket), eq(key), data.capture(), eq("application/x-gzip"), eq(Map.of()));
try (GZIPInputStream gunzip = new GZIPInputStream(data.getValue())) {
verify(s3).putObjectFromStream(eq(bucket), eq(key), any(), eq("application/x-gzip"), eq(Map.of()));
try (GZIPInputStream gunzip = new GZIPInputStream(new ByteArrayInputStream(put.get(bucket + "/" + key)))) {
return new String(gunzip.readAllBytes(), StandardCharsets.UTF_8);
}
}