diff --git a/docs/services/emr-containers.md b/docs/services/emr-containers.md index 83cb4ec838..9b3e1e4226 100644 --- a/docs/services/emr-containers.md +++ b/docs/services/emr-containers.md @@ -168,7 +168,20 @@ wrapper with `FLOCI_SERVICES_EMRCONTAINERS_RUNNER_MODE=docker` (see [Docker](../ `failureReason` `INTERNAL_ERROR` and `stateDetails` "Trouble monitoring your JobRun due to an internal error". Floci's shutdown and a state reset stop every driver, and a driver a hard stop left running is removed when Floci starts again, unless `reconcile-containers-on-startup` is off. -* **Not emulated yet**: the driver's output goes to Floci's log only, not to the run's - `monitoringConfiguration` destinations in S3 or CloudWatch Logs; a `retryPolicyConfiguration` does not - start the driver again; and a run waits for its container however long it takes, with no - `job-start-timeout`. +* **Logs**: the driver's output always goes to Floci's log, and to the run's `monitoringConfiguration` + destinations as the development guide lays them out. With an `s3MonitoringConfiguration`, its `stdout.gz` + and `stderr.gz` go to `//jobs//containers//spark--driver/` + once the run ends, where EMR on EKS uploads them as it runs. With a `cloudWatchMonitoringConfiguration`, + its standard output and standard error go, as the driver writes them, to the streams + `//jobs//containers//spark--driver/stdout` + and `.../stderr` in its `logGroupName`, the group and streams created if they do not exist; without a prefix a + stream's name starts at the virtual cluster's id. Each line goes as the driver wrote it, but for an empty one, + which CloudWatch Logs refuses as an event. A run from a job template whose destination leaves out its + `logGroupName` or `logUri`, which the template's model allows, is refused with `ValidationException`, as + `StartJobRun` refuses a request that does. The `` has the form a Spark + application on Kubernetes gets, `spark-` and 32 hexadecimal digits, but is Floci's own: the driver's local + mode reports another. Floci runs no job submitter, so there are no submitter logs, and its executors run + in the driver's container, so their output is the driver's. `persistentAppUI`, `containerLogRotationConfiguration` + and `managedLogs` are kept but not applied. +* **Not emulated yet**: a `retryPolicyConfiguration` does not start the driver again, and a run waits for its + container however long it takes, with no `job-start-timeout`. diff --git a/src/main/java/io/floci/aws/core/common/docker/ContainerLogStreamer.java b/src/main/java/io/floci/aws/core/common/docker/ContainerLogStreamer.java index d466ee24c9..c0974126cd 100644 --- a/src/main/java/io/floci/aws/core/common/docker/ContainerLogStreamer.java +++ b/src/main/java/io/floci/aws/core/common/docker/ContainerLogStreamer.java @@ -28,6 +28,7 @@ import java.util.Comparator; import java.util.Deque; import java.util.EnumMap; import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -203,15 +204,28 @@ public class ContainerLogStreamer { ensureLogGroupAndStreamForAccount(accountId, logGroup, logStream, region); } } + // The lines of one emission, by stream, each sent as the container wrote it, but for a line ending and an empty + // line, which CloudWatch Logs refuses as an event. One emitter at a time touches it. + Map>> batch = new LinkedHashMap<>(); BiConsumer emitter = (stream, line) -> { - String logged = logToConsole(logPrefix, line); + logToConsole(logPrefix, line); String logStream = stream == StreamType.STDERR ? stderrStream : stdoutStream; - if (logged != null && logStream != null) { - forwardToCloudWatchLogs(accountId, logGroup, logStream, region, logged); + String message = line.endsWith("\r") ? line.substring(0, line.length() - 1) : line; + if (logStream != null && !message.isEmpty()) { + Map event = new HashMap<>(); + event.put("timestamp", System.currentTimeMillis()); + event.put("message", message); + batch.computeIfAbsent(logStream, ignored -> new ArrayList<>()).add(event); } }; + // Each stream's lines of one emission in one PutLogEvents, not one call a line. + Runnable drained = () -> { + batch.forEach((logStream, events) -> forwardToCloudWatchLogs(accountId, logGroup, logStream, region, + events)); + batch.clear(); + }; return follow(containerId, null, - new LogReassemblyCallback(LogReassemblyCallback.DEFAULT_CLOSE_GRACE_MILLIS, emitter)); + new LogReassemblyCallback(LogReassemblyCallback.DEFAULT_CLOSE_GRACE_MILLIS, emitter, drained)); } /** @@ -401,14 +415,18 @@ public class ContainerLogStreamer { private void forwardToCloudWatchLogs( String accountId, String logGroup, String logStream, String region, String line) { + Map event = new HashMap<>(); + event.put("timestamp", System.currentTimeMillis()); + event.put("message", line); + forwardToCloudWatchLogs(accountId, logGroup, logStream, region, List.of(event)); + } + + private void forwardToCloudWatchLogs( + String accountId, String logGroup, String logStream, String region, List> events) { try { - Map event = new HashMap<>(); - event.put("timestamp", System.currentTimeMillis()); - event.put("message", line); - cloudWatchLogsService.putLogEventsForAccount( - accountId, logGroup, logStream, List.of(event), region); + cloudWatchLogsService.putLogEventsForAccount(accountId, logGroup, logStream, events, region); } catch (Exception e) { - LOG.debugv("Could not forward log line to CloudWatch Logs: {0}", e.getMessage()); + LOG.debugv("Could not forward log lines to CloudWatch Logs: {0}", e.getMessage()); } } @@ -445,6 +463,9 @@ public class ContainerLogStreamer { // any later callback until the transport has been closed and the final tail has been flushed. private final ReentrantReadWriteLock callbackGate = new ReentrantReadWriteLock(true); private final BiConsumer lineConsumer; + // Runs once the lines pending at a time have all gone to lineConsumer, on the thread that emitted them, which + // is still the only one emitting; a consumer that gathers lines sends them on from here. + private final Runnable drained; private final long closeGraceMillis; // Guarded by 'buffers'. Set only by the Docker transport terminal callback; afterwards onNext // refuses to append, so nothing is ever buffered past the final flush. @@ -466,7 +487,12 @@ public class ContainerLogStreamer { } LogReassemblyCallback(long closeGraceMillis, BiConsumer lineConsumer) { + this(closeGraceMillis, lineConsumer, () -> { }); + } + + LogReassemblyCallback(long closeGraceMillis, BiConsumer lineConsumer, Runnable drained) { this.lineConsumer = lineConsumer; + this.drained = drained; this.closeGraceMillis = closeGraceMillis; } @@ -604,13 +630,27 @@ public class ContainerLogStreamer { synchronized (emissionLock) { synchronized (buffers) { pending = pendingLines.pollFirst(); - if (pending == null) { + } + } + if (pending != null) { + lineConsumer.accept(pending.stream(), pending.line()); + continue; + } + // Still the only emitter here, so drained never runs beside lineConsumer; lines that came while it + // ran are emitted before this emission ends. + try { + drained.run(); + } catch (RuntimeException e) { + LOG.debugv("Could not send on a container's log lines: {0}", e.getMessage()); + } + synchronized (emissionLock) { + synchronized (buffers) { + if (pendingLines.isEmpty()) { emitting = false; return; } } } - lineConsumer.accept(pending.stream(), pending.line()); } } diff --git a/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersRequestShapes.java b/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersRequestShapes.java index 0f4b192a9d..990c53513b 100644 --- a/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersRequestShapes.java +++ b/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersRequestShapes.java @@ -19,4 +19,9 @@ final class EmrContainersRequestShapes { static void check(String operation, JsonNode request) { CHECK.check(operation, request); } + + /** Checks {@code value} against the model's shape {@code shape}, one member of a request. */ + static void checkShape(String shape, JsonNode value) { + CHECK.checkShape(shape, value); + } } diff --git a/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersService.java b/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersService.java index 9e5648c92c..14e95a578e 100644 --- a/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersService.java +++ b/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersService.java @@ -54,6 +54,7 @@ import java.util.Map; import java.util.Optional; import java.util.PriorityQueue; import java.util.Set; +import java.util.UUID; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -376,6 +377,11 @@ public class EmrContainersService implements Resettable, StoredResourceArns { if (!missing.isEmpty()) { throw SmithyValidationErrors.validationException(missing); } + // A template's configurationOverrides follow its parametric model, whose monitoring destinations need not name + // their log group or log URI; the run they make follows StartJobRun's, which a request's own already met. + if (!request.hasNonNull("configurationOverrides") && template.hasNonNull("configurationOverrides")) { + EmrContainersRequestShapes.checkShape("ConfigurationOverrides", template.get("configurationOverrides")); + } String id = newId(JOB_RUN_ID_LENGTH); String arn = clusterArn + JOB_RUNS + id; @@ -1134,7 +1140,8 @@ public class EmrContainersService implements Resettable, StoredResourceArns { for (ObjectNode run : submitted) { String arn = run.get("arn").textValue(); try { - SparkJobRunner.Job job = EmrContainersSparkJobs.job(run, imageTemplate, dockerNetwork); + SparkJobRunner.Job job = EmrContainersSparkJobs.job(run, imageTemplate, dockerNetwork, + sparkApplicationId()); runExecutor.execute(() -> execute(arn, job, launchedIn)); } catch (RuntimeException e) { LOG.warnv(e, "EMR on EKS job run {0} could not be handed to a thread", run.get("id").textValue()); @@ -1363,6 +1370,14 @@ public class EmrContainersService implements Resettable, StoredResourceArns { return id.toString(); } + /** + * An id of the form a Spark application on Kubernetes gets, {@code spark-} and 32 hexadecimal digits, which names + * a run's driver logs as its Spark application's id names them on EMR on EKS. + */ + static String sparkApplicationId() { + return "spark-" + UUID.randomUUID().toString().replace("-", ""); + } + private static String sessionToken() { byte[] bytes = new byte[48]; ThreadLocalRandom.current().nextBytes(bytes); diff --git a/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersSparkJobs.java b/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersSparkJobs.java index e6338b4581..39e7534cbb 100644 --- a/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersSparkJobs.java +++ b/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersSparkJobs.java @@ -21,7 +21,8 @@ import java.util.regex.Pattern; * {@code spark-submit}, or its {@code sparkSqlJobDriver}'s {@code spark-sql}, in a container of its release's EMR on * EKS base image, with the {@code spark-defaults} of its {@code configurationOverrides} and its execution role's * credentials. Its driver runs in that container, its executors with it in Spark's local mode, where EMR on EKS runs - * each in a pod of its own. + * each in a pod of its own. Its driver's output goes where its {@code monitoringConfiguration} sends a driver's logs, + * in S3 and CloudWatch Logs. */ final class EmrContainersSparkJobs { @@ -47,6 +48,8 @@ final class EmrContainersSparkJobs { // A release label is its image's repository and tag joined by a hyphen: emr-7.2.0-20240610 runs the image tagged // emr-7.2.0:20240610, and emr-7.2.0-java11-latest the one tagged emr-7.2.0-java11:latest. private static final Pattern RELEASE_LABEL = Pattern.compile("(.+)-(latest|\\d{8})"); + private static final String STDOUT = "stdout"; + private static final String STDERR = "stderr"; private EmrContainersSparkJobs() { } @@ -98,9 +101,11 @@ final class EmrContainersSparkJobs { * {@code sparkSqlParameters} and its entry point as the file it runs ({@code -f}). Its custom image is the one * {@code spark.kubernetes.driver.container.image}, or else {@code spark.kubernetes.container.image}, names; its * driver's environment its {@code spark.kubernetes.driverEnv.} properties; its {@code spark.archives} are - * unpacked in its working directory, as they are in a pod's. + * unpacked in its working directory, as they are in a pod's. Its driver's logs go to {@link #driverLogFolder} and + * {@link #driverCloudWatchLogs}, under {@code sparkApplicationId}. */ - static SparkJobRunner.Job job(ObjectNode run, String imageTemplate, String dockerNetwork) { + static SparkJobRunner.Job job(ObjectNode run, String imageTemplate, String dockerNetwork, + String sparkApplicationId) { AwsArnUtils.Arn arn = AwsArnUtils.parse(run.get("arn").textValue()); String releaseLabel = run.get("releaseLabel").textValue(); JsonNode sparkSql = run.path("jobDriver").path("sparkSqlJobDriver"); @@ -125,9 +130,48 @@ final class EmrContainersSparkJobs { return new SparkJobRunner.Job(EmrContainersService.SERVICE, run.get("id").textValue(), arn.accountId(), arn.region(), releaseLabel, SparkJobRunner.Engine.SPARK, image(imageTemplate, releaseLabel), customImage, dockerNetwork, run.get("executionRoleArn").textValue(), sparkDefaults, application, - command, Duration.ZERO, null, null, + command, Duration.ZERO, driverLogFolder(run, sparkApplicationId), + driverCloudWatchLogs(run, sparkApplicationId), EmrServerlessJobRunService.environment(properties, DRIVER_ENV_PREFIX), EmrServerlessJobRunService.archives(properties), null, Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), null); } + + /** + * The S3 folder a run's driver logs go to, or null without an {@code s3MonitoringConfiguration}: "Driver Logs - + * /logUri/virtual-cluster-id/jobs/job-id/containers/spark-application-id/spark-job-id-driver/(stderr.gz/stdout.gz)" + * (EMR on EKS Development Guide, "Configure a job run to use Amazon S3 logs"). + */ + static String driverLogFolder(ObjectNode run, String sparkApplicationId) { + String logUri = run.path("configurationOverrides").path("monitoringConfiguration") + .path("s3MonitoringConfiguration").path("logUri").textValue(); + return EmrServerlessSparkRunner.logFolder(logUri, driverLogPath(run, sparkApplicationId) + "/"); + } + + /** + * Where in CloudWatch Logs a run's driver output goes, or null without a {@code cloudWatchMonitoringConfiguration}: + * its {@code logGroupName}, and "Driver logs - logGroup/logStreamPrefix/virtual-cluster-id/jobs/job-id/containers/ + * spark-application-id/spark-job-id-driver/(stderr/stdout)", a stream for each (EMR on EKS Development Guide, + * "Configure a job run to use Amazon CloudWatch Logs"). Without a {@code logStreamNamePrefix} a stream's name + * starts at the virtual cluster's id. + */ + static SparkJobRunner.CloudWatchLogs driverCloudWatchLogs(ObjectNode run, String sparkApplicationId) { + JsonNode cloudWatch = run.path("configurationOverrides").path("monitoringConfiguration") + .path("cloudWatchMonitoringConfiguration"); + String logGroup = cloudWatch.path("logGroupName").textValue(); + if (logGroup == null) { + return null; + } + String prefix = cloudWatch.path("logStreamNamePrefix").textValue(); + String driver = (prefix != null && !prefix.isEmpty() ? prefix + "/" : "") + + driverLogPath(run, sparkApplicationId) + "/"; + return new SparkJobRunner.CloudWatchLogs(logGroup, driver + STDOUT, driver + STDERR); + } + + // virtual-cluster-id/jobs/job-id/containers/spark-application-id/spark-job-id-driver, the driver pod's name. + private static String driverLogPath(ObjectNode run, String sparkApplicationId) { + String jobId = run.get("id").textValue(); + return run.get("virtualClusterId").textValue() + "/jobs/" + jobId + "/containers/" + sparkApplicationId + + "/spark-" + jobId + "-driver"; + } } diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java index 3c9d6d0f81..cafc79ed9f 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java @@ -35,12 +35,14 @@ import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.jboss.logging.Logger; +import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; import java.security.SecureRandom; import java.time.Clock; import java.time.Duration; @@ -1902,8 +1904,11 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo 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()) { + // Closed however the read ends, which ends Docker's stream and the compressors, and its files deleted after: + // Docker closes the callback as its stream completes, before the files are read. + DriverOutput output = null; + try { + output = new DriverOutput(); killInterruptible(job, containerId); lifecycleManager.stop(containerId, STOP_TIMEOUT_SECONDS); lifecycleManager.getDockerClient().logContainerCmd(containerId) @@ -1915,14 +1920,20 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo if (!output.awaitCompletion(LOG_READ_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS)) { throw new IOException("reading the driver's output took longer than " + LOG_READ_TIMEOUT); } - putLogs(s3Service, job.accountId(), job.region(), job.logFolder(), output.gzipped(StreamType.STDOUT), - output.gzipped(StreamType.STDERR)); + try (InputStream stdout = output.gzipped(StreamType.STDOUT); + InputStream stderr = output.gzipped(StreamType.STDERR)) { + putLogs(s3Service, job.accountId(), job.region(), job.logFolder(), stdout, stderr); + } } 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()); + } finally { + if (output != null) { + output.discard(); + } } } @@ -1933,16 +1944,35 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo * 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(); + // Each stream gzipped into a file of its own, which a long run's output never holds in memory. + private final Path stdout; + private final Path stderr; 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); + Path out = Files.createTempFile("floci-driver-", ".stdout.gz"); + try { + stderr = Files.createTempFile("floci-driver-", ".stderr.gz"); + } catch (IOException e) { + Files.deleteIfExists(out); + throw e; + } + stdout = out; + GZIPOutputStream stdoutCompressor = null; + try { + stdoutCompressor = new GZIPOutputStream(new BufferedOutputStream(Files.newOutputStream(stdout))); + stderrGzip = new GZIPOutputStream(new BufferedOutputStream(Files.newOutputStream(stderr))); + } catch (IOException e) { + if (stdoutCompressor != null) { + stdoutCompressor.close(); + } + deleteFiles(); + throw e; + } + stdoutGzip = stdoutCompressor; } @Override @@ -1957,10 +1987,10 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo } } - // A stream's whole gzipped output, once Docker has sent everything. - synchronized byte[] gzipped(StreamType stream) throws IOException { + // A stream's whole gzipped output, once Docker has sent everything, read from its file. + synchronized InputStream gzipped(StreamType stream) throws IOException { closeCompressors(); - return (stream == StreamType.STDERR ? stderr : stdout).toByteArray(); + return Files.newInputStream(stream == StreamType.STDERR ? stderr : stdout); } @Override @@ -1974,6 +2004,27 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo } } + // Closes it, if Docker has not, and deletes its files, once they have been read or the read has failed. + void discard() { + try { + close(); + } catch (IOException e) { + LOG.debugv("Could not close the driver's output: {0}", e.getMessage()); + } finally { + deleteFiles(); + } + } + + private void deleteFiles() { + for (Path file : List.of(stdout, stderr)) { + try { + Files.deleteIfExists(file); + } catch (IOException e) { + LOG.warnv("Could not delete the driver output file {0}: {1}", file, e.getMessage()); + } + } + } + // Guarded by this. Closing a compressor writes its trailer and frees its deflater, once only. private void closeCompressors() throws IOException { compressorsClosed = true; diff --git a/src/test/java/io/floci/aws/core/common/docker/ContainerLogStreamerTest.java b/src/test/java/io/floci/aws/core/common/docker/ContainerLogStreamerTest.java index d9549fe8e4..a7810441bc 100644 --- a/src/test/java/io/floci/aws/core/common/docker/ContainerLogStreamerTest.java +++ b/src/test/java/io/floci/aws/core/common/docker/ContainerLogStreamerTest.java @@ -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 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); diff --git a/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersServiceTest.java b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersServiceTest.java index b76eaff399..572c705a3a 100644 --- a/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersServiceTest.java +++ b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersServiceTest.java @@ -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); diff --git a/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersSparkJobsTest.java b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersSparkJobsTest.java index 971702927b..292148547b 100644 --- a/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersSparkJobsTest.java +++ b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersSparkJobsTest.java @@ -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()); } } diff --git a/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersSparkNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersSparkNightlyIntegrationTest.java index 2132f0316a..cf3827b6ec 100644 --- a/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersSparkNightlyIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersSparkNightlyIntegrationTest.java @@ -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. * *

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"); diff --git a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunnerTest.java b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunnerTest.java index b30ccad81c..77ac5f13c9 100644 --- a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunnerTest.java +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunnerTest.java @@ -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 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 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 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); } }