mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(emrserverless): run Hive job runs in the docker runner mode (#7407)
In the docker runner mode a Hive application's job run failed without
running ("Floci runs Spark job runs only"). It now runs: Floci starts
hive in a container of the release's EMR Serverless Hive image
(public.ecr.aws/emr-serverless/hive/<release>, or the new
hive-image-template), with Tez in local mode in Hive's JVM, S3A on
Floci's S3 and the Glue Data Catalog client, the image's metastore, on
Floci's Glue in the run's account.
- hive gets the core-site, tez-site and hive-site classifications as
--hiveconf settings, the application's then the run's, a run's
classification replacing the application's; then -i initQueryFile
and -f query; then the run's parameters, whose --hiveconf settings
take priority, as the user guide ranks them.
- The run's hive.exec.scratchdir and hive.metastore.warehouse.dir are
used as it sets them, in S3. Tez in local mode copies a session's
staging folder, which Hive puts under the scratch folder, to the same
path in the container, a copy that silently does nothing where the
image's hadoop user cannot create that path. The container starts as
root, makes that path hadoop's, sets the Tez addresses EMR
Serverless's runtime would set, then runs hive as hadoop in its home
folder, with the groups Docker gives it. The scratch folder is the
last hive.exec.scratchdir setting, in any form Hive's CLI reads:
--hiveconf name=value, --hiveconf=name=value, with one dash or two,
or the value as the next argument.
- A Hive application's custom image is its HiveDriver worker type's,
else the application's; Tez's tasks run in the driver's container, so
a TezTask image is not used.
- The driver's stdout.gz and stderr.gz go to the run's HIVE_DRIVER log
folder, and its CloudWatch log streams are under HIVE_DRIVER, the
entry of logTypes it reads; Hive's own log stays in the container.
- A run whose driver is not its application's type, hive on a Spark
application or sparkSubmit on a Hive one, fails without running.
spark-defaults go through the same classification merge. The
Docker-gated EmrServerlessHiveDockerIntegrationTest runs the user
guide's Hive job and a failing query in the emr-7.5.0 Hive image, which
the CI prefetch pulls for its shard. EmrServerlessRequests'
createApplication takes the application's type, and S3TestClients'
deleteBucket empties and deletes a test's bucket.
This commit is contained in:
1 parent
8d9d74084d
commit
710b2488bf
14 files changed
+753
-82
No files matched your search
@@ -97,6 +97,9 @@ starts ElbV2LambdaTargetDataPlaneIntegrationTest && ecr public.ecr.aws/lambda/py
|
||||
# EmrDockerRunnerDockerIntegrationTest runs EMR steps and EMR Serverless job runs in the emr-7.5.0 image the runner's
|
||||
# default template names (EmrServerlessSparkRunner), 3.5 GB, so it is queued last, behind the Lambda runtimes.
|
||||
starts EmrDockerRunnerDockerIntegrationTest && ecr public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest
|
||||
# EmrServerlessHiveDockerIntegrationTest runs EMR Serverless Hive job runs in the emr-7.5.0 Hive image the runner's
|
||||
# default Hive template names, 2.7 GB.
|
||||
starts EmrServerlessHiveDockerIntegrationTest && ecr public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest
|
||||
|
||||
# package token in shard.txt -> images its tests are known to launch
|
||||
# (measured inline pulls; update alongside image-catalog changes)
|
||||
|
||||
@@ -9,9 +9,10 @@ EMR Serverless is an AWS service that provides serverless data analytics environ
|
||||
| `floci.emrserverless.enabled` | Whether the EMR Serverless API is enabled | `true` |
|
||||
| `floci.emrserverless.port` | The port the service is exposed on | `4566` |
|
||||
| `floci.services.emrserverless.job-run-duration-seconds` | How long a `BATCH` job run stays `RUNNING` before it succeeds; `0` makes it `SUCCESS` as soon as it starts | `0` |
|
||||
| `floci.services.emrserverless.runner-mode` | `immediate` moves job runs through their states without running anything; `docker` runs each Spark job run in a container (see [Running Spark job runs](#running-spark-job-runs)) | `immediate` |
|
||||
| `floci.services.emrserverless.runner-mode` | `immediate` moves job runs through their states without running anything; `docker` runs each job run in a container (see [Running Spark job runs](#running-spark-job-runs) and [Running Hive job runs](#running-hive-job-runs)) | `immediate` |
|
||||
| `floci.services.emrserverless.docker-network` | Docker network for job run containers | the global default |
|
||||
| `floci.services.emrserverless.image-template` | Image for a `docker` job run whose application names no custom image, `%s` standing for the release label | `public.ecr.aws/emr-serverless/spark/%s:latest`, or `spark4/` in place of `spark/` for an `emr-spark-*` release |
|
||||
| `floci.services.emrserverless.hive-image-template` | Image for a `docker` Hive job run whose application names no custom image, `%s` standing for the release label | `public.ecr.aws/emr-serverless/hive/%s:latest` |
|
||||
| `floci.services.emrserverless.reconcile-containers-on-startup` | Remove the drivers a previous run of this Floci left on the Docker daemon before the first job run starts; turn it off when two Floci instances share a daemon with the same port and no resource namespace | `true` |
|
||||
|
||||
## Endpoints
|
||||
@@ -198,9 +199,43 @@ AWS runtime for Apache Spark releases, `emr-spark-8.0.0` on), and runs
|
||||
`image-template` names another image than the release's, such as a mirror or a dated tag of it:
|
||||
`registry.internal/emr-serverless/spark/%s:20250425`.
|
||||
|
||||
## Running Hive job runs
|
||||
|
||||
With `runner-mode` set to `docker`, a Hive application's job run executes too. Floci starts one container per
|
||||
run from the application's custom image, if it names one, or else from the release's Hive image, the base image
|
||||
AWS publishes for customizing EMR Serverless Hive images (`public.ecr.aws/emr-serverless/hive/<release>`), and
|
||||
runs `hive` in it, with Tez in local mode, in Hive's JVM: the container holds the Hive driver and its Tez tasks.
|
||||
The custom image is the `HiveDriver` worker type's `imageConfiguration` in `workerTypeSpecifications`, or else the
|
||||
application's `imageConfiguration`; a `TezTask` image is not used, as Tez's tasks run in the driver's container.
|
||||
|
||||
* **States, credentials, HTTPS and the image**: as for a Spark run, above, the driver being `hive`. The first run
|
||||
of a release pulls its Hive image, 2.7 GB unpacked. Without a custom image, `hive-image-template` names another
|
||||
image than the release's: `registry.internal/emr-serverless/hive/%s:20250425`.
|
||||
* **What `hive` gets**: the properties of the `core-site`, `tez-site` and `hive-site` classifications, each a
|
||||
`--hiveconf`, from the application's `runtimeConfiguration` or the run's own
|
||||
`configurationOverrides.applicationConfiguration`, which replaces the application's whole classification; then
|
||||
the run's `initQueryFile` and `query`, which Hive reads from Floci's S3 and runs in that order; then its
|
||||
`parameters`, split as a shell would split them, so a `--hiveconf` there takes priority over the classifications,
|
||||
as the user guide ranks them. Before them all come Floci's own settings, which any of them replaces: S3A on
|
||||
Floci's S3 for `s3://`, the Glue Data Catalog client, the image's metastore, on Floci's Glue with the run's
|
||||
account as its `hive.metastore.glue.catalogid` (a `hive-site` one names another account's catalog), and Tez in
|
||||
local mode. `emrfs-site` is not applied, as `s3://` goes through S3A rather than EMRFS.
|
||||
* **Scratch and warehouse folders**: `hive.exec.scratchdir` and `hive.metastore.warehouse.dir`, which the user
|
||||
guide makes mandatory, are used as the run sets them, in Floci's S3. Hive runs as the image's `hadoop` user, in
|
||||
its home folder; Tez in local mode copies its session's staging folder, which Hive puts under the scratch
|
||||
folder, to the same path in the container, so Floci makes that path `hadoop`'s before Hive starts.
|
||||
* **Output**: the driver's standard output, where Hive prints a query's results, and its standard error, where the
|
||||
Hive CLI prints its progress and errors, go to Floci's log, prefixed `emr-serverless:<jobRunId>`. With an S3 log
|
||||
destination they also go to `stdout.gz` and `stderr.gz` under
|
||||
`<logUri>/applications/<applicationId>/jobs/<jobRunId>/HIVE_DRIVER/` once the run ends, and with CloudWatch
|
||||
logging to the log streams `.../HIVE_DRIVER/stdout` and `.../HIVE_DRIVER/stderr` while it runs, as a Spark run's
|
||||
go under `SPARK_DRIVER`; a `logTypes` takes the driver's types from its `HIVE_DRIVER` entry.
|
||||
|
||||
## Limitations and Differences from AWS
|
||||
|
||||
* **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).
|
||||
* **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, and a Hive run with Tez in local mode, so worker counts and sizes, initial and maximum capacity are not applied. A driver's failure is `FAILED` in Floci's own wording. 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, no `HIVE_LOG`, `TEZ_AM` or `TEZ_TASK` logs of a Hive run, whose own log stays in its container, and `encryptionKeyArn` is ignored).
|
||||
* **A driver that is not its application's type**: AWS documents no answer for a `hive` run on a Spark application, or a `sparkSubmit` run on a Hive application. In the `docker` mode Floci records such a run, then fails it without running, in Floci's own wording, as its application's image could not run it.
|
||||
* **Mandatory Hive properties**: Floci does not refuse a Hive run without `hive.exec.scratchdir` or `hive.metastore.warehouse.dir`. Hive then keeps its scratch files and its managed tables' data in the container, which go with it.
|
||||
* **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,
|
||||
|
||||
@@ -1117,8 +1117,8 @@ public interface EmulatorConfig {
|
||||
|
||||
/**
|
||||
* {@code immediate} follows the job run states without running anything; {@code docker} runs
|
||||
* each Spark job run's {@code spark-submit} in a container of the application's custom image, or
|
||||
* else of the release's EMR Serverless image.
|
||||
* each Spark job run's {@code spark-submit}, and each Hive job run's {@code hive}, in a container of the
|
||||
* application's custom image, or else of the release's EMR Serverless image.
|
||||
*/
|
||||
@WithDefault("immediate")
|
||||
String runnerMode();
|
||||
@@ -1133,6 +1133,14 @@ public interface EmulatorConfig {
|
||||
*/
|
||||
Optional<String> imageTemplate();
|
||||
|
||||
/**
|
||||
* The image a {@code docker} Hive job run uses when its application names no custom image, as
|
||||
* {@link #imageTemplate()} is for a Spark run, for example
|
||||
* "registry.internal/emr-serverless/hive/%s:20250425". If omitted, Floci uses the release's public
|
||||
* Hive image on Amazon ECR Public.
|
||||
*/
|
||||
Optional<String> hiveImageTemplate();
|
||||
|
||||
/**
|
||||
* When true, Floci removes, in the {@code docker} runner mode, every EMR Serverless driver a
|
||||
* previous run of <em>this same</em> Floci left on the daemon (matched by the
|
||||
|
||||
@@ -1416,6 +1416,7 @@ public class EmrService implements Resettable, StoredResourceArns {
|
||||
}
|
||||
SparkJobRunner.Job job = application == null && command == null ? null
|
||||
: new SparkJobRunner.Job(SERVICE, step.getId(), accountId, region, cluster.getReleaseLabel(),
|
||||
SparkJobRunner.Engine.SPARK,
|
||||
cluster.getBootstrapImage() != null ? cluster.getBootstrapImage() : imageTemplate, null,
|
||||
dockerNetwork, executionRole(cluster, step, accountId),
|
||||
EmrSparkSteps.sparkDefaults(cluster.getConfigurations(), SNAPSHOT_MAPPER),
|
||||
|
||||
+102
-39
@@ -91,8 +91,15 @@ public class EmrServerlessJobRunService implements Resettable {
|
||||
// "If you don't specify the optional values, then CloudWatch publishes the logs to a default log group".
|
||||
private static final String DEFAULT_LOG_GROUP = "/aws/emr-serverless";
|
||||
private static final String SPARK_DRIVER = "SPARK_DRIVER";
|
||||
// The worker type a Spark application's driver runs as.
|
||||
private static final String HIVE_DRIVER = "HIVE_DRIVER";
|
||||
private static final String HIVE_TYPE = "HIVE";
|
||||
// The classifications a Hive run's settings come from, "Hadoop's core-site.xml", "Tez's tez-site.xml" and "Hive's
|
||||
// hive-site.xml", in the order Hive loads the files, a later one winning. emrfs-site sets EMRFS, which Floci's
|
||||
// S3A replaces.
|
||||
private static final List<String> HIVE_CLASSIFICATIONS = List.of("core-site", "tez-site", "hive-site");
|
||||
// The worker types a Spark application's driver and a Hive application's run as.
|
||||
private static final String DRIVER_WORKER_TYPE = "Driver";
|
||||
private static final String HIVE_DRIVER_WORKER_TYPE = "HiveDriver";
|
||||
// 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";
|
||||
@@ -101,7 +108,8 @@ public class EmrServerlessJobRunService implements Resettable {
|
||||
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 DRIVER_NOT_THE_APPLICATIONS = "Floci runs a Spark application's sparkSubmit job runs and a"
|
||||
+ " Hive application's hive job runs, and this job run's driver is not its application's type.";
|
||||
static final String INTERRUPTED = "Floci stopped while the job run was in progress.";
|
||||
|
||||
private static final Set<String> TERMINAL_STATES = Set.of(STATE_SUCCESS, STATE_FAILED, STATE_CANCELLED);
|
||||
@@ -148,9 +156,10 @@ public class EmrServerlessJobRunService implements Resettable {
|
||||
// Null in the immediate runner mode.
|
||||
private final SparkJobRunner sparkRunner;
|
||||
private final Executor runExecutor;
|
||||
// Where a container run's driver runs: image-template, with the release label for %s, and docker-network;
|
||||
// null when not set.
|
||||
// Where a container run's driver runs: image-template for a Spark run and hive-image-template for a Hive one,
|
||||
// with the release label for %s, and docker-network; null when not set.
|
||||
private final String imageTemplate;
|
||||
private final String hiveImageTemplate;
|
||||
private final String dockerNetwork;
|
||||
// Container runs a thread is running; one not here that has not ended was left by a restart.
|
||||
private final Set<String> executing = new HashSet<>();
|
||||
@@ -168,6 +177,7 @@ public class EmrServerlessJobRunService implements Resettable {
|
||||
RUNNER_DOCKER.equalsIgnoreCase(config.services().emrserverless().runnerMode()) ? sparkRunner : null,
|
||||
Executors.newCachedThreadPool(Thread.ofPlatform().daemon().name("emr-serverless-run-", 0).factory()),
|
||||
config.services().emrserverless().imageTemplate().orElse(null),
|
||||
config.services().emrserverless().hiveImageTemplate().orElse(null),
|
||||
config.services().emrserverless().dockerNetwork().orElse(null));
|
||||
// Before any run of this process starts: a driver an earlier one left belongs to a run read as FAILED.
|
||||
if (this.sparkRunner != null && config.services().emrserverless().reconcileContainersOnStartup()) {
|
||||
@@ -187,15 +197,14 @@ public class EmrServerlessJobRunService implements Resettable {
|
||||
ObjectMapper objectMapper, int runDurationSeconds, Clock clock,
|
||||
SparkJobRunner sparkRunner, Executor runExecutor) {
|
||||
this(store, applications, iamService, regionResolver, requestContext, objectMapper, runDurationSeconds, clock,
|
||||
sparkRunner, runExecutor, null, null);
|
||||
sparkRunner, runExecutor, null, null, null);
|
||||
}
|
||||
|
||||
private EmrServerlessJobRunService(AccountAwareStorageBackend<JobRunRecord> store,
|
||||
EmrServerlessService applications, IamService iamService,
|
||||
RegionResolver regionResolver, RequestContext requestContext,
|
||||
ObjectMapper objectMapper, int runDurationSeconds, Clock clock,
|
||||
SparkJobRunner sparkRunner, Executor runExecutor,
|
||||
String imageTemplate, String dockerNetwork) {
|
||||
EmrServerlessJobRunService(AccountAwareStorageBackend<JobRunRecord> store, EmrServerlessService applications,
|
||||
IamService iamService, RegionResolver regionResolver, RequestContext requestContext,
|
||||
ObjectMapper objectMapper, int runDurationSeconds, Clock clock,
|
||||
SparkJobRunner sparkRunner, Executor runExecutor,
|
||||
String imageTemplate, String hiveImageTemplate, String dockerNetwork) {
|
||||
if (runDurationSeconds < 0) {
|
||||
throw new IllegalArgumentException(
|
||||
"floci.services.emrserverless.job-run-duration-seconds must not be negative: " + runDurationSeconds);
|
||||
@@ -211,6 +220,7 @@ public class EmrServerlessJobRunService implements Resettable {
|
||||
this.sparkRunner = sparkRunner;
|
||||
this.runExecutor = runExecutor;
|
||||
this.imageTemplate = imageTemplate;
|
||||
this.hiveImageTemplate = hiveImageTemplate;
|
||||
this.dockerNetwork = dockerNetwork;
|
||||
}
|
||||
|
||||
@@ -475,12 +485,17 @@ public class EmrServerlessJobRunService implements Resettable {
|
||||
return record;
|
||||
}
|
||||
|
||||
/** Hands a container run to a thread of its own, which runs it to its end. */
|
||||
/**
|
||||
* Hands a container run to a thread of its own, which runs it to its end. A run whose driver is not its
|
||||
* application's type, a {@code hive} one on a Spark application or a {@code sparkSubmit} one on a Hive
|
||||
* application, fails without running: AWS documents no answer for one, and its application's image could
|
||||
* not run it.
|
||||
*/
|
||||
private void launch(JobRunRecord record, Application app) {
|
||||
JobRun run = record.getJobRun();
|
||||
JobDriver.SparkSubmit sparkSubmit = run.getJobDriver().getSparkSubmit();
|
||||
if (sparkSubmit == null) {
|
||||
run.setStateDetails(HIVE_NOT_RUN);
|
||||
JobDriver.Hive hive = run.getJobDriver().getHive();
|
||||
if ((hive != null) != HIVE_TYPE.equalsIgnoreCase(app.getType())) {
|
||||
run.setStateDetails(DRIVER_NOT_THE_APPLICATIONS);
|
||||
finish(record, STATE_FAILED, run.getCreatedAt());
|
||||
return;
|
||||
}
|
||||
@@ -489,13 +504,23 @@ 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, application(sparkSubmit), null, timeout, driverLogFolder(app, run),
|
||||
driverCloudWatchLogs(app, run), driverEnvironment(sparkProperties), archives(sparkProperties),
|
||||
null, Map.of(), Map.of(), Map.of(), Map.of(), Map.of());
|
||||
SparkJobRunner.Job job;
|
||||
if (hive != null) {
|
||||
job = new SparkJobRunner.Job(SERVICE, run.getJobRunId(), arn.accountId(), arn.region(),
|
||||
run.getReleaseLabel(), SparkJobRunner.Engine.HIVE, hiveImageTemplate, customImage(app),
|
||||
dockerNetwork, run.getExecutionRole(), Map.of(), hiveArguments(app, run, hive), null, timeout,
|
||||
driverLogFolder(app, run), driverCloudWatchLogs(app, run), Map.of(), List.of(), null, Map.of(),
|
||||
Map.of(), Map.of(), Map.of(), Map.of());
|
||||
} else {
|
||||
JobDriver.SparkSubmit sparkSubmit = run.getJobDriver().getSparkSubmit();
|
||||
Map<String, String> sparkDefaults = sparkDefaults(app, run);
|
||||
Map<String, String> sparkProperties = sparkProperties(sparkDefaults, sparkSubmit);
|
||||
job = new SparkJobRunner.Job(SERVICE, run.getJobRunId(), arn.accountId(), arn.region(),
|
||||
run.getReleaseLabel(), SparkJobRunner.Engine.SPARK, imageTemplate, customImage(app),
|
||||
dockerNetwork, run.getExecutionRole(), sparkDefaults, application(sparkSubmit), null, timeout,
|
||||
driverLogFolder(app, run), driverCloudWatchLogs(app, run), driverEnvironment(sparkProperties),
|
||||
archives(sparkProperties), null, Map.of(), Map.of(), Map.of(), Map.of(), Map.of());
|
||||
}
|
||||
executing.add(run.getJobRunId());
|
||||
long launchedIn = generation;
|
||||
runExecutor.execute(() -> execute(job, launchedIn));
|
||||
@@ -514,13 +539,15 @@ public class EmrServerlessJobRunService implements Resettable {
|
||||
}
|
||||
|
||||
/**
|
||||
* The custom image a run's driver starts from, or null for the release's: the {@code Driver} worker type's,
|
||||
* else the application's, which "EMR Serverless applies ... to all worker types". Local mode runs the
|
||||
* executors in the driver's container, so an {@code Executor} image is not used.
|
||||
* The custom image a run's driver starts from, or null for the release's: its driver's worker type's,
|
||||
* {@code Driver} for a Spark application and {@code HiveDriver} for a Hive one, else the application's, which
|
||||
* "EMR Serverless applies ... to all worker types". Local mode runs Spark's executors and Tez's tasks in the
|
||||
* driver's container, so an {@code Executor} or {@code TezTask} image is not used.
|
||||
*/
|
||||
static String customImage(Application app) {
|
||||
String workerType = HIVE_TYPE.equalsIgnoreCase(app.getType()) ? HIVE_DRIVER_WORKER_TYPE : DRIVER_WORKER_TYPE;
|
||||
WorkerTypeSpecification driver = app.getWorkerTypeSpecifications() != null
|
||||
? app.getWorkerTypeSpecifications().get(DRIVER_WORKER_TYPE) : null;
|
||||
? app.getWorkerTypeSpecifications().get(workerType) : null;
|
||||
if (driver != null && driver.getImageConfiguration() != null
|
||||
&& driver.getImageConfiguration().getImageUri() != null) {
|
||||
return driver.getImageConfiguration().getImageUri();
|
||||
@@ -543,6 +570,30 @@ public class EmrServerlessJobRunService implements Resettable {
|
||||
return application;
|
||||
}
|
||||
|
||||
/**
|
||||
* What follows Floci's own settings on a Hive run's {@code hive} command line, in the user guide's order, a later
|
||||
* setting winning: its {@code core-site}, {@code tez-site} and {@code hive-site} properties, each a
|
||||
* {@code --hiveconf}, then its {@code initQueryFile} and {@code query}, which Hive runs in that order, then its
|
||||
* {@code parameters}, split as a shell would split them, whose {@code --hiveconf} settings "take priority".
|
||||
*/
|
||||
static List<String> hiveArguments(Application app, JobRun run, JobDriver.Hive hive) {
|
||||
List<String> arguments = new ArrayList<>();
|
||||
for (String classification : HIVE_CLASSIFICATIONS) {
|
||||
classificationProperties(app, run, classification).forEach((name, value) -> {
|
||||
arguments.add(EmrServerlessSparkRunner.HIVECONF_OPTION);
|
||||
arguments.add(name + "=" + value);
|
||||
});
|
||||
}
|
||||
if (hive.getInitQueryFile() != null) {
|
||||
arguments.add("-i");
|
||||
arguments.add(hive.getInitQueryFile());
|
||||
}
|
||||
arguments.add("-f");
|
||||
arguments.add(hive.getQuery());
|
||||
arguments.addAll(EmrServerlessSparkRunner.splitParameters(hive.getParameters()));
|
||||
return arguments;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -751,17 +802,22 @@ public class EmrServerlessJobRunService implements Resettable {
|
||||
launch(record, app);
|
||||
}
|
||||
|
||||
/** The {@code spark-defaults} properties for a run, as {@link #classificationProperties} merges them. */
|
||||
private static Map<String, String> sparkDefaults(Application app, JobRun run) {
|
||||
return classificationProperties(app, run, SPARK_DEFAULTS);
|
||||
}
|
||||
|
||||
/**
|
||||
* The {@code spark-defaults} properties for a run: the application's runtime configuration, then the
|
||||
* A {@code classification}'s properties for a run: the application's runtime configuration, then the
|
||||
* run's own {@code applicationConfiguration}. The two merge by classification, so a run's
|
||||
* {@code spark-defaults} replaces the application's: "Only the properties included in StartJobRun is
|
||||
* classification replaces the application's: "Only the properties included in StartJobRun is
|
||||
* considered for this classification." From emr-spark-8.1.0 they merge by property, the run's winning.
|
||||
*/
|
||||
private static Map<String, String> sparkDefaults(Application app, JobRun run) {
|
||||
private static Map<String, String> classificationProperties(Application app, JobRun run, String classification) {
|
||||
Map<String, String> properties = new LinkedHashMap<>();
|
||||
if (app.getRuntimeConfiguration() != null) {
|
||||
for (RuntimeConfiguration configuration : app.getRuntimeConfiguration()) {
|
||||
addSparkDefaults(properties, configuration.getMembers());
|
||||
addProperties(properties, configuration.getMembers(), classification);
|
||||
}
|
||||
}
|
||||
Object overrides = run.getConfigurationOverrides() != null
|
||||
@@ -770,12 +826,12 @@ public class EmrServerlessJobRunService implements Resettable {
|
||||
boolean replaces = !releaseAtLeast(SPARK_RUNTIME_RELEASE_LABEL, run.getReleaseLabel(), 8, 1);
|
||||
for (Object configuration : configurations) {
|
||||
if (configuration instanceof Map<?, ?> members
|
||||
&& SPARK_DEFAULTS.equals(members.get("classification"))) {
|
||||
&& classification.equals(members.get("classification"))) {
|
||||
if (replaces) {
|
||||
properties.clear();
|
||||
replaces = false;
|
||||
}
|
||||
addSparkDefaults(properties, members);
|
||||
addProperties(properties, members, classification);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -787,7 +843,8 @@ public class EmrServerlessJobRunService implements Resettable {
|
||||
* {@code s3MonitoringConfiguration} or else the application's, an empty one at the run removing it. Under
|
||||
* its {@code logUri} the user guide puts a run's logs at {@code /applications/<applicationId>/jobs/<jobId>},
|
||||
* with {@code /attempts/<attemptNumber>} after it for "all streaming jobs and any batch jobs that have retry
|
||||
* enabled" from release 7.1.0, and the driver's in {@code SPARK_DRIVER/}.
|
||||
* enabled" from release 7.1.0, and the driver's in {@code SPARK_DRIVER/}, or a Hive run's in
|
||||
* {@code HIVE_DRIVER/}: "EMR Serverless continuously uploads the Hive driver to the HIVE_DRIVER folder".
|
||||
*/
|
||||
static String driverLogFolder(Application app, JobRun run) {
|
||||
String logUri = monitoring(app, run, S3_MONITORING) instanceof Map<?, ?> configuration
|
||||
@@ -803,7 +860,8 @@ public class EmrServerlessJobRunService implements Resettable {
|
||||
* {@code logStreamNamePrefix}, with the attempt as for S3, and "By default, EMR Serverless publishes only
|
||||
* the driver stdout and stderr logs". Each goes to a stream of its own under the driver's, as the
|
||||
* clients that read them (Dagster's EMR Serverless client) name them: {@code .../SPARK_DRIVER/stdout}
|
||||
* and {@code .../SPARK_DRIVER/stderr}. A {@code logTypes} that names some types takes only those of the
|
||||
* and {@code .../SPARK_DRIVER/stderr}, {@code HIVE_DRIVER} for a Hive run, the worker type {@code logTypes}
|
||||
* names its driver by. A {@code logTypes} that names some types takes only those of the
|
||||
* driver's it names, none when it names only other workers': "The types of logs that you want to publish
|
||||
* to CloudWatch. If you don't specify any log types, driver STDOUT and STDERR logs will be published".
|
||||
*/
|
||||
@@ -817,14 +875,14 @@ public class EmrServerlessJobRunService implements Resettable {
|
||||
String driver = prefix + driverLogPath(run) + "/";
|
||||
List<?> driverTypes = null;
|
||||
if (configuration.get("logTypes") instanceof Map<?, ?> logTypes && !logTypes.isEmpty()) {
|
||||
driverTypes = logTypes.get(SPARK_DRIVER) instanceof List<?> types ? types : List.of();
|
||||
driverTypes = logTypes.get(driverWorkerType(run)) instanceof List<?> types ? types : List.of();
|
||||
}
|
||||
String stdout = publishes(driverTypes, "stdout") ? driver + "stdout" : null;
|
||||
String stderr = publishes(driverTypes, "stderr") ? driver + "stderr" : null;
|
||||
return stdout == null && stderr == null ? null : new SparkJobRunner.CloudWatchLogs(logGroup, stdout, stderr);
|
||||
}
|
||||
|
||||
// Whether the driver's log types, as logTypes lists them for SPARK_DRIVER, take this one; both without a list.
|
||||
// Whether the driver's log types, as logTypes lists them for its worker type, take this one; both without a list.
|
||||
private static boolean publishes(List<?> driverTypes, String logType) {
|
||||
return driverTypes == null
|
||||
|| driverTypes.stream().anyMatch(type -> logType.equalsIgnoreCase(String.valueOf(type)));
|
||||
@@ -849,7 +907,12 @@ public class EmrServerlessJobRunService implements Resettable {
|
||||
private static String driverLogPath(JobRun run) {
|
||||
String attempts = retried(run) && retriesAttempts(run.getReleaseLabel()) ? "/attempts/" + run.getAttempt() : "";
|
||||
return "/applications/" + run.getApplicationId() + "/jobs/" + run.getJobRunId() + attempts + "/"
|
||||
+ SPARK_DRIVER;
|
||||
+ driverWorkerType(run);
|
||||
}
|
||||
|
||||
// The worker type a run's driver logs as: HIVE_DRIVER for a Hive run, SPARK_DRIVER for a Spark one.
|
||||
private static String driverWorkerType(JobRun run) {
|
||||
return run.getJobDriver() != null && run.getJobDriver().getHive() != null ? HIVE_DRIVER : SPARK_DRIVER;
|
||||
}
|
||||
|
||||
// A STREAMING run is retried, and a BATCH run whose retryPolicy allows more than one attempt.
|
||||
@@ -863,8 +926,8 @@ public class EmrServerlessJobRunService implements Resettable {
|
||||
|| SPARK_RUNTIME_RELEASE_LABEL.matcher(releaseLabel != null ? releaseLabel : "").matches();
|
||||
}
|
||||
|
||||
private static void addSparkDefaults(Map<String, String> properties, Map<?, ?> configuration) {
|
||||
if (SPARK_DEFAULTS.equals(configuration.get("classification"))
|
||||
private static void addProperties(Map<String, String> properties, Map<?, ?> configuration, String classification) {
|
||||
if (classification.equals(configuration.get("classification"))
|
||||
&& configuration.get("properties") instanceof Map<?, ?> values) {
|
||||
values.forEach((key, value) -> properties.put(String.valueOf(key), String.valueOf(value)));
|
||||
}
|
||||
|
||||
+121
-4
@@ -39,7 +39,9 @@ import java.io.OutputStream;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Deque;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -62,13 +64,19 @@ import java.util.zip.GZIPOutputStream;
|
||||
* standard output and error go, gzipped, to the run's log folder in Floci's S3, when it has one. An EMR step's
|
||||
* container mounts its cluster's storage, where {@code hdfs://} paths, and paths without a scheme, lead, and a
|
||||
* step's {@code hadoop} command, and a MapReduce job its {@code spark-submit} starts, reach Floci's S3 and run
|
||||
* MapReduce in local mode, with the cluster's Hadoop configuration.
|
||||
* MapReduce in local mode, with the cluster's Hadoop configuration. A Hive run starts {@code hive} in a container of
|
||||
* the release's EMR Serverless Hive image instead, with Tez in local mode in Hive's JVM, S3A on Floci's S3 and the
|
||||
* Glue Data Catalog client, the image's metastore, on Floci's Glue.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardown {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(EmrServerlessSparkRunner.class);
|
||||
private static final String SPARK_SUBMIT = "/usr/lib/spark/bin/spark-submit";
|
||||
private static final String HIVE = "/usr/bin/hive";
|
||||
// hive's option for a setting, and its single-dash form.
|
||||
static final String HIVECONF_OPTION = "--hiveconf";
|
||||
private static final String HIVECONF_SHORT_OPTION = "-hiveconf";
|
||||
private static final String SPARK_DEFAULTS_VARIABLE = "FLOCI_SPARK_DEFAULTS";
|
||||
private static final String HADOOP_SITE_VARIABLE = "FLOCI_HADOOP_SITE";
|
||||
private static final String SPARK_LOG4J2_VARIABLE = "FLOCI_SPARK_LOG4J2";
|
||||
@@ -226,6 +234,41 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
|
||||
// The AWS runtime for Apache Spark (emr-spark-8.0.0 on) publishes its images under spark4/ instead.
|
||||
private static final String SPARK_RUNTIME_DEFAULT_IMAGE =
|
||||
"public.ecr.aws/emr-serverless/spark4/%s:latest"; // partition-literal: ECR Public's registry host, where AWS publishes the base images; image-template overrides it
|
||||
private static final String HIVE_DEFAULT_IMAGE =
|
||||
"public.ecr.aws/emr-serverless/hive/%s:latest"; // partition-literal: ECR Public's registry host, where AWS publishes the base images; hive-image-template overrides it
|
||||
// Hive's settings beside Floci's Hadoop ones. The image's Tez runs its DAGs through EMR Serverless's own container
|
||||
// plugins, which the public image cannot reach, so Tez runs them in local mode, in Hive's JVM. The port range its
|
||||
// client talks to it on is a placeholder EMR Serverless fills.
|
||||
private static final List<SparkSetting> HIVE_SETTINGS = List.of(
|
||||
new SparkSetting("tez.local.mode", "true"),
|
||||
new SparkSetting("tez.am.client.am.port-range", "40000-40100"));
|
||||
// Hive logs to a file in the folder EMR Serverless names in LOGS_DIR, its HIVE_LOG, apart from the driver's standard
|
||||
// output and error.
|
||||
private static final List<String> HIVE_ENVIRONMENT = List.of("LOGS_DIR=/tmp/floci-hive-logs");
|
||||
private static final String HIVE_SCRATCH_VARIABLE = "FLOCI_HIVE_SCRATCH";
|
||||
private static final String HIVE_SCRATCHDIR = "hive.exec.scratchdir";
|
||||
// The user every EMR Serverless image runs as: a custom one sets "the USER back to hadoop:hadoop".
|
||||
private static final String IMAGE_USER = "hadoop";
|
||||
// Starts hive as the image's user, after what EMR Serverless's runtime would do. The image's tez-site.xml takes
|
||||
// Tez's addresses from variables that runtime sets: Tez in local mode listens on every address of the container
|
||||
// and names it by its host name, which its own client connects to. Hive puts Tez's staging folder under the
|
||||
// session's scratch folder, which a run puts in S3, and Tez in local mode copies it to the same path on the local
|
||||
// file system (LocalClient), a copy that silently does nothing where the image's user cannot create that path, at
|
||||
// the root of the container for one; so the container starts as root, makes that path its user's, then runs hive
|
||||
// as that user, in that user's home, as a Spark image's working directory is: Tez in local mode puts each task's
|
||||
// files in the working directory, and the Hive image names none, which leaves the root.
|
||||
private static final String HIVE_WRAPPER = String.join("\n",
|
||||
"host=$(hostname)",
|
||||
"export CLIENT_AM_BIND_ADDRESS=0.0.0.0 TASK_AM_BIND_ADDRESS=0.0.0.0 SHUFFLE_BIND_ADDRESS=0.0.0.0",
|
||||
"export CLIENT_AM_HOSTNAME=\"$host\" TASK_AM_HOSTNAME=\"$host\" HOST_ADDRESS_LOCAL=\"$host\"",
|
||||
"if [ -n \"${" + HIVE_SCRATCH_VARIABLE + ":-}\" ]; then",
|
||||
" mkdir -p \"$" + HIVE_SCRATCH_VARIABLE + "\" && chown " + IMAGE_USER + ":" + IMAGE_USER + " \"$"
|
||||
+ HIVE_SCRATCH_VARIABLE + "\" || exit",
|
||||
"fi",
|
||||
"export HOME=~" + IMAGE_USER,
|
||||
"cd \"$HOME\" || exit",
|
||||
// The image's user has no other group, as Docker starts it.
|
||||
"exec setpriv --reuid=" + IMAGE_USER + " --regid=" + IMAGE_USER + " --clear-groups \"$@\"");
|
||||
// "The default behavior for shutdown is to have no grace period": immediate termination.
|
||||
private static final int STOP_TIMEOUT_SECONDS = 0;
|
||||
// The characters a backslash escapes inside double quotes; before any other it is kept.
|
||||
@@ -299,7 +342,17 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
|
||||
awsEnv.sdkBaselineEnv(job.region(), Optional.empty(), credentials, job.accountId()),
|
||||
job.environment()));
|
||||
// bash -c's script gets "floci" as its $0, and what runs after it as its arguments, "$@".
|
||||
if (job.command() == null) {
|
||||
if (job.engine() == Engine.HIVE) {
|
||||
List<String> hive = hiveArguments(job, endpoint);
|
||||
container.withUser("root")
|
||||
.withEntrypoint(List.of("/bin/bash", "-c", HIVE_WRAPPER, "floci", HIVE))
|
||||
.withCmd(hive)
|
||||
.withEnv(HIVE_ENVIRONMENT);
|
||||
String scratch = hiveScratchMirror(hive);
|
||||
if (scratch != null) {
|
||||
container.withEnv(HIVE_SCRATCH_VARIABLE, scratch);
|
||||
}
|
||||
} else if (job.command() == null) {
|
||||
List<String> sparkSubmit = job.sparkLog4j2().isEmpty() && job.storage() == null
|
||||
? List.of(SPARK_SUBMIT) : List.of("/bin/bash", "-c", SPARK_CONF_WRAPPER, "floci", SPARK_SUBMIT);
|
||||
container.withEntrypoint(unpackingFirst(archives, sparkSubmit))
|
||||
@@ -472,11 +525,17 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
|
||||
}
|
||||
|
||||
/**
|
||||
* The image a release's runs use: {@code imageTemplate}, with {@code %s} standing for the release
|
||||
* The image a release's Spark runs use: {@code imageTemplate}, with {@code %s} standing for the release
|
||||
* label, or, when it is null, the release's public EMR Serverless image.
|
||||
*/
|
||||
public static String image(String imageTemplate, String releaseLabel) {
|
||||
return image(imageTemplate, releaseLabel, Engine.SPARK);
|
||||
}
|
||||
|
||||
/** The image a release's runs on {@code engine} use, as the other {@code image} says, Hive's for Hive. */
|
||||
static String image(String imageTemplate, String releaseLabel, Engine engine) {
|
||||
String template = imageTemplate != null ? imageTemplate
|
||||
: engine == Engine.HIVE ? HIVE_DEFAULT_IMAGE
|
||||
: releaseLabel.startsWith("emr-spark-") ? SPARK_RUNTIME_DEFAULT_IMAGE : DEFAULT_IMAGE;
|
||||
return template.formatted(releaseLabel);
|
||||
}
|
||||
@@ -541,7 +600,7 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
|
||||
*/
|
||||
private String launchImage(Job job) {
|
||||
if (job.customImage() == null) {
|
||||
return image(job.imageTemplate(), job.releaseLabel());
|
||||
return image(job.imageTemplate(), job.releaseLabel(), job.engine());
|
||||
}
|
||||
String image = containerBuilder.resolveImage(ecrRegistryManager.rewriteImageUri(job.customImage()));
|
||||
return lifecycleManager.resolveImageForLaunch(image, ImagePullBehavior.DEFAULT, null).imageId();
|
||||
@@ -641,6 +700,64 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
|
||||
return file.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code hive}'s arguments: Floci's S3 and Glue, as a Spark run gets them, and Tez in local mode, each a
|
||||
* {@code --hiveconf}, which a later one replaces, then the run's own arguments.
|
||||
*/
|
||||
static List<String> hiveArguments(Job job, String flociEndpoint) {
|
||||
List<SparkSetting> settings = new ArrayList<>(hadoopSettings(job, flociEndpoint));
|
||||
settings.addAll(HIVE_SETTINGS);
|
||||
List<String> arguments = new ArrayList<>();
|
||||
for (SparkSetting setting : settings) {
|
||||
arguments.add(HIVECONF_OPTION);
|
||||
arguments.add(setting.key() + "=" + setting.value());
|
||||
}
|
||||
arguments.addAll(job.application());
|
||||
return arguments;
|
||||
}
|
||||
|
||||
/**
|
||||
* The local folder Tez in local mode needs for a Hive session's staging folder, or null when there is none to make:
|
||||
* where the path of {@code hive}'s scratch folder, the last {@code hive.exec.scratchdir} its arguments set, leads
|
||||
* on the local file system, when that folder is in S3, then the folder of the user Hive runs as, which Hive puts
|
||||
* the session's folders in. Hive's default scratch folder is local already. The path is the container's, so it is
|
||||
* built with {@code /} whatever Floci runs on, normalized as Hadoop normalizes the staging folder's.
|
||||
* <p>
|
||||
* Hive's CLI takes a setting as {@code --hiveconf name=value} or {@code --hiveconf=name=value}, with one dash or
|
||||
* two, and a setting without an {@code =} takes its value from the next argument, unless that is an option.
|
||||
*/
|
||||
static String hiveScratchMirror(List<String> hiveArguments) {
|
||||
String scratch = null;
|
||||
for (int i = 0; i < hiveArguments.size(); i++) {
|
||||
String argument = hiveArguments.get(i);
|
||||
String setting = null;
|
||||
if (argument.startsWith(HIVECONF_OPTION + "=") || argument.startsWith(HIVECONF_SHORT_OPTION + "=")) {
|
||||
setting = argument.substring(argument.indexOf('=') + 1);
|
||||
} else if ((HIVECONF_OPTION.equals(argument) || HIVECONF_SHORT_OPTION.equals(argument))
|
||||
&& i + 1 < hiveArguments.size()) {
|
||||
setting = hiveArguments.get(++i);
|
||||
}
|
||||
if (HIVE_SCRATCHDIR.equals(setting)) {
|
||||
boolean valued = i + 1 < hiveArguments.size() && !hiveArguments.get(i + 1).startsWith("-");
|
||||
scratch = valued ? hiveArguments.get(++i) : null;
|
||||
} else if (setting != null && setting.startsWith(HIVE_SCRATCHDIR + "=")) {
|
||||
scratch = setting.substring(HIVE_SCRATCHDIR.length() + 1);
|
||||
}
|
||||
}
|
||||
if (scratch == null || !S3Uri.isS3(scratch)) {
|
||||
return null;
|
||||
}
|
||||
Deque<String> segments = new ArrayDeque<>();
|
||||
for (String segment : (S3Uri.parseAnyScheme(scratch).key() + "/" + IMAGE_USER).split("/")) {
|
||||
if ("..".equals(segment)) {
|
||||
segments.pollLast();
|
||||
} else if (!segment.isEmpty() && !".".equals(segment)) {
|
||||
segments.addLast(segment);
|
||||
}
|
||||
}
|
||||
return "/" + String.join("/", segments);
|
||||
}
|
||||
|
||||
/**
|
||||
* The {@code core-site.xml} properties a step's {@code hadoop} command gets: Floci's S3 and Glue, as its
|
||||
* {@code spark-submit} gets them, its cluster's HDFS, then the job's {@code core-site}, which wins, as a
|
||||
|
||||
+15
-7
@@ -5,8 +5,8 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Runs a Spark application to its end, in the EMR services' {@code docker} runner mode: an EMR
|
||||
* Serverless job run, or a step of an EMR cluster. The service holds the run's state and calls this
|
||||
* Runs a Spark application, or a Hive query, to its end, in the EMR services' {@code docker} runner mode: an
|
||||
* EMR Serverless job run, or a step of an EMR cluster. The service holds the run's state and calls this
|
||||
* off the request thread; {@link EmrServerlessSparkRunner} is the Docker implementation, and a test
|
||||
* supplies its own.
|
||||
*/
|
||||
@@ -47,15 +47,23 @@ public interface SparkJobRunner {
|
||||
boolean cancelled();
|
||||
}
|
||||
|
||||
/** What a run's driver runs: Spark's {@code spark-submit}, or Hive's {@code hive}. */
|
||||
enum Engine {
|
||||
SPARK,
|
||||
HIVE
|
||||
}
|
||||
|
||||
/**
|
||||
* What a run needs: the service it belongs to and its id there, which name its container; its account
|
||||
* and Region; its release, and the image template and Docker network to run it in (a null template is
|
||||
* the release's public EMR Serverless image, a null network the global default); {@code customImage}, when
|
||||
* not null, the image the run's application names, which it runs in place of the template's, resolved
|
||||
* and Region; its release; its engine; the image template and Docker network to run it in (a null template
|
||||
* is the release's public EMR Serverless image for the engine, a null network the global default);
|
||||
* {@code customImage}, when not null, the image the run's application names, which it runs in place of the
|
||||
* template's, resolved
|
||||
* again for each run; the execution role whose credentials it gets; the {@code spark-defaults} properties
|
||||
* that apply to it;
|
||||
* {@code application}, what follows Floci's own settings on {@code spark-submit}'s command line (the
|
||||
* run's options, then its application and that application's arguments); or {@code command}, when not
|
||||
* run's options, then its application and that application's arguments), or on {@code hive}'s for a Hive run
|
||||
* (its settings, then its query files and parameters); or {@code command}, when not
|
||||
* null, what the container runs in place of {@code spark-submit}, where a {@code spark-submit} it starts
|
||||
* gets Floci's settings and the {@code spark-defaults} as defaults (its {@code application} is then
|
||||
* empty); how long it may run
|
||||
@@ -73,7 +81,7 @@ public interface SparkJobRunner {
|
||||
* MapReduce gets, the {@code log4j.properties} lines and the {@code hadoop-env.sh} exports its {@code hadoop}
|
||||
* command gets (each empty for none).
|
||||
*/
|
||||
record Job(String service, String runId, String accountId, String region, String releaseLabel,
|
||||
record Job(String service, String runId, String accountId, String region, String releaseLabel, Engine engine,
|
||||
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,
|
||||
|
||||
@@ -1023,9 +1023,10 @@ floci:
|
||||
emrserverless:
|
||||
enabled: true
|
||||
job-run-duration-seconds: 0 # 0 = BATCH job runs succeed as soon as they start
|
||||
runner-mode: immediate # docker = run each Spark job run's spark-submit in a container
|
||||
runner-mode: immediate # docker = run each job run's spark-submit or hive in a container
|
||||
# docker-network: floci-network
|
||||
# image-template: "registry.internal/emr-serverless/spark/%s:20250425" # %s = the release label
|
||||
# hive-image-template: "registry.internal/emr-serverless/hive/%s:20250425" # for Hive job runs
|
||||
# Remove the drivers a previous run of this deployment left on the daemon before the first
|
||||
# job run starts. Scoped to this deployment's own containers.
|
||||
reconcile-containers-on-startup: true
|
||||
|
||||
+2
-8
@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.testing.ContainerDataPlaneProfile;
|
||||
import io.github.hectorvent.floci.testing.DockerAvailability;
|
||||
import io.github.hectorvent.floci.testing.PartitionCleanup;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.github.hectorvent.floci.testing.S3TestClients;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.Response;
|
||||
@@ -91,7 +92,7 @@ class EmrDockerRunnerDockerIntegrationTest {
|
||||
cleanup.register(s3::close);
|
||||
bucket = "emr-docker-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
s3.createBucket(request -> request.bucket(bucket));
|
||||
cleanup.register(this::deleteBucket);
|
||||
cleanup.register(() -> S3TestClients.deleteBucket(s3, bucket));
|
||||
put("in/words.txt", WORDS);
|
||||
put("side/mapper.py", MAPPER);
|
||||
put("side/reducer.py", REDUCER);
|
||||
@@ -258,13 +259,6 @@ class EmrDockerRunnerDockerIntegrationTest {
|
||||
return awaitStep(clusterId, stepId).jsonPath().getString("Step.Status.State");
|
||||
}
|
||||
|
||||
/** Empties the test's bucket and deletes it. */
|
||||
private void deleteBucket() {
|
||||
s3.listObjectsV2Paginator(request -> request.bucket(bucket)).contents()
|
||||
.forEach(object -> s3.deleteObject(request -> request.bucket(bucket).key(object.key())));
|
||||
s3.deleteBucket(request -> request.bucket(bucket));
|
||||
}
|
||||
|
||||
private void put(String key, String text) {
|
||||
s3.putObject(request -> request.bucket(bucket).key(key), RequestBody.fromString(text));
|
||||
}
|
||||
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
package io.github.hectorvent.floci.services.emrserverless;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.testing.AwsTestClients;
|
||||
import io.github.hectorvent.floci.testing.ContainerDataPlaneProfile;
|
||||
import io.github.hectorvent.floci.testing.DockerAvailability;
|
||||
import io.github.hectorvent.floci.testing.PartitionCleanup;
|
||||
import io.github.hectorvent.floci.testing.S3TestClients;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
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.glue.GlueClient;
|
||||
import software.amazon.awssdk.services.glue.model.Table;
|
||||
import software.amazon.awssdk.services.s3.S3Client;
|
||||
import software.amazon.awssdk.services.s3.model.S3Object;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
|
||||
import static io.github.hectorvent.floci.testing.EmrServerlessRequests.awaitJobRun;
|
||||
import static io.github.hectorvent.floci.testing.EmrServerlessRequests.createApplication;
|
||||
import static io.github.hectorvent.floci.testing.EmrServerlessRequests.deleteApplication;
|
||||
import static io.github.hectorvent.floci.testing.EmrServerlessRequests.startJobRun;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
|
||||
/**
|
||||
* EMR Serverless Hive job runs through Floci's Docker runner for real: a Hive application in the {@code docker} runner
|
||||
* mode runs each job run's {@code hive} in a container of the release's EMR Serverless Hive image, Tez in local mode,
|
||||
* on Floci's S3 and with Floci's Glue as its metastore. The cached {@code emr-7.5.0} Hive image keeps a local run from
|
||||
* pulling; CI pulls it (2.7 GB) the first time.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(ContainerDataPlaneProfile.class)
|
||||
class EmrServerlessHiveDockerIntegrationTest {
|
||||
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ROWS = "a,1\nb,2\nc,3\n";
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
private S3Client s3;
|
||||
private String bucket;
|
||||
|
||||
@BeforeEach
|
||||
void putInputs() throws InterruptedException {
|
||||
assumeTrue(DockerAvailability.isAvailable(), "Docker daemon must be available for EMR Serverless's Hive runs");
|
||||
s3 = AwsTestClients.create(S3Client.builder().forcePathStyle(true), "000000000000", Region.US_EAST_1);
|
||||
cleanup.register(s3::close);
|
||||
bucket = "emr-hive-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
s3.createBucket(request -> request.bucket(bucket));
|
||||
cleanup.register(() -> S3TestClients.deleteBucket(s3, bucket));
|
||||
put("data/rows/rows.csv", ROWS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theGuidesHiveRunKeepsItsTablesInFlocisGlueAndWritesItsReportAndLogsToS3() {
|
||||
String database = bucket.replace('-', '_');
|
||||
// The user guide's Hive job: an init query file, then the query, with its variables and settings.
|
||||
put("queries/init.sql", """
|
||||
create database if not exists ${dbname};
|
||||
create external table if not exists ${dbname}.kv (k string, v int)
|
||||
row format delimited fields terminated by ',' location '%s';
|
||||
""".formatted(s3Uri("data/rows/")));
|
||||
put("queries/report.sql", """
|
||||
create table ${dbname}.scaled stored as textfile
|
||||
as select k, v * ${hiveconf:factor} as v from ${dbname}.kv;
|
||||
insert overwrite directory '%s' row format delimited fields terminated by ','
|
||||
select k, v from ${dbname}.scaled order by k;
|
||||
select k, v from ${dbname}.scaled order by k;
|
||||
select '${env:HOME}', '${system:user.dir}', '${system:user.name}';
|
||||
""".formatted(s3Uri("out/report/")));
|
||||
GlueClient glue = AwsTestClients.create(GlueClient.builder(), "000000000000", Region.US_EAST_1);
|
||||
cleanup.register(glue::close);
|
||||
cleanup.register(() -> glue.deleteDatabase(request -> request.name(database)));
|
||||
String applicationId = hiveApplication();
|
||||
ObjectNode run = run(applicationId, "--hivevar dbname=" + database + " --hiveconf factor=10");
|
||||
|
||||
Response ended = awaitJobRun(REGION, applicationId, startJobRun(REGION, applicationId, run.toString()));
|
||||
|
||||
assertEquals("SUCCESS", ended.jsonPath().getString("jobRun.state"));
|
||||
assertEquals("a,10\nb,20\nc,30\n", objects("out/report/"));
|
||||
// The managed table's data is under the hive-site classification's warehouse, and Floci's Glue holds both.
|
||||
assertEquals("a\u000110\nb\u000120\nc\u000130\n", objects("hive/warehouse/" + database + ".db/scaled/"));
|
||||
assertEquals(List.of("kv", "scaled"), glue.getTables(request -> request.databaseName(database)).tableList()
|
||||
.stream().map(Table::name).sorted().toList());
|
||||
// The query's result is the driver's standard output, in the run's HIVE_DRIVER log folder.
|
||||
String driverLogs = "logs/applications/" + applicationId + "/jobs/"
|
||||
+ ended.jsonPath().getString("jobRun.jobRunId") + "/HIVE_DRIVER/";
|
||||
String stdout = gunzipped(driverLogs + "stdout.gz");
|
||||
assertTrue(stdout.contains("a\t10\nb\t20\nc\t30\n"));
|
||||
// Hive runs as the image's user, in its home folder, as EMR Serverless runs it.
|
||||
assertTrue(stdout.contains("/home/hadoop\t/home/hadoop\thadoop\n"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aHiveQueryThatFailsFailsItsRun() {
|
||||
put("queries/report.sql", "select k from missing_database.missing_table;\n");
|
||||
String applicationId = hiveApplication();
|
||||
|
||||
Response ended = awaitJobRun(REGION, applicationId,
|
||||
startJobRun(REGION, applicationId, run(applicationId, null).toString()));
|
||||
|
||||
assertEquals("FAILED", ended.jsonPath().getString("jobRun.state"));
|
||||
// Hive's reason, on the driver's standard error.
|
||||
assertTrue(gunzipped("logs/applications/" + applicationId + "/jobs/"
|
||||
+ ended.jsonPath().getString("jobRun.jobRunId") + "/HIVE_DRIVER/stderr.gz")
|
||||
.contains("Table not found 'missing_table'"));
|
||||
}
|
||||
|
||||
/** A HIVE application on the cached release, deleted after the test. */
|
||||
private String hiveApplication() {
|
||||
String applicationId = createApplication(REGION, "emr-7.5.0", "HIVE");
|
||||
cleanup.register(() -> deleteApplication(REGION, applicationId));
|
||||
return applicationId;
|
||||
}
|
||||
|
||||
/**
|
||||
* A job run of {@code queries/report.sql}, after {@code queries/init.sql} when there is one, with
|
||||
* {@code parameters} (null for none), the guide's two mandatory Hive properties in its {@code hive-site} and its
|
||||
* logs under {@code logs/}.
|
||||
*/
|
||||
private ObjectNode run(String applicationId, String parameters) {
|
||||
ObjectNode run = JSON.createObjectNode().put("clientToken", UUID.randomUUID().toString())
|
||||
.put("executionRoleArn", "arn:aws:iam::000000000000:role/emr-serverless-job");
|
||||
ObjectNode hive = run.putObject("jobDriver").putObject("hive").put("query", s3Uri("queries/report.sql"));
|
||||
if (s3.listObjectsV2(request -> request.bucket(bucket).prefix("queries/init.sql")).keyCount() > 0) {
|
||||
hive.put("initQueryFile", s3Uri("queries/init.sql"));
|
||||
}
|
||||
if (parameters != null) {
|
||||
hive.put("parameters", parameters);
|
||||
}
|
||||
ObjectNode overrides = run.putObject("configurationOverrides");
|
||||
overrides.putArray("applicationConfiguration").addObject().put("classification", "hive-site")
|
||||
.putObject("properties")
|
||||
.put("hive.exec.scratchdir", s3Uri("hive/scratch/"))
|
||||
.put("hive.metastore.warehouse.dir", s3Uri("hive/warehouse/"));
|
||||
overrides.putObject("monitoringConfiguration").putObject("s3MonitoringConfiguration")
|
||||
.put("logUri", s3Uri("logs/"));
|
||||
return run;
|
||||
}
|
||||
|
||||
private void put(String key, String text) {
|
||||
s3.putObject(request -> request.bucket(bucket).key(key), RequestBody.fromString(text));
|
||||
}
|
||||
|
||||
private String s3Uri(String key) {
|
||||
return "s3://" + bucket + "/" + key;
|
||||
}
|
||||
|
||||
/** The objects under {@code prefix}, in key order, one after the other. */
|
||||
private String objects(String prefix) {
|
||||
StringBuilder text = new StringBuilder();
|
||||
for (S3Object object : s3.listObjectsV2(request -> request.bucket(bucket).prefix(prefix)).contents()) {
|
||||
text.append(s3.getObjectAsBytes(request -> request.bucket(bucket).key(object.key())).asUtf8String());
|
||||
}
|
||||
return text.toString();
|
||||
}
|
||||
|
||||
private String gunzipped(String key) {
|
||||
try (GZIPInputStream in = new GZIPInputStream(s3.getObject(request -> request.bucket(bucket).key(key)))) {
|
||||
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+153
-9
@@ -296,6 +296,38 @@ class EmrServerlessJobRunServiceTest {
|
||||
assertNull(runner.jobs.get(2).customImage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aHiveRunGetsTheHiveDriverWorkerTypesCustomImageElseTheApplicationsElseTheReleases() {
|
||||
FakeRunner runner = new FakeRunner();
|
||||
EmrServerlessJobRunService service = dockerService(runner);
|
||||
String applicationImage = "123456789012.dkr.ecr.us-east-1.amazonaws.com/hive/custom:7.5.0";
|
||||
String driverImage = "123456789012.dkr.ecr.us-east-1.amazonaws.com/hive/driver:7.5.0";
|
||||
CreateApplicationRequest wholeApplication = applicationRequest("custom", "emr-7.5.0", "HIVE");
|
||||
wholeApplication.setImageConfiguration(EmrServerlessServiceTest.image(applicationImage));
|
||||
// Tez in local mode runs its tasks in the driver's container, so a TezTask image is not used.
|
||||
wholeApplication.setWorkerTypeSpecifications(
|
||||
Map.of("TezTask", EmrServerlessServiceTest.workerType(driverImage)));
|
||||
CreateApplicationRequest perWorkerType = applicationRequest("per-worker-type", "emr-7.5.0", "HIVE");
|
||||
perWorkerType.setImageConfiguration(EmrServerlessServiceTest.image(applicationImage));
|
||||
perWorkerType.setWorkerTypeSpecifications(
|
||||
Map.of("HiveDriver", EmrServerlessServiceTest.workerType(driverImage)));
|
||||
String release = applications.createApplication(applicationRequest("hive", "emr-7.5.0", "HIVE"))
|
||||
.getApplicationId();
|
||||
|
||||
for (CreateApplicationRequest create : List.of(wholeApplication, perWorkerType)) {
|
||||
service.startJobRun(applications.createApplication(create).getApplicationId(),
|
||||
hiveRequest("s3://bucket/queries/report.sql", null, null));
|
||||
}
|
||||
service.startJobRun(release, hiveRequest("s3://bucket/queries/report.sql", null, null));
|
||||
for (int i = 0; i < 3; i++) {
|
||||
runNext();
|
||||
}
|
||||
|
||||
assertEquals(applicationImage, runner.jobs.get(0).customImage());
|
||||
assertEquals(driverImage, runner.jobs.get(1).customImage());
|
||||
assertNull(runner.jobs.get(2).customImage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRunsDriverOutputGoesToCloudWatchWhenItsOwnOrTheApplicationsLoggingIsEnabled() {
|
||||
FakeRunner runner = new FakeRunner();
|
||||
@@ -617,6 +649,25 @@ class EmrServerlessJobRunServiceTest {
|
||||
return create;
|
||||
}
|
||||
|
||||
// A run of query, after initQueryFile, with parameters, either of the two null for none.
|
||||
private static StartJobRunRequest hiveRequest(String query, String initQueryFile, String parameters) {
|
||||
JobDriver.Hive hive = new JobDriver.Hive();
|
||||
hive.setQuery(query);
|
||||
hive.setInitQueryFile(initQueryFile);
|
||||
hive.setParameters(parameters);
|
||||
StartJobRunRequest request = request(null, null);
|
||||
request.getJobDriver().setSparkSubmit(null);
|
||||
request.getJobDriver().setHive(hive);
|
||||
return request;
|
||||
}
|
||||
|
||||
private static RuntimeConfiguration configuration(String classification, Map<String, String> properties) {
|
||||
RuntimeConfiguration configuration = new RuntimeConfiguration();
|
||||
configuration.setMember("classification", classification);
|
||||
configuration.setMember("properties", properties);
|
||||
return configuration;
|
||||
}
|
||||
|
||||
private static MonitoringConfiguration s3LogUri(String logUri) {
|
||||
MonitoringConfiguration monitoring = new MonitoringConfiguration();
|
||||
monitoring.setProperty("s3MonitoringConfiguration", Map.of("logUri", logUri));
|
||||
@@ -818,20 +869,113 @@ class EmrServerlessJobRunServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void aHiveRunFailsWithoutRunning() {
|
||||
void aHiveRunGoesToTheRunnerWithItsSettingsQueryFilesAndParametersInTheGuidesOrder() {
|
||||
FakeRunner runner = new FakeRunner();
|
||||
EmrServerlessJobRunService service = dockerService(runner);
|
||||
CreateApplicationRequest create = applicationRequest("hive", "emr-7.5.0", "HIVE");
|
||||
create.setRuntimeConfiguration(List.of(
|
||||
configuration("core-site", Map.of("fs.s3a.connection.maximum", "50")),
|
||||
configuration("hive-site", Map.of("hive.exec.scratchdir", "s3://bucket/app-scratch/"))));
|
||||
create.setMonitoringConfiguration(s3LogUri("s3://logs/hive"));
|
||||
String hive = applications.createApplication(create).getApplicationId();
|
||||
StartJobRunRequest request = hiveRequest("s3://bucket/queries/report.sql", "s3://bucket/queries/init.sql",
|
||||
"--hiveconf hive.exec.reducers.max=4 --hivevar day=2026-11-03");
|
||||
// The run's hive-site replaces the application's, and its tez-site adds Tez's file.
|
||||
request.setConfigurationOverrides(Map.of("applicationConfiguration", List.of(
|
||||
Map.of("classification", "hive-site", "properties",
|
||||
Map.of("hive.exec.scratchdir", "s3://bucket/scratch/")),
|
||||
Map.of("classification", "tez-site", "properties", Map.of("tez.grouping.max-size", "268435456")))));
|
||||
|
||||
String jobRunId = service.startJobRun(hive, request).getJobRunId();
|
||||
runNext();
|
||||
|
||||
SparkJobRunner.Job job = runner.jobs.get(0);
|
||||
assertEquals(SparkJobRunner.Engine.HIVE, job.engine());
|
||||
assertNull(job.imageTemplate());
|
||||
assertEquals(List.of(
|
||||
"--hiveconf", "fs.s3a.connection.maximum=50",
|
||||
"--hiveconf", "tez.grouping.max-size=268435456",
|
||||
"--hiveconf", "hive.exec.scratchdir=s3://bucket/scratch/",
|
||||
"-i", "s3://bucket/queries/init.sql", "-f", "s3://bucket/queries/report.sql",
|
||||
"--hiveconf", "hive.exec.reducers.max=4", "--hivevar", "day=2026-11-03"), job.application());
|
||||
assertEquals(Map.of(), job.sparkDefaults());
|
||||
assertEquals(List.of(), job.archives());
|
||||
assertEquals("s3://logs/hive/applications/" + hive + "/jobs/" + jobRunId + "/HIVE_DRIVER/", job.logFolder());
|
||||
assertEquals("SUCCESS", service.getJobRun(hive, jobRunId, null).getState());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSparkRunGetsTheImageTemplateAndAHiveRunTheHiveImageTemplate() {
|
||||
FakeRunner runner = new FakeRunner();
|
||||
EmrServerlessJobRunService service = new EmrServerlessJobRunService(store, applications, iamService,
|
||||
new RegionResolver(REGION, ACCOUNT_ID), null, objectMapper, 0, clock, runner, tasks::add,
|
||||
"registry.internal/emr-serverless/spark/%s:20250425",
|
||||
"registry.internal/emr-serverless/hive/%s:20250425", "floci-network");
|
||||
String hive = applications.createApplication(applicationRequest("hive", "emr-7.5.0", "HIVE"))
|
||||
.getApplicationId();
|
||||
JobDriver.Hive query = new JobDriver.Hive();
|
||||
query.setQuery("s3://bucket/queries/report.sql");
|
||||
StartJobRunRequest request = request(null, null);
|
||||
request.getJobDriver().setSparkSubmit(null);
|
||||
request.getJobDriver().setHive(query);
|
||||
|
||||
JobRun run = dockerService(new FakeRunner()).startJobRun(hive, request);
|
||||
service.startJobRun(applicationId, request(null, null));
|
||||
service.startJobRun(hive, hiveRequest("s3://bucket/queries/report.sql", null, null));
|
||||
runNext();
|
||||
runNext();
|
||||
|
||||
assertEquals("FAILED", run.getState());
|
||||
assertEquals(EmrServerlessJobRunService.HIVE_NOT_RUN, run.getStateDetails());
|
||||
assertEquals("registry.internal/emr-serverless/spark/%s:20250425", runner.jobs.get(0).imageTemplate());
|
||||
assertEquals("registry.internal/emr-serverless/hive/%s:20250425", runner.jobs.get(1).imageTemplate());
|
||||
assertEquals("floci-network", runner.jobs.get(1).dockerNetwork());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aHiveRunWithoutAnInitQueryFileOrParametersRunsItsQuery() {
|
||||
FakeRunner runner = new FakeRunner();
|
||||
EmrServerlessJobRunService service = dockerService(runner);
|
||||
String hive = applications.createApplication(applicationRequest("hive", "emr-7.5.0", "HIVE"))
|
||||
.getApplicationId();
|
||||
|
||||
service.startJobRun(hive, hiveRequest("s3://bucket/queries/report.sql", null, null));
|
||||
runNext();
|
||||
|
||||
assertEquals(List.of("-f", "s3://bucket/queries/report.sql"), runner.jobs.get(0).application());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRunWhoseDriverIsNotItsApplicationsTypeFailsWithoutRunning() {
|
||||
FakeRunner runner = new FakeRunner();
|
||||
EmrServerlessJobRunService service = dockerService(runner);
|
||||
String hive = applications.createApplication(applicationRequest("hive", "emr-7.5.0", "HIVE"))
|
||||
.getApplicationId();
|
||||
|
||||
JobRun sparkOnHive = service.startJobRun(hive, request(null, null));
|
||||
JobRun hiveOnSpark = service.startJobRun(applicationId,
|
||||
hiveRequest("s3://bucket/queries/report.sql", null, null));
|
||||
|
||||
for (JobRun run : List.of(sparkOnHive, hiveOnSpark)) {
|
||||
assertEquals("FAILED", run.getState());
|
||||
assertEquals(EmrServerlessJobRunService.DRIVER_NOT_THE_APPLICATIONS, run.getStateDetails());
|
||||
}
|
||||
assertEquals(List.of(), tasks);
|
||||
assertEquals(List.of(), runner.jobs);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aHiveRunsDriverLogsToCloudWatchUnderItsHiveDriverAsLogTypesNamesIt() {
|
||||
Application app = new Application();
|
||||
app.setMonitoringConfiguration(cloudWatchLogging(Map.of("enabled", true)));
|
||||
JobRun run = run("emr-7.5.0", "BATCH", null);
|
||||
JobDriver driver = new JobDriver();
|
||||
driver.setHive(new JobDriver.Hive());
|
||||
run.setJobDriver(driver);
|
||||
|
||||
assertEquals(new SparkJobRunner.CloudWatchLogs("/aws/emr-serverless",
|
||||
"/applications/app/jobs/run/HIVE_DRIVER/stdout", "/applications/app/jobs/run/HIVE_DRIVER/stderr"),
|
||||
EmrServerlessJobRunService.driverCloudWatchLogs(app, run));
|
||||
|
||||
// "HIVE_DRIVER : ["STDERR", "STDOUT", "HIVE_LOG", "TEZ_AM"]": its driver's, not SPARK_DRIVER's.
|
||||
app.setMonitoringConfiguration(cloudWatchLogging(Map.of("enabled", true,
|
||||
"logTypes", Map.of("HIVE_DRIVER", List.of("STDERR"), "SPARK_DRIVER", List.of("STDOUT")))));
|
||||
|
||||
assertEquals(new SparkJobRunner.CloudWatchLogs("/aws/emr-serverless", null,
|
||||
"/applications/app/jobs/run/HIVE_DRIVER/stderr"),
|
||||
EmrServerlessJobRunService.driverCloudWatchLogs(app, run));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+112
-7
@@ -54,6 +54,8 @@ import java.util.zip.GZIPOutputStream;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import static io.github.hectorvent.floci.services.emrserverless.SparkJobRunner.Engine.HIVE;
|
||||
import static io.github.hectorvent.floci.services.emrserverless.SparkJobRunner.Engine.SPARK;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
@@ -163,6 +165,103 @@ class EmrServerlessSparkRunnerTest {
|
||||
// The image a cluster's bootstrap left, which its steps get by id.
|
||||
String bootstrapped = "sha256:" + "2".repeat(64);
|
||||
assertEquals(bootstrapped, EmrServerlessSparkRunner.image(bootstrapped, "emr-7.5.0"));
|
||||
// A Hive run's is the release's Hive image, or its own template's.
|
||||
assertEquals("public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest",
|
||||
EmrServerlessSparkRunner.image(null, "emr-7.5.0", HIVE));
|
||||
assertEquals("registry.internal/emr-serverless/hive/emr-7.5.0:20250425",
|
||||
EmrServerlessSparkRunner.image("registry.internal/emr-serverless/hive/%s:20250425", "emr-7.5.0", HIVE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void hiveRunsOnFlocisS3AndGlueWithTezInLocalModeThenTheRunsOwnArguments() {
|
||||
List<String> application = List.of("--hiveconf", "hive.exec.scratchdir=s3://bucket/scratch/",
|
||||
"-i", "s3://bucket/queries/init.sql", "-f", "s3://bucket/queries/report.sql",
|
||||
"--hivevar", "day=2026-11-03");
|
||||
|
||||
List<String> arguments = EmrServerlessSparkRunner.hiveArguments(hiveJob(application), ENDPOINT);
|
||||
|
||||
assertEquals(List.of(
|
||||
"--hiveconf", "fs.s3a.endpoint=http://floci:4566",
|
||||
"--hiveconf", "fs.s3a.endpoint.region=eu-west-1",
|
||||
"--hiveconf", "fs.s3a.path.style.access=true",
|
||||
"--hiveconf", "fs.s3a.committer.magic.track.commits.in.memory.enabled=true",
|
||||
"--hiveconf", "fs.s3.impl=org.apache.hadoop.fs.s3a.S3AFileSystem",
|
||||
"--hiveconf", "fs.AbstractFileSystem.s3.impl=org.apache.hadoop.fs.s3a.S3A",
|
||||
"--hiveconf", "aws.glue.endpoint=http://floci:4566",
|
||||
"--hiveconf", "hive.metastore.glue.catalogid=123456789012",
|
||||
"--hiveconf", "aws.region=eu-west-1",
|
||||
"--hiveconf", "tez.local.mode=true",
|
||||
"--hiveconf", "tez.am.client.am.port-range=40000-40100",
|
||||
"--hiveconf", "hive.exec.scratchdir=s3://bucket/scratch/",
|
||||
"-i", "s3://bucket/queries/init.sql", "-f", "s3://bucket/queries/report.sql",
|
||||
"--hivevar", "day=2026-11-03"), arguments);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aHiveRunStartsHiveAsTheImagesUserInTheReleasesHiveImageAfterItsScratchFoldersLocalPath() {
|
||||
ContainerBuilder builder = mock(ContainerBuilder.class);
|
||||
ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
|
||||
when(builder.newContainer(anyString())).thenReturn(spec);
|
||||
|
||||
runner(builder).run(hiveJob(List.of("--hiveconf", "hive.exec.scratchdir=s3://bucket/hive/scratch/",
|
||||
"-f", "s3://bucket/queries/report.sql")), progress);
|
||||
|
||||
verify(builder).newContainer("public.ecr.aws/emr-serverless/hive/emr-7.5.0:latest");
|
||||
// As root, which makes the scratch folder's local path the image's user's, then hive as that user.
|
||||
verify(spec).withUser("root");
|
||||
verify(spec).withEntrypoint(argThat((List<String> entrypoint) -> entrypoint.size() == 5
|
||||
&& List.of("/bin/bash", "-c").equals(entrypoint.subList(0, 2))
|
||||
&& entrypoint.get(2).contains("setpriv --reuid=hadoop --regid=hadoop --clear-groups \"$@\"")
|
||||
&& List.of("floci", "/usr/bin/hive").equals(entrypoint.subList(3, 5))));
|
||||
verify(spec).withCmd(argThat((List<String> cmd) -> "--hiveconf".equals(cmd.getFirst())
|
||||
&& List.of("-f", "s3://bucket/queries/report.sql").equals(cmd.subList(cmd.size() - 2, cmd.size()))));
|
||||
verify(spec).withEnv("FLOCI_HIVE_SCRATCH", "/hive/scratch/hadoop");
|
||||
verify(spec).withEnv(List.of("LOGS_DIR=/tmp/floci-hive-logs"));
|
||||
// Nothing of Spark's: no spark-defaults for a command, and no Spark configuration of its own.
|
||||
verify(spec, never()).withEnv(eq("FLOCI_SPARK_DEFAULTS"), anyString());
|
||||
verify(spec, never()).withEnv(eq("FLOCI_SPARK_LOG4J2"), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aHiveScratchFolderInS3LeadsToTheSamePathLocallyThenItsUsersFolder() {
|
||||
assertEquals("/hive/scratch/hadoop", EmrServerlessSparkRunner.hiveScratchMirror(
|
||||
List.of("--hiveconf", "hive.exec.scratchdir=s3://bucket/hive/scratch/")));
|
||||
// The last setting wins, in either form of the option and in any of Hadoop's S3 schemes.
|
||||
assertEquals("/later/hadoop", EmrServerlessSparkRunner.hiveScratchMirror(List.of(
|
||||
"--hiveconf", "hive.exec.scratchdir=s3://bucket/earlier", "-f", "s3://bucket/queries/report.sql",
|
||||
"-hiveconf", "hive.exec.scratchdir=s3a://bucket/later")));
|
||||
// Hive's CLI also takes the option and its setting as one argument, and a setting's value as the next one.
|
||||
assertEquals("/inline/hadoop", EmrServerlessSparkRunner.hiveScratchMirror(List.of(
|
||||
"--hiveconf", "hive.exec.scratchdir=s3://bucket/earlier",
|
||||
"--hiveconf=hive.exec.scratchdir=s3://bucket/inline")));
|
||||
assertEquals("/short/inline/hadoop", EmrServerlessSparkRunner.hiveScratchMirror(List.of(
|
||||
"--hiveconf=hive.exec.scratchdir=s3://bucket/earlier",
|
||||
"-hiveconf=hive.exec.scratchdir=s3://bucket/short/inline")));
|
||||
assertEquals("/separate/hadoop", EmrServerlessSparkRunner.hiveScratchMirror(List.of(
|
||||
"--hiveconf=hive.exec.scratchdir=s3://bucket/earlier",
|
||||
"--hiveconf", "hive.exec.scratchdir", "s3://bucket/separate", "-f", "s3://bucket/queries/report.sql")));
|
||||
assertEquals("/inline/separate/hadoop", EmrServerlessSparkRunner.hiveScratchMirror(List.of(
|
||||
"--hiveconf=hive.exec.scratchdir", "s3://bucket/inline/separate")));
|
||||
// Without a value, an option following it, Hive sets it to true, a local folder.
|
||||
assertNull(EmrServerlessSparkRunner.hiveScratchMirror(List.of(
|
||||
"--hiveconf", "hive.exec.scratchdir=s3://bucket/earlier", "--hiveconf", "hive.exec.scratchdir",
|
||||
"-f", "s3://bucket/queries/report.sql")));
|
||||
assertEquals("/later/hadoop", EmrServerlessSparkRunner.hiveScratchMirror(List.of(
|
||||
"--hiveconf", "hive.exec.scratchdir", "--hiveconf", "hive.exec.scratchdir=s3://bucket/later")));
|
||||
// Another setting's value, or a variable of the same name, is not the scratch folder.
|
||||
assertNull(EmrServerlessSparkRunner.hiveScratchMirror(List.of(
|
||||
"--hiveconf", "hive.exec.stagingdir", "hive.exec.scratchdir=s3://bucket/value",
|
||||
"--hivevar", "hive.exec.scratchdir=s3://bucket/variable")));
|
||||
assertEquals("/hadoop", EmrServerlessSparkRunner.hiveScratchMirror(
|
||||
List.of("--hiveconf", "hive.exec.scratchdir=s3://bucket")));
|
||||
assertEquals("/scratch/hadoop", EmrServerlessSparkRunner.hiveScratchMirror(
|
||||
List.of("--hiveconf", "hive.exec.scratchdir=s3://bucket/a/../scratch/")));
|
||||
assertEquals("/hive/scratch/hadoop", EmrServerlessSparkRunner.hiveScratchMirror(
|
||||
List.of("--hiveconf", "hive.exec.scratchdir=s3://bucket//hive/./scratch//")));
|
||||
// A local scratch folder, or Hive's default one, is the image user's to make.
|
||||
assertNull(EmrServerlessSparkRunner.hiveScratchMirror(
|
||||
List.of("--hiveconf", "hive.exec.scratchdir=/tmp/hive-scratch")));
|
||||
assertNull(EmrServerlessSparkRunner.hiveScratchMirror(List.of("-f", "s3://bucket/queries/report.sql")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1249,21 +1348,27 @@ class EmrServerlessSparkRunnerTest {
|
||||
Map<String, String> sparkDefaults, Duration timeout, String logFolder,
|
||||
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,
|
||||
SPARK, imageTemplate, null, "floci-network", "arn:aws:iam::123456789012:role/job", sparkDefaults,
|
||||
application, null, timeout, logFolder, cloudWatchLogs, Map.of(), List.of(), null, Map.of(), Map.of(),
|
||||
Map.of(), Map.of(), Map.of());
|
||||
}
|
||||
|
||||
private static SparkJobRunner.Job hiveJob(List<String> application) {
|
||||
return new SparkJobRunner.Job("emr-serverless", "00f0000000000002", "123456789012", "eu-west-1", "emr-7.5.0",
|
||||
HIVE, null, null, "floci-network", "arn:aws:iam::123456789012:role/job", Map.of(), application, null,
|
||||
Duration.ZERO, null, null, Map.of(), List.of(), null, Map.of(), Map.of(), Map.of(), Map.of(), Map.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(),
|
||||
SPARK, 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(), null,
|
||||
Map.of(), Map.of(), Map.of(), Map.of(), Map.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(),
|
||||
SPARK, 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, null,
|
||||
Map.of(), Map.of(), Map.of(), Map.of(), Map.of());
|
||||
}
|
||||
@@ -1274,7 +1379,7 @@ class EmrServerlessSparkRunnerTest {
|
||||
|
||||
private static SparkJobRunner.Job commandJob(List<String> command, Map<String, String> sparkDefaults,
|
||||
SparkJobRunner.Storage storage) {
|
||||
return new SparkJobRunner.Job("emr", "s-1A2B3C4D5E6F7", "123456789012", "eu-west-1", "emr-7.5.0", null,
|
||||
return new SparkJobRunner.Job("emr", "s-1A2B3C4D5E6F7", "123456789012", "eu-west-1", "emr-7.5.0", SPARK, 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"), List.of(),
|
||||
storage, Map.of(), Map.of(), Map.of(), Map.of(), Map.of());
|
||||
@@ -1283,7 +1388,7 @@ class EmrServerlessSparkRunnerTest {
|
||||
// A step on a cluster with core-site and spark-log4j2 properties: a command, or a Spark step for a null one.
|
||||
private static SparkJobRunner.Job clusterJob(List<String> command, Map<String, String> coreSite,
|
||||
Map<String, String> sparkLog4j2) {
|
||||
return new SparkJobRunner.Job("emr", "s-1A2B3C4D5E6F7", "123456789012", "eu-west-1", "emr-7.5.0", null,
|
||||
return new SparkJobRunner.Job("emr", "s-1A2B3C4D5E6F7", "123456789012", "eu-west-1", "emr-7.5.0", SPARK, null,
|
||||
null, "floci-network", "arn:aws:iam::123456789012:role/job", Map.of(),
|
||||
command == null ? List.of("s3://bucket/jobs/report.py") : List.of(), command, Duration.ZERO, null,
|
||||
null, Map.of(), List.of(), STORAGE, coreSite, sparkLog4j2, Map.of(), Map.of(), Map.of());
|
||||
@@ -1293,7 +1398,7 @@ class EmrServerlessSparkRunnerTest {
|
||||
private static SparkJobRunner.Job hadoopJob(List<String> command, Map<String, String> mapredSite,
|
||||
Map<String, String> hadoopLog4j,
|
||||
Map<String, String> hadoopEnvironment) {
|
||||
return new SparkJobRunner.Job("emr", "s-1A2B3C4D5E6F7", "123456789012", "eu-west-1", "emr-7.5.0", null,
|
||||
return new SparkJobRunner.Job("emr", "s-1A2B3C4D5E6F7", "123456789012", "eu-west-1", "emr-7.5.0", SPARK, null,
|
||||
null, "floci-network", "arn:aws:iam::123456789012:role/job", Map.of(),
|
||||
command == null ? List.of("s3://bucket/jobs/report.jar") : List.of(), command, Duration.ZERO, null,
|
||||
null, Map.of(), List.of(), STORAGE, Map.of(), Map.of(), mapredSite, hadoopLog4j, hadoopEnvironment);
|
||||
@@ -1301,7 +1406,7 @@ class EmrServerlessSparkRunnerTest {
|
||||
|
||||
// A Spark step on a cluster, which has storage.
|
||||
private static SparkJobRunner.Job stepJob(Map<String, String> sparkDefaults) {
|
||||
return new SparkJobRunner.Job("emr", "s-1A2B3C4D5E6F7", "123456789012", "eu-west-1", "emr-7.5.0", null,
|
||||
return new SparkJobRunner.Job("emr", "s-1A2B3C4D5E6F7", "123456789012", "eu-west-1", "emr-7.5.0", SPARK, null,
|
||||
null, "floci-network", "arn:aws:iam::123456789012:role/job", sparkDefaults,
|
||||
List.of("s3://bucket/jobs/report.py"), null, Duration.ZERO, null, null, Map.of(), List.of(), STORAGE,
|
||||
Map.of(), Map.of(), Map.of(), Map.of(), Map.of());
|
||||
|
||||
@@ -30,10 +30,15 @@ public final class EmrServerlessRequests {
|
||||
|
||||
/** Creates a SPARK application on {@code releaseLabel} in {@code region} and returns its id. */
|
||||
public static String createSparkApplication(String region, String releaseLabel) {
|
||||
return createApplication(region, releaseLabel, "SPARK");
|
||||
}
|
||||
|
||||
/** Creates an application of {@code type}, SPARK or HIVE, on {@code releaseLabel} in {@code region}; its id. */
|
||||
public static String createApplication(String region, String releaseLabel, String type) {
|
||||
return emrServerless(region)
|
||||
.body("""
|
||||
{"name": "app-%s", "releaseLabel": "%s", "type": "SPARK", "clientToken": "%s"}
|
||||
""".formatted(UUID.randomUUID(), releaseLabel, UUID.randomUUID()))
|
||||
{"name": "app-%s", "releaseLabel": "%s", "type": "%s", "clientToken": "%s"}
|
||||
""".formatted(UUID.randomUUID(), releaseLabel, type, UUID.randomUUID()))
|
||||
.when().post("/applications")
|
||||
.then().statusCode(200).extract().path("applicationId");
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import software.amazon.awssdk.services.s3.S3Client;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
/** AWS SDK S3 clients pointed at the Floci instance a {@code @QuarkusTest} runs. */
|
||||
/** AWS SDK S3 clients pointed at the Floci instance a {@code @QuarkusTest} runs, and what a test does with them. */
|
||||
public final class S3TestClients {
|
||||
|
||||
private S3TestClients() {
|
||||
@@ -25,4 +25,11 @@ public final class S3TestClients {
|
||||
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("741624100001", "test")))
|
||||
.build();
|
||||
}
|
||||
|
||||
/** Empties {@code bucket}, every page of it, and deletes it, as a test cleans up the bucket it wrote to. */
|
||||
public static void deleteBucket(S3Client s3, String bucket) {
|
||||
s3.listObjectsV2Paginator(request -> request.bucket(bucket)).contents()
|
||||
.forEach(object -> s3.deleteObject(request -> request.bucket(bucket).key(object.key())));
|
||||
s3.deleteBucket(request -> request.bucket(bucket));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user