mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(emr-serverless): give a job run's driver its driverEnv and S3 archives (#7107)
In the docker runner mode the user guide's way of giving an EMR
Serverless job run its Python libraries did nothing. "Building a Python
virtual environment" packs a virtualenv into an archive in S3 and
submits the job with:
--conf spark.archives=s3://.../pyspark_venv.tar.gz#environment
--conf spark.emr-serverless.driverEnv.PYSPARK_DRIVER_PYTHON=./environment/bin/python
--conf spark.emr-serverless.driverEnv.PYSPARK_PYTHON=./environment/bin/python
--conf spark.executorEnv.PYSPARK_PYTHON=./environment/bin/python
Floci set no driverEnv variable on the driver's container, and Spark in
local mode unpacks spark.archives into a temporary files folder of its
own once the driver's Python has started, not into the working
directory. With the variables set, the driver could not start: "Cannot
run program "./environment/bin/python"".
Now:
- a spark.emr-serverless.driverEnv.<KEY> property ("Option that adds
environment variables to the Spark driver"), from the run's
spark-defaults or a --conf in its sparkSubmitParameters, which wins,
is an environment variable of the driver's container, replacing one
of Floci's own of that name;
- each archive of spark.archives (which spark-submit's own --archives
sets, winning over a --conf, as in Spark) in Floci's S3 is read as the
run's account, streamed into the created container and unpacked into
its working directory before spark-submit starts, under the name after
its # or else its file's name, as Spark's Utils.unpack does it (.jar
and .zip unzipped, .tar.gz, .tgz and .tar untarred, anything else
copied). The guide's venv-pack example puts the environment in
/home/hadoop/environment, and /home/hadoop is the image's working
directory. An archive that cannot be read fails the run before its
driver starts, naming it; a cancel, a reset or a shutdown while they
are put in ends the copy and puts in no other.
SparkJobRunner.Job carries the archives, which classic EMR's steps
leave empty. Spark still unpacks each archive into its own files folder
too, where SparkFiles.get finds it, and gives spark.executorEnv
variables to the Python workers it starts, so those need nothing more.
This commit is contained in:
1 parent
81e1dbc573
commit
2b6a8b4e66
7 files changed
+536
-16
No files matched your search
@@ -134,6 +134,27 @@ AWS runtime for Apache Spark releases, `emr-spark-8.0.0` on), and runs
|
||||
two are merged by property instead, the run's winning. `s3://` and `s3a://` paths reach Floci's S3 through S3A, on releases before 7.10.0
|
||||
too, where `s3://` would otherwise be EMRFS; the entry point and its files can be read from there.
|
||||
The Glue Data Catalog client is pointed at Floci's Glue.
|
||||
* **Driver environment and archives**: a `spark.emr-serverless.driverEnv.<KEY>` property, from the
|
||||
`spark-defaults` above or a `--conf` in `sparkSubmitParameters`, which wins, is an environment variable
|
||||
of the container, replacing one of Floci's own of that name, such as the user guide's `JAVA_HOME` for
|
||||
Java 17. Each archive of `spark.archives` (which `spark-submit`'s `--archives` sets, winning over a
|
||||
`--conf`) that is in Floci's S3 is unpacked into the container's working directory, `/home/hadoop` in the
|
||||
release's image, before the driver starts, under the name that follows its `#`, or else its file's
|
||||
name: a `.jar` or `.zip` is unzipped, a `.tar.gz`, `.tgz` or `.tar` untarred, and any other file copied,
|
||||
as Spark unpacks one. So the user guide's Python virtual environment runs as it is written there:
|
||||
|
||||
```
|
||||
--conf spark.archives=s3://amzn-s3-demo-bucket/EXAMPLE-PREFIX/pyspark_venv.tar.gz#environment
|
||||
--conf spark.emr-serverless.driverEnv.PYSPARK_DRIVER_PYTHON=./environment/bin/python
|
||||
--conf spark.emr-serverless.driverEnv.PYSPARK_PYTHON=./environment/bin/python
|
||||
--conf spark.executorEnv.PYSPARK_PYTHON=./environment/bin/python
|
||||
```
|
||||
|
||||
Floci reads each archive as the run's account. One it cannot read fails the run before its driver
|
||||
starts, with "Job run could not start" naming it, and one that does not unpack fails the run as a
|
||||
driver's failure does. Spark also unpacks every archive itself, into its own files folder, where
|
||||
`SparkFiles.get` finds it. A `spark.executorEnv.<KEY>` needs nothing more from Floci: local mode's
|
||||
executors run in the driver's JVM, and Spark gives these variables to the Python workers it starts.
|
||||
* **Credentials**: the container gets a session for the run's execution role when IAM knows the role,
|
||||
otherwise the account's placeholder credentials, and `AWS_ENDPOINT_URL` pointing at Floci, so the
|
||||
job's own SDK clients reach Floci too.
|
||||
@@ -179,6 +200,9 @@ AWS runtime for Apache Spark releases, `emr-spark-8.0.0` on), and runs
|
||||
|
||||
* **Jobs do not execute by default**: in the `immediate` runner mode `StartJobRun` records a job run and moves it through its states, but nothing runs. In the `docker` mode a Spark run executes in local mode in one container, so worker counts and sizes, initial and maximum capacity are not applied; a Hive run is `FAILED` without running, in Floci's own wording, as is a driver's failure. Of the monitoring configuration, the S3 log destination gets the driver's `stdout.gz` and `stderr.gz` once a run ends (no event logs, rotated files or uploads while it runs), and CloudWatch Logs the driver's output while it runs (there are no executor logs, local mode having no executors, and `encryptionKeyArn` is ignored).
|
||||
* **Unsourced errors**: AWS documents neither the error for a run submitted to an application whose auto-start is off nor the one for a run on a terminated application; Floci answers both with `ValidationException`. The same holds for a `BATCH` timeout outside 1 to 10080 minutes on `emr-7.11.0` or later (`ValidationException`) and for `GetJobRun` naming an attempt a run never made (`ResourceNotFoundException`), both in Floci's own wording. A run needs a `jobDriver`, as every `JobRun` carries one, and `jobDriver` is a union, so a run without a driver, or with one that sets both `sparkSubmit` and `hive` or neither, is refused with `ValidationException` too, in Floci's own wording.
|
||||
* **Archives**: only the archives of `spark.archives` that are in S3 are unpacked into the driver's working
|
||||
directory; Spark alone unpacks the others, into its own files folder. Floci reads an archive itself,
|
||||
whatever the execution role may read, though Spark's own read of it uses the role's credentials.
|
||||
* **Custom images**: Floci does not check an `imageUri` against the model's pattern, which would refuse the repository URIs Floci's own ECR hands out, nor that the image was built from its release's base image (AWS refuses one that was not from `emr-7.14.0` and `emr-spark-8.1.0` on), nor the image's size. An image that cannot be pulled fails the run, not the request that names it. Every run resolves its image again, as releases from 7.14 do and earlier ones with `applicationLevelDigestResolution` false: Floci keeps no digest from the application's start, and reports no `resolvedImageDigest`, on the application or on a job run.
|
||||
* **StopApplication with running jobs**: AWS requires running jobs to finish or be cancelled before an application stops. Floci does not enforce it; with the default duration of `0` no `BATCH` run is ever running.
|
||||
* **Not emulated**: the "EMR Serverless Job Run Retry" event, as Floci sends no EMR Serverless events, queuing (`QUEUED`), `totalResourceUtilization` and `billedResourceUtilization`, and `shutdownGracePeriodInSeconds` (accepted and ignored: a cancelled run's driver is stopped at once).
|
||||
|
||||
@@ -1322,7 +1322,7 @@ public class EmrService implements Resettable {
|
||||
EmrSparkSteps.sparkDefaults(cluster.getConfigurations(), SNAPSHOT_MAPPER),
|
||||
application != null ? application : List.of(), command, Duration.ZERO,
|
||||
EmrSparkSteps.logFolder(cluster, step), null,
|
||||
EmrSparkSteps.sparkEnvironment(cluster.getConfigurations(), SNAPSHOT_MAPPER));
|
||||
EmrSparkSteps.sparkEnvironment(cluster.getConfigurations(), SNAPSHOT_MAPPER), List.of());
|
||||
StepLaunch launch = new StepLaunch(accountId, region, cluster.getId(), step.getId(), generation);
|
||||
executing.add(stepKey(accountId, step.getId()));
|
||||
stepExecutor.execute(() -> runStep(job, launch));
|
||||
|
||||
+72
-3
@@ -39,6 +39,7 @@ import java.time.OffsetDateTime;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
@@ -92,6 +93,13 @@ public class EmrServerlessJobRunService implements Resettable {
|
||||
private static final String SPARK_DRIVER = "SPARK_DRIVER";
|
||||
// The worker type a Spark application's driver runs as.
|
||||
private static final String DRIVER_WORKER_TYPE = "Driver";
|
||||
// spark-submit's option for a Spark property, and its short form; and its option for spark.archives.
|
||||
private static final String CONF_OPTION = "--conf";
|
||||
private static final String CONF_SHORT_OPTION = "-c";
|
||||
private static final String ARCHIVES_OPTION = "--archives";
|
||||
// "Option that adds environment variables to the Spark driver."
|
||||
private static final String DRIVER_ENV_PREFIX = "spark.emr-serverless.driverEnv.";
|
||||
private static final String SPARK_ARCHIVES = "spark.archives";
|
||||
// No source gives AWS's wording for these; they are Floci's.
|
||||
static final String HIVE_NOT_RUN = "Floci runs Spark job runs only, and this is a Hive job run.";
|
||||
static final String INTERRUPTED = "Floci stopped while the job run was in progress.";
|
||||
@@ -470,7 +478,8 @@ public class EmrServerlessJobRunService implements Resettable {
|
||||
/** Hands a container run to a thread of its own, which runs it to its end. */
|
||||
private void launch(JobRunRecord record, Application app) {
|
||||
JobRun run = record.getJobRun();
|
||||
if (run.getJobDriver().getSparkSubmit() == null) {
|
||||
JobDriver.SparkSubmit sparkSubmit = run.getJobDriver().getSparkSubmit();
|
||||
if (sparkSubmit == null) {
|
||||
run.setStateDetails(HIVE_NOT_RUN);
|
||||
finish(record, STATE_FAILED, run.getCreatedAt());
|
||||
return;
|
||||
@@ -480,10 +489,12 @@ public class EmrServerlessJobRunService implements Resettable {
|
||||
Long minutes = run.getExecutionTimeoutMinutes();
|
||||
Duration timeout = MODE_STREAMING.equals(run.getMode()) || minutes == null || minutes == 0
|
||||
? Duration.ZERO : Duration.ofMinutes(minutes);
|
||||
Map<String, String> sparkDefaults = sparkDefaults(app, run);
|
||||
Map<String, String> sparkProperties = sparkProperties(sparkDefaults, sparkSubmit);
|
||||
SparkJobRunner.Job job = new SparkJobRunner.Job(SERVICE, run.getJobRunId(), arn.accountId(), arn.region(),
|
||||
run.getReleaseLabel(), imageTemplate, customImage(app), dockerNetwork, run.getExecutionRole(),
|
||||
sparkDefaults(app, run), application(run.getJobDriver().getSparkSubmit()), null, timeout,
|
||||
driverLogFolder(app, run), driverCloudWatchLogs(app, run), Map.of());
|
||||
sparkDefaults, application(sparkSubmit), null, timeout, driverLogFolder(app, run),
|
||||
driverCloudWatchLogs(app, run), driverEnvironment(sparkProperties), archives(sparkProperties));
|
||||
executing.add(run.getJobRunId());
|
||||
long launchedIn = generation;
|
||||
runExecutor.execute(() -> execute(job, launchedIn));
|
||||
@@ -531,6 +542,64 @@ public class EmrServerlessJobRunService implements Resettable {
|
||||
return application;
|
||||
}
|
||||
|
||||
/**
|
||||
* A run's Spark properties as its driver gets them: its {@code spark-defaults}, then the {@code --conf}
|
||||
* settings of its {@code sparkSubmitParameters}, which {@code spark-submit} lets win, a later one over an
|
||||
* earlier. A setting without an {@code =}, which {@code spark-submit} refuses, sets nothing. The last
|
||||
* {@code --archives} option is {@code spark.archives}, winning over any setting of it, as
|
||||
* {@code spark-submit} has it.
|
||||
*/
|
||||
static Map<String, String> sparkProperties(Map<String, String> sparkDefaults, JobDriver.SparkSubmit sparkSubmit) {
|
||||
Map<String, String> properties = new LinkedHashMap<>(sparkDefaults);
|
||||
List<String> parameters = EmrServerlessSparkRunner.splitParameters(sparkSubmit.getSparkSubmitParameters());
|
||||
String archivesOption = null;
|
||||
for (int i = 0; i < parameters.size(); i++) {
|
||||
String parameter = parameters.get(i);
|
||||
String setting = null;
|
||||
if (parameter.startsWith(CONF_OPTION + "=")) {
|
||||
setting = parameter.substring(CONF_OPTION.length() + 1);
|
||||
} else if ((CONF_OPTION.equals(parameter) || CONF_SHORT_OPTION.equals(parameter))
|
||||
&& i + 1 < parameters.size()) {
|
||||
setting = parameters.get(++i);
|
||||
} else if (parameter.startsWith(ARCHIVES_OPTION + "=")) {
|
||||
archivesOption = parameter.substring(ARCHIVES_OPTION.length() + 1);
|
||||
} else if (ARCHIVES_OPTION.equals(parameter) && i + 1 < parameters.size()) {
|
||||
archivesOption = parameters.get(++i);
|
||||
}
|
||||
int equals = setting != null ? setting.indexOf('=') : -1;
|
||||
if (equals > 0) {
|
||||
properties.put(setting.substring(0, equals), setting.substring(equals + 1));
|
||||
}
|
||||
}
|
||||
if (archivesOption != null) {
|
||||
properties.put(SPARK_ARCHIVES, archivesOption);
|
||||
}
|
||||
return properties;
|
||||
}
|
||||
|
||||
/** The environment variables a run's driver gets: its {@code spark.emr-serverless.driverEnv.<KEY>} properties. */
|
||||
static Map<String, String> driverEnvironment(Map<String, String> sparkProperties) {
|
||||
Map<String, String> environment = new LinkedHashMap<>();
|
||||
sparkProperties.forEach((key, value) -> {
|
||||
if (key.startsWith(DRIVER_ENV_PREFIX) && key.length() > DRIVER_ENV_PREFIX.length()) {
|
||||
environment.put(key.substring(DRIVER_ENV_PREFIX.length()), value);
|
||||
}
|
||||
});
|
||||
return environment;
|
||||
}
|
||||
|
||||
/**
|
||||
* A run's {@code spark.archives}: a comma-separated list, of which Spark takes each entry trimmed and drops
|
||||
* the empty ones.
|
||||
*/
|
||||
static List<String> archives(Map<String, String> sparkProperties) {
|
||||
String archives = sparkProperties.get(SPARK_ARCHIVES);
|
||||
if (archives == null) {
|
||||
return List.of();
|
||||
}
|
||||
return Arrays.stream(archives.split(",")).map(String::trim).filter(archive -> !archive.isEmpty()).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* A reset has begun: the runs' threads from before it write nothing more, so the storage wipe that
|
||||
* follows leaves none of their runs behind. Its teardown has already stopped their drivers.
|
||||
|
||||
+148
-6
@@ -7,6 +7,7 @@ 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.config.EmulatorConfig.EcsServiceConfig.ImagePullBehavior;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.ContainerTeardown;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.core.common.S3Uri;
|
||||
@@ -17,12 +18,15 @@ import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
|
||||
import io.github.hectorvent.floci.core.common.docker.LaunchedContainerAwsEnv;
|
||||
import io.github.hectorvent.floci.core.common.docker.RetryingTarCopier;
|
||||
import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;
|
||||
import io.github.hectorvent.floci.services.iam.model.SessionCreds;
|
||||
import io.github.hectorvent.floci.services.lambda.launcher.LambdaExecutionRoleCredentials;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
@@ -30,6 +34,7 @@ import java.io.ByteArrayOutputStream;
|
||||
import java.io.Closeable;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
@@ -39,6 +44,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.BooleanSupplier;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
/**
|
||||
@@ -48,7 +54,8 @@ import java.util.zip.GZIPOutputStream;
|
||||
* in local mode: the container holds the driver and its executors. The container reaches Floci as the
|
||||
* other containers Floci launches do, with the run's execution role as its credentials, and S3A, which
|
||||
* takes {@code s3://} on every release, is pointed at Floci's S3. With TLS on, every JVM in the container
|
||||
* trusts Floci's CA, through the Java trust store copied in before it starts. The driver's output goes to
|
||||
* trusts Floci's CA, through the Java trust store copied in before it starts, and the run's archives in S3
|
||||
* are unpacked into its working directory before the driver starts. The driver's output goes to
|
||||
* Floci's log and, while it runs, to the run's CloudWatch log streams, when it has some; once it ends, its
|
||||
* standard output and error go, gzipped, to the run's log folder in Floci's S3, when it has one.
|
||||
*/
|
||||
@@ -72,6 +79,28 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
|
||||
"printf '%s\\n' \"$" + SPARK_DEFAULTS_VARIABLE + "\" >> \"$conf/spark-defaults.conf\"",
|
||||
"export SPARK_CONF_DIR=\"$conf\"",
|
||||
"exec \"$@\"");
|
||||
// The archives a driver needs in its working directory are put in this folder of its container, each in a
|
||||
// numbered folder of its own, which the copy creates.
|
||||
private static final String ARCHIVES_FOLDER = "/tmp/floci-archives";
|
||||
// While an archive is streamed in, a stop is looked for after each this many bytes, as Progress.cancelled()
|
||||
// takes the run service's lock.
|
||||
private static final long STOP_LOOK_BYTES = 4L * 1024 * 1024;
|
||||
private static final int ARCHIVE_BUFFER_BYTES = 64 * 1024;
|
||||
// Gets each archive's file and the directory it goes to, then "--" and what runs after, and unpacks each into
|
||||
// the working directory as Spark's Utils.unpack does: a .jar or .zip unzipped, a .tar.gz, .tgz or .tar
|
||||
// untarred, and any other file copied.
|
||||
private static final String ARCHIVES_WRAPPER = String.join("\n",
|
||||
"shopt -s nocasematch",
|
||||
"while [ \"$1\" != -- ]; do",
|
||||
" case \"$1\" in",
|
||||
" *.jar|*.zip) mkdir -p \"$2\" && unzip -q -o \"$1\" -d \"$2\" ;;",
|
||||
" *.tar.gz|*.tgz|*.tar) mkdir -p \"$2\" && tar -xf \"$1\" -C \"$2\" ;;",
|
||||
" *) cp \"$1\" \"$2\" ;;",
|
||||
" esac || exit",
|
||||
" shift 2",
|
||||
"done",
|
||||
"shift",
|
||||
"exec \"$@\"");
|
||||
private static final String DEFAULT_IMAGE =
|
||||
"public.ecr.aws/emr-serverless/spark/%s:latest"; // partition-literal: ECR Public's registry host, where AWS publishes the base images; image-template overrides it
|
||||
// The AWS runtime for Apache Spark (emr-spark-8.0.0 on) publishes its images under spark4/ instead.
|
||||
@@ -143,16 +172,18 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
|
||||
// The deployment that started the driver, which removeLeftoverDrivers() goes by.
|
||||
labels.put(ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config));
|
||||
String endpoint = awsEnv.flociEndpoint();
|
||||
List<Archive> archives = archives(job);
|
||||
ContainerBuilder.Builder container = containerBuilder.newContainer(launchImage(job))
|
||||
.withName(ContainerStorageHelper.dockerName(config, job.service() + "-" + job.runId()))
|
||||
.withEnv(environment(
|
||||
awsEnv.sdkBaselineEnv(job.region(), Optional.empty(), credentials, job.accountId()),
|
||||
job.environment()));
|
||||
if (job.command() == null) {
|
||||
container.withEntrypoint(List.of(SPARK_SUBMIT)).withCmd(sparkSubmitArguments(job, endpoint));
|
||||
container.withEntrypoint(unpackingFirst(archives, List.of(SPARK_SUBMIT)))
|
||||
.withCmd(sparkSubmitArguments(job, endpoint));
|
||||
} else {
|
||||
// bash -c's script gets "floci" as its $0, and the command as its arguments, "$@".
|
||||
container.withEntrypoint(List.of("/bin/bash", "-c", COMMAND_WRAPPER, "floci"))
|
||||
container.withEntrypoint(unpackingFirst(archives, List.of("/bin/bash", "-c", COMMAND_WRAPPER, "floci")))
|
||||
.withCmd(job.command())
|
||||
.withEnv(SPARK_DEFAULTS_VARIABLE, sparkDefaultsFile(job, endpoint));
|
||||
}
|
||||
@@ -166,9 +197,12 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
|
||||
.build();
|
||||
String containerId = lifecycleManager.create(spec);
|
||||
launch.started(containerId);
|
||||
// A stop, a reset or a shutdown while the image was pulled or the trust store copied is read now,
|
||||
// before the driver starts.
|
||||
if (launch.stopRequested() || progress.cancelled()) {
|
||||
// A stop, a reset or a shutdown while the image was pulled, the trust store copied or the archives put
|
||||
// in is read now, before the driver starts; one before an archive or while it streams in puts in no
|
||||
// more of them.
|
||||
BooleanSupplier stopped = () -> launch.stopRequested() || progress.cancelled();
|
||||
putArchives(job, archives, containerId, stopped);
|
||||
if (stopped.getAsBoolean()) {
|
||||
return Outcome.halted();
|
||||
}
|
||||
lifecycleManager.startCreated(containerId, spec);
|
||||
@@ -321,6 +355,46 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
|
||||
return new ArrayList<>(byName.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* A job's archives in S3, which its driver finds in its working directory: each with the file it is put at, in
|
||||
* a folder of its own, and the directory it is unpacked to, named as Spark names it, by what follows its
|
||||
* {@code #} or else by its file's name. Spark alone unpacks the others, into its own files folder.
|
||||
*/
|
||||
static List<Archive> archives(Job job) {
|
||||
List<Archive> archives = new ArrayList<>();
|
||||
for (String archive : job.archives()) {
|
||||
int hash = archive.indexOf('#');
|
||||
String path = hash < 0 ? archive : archive.substring(0, hash);
|
||||
if (!S3Uri.isS3(path)) {
|
||||
continue;
|
||||
}
|
||||
S3Uri location = S3Uri.parseAnyScheme(path);
|
||||
String name = location.key().substring(location.key().lastIndexOf('/') + 1);
|
||||
if (name.isEmpty()) {
|
||||
throw new IllegalArgumentException("The archive " + archive + " names no object.");
|
||||
}
|
||||
String file = ARCHIVES_FOLDER + "/" + (archives.size() + 1) + "/" + name;
|
||||
archives.add(new Archive(path, location, file, hash < 0 ? name : archive.substring(hash + 1)));
|
||||
}
|
||||
return archives;
|
||||
}
|
||||
|
||||
/** {@code entrypoint}, after the wrapper that unpacks {@code archives} into the working directory, if any. */
|
||||
static List<String> unpackingFirst(List<Archive> archives, List<String> entrypoint) {
|
||||
if (archives.isEmpty()) {
|
||||
return entrypoint;
|
||||
}
|
||||
// bash -c's script gets "floci" as its $0, then each archive's file and directory, "--" and the entrypoint.
|
||||
List<String> unpacking = new ArrayList<>(List.of("/bin/bash", "-c", ARCHIVES_WRAPPER, "floci"));
|
||||
for (Archive archive : archives) {
|
||||
unpacking.add(archive.file());
|
||||
unpacking.add(archive.directory());
|
||||
}
|
||||
unpacking.add("--");
|
||||
unpacking.addAll(entrypoint);
|
||||
return unpacking;
|
||||
}
|
||||
|
||||
/**
|
||||
* The image a run's driver starts from: the release's, or the template's, or the application's custom
|
||||
* image. A custom image's ECR URI leads to Floci's own registry, as a Lambda function's or an ECS task's
|
||||
@@ -336,6 +410,67 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
|
||||
return lifecycleManager.resolveImageForLaunch(image, ImagePullBehavior.DEFAULT, null).imageId();
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts each archive in the created container, for its entrypoint to unpack: read from Floci's S3 as the run's
|
||||
* account and streamed in, so Floci holds little of it however large it is. One that cannot be read fails
|
||||
* the run, naming it. Once the run is {@code stopped}, no other archive is put in, and the one streaming in
|
||||
* stops, leaving run() to read the stop.
|
||||
*/
|
||||
private void putArchives(Job job, List<Archive> archives, String containerId, BooleanSupplier stopped) {
|
||||
for (Archive archive : archives) {
|
||||
if (stopped.getAsBoolean()) {
|
||||
return;
|
||||
}
|
||||
S3Uri location = archive.location();
|
||||
try {
|
||||
RequestScopes.runAs(job.accountId(), job.region(),
|
||||
() -> s3Service.headObject(location.bucket(), location.key()));
|
||||
} catch (AwsException e) {
|
||||
throw new IllegalArgumentException(
|
||||
"Could not read the archive " + archive.path() + ": " + e.getMessage(), e);
|
||||
}
|
||||
try {
|
||||
// Extracted at the root, the entry is the file's path without its leading slash.
|
||||
RetryingTarCopier.copyStreamed(lifecycleManager.getDockerClient(), containerId, "/", archive.path(),
|
||||
out -> {
|
||||
try (S3Service.ObjectRead read = RequestScopes.callAs(job.accountId(), job.region(),
|
||||
() -> s3Service.openObject(location.bucket(), location.key(), null));
|
||||
TarArchiveOutputStream tar = RetryingTarCopier.newTarStream(out)) {
|
||||
TarArchiveEntry entry = new TarArchiveEntry(archive.file().substring(1));
|
||||
entry.setSize(read.object().getSize());
|
||||
entry.setMode(0644);
|
||||
tar.putArchiveEntry(entry);
|
||||
transferUntilStopped(read.body(), tar, stopped);
|
||||
tar.closeArchiveEntry();
|
||||
}
|
||||
});
|
||||
} catch (RuntimeException e) {
|
||||
// A copy the stop ended, or one whose container a reset removed.
|
||||
if (stopped.getAsBoolean()) {
|
||||
return;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Copies {@code in} to {@code out}, failing once the run is {@code stopped}, as looked at each few MiB. */
|
||||
private static void transferUntilStopped(InputStream in, OutputStream out, BooleanSupplier stopped)
|
||||
throws IOException {
|
||||
byte[] buffer = new byte[ARCHIVE_BUFFER_BYTES];
|
||||
long sinceLook = 0;
|
||||
for (int read = in.read(buffer); read >= 0; read = in.read(buffer)) {
|
||||
out.write(buffer, 0, read);
|
||||
sinceLook += read;
|
||||
if (sinceLook >= STOP_LOOK_BYTES) {
|
||||
sinceLook = 0;
|
||||
if (stopped.getAsBoolean()) {
|
||||
throw new IOException("the job run was stopped");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code spark-submit}'s arguments: local mode, S3A on Floci's S3 for {@code s3://} and {@code s3a://}
|
||||
* paths, then the run's {@code spark-defaults} and its own options, which win over what comes before
|
||||
@@ -404,6 +539,13 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
|
||||
private record SparkSetting(String key, String value) {
|
||||
}
|
||||
|
||||
/**
|
||||
* A job's archive in S3: its path and where that is, the file it is put at in the container, and the directory
|
||||
* of the working directory it is unpacked to.
|
||||
*/
|
||||
record Archive(String path, S3Uri location, String file, String directory) {
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code spark-submit} parameters given as one string, as EMR Serverless's
|
||||
* {@code sparkSubmitParameters}, split as a POSIX shell would split them: on whitespace, except inside single
|
||||
|
||||
@@ -61,13 +61,17 @@ public interface SparkJobRunner {
|
||||
* empty); how long it may run
|
||||
* ({@link Duration#ZERO} for no limit); the S3 folder its driver's {@code stdout.gz} and
|
||||
* {@code stderr.gz} go to once it ends, ending in a slash (null for none); where in CloudWatch Logs
|
||||
* its driver's output goes while it runs (null for nowhere but Floci's log); and the environment variables
|
||||
* its container gets besides Floci's own, which they replace where a name is the same (empty for none).
|
||||
* its driver's output goes while it runs (null for nowhere but Floci's log); the environment variables
|
||||
* its container gets besides Floci's own, which they replace where a name is the same (empty for none);
|
||||
* and its {@code spark.archives}, each a path with, after a {@code #}, the directory it is unpacked to,
|
||||
* of which those in S3 are unpacked into the container's working directory before the driver starts
|
||||
* (empty for none).
|
||||
*/
|
||||
record Job(String service, String runId, String accountId, String region, String releaseLabel,
|
||||
String imageTemplate, String customImage, String dockerNetwork, String executionRole,
|
||||
Map<String, String> sparkDefaults, List<String> application, List<String> command, Duration timeout,
|
||||
String logFolder, CloudWatchLogs cloudWatchLogs, Map<String, String> environment) {
|
||||
String logFolder, CloudWatchLogs cloudWatchLogs, Map<String, String> environment,
|
||||
List<String> archives) {
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+66
@@ -264,6 +264,7 @@ class EmrServerlessJobRunServiceTest {
|
||||
assertNull(job.logFolder());
|
||||
assertNull(job.cloudWatchLogs());
|
||||
assertEquals(Map.of(), job.environment());
|
||||
assertEquals(List.of(), job.archives());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -666,6 +667,71 @@ class EmrServerlessJobRunServiceTest {
|
||||
EmrServerlessJobRunService.application(sparkSubmit));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRunsDriverEnvAndArchivesAreItsSparkPropertiesTheSubmitParametersWinning() {
|
||||
FakeRunner runner = new FakeRunner();
|
||||
EmrServerlessJobRunService service = dockerService(runner);
|
||||
RuntimeConfiguration defaults = new RuntimeConfiguration();
|
||||
defaults.setMember("classification", "spark-defaults");
|
||||
defaults.setMember("properties", Map.of(
|
||||
"spark.emr-serverless.driverEnv.JAVA_HOME", "/usr/lib/jvm/java-17-amazon-corretto.x86_64/",
|
||||
"spark.archives", "s3://bucket/envs/previous.tar.gz#environment"));
|
||||
CreateApplicationRequest create = applicationRequest("python", "emr-7.5.0", "SPARK");
|
||||
create.setRuntimeConfiguration(List.of(defaults));
|
||||
String python = applications.createApplication(create).getApplicationId();
|
||||
// The user guide's "Building a Python virtual environment".
|
||||
StartJobRunRequest request = request(null, null);
|
||||
request.getJobDriver().getSparkSubmit().setSparkSubmitParameters(String.join(" ",
|
||||
"--conf spark.archives=s3://bucket/envs/pyspark_venv.tar.gz#environment",
|
||||
"--conf spark.emr-serverless.driverEnv.PYSPARK_DRIVER_PYTHON=./environment/bin/python",
|
||||
"--conf spark.emr-serverless.driverEnv.PYSPARK_PYTHON=./environment/bin/python",
|
||||
"--conf spark.executorEnv.PYSPARK_PYTHON=./environment/bin/python"));
|
||||
|
||||
service.startJobRun(python, request);
|
||||
runNext();
|
||||
|
||||
SparkJobRunner.Job job = runner.jobs.get(0);
|
||||
assertEquals(Map.of("JAVA_HOME", "/usr/lib/jvm/java-17-amazon-corretto.x86_64/",
|
||||
"PYSPARK_DRIVER_PYTHON", "./environment/bin/python", "PYSPARK_PYTHON", "./environment/bin/python"),
|
||||
job.environment());
|
||||
assertEquals(List.of("s3://bucket/envs/pyspark_venv.tar.gz#environment"), job.archives());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sparkPropertiesTakeEachFormOfConfASubmitGivesALaterOneWinning() {
|
||||
JobDriver.SparkSubmit sparkSubmit = new JobDriver.SparkSubmit();
|
||||
sparkSubmit.setSparkSubmitParameters("--conf spark.archives=s3://bucket/a.zip "
|
||||
+ "--conf='spark.archives= s3://bucket/b.tar.gz#b ,, s3://bucket/c.tgz' "
|
||||
+ "-c spark.emr-serverless.driverEnv.A=1=2 --conf spark.emr-serverless.driverEnv.=x "
|
||||
+ "--conf no-value --name spark.archives=ignored --conf");
|
||||
|
||||
Map<String, String> properties = EmrServerlessJobRunService.sparkProperties(
|
||||
Map.of("spark.executor.cores", "4"), sparkSubmit);
|
||||
|
||||
assertEquals(Map.of("spark.executor.cores", "4",
|
||||
"spark.archives", " s3://bucket/b.tar.gz#b ,, s3://bucket/c.tgz",
|
||||
"spark.emr-serverless.driverEnv.A", "1=2", "spark.emr-serverless.driverEnv.", "x"), properties);
|
||||
assertEquals(List.of("s3://bucket/b.tar.gz#b", "s3://bucket/c.tgz"),
|
||||
EmrServerlessJobRunService.archives(properties));
|
||||
assertEquals(Map.of("A", "1=2"), EmrServerlessJobRunService.driverEnvironment(properties));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theLastArchivesOptionIsSparkArchivesWinningOverASettingOfItWhereverThatComes() {
|
||||
JobDriver.SparkSubmit sparkSubmit = new JobDriver.SparkSubmit();
|
||||
sparkSubmit.setSparkSubmitParameters("--archives s3://bucket/first.zip "
|
||||
+ "--archives=s3://bucket/envs/pyspark_venv.tar.gz#environment "
|
||||
+ "--conf spark.archives=s3://bucket/conf.zip");
|
||||
|
||||
Map<String, String> properties = EmrServerlessJobRunService.sparkProperties(
|
||||
Map.of("spark.archives", "s3://bucket/defaults.zip"), sparkSubmit);
|
||||
|
||||
assertEquals(Map.of("spark.archives", "s3://bucket/envs/pyspark_venv.tar.gz#environment"), properties);
|
||||
sparkSubmit.setSparkSubmitParameters("--conf spark.archives=s3://bucket/conf.zip --archives");
|
||||
assertEquals(Map.of("spark.archives", "s3://bucket/conf.zip"),
|
||||
EmrServerlessJobRunService.sparkProperties(Map.of(), sparkSubmit));
|
||||
}
|
||||
|
||||
private String applicationWithSparkDefaults(String releaseLabel) {
|
||||
RuntimeConfiguration defaults = new RuntimeConfiguration();
|
||||
defaults.setMember("classification", "spark-defaults");
|
||||
|
||||
+218
-3
@@ -2,6 +2,7 @@ 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.command.CopyArchiveToContainerCmd;
|
||||
import com.github.dockerjava.api.exception.InternalServerErrorException;
|
||||
import com.github.dockerjava.api.model.Container;
|
||||
import com.github.dockerjava.api.model.Frame;
|
||||
@@ -15,29 +16,45 @@ 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.ecr.registry.EcrRegistryManager;
|
||||
import io.github.hectorvent.floci.services.lambda.launcher.BootstrapProcess;
|
||||
import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService.LaunchImage;
|
||||
import io.github.hectorvent.floci.services.lambda.launcher.LambdaExecutionRoleCredentials;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.s3.model.S3Object;
|
||||
import io.github.hectorvent.floci.testing.MutableClock;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InOrder;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.Closeable;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.io.StringReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Properties;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
@@ -215,6 +232,170 @@ class EmrServerlessSparkRunnerTest {
|
||||
EmrServerlessSparkRunner.environment(List.of("AWS_REGION=eu-west-1"), Map.of()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anArchiveInS3IsPutInTheContainerAndUnpackedIntoTheWorkingDirectoryBeforeTheDriverStarts() {
|
||||
ContainerBuilder builder = mock(ContainerBuilder.class);
|
||||
ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
|
||||
when(builder.newContainer(anyString())).thenReturn(spec);
|
||||
EmrServerlessSparkRunner runner = runner(builder);
|
||||
CopyArchiveToContainerCmd copy = mock(CopyArchiveToContainerCmd.class, RETURNS_SELF);
|
||||
when(docker.copyArchiveToContainerCmd("driver")).thenReturn(copy);
|
||||
Map<String, String> copied = copiedIn(copy);
|
||||
inS3("bucket", "envs/pyspark_venv.tar.gz", "a virtual environment");
|
||||
inS3("bucket", "libs/deps.zip", "some libraries");
|
||||
|
||||
runner.run(archiveJob(List.of("s3://bucket/envs/pyspark_venv.tar.gz#environment", "s3a://bucket/libs/deps.zip",
|
||||
"file:///opt/local.tar.gz#local")), progress);
|
||||
|
||||
// The guide's virtual environment by the name after its "#", one without a "#" by its file's; Spark alone
|
||||
// unpacks one outside S3.
|
||||
verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.subList(0, 2).equals(List.of("/bin/bash", "-c"))
|
||||
&& entrypoint.get(2).contains("tar -xf") && entrypoint.subList(3, entrypoint.size()).equals(List.of(
|
||||
"floci", "/tmp/floci-archives/1/pyspark_venv.tar.gz", "environment",
|
||||
"/tmp/floci-archives/2/deps.zip", "deps.zip", "--", "/usr/lib/spark/bin/spark-submit"))));
|
||||
verify(spec).withCmd(argThat((List<String> cmd) -> "s3://bucket/jobs/app.jar".equals(cmd.getLast())));
|
||||
// Each streamed into the created container, extracted at its root.
|
||||
assertEquals(Map.of("tmp/floci-archives/1/pyspark_venv.tar.gz", "a virtual environment",
|
||||
"tmp/floci-archives/2/deps.zip", "some libraries"), copied);
|
||||
InOrder order = inOrder(lifecycle, copy);
|
||||
order.verify(lifecycle).create(any());
|
||||
order.verify(copy, times(2)).withRemotePath("/");
|
||||
order.verify(lifecycle).startCreated(eq("driver"), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anArchiveThatCannotBeReadFailsTheRunNamingItAndNeverStartsItsDriver() {
|
||||
EmrServerlessSparkRunner runner = runner();
|
||||
when(s3.headObject("bucket", "envs/missing.tar.gz"))
|
||||
.thenThrow(new AwsException("NoSuchKey", "The specified key does not exist.", 404));
|
||||
|
||||
SparkJobRunner.Outcome outcome = runner.run(
|
||||
archiveJob(List.of("s3://bucket/envs/missing.tar.gz#environment")), progress);
|
||||
|
||||
assertEquals("Could not read the archive s3://bucket/envs/missing.tar.gz: The specified key does not exist.",
|
||||
outcome.failure());
|
||||
verify(lifecycle, never()).startCreated(anyString(), any());
|
||||
verify(lifecycle).stopAndRemove("driver", null, 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRunStoppedWhileItsImageIsPulledPutsInNoArchiveAndNeverStartsItsDriver() {
|
||||
EmrServerlessSparkRunner runner = runner();
|
||||
SparkJobRunner.Job job = archiveJob(List.of("s3://bucket/envs/pyspark_venv.tar.gz#environment"));
|
||||
inS3("bucket", "envs/pyspark_venv.tar.gz", "a virtual environment");
|
||||
when(lifecycle.create(any())).thenAnswer(pulling -> {
|
||||
runner.stop(job.runId());
|
||||
return "driver";
|
||||
});
|
||||
|
||||
SparkJobRunner.Outcome outcome = runner.run(job, progress);
|
||||
|
||||
assertTrue(outcome.stopped());
|
||||
verify(s3, never()).openObject(anyString(), anyString(), any());
|
||||
verify(docker, never()).copyArchiveToContainerCmd(anyString());
|
||||
verify(lifecycle, never()).startCreated(anyString(), any());
|
||||
verify(lifecycle).stopAndRemove("driver", null, 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCancelWhileAnArchiveStreamsInEndsItsCopyAndPutsInNoOther() {
|
||||
EmrServerlessSparkRunner runner = runner();
|
||||
inS3("bucket", "libs/deps.zip", "some libraries");
|
||||
// A 1 GiB archive, the run cancelled once its first bytes are read.
|
||||
long size = 1L << 30;
|
||||
AtomicLong served = new AtomicLong();
|
||||
InputStream body = new InputStream() {
|
||||
@Override
|
||||
public int read() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read(byte[] buffer, int offset, int length) {
|
||||
int read = (int) Math.min(length, size - served.get());
|
||||
if (read == 0) {
|
||||
return -1;
|
||||
}
|
||||
served.addAndGet(read);
|
||||
return read;
|
||||
}
|
||||
};
|
||||
when(s3.openObject("bucket", "envs/large.tar.gz", null)).thenReturn(new S3Service.ObjectRead(
|
||||
new S3Object("bucket", "envs/large.tar.gz", size, "application/gzip", null), body));
|
||||
when(progress.cancelled()).thenAnswer(look -> served.get() > 0);
|
||||
CopyArchiveToContainerCmd copy = mock(CopyArchiveToContainerCmd.class, RETURNS_SELF);
|
||||
when(docker.copyArchiveToContainerCmd("driver")).thenReturn(copy);
|
||||
when(copy.withTarInputStream(any())).thenAnswer(streaming -> {
|
||||
// Read to its end, as the daemon does.
|
||||
streaming.<InputStream>getArgument(0).transferTo(OutputStream.nullOutputStream());
|
||||
return copy;
|
||||
});
|
||||
|
||||
SparkJobRunner.Outcome outcome = runner.run(
|
||||
archiveJob(List.of("s3://bucket/envs/large.tar.gz#environment", "s3://bucket/libs/deps.zip")),
|
||||
progress);
|
||||
|
||||
assertTrue(outcome.stopped());
|
||||
assertTrue(served.get() < 16L << 20, served.get() + " bytes were read");
|
||||
verify(s3, never()).openObject("bucket", "libs/deps.zip", null);
|
||||
verify(lifecycle, never()).startCreated(anyString(), any());
|
||||
verify(lifecycle).stopAndRemove("driver", null, 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aJobWithoutArchivesInS3StartsSparkSubmitItself() {
|
||||
assertEquals(List.of("/usr/lib/spark/bin/spark-submit"), EmrServerlessSparkRunner.unpackingFirst(
|
||||
EmrServerlessSparkRunner.archives(archiveJob(List.of("https://example.com/env.tar.gz#environment"))),
|
||||
List.of("/usr/lib/spark/bin/spark-submit")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theWrapperUnpacksEachArchiveAsSparkDoesThenRunsWhatFollows(@TempDir Path directory) throws Exception {
|
||||
Path environment = directory.resolve("pyspark_venv.TAR.GZ");
|
||||
try (TarArchiveOutputStream tar = new TarArchiveOutputStream(
|
||||
new GZIPOutputStream(Files.newOutputStream(environment)))) {
|
||||
byte[] python = bytes("#!/bin/sh\necho python\n");
|
||||
TarArchiveEntry entry = new TarArchiveEntry("bin/python");
|
||||
entry.setSize(python.length);
|
||||
entry.setMode(0755);
|
||||
tar.putArchiveEntry(entry);
|
||||
tar.write(python);
|
||||
tar.closeArchiveEntry();
|
||||
}
|
||||
Path libraries = directory.resolve("deps.zip");
|
||||
try (ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(libraries))) {
|
||||
zip.putNextEntry(new ZipEntry("lib/helpers.py"));
|
||||
zip.write(bytes("helpers"));
|
||||
zip.closeEntry();
|
||||
}
|
||||
Path notes = directory.resolve("notes.txt");
|
||||
Files.writeString(notes, "notes");
|
||||
Path workingDirectory = Files.createDirectory(directory.resolve("home"));
|
||||
String script = "./environment/bin/python; cat deps.zip/lib/helpers.py readme; echo \" $1\"";
|
||||
List<String> entrypoint = EmrServerlessSparkRunner.unpackingFirst(List.of(
|
||||
archive(environment, "environment"), archive(libraries, "deps.zip"), archive(notes, "readme")),
|
||||
List.of("sh", "-c", script, "sh"));
|
||||
List<String> command = new ArrayList<>(entrypoint);
|
||||
command.add("argument");
|
||||
|
||||
BootstrapProcess.Result ended = BootstrapProcess.run(new ProcessBuilder(command).directory(
|
||||
workingDirectory.toFile()));
|
||||
|
||||
assertEquals(new BootstrapProcess.Result(0, "python\nhelpersnotes argument\n"), ended);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anArchiveThatDoesNotUnpackStopsTheDriverFromStarting(@TempDir Path directory) throws Exception {
|
||||
Path broken = Files.writeString(directory.resolve("broken.tar.gz"), "not an archive");
|
||||
List<String> command = EmrServerlessSparkRunner.unpackingFirst(List.of(archive(broken, "environment")),
|
||||
List.of("echo", "started"));
|
||||
|
||||
BootstrapProcess.Result ended = BootstrapProcess.run(new ProcessBuilder(command).directory(directory.toFile()));
|
||||
|
||||
assertTrue(ended.exit() != 0);
|
||||
assertFalse(ended.output().contains("started"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCommandsOwnSparkSubmitRunsLocallyOnFlocisS3WithTheJobsSparkDefaults() {
|
||||
assertEquals(String.join("\n",
|
||||
@@ -583,6 +764,34 @@ class EmrServerlessSparkRunnerTest {
|
||||
}
|
||||
}
|
||||
|
||||
// What each tar copied into the container holds, by entry, read as the daemon reads it.
|
||||
private static Map<String, String> copiedIn(CopyArchiveToContainerCmd copy) {
|
||||
Map<String, String> copied = new LinkedHashMap<>();
|
||||
when(copy.withTarInputStream(any())).thenAnswer(streaming -> {
|
||||
InputStream stream = streaming.getArgument(0);
|
||||
TarArchiveInputStream tar = new TarArchiveInputStream(stream);
|
||||
for (TarArchiveEntry entry = tar.getNextEntry(); entry != null; entry = tar.getNextEntry()) {
|
||||
copied.put(entry.getName(), new String(tar.readAllBytes(), StandardCharsets.UTF_8));
|
||||
}
|
||||
// Read to its end, as the daemon does, so the writer finishes; the copy closes the stream.
|
||||
stream.transferTo(OutputStream.nullOutputStream());
|
||||
return copy;
|
||||
});
|
||||
return copied;
|
||||
}
|
||||
|
||||
// An object in Floci's S3, which each read opens afresh.
|
||||
private void inS3(String bucket, String key, String content) {
|
||||
S3Object object = new S3Object(bucket, key, bytes(content), "application/octet-stream");
|
||||
when(s3.openObject(bucket, key, null))
|
||||
.thenAnswer(read -> new S3Service.ObjectRead(object, new ByteArrayInputStream(object.getData())));
|
||||
}
|
||||
|
||||
// An archive at file, a path on this host, to be unpacked into directory.
|
||||
private static EmrServerlessSparkRunner.Archive archive(Path file, String directory) {
|
||||
return new EmrServerlessSparkRunner.Archive(null, null, file.toString(), directory);
|
||||
}
|
||||
|
||||
private static byte[] bytes(String text) {
|
||||
return text.getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
@@ -626,18 +835,24 @@ class EmrServerlessSparkRunnerTest {
|
||||
SparkJobRunner.CloudWatchLogs cloudWatchLogs) {
|
||||
return new SparkJobRunner.Job("emr-serverless", "00f0000000000001", "123456789012", "eu-west-1", "emr-7.5.0",
|
||||
imageTemplate, null, "floci-network", "arn:aws:iam::123456789012:role/job", sparkDefaults,
|
||||
application, null, timeout, logFolder, cloudWatchLogs, Map.of());
|
||||
application, null, timeout, logFolder, cloudWatchLogs, Map.of(), List.of());
|
||||
}
|
||||
|
||||
private static SparkJobRunner.Job customImageJob(String customImage) {
|
||||
return new SparkJobRunner.Job("emr-serverless", "00f0000000000001", "123456789012", "eu-west-1", "emr-7.5.0",
|
||||
null, customImage, "floci-network", "arn:aws:iam::123456789012:role/job", Map.of(),
|
||||
List.of("s3://bucket/jobs/app.jar"), null, Duration.ZERO, null, null, Map.of());
|
||||
List.of("s3://bucket/jobs/app.jar"), null, Duration.ZERO, null, null, Map.of(), List.of());
|
||||
}
|
||||
|
||||
private static SparkJobRunner.Job archiveJob(List<String> archives) {
|
||||
return new SparkJobRunner.Job("emr-serverless", "00f0000000000001", "123456789012", "eu-west-1", "emr-7.5.0",
|
||||
null, null, "floci-network", "arn:aws:iam::123456789012:role/job", Map.of(),
|
||||
List.of("s3://bucket/jobs/app.jar"), null, Duration.ZERO, null, null, Map.of(), archives);
|
||||
}
|
||||
|
||||
private static SparkJobRunner.Job commandJob(List<String> command, Map<String, String> sparkDefaults) {
|
||||
return new SparkJobRunner.Job("emr", "s-1A2B3C4D5E6F7", "123456789012", "eu-west-1", "emr-7.5.0", null,
|
||||
null, "floci-network", "arn:aws:iam::123456789012:role/job", sparkDefaults, List.of(), command,
|
||||
Duration.ZERO, null, null, Map.of("PYSPARK_PYTHON", "/usr/bin/python3.11"));
|
||||
Duration.ZERO, null, null, Map.of("PYSPARK_PYTHON", "/usr/bin/python3.11"), List.of());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user