mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
0638a7f1d1
commit
5c62948838
11 files changed
+386
-46
No files matched your search
@@ -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<String, List<Map<String, Object>>> batch = new LinkedHashMap<>();
|
||||
BiConsumer<StreamType, String> 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<String, Object> 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<String, Object> 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<Map<String, Object>> events) {
|
||||
try {
|
||||
Map<String, Object> 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<StreamType, String> 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<StreamType, String> lineConsumer) {
|
||||
this(closeGraceMillis, lineConsumer, () -> { });
|
||||
}
|
||||
|
||||
LogReassemblyCallback(long closeGraceMillis, BiConsumer<StreamType, String> 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());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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.<KEY>} 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";
|
||||
}
|
||||
}
|
||||
@@ -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<Frame> {
|
||||
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;
|
||||
|
||||
Reference in new issue
Block a user